braintrust 3.11.0 → 3.12.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.
- package/README.md +8 -8
- package/dev/dist/index.d.mts +1 -1
- package/dev/dist/index.d.ts +1 -1
- package/dev/dist/index.js +2607 -316
- package/dev/dist/index.mjs +2388 -97
- package/dist/apply-auto-instrumentation.browser.d.mts +2 -0
- package/dist/apply-auto-instrumentation.browser.d.ts +2 -0
- package/dist/apply-auto-instrumentation.browser.js +18 -0
- package/dist/apply-auto-instrumentation.browser.mjs +0 -0
- package/dist/apply-auto-instrumentation.d.mts +2 -0
- package/dist/apply-auto-instrumentation.d.ts +2 -0
- package/dist/apply-auto-instrumentation.js +2534 -0
- package/dist/apply-auto-instrumentation.mjs +2534 -0
- package/dist/auto-instrumentations/bundler/esbuild.cjs +1802 -1283
- package/dist/auto-instrumentations/bundler/esbuild.d.mts +9 -5
- package/dist/auto-instrumentations/bundler/esbuild.d.ts +9 -5
- package/dist/auto-instrumentations/bundler/esbuild.mjs +10 -2
- package/dist/auto-instrumentations/bundler/next.cjs +3268 -0
- package/dist/auto-instrumentations/bundler/next.d.mts +3 -0
- package/dist/auto-instrumentations/bundler/next.d.ts +3 -0
- package/dist/auto-instrumentations/bundler/next.mjs +189 -0
- package/dist/auto-instrumentations/bundler/rollup.cjs +1802 -1283
- package/dist/auto-instrumentations/bundler/rollup.d.mts +9 -5
- package/dist/auto-instrumentations/bundler/rollup.d.ts +9 -5
- package/dist/auto-instrumentations/bundler/rollup.mjs +10 -2
- package/dist/auto-instrumentations/bundler/vite.cjs +1802 -1283
- package/dist/auto-instrumentations/bundler/vite.d.mts +9 -5
- package/dist/auto-instrumentations/bundler/vite.d.ts +9 -5
- package/dist/auto-instrumentations/bundler/vite.mjs +10 -2
- package/dist/auto-instrumentations/bundler/webpack-loader.cjs +1860 -1308
- package/dist/auto-instrumentations/bundler/webpack-loader.d.ts +3 -3
- package/dist/auto-instrumentations/bundler/webpack.cjs +1802 -1283
- package/dist/auto-instrumentations/bundler/webpack.d.mts +9 -5
- package/dist/auto-instrumentations/bundler/webpack.d.ts +9 -5
- package/dist/auto-instrumentations/bundler/webpack.mjs +6 -6
- package/dist/auto-instrumentations/{chunk-DIV5TO4S.mjs → chunk-2DPA74KK.mjs} +337 -1
- package/dist/auto-instrumentations/chunk-73BZUKVI.mjs +300 -0
- package/dist/auto-instrumentations/chunk-AFXRW7I7.mjs +18 -0
- package/dist/auto-instrumentations/hook.mjs +1712 -1460
- package/dist/auto-instrumentations/index.cjs +93 -0
- package/dist/auto-instrumentations/index.d.mts +5 -1
- package/dist/auto-instrumentations/index.d.ts +5 -1
- package/dist/auto-instrumentations/index.mjs +6 -247
- package/dist/auto-instrumentations/loader/esm-hook.mjs +19 -2
- package/dist/auto-instrumentations/plugin-D7nDswtC.d.mts +44 -0
- package/dist/auto-instrumentations/plugin-D7nDswtC.d.ts +44 -0
- package/dist/browser.d.mts +120 -31
- package/dist/browser.d.ts +120 -31
- package/dist/browser.js +2395 -123
- package/dist/browser.mjs +2395 -123
- package/dist/chunk-BW4DF4CY.js +816 -0
- package/dist/chunk-MSLBGITU.mjs +816 -0
- package/dist/cli.js +2407 -96
- package/dist/edge-light.d.mts +1 -1
- package/dist/edge-light.d.ts +1 -1
- package/dist/edge-light.js +2395 -123
- package/dist/edge-light.mjs +2395 -123
- package/dist/index.d.mts +120 -31
- package/dist/index.d.ts +120 -31
- package/dist/index.js +3362 -1849
- package/dist/index.mjs +2505 -992
- package/dist/instrumentation/index.d.mts +7860 -48
- package/dist/instrumentation/index.d.ts +7860 -48
- package/dist/instrumentation/index.js +2395 -95
- package/dist/instrumentation/index.mjs +2394 -95
- package/dist/workerd.d.mts +1 -1
- package/dist/workerd.d.ts +1 -1
- package/dist/workerd.js +2395 -123
- package/dist/workerd.mjs +2395 -123
- package/package.json +23 -3
- package/util/dist/index.js +6 -0
- package/util/dist/index.mjs +6 -0
- package/dist/auto-instrumentations/chunk-G6ZWXGZB.mjs +0 -116
- package/dist/auto-instrumentations/plugin-Df3qKIl2.d.mts +0 -22
- package/dist/auto-instrumentations/plugin-Df3qKIl2.d.ts +0 -22
|
@@ -32,6 +32,7 @@ var index_exports = {};
|
|
|
32
32
|
__export(index_exports, {
|
|
33
33
|
BasePlugin: () => BasePlugin,
|
|
34
34
|
BraintrustPlugin: () => BraintrustPlugin,
|
|
35
|
+
OpenAIAgentsTraceProcessor: () => OpenAIAgentsTraceProcessor,
|
|
35
36
|
configureInstrumentation: () => configureInstrumentation,
|
|
36
37
|
createChannelName: () => createChannelName,
|
|
37
38
|
isValidChannelName: () => isValidChannelName,
|
|
@@ -1167,6 +1168,11 @@ function isPromiseLike(value) {
|
|
|
1167
1168
|
|
|
1168
1169
|
// util/object_util.ts
|
|
1169
1170
|
var SET_UNION_FIELDS = /* @__PURE__ */ new Set(["tags"]);
|
|
1171
|
+
var FORBIDDEN_MERGE_KEYS = /* @__PURE__ */ new Set([
|
|
1172
|
+
"__proto__",
|
|
1173
|
+
"constructor",
|
|
1174
|
+
"prototype"
|
|
1175
|
+
]);
|
|
1170
1176
|
function mergeDictsWithPaths({
|
|
1171
1177
|
mergeInto,
|
|
1172
1178
|
mergeFrom,
|
|
@@ -1189,6 +1195,7 @@ function mergeDictsWithPathsHelper({
|
|
|
1189
1195
|
mergePaths
|
|
1190
1196
|
}) {
|
|
1191
1197
|
Object.entries(mergeFrom).forEach(([k, mergeFromV]) => {
|
|
1198
|
+
if (FORBIDDEN_MERGE_KEYS.has(k)) return;
|
|
1192
1199
|
const fullPath = path.concat([k]);
|
|
1193
1200
|
const fullPathSerialized = JSON.stringify(fullPath);
|
|
1194
1201
|
const mergeIntoV = recordFind(mergeInto, k);
|
|
@@ -5058,6 +5065,13 @@ var HTTPConnection = class _HTTPConnection {
|
|
|
5058
5065
|
debugLogger.debug(
|
|
5059
5066
|
`Retrying API request ${object_type} ${JSON.stringify(args)} ${e.status} ${e.text}`
|
|
5060
5067
|
);
|
|
5068
|
+
const sleepTimeS = HTTP_RETRY_BASE_SLEEP_TIME_S * 2 ** i;
|
|
5069
|
+
debugLogger.info(
|
|
5070
|
+
`Sleeping for ${sleepTimeS}s before retrying API request`
|
|
5071
|
+
);
|
|
5072
|
+
await new Promise(
|
|
5073
|
+
(resolve) => setTimeout(resolve, sleepTimeS * 1e3)
|
|
5074
|
+
);
|
|
5061
5075
|
continue;
|
|
5062
5076
|
}
|
|
5063
5077
|
throw e;
|
|
@@ -5580,20 +5594,7 @@ function startSpanParentArgs(args) {
|
|
|
5580
5594
|
`Mismatch between expected span parent object type ${args.parentObjectType} and provided type ${parentComponents.data.object_type}`
|
|
5581
5595
|
);
|
|
5582
5596
|
}
|
|
5583
|
-
|
|
5584
|
-
args.state,
|
|
5585
|
-
parentComponents
|
|
5586
|
-
);
|
|
5587
|
-
const computeParentObjectId = async () => {
|
|
5588
|
-
const parentComponentsObjectId = await parentComponentsObjectIdLambda();
|
|
5589
|
-
if (await args.parentObjectId.get() !== parentComponentsObjectId) {
|
|
5590
|
-
throw new Error(
|
|
5591
|
-
`Mismatch between expected span parent object id ${await args.parentObjectId.get()} and provided id ${parentComponentsObjectId}`
|
|
5592
|
-
);
|
|
5593
|
-
}
|
|
5594
|
-
return await args.parentObjectId.get();
|
|
5595
|
-
};
|
|
5596
|
-
argParentObjectId = new LazyValue(computeParentObjectId);
|
|
5597
|
+
argParentObjectId = args.parentObjectId;
|
|
5597
5598
|
if (parentComponents.data.row_id) {
|
|
5598
5599
|
argParentSpanIds = {
|
|
5599
5600
|
spanId: parentComponents.data.span_id,
|
|
@@ -5922,6 +5923,7 @@ function now() {
|
|
|
5922
5923
|
}
|
|
5923
5924
|
var DEFAULT_FLUSH_BACKPRESSURE_BYTES = 10 * 1024 * 1024;
|
|
5924
5925
|
var BACKGROUND_LOGGER_BASE_SLEEP_TIME_S = 1;
|
|
5926
|
+
var HTTP_RETRY_BASE_SLEEP_TIME_S = 1;
|
|
5925
5927
|
var HTTPBackgroundLogger = class _HTTPBackgroundLogger {
|
|
5926
5928
|
apiConn;
|
|
5927
5929
|
queue;
|
|
@@ -6494,6 +6496,55 @@ async function computeLoggerMetadata(state, {
|
|
|
6494
6496
|
};
|
|
6495
6497
|
}
|
|
6496
6498
|
}
|
|
6499
|
+
function initLogger(options = {}) {
|
|
6500
|
+
const {
|
|
6501
|
+
projectName,
|
|
6502
|
+
projectId,
|
|
6503
|
+
asyncFlush: asyncFlushArg,
|
|
6504
|
+
appUrl,
|
|
6505
|
+
apiKey,
|
|
6506
|
+
orgName,
|
|
6507
|
+
forceLogin,
|
|
6508
|
+
debugLogLevel,
|
|
6509
|
+
fetch: fetch2,
|
|
6510
|
+
state: stateArg
|
|
6511
|
+
} = options || {};
|
|
6512
|
+
const asyncFlush = asyncFlushArg === void 0 ? true : asyncFlushArg;
|
|
6513
|
+
const computeMetadataArgs = {
|
|
6514
|
+
project_name: projectName,
|
|
6515
|
+
project_id: projectId
|
|
6516
|
+
};
|
|
6517
|
+
const linkArgs = {
|
|
6518
|
+
org_name: orgName,
|
|
6519
|
+
app_url: appUrl,
|
|
6520
|
+
project_name: projectName,
|
|
6521
|
+
project_id: projectId
|
|
6522
|
+
};
|
|
6523
|
+
const state = stateArg ?? _globalState;
|
|
6524
|
+
state.setDebugLogLevel(debugLogLevel);
|
|
6525
|
+
state.enforceQueueSizeLimit(true);
|
|
6526
|
+
const lazyMetadata = new LazyValue(
|
|
6527
|
+
async () => {
|
|
6528
|
+
await state.login({
|
|
6529
|
+
orgName,
|
|
6530
|
+
apiKey,
|
|
6531
|
+
appUrl,
|
|
6532
|
+
forceLogin,
|
|
6533
|
+
fetch: fetch2
|
|
6534
|
+
});
|
|
6535
|
+
return computeLoggerMetadata(state, computeMetadataArgs);
|
|
6536
|
+
}
|
|
6537
|
+
);
|
|
6538
|
+
const ret = new Logger(state, lazyMetadata, {
|
|
6539
|
+
asyncFlush,
|
|
6540
|
+
computeMetadataArgs,
|
|
6541
|
+
linkArgs
|
|
6542
|
+
});
|
|
6543
|
+
if (options.setCurrent ?? true) {
|
|
6544
|
+
state.currentLogger = ret;
|
|
6545
|
+
}
|
|
6546
|
+
return ret;
|
|
6547
|
+
}
|
|
6497
6548
|
async function loginToState(options = {}) {
|
|
6498
6549
|
const {
|
|
6499
6550
|
appUrl = isomorph_default.getEnv("BRAINTRUST_APP_URL") || "https://www.braintrust.dev",
|
|
@@ -11417,11 +11468,11 @@ function resolveDenyOutputPaths(event, defaultDenyOutputPaths) {
|
|
|
11417
11468
|
if (Array.isArray(event?.denyOutputPaths)) {
|
|
11418
11469
|
return event.denyOutputPaths;
|
|
11419
11470
|
}
|
|
11420
|
-
const
|
|
11421
|
-
if (!
|
|
11471
|
+
const firstArgument2 = event?.arguments && event.arguments.length > 0 ? event.arguments[0] : void 0;
|
|
11472
|
+
if (!firstArgument2 || typeof firstArgument2 !== "object") {
|
|
11422
11473
|
return defaultDenyOutputPaths;
|
|
11423
11474
|
}
|
|
11424
|
-
const runtimeDenyOutputPaths =
|
|
11475
|
+
const runtimeDenyOutputPaths = firstArgument2[RUNTIME_DENY_OUTPUT_PATHS];
|
|
11425
11476
|
if (Array.isArray(runtimeDenyOutputPaths) && runtimeDenyOutputPaths.every((path) => typeof path === "string")) {
|
|
11426
11477
|
return runtimeDenyOutputPaths;
|
|
11427
11478
|
}
|
|
@@ -15080,6 +15131,467 @@ function cleanMetrics2(metrics) {
|
|
|
15080
15131
|
return cleaned;
|
|
15081
15132
|
}
|
|
15082
15133
|
|
|
15134
|
+
// src/instrumentation/plugins/openai-agents-channels.ts
|
|
15135
|
+
var openAIAgentsCoreChannels = defineChannels("@openai/agents-core", {
|
|
15136
|
+
onTraceStart: channel({
|
|
15137
|
+
channelName: "tracing.processor.onTraceStart",
|
|
15138
|
+
kind: "async"
|
|
15139
|
+
}),
|
|
15140
|
+
onTraceEnd: channel({
|
|
15141
|
+
channelName: "tracing.processor.onTraceEnd",
|
|
15142
|
+
kind: "async"
|
|
15143
|
+
}),
|
|
15144
|
+
onSpanStart: channel({
|
|
15145
|
+
channelName: "tracing.processor.onSpanStart",
|
|
15146
|
+
kind: "async"
|
|
15147
|
+
}),
|
|
15148
|
+
onSpanEnd: channel({
|
|
15149
|
+
channelName: "tracing.processor.onSpanEnd",
|
|
15150
|
+
kind: "async"
|
|
15151
|
+
})
|
|
15152
|
+
});
|
|
15153
|
+
|
|
15154
|
+
// src/instrumentation/plugins/openai-agents-trace-processor.ts
|
|
15155
|
+
function isSpanData(spanData, type) {
|
|
15156
|
+
return spanData.type === type;
|
|
15157
|
+
}
|
|
15158
|
+
function spanTypeFromAgents(span) {
|
|
15159
|
+
const spanType = span.spanData.type;
|
|
15160
|
+
if (spanType === "function" || spanType === "guardrail" || spanType === "mcp_tools") {
|
|
15161
|
+
return "tool" /* TOOL */;
|
|
15162
|
+
}
|
|
15163
|
+
if (spanType === "generation" || spanType === "response" || spanType === "transcription" || spanType === "speech") {
|
|
15164
|
+
return "llm" /* LLM */;
|
|
15165
|
+
}
|
|
15166
|
+
return "task" /* TASK */;
|
|
15167
|
+
}
|
|
15168
|
+
function spanNameFromAgents(span) {
|
|
15169
|
+
const spanData = span.spanData;
|
|
15170
|
+
if ("name" in spanData && spanData.name) {
|
|
15171
|
+
return spanData.name;
|
|
15172
|
+
}
|
|
15173
|
+
switch (spanData.type) {
|
|
15174
|
+
case "generation":
|
|
15175
|
+
return "Generation";
|
|
15176
|
+
case "response":
|
|
15177
|
+
return "Response";
|
|
15178
|
+
case "handoff":
|
|
15179
|
+
return "Handoff";
|
|
15180
|
+
case "mcp_tools":
|
|
15181
|
+
return isSpanData(spanData, "mcp_tools") && spanData.server ? `List Tools (${spanData.server})` : "MCP List Tools";
|
|
15182
|
+
case "transcription":
|
|
15183
|
+
return "Transcription";
|
|
15184
|
+
case "speech":
|
|
15185
|
+
return "Speech";
|
|
15186
|
+
case "speech_group":
|
|
15187
|
+
return "Speech Group";
|
|
15188
|
+
default:
|
|
15189
|
+
return "Unknown";
|
|
15190
|
+
}
|
|
15191
|
+
}
|
|
15192
|
+
function getTimeElapsed(end, start) {
|
|
15193
|
+
if (!start || !end) {
|
|
15194
|
+
return void 0;
|
|
15195
|
+
}
|
|
15196
|
+
const startTime = new Date(start).getTime();
|
|
15197
|
+
const endTime = new Date(end).getTime();
|
|
15198
|
+
if (Number.isNaN(startTime) || Number.isNaN(endTime)) {
|
|
15199
|
+
return void 0;
|
|
15200
|
+
}
|
|
15201
|
+
return (endTime - startTime) / 1e3;
|
|
15202
|
+
}
|
|
15203
|
+
function getNumberProperty2(obj, key) {
|
|
15204
|
+
if (!isObject(obj) || !(key in obj)) {
|
|
15205
|
+
return void 0;
|
|
15206
|
+
}
|
|
15207
|
+
const value = obj[key];
|
|
15208
|
+
return typeof value === "number" ? value : void 0;
|
|
15209
|
+
}
|
|
15210
|
+
function parseUsageMetrics(usage) {
|
|
15211
|
+
const metrics = {};
|
|
15212
|
+
if (!isObject(usage)) {
|
|
15213
|
+
return metrics;
|
|
15214
|
+
}
|
|
15215
|
+
const promptTokens = getNumberProperty2(usage, "prompt_tokens") ?? getNumberProperty2(usage, "input_tokens") ?? getNumberProperty2(usage, "promptTokens") ?? getNumberProperty2(usage, "inputTokens");
|
|
15216
|
+
const completionTokens = getNumberProperty2(usage, "completion_tokens") ?? getNumberProperty2(usage, "output_tokens") ?? getNumberProperty2(usage, "completionTokens") ?? getNumberProperty2(usage, "outputTokens");
|
|
15217
|
+
const totalTokens = getNumberProperty2(usage, "total_tokens") ?? getNumberProperty2(usage, "totalTokens");
|
|
15218
|
+
if (promptTokens !== void 0) {
|
|
15219
|
+
metrics.prompt_tokens = promptTokens;
|
|
15220
|
+
}
|
|
15221
|
+
if (completionTokens !== void 0) {
|
|
15222
|
+
metrics.completion_tokens = completionTokens;
|
|
15223
|
+
}
|
|
15224
|
+
if (totalTokens !== void 0) {
|
|
15225
|
+
metrics.tokens = totalTokens;
|
|
15226
|
+
} else if (promptTokens !== void 0 && completionTokens !== void 0) {
|
|
15227
|
+
metrics.tokens = promptTokens + completionTokens;
|
|
15228
|
+
}
|
|
15229
|
+
const inputDetails = usage.input_tokens_details;
|
|
15230
|
+
const cachedTokens = getNumberProperty2(inputDetails, "cached_tokens");
|
|
15231
|
+
const cacheWriteTokens = getNumberProperty2(
|
|
15232
|
+
inputDetails,
|
|
15233
|
+
"cache_write_tokens"
|
|
15234
|
+
);
|
|
15235
|
+
if (cachedTokens !== void 0) {
|
|
15236
|
+
metrics.prompt_cached_tokens = cachedTokens;
|
|
15237
|
+
}
|
|
15238
|
+
if (cacheWriteTokens !== void 0) {
|
|
15239
|
+
metrics.prompt_cache_creation_tokens = cacheWriteTokens;
|
|
15240
|
+
}
|
|
15241
|
+
return metrics;
|
|
15242
|
+
}
|
|
15243
|
+
var OpenAIAgentsTraceProcessor = class _OpenAIAgentsTraceProcessor {
|
|
15244
|
+
static DEFAULT_MAX_TRACES = 1e4;
|
|
15245
|
+
logger;
|
|
15246
|
+
maxTraces;
|
|
15247
|
+
traceSpans = /* @__PURE__ */ new Map();
|
|
15248
|
+
traceOrder = [];
|
|
15249
|
+
_traceSpans = this.traceSpans;
|
|
15250
|
+
constructor(options = {}) {
|
|
15251
|
+
this.logger = options.logger;
|
|
15252
|
+
this.maxTraces = options.maxTraces ?? _OpenAIAgentsTraceProcessor.DEFAULT_MAX_TRACES;
|
|
15253
|
+
}
|
|
15254
|
+
evictOldestTrace() {
|
|
15255
|
+
const oldestTraceId = this.traceOrder.shift();
|
|
15256
|
+
if (oldestTraceId) {
|
|
15257
|
+
this.traceSpans.delete(oldestTraceId);
|
|
15258
|
+
}
|
|
15259
|
+
}
|
|
15260
|
+
onTraceStart(trace) {
|
|
15261
|
+
if (!trace?.traceId) {
|
|
15262
|
+
return Promise.resolve();
|
|
15263
|
+
}
|
|
15264
|
+
if (this.traceOrder.length >= this.maxTraces) {
|
|
15265
|
+
this.evictOldestTrace();
|
|
15266
|
+
}
|
|
15267
|
+
const current = currentSpan();
|
|
15268
|
+
const span = current && current !== NOOP_SPAN ? current.startSpan({
|
|
15269
|
+
name: trace.name,
|
|
15270
|
+
type: "task" /* TASK */
|
|
15271
|
+
}) : this.logger ? this.logger.startSpan({
|
|
15272
|
+
name: trace.name,
|
|
15273
|
+
type: "task" /* TASK */
|
|
15274
|
+
}) : startSpan({
|
|
15275
|
+
name: trace.name,
|
|
15276
|
+
type: "task" /* TASK */
|
|
15277
|
+
});
|
|
15278
|
+
span.log({
|
|
15279
|
+
input: "Agent workflow started",
|
|
15280
|
+
metadata: {
|
|
15281
|
+
group_id: trace.groupId,
|
|
15282
|
+
...trace.metadata || {}
|
|
15283
|
+
}
|
|
15284
|
+
});
|
|
15285
|
+
this.traceSpans.set(trace.traceId, {
|
|
15286
|
+
rootSpan: span,
|
|
15287
|
+
childSpans: /* @__PURE__ */ new Map(),
|
|
15288
|
+
metadata: {
|
|
15289
|
+
firstInput: null,
|
|
15290
|
+
lastOutput: null
|
|
15291
|
+
}
|
|
15292
|
+
});
|
|
15293
|
+
this.traceOrder.push(trace.traceId);
|
|
15294
|
+
return Promise.resolve();
|
|
15295
|
+
}
|
|
15296
|
+
async onTraceEnd(trace) {
|
|
15297
|
+
const traceData = this.traceSpans.get(trace?.traceId);
|
|
15298
|
+
if (!traceData) {
|
|
15299
|
+
return;
|
|
15300
|
+
}
|
|
15301
|
+
try {
|
|
15302
|
+
traceData.rootSpan.log({
|
|
15303
|
+
input: traceData.metadata.firstInput,
|
|
15304
|
+
output: traceData.metadata.lastOutput
|
|
15305
|
+
});
|
|
15306
|
+
traceData.rootSpan.end();
|
|
15307
|
+
await traceData.rootSpan.flush();
|
|
15308
|
+
} finally {
|
|
15309
|
+
this.traceSpans.delete(trace.traceId);
|
|
15310
|
+
const orderIndex = this.traceOrder.indexOf(trace.traceId);
|
|
15311
|
+
if (orderIndex > -1) {
|
|
15312
|
+
this.traceOrder.splice(orderIndex, 1);
|
|
15313
|
+
}
|
|
15314
|
+
}
|
|
15315
|
+
}
|
|
15316
|
+
onSpanStart(span) {
|
|
15317
|
+
if (!span?.spanId || !span.traceId) {
|
|
15318
|
+
return Promise.resolve();
|
|
15319
|
+
}
|
|
15320
|
+
const traceData = this.traceSpans.get(span.traceId);
|
|
15321
|
+
if (!traceData) {
|
|
15322
|
+
return Promise.resolve();
|
|
15323
|
+
}
|
|
15324
|
+
const parentSpan = span.parentId ? traceData.childSpans.get(span.parentId) : traceData.rootSpan;
|
|
15325
|
+
if (!parentSpan) {
|
|
15326
|
+
return Promise.resolve();
|
|
15327
|
+
}
|
|
15328
|
+
const childSpan = parentSpan.startSpan({
|
|
15329
|
+
name: spanNameFromAgents(span),
|
|
15330
|
+
type: spanTypeFromAgents(span)
|
|
15331
|
+
});
|
|
15332
|
+
traceData.childSpans.set(span.spanId, childSpan);
|
|
15333
|
+
return Promise.resolve();
|
|
15334
|
+
}
|
|
15335
|
+
onSpanEnd(span) {
|
|
15336
|
+
if (!span?.spanId || !span.traceId) {
|
|
15337
|
+
return Promise.resolve();
|
|
15338
|
+
}
|
|
15339
|
+
const traceData = this.traceSpans.get(span.traceId);
|
|
15340
|
+
if (!traceData) {
|
|
15341
|
+
return Promise.resolve();
|
|
15342
|
+
}
|
|
15343
|
+
const braintrustSpan = traceData.childSpans.get(span.spanId);
|
|
15344
|
+
if (!braintrustSpan) {
|
|
15345
|
+
return Promise.resolve();
|
|
15346
|
+
}
|
|
15347
|
+
const logData = this.extractLogData(span);
|
|
15348
|
+
braintrustSpan.log({
|
|
15349
|
+
error: span.error,
|
|
15350
|
+
...logData
|
|
15351
|
+
});
|
|
15352
|
+
braintrustSpan.end();
|
|
15353
|
+
traceData.childSpans.delete(span.spanId);
|
|
15354
|
+
const input = logData.input;
|
|
15355
|
+
const output = logData.output;
|
|
15356
|
+
if (traceData.metadata.firstInput === null && input != null) {
|
|
15357
|
+
traceData.metadata.firstInput = input;
|
|
15358
|
+
}
|
|
15359
|
+
if (output != null) {
|
|
15360
|
+
traceData.metadata.lastOutput = output;
|
|
15361
|
+
}
|
|
15362
|
+
return Promise.resolve();
|
|
15363
|
+
}
|
|
15364
|
+
async shutdown() {
|
|
15365
|
+
if (this.logger && typeof this.logger.flush === "function") {
|
|
15366
|
+
await this.logger.flush();
|
|
15367
|
+
}
|
|
15368
|
+
}
|
|
15369
|
+
async forceFlush() {
|
|
15370
|
+
if (this.logger && typeof this.logger.flush === "function") {
|
|
15371
|
+
await this.logger.flush();
|
|
15372
|
+
}
|
|
15373
|
+
}
|
|
15374
|
+
extractLogData(span) {
|
|
15375
|
+
const spanData = span.spanData;
|
|
15376
|
+
switch (spanData.type) {
|
|
15377
|
+
case "agent":
|
|
15378
|
+
return this.extractAgentLogData(spanData);
|
|
15379
|
+
case "response":
|
|
15380
|
+
return this.extractResponseLogData(spanData, span);
|
|
15381
|
+
case "function":
|
|
15382
|
+
return this.extractFunctionLogData(spanData);
|
|
15383
|
+
case "handoff":
|
|
15384
|
+
return this.extractHandoffLogData(spanData);
|
|
15385
|
+
case "guardrail":
|
|
15386
|
+
return this.extractGuardrailLogData(spanData);
|
|
15387
|
+
case "generation":
|
|
15388
|
+
return this.extractGenerationLogData(spanData, span);
|
|
15389
|
+
case "custom":
|
|
15390
|
+
return this.extractCustomLogData(spanData);
|
|
15391
|
+
case "mcp_tools":
|
|
15392
|
+
return this.extractMCPListToolsLogData(spanData);
|
|
15393
|
+
case "transcription":
|
|
15394
|
+
return this.extractTranscriptionLogData(spanData);
|
|
15395
|
+
case "speech":
|
|
15396
|
+
return this.extractSpeechLogData(spanData);
|
|
15397
|
+
case "speech_group":
|
|
15398
|
+
return this.extractSpeechGroupLogData(spanData);
|
|
15399
|
+
default:
|
|
15400
|
+
return {};
|
|
15401
|
+
}
|
|
15402
|
+
}
|
|
15403
|
+
extractAgentLogData(spanData) {
|
|
15404
|
+
return {
|
|
15405
|
+
metadata: {
|
|
15406
|
+
tools: spanData.tools,
|
|
15407
|
+
handoffs: spanData.handoffs,
|
|
15408
|
+
output_type: spanData.output_type
|
|
15409
|
+
}
|
|
15410
|
+
};
|
|
15411
|
+
}
|
|
15412
|
+
extractResponseLogData(spanData, span) {
|
|
15413
|
+
const response = spanData._response;
|
|
15414
|
+
const output = isObject(response) ? response.output : void 0;
|
|
15415
|
+
const usage = isObject(response) ? response.usage : void 0;
|
|
15416
|
+
const metrics = {
|
|
15417
|
+
...this.extractTimingMetrics(span),
|
|
15418
|
+
...parseUsageMetrics(usage)
|
|
15419
|
+
};
|
|
15420
|
+
return {
|
|
15421
|
+
input: spanData._input,
|
|
15422
|
+
output,
|
|
15423
|
+
metadata: isObject(response) ? this.omitKeys(response, ["output", "usage"]) : {},
|
|
15424
|
+
metrics
|
|
15425
|
+
};
|
|
15426
|
+
}
|
|
15427
|
+
extractFunctionLogData(spanData) {
|
|
15428
|
+
return {
|
|
15429
|
+
input: spanData.input,
|
|
15430
|
+
output: spanData.output
|
|
15431
|
+
};
|
|
15432
|
+
}
|
|
15433
|
+
extractHandoffLogData(spanData) {
|
|
15434
|
+
return {
|
|
15435
|
+
metadata: {
|
|
15436
|
+
from_agent: spanData.from_agent,
|
|
15437
|
+
to_agent: spanData.to_agent
|
|
15438
|
+
}
|
|
15439
|
+
};
|
|
15440
|
+
}
|
|
15441
|
+
extractGuardrailLogData(spanData) {
|
|
15442
|
+
return {
|
|
15443
|
+
metadata: {
|
|
15444
|
+
triggered: spanData.triggered
|
|
15445
|
+
}
|
|
15446
|
+
};
|
|
15447
|
+
}
|
|
15448
|
+
extractGenerationLogData(spanData, span) {
|
|
15449
|
+
return {
|
|
15450
|
+
input: spanData.input,
|
|
15451
|
+
output: spanData.output,
|
|
15452
|
+
metadata: {
|
|
15453
|
+
model: spanData.model,
|
|
15454
|
+
model_config: spanData.model_config
|
|
15455
|
+
},
|
|
15456
|
+
metrics: {
|
|
15457
|
+
...this.extractTimingMetrics(span),
|
|
15458
|
+
...parseUsageMetrics(spanData.usage)
|
|
15459
|
+
}
|
|
15460
|
+
};
|
|
15461
|
+
}
|
|
15462
|
+
extractCustomLogData(spanData) {
|
|
15463
|
+
return spanData.data || {};
|
|
15464
|
+
}
|
|
15465
|
+
extractMCPListToolsLogData(spanData) {
|
|
15466
|
+
return {
|
|
15467
|
+
output: spanData.result,
|
|
15468
|
+
metadata: {
|
|
15469
|
+
server: spanData.server
|
|
15470
|
+
}
|
|
15471
|
+
};
|
|
15472
|
+
}
|
|
15473
|
+
extractTranscriptionLogData(spanData) {
|
|
15474
|
+
return {
|
|
15475
|
+
input: spanData.input,
|
|
15476
|
+
output: spanData.output,
|
|
15477
|
+
metadata: {
|
|
15478
|
+
model: spanData.model,
|
|
15479
|
+
model_config: spanData.model_config
|
|
15480
|
+
}
|
|
15481
|
+
};
|
|
15482
|
+
}
|
|
15483
|
+
extractSpeechLogData(spanData) {
|
|
15484
|
+
return {
|
|
15485
|
+
input: spanData.input,
|
|
15486
|
+
output: spanData.output,
|
|
15487
|
+
metadata: {
|
|
15488
|
+
model: spanData.model,
|
|
15489
|
+
model_config: spanData.model_config
|
|
15490
|
+
}
|
|
15491
|
+
};
|
|
15492
|
+
}
|
|
15493
|
+
extractSpeechGroupLogData(spanData) {
|
|
15494
|
+
return {
|
|
15495
|
+
input: spanData.input
|
|
15496
|
+
};
|
|
15497
|
+
}
|
|
15498
|
+
extractTimingMetrics(span) {
|
|
15499
|
+
const timeToFirstToken = getTimeElapsed(
|
|
15500
|
+
span.endedAt ?? void 0,
|
|
15501
|
+
span.startedAt ?? void 0
|
|
15502
|
+
);
|
|
15503
|
+
return timeToFirstToken === void 0 ? {} : { time_to_first_token: timeToFirstToken };
|
|
15504
|
+
}
|
|
15505
|
+
omitKeys(value, keys) {
|
|
15506
|
+
const result = {};
|
|
15507
|
+
for (const [key, fieldValue] of Object.entries(value)) {
|
|
15508
|
+
if (!keys.includes(key)) {
|
|
15509
|
+
result[key] = fieldValue;
|
|
15510
|
+
}
|
|
15511
|
+
}
|
|
15512
|
+
return result;
|
|
15513
|
+
}
|
|
15514
|
+
};
|
|
15515
|
+
|
|
15516
|
+
// src/instrumentation/plugins/openai-agents-plugin.ts
|
|
15517
|
+
function firstArgument(args) {
|
|
15518
|
+
if (Array.isArray(args)) {
|
|
15519
|
+
return args[0];
|
|
15520
|
+
}
|
|
15521
|
+
if (isObject(args) && "length" in args && typeof args.length === "number" && Number.isInteger(args.length) && args.length >= 0) {
|
|
15522
|
+
return Array.from(args)[0];
|
|
15523
|
+
}
|
|
15524
|
+
return void 0;
|
|
15525
|
+
}
|
|
15526
|
+
function isOpenAIAgentsTrace(value) {
|
|
15527
|
+
return isObject(value) && value.type === "trace" && typeof value.traceId === "string";
|
|
15528
|
+
}
|
|
15529
|
+
function isOpenAIAgentsSpan(value) {
|
|
15530
|
+
return isObject(value) && value.type === "trace.span" && typeof value.traceId === "string" && typeof value.spanId === "string";
|
|
15531
|
+
}
|
|
15532
|
+
var OpenAIAgentsPlugin = class extends BasePlugin {
|
|
15533
|
+
processor = new OpenAIAgentsTraceProcessor();
|
|
15534
|
+
onEnable() {
|
|
15535
|
+
this.subscribeToTraceLifecycle();
|
|
15536
|
+
}
|
|
15537
|
+
onDisable() {
|
|
15538
|
+
this.unsubscribers = unsubscribeAll(this.unsubscribers);
|
|
15539
|
+
void this.processor.shutdown();
|
|
15540
|
+
}
|
|
15541
|
+
subscribeToTraceLifecycle() {
|
|
15542
|
+
const traceStartChannel = openAIAgentsCoreChannels.onTraceStart.tracingChannel();
|
|
15543
|
+
const traceStartHandlers = {
|
|
15544
|
+
start: (event) => {
|
|
15545
|
+
const trace = firstArgument(event.arguments);
|
|
15546
|
+
if (isOpenAIAgentsTrace(trace)) {
|
|
15547
|
+
void this.processor.onTraceStart(trace);
|
|
15548
|
+
}
|
|
15549
|
+
}
|
|
15550
|
+
};
|
|
15551
|
+
traceStartChannel.subscribe(traceStartHandlers);
|
|
15552
|
+
this.unsubscribers.push(
|
|
15553
|
+
() => traceStartChannel.unsubscribe(traceStartHandlers)
|
|
15554
|
+
);
|
|
15555
|
+
const traceEndChannel = openAIAgentsCoreChannels.onTraceEnd.tracingChannel();
|
|
15556
|
+
const traceEndHandlers = {
|
|
15557
|
+
start: (event) => {
|
|
15558
|
+
const trace = firstArgument(event.arguments);
|
|
15559
|
+
if (isOpenAIAgentsTrace(trace)) {
|
|
15560
|
+
void this.processor.onTraceEnd(trace);
|
|
15561
|
+
}
|
|
15562
|
+
}
|
|
15563
|
+
};
|
|
15564
|
+
traceEndChannel.subscribe(traceEndHandlers);
|
|
15565
|
+
this.unsubscribers.push(
|
|
15566
|
+
() => traceEndChannel.unsubscribe(traceEndHandlers)
|
|
15567
|
+
);
|
|
15568
|
+
const spanStartChannel = openAIAgentsCoreChannels.onSpanStart.tracingChannel();
|
|
15569
|
+
const spanStartHandlers = {
|
|
15570
|
+
start: (event) => {
|
|
15571
|
+
const span = firstArgument(event.arguments);
|
|
15572
|
+
if (isOpenAIAgentsSpan(span)) {
|
|
15573
|
+
void this.processor.onSpanStart(span);
|
|
15574
|
+
}
|
|
15575
|
+
}
|
|
15576
|
+
};
|
|
15577
|
+
spanStartChannel.subscribe(spanStartHandlers);
|
|
15578
|
+
this.unsubscribers.push(
|
|
15579
|
+
() => spanStartChannel.unsubscribe(spanStartHandlers)
|
|
15580
|
+
);
|
|
15581
|
+
const spanEndChannel = openAIAgentsCoreChannels.onSpanEnd.tracingChannel();
|
|
15582
|
+
const spanEndHandlers = {
|
|
15583
|
+
start: (event) => {
|
|
15584
|
+
const span = firstArgument(event.arguments);
|
|
15585
|
+
if (isOpenAIAgentsSpan(span)) {
|
|
15586
|
+
void this.processor.onSpanEnd(span);
|
|
15587
|
+
}
|
|
15588
|
+
}
|
|
15589
|
+
};
|
|
15590
|
+
spanEndChannel.subscribe(spanEndHandlers);
|
|
15591
|
+
this.unsubscribers.push(() => spanEndChannel.unsubscribe(spanEndHandlers));
|
|
15592
|
+
}
|
|
15593
|
+
};
|
|
15594
|
+
|
|
15083
15595
|
// src/instrumentation/plugins/google-genai-channels.ts
|
|
15084
15596
|
var googleGenAIChannels = defineChannels("@google/genai", {
|
|
15085
15597
|
generateContent: channel({
|
|
@@ -21372,51 +21884,1761 @@ var GitHubCopilotPlugin = class extends BasePlugin {
|
|
|
21372
21884
|
}
|
|
21373
21885
|
};
|
|
21374
21886
|
|
|
21375
|
-
// src/instrumentation/
|
|
21376
|
-
|
|
21377
|
-
|
|
21887
|
+
// src/instrumentation/plugins/flue-channels.ts
|
|
21888
|
+
var flueChannels = defineChannels("@flue/runtime", {
|
|
21889
|
+
createContext: channel({
|
|
21890
|
+
channelName: "createFlueContext",
|
|
21891
|
+
kind: "sync-stream"
|
|
21892
|
+
}),
|
|
21893
|
+
openSession: channel({
|
|
21894
|
+
channelName: "Harness.openSession",
|
|
21895
|
+
kind: "async"
|
|
21896
|
+
}),
|
|
21897
|
+
contextEvent: channel({
|
|
21898
|
+
channelName: "context.event",
|
|
21899
|
+
kind: "sync-stream"
|
|
21900
|
+
}),
|
|
21901
|
+
prompt: channel({
|
|
21902
|
+
channelName: "session.prompt",
|
|
21903
|
+
kind: "async"
|
|
21904
|
+
}),
|
|
21905
|
+
skill: channel({
|
|
21906
|
+
channelName: "session.skill",
|
|
21907
|
+
kind: "async"
|
|
21908
|
+
}),
|
|
21909
|
+
task: channel({
|
|
21910
|
+
channelName: "session.task",
|
|
21911
|
+
kind: "async"
|
|
21912
|
+
}),
|
|
21913
|
+
compact: channel({
|
|
21914
|
+
channelName: "session.compact",
|
|
21915
|
+
kind: "async"
|
|
21916
|
+
})
|
|
21917
|
+
});
|
|
21918
|
+
|
|
21919
|
+
// src/wrappers/flue.ts
|
|
21920
|
+
var WRAPPED_FLUE_CONTEXT = /* @__PURE__ */ Symbol.for("braintrust.flue.wrapped-context");
|
|
21921
|
+
var WRAPPED_FLUE_HARNESS = /* @__PURE__ */ Symbol.for("braintrust.flue.wrapped-harness");
|
|
21922
|
+
var WRAPPED_FLUE_SESSION = /* @__PURE__ */ Symbol.for("braintrust.flue.wrapped-session");
|
|
21923
|
+
var SUBSCRIBED_FLUE_CONTEXT_EVENTS = /* @__PURE__ */ Symbol.for(
|
|
21924
|
+
"braintrust.flue.subscribed-context-events"
|
|
21925
|
+
);
|
|
21926
|
+
function patchFlueContextInPlace(ctx) {
|
|
21927
|
+
const context = ctx;
|
|
21928
|
+
if (context[WRAPPED_FLUE_CONTEXT]) {
|
|
21929
|
+
return ctx;
|
|
21930
|
+
}
|
|
21931
|
+
const originalInit = context.init.bind(context);
|
|
21932
|
+
try {
|
|
21933
|
+
Object.defineProperty(context, WRAPPED_FLUE_CONTEXT, {
|
|
21934
|
+
configurable: false,
|
|
21935
|
+
enumerable: false,
|
|
21936
|
+
value: true
|
|
21937
|
+
});
|
|
21938
|
+
Object.defineProperty(context, "init", {
|
|
21939
|
+
configurable: true,
|
|
21940
|
+
value: async function wrappedFlueInit(options) {
|
|
21941
|
+
const harness = await originalInit(options);
|
|
21942
|
+
return wrapFlueHarness(harness);
|
|
21943
|
+
},
|
|
21944
|
+
writable: true
|
|
21945
|
+
});
|
|
21946
|
+
} catch {
|
|
21947
|
+
}
|
|
21948
|
+
return ctx;
|
|
21378
21949
|
}
|
|
21379
|
-
|
|
21380
|
-
|
|
21381
|
-
|
|
21382
|
-
openAICodexPlugin = null;
|
|
21383
|
-
anthropicPlugin = null;
|
|
21384
|
-
aiSDKPlugin = null;
|
|
21385
|
-
claudeAgentSDKPlugin = null;
|
|
21386
|
-
cursorSDKPlugin = null;
|
|
21387
|
-
googleGenAIPlugin = null;
|
|
21388
|
-
huggingFacePlugin = null;
|
|
21389
|
-
openRouterPlugin = null;
|
|
21390
|
-
openRouterAgentPlugin = null;
|
|
21391
|
-
mistralPlugin = null;
|
|
21392
|
-
googleADKPlugin = null;
|
|
21393
|
-
coherePlugin = null;
|
|
21394
|
-
groqPlugin = null;
|
|
21395
|
-
genkitPlugin = null;
|
|
21396
|
-
gitHubCopilotPlugin = null;
|
|
21397
|
-
constructor(config = {}) {
|
|
21398
|
-
super();
|
|
21399
|
-
this.config = config;
|
|
21950
|
+
function subscribeFlueContextEvents(ctx, options = {}) {
|
|
21951
|
+
if (!ctx || typeof ctx !== "object" || typeof ctx.subscribeEvent !== "function") {
|
|
21952
|
+
return void 0;
|
|
21400
21953
|
}
|
|
21401
|
-
|
|
21402
|
-
|
|
21403
|
-
|
|
21404
|
-
|
|
21405
|
-
|
|
21406
|
-
|
|
21407
|
-
if (integrations.openaiCodexSDK !== false) {
|
|
21408
|
-
this.openAICodexPlugin = new OpenAICodexPlugin();
|
|
21409
|
-
this.openAICodexPlugin.enable();
|
|
21954
|
+
const context = ctx;
|
|
21955
|
+
const captureTurnSpans = options.captureTurnSpans ?? true;
|
|
21956
|
+
const existingSubscription = context[SUBSCRIBED_FLUE_CONTEXT_EVENTS];
|
|
21957
|
+
if (existingSubscription) {
|
|
21958
|
+
if (existingSubscription.captureTurnSpans || !captureTurnSpans) {
|
|
21959
|
+
return void 0;
|
|
21410
21960
|
}
|
|
21411
|
-
|
|
21412
|
-
|
|
21413
|
-
|
|
21961
|
+
try {
|
|
21962
|
+
existingSubscription.unsubscribe();
|
|
21963
|
+
} catch {
|
|
21414
21964
|
}
|
|
21415
|
-
|
|
21416
|
-
|
|
21417
|
-
|
|
21965
|
+
}
|
|
21966
|
+
try {
|
|
21967
|
+
const unsubscribe = ctx.subscribeEvent((event) => {
|
|
21968
|
+
flueChannels.contextEvent.traceSync(() => void 0, {
|
|
21969
|
+
arguments: [event],
|
|
21970
|
+
captureTurnSpans,
|
|
21971
|
+
context: ctx
|
|
21972
|
+
});
|
|
21973
|
+
});
|
|
21974
|
+
if (existingSubscription) {
|
|
21975
|
+
existingSubscription.captureTurnSpans = captureTurnSpans;
|
|
21976
|
+
existingSubscription.unsubscribe = unsubscribe;
|
|
21977
|
+
} else {
|
|
21978
|
+
Object.defineProperty(context, SUBSCRIBED_FLUE_CONTEXT_EVENTS, {
|
|
21979
|
+
configurable: false,
|
|
21980
|
+
enumerable: false,
|
|
21981
|
+
value: {
|
|
21982
|
+
captureTurnSpans,
|
|
21983
|
+
unsubscribe
|
|
21984
|
+
}
|
|
21985
|
+
});
|
|
21418
21986
|
}
|
|
21419
|
-
|
|
21987
|
+
return unsubscribe;
|
|
21988
|
+
} catch {
|
|
21989
|
+
return void 0;
|
|
21990
|
+
}
|
|
21991
|
+
}
|
|
21992
|
+
function wrapFlueHarness(harness) {
|
|
21993
|
+
if (!isPlausibleFlueHarness(harness)) {
|
|
21994
|
+
return harness;
|
|
21995
|
+
}
|
|
21996
|
+
const target = harness;
|
|
21997
|
+
if (target[WRAPPED_FLUE_HARNESS]) {
|
|
21998
|
+
return harness;
|
|
21999
|
+
}
|
|
22000
|
+
const originalSession = target.session.bind(target);
|
|
22001
|
+
try {
|
|
22002
|
+
Object.defineProperty(target, WRAPPED_FLUE_HARNESS, {
|
|
22003
|
+
configurable: false,
|
|
22004
|
+
enumerable: false,
|
|
22005
|
+
value: true
|
|
22006
|
+
});
|
|
22007
|
+
Object.defineProperty(target, "session", {
|
|
22008
|
+
configurable: true,
|
|
22009
|
+
value: async function wrappedFlueHarnessSession(name, options) {
|
|
22010
|
+
const session = await originalSession(name, options);
|
|
22011
|
+
return patchFlueSessionInPlace(session);
|
|
22012
|
+
},
|
|
22013
|
+
writable: true
|
|
22014
|
+
});
|
|
22015
|
+
const sessions = target.sessions;
|
|
22016
|
+
if (sessions && typeof sessions === "object") {
|
|
22017
|
+
patchFlueSessionFactory(sessions, "get");
|
|
22018
|
+
patchFlueSessionFactory(sessions, "create");
|
|
22019
|
+
}
|
|
22020
|
+
} catch {
|
|
22021
|
+
}
|
|
22022
|
+
return harness;
|
|
22023
|
+
}
|
|
22024
|
+
function patchFlueSessionInPlace(session) {
|
|
22025
|
+
if (session[WRAPPED_FLUE_SESSION]) {
|
|
22026
|
+
return session;
|
|
22027
|
+
}
|
|
22028
|
+
try {
|
|
22029
|
+
Object.defineProperty(session, WRAPPED_FLUE_SESSION, {
|
|
22030
|
+
configurable: false,
|
|
22031
|
+
enumerable: false,
|
|
22032
|
+
value: true
|
|
22033
|
+
});
|
|
22034
|
+
patchCallHandleMethod(session, "prompt", flueChannels.prompt);
|
|
22035
|
+
patchCallHandleMethod(session, "skill", flueChannels.skill);
|
|
22036
|
+
patchCallHandleMethod(session, "task", flueChannels.task);
|
|
22037
|
+
patchCompact(session);
|
|
22038
|
+
} catch {
|
|
22039
|
+
}
|
|
22040
|
+
return session;
|
|
22041
|
+
}
|
|
22042
|
+
function patchFlueSessionFactory(sessions, method) {
|
|
22043
|
+
const original = sessions[method];
|
|
22044
|
+
if (typeof original !== "function") {
|
|
22045
|
+
return;
|
|
22046
|
+
}
|
|
22047
|
+
const bound = original.bind(sessions);
|
|
22048
|
+
Object.defineProperty(sessions, method, {
|
|
22049
|
+
configurable: true,
|
|
22050
|
+
value: async function wrappedFlueSessionFactory(name, options) {
|
|
22051
|
+
const session = await bound(name, options);
|
|
22052
|
+
return patchFlueSessionInPlace(session);
|
|
22053
|
+
},
|
|
22054
|
+
writable: true
|
|
22055
|
+
});
|
|
22056
|
+
}
|
|
22057
|
+
function patchCallHandleMethod(session, method, channel2) {
|
|
22058
|
+
const original = session[method];
|
|
22059
|
+
if (typeof original !== "function") {
|
|
22060
|
+
return;
|
|
22061
|
+
}
|
|
22062
|
+
const bound = original.bind(session);
|
|
22063
|
+
Object.defineProperty(session, method, {
|
|
22064
|
+
configurable: true,
|
|
22065
|
+
value(input, options) {
|
|
22066
|
+
const args = [input, options];
|
|
22067
|
+
const { originalResult, traced } = traceFlueOperation(channel2, {
|
|
22068
|
+
context: {
|
|
22069
|
+
arguments: args,
|
|
22070
|
+
operation: method,
|
|
22071
|
+
session
|
|
22072
|
+
},
|
|
22073
|
+
run: () => bound(input, options)
|
|
22074
|
+
});
|
|
22075
|
+
return preserveCallHandle(originalResult, traced);
|
|
22076
|
+
},
|
|
22077
|
+
writable: true
|
|
22078
|
+
});
|
|
22079
|
+
}
|
|
22080
|
+
function patchCompact(session) {
|
|
22081
|
+
const original = session.compact;
|
|
22082
|
+
if (typeof original !== "function") {
|
|
22083
|
+
return;
|
|
22084
|
+
}
|
|
22085
|
+
const bound = original.bind(session);
|
|
22086
|
+
Object.defineProperty(session, "compact", {
|
|
22087
|
+
configurable: true,
|
|
22088
|
+
value() {
|
|
22089
|
+
const context = {
|
|
22090
|
+
arguments: [],
|
|
22091
|
+
operation: "compact",
|
|
22092
|
+
session
|
|
22093
|
+
};
|
|
22094
|
+
return flueChannels.compact.tracePromise(() => bound(), context);
|
|
22095
|
+
},
|
|
22096
|
+
writable: true
|
|
22097
|
+
});
|
|
22098
|
+
}
|
|
22099
|
+
function traceFlueOperation(channel2, args) {
|
|
22100
|
+
const tracingChannel = channel2.tracingChannel();
|
|
22101
|
+
const context = args.context;
|
|
22102
|
+
let originalResult;
|
|
22103
|
+
let traced;
|
|
22104
|
+
const run = () => {
|
|
22105
|
+
try {
|
|
22106
|
+
originalResult = args.run();
|
|
22107
|
+
tracingChannel.end?.publish(context);
|
|
22108
|
+
} catch (error) {
|
|
22109
|
+
context.error = normalizeError3(error);
|
|
22110
|
+
tracingChannel.error?.publish(context);
|
|
22111
|
+
tracingChannel.end?.publish(context);
|
|
22112
|
+
throw error;
|
|
22113
|
+
}
|
|
22114
|
+
traced = Promise.resolve(originalResult).then(
|
|
22115
|
+
(result) => {
|
|
22116
|
+
context.result = result;
|
|
22117
|
+
tracingChannel.asyncStart?.publish(context);
|
|
22118
|
+
tracingChannel.asyncEnd?.publish(context);
|
|
22119
|
+
return result;
|
|
22120
|
+
},
|
|
22121
|
+
(error) => {
|
|
22122
|
+
context.error = normalizeError3(error);
|
|
22123
|
+
tracingChannel.error?.publish(context);
|
|
22124
|
+
tracingChannel.asyncStart?.publish(context);
|
|
22125
|
+
tracingChannel.asyncEnd?.publish(context);
|
|
22126
|
+
throw error;
|
|
22127
|
+
}
|
|
22128
|
+
);
|
|
22129
|
+
};
|
|
22130
|
+
if (tracingChannel.start?.runStores) {
|
|
22131
|
+
tracingChannel.start.runStores(context, run);
|
|
22132
|
+
} else {
|
|
22133
|
+
tracingChannel.start?.publish(context);
|
|
22134
|
+
run();
|
|
22135
|
+
}
|
|
22136
|
+
return { originalResult, traced };
|
|
22137
|
+
}
|
|
22138
|
+
function normalizeError3(error) {
|
|
22139
|
+
return error instanceof Error ? error : new Error(String(error));
|
|
22140
|
+
}
|
|
22141
|
+
function preserveCallHandle(originalHandle, traced) {
|
|
22142
|
+
if (!isFlueCallHandle(originalHandle)) {
|
|
22143
|
+
return traced;
|
|
22144
|
+
}
|
|
22145
|
+
const handle = originalHandle;
|
|
22146
|
+
const wrapped = {
|
|
22147
|
+
get signal() {
|
|
22148
|
+
return handle.signal;
|
|
22149
|
+
},
|
|
22150
|
+
abort(reason) {
|
|
22151
|
+
return handle.abort(reason);
|
|
22152
|
+
},
|
|
22153
|
+
then(onfulfilled, onrejected) {
|
|
22154
|
+
return traced.then(onfulfilled, onrejected);
|
|
22155
|
+
}
|
|
22156
|
+
};
|
|
22157
|
+
return wrapped;
|
|
22158
|
+
}
|
|
22159
|
+
function isPlausibleFlueHarness(value) {
|
|
22160
|
+
return !!value && typeof value === "object" && typeof value.session === "function";
|
|
22161
|
+
}
|
|
22162
|
+
function isFlueCallHandle(value) {
|
|
22163
|
+
return !!value && typeof value === "object" && typeof value.then === "function" && typeof value.abort === "function" && "signal" in value;
|
|
22164
|
+
}
|
|
22165
|
+
|
|
22166
|
+
// src/instrumentation/plugins/flue-plugin.ts
|
|
22167
|
+
var FluePlugin = class extends BasePlugin {
|
|
22168
|
+
activeOperationsById = /* @__PURE__ */ new Map();
|
|
22169
|
+
activeOperationsByScope = /* @__PURE__ */ new Map();
|
|
22170
|
+
compactionsByScope = /* @__PURE__ */ new Map();
|
|
22171
|
+
pendingOperationsByKey = /* @__PURE__ */ new Map();
|
|
22172
|
+
tasksById = /* @__PURE__ */ new Map();
|
|
22173
|
+
toolsById = /* @__PURE__ */ new Map();
|
|
22174
|
+
turnsByScope = /* @__PURE__ */ new Map();
|
|
22175
|
+
onEnable() {
|
|
22176
|
+
this.subscribeToContextCreation();
|
|
22177
|
+
this.subscribeToSessionCreation();
|
|
22178
|
+
this.subscribeToContextEvents();
|
|
22179
|
+
this.subscribeToSessionOperations();
|
|
22180
|
+
}
|
|
22181
|
+
onDisable() {
|
|
22182
|
+
for (const unsubscribe of this.unsubscribers) {
|
|
22183
|
+
unsubscribe();
|
|
22184
|
+
}
|
|
22185
|
+
this.unsubscribers = [];
|
|
22186
|
+
this.activeOperationsById.clear();
|
|
22187
|
+
this.activeOperationsByScope.clear();
|
|
22188
|
+
this.compactionsByScope.clear();
|
|
22189
|
+
this.pendingOperationsByKey.clear();
|
|
22190
|
+
this.tasksById.clear();
|
|
22191
|
+
this.toolsById.clear();
|
|
22192
|
+
this.turnsByScope.clear();
|
|
22193
|
+
}
|
|
22194
|
+
subscribeToContextCreation() {
|
|
22195
|
+
const channel2 = flueChannels.createContext.tracingChannel();
|
|
22196
|
+
const handlers = {
|
|
22197
|
+
end: (event) => {
|
|
22198
|
+
const ctx = event.result;
|
|
22199
|
+
if (!ctx) {
|
|
22200
|
+
return;
|
|
22201
|
+
}
|
|
22202
|
+
subscribeFlueContextEvents(ctx, { captureTurnSpans: false });
|
|
22203
|
+
patchFlueContextInPlace(ctx);
|
|
22204
|
+
},
|
|
22205
|
+
error: () => {
|
|
22206
|
+
}
|
|
22207
|
+
};
|
|
22208
|
+
channel2.subscribe(handlers);
|
|
22209
|
+
this.unsubscribers.push(() => {
|
|
22210
|
+
channel2.unsubscribe(handlers);
|
|
22211
|
+
});
|
|
22212
|
+
}
|
|
22213
|
+
subscribeToSessionCreation() {
|
|
22214
|
+
const channel2 = flueChannels.openSession.tracingChannel();
|
|
22215
|
+
const handlers = {
|
|
22216
|
+
asyncEnd: (event) => {
|
|
22217
|
+
if (event.result) {
|
|
22218
|
+
patchFlueSessionInPlace(
|
|
22219
|
+
event.result
|
|
22220
|
+
);
|
|
22221
|
+
}
|
|
22222
|
+
if (event.harness) {
|
|
22223
|
+
wrapFlueHarness(event.harness);
|
|
22224
|
+
}
|
|
22225
|
+
},
|
|
22226
|
+
error: () => {
|
|
22227
|
+
}
|
|
22228
|
+
};
|
|
22229
|
+
channel2.subscribe(handlers);
|
|
22230
|
+
this.unsubscribers.push(() => {
|
|
22231
|
+
channel2.unsubscribe(handlers);
|
|
22232
|
+
});
|
|
22233
|
+
}
|
|
22234
|
+
subscribeToSessionOperations() {
|
|
22235
|
+
this.subscribeToSessionOperation(flueChannels.prompt);
|
|
22236
|
+
this.subscribeToSessionOperation(flueChannels.skill);
|
|
22237
|
+
this.subscribeToSessionOperation(flueChannels.task);
|
|
22238
|
+
this.subscribeToCompact();
|
|
22239
|
+
}
|
|
22240
|
+
subscribeToSessionOperation(channel2) {
|
|
22241
|
+
const tracingChannel = channel2.tracingChannel();
|
|
22242
|
+
const states = /* @__PURE__ */ new WeakMap();
|
|
22243
|
+
const ensureState2 = (event) => {
|
|
22244
|
+
const existing = states.get(event);
|
|
22245
|
+
if (existing) {
|
|
22246
|
+
return existing;
|
|
22247
|
+
}
|
|
22248
|
+
const state = this.startOperationState({
|
|
22249
|
+
args: event.arguments,
|
|
22250
|
+
moduleVersion: typeof event.moduleVersion === "string" ? event.moduleVersion : void 0,
|
|
22251
|
+
operation: event.operation,
|
|
22252
|
+
session: event.session
|
|
22253
|
+
});
|
|
22254
|
+
states.set(event, state);
|
|
22255
|
+
return state;
|
|
22256
|
+
};
|
|
22257
|
+
const unbindCurrentSpanStore = this.bindCurrentSpanStoreToOperationStart(
|
|
22258
|
+
tracingChannel,
|
|
22259
|
+
ensureState2
|
|
22260
|
+
);
|
|
22261
|
+
const handlers = {
|
|
22262
|
+
start: (event) => {
|
|
22263
|
+
ensureState2(event);
|
|
22264
|
+
},
|
|
22265
|
+
asyncEnd: (event) => {
|
|
22266
|
+
this.endOperationState(states.get(event), event.result);
|
|
22267
|
+
states.delete(event);
|
|
22268
|
+
},
|
|
22269
|
+
error: (event) => {
|
|
22270
|
+
const state = states.get(event);
|
|
22271
|
+
if (state && event.error) {
|
|
22272
|
+
safeLog3(state.span, { error: errorToString(event.error) });
|
|
22273
|
+
this.finishOperationState(state);
|
|
22274
|
+
}
|
|
22275
|
+
states.delete(event);
|
|
22276
|
+
}
|
|
22277
|
+
};
|
|
22278
|
+
tracingChannel.subscribe(handlers);
|
|
22279
|
+
this.unsubscribers.push(() => {
|
|
22280
|
+
unbindCurrentSpanStore?.();
|
|
22281
|
+
tracingChannel.unsubscribe(handlers);
|
|
22282
|
+
});
|
|
22283
|
+
}
|
|
22284
|
+
subscribeToCompact() {
|
|
22285
|
+
const tracingChannel = flueChannels.compact.tracingChannel();
|
|
22286
|
+
const states = /* @__PURE__ */ new WeakMap();
|
|
22287
|
+
const ensureState2 = (event) => {
|
|
22288
|
+
const existing = states.get(event);
|
|
22289
|
+
if (existing) {
|
|
22290
|
+
return existing;
|
|
22291
|
+
}
|
|
22292
|
+
const state = this.startOperationState({
|
|
22293
|
+
args: [],
|
|
22294
|
+
moduleVersion: typeof event.moduleVersion === "string" ? event.moduleVersion : void 0,
|
|
22295
|
+
operation: event.operation,
|
|
22296
|
+
session: event.session
|
|
22297
|
+
});
|
|
22298
|
+
states.set(event, state);
|
|
22299
|
+
return state;
|
|
22300
|
+
};
|
|
22301
|
+
const unbindCurrentSpanStore = this.bindCurrentSpanStoreToOperationStart(
|
|
22302
|
+
tracingChannel,
|
|
22303
|
+
ensureState2
|
|
22304
|
+
);
|
|
22305
|
+
const handlers = {
|
|
22306
|
+
start: (event) => {
|
|
22307
|
+
ensureState2(event);
|
|
22308
|
+
},
|
|
22309
|
+
asyncEnd: (event) => {
|
|
22310
|
+
this.endOperationState(states.get(event), void 0);
|
|
22311
|
+
states.delete(event);
|
|
22312
|
+
},
|
|
22313
|
+
error: (event) => {
|
|
22314
|
+
const state = states.get(event);
|
|
22315
|
+
if (state && event.error) {
|
|
22316
|
+
safeLog3(state.span, { error: errorToString(event.error) });
|
|
22317
|
+
this.finishOperationState(state);
|
|
22318
|
+
}
|
|
22319
|
+
states.delete(event);
|
|
22320
|
+
}
|
|
22321
|
+
};
|
|
22322
|
+
tracingChannel.subscribe(handlers);
|
|
22323
|
+
this.unsubscribers.push(() => {
|
|
22324
|
+
unbindCurrentSpanStore?.();
|
|
22325
|
+
tracingChannel.unsubscribe(handlers);
|
|
22326
|
+
});
|
|
22327
|
+
}
|
|
22328
|
+
subscribeToContextEvents() {
|
|
22329
|
+
const channel2 = flueChannels.contextEvent.tracingChannel();
|
|
22330
|
+
const handlers = {
|
|
22331
|
+
start: (event) => {
|
|
22332
|
+
const flueEvent = event.arguments[0];
|
|
22333
|
+
if (!flueEvent) {
|
|
22334
|
+
return;
|
|
22335
|
+
}
|
|
22336
|
+
try {
|
|
22337
|
+
this.handleFlueEvent(flueEvent, {
|
|
22338
|
+
captureTurnSpans: event.captureTurnSpans !== false
|
|
22339
|
+
});
|
|
22340
|
+
} catch (error) {
|
|
22341
|
+
logInstrumentationError3("Flue event", error);
|
|
22342
|
+
}
|
|
22343
|
+
},
|
|
22344
|
+
error: () => {
|
|
22345
|
+
}
|
|
22346
|
+
};
|
|
22347
|
+
channel2.subscribe(handlers);
|
|
22348
|
+
this.unsubscribers.push(() => {
|
|
22349
|
+
channel2.unsubscribe(handlers);
|
|
22350
|
+
});
|
|
22351
|
+
}
|
|
22352
|
+
bindCurrentSpanStoreToOperationStart(tracingChannel, ensureState2) {
|
|
22353
|
+
const state = _internalGetGlobalState();
|
|
22354
|
+
const startChannel = tracingChannel.start;
|
|
22355
|
+
const contextManager = state?.contextManager;
|
|
22356
|
+
const currentSpanStore = contextManager ? contextManager[BRAINTRUST_CURRENT_SPAN_STORE] : void 0;
|
|
22357
|
+
if (!currentSpanStore || !startChannel) {
|
|
22358
|
+
return void 0;
|
|
22359
|
+
}
|
|
22360
|
+
startChannel.bindStore(currentSpanStore, (event) => {
|
|
22361
|
+
const operationState = ensureState2(event);
|
|
22362
|
+
return contextManager.wrapSpanForStore(operationState.span);
|
|
22363
|
+
});
|
|
22364
|
+
return () => {
|
|
22365
|
+
startChannel.unbindStore(currentSpanStore);
|
|
22366
|
+
};
|
|
22367
|
+
}
|
|
22368
|
+
startOperationState(args) {
|
|
22369
|
+
const sessionName = getSessionName(args.session);
|
|
22370
|
+
const metadata = {
|
|
22371
|
+
...extractOperationInputMetadata(args.operation, args.args),
|
|
22372
|
+
...extractSessionMetadata(args.session),
|
|
22373
|
+
"flue.operation": args.operation,
|
|
22374
|
+
provider: "flue",
|
|
22375
|
+
...args.moduleVersion ? { "flue.version": args.moduleVersion } : {}
|
|
22376
|
+
};
|
|
22377
|
+
const span = startSpan({
|
|
22378
|
+
name: `flue.session.${args.operation}`,
|
|
22379
|
+
spanAttributes: { type: "task" /* TASK */ }
|
|
22380
|
+
});
|
|
22381
|
+
const state = {
|
|
22382
|
+
metadata,
|
|
22383
|
+
operation: args.operation,
|
|
22384
|
+
sessionName,
|
|
22385
|
+
span,
|
|
22386
|
+
startTime: getCurrentUnixTimestamp()
|
|
22387
|
+
};
|
|
22388
|
+
safeLog3(span, {
|
|
22389
|
+
input: extractOperationInput(args.operation, args.args),
|
|
22390
|
+
metadata
|
|
22391
|
+
});
|
|
22392
|
+
this.pendingOperationQueue(operationKey(sessionName, args.operation)).push(
|
|
22393
|
+
state
|
|
22394
|
+
);
|
|
22395
|
+
addOperationToScope(
|
|
22396
|
+
this.activeOperationsByScope,
|
|
22397
|
+
sessionName ?? "unknown",
|
|
22398
|
+
state
|
|
22399
|
+
);
|
|
22400
|
+
return state;
|
|
22401
|
+
}
|
|
22402
|
+
endOperationState(state, result) {
|
|
22403
|
+
if (!state) {
|
|
22404
|
+
return;
|
|
22405
|
+
}
|
|
22406
|
+
const metadata = {
|
|
22407
|
+
...state.metadata,
|
|
22408
|
+
...extractPromptResponseMetadata(result)
|
|
22409
|
+
};
|
|
22410
|
+
const metrics = {
|
|
22411
|
+
...buildDurationMetrics3(state.startTime),
|
|
22412
|
+
...metricsFromUsage(result?.usage)
|
|
22413
|
+
};
|
|
22414
|
+
safeLog3(state.span, {
|
|
22415
|
+
metadata,
|
|
22416
|
+
metrics,
|
|
22417
|
+
output: extractOperationOutput(result)
|
|
22418
|
+
});
|
|
22419
|
+
this.finishCompactionsForOperation(state);
|
|
22420
|
+
this.finishOperationState(state);
|
|
22421
|
+
}
|
|
22422
|
+
finishOperationState(state) {
|
|
22423
|
+
removePendingOperation(this.pendingOperationsByKey, state);
|
|
22424
|
+
if (state.operationId) {
|
|
22425
|
+
this.activeOperationsById.delete(state.operationId);
|
|
22426
|
+
}
|
|
22427
|
+
removeScopedOperation(this.activeOperationsByScope, state);
|
|
22428
|
+
state.span.end();
|
|
22429
|
+
}
|
|
22430
|
+
handleFlueEvent(event, options) {
|
|
22431
|
+
switch (event.type) {
|
|
22432
|
+
case "operation_start":
|
|
22433
|
+
this.handleOperationStart(event);
|
|
22434
|
+
return;
|
|
22435
|
+
case "operation":
|
|
22436
|
+
this.handleOperation(event);
|
|
22437
|
+
return;
|
|
22438
|
+
case "text_delta":
|
|
22439
|
+
if (!options.captureTurnSpans) {
|
|
22440
|
+
return;
|
|
22441
|
+
}
|
|
22442
|
+
this.ensureTurnState(event).text.push(
|
|
22443
|
+
typeof event.text === "string" ? event.text : ""
|
|
22444
|
+
);
|
|
22445
|
+
return;
|
|
22446
|
+
case "thinking_start":
|
|
22447
|
+
if (!options.captureTurnSpans) {
|
|
22448
|
+
return;
|
|
22449
|
+
}
|
|
22450
|
+
this.handleThinkingStart(event);
|
|
22451
|
+
return;
|
|
22452
|
+
case "thinking_delta":
|
|
22453
|
+
if (!options.captureTurnSpans) {
|
|
22454
|
+
return;
|
|
22455
|
+
}
|
|
22456
|
+
this.handleThinkingDelta(event);
|
|
22457
|
+
return;
|
|
22458
|
+
case "thinking_end":
|
|
22459
|
+
if (!options.captureTurnSpans) {
|
|
22460
|
+
return;
|
|
22461
|
+
}
|
|
22462
|
+
this.handleThinkingEnd(event);
|
|
22463
|
+
return;
|
|
22464
|
+
case "turn":
|
|
22465
|
+
if (!options.captureTurnSpans) {
|
|
22466
|
+
return;
|
|
22467
|
+
}
|
|
22468
|
+
this.handleTurn(event);
|
|
22469
|
+
return;
|
|
22470
|
+
case "tool_start":
|
|
22471
|
+
this.handleToolStart(event, options);
|
|
22472
|
+
return;
|
|
22473
|
+
case "tool_call":
|
|
22474
|
+
this.handleToolCall(event);
|
|
22475
|
+
return;
|
|
22476
|
+
case "task_start":
|
|
22477
|
+
this.handleTaskStart(event);
|
|
22478
|
+
return;
|
|
22479
|
+
case "task":
|
|
22480
|
+
this.handleTask(event);
|
|
22481
|
+
return;
|
|
22482
|
+
case "compaction_start":
|
|
22483
|
+
this.handleCompactionStart(event);
|
|
22484
|
+
return;
|
|
22485
|
+
case "compaction":
|
|
22486
|
+
this.handleCompaction(event);
|
|
22487
|
+
return;
|
|
22488
|
+
default:
|
|
22489
|
+
return;
|
|
22490
|
+
}
|
|
22491
|
+
}
|
|
22492
|
+
handleOperationStart(event) {
|
|
22493
|
+
if (!isInstrumentedOperation(event.operationKind)) {
|
|
22494
|
+
return;
|
|
22495
|
+
}
|
|
22496
|
+
const state = this.takePendingOperationForEvent(event);
|
|
22497
|
+
if (!state) {
|
|
22498
|
+
return;
|
|
22499
|
+
}
|
|
22500
|
+
state.operationId = event.operationId;
|
|
22501
|
+
this.activeOperationsById.set(event.operationId, state);
|
|
22502
|
+
addScopedOperation(this.activeOperationsByScope, event, state);
|
|
22503
|
+
state.metadata = {
|
|
22504
|
+
...state.metadata,
|
|
22505
|
+
...extractEventMetadata(event),
|
|
22506
|
+
"flue.operation_id": event.operationId
|
|
22507
|
+
};
|
|
22508
|
+
safeLog3(state.span, { metadata: state.metadata });
|
|
22509
|
+
}
|
|
22510
|
+
handleOperation(event) {
|
|
22511
|
+
const state = event.operationId ? this.activeOperationsById.get(event.operationId) : void 0;
|
|
22512
|
+
if (!state) {
|
|
22513
|
+
return;
|
|
22514
|
+
}
|
|
22515
|
+
const metadata = {
|
|
22516
|
+
...state.metadata,
|
|
22517
|
+
...extractEventMetadata(event),
|
|
22518
|
+
...typeof event.durationMs === "number" ? { "flue.duration_ms": event.durationMs } : {},
|
|
22519
|
+
...event.isError !== void 0 ? { "flue.is_error": event.isError } : {}
|
|
22520
|
+
};
|
|
22521
|
+
const metrics = metricsFromUsage(event.usage);
|
|
22522
|
+
safeLog3(state.span, {
|
|
22523
|
+
...event.error ? { error: errorToString(event.error) } : {},
|
|
22524
|
+
metadata,
|
|
22525
|
+
...Object.keys(metrics).length ? { metrics } : {}
|
|
22526
|
+
});
|
|
22527
|
+
}
|
|
22528
|
+
ensureTurnState(event) {
|
|
22529
|
+
const scope = scopeKey(event);
|
|
22530
|
+
const existing = this.turnsByScope.get(scope);
|
|
22531
|
+
if (existing) {
|
|
22532
|
+
return existing;
|
|
22533
|
+
}
|
|
22534
|
+
const parent = this.parentSpanForEvent(event);
|
|
22535
|
+
const metadata = {
|
|
22536
|
+
...extractEventMetadata(event),
|
|
22537
|
+
provider: "flue"
|
|
22538
|
+
};
|
|
22539
|
+
const span = startFlueSpan(parent, {
|
|
22540
|
+
name: "flue.turn",
|
|
22541
|
+
spanAttributes: { type: "llm" /* LLM */ }
|
|
22542
|
+
});
|
|
22543
|
+
const state = {
|
|
22544
|
+
metadata,
|
|
22545
|
+
span,
|
|
22546
|
+
hasThinking: false,
|
|
22547
|
+
startTime: getCurrentUnixTimestamp(),
|
|
22548
|
+
text: [],
|
|
22549
|
+
thinking: [],
|
|
22550
|
+
toolCalls: []
|
|
22551
|
+
};
|
|
22552
|
+
safeLog3(span, { metadata });
|
|
22553
|
+
this.turnsByScope.set(scope, state);
|
|
22554
|
+
return state;
|
|
22555
|
+
}
|
|
22556
|
+
handleTurn(event) {
|
|
22557
|
+
const scope = scopeKey(event);
|
|
22558
|
+
const state = this.ensureTurnState(event);
|
|
22559
|
+
const text = state.text.join("");
|
|
22560
|
+
const reasoning = state.finalThinking ?? state.thinking.join("");
|
|
22561
|
+
const outputReasoning = reasoning || (state.hasThinking ? "[reasoning stream present; content unavailable]" : void 0);
|
|
22562
|
+
const metadata = {
|
|
22563
|
+
...state.metadata,
|
|
22564
|
+
...extractEventMetadata(event),
|
|
22565
|
+
...event.model ? { model: event.model, "flue.model": event.model } : {},
|
|
22566
|
+
...event.stopReason ? { "flue.stop_reason": event.stopReason } : {},
|
|
22567
|
+
...event.isError !== void 0 ? { "flue.is_error": event.isError } : {},
|
|
22568
|
+
provider: "flue"
|
|
22569
|
+
};
|
|
22570
|
+
safeLog3(state.span, {
|
|
22571
|
+
...event.error ? { error: errorToString(event.error) } : {},
|
|
22572
|
+
metadata,
|
|
22573
|
+
metrics: {
|
|
22574
|
+
...durationMsMetrics(event.durationMs),
|
|
22575
|
+
...metricsFromUsage(event.usage)
|
|
22576
|
+
},
|
|
22577
|
+
output: toAssistantOutput(
|
|
22578
|
+
text,
|
|
22579
|
+
event.stopReason,
|
|
22580
|
+
outputReasoning,
|
|
22581
|
+
state.toolCalls
|
|
22582
|
+
)
|
|
22583
|
+
});
|
|
22584
|
+
state.span.end();
|
|
22585
|
+
this.turnsByScope.delete(scope);
|
|
22586
|
+
}
|
|
22587
|
+
handleThinkingDelta(event) {
|
|
22588
|
+
const delta = event.delta;
|
|
22589
|
+
if (typeof delta !== "string" || !delta) {
|
|
22590
|
+
return;
|
|
22591
|
+
}
|
|
22592
|
+
const state = this.ensureTurnState(event);
|
|
22593
|
+
state.hasThinking = true;
|
|
22594
|
+
state.metadata["flue.thinking"] = true;
|
|
22595
|
+
state.thinking.push(delta);
|
|
22596
|
+
}
|
|
22597
|
+
handleThinkingStart(event) {
|
|
22598
|
+
const state = this.ensureTurnState(event);
|
|
22599
|
+
state.hasThinking = true;
|
|
22600
|
+
state.metadata["flue.thinking"] = true;
|
|
22601
|
+
}
|
|
22602
|
+
handleThinkingEnd(event) {
|
|
22603
|
+
const state = this.ensureTurnState(event);
|
|
22604
|
+
state.hasThinking = true;
|
|
22605
|
+
state.metadata["flue.thinking"] = true;
|
|
22606
|
+
if (typeof event.content === "string" && event.content) {
|
|
22607
|
+
state.finalThinking = event.content;
|
|
22608
|
+
}
|
|
22609
|
+
}
|
|
22610
|
+
handleToolStart(event, options) {
|
|
22611
|
+
const toolCallId = event.toolCallId;
|
|
22612
|
+
if (!toolCallId) {
|
|
22613
|
+
return;
|
|
22614
|
+
}
|
|
22615
|
+
const parent = this.parentSpanForEvent(event);
|
|
22616
|
+
const scope = scopeKey(event);
|
|
22617
|
+
let turnState = this.turnsByScope.get(scope);
|
|
22618
|
+
if (!turnState && parent && options.captureTurnSpans) {
|
|
22619
|
+
turnState = this.ensureTurnState(event);
|
|
22620
|
+
}
|
|
22621
|
+
const metadata = {
|
|
22622
|
+
...extractEventMetadata(event),
|
|
22623
|
+
...event.toolName ? { "flue.tool_name": event.toolName } : {},
|
|
22624
|
+
"flue.tool_call_id": toolCallId,
|
|
22625
|
+
provider: "flue"
|
|
22626
|
+
};
|
|
22627
|
+
const span = startFlueSpan(parent, {
|
|
22628
|
+
name: `tool: ${event.toolName ?? "unknown"}`,
|
|
22629
|
+
spanAttributes: { type: "tool" /* TOOL */ }
|
|
22630
|
+
});
|
|
22631
|
+
if (turnState) {
|
|
22632
|
+
turnState.toolCalls.push({
|
|
22633
|
+
args: event.args,
|
|
22634
|
+
toolCallId,
|
|
22635
|
+
toolName: event.toolName
|
|
22636
|
+
});
|
|
22637
|
+
}
|
|
22638
|
+
safeLog3(span, {
|
|
22639
|
+
input: event.args,
|
|
22640
|
+
metadata
|
|
22641
|
+
});
|
|
22642
|
+
this.toolsById.set(toolKey(event), {
|
|
22643
|
+
metadata,
|
|
22644
|
+
span,
|
|
22645
|
+
startTime: getCurrentUnixTimestamp()
|
|
22646
|
+
});
|
|
22647
|
+
}
|
|
22648
|
+
handleToolCall(event) {
|
|
22649
|
+
const key = toolKey(event);
|
|
22650
|
+
const state = this.toolsById.get(key) ?? this.startSyntheticToolState(event, event.toolName ?? "unknown");
|
|
22651
|
+
const metadata = {
|
|
22652
|
+
...state.metadata,
|
|
22653
|
+
...extractEventMetadata(event),
|
|
22654
|
+
...event.toolName ? { "flue.tool_name": event.toolName } : {},
|
|
22655
|
+
...event.toolCallId ? { "flue.tool_call_id": event.toolCallId } : {},
|
|
22656
|
+
...event.isError !== void 0 ? { "flue.is_error": event.isError } : {}
|
|
22657
|
+
};
|
|
22658
|
+
safeLog3(state.span, {
|
|
22659
|
+
...event.isError ? { error: errorToString(event.result) } : {},
|
|
22660
|
+
metadata,
|
|
22661
|
+
metrics: durationMsMetrics(event.durationMs),
|
|
22662
|
+
output: event.result
|
|
22663
|
+
});
|
|
22664
|
+
state.span.end();
|
|
22665
|
+
this.toolsById.delete(key);
|
|
22666
|
+
}
|
|
22667
|
+
handleTaskStart(event) {
|
|
22668
|
+
const parent = this.parentSpanForEvent(event);
|
|
22669
|
+
const metadata = {
|
|
22670
|
+
...extractEventMetadata(event),
|
|
22671
|
+
...event.role ? { "flue.role": event.role } : {},
|
|
22672
|
+
...event.cwd ? { "flue.cwd": event.cwd } : {},
|
|
22673
|
+
"flue.task_id": event.taskId,
|
|
22674
|
+
provider: "flue"
|
|
22675
|
+
};
|
|
22676
|
+
const span = startFlueSpan(parent, {
|
|
22677
|
+
name: "flue.task",
|
|
22678
|
+
spanAttributes: { type: "task" /* TASK */ }
|
|
22679
|
+
});
|
|
22680
|
+
safeLog3(span, {
|
|
22681
|
+
input: event.prompt,
|
|
22682
|
+
metadata
|
|
22683
|
+
});
|
|
22684
|
+
this.tasksById.set(event.taskId, {
|
|
22685
|
+
metadata,
|
|
22686
|
+
span,
|
|
22687
|
+
startTime: getCurrentUnixTimestamp()
|
|
22688
|
+
});
|
|
22689
|
+
}
|
|
22690
|
+
handleTask(event) {
|
|
22691
|
+
const state = this.tasksById.get(event.taskId);
|
|
22692
|
+
if (!state) {
|
|
22693
|
+
return;
|
|
22694
|
+
}
|
|
22695
|
+
safeLog3(state.span, {
|
|
22696
|
+
...event.isError ? { error: errorToString(event.result) } : {},
|
|
22697
|
+
metadata: {
|
|
22698
|
+
...state.metadata,
|
|
22699
|
+
...extractEventMetadata(event),
|
|
22700
|
+
...event.isError !== void 0 ? { "flue.is_error": event.isError } : {}
|
|
22701
|
+
},
|
|
22702
|
+
metrics: durationMsMetrics(event.durationMs),
|
|
22703
|
+
output: event.result
|
|
22704
|
+
});
|
|
22705
|
+
state.span.end();
|
|
22706
|
+
this.tasksById.delete(event.taskId);
|
|
22707
|
+
}
|
|
22708
|
+
handleCompactionStart(event) {
|
|
22709
|
+
const operationState = this.operationStateForEvent(event);
|
|
22710
|
+
const parent = operationState?.span ?? this.parentSpanForEvent(event);
|
|
22711
|
+
const metadata = {
|
|
22712
|
+
...extractEventMetadata(event),
|
|
22713
|
+
...event.reason ? { "flue.compaction_reason": event.reason } : {},
|
|
22714
|
+
provider: "flue"
|
|
22715
|
+
};
|
|
22716
|
+
const input = {
|
|
22717
|
+
...typeof event.estimatedTokens === "number" ? { estimatedTokens: event.estimatedTokens } : {},
|
|
22718
|
+
...event.reason ? { reason: event.reason } : {}
|
|
22719
|
+
};
|
|
22720
|
+
const span = startFlueSpan(parent, {
|
|
22721
|
+
name: "flue.compaction",
|
|
22722
|
+
spanAttributes: { type: "task" /* TASK */ }
|
|
22723
|
+
});
|
|
22724
|
+
safeLog3(span, {
|
|
22725
|
+
input,
|
|
22726
|
+
metadata
|
|
22727
|
+
});
|
|
22728
|
+
this.compactionsByScope.set(scopeKey(event), {
|
|
22729
|
+
input,
|
|
22730
|
+
metadata,
|
|
22731
|
+
operationState,
|
|
22732
|
+
span,
|
|
22733
|
+
startTime: getCurrentUnixTimestamp()
|
|
22734
|
+
});
|
|
22735
|
+
}
|
|
22736
|
+
handleCompaction(event) {
|
|
22737
|
+
const key = scopeKey(event);
|
|
22738
|
+
const state = this.compactionsByScope.get(key) ?? this.findCompactionState(event);
|
|
22739
|
+
if (!state) {
|
|
22740
|
+
return;
|
|
22741
|
+
}
|
|
22742
|
+
safeLog3(state.span, {
|
|
22743
|
+
metadata: {
|
|
22744
|
+
...state.metadata,
|
|
22745
|
+
...extractEventMetadata(event),
|
|
22746
|
+
...typeof event.messagesBefore === "number" ? { "flue.messages_before": event.messagesBefore } : {},
|
|
22747
|
+
...typeof event.messagesAfter === "number" ? { "flue.messages_after": event.messagesAfter } : {}
|
|
22748
|
+
},
|
|
22749
|
+
metrics: {
|
|
22750
|
+
...durationMsMetrics(event.durationMs),
|
|
22751
|
+
...metricsFromUsage(event.usage)
|
|
22752
|
+
},
|
|
22753
|
+
output: {
|
|
22754
|
+
messagesAfter: event.messagesAfter,
|
|
22755
|
+
messagesBefore: event.messagesBefore
|
|
22756
|
+
}
|
|
22757
|
+
});
|
|
22758
|
+
state.span.end();
|
|
22759
|
+
this.deleteCompactionState(state);
|
|
22760
|
+
}
|
|
22761
|
+
findCompactionState(event) {
|
|
22762
|
+
const operationState = this.operationStateForEvent(event);
|
|
22763
|
+
for (const state of this.compactionsByScope.values()) {
|
|
22764
|
+
if (operationState && state.operationState === operationState) {
|
|
22765
|
+
return state;
|
|
22766
|
+
}
|
|
22767
|
+
}
|
|
22768
|
+
return void 0;
|
|
22769
|
+
}
|
|
22770
|
+
finishCompactionsForOperation(operationState) {
|
|
22771
|
+
for (const state of [...this.compactionsByScope.values()]) {
|
|
22772
|
+
if (state.operationState !== operationState) {
|
|
22773
|
+
continue;
|
|
22774
|
+
}
|
|
22775
|
+
safeLog3(state.span, {
|
|
22776
|
+
input: state.input,
|
|
22777
|
+
metadata: state.metadata,
|
|
22778
|
+
metrics: {
|
|
22779
|
+
...buildDurationMetrics3(state.startTime)
|
|
22780
|
+
},
|
|
22781
|
+
output: { completed: true }
|
|
22782
|
+
});
|
|
22783
|
+
state.span.end();
|
|
22784
|
+
this.deleteCompactionState(state);
|
|
22785
|
+
}
|
|
22786
|
+
}
|
|
22787
|
+
deleteCompactionState(state) {
|
|
22788
|
+
for (const [key, candidate] of this.compactionsByScope) {
|
|
22789
|
+
if (candidate !== state) {
|
|
22790
|
+
continue;
|
|
22791
|
+
}
|
|
22792
|
+
this.compactionsByScope.delete(key);
|
|
22793
|
+
return;
|
|
22794
|
+
}
|
|
22795
|
+
}
|
|
22796
|
+
startSyntheticToolState(event, toolName) {
|
|
22797
|
+
const parent = this.parentSpanForEvent(event);
|
|
22798
|
+
const metadata = {
|
|
22799
|
+
...extractEventMetadata(event),
|
|
22800
|
+
...event.toolCallId ? { "flue.tool_call_id": event.toolCallId } : {},
|
|
22801
|
+
"flue.tool_name": toolName,
|
|
22802
|
+
provider: "flue"
|
|
22803
|
+
};
|
|
22804
|
+
const span = startFlueSpan(parent, {
|
|
22805
|
+
name: `tool: ${toolName}`,
|
|
22806
|
+
spanAttributes: { type: "tool" /* TOOL */ }
|
|
22807
|
+
});
|
|
22808
|
+
safeLog3(span, { metadata });
|
|
22809
|
+
return { metadata, span, startTime: getCurrentUnixTimestamp() };
|
|
22810
|
+
}
|
|
22811
|
+
operationStateForEvent(event) {
|
|
22812
|
+
if (event.operationId) {
|
|
22813
|
+
const operation = this.activeOperationsById.get(event.operationId) ?? this.promotePendingOperationForEvent(event);
|
|
22814
|
+
if (operation) {
|
|
22815
|
+
return operation;
|
|
22816
|
+
}
|
|
22817
|
+
}
|
|
22818
|
+
return this.activeOperationForEventScope(event) ?? this.pendingOperationForEventScope(event);
|
|
22819
|
+
}
|
|
22820
|
+
parentSpanForEvent(event) {
|
|
22821
|
+
if (event.operationId) {
|
|
22822
|
+
const operation = this.operationStateForEvent(event);
|
|
22823
|
+
if (operation) {
|
|
22824
|
+
return operation.span;
|
|
22825
|
+
}
|
|
22826
|
+
}
|
|
22827
|
+
if (event.taskId) {
|
|
22828
|
+
return this.tasksById.get(event.taskId)?.span;
|
|
22829
|
+
}
|
|
22830
|
+
return this.operationStateForEvent(event)?.span;
|
|
22831
|
+
}
|
|
22832
|
+
promotePendingOperationForEvent(event) {
|
|
22833
|
+
if (!event.operationId) {
|
|
22834
|
+
return void 0;
|
|
22835
|
+
}
|
|
22836
|
+
const scopePrefixes = operationScopePrefixes(event);
|
|
22837
|
+
for (const [candidateKey, candidateQueue] of this.pendingOperationsByKey) {
|
|
22838
|
+
if (!candidateQueue.length || !operationKeyMatchesScopes(candidateKey, scopePrefixes)) {
|
|
22839
|
+
continue;
|
|
22840
|
+
}
|
|
22841
|
+
const state = candidateQueue.shift();
|
|
22842
|
+
if (!state) {
|
|
22843
|
+
return void 0;
|
|
22844
|
+
}
|
|
22845
|
+
state.operationId = event.operationId;
|
|
22846
|
+
this.activeOperationsById.set(event.operationId, state);
|
|
22847
|
+
addScopedOperation(this.activeOperationsByScope, event, state);
|
|
22848
|
+
state.metadata = {
|
|
22849
|
+
...state.metadata,
|
|
22850
|
+
...extractEventMetadata(event),
|
|
22851
|
+
"flue.operation_id": event.operationId
|
|
22852
|
+
};
|
|
22853
|
+
safeLog3(state.span, { metadata: state.metadata });
|
|
22854
|
+
return state;
|
|
22855
|
+
}
|
|
22856
|
+
return void 0;
|
|
22857
|
+
}
|
|
22858
|
+
activeOperationForEventScope(event) {
|
|
22859
|
+
for (const scope of operationScopeNames(event)) {
|
|
22860
|
+
const operations = this.activeOperationsByScope.get(scope);
|
|
22861
|
+
if (operations?.length) {
|
|
22862
|
+
return operations[operations.length - 1];
|
|
22863
|
+
}
|
|
22864
|
+
}
|
|
22865
|
+
return void 0;
|
|
22866
|
+
}
|
|
22867
|
+
pendingOperationForEventScope(event) {
|
|
22868
|
+
const scopePrefixes = operationScopePrefixes(event);
|
|
22869
|
+
for (const [candidateKey, candidateQueue] of this.pendingOperationsByKey) {
|
|
22870
|
+
if (!candidateQueue.length || !operationKeyMatchesScopes(candidateKey, scopePrefixes)) {
|
|
22871
|
+
continue;
|
|
22872
|
+
}
|
|
22873
|
+
return candidateQueue[0];
|
|
22874
|
+
}
|
|
22875
|
+
return void 0;
|
|
22876
|
+
}
|
|
22877
|
+
takePendingOperationForEvent(event) {
|
|
22878
|
+
const key = operationKey(event.session, event.operationKind);
|
|
22879
|
+
const queue = this.pendingOperationsByKey.get(key);
|
|
22880
|
+
if (queue?.length) {
|
|
22881
|
+
return queue.shift();
|
|
22882
|
+
}
|
|
22883
|
+
for (const [candidateKey, candidateQueue] of this.pendingOperationsByKey) {
|
|
22884
|
+
if (candidateKey.endsWith(`::${event.operationKind}`) && candidateQueue.length) {
|
|
22885
|
+
return candidateQueue.shift();
|
|
22886
|
+
}
|
|
22887
|
+
}
|
|
22888
|
+
return void 0;
|
|
22889
|
+
}
|
|
22890
|
+
pendingOperationQueue(key) {
|
|
22891
|
+
const existing = this.pendingOperationsByKey.get(key);
|
|
22892
|
+
if (existing) {
|
|
22893
|
+
return existing;
|
|
22894
|
+
}
|
|
22895
|
+
const queue = [];
|
|
22896
|
+
this.pendingOperationsByKey.set(key, queue);
|
|
22897
|
+
return queue;
|
|
22898
|
+
}
|
|
22899
|
+
};
|
|
22900
|
+
function isInstrumentedOperation(operation) {
|
|
22901
|
+
return operation === "prompt" || operation === "skill" || operation === "task" || operation === "compact";
|
|
22902
|
+
}
|
|
22903
|
+
function getSessionName(session) {
|
|
22904
|
+
return typeof session?.name === "string" ? session.name : void 0;
|
|
22905
|
+
}
|
|
22906
|
+
function operationKey(sessionName, operation) {
|
|
22907
|
+
return `${sessionName ?? "unknown"}::${operation}`;
|
|
22908
|
+
}
|
|
22909
|
+
function operationScopePrefixes(event) {
|
|
22910
|
+
const scopes = /* @__PURE__ */ new Set();
|
|
22911
|
+
for (const scope of operationScopeNames(event)) {
|
|
22912
|
+
scopes.add(`${scope}::`);
|
|
22913
|
+
}
|
|
22914
|
+
return scopes;
|
|
22915
|
+
}
|
|
22916
|
+
function operationKeyMatchesScopes(key, scopes) {
|
|
22917
|
+
for (const scope of scopes) {
|
|
22918
|
+
if (key.startsWith(scope)) {
|
|
22919
|
+
return true;
|
|
22920
|
+
}
|
|
22921
|
+
}
|
|
22922
|
+
return false;
|
|
22923
|
+
}
|
|
22924
|
+
function operationScopeNames(event) {
|
|
22925
|
+
const scopes = /* @__PURE__ */ new Set();
|
|
22926
|
+
if (event.session) {
|
|
22927
|
+
scopes.add(event.session);
|
|
22928
|
+
}
|
|
22929
|
+
if (event.parentSession) {
|
|
22930
|
+
scopes.add(event.parentSession);
|
|
22931
|
+
}
|
|
22932
|
+
if (!scopes.size) {
|
|
22933
|
+
scopes.add("unknown");
|
|
22934
|
+
}
|
|
22935
|
+
return scopes;
|
|
22936
|
+
}
|
|
22937
|
+
function addScopedOperation(operationsByScope, event, state) {
|
|
22938
|
+
for (const scope of operationScopeNames(event)) {
|
|
22939
|
+
addOperationToScope(operationsByScope, scope, state);
|
|
22940
|
+
}
|
|
22941
|
+
}
|
|
22942
|
+
function addOperationToScope(operationsByScope, scope, state) {
|
|
22943
|
+
const operations = operationsByScope.get(scope);
|
|
22944
|
+
if (operations) {
|
|
22945
|
+
if (!operations.includes(state)) {
|
|
22946
|
+
operations.push(state);
|
|
22947
|
+
}
|
|
22948
|
+
} else {
|
|
22949
|
+
operationsByScope.set(scope, [state]);
|
|
22950
|
+
}
|
|
22951
|
+
}
|
|
22952
|
+
function removeScopedOperation(operationsByScope, state) {
|
|
22953
|
+
for (const [scope, operations] of operationsByScope) {
|
|
22954
|
+
const index = operations.indexOf(state);
|
|
22955
|
+
if (index === -1) {
|
|
22956
|
+
continue;
|
|
22957
|
+
}
|
|
22958
|
+
operations.splice(index, 1);
|
|
22959
|
+
if (operations.length === 0) {
|
|
22960
|
+
operationsByScope.delete(scope);
|
|
22961
|
+
}
|
|
22962
|
+
}
|
|
22963
|
+
}
|
|
22964
|
+
function removePendingOperation(pendingOperationsByKey, state) {
|
|
22965
|
+
for (const [key, queue] of pendingOperationsByKey) {
|
|
22966
|
+
const index = queue.indexOf(state);
|
|
22967
|
+
if (index === -1) {
|
|
22968
|
+
continue;
|
|
22969
|
+
}
|
|
22970
|
+
queue.splice(index, 1);
|
|
22971
|
+
if (queue.length === 0) {
|
|
22972
|
+
pendingOperationsByKey.delete(key);
|
|
22973
|
+
}
|
|
22974
|
+
return;
|
|
22975
|
+
}
|
|
22976
|
+
}
|
|
22977
|
+
function extractSessionMetadata(session) {
|
|
22978
|
+
const sessionName = getSessionName(session);
|
|
22979
|
+
return sessionName ? { "flue.session": sessionName } : {};
|
|
22980
|
+
}
|
|
22981
|
+
function extractEventMetadata(event) {
|
|
22982
|
+
return {
|
|
22983
|
+
...event.runId ? { "flue.run_id": event.runId } : {},
|
|
22984
|
+
...typeof event.eventIndex === "number" ? { "flue.event_index": event.eventIndex } : {},
|
|
22985
|
+
...event.session ? { "flue.session": event.session } : {},
|
|
22986
|
+
...event.parentSession ? { "flue.parent_session": event.parentSession } : {},
|
|
22987
|
+
...event.harness ? { "flue.harness": event.harness } : {},
|
|
22988
|
+
...event.taskId ? { "flue.task_id": event.taskId } : {},
|
|
22989
|
+
...event.operationId ? { "flue.operation_id": event.operationId } : {}
|
|
22990
|
+
};
|
|
22991
|
+
}
|
|
22992
|
+
function extractOperationInput(operation, args) {
|
|
22993
|
+
switch (operation) {
|
|
22994
|
+
case "prompt":
|
|
22995
|
+
case "task":
|
|
22996
|
+
return args[0];
|
|
22997
|
+
case "skill":
|
|
22998
|
+
return {
|
|
22999
|
+
args: getOptionObject(args[1])?.args,
|
|
23000
|
+
name: args[0]
|
|
23001
|
+
};
|
|
23002
|
+
case "compact":
|
|
23003
|
+
return void 0;
|
|
23004
|
+
}
|
|
23005
|
+
}
|
|
23006
|
+
function extractOperationInputMetadata(operation, args) {
|
|
23007
|
+
const options = getOptionObject(args[1]);
|
|
23008
|
+
return {
|
|
23009
|
+
...operation === "skill" && typeof args[0] === "string" ? { "flue.skill_name": args[0] } : {},
|
|
23010
|
+
...options?.model ? { model: options.model, "flue.model": options.model } : {},
|
|
23011
|
+
...options?.role ? { "flue.role": options.role } : {},
|
|
23012
|
+
...options?.thinkingLevel ? { "flue.thinking_level": options.thinkingLevel } : {},
|
|
23013
|
+
...typeof options?.cwd === "string" ? { "flue.cwd": options.cwd } : {},
|
|
23014
|
+
...Array.isArray(options?.tools) ? {
|
|
23015
|
+
"flue.tools_count": options.tools.length,
|
|
23016
|
+
tools: summarizeTools(options.tools)
|
|
23017
|
+
} : {},
|
|
23018
|
+
...Array.isArray(options?.images) ? { "flue.images_count": options.images.length } : {},
|
|
23019
|
+
...options?.result || options?.schema ? { "flue.result_schema": true } : {}
|
|
23020
|
+
};
|
|
23021
|
+
}
|
|
23022
|
+
function getOptionObject(value) {
|
|
23023
|
+
return isObject(value) ? value : void 0;
|
|
23024
|
+
}
|
|
23025
|
+
function summarizeTools(tools) {
|
|
23026
|
+
return tools.flatMap((tool) => {
|
|
23027
|
+
if (!isObject(tool)) {
|
|
23028
|
+
return [];
|
|
23029
|
+
}
|
|
23030
|
+
const name = typeof tool.name === "string" ? tool.name : void 0;
|
|
23031
|
+
if (!name) {
|
|
23032
|
+
return [];
|
|
23033
|
+
}
|
|
23034
|
+
return [
|
|
23035
|
+
{
|
|
23036
|
+
function: {
|
|
23037
|
+
description: typeof tool.description === "string" ? tool.description : void 0,
|
|
23038
|
+
name,
|
|
23039
|
+
parameters: tool.parameters
|
|
23040
|
+
},
|
|
23041
|
+
type: "function"
|
|
23042
|
+
}
|
|
23043
|
+
];
|
|
23044
|
+
});
|
|
23045
|
+
}
|
|
23046
|
+
function extractPromptResponseMetadata(result) {
|
|
23047
|
+
const modelId = result?.model && typeof result.model.id === "string" ? result.model.id : void 0;
|
|
23048
|
+
return modelId ? {
|
|
23049
|
+
model: modelId,
|
|
23050
|
+
"flue.model": modelId
|
|
23051
|
+
} : {};
|
|
23052
|
+
}
|
|
23053
|
+
function extractOperationOutput(result) {
|
|
23054
|
+
if (!result) {
|
|
23055
|
+
return void 0;
|
|
23056
|
+
}
|
|
23057
|
+
if ("data" in result) {
|
|
23058
|
+
return result.data;
|
|
23059
|
+
}
|
|
23060
|
+
if ("text" in result) {
|
|
23061
|
+
return result.text;
|
|
23062
|
+
}
|
|
23063
|
+
return result;
|
|
23064
|
+
}
|
|
23065
|
+
function metricsFromUsage(usage) {
|
|
23066
|
+
return {
|
|
23067
|
+
...typeof usage?.input === "number" ? { prompt_tokens: usage.input } : {},
|
|
23068
|
+
...typeof usage?.output === "number" ? { completion_tokens: usage.output } : {},
|
|
23069
|
+
...typeof usage?.cacheRead === "number" ? { prompt_cached_tokens: usage.cacheRead } : {},
|
|
23070
|
+
...typeof usage?.cacheWrite === "number" ? { prompt_cache_creation_tokens: usage.cacheWrite } : {},
|
|
23071
|
+
...typeof usage?.totalTokens === "number" ? { tokens: usage.totalTokens } : {},
|
|
23072
|
+
...typeof usage?.cost?.total === "number" ? { estimated_cost: usage.cost.total } : {}
|
|
23073
|
+
};
|
|
23074
|
+
}
|
|
23075
|
+
function buildDurationMetrics3(startTime) {
|
|
23076
|
+
return {
|
|
23077
|
+
duration_ms: Math.max(0, (getCurrentUnixTimestamp() - startTime) * 1e3)
|
|
23078
|
+
};
|
|
23079
|
+
}
|
|
23080
|
+
function durationMsMetrics(durationMs) {
|
|
23081
|
+
return typeof durationMs === "number" ? { duration_ms: durationMs } : {};
|
|
23082
|
+
}
|
|
23083
|
+
function scopeKey(event) {
|
|
23084
|
+
if (event.operationId) {
|
|
23085
|
+
return `operation:${event.operationId}`;
|
|
23086
|
+
}
|
|
23087
|
+
if (event.taskId) {
|
|
23088
|
+
return `task:${event.taskId}`;
|
|
23089
|
+
}
|
|
23090
|
+
if (event.session) {
|
|
23091
|
+
return `session:${event.session}`;
|
|
23092
|
+
}
|
|
23093
|
+
return "flue:unknown";
|
|
23094
|
+
}
|
|
23095
|
+
function toolKey(event) {
|
|
23096
|
+
return `${scopeKey(event)}::tool:${event.toolCallId ?? "unknown"}`;
|
|
23097
|
+
}
|
|
23098
|
+
function toAssistantOutput(text, finishReason, reasoning, toolCalls) {
|
|
23099
|
+
return [
|
|
23100
|
+
{
|
|
23101
|
+
finish_reason: finishReason ?? "stop",
|
|
23102
|
+
index: 0,
|
|
23103
|
+
message: {
|
|
23104
|
+
content: text,
|
|
23105
|
+
...reasoning ? { reasoning } : {},
|
|
23106
|
+
role: "assistant",
|
|
23107
|
+
...toolCalls?.length ? {
|
|
23108
|
+
tool_calls: toolCalls.map((toolCall) => ({
|
|
23109
|
+
function: {
|
|
23110
|
+
arguments: toolCall.args === void 0 ? "{}" : JSON.stringify(toolCall.args),
|
|
23111
|
+
name: toolCall.toolName ?? "unknown"
|
|
23112
|
+
},
|
|
23113
|
+
...toolCall.toolCallId ? { id: toolCall.toolCallId } : {},
|
|
23114
|
+
type: "function"
|
|
23115
|
+
}))
|
|
23116
|
+
} : {}
|
|
23117
|
+
}
|
|
23118
|
+
}
|
|
23119
|
+
];
|
|
23120
|
+
}
|
|
23121
|
+
function startFlueSpan(parent, args) {
|
|
23122
|
+
return parent ? withCurrent(parent, () => startSpan(args)) : startSpan(args);
|
|
23123
|
+
}
|
|
23124
|
+
function safeLog3(span, event) {
|
|
23125
|
+
try {
|
|
23126
|
+
span.log(event);
|
|
23127
|
+
} catch (error) {
|
|
23128
|
+
logInstrumentationError3("Flue span log", error);
|
|
23129
|
+
}
|
|
23130
|
+
}
|
|
23131
|
+
function errorToString(error) {
|
|
23132
|
+
if (error instanceof Error) {
|
|
23133
|
+
return error.message;
|
|
23134
|
+
}
|
|
23135
|
+
if (typeof error === "string") {
|
|
23136
|
+
return error;
|
|
23137
|
+
}
|
|
23138
|
+
try {
|
|
23139
|
+
return JSON.stringify(error);
|
|
23140
|
+
} catch {
|
|
23141
|
+
return String(error);
|
|
23142
|
+
}
|
|
23143
|
+
}
|
|
23144
|
+
function logInstrumentationError3(label, error) {
|
|
23145
|
+
console.error(`Error in ${label} instrumentation:`, error);
|
|
23146
|
+
}
|
|
23147
|
+
|
|
23148
|
+
// src/wrappers/langchain/callback-handler.ts
|
|
23149
|
+
var BRAINTRUST_LANGCHAIN_CALLBACK_HANDLER_NAME = "BraintrustCallbackHandler";
|
|
23150
|
+
var BraintrustLangChainCallbackHandler = class {
|
|
23151
|
+
name = BRAINTRUST_LANGCHAIN_CALLBACK_HANDLER_NAME;
|
|
23152
|
+
spans = /* @__PURE__ */ new Map();
|
|
23153
|
+
skippedRuns = /* @__PURE__ */ new Set();
|
|
23154
|
+
parent;
|
|
23155
|
+
rootRunId;
|
|
23156
|
+
options;
|
|
23157
|
+
startTimes = /* @__PURE__ */ new Map();
|
|
23158
|
+
firstTokenTimes = /* @__PURE__ */ new Map();
|
|
23159
|
+
ttftMs = /* @__PURE__ */ new Map();
|
|
23160
|
+
constructor(options) {
|
|
23161
|
+
this.parent = options?.parent;
|
|
23162
|
+
this.options = {
|
|
23163
|
+
debug: options?.debug ?? false,
|
|
23164
|
+
excludeMetadataProps: options?.excludeMetadataProps ?? /^(l[sc]_|langgraph_|__pregel_|checkpoint_ns)/,
|
|
23165
|
+
logger: options?.logger
|
|
23166
|
+
};
|
|
23167
|
+
}
|
|
23168
|
+
startSpan({
|
|
23169
|
+
runId,
|
|
23170
|
+
parentRunId,
|
|
23171
|
+
...args
|
|
23172
|
+
}) {
|
|
23173
|
+
if (this.spans.has(runId)) {
|
|
23174
|
+
return;
|
|
23175
|
+
}
|
|
23176
|
+
if (!parentRunId) {
|
|
23177
|
+
this.rootRunId = runId;
|
|
23178
|
+
}
|
|
23179
|
+
const tags = args.event?.tags;
|
|
23180
|
+
const spanAttributes = args.spanAttributes || {};
|
|
23181
|
+
spanAttributes.type = args.type || spanAttributes.type || "task";
|
|
23182
|
+
args.type = spanAttributes.type;
|
|
23183
|
+
const currentParent = (typeof this.parent === "function" ? this.parent() : this.parent) ?? currentSpan();
|
|
23184
|
+
let parentSpan;
|
|
23185
|
+
if (parentRunId && this.spans.has(parentRunId)) {
|
|
23186
|
+
parentSpan = this.spans.get(parentRunId);
|
|
23187
|
+
} else if (!Object.is(currentParent, NOOP_SPAN)) {
|
|
23188
|
+
parentSpan = currentParent;
|
|
23189
|
+
} else if (this.options.logger) {
|
|
23190
|
+
parentSpan = this.options.logger;
|
|
23191
|
+
} else {
|
|
23192
|
+
parentSpan = { startSpan };
|
|
23193
|
+
}
|
|
23194
|
+
args.event = {
|
|
23195
|
+
...args.event,
|
|
23196
|
+
tags: void 0,
|
|
23197
|
+
metadata: {
|
|
23198
|
+
...tags ? { tags } : {},
|
|
23199
|
+
...args.event?.metadata,
|
|
23200
|
+
braintrust: {
|
|
23201
|
+
integration_name: "langchain-js",
|
|
23202
|
+
sdk_language: "javascript"
|
|
23203
|
+
},
|
|
23204
|
+
run_id: runId,
|
|
23205
|
+
parent_run_id: parentRunId,
|
|
23206
|
+
...this.options.debug ? { runId, parentRunId } : {}
|
|
23207
|
+
}
|
|
23208
|
+
};
|
|
23209
|
+
let span = parentSpan.startSpan(args);
|
|
23210
|
+
if (!Object.is(this.options.logger, NOOP_SPAN) && Object.is(span, NOOP_SPAN)) {
|
|
23211
|
+
span = initLogger().startSpan(args);
|
|
23212
|
+
}
|
|
23213
|
+
this.spans.set(runId, span);
|
|
23214
|
+
}
|
|
23215
|
+
endSpan({
|
|
23216
|
+
runId,
|
|
23217
|
+
parentRunId,
|
|
23218
|
+
tags,
|
|
23219
|
+
metadata,
|
|
23220
|
+
...args
|
|
23221
|
+
}) {
|
|
23222
|
+
if (!this.spans.has(runId)) {
|
|
23223
|
+
return;
|
|
23224
|
+
}
|
|
23225
|
+
if (this.skippedRuns.has(runId)) {
|
|
23226
|
+
this.skippedRuns.delete(runId);
|
|
23227
|
+
return;
|
|
23228
|
+
}
|
|
23229
|
+
const span = this.spans.get(runId);
|
|
23230
|
+
this.spans.delete(runId);
|
|
23231
|
+
if (runId === this.rootRunId) {
|
|
23232
|
+
this.rootRunId = void 0;
|
|
23233
|
+
}
|
|
23234
|
+
span.log({ ...args, metadata: { tags, ...metadata } });
|
|
23235
|
+
span.end();
|
|
23236
|
+
}
|
|
23237
|
+
async handleLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, runName) {
|
|
23238
|
+
this.startSpan({
|
|
23239
|
+
runId,
|
|
23240
|
+
parentRunId,
|
|
23241
|
+
name: runName ?? getSerializedName(llm) ?? "LLM",
|
|
23242
|
+
type: "llm",
|
|
23243
|
+
event: {
|
|
23244
|
+
input: prompts,
|
|
23245
|
+
tags,
|
|
23246
|
+
metadata: {
|
|
23247
|
+
serialized: llm,
|
|
23248
|
+
name: runName,
|
|
23249
|
+
metadata,
|
|
23250
|
+
...extraParams
|
|
23251
|
+
}
|
|
23252
|
+
}
|
|
23253
|
+
});
|
|
23254
|
+
}
|
|
23255
|
+
async handleLLMError(err, runId, parentRunId, tags) {
|
|
23256
|
+
this.endSpan({ runId, parentRunId, error: err, tags });
|
|
23257
|
+
}
|
|
23258
|
+
async handleLLMEnd(output, runId, parentRunId, tags) {
|
|
23259
|
+
const metrics = getMetricsFromResponse(output);
|
|
23260
|
+
const modelName2 = getModelNameFromResponse(output);
|
|
23261
|
+
const ttft = this.ttftMs.get(runId);
|
|
23262
|
+
if (ttft !== void 0) {
|
|
23263
|
+
metrics.time_to_first_token = ttft;
|
|
23264
|
+
}
|
|
23265
|
+
this.startTimes.delete(runId);
|
|
23266
|
+
this.firstTokenTimes.delete(runId);
|
|
23267
|
+
this.ttftMs.delete(runId);
|
|
23268
|
+
this.endSpan({
|
|
23269
|
+
runId,
|
|
23270
|
+
parentRunId,
|
|
23271
|
+
output,
|
|
23272
|
+
metrics,
|
|
23273
|
+
tags,
|
|
23274
|
+
metadata: {
|
|
23275
|
+
model: modelName2
|
|
23276
|
+
}
|
|
23277
|
+
});
|
|
23278
|
+
}
|
|
23279
|
+
async handleChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, runName) {
|
|
23280
|
+
this.startTimes.set(runId, Date.now());
|
|
23281
|
+
this.firstTokenTimes.delete(runId);
|
|
23282
|
+
this.ttftMs.delete(runId);
|
|
23283
|
+
this.startSpan({
|
|
23284
|
+
runId,
|
|
23285
|
+
parentRunId,
|
|
23286
|
+
name: runName ?? getSerializedName(llm) ?? "Chat Model",
|
|
23287
|
+
type: "llm",
|
|
23288
|
+
event: {
|
|
23289
|
+
input: messages,
|
|
23290
|
+
tags,
|
|
23291
|
+
metadata: {
|
|
23292
|
+
serialized: llm,
|
|
23293
|
+
name: runName,
|
|
23294
|
+
metadata,
|
|
23295
|
+
...extraParams
|
|
23296
|
+
}
|
|
23297
|
+
}
|
|
23298
|
+
});
|
|
23299
|
+
}
|
|
23300
|
+
async handleChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, runName) {
|
|
23301
|
+
if (tags?.includes("langsmith:hidden")) {
|
|
23302
|
+
this.skippedRuns.add(runId);
|
|
23303
|
+
return;
|
|
23304
|
+
}
|
|
23305
|
+
this.startSpan({
|
|
23306
|
+
runId,
|
|
23307
|
+
parentRunId,
|
|
23308
|
+
name: runName ?? getSerializedName(chain) ?? "Chain",
|
|
23309
|
+
event: {
|
|
23310
|
+
input: inputs,
|
|
23311
|
+
tags,
|
|
23312
|
+
metadata: {
|
|
23313
|
+
serialized: chain,
|
|
23314
|
+
name: runName,
|
|
23315
|
+
metadata,
|
|
23316
|
+
run_type: runType
|
|
23317
|
+
}
|
|
23318
|
+
}
|
|
23319
|
+
});
|
|
23320
|
+
}
|
|
23321
|
+
async handleChainError(err, runId, parentRunId, tags, kwargs) {
|
|
23322
|
+
this.endSpan({ runId, parentRunId, error: err, tags, metadata: kwargs });
|
|
23323
|
+
}
|
|
23324
|
+
async handleChainEnd(outputs, runId, parentRunId, tags, kwargs) {
|
|
23325
|
+
this.endSpan({
|
|
23326
|
+
runId,
|
|
23327
|
+
parentRunId,
|
|
23328
|
+
tags,
|
|
23329
|
+
output: outputs,
|
|
23330
|
+
metadata: { ...kwargs }
|
|
23331
|
+
});
|
|
23332
|
+
}
|
|
23333
|
+
async handleToolStart(tool, input, runId, parentRunId, tags, metadata, runName) {
|
|
23334
|
+
this.startSpan({
|
|
23335
|
+
runId,
|
|
23336
|
+
parentRunId,
|
|
23337
|
+
name: runName ?? getSerializedName(tool) ?? "Tool",
|
|
23338
|
+
type: "llm",
|
|
23339
|
+
event: {
|
|
23340
|
+
input: safeJsonParse(input),
|
|
23341
|
+
tags,
|
|
23342
|
+
metadata: {
|
|
23343
|
+
metadata,
|
|
23344
|
+
serialized: tool,
|
|
23345
|
+
input_str: input,
|
|
23346
|
+
input: safeJsonParse(input),
|
|
23347
|
+
name: runName
|
|
23348
|
+
}
|
|
23349
|
+
}
|
|
23350
|
+
});
|
|
23351
|
+
}
|
|
23352
|
+
async handleToolError(err, runId, parentRunId, tags) {
|
|
23353
|
+
this.endSpan({ runId, parentRunId, error: err, tags });
|
|
23354
|
+
}
|
|
23355
|
+
async handleToolEnd(output, runId, parentRunId, tags) {
|
|
23356
|
+
this.endSpan({ runId, parentRunId, output, tags });
|
|
23357
|
+
}
|
|
23358
|
+
async handleAgentAction(action, runId, parentRunId, tags) {
|
|
23359
|
+
this.startSpan({
|
|
23360
|
+
runId,
|
|
23361
|
+
parentRunId,
|
|
23362
|
+
type: "llm",
|
|
23363
|
+
name: typeof action.tool === "string" ? action.tool : "Agent",
|
|
23364
|
+
event: {
|
|
23365
|
+
input: action,
|
|
23366
|
+
tags
|
|
23367
|
+
}
|
|
23368
|
+
});
|
|
23369
|
+
}
|
|
23370
|
+
async handleAgentEnd(action, runId, parentRunId, tags) {
|
|
23371
|
+
this.endSpan({ runId, parentRunId, output: action, tags });
|
|
23372
|
+
}
|
|
23373
|
+
async handleRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name) {
|
|
23374
|
+
this.startSpan({
|
|
23375
|
+
runId,
|
|
23376
|
+
parentRunId,
|
|
23377
|
+
name: name ?? getSerializedName(retriever) ?? "Retriever",
|
|
23378
|
+
type: "function",
|
|
23379
|
+
event: {
|
|
23380
|
+
input: query,
|
|
23381
|
+
tags,
|
|
23382
|
+
metadata: {
|
|
23383
|
+
serialized: retriever,
|
|
23384
|
+
metadata,
|
|
23385
|
+
name
|
|
23386
|
+
}
|
|
23387
|
+
}
|
|
23388
|
+
});
|
|
23389
|
+
}
|
|
23390
|
+
async handleRetrieverEnd(documents, runId, parentRunId, tags) {
|
|
23391
|
+
this.endSpan({ runId, parentRunId, output: documents, tags });
|
|
23392
|
+
}
|
|
23393
|
+
async handleRetrieverError(err, runId, parentRunId, tags) {
|
|
23394
|
+
this.endSpan({ runId, parentRunId, error: err, tags });
|
|
23395
|
+
}
|
|
23396
|
+
async handleLLMNewToken(_token, _idx, runId, _parentRunId, _tags) {
|
|
23397
|
+
if (!this.firstTokenTimes.has(runId)) {
|
|
23398
|
+
const now2 = Date.now();
|
|
23399
|
+
this.firstTokenTimes.set(runId, now2);
|
|
23400
|
+
const start = this.startTimes.get(runId);
|
|
23401
|
+
if (start !== void 0) {
|
|
23402
|
+
this.ttftMs.set(runId, (now2 - start) / 1e3);
|
|
23403
|
+
}
|
|
23404
|
+
}
|
|
23405
|
+
}
|
|
23406
|
+
};
|
|
23407
|
+
function getSerializedName(serialized) {
|
|
23408
|
+
if (typeof serialized.name === "string") {
|
|
23409
|
+
return serialized.name;
|
|
23410
|
+
}
|
|
23411
|
+
const lastIdPart = serialized.id?.at(-1);
|
|
23412
|
+
return typeof lastIdPart === "string" ? lastIdPart : void 0;
|
|
23413
|
+
}
|
|
23414
|
+
function cleanObject(obj) {
|
|
23415
|
+
return Object.fromEntries(
|
|
23416
|
+
Object.entries(obj).filter(([, value]) => {
|
|
23417
|
+
if (typeof value !== "number") {
|
|
23418
|
+
return false;
|
|
23419
|
+
}
|
|
23420
|
+
return Number.isFinite(value);
|
|
23421
|
+
})
|
|
23422
|
+
);
|
|
23423
|
+
}
|
|
23424
|
+
function walkGenerations(response) {
|
|
23425
|
+
const result = [];
|
|
23426
|
+
const generations = response.generations || [];
|
|
23427
|
+
for (const batch of generations) {
|
|
23428
|
+
if (Array.isArray(batch)) {
|
|
23429
|
+
for (const generation of batch) {
|
|
23430
|
+
if (isRecord(generation)) {
|
|
23431
|
+
result.push(generation);
|
|
23432
|
+
}
|
|
23433
|
+
}
|
|
23434
|
+
} else if (isRecord(batch)) {
|
|
23435
|
+
result.push(batch);
|
|
23436
|
+
}
|
|
23437
|
+
}
|
|
23438
|
+
return result;
|
|
23439
|
+
}
|
|
23440
|
+
function getModelNameFromResponse(response) {
|
|
23441
|
+
for (const generation of walkGenerations(response)) {
|
|
23442
|
+
const message = generation.message;
|
|
23443
|
+
if (!isRecord(message)) {
|
|
23444
|
+
continue;
|
|
23445
|
+
}
|
|
23446
|
+
const responseMetadata = message.response_metadata;
|
|
23447
|
+
if (!isRecord(responseMetadata)) {
|
|
23448
|
+
continue;
|
|
23449
|
+
}
|
|
23450
|
+
const modelName3 = responseMetadata.model_name ?? responseMetadata.model;
|
|
23451
|
+
if (typeof modelName3 === "string") {
|
|
23452
|
+
return modelName3;
|
|
23453
|
+
}
|
|
23454
|
+
}
|
|
23455
|
+
const llmOutput = response.llmOutput || {};
|
|
23456
|
+
const modelName2 = llmOutput.model_name ?? llmOutput.model;
|
|
23457
|
+
return typeof modelName2 === "string" ? modelName2 : void 0;
|
|
23458
|
+
}
|
|
23459
|
+
function getMetricsFromResponse(response) {
|
|
23460
|
+
for (const generation of walkGenerations(response)) {
|
|
23461
|
+
const message = generation.message;
|
|
23462
|
+
if (!isRecord(message)) {
|
|
23463
|
+
continue;
|
|
23464
|
+
}
|
|
23465
|
+
const usageMetadata = message.usage_metadata;
|
|
23466
|
+
if (!isRecord(usageMetadata)) {
|
|
23467
|
+
continue;
|
|
23468
|
+
}
|
|
23469
|
+
const inputTokenDetails = usageMetadata.input_token_details;
|
|
23470
|
+
return cleanObject({
|
|
23471
|
+
total_tokens: usageMetadata.total_tokens,
|
|
23472
|
+
prompt_tokens: usageMetadata.input_tokens,
|
|
23473
|
+
completion_tokens: usageMetadata.output_tokens,
|
|
23474
|
+
prompt_cache_creation_tokens: isRecord(inputTokenDetails) ? inputTokenDetails.cache_creation : void 0,
|
|
23475
|
+
prompt_cached_tokens: isRecord(inputTokenDetails) ? inputTokenDetails.cache_read : void 0
|
|
23476
|
+
});
|
|
23477
|
+
}
|
|
23478
|
+
const llmOutput = response.llmOutput || {};
|
|
23479
|
+
const tokenUsage = isRecord(llmOutput.tokenUsage) ? llmOutput.tokenUsage : isRecord(llmOutput.estimatedTokens) ? llmOutput.estimatedTokens : {};
|
|
23480
|
+
return cleanObject({
|
|
23481
|
+
total_tokens: tokenUsage.totalTokens,
|
|
23482
|
+
prompt_tokens: tokenUsage.promptTokens,
|
|
23483
|
+
completion_tokens: tokenUsage.completionTokens
|
|
23484
|
+
});
|
|
23485
|
+
}
|
|
23486
|
+
function safeJsonParse(input) {
|
|
23487
|
+
try {
|
|
23488
|
+
return JSON.parse(input);
|
|
23489
|
+
} catch {
|
|
23490
|
+
return input;
|
|
23491
|
+
}
|
|
23492
|
+
}
|
|
23493
|
+
function isRecord(value) {
|
|
23494
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
23495
|
+
}
|
|
23496
|
+
|
|
23497
|
+
// src/instrumentation/plugins/langchain-channels.ts
|
|
23498
|
+
var langChainChannels = defineChannels("@langchain/core", {
|
|
23499
|
+
configure: channel({
|
|
23500
|
+
channelName: "CallbackManager.configure",
|
|
23501
|
+
kind: "sync-stream"
|
|
23502
|
+
}),
|
|
23503
|
+
configureSync: channel({
|
|
23504
|
+
channelName: "CallbackManager._configureSync",
|
|
23505
|
+
kind: "sync-stream"
|
|
23506
|
+
})
|
|
23507
|
+
});
|
|
23508
|
+
|
|
23509
|
+
// src/instrumentation/plugins/langchain-plugin.ts
|
|
23510
|
+
var LangChainPlugin = class extends BasePlugin {
|
|
23511
|
+
injectedManagers = /* @__PURE__ */ new WeakSet();
|
|
23512
|
+
onEnable() {
|
|
23513
|
+
this.subscribeToConfigure(langChainChannels.configure);
|
|
23514
|
+
this.subscribeToConfigure(langChainChannels.configureSync);
|
|
23515
|
+
}
|
|
23516
|
+
onDisable() {
|
|
23517
|
+
for (const unsubscribe of this.unsubscribers) {
|
|
23518
|
+
unsubscribe();
|
|
23519
|
+
}
|
|
23520
|
+
this.unsubscribers = [];
|
|
23521
|
+
this.injectedManagers = /* @__PURE__ */ new WeakSet();
|
|
23522
|
+
}
|
|
23523
|
+
subscribeToConfigure(channel2) {
|
|
23524
|
+
const tracingChannel = channel2.tracingChannel();
|
|
23525
|
+
const handlers = {
|
|
23526
|
+
start: (event) => {
|
|
23527
|
+
injectHandlerIntoArguments(event.arguments);
|
|
23528
|
+
},
|
|
23529
|
+
end: (event) => {
|
|
23530
|
+
this.injectHandler(event.result);
|
|
23531
|
+
}
|
|
23532
|
+
};
|
|
23533
|
+
tracingChannel.subscribe(handlers);
|
|
23534
|
+
this.unsubscribers.push(() => {
|
|
23535
|
+
tracingChannel.unsubscribe(handlers);
|
|
23536
|
+
});
|
|
23537
|
+
}
|
|
23538
|
+
injectHandler(result) {
|
|
23539
|
+
if (!isCallbackManager(result)) {
|
|
23540
|
+
return;
|
|
23541
|
+
}
|
|
23542
|
+
if (this.injectedManagers.has(result) || hasBraintrustHandler(result)) {
|
|
23543
|
+
return;
|
|
23544
|
+
}
|
|
23545
|
+
try {
|
|
23546
|
+
result.addHandler(new BraintrustLangChainCallbackHandler(), true);
|
|
23547
|
+
this.injectedManagers.add(result);
|
|
23548
|
+
} catch {
|
|
23549
|
+
}
|
|
23550
|
+
}
|
|
23551
|
+
};
|
|
23552
|
+
function isCallbackManager(value) {
|
|
23553
|
+
if (typeof value !== "object" || value === null) {
|
|
23554
|
+
return false;
|
|
23555
|
+
}
|
|
23556
|
+
const maybeManager = value;
|
|
23557
|
+
return typeof maybeManager.addHandler === "function";
|
|
23558
|
+
}
|
|
23559
|
+
function hasBraintrustHandler(manager) {
|
|
23560
|
+
return manager.handlers?.some((handler) => {
|
|
23561
|
+
if (typeof handler !== "object" || handler === null) {
|
|
23562
|
+
return false;
|
|
23563
|
+
}
|
|
23564
|
+
const name = Reflect.get(handler, "name");
|
|
23565
|
+
return name === BRAINTRUST_LANGCHAIN_CALLBACK_HANDLER_NAME;
|
|
23566
|
+
}) ?? false;
|
|
23567
|
+
}
|
|
23568
|
+
function injectHandlerIntoArguments(args) {
|
|
23569
|
+
if (!isWritableArgumentsObject(args)) {
|
|
23570
|
+
return;
|
|
23571
|
+
}
|
|
23572
|
+
const inheritedHandlers = Reflect.get(args, "0");
|
|
23573
|
+
const handler = new BraintrustLangChainCallbackHandler();
|
|
23574
|
+
if (inheritedHandlers === void 0 || inheritedHandlers === null) {
|
|
23575
|
+
Reflect.set(args, "0", [handler]);
|
|
23576
|
+
return;
|
|
23577
|
+
}
|
|
23578
|
+
if (Array.isArray(inheritedHandlers)) {
|
|
23579
|
+
if (!inheritedHandlers.some(isBraintrustHandler)) {
|
|
23580
|
+
inheritedHandlers.push(handler);
|
|
23581
|
+
}
|
|
23582
|
+
}
|
|
23583
|
+
}
|
|
23584
|
+
function isWritableArgumentsObject(args) {
|
|
23585
|
+
return typeof args === "object" && args !== null;
|
|
23586
|
+
}
|
|
23587
|
+
function isBraintrustHandler(handler) {
|
|
23588
|
+
if (typeof handler !== "object" || handler === null) {
|
|
23589
|
+
return false;
|
|
23590
|
+
}
|
|
23591
|
+
return Reflect.get(handler, "name") === BRAINTRUST_LANGCHAIN_CALLBACK_HANDLER_NAME;
|
|
23592
|
+
}
|
|
23593
|
+
|
|
23594
|
+
// src/instrumentation/braintrust-plugin.ts
|
|
23595
|
+
function getIntegrationConfig(integrations, key) {
|
|
23596
|
+
return integrations[key];
|
|
23597
|
+
}
|
|
23598
|
+
var BraintrustPlugin = class extends BasePlugin {
|
|
23599
|
+
config;
|
|
23600
|
+
openaiPlugin = null;
|
|
23601
|
+
openAICodexPlugin = null;
|
|
23602
|
+
anthropicPlugin = null;
|
|
23603
|
+
aiSDKPlugin = null;
|
|
23604
|
+
claudeAgentSDKPlugin = null;
|
|
23605
|
+
cursorSDKPlugin = null;
|
|
23606
|
+
openAIAgentsPlugin = null;
|
|
23607
|
+
googleGenAIPlugin = null;
|
|
23608
|
+
huggingFacePlugin = null;
|
|
23609
|
+
openRouterPlugin = null;
|
|
23610
|
+
openRouterAgentPlugin = null;
|
|
23611
|
+
mistralPlugin = null;
|
|
23612
|
+
googleADKPlugin = null;
|
|
23613
|
+
coherePlugin = null;
|
|
23614
|
+
groqPlugin = null;
|
|
23615
|
+
genkitPlugin = null;
|
|
23616
|
+
gitHubCopilotPlugin = null;
|
|
23617
|
+
fluePlugin = null;
|
|
23618
|
+
langChainPlugin = null;
|
|
23619
|
+
constructor(config = {}) {
|
|
23620
|
+
super();
|
|
23621
|
+
this.config = config;
|
|
23622
|
+
}
|
|
23623
|
+
onEnable() {
|
|
23624
|
+
const integrations = this.config.integrations || {};
|
|
23625
|
+
if (integrations.openai !== false) {
|
|
23626
|
+
this.openaiPlugin = new OpenAIPlugin();
|
|
23627
|
+
this.openaiPlugin.enable();
|
|
23628
|
+
}
|
|
23629
|
+
if (integrations.openaiCodexSDK !== false) {
|
|
23630
|
+
this.openAICodexPlugin = new OpenAICodexPlugin();
|
|
23631
|
+
this.openAICodexPlugin.enable();
|
|
23632
|
+
}
|
|
23633
|
+
if (integrations.anthropic !== false) {
|
|
23634
|
+
this.anthropicPlugin = new AnthropicPlugin();
|
|
23635
|
+
this.anthropicPlugin.enable();
|
|
23636
|
+
}
|
|
23637
|
+
if (integrations.aisdk !== false && integrations.vercel !== false) {
|
|
23638
|
+
this.aiSDKPlugin = new AISDKPlugin();
|
|
23639
|
+
this.aiSDKPlugin.enable();
|
|
23640
|
+
}
|
|
23641
|
+
if (integrations.claudeAgentSDK !== false) {
|
|
21420
23642
|
this.claudeAgentSDKPlugin = new ClaudeAgentSDKPlugin();
|
|
21421
23643
|
this.claudeAgentSDKPlugin.enable();
|
|
21422
23644
|
}
|
|
@@ -21424,6 +23646,10 @@ var BraintrustPlugin = class extends BasePlugin {
|
|
|
21424
23646
|
this.cursorSDKPlugin = new CursorSDKPlugin();
|
|
21425
23647
|
this.cursorSDKPlugin.enable();
|
|
21426
23648
|
}
|
|
23649
|
+
if (integrations.openAIAgents !== false) {
|
|
23650
|
+
this.openAIAgentsPlugin = new OpenAIAgentsPlugin();
|
|
23651
|
+
this.openAIAgentsPlugin.enable();
|
|
23652
|
+
}
|
|
21427
23653
|
if (integrations.googleGenAI !== false && integrations.google !== false) {
|
|
21428
23654
|
this.googleGenAIPlugin = new GoogleGenAIPlugin();
|
|
21429
23655
|
this.googleGenAIPlugin.enable();
|
|
@@ -21464,6 +23690,14 @@ var BraintrustPlugin = class extends BasePlugin {
|
|
|
21464
23690
|
this.gitHubCopilotPlugin = new GitHubCopilotPlugin();
|
|
21465
23691
|
this.gitHubCopilotPlugin.enable();
|
|
21466
23692
|
}
|
|
23693
|
+
if (getIntegrationConfig(integrations, "flue") !== false) {
|
|
23694
|
+
this.fluePlugin = new FluePlugin();
|
|
23695
|
+
this.fluePlugin.enable();
|
|
23696
|
+
}
|
|
23697
|
+
if (integrations.langchain !== false && integrations.langgraph !== false) {
|
|
23698
|
+
this.langChainPlugin = new LangChainPlugin();
|
|
23699
|
+
this.langChainPlugin.enable();
|
|
23700
|
+
}
|
|
21467
23701
|
}
|
|
21468
23702
|
onDisable() {
|
|
21469
23703
|
if (this.openaiPlugin) {
|
|
@@ -21490,6 +23724,10 @@ var BraintrustPlugin = class extends BasePlugin {
|
|
|
21490
23724
|
this.cursorSDKPlugin.disable();
|
|
21491
23725
|
this.cursorSDKPlugin = null;
|
|
21492
23726
|
}
|
|
23727
|
+
if (this.openAIAgentsPlugin) {
|
|
23728
|
+
this.openAIAgentsPlugin.disable();
|
|
23729
|
+
this.openAIAgentsPlugin = null;
|
|
23730
|
+
}
|
|
21493
23731
|
if (this.googleGenAIPlugin) {
|
|
21494
23732
|
this.googleGenAIPlugin.disable();
|
|
21495
23733
|
this.googleGenAIPlugin = null;
|
|
@@ -21530,9 +23768,104 @@ var BraintrustPlugin = class extends BasePlugin {
|
|
|
21530
23768
|
this.gitHubCopilotPlugin.disable();
|
|
21531
23769
|
this.gitHubCopilotPlugin = null;
|
|
21532
23770
|
}
|
|
23771
|
+
if (this.fluePlugin) {
|
|
23772
|
+
this.fluePlugin.disable();
|
|
23773
|
+
this.fluePlugin = null;
|
|
23774
|
+
}
|
|
23775
|
+
if (this.langChainPlugin) {
|
|
23776
|
+
this.langChainPlugin.disable();
|
|
23777
|
+
this.langChainPlugin = null;
|
|
23778
|
+
}
|
|
21533
23779
|
}
|
|
21534
23780
|
};
|
|
21535
23781
|
|
|
23782
|
+
// src/instrumentation/config.ts
|
|
23783
|
+
var envIntegrationAliases = {
|
|
23784
|
+
openai: "openai",
|
|
23785
|
+
"openai-codex": "openaiCodexSDK",
|
|
23786
|
+
"openai-codex-sdk": "openaiCodexSDK",
|
|
23787
|
+
openaicodexsdk: "openaiCodexSDK",
|
|
23788
|
+
codex: "openaiCodexSDK",
|
|
23789
|
+
"codex-sdk": "openaiCodexSDK",
|
|
23790
|
+
anthropic: "anthropic",
|
|
23791
|
+
aisdk: "aisdk",
|
|
23792
|
+
"ai-sdk": "aisdk",
|
|
23793
|
+
"vercel-ai": "aisdk",
|
|
23794
|
+
vercel: "vercel",
|
|
23795
|
+
claudeagentsdk: "claudeAgentSDK",
|
|
23796
|
+
"claude-agent-sdk": "claudeAgentSDK",
|
|
23797
|
+
cursor: "cursor",
|
|
23798
|
+
"cursor-sdk": "cursorSDK",
|
|
23799
|
+
cursorsdk: "cursorSDK",
|
|
23800
|
+
flue: "flue",
|
|
23801
|
+
"flue-runtime": "flue",
|
|
23802
|
+
"openai-agents": "openAIAgents",
|
|
23803
|
+
openaiagents: "openAIAgents",
|
|
23804
|
+
"openai-agents-core": "openAIAgents",
|
|
23805
|
+
openaiagentscore: "openAIAgents",
|
|
23806
|
+
google: "google",
|
|
23807
|
+
"google-genai": "googleGenAI",
|
|
23808
|
+
googlegenai: "googleGenAI",
|
|
23809
|
+
huggingface: "huggingface",
|
|
23810
|
+
openrouter: "openrouter",
|
|
23811
|
+
openrouteragent: "openrouterAgent",
|
|
23812
|
+
"openrouter-agent": "openrouterAgent",
|
|
23813
|
+
mistral: "mistral",
|
|
23814
|
+
googleadk: "googleADK",
|
|
23815
|
+
"google-adk": "googleADK",
|
|
23816
|
+
cohere: "cohere",
|
|
23817
|
+
groq: "groq",
|
|
23818
|
+
"groq-sdk": "groq",
|
|
23819
|
+
genkit: "genkit",
|
|
23820
|
+
"firebase-genkit": "genkit",
|
|
23821
|
+
githubcopilot: "gitHubCopilot",
|
|
23822
|
+
"github-copilot": "gitHubCopilot",
|
|
23823
|
+
"copilot-sdk": "gitHubCopilot",
|
|
23824
|
+
langchain: "langchain",
|
|
23825
|
+
"langchain-js": "langchain",
|
|
23826
|
+
"@langchain": "langchain",
|
|
23827
|
+
langgraph: "langgraph"
|
|
23828
|
+
};
|
|
23829
|
+
function getDefaultInstrumentationIntegrations() {
|
|
23830
|
+
return {
|
|
23831
|
+
openai: true,
|
|
23832
|
+
openaiCodexSDK: true,
|
|
23833
|
+
anthropic: true,
|
|
23834
|
+
vercel: true,
|
|
23835
|
+
aisdk: true,
|
|
23836
|
+
google: true,
|
|
23837
|
+
googleGenAI: true,
|
|
23838
|
+
googleADK: true,
|
|
23839
|
+
huggingface: true,
|
|
23840
|
+
claudeAgentSDK: true,
|
|
23841
|
+
cursor: true,
|
|
23842
|
+
cursorSDK: true,
|
|
23843
|
+
flue: true,
|
|
23844
|
+
openAIAgents: true,
|
|
23845
|
+
openrouter: true,
|
|
23846
|
+
openrouterAgent: true,
|
|
23847
|
+
mistral: true,
|
|
23848
|
+
cohere: true,
|
|
23849
|
+
groq: true,
|
|
23850
|
+
genkit: true,
|
|
23851
|
+
gitHubCopilot: true,
|
|
23852
|
+
langchain: true,
|
|
23853
|
+
langgraph: true
|
|
23854
|
+
};
|
|
23855
|
+
}
|
|
23856
|
+
function readDisabledInstrumentationEnvConfig(disabledList) {
|
|
23857
|
+
const integrations = {};
|
|
23858
|
+
if (disabledList) {
|
|
23859
|
+
for (const value of disabledList.split(",")) {
|
|
23860
|
+
const sdk = value.trim().toLowerCase();
|
|
23861
|
+
if (sdk.length > 0) {
|
|
23862
|
+
integrations[envIntegrationAliases[sdk] ?? sdk] = false;
|
|
23863
|
+
}
|
|
23864
|
+
}
|
|
23865
|
+
}
|
|
23866
|
+
return { integrations };
|
|
23867
|
+
}
|
|
23868
|
+
|
|
21536
23869
|
// src/instrumentation/registry.ts
|
|
21537
23870
|
var REGISTRY_STATE_KEY = /* @__PURE__ */ Symbol.for("braintrust.registry");
|
|
21538
23871
|
function getSharedState() {
|
|
@@ -21611,50 +23944,16 @@ var PluginRegistry = class {
|
|
|
21611
23944
|
* Get default configuration (all integrations enabled).
|
|
21612
23945
|
*/
|
|
21613
23946
|
getDefaultConfig() {
|
|
21614
|
-
return
|
|
21615
|
-
openai: true,
|
|
21616
|
-
openaiCodexSDK: true,
|
|
21617
|
-
anthropic: true,
|
|
21618
|
-
vercel: true,
|
|
21619
|
-
aisdk: true,
|
|
21620
|
-
google: true,
|
|
21621
|
-
googleGenAI: true,
|
|
21622
|
-
googleADK: true,
|
|
21623
|
-
huggingface: true,
|
|
21624
|
-
claudeAgentSDK: true,
|
|
21625
|
-
cursor: true,
|
|
21626
|
-
cursorSDK: true,
|
|
21627
|
-
openrouter: true,
|
|
21628
|
-
openrouterAgent: true,
|
|
21629
|
-
mistral: true,
|
|
21630
|
-
cohere: true,
|
|
21631
|
-
groq: true,
|
|
21632
|
-
genkit: true,
|
|
21633
|
-
gitHubCopilot: true
|
|
21634
|
-
};
|
|
23947
|
+
return getDefaultInstrumentationIntegrations();
|
|
21635
23948
|
}
|
|
21636
23949
|
/**
|
|
21637
23950
|
* Read configuration from environment variables.
|
|
21638
23951
|
* Supports: BRAINTRUST_DISABLE_INSTRUMENTATION=openai,anthropic,...
|
|
21639
23952
|
*/
|
|
21640
23953
|
readEnvConfig() {
|
|
21641
|
-
|
|
21642
|
-
|
|
21643
|
-
|
|
21644
|
-
const disabled = disabledList.split(",").map((s) => s.trim().toLowerCase()).filter((s) => s.length > 0);
|
|
21645
|
-
for (const sdk of disabled) {
|
|
21646
|
-
if (sdk === "cursor-sdk") {
|
|
21647
|
-
integrations.cursorSDK = false;
|
|
21648
|
-
} else if (sdk === "githubcopilot" || sdk === "github-copilot" || sdk === "copilot-sdk") {
|
|
21649
|
-
integrations.gitHubCopilot = false;
|
|
21650
|
-
} else if (sdk === "openai-codex-sdk") {
|
|
21651
|
-
integrations.openaiCodexSDK = false;
|
|
21652
|
-
} else {
|
|
21653
|
-
integrations[sdk] = false;
|
|
21654
|
-
}
|
|
21655
|
-
}
|
|
21656
|
-
}
|
|
21657
|
-
return { integrations };
|
|
23954
|
+
return readDisabledInstrumentationEnvConfig(
|
|
23955
|
+
isomorph_default.getEnv("BRAINTRUST_DISABLE_INSTRUMENTATION")
|
|
23956
|
+
);
|
|
21658
23957
|
}
|
|
21659
23958
|
};
|
|
21660
23959
|
var registry = new PluginRegistry();
|
|
@@ -21665,6 +23964,7 @@ function configureInstrumentation(config) {
|
|
|
21665
23964
|
0 && (module.exports = {
|
|
21666
23965
|
BasePlugin,
|
|
21667
23966
|
BraintrustPlugin,
|
|
23967
|
+
OpenAIAgentsTraceProcessor,
|
|
21668
23968
|
configureInstrumentation,
|
|
21669
23969
|
createChannelName,
|
|
21670
23970
|
isValidChannelName,
|