netra-sdk 1.5.0 → 1.7.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/dist/index.cjs +1093 -514
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +258 -95
- package/dist/index.d.ts +258 -95
- package/dist/index.js +1085 -508
- package/dist/index.js.map +1 -1
- package/package.json +8 -8
package/dist/index.js
CHANGED
|
@@ -2,6 +2,7 @@ import { __toESM, require_decamelize, require_camelcase, init_esm_node, __public
|
|
|
2
2
|
import { createContextKey, propagation, trace, context, SpanKind, SpanStatusCode, ROOT_CONTEXT } from '@opentelemetry/api';
|
|
3
3
|
import { createRequire } from 'module';
|
|
4
4
|
import { AsyncLocalStorage } from 'async_hooks';
|
|
5
|
+
import { jsonrepair } from 'jsonrepair';
|
|
5
6
|
import { ConsoleSpanExporter } from '@opentelemetry/sdk-trace-base';
|
|
6
7
|
import { initialize } from '@traceloop/node-server-sdk';
|
|
7
8
|
import shimmer from 'shimmer';
|
|
@@ -9,7 +10,7 @@ import { CompositePropagator, W3CTraceContextPropagator, W3CBaggagePropagator, E
|
|
|
9
10
|
import * as http from 'http';
|
|
10
11
|
import * as https from 'https';
|
|
11
12
|
import { JsonTraceSerializer } from '@opentelemetry/otlp-transformer';
|
|
12
|
-
import
|
|
13
|
+
import pLimit2 from 'p-limit';
|
|
13
14
|
import axios from 'axios';
|
|
14
15
|
|
|
15
16
|
// src/logger.ts
|
|
@@ -464,8 +465,8 @@ var Usage = class {
|
|
|
464
465
|
if (!page) {
|
|
465
466
|
break;
|
|
466
467
|
}
|
|
467
|
-
for (const
|
|
468
|
-
yield
|
|
468
|
+
for (const trace24 of page.traces) {
|
|
469
|
+
yield trace24;
|
|
469
470
|
}
|
|
470
471
|
if (!page.hasNextPage || !page.nextCursor) {
|
|
471
472
|
break;
|
|
@@ -578,7 +579,7 @@ var Usage = class {
|
|
|
578
579
|
};
|
|
579
580
|
|
|
580
581
|
// src/version.ts
|
|
581
|
-
var SDK_VERSION = "1.
|
|
582
|
+
var SDK_VERSION = "1.6.0";
|
|
582
583
|
|
|
583
584
|
// src/config.ts
|
|
584
585
|
var NetraInstruments = /* @__PURE__ */ ((NetraInstruments2) => {
|
|
@@ -634,7 +635,20 @@ var DEFAULT_INSTRUMENTS = /* @__PURE__ */ new Set([
|
|
|
634
635
|
// Web Frameworks
|
|
635
636
|
"express" /* EXPRESS */
|
|
636
637
|
]);
|
|
637
|
-
var
|
|
638
|
+
var _Config = class _Config {
|
|
639
|
+
/**
|
|
640
|
+
* Lazily reads NETRA_SPAN_ATTRIBUTE_MAX_SIZE from process.env on first
|
|
641
|
+
* access so that env vars set before Netra.init() (via dotenv, shell
|
|
642
|
+
* export, Docker, etc.) are always respected regardless of import order.
|
|
643
|
+
*/
|
|
644
|
+
static get SPAN_ATTRIBUTE_MAX_SIZE() {
|
|
645
|
+
if (_Config._spanAttributeMaxSize === void 0) {
|
|
646
|
+
_Config._spanAttributeMaxSize = parseInt(
|
|
647
|
+
process.env.NETRA_SPAN_ATTRIBUTE_MAX_SIZE || "30000"
|
|
648
|
+
);
|
|
649
|
+
}
|
|
650
|
+
return _Config._spanAttributeMaxSize;
|
|
651
|
+
}
|
|
638
652
|
constructor(config = {}) {
|
|
639
653
|
this.appName = this._getAppName(config.appName);
|
|
640
654
|
this.otlpEndpoint = this._getOtlpEndpoint();
|
|
@@ -805,20 +819,11 @@ var Config = class {
|
|
|
805
819
|
process.env.OTEL_RESOURCE_ATTRIBUTES = Object.entries(attrs).map(([k, v]) => `${encodeAttrValue(k)}=${encodeAttrValue(v)}`).join(",");
|
|
806
820
|
}
|
|
807
821
|
};
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
Config.ATTRIBUTE_MAX_LEN = parseInt(
|
|
814
|
-
process.env.NETRA_ATTRIBUTE_MAX_LEN || "50000"
|
|
815
|
-
);
|
|
816
|
-
Config.CONVERSATION_MAX_LEN = parseInt(
|
|
817
|
-
process.env.NETRA_CONVERSATION_CONTENT_MAX_LEN || "50000"
|
|
818
|
-
);
|
|
819
|
-
Config.SPAN_ATTRIBUTE_MAX_SIZE = parseInt(
|
|
820
|
-
process.env.NETRA_SPAN_ATTRIBUTE_MAX_SIZE || "30000"
|
|
821
|
-
);
|
|
822
|
+
_Config.SDK_NAME = "netra";
|
|
823
|
+
_Config.LIBRARY_NAME = "netra";
|
|
824
|
+
_Config.LIBRARY_VERSION = SDK_VERSION;
|
|
825
|
+
_Config.TRIAL_BLOCK_DURATION_SECONDS = 900;
|
|
826
|
+
var Config = _Config;
|
|
822
827
|
|
|
823
828
|
// src/utils/pattern-matching.ts
|
|
824
829
|
function compilePatterns(patterns) {
|
|
@@ -1080,27 +1085,26 @@ var ConversationType = /* @__PURE__ */ ((ConversationType3) => {
|
|
|
1080
1085
|
return ConversationType3;
|
|
1081
1086
|
})(ConversationType || {});
|
|
1082
1087
|
|
|
1083
|
-
// src/utils/serialization.ts
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
if (s.length <= maxLength) return s;
|
|
1087
|
-
if (maxLength <= ELLIPSIS.length) return s.slice(0, maxLength);
|
|
1088
|
-
return s.slice(0, maxLength - ELLIPSIS.length) + ELLIPSIS;
|
|
1089
|
-
}
|
|
1090
|
-
function safeStringify(value, maxLength) {
|
|
1088
|
+
// src/utils/serialization/safe-stringify.ts
|
|
1089
|
+
function safeStringify(value, options) {
|
|
1090
|
+
const maxLength = options?.maxLength;
|
|
1091
1091
|
if (typeof value === "string") {
|
|
1092
1092
|
if (maxLength && value.length > maxLength) {
|
|
1093
|
-
return
|
|
1093
|
+
return value.slice(0, maxLength);
|
|
1094
1094
|
}
|
|
1095
1095
|
return value;
|
|
1096
1096
|
}
|
|
1097
|
+
if (value === null) return "null";
|
|
1098
|
+
if (value === void 0) return "undefined";
|
|
1099
|
+
const t = typeof value;
|
|
1100
|
+
if (t === "number" || t === "boolean") return String(value);
|
|
1101
|
+
if (t === "bigint") return value.toString();
|
|
1102
|
+
if (t === "symbol") return value.toString();
|
|
1103
|
+
if (t === "function") return `[Function: ${value.name || "anonymous"}]`;
|
|
1097
1104
|
const seen = /* @__PURE__ */ new WeakSet();
|
|
1098
1105
|
let result;
|
|
1099
1106
|
try {
|
|
1100
1107
|
result = JSON.stringify(value, (_key, val) => {
|
|
1101
|
-
if (typeof val === "string" && maxLength && val.length > maxLength) {
|
|
1102
|
-
return truncate(val, maxLength);
|
|
1103
|
-
}
|
|
1104
1108
|
if (typeof val === "function")
|
|
1105
1109
|
return `[Function: ${val.name || "anonymous"}]`;
|
|
1106
1110
|
if (typeof val === "symbol") return val.toString();
|
|
@@ -1114,25 +1118,148 @@ function safeStringify(value, maxLength) {
|
|
|
1114
1118
|
}
|
|
1115
1119
|
}
|
|
1116
1120
|
return val;
|
|
1117
|
-
}) ??
|
|
1121
|
+
}) ?? "null";
|
|
1118
1122
|
} catch {
|
|
1119
|
-
|
|
1123
|
+
const name = value?.constructor?.name;
|
|
1124
|
+
result = name ? `[Unserializable: ${name}]` : "[Unserializable]";
|
|
1120
1125
|
}
|
|
1121
1126
|
if (maxLength && result.length > maxLength) {
|
|
1122
|
-
return
|
|
1127
|
+
return result.slice(0, maxLength);
|
|
1123
1128
|
}
|
|
1124
1129
|
return result;
|
|
1125
1130
|
}
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1131
|
+
var TRUNCATION_SUFFIX = "...[TRUNCATED]";
|
|
1132
|
+
var MINIMAL_TRUNCATED_OBJECT = '{"__truncated__":true}';
|
|
1133
|
+
var MINIMAL_TRUNCATED_ARRAY = '[{"__truncated__":true}]';
|
|
1134
|
+
var MIN_JSON_TRUNCATION_LENGTH = MINIMAL_TRUNCATED_ARRAY.length;
|
|
1135
|
+
var RETRY_RATIOS = [0.7, 0.5, 0.3];
|
|
1136
|
+
var DEFAULT_CONFIG = {
|
|
1137
|
+
maxAttributeSize: 3e4
|
|
1138
|
+
};
|
|
1139
|
+
function isJsonLike(str) {
|
|
1140
|
+
const trimmed = str.trimStart();
|
|
1141
|
+
return trimmed.startsWith("{") || trimmed.startsWith("[");
|
|
1142
|
+
}
|
|
1143
|
+
function minimalTruncatedJson(json) {
|
|
1144
|
+
return json.trimStart().startsWith("[") ? MINIMAL_TRUNCATED_ARRAY : MINIMAL_TRUNCATED_OBJECT;
|
|
1145
|
+
}
|
|
1146
|
+
function injectTruncationMarker(parsed) {
|
|
1147
|
+
if (Array.isArray(parsed)) {
|
|
1148
|
+
parsed.push({ __truncated__: true });
|
|
1149
|
+
} else if (typeof parsed === "object" && parsed !== null) {
|
|
1150
|
+
parsed.__truncated__ = true;
|
|
1151
|
+
}
|
|
1152
|
+
}
|
|
1153
|
+
function tryRepairAndFit(json, cutLen, budget) {
|
|
1154
|
+
if (cutLen <= 0) return null;
|
|
1155
|
+
try {
|
|
1156
|
+
const repaired = jsonrepair(json.slice(0, cutLen));
|
|
1157
|
+
const parsed = JSON.parse(repaired);
|
|
1158
|
+
injectTruncationMarker(parsed);
|
|
1159
|
+
const result = JSON.stringify(parsed);
|
|
1160
|
+
if (result.length <= budget) return result;
|
|
1161
|
+
} catch {
|
|
1162
|
+
Logger.debug("Failed to repair and fit JSON at cut length", {
|
|
1163
|
+
length: json.length,
|
|
1164
|
+
cutLength: cutLen
|
|
1165
|
+
});
|
|
1166
|
+
}
|
|
1167
|
+
return null;
|
|
1168
|
+
}
|
|
1169
|
+
function truncateJsonValue(json, budget) {
|
|
1170
|
+
const minimal = minimalTruncatedJson(json);
|
|
1171
|
+
if (budget < minimal.length) {
|
|
1172
|
+
return truncatePlainString(json, budget);
|
|
1173
|
+
}
|
|
1174
|
+
const overhead = Math.max(30, Math.ceil(budget * 0.05));
|
|
1175
|
+
const initialCut = budget - overhead;
|
|
1176
|
+
const candidateLengths = [
|
|
1177
|
+
initialCut,
|
|
1178
|
+
...RETRY_RATIOS.map((ratio) => Math.floor(initialCut * ratio))
|
|
1179
|
+
];
|
|
1180
|
+
for (const cutLen of candidateLengths) {
|
|
1181
|
+
const result = tryRepairAndFit(json, cutLen, budget);
|
|
1182
|
+
if (result !== null) return result;
|
|
1183
|
+
}
|
|
1184
|
+
let lo = 1;
|
|
1185
|
+
let hi = Math.max(1, Math.floor(initialCut * 0.1));
|
|
1186
|
+
let bestResult = null;
|
|
1187
|
+
while (lo <= hi) {
|
|
1188
|
+
const mid = Math.floor((lo + hi) / 2);
|
|
1189
|
+
const result = tryRepairAndFit(json, mid, budget);
|
|
1190
|
+
if (result !== null) {
|
|
1191
|
+
bestResult = result;
|
|
1192
|
+
lo = mid + 1;
|
|
1193
|
+
} else {
|
|
1194
|
+
hi = mid - 1;
|
|
1195
|
+
}
|
|
1196
|
+
}
|
|
1197
|
+
if (bestResult !== null) return bestResult;
|
|
1198
|
+
return minimal;
|
|
1199
|
+
}
|
|
1200
|
+
function truncatePlainString(str, maxLen) {
|
|
1201
|
+
if (maxLen <= TRUNCATION_SUFFIX.length) {
|
|
1202
|
+
return str.slice(0, maxLen);
|
|
1203
|
+
}
|
|
1204
|
+
return str.slice(0, maxLen - TRUNCATION_SUFFIX.length) + TRUNCATION_SUFFIX;
|
|
1205
|
+
}
|
|
1206
|
+
function truncateString(value, budget) {
|
|
1207
|
+
if (value.length <= budget) return value;
|
|
1208
|
+
if (isJsonLike(value) && budget >= MIN_JSON_TRUNCATION_LENGTH) {
|
|
1209
|
+
return truncateJsonValue(value, budget);
|
|
1210
|
+
}
|
|
1211
|
+
return truncatePlainString(value, budget);
|
|
1212
|
+
}
|
|
1213
|
+
function serializeAttribute(value, maxSize) {
|
|
1214
|
+
if (typeof value === "number" || typeof value === "boolean") {
|
|
1215
|
+
return value;
|
|
1216
|
+
}
|
|
1217
|
+
if (typeof value === "string") {
|
|
1218
|
+
return truncateString(value, maxSize);
|
|
1219
|
+
}
|
|
1220
|
+
if (Array.isArray(value)) {
|
|
1221
|
+
if (value.every((v) => v == null || typeof v === "number")) {
|
|
1222
|
+
const serializedLen = estimateArraySize(value);
|
|
1223
|
+
if (serializedLen <= maxSize) {
|
|
1224
|
+
return value;
|
|
1225
|
+
}
|
|
1226
|
+
} else if (value.every((v) => v == null || typeof v === "boolean")) {
|
|
1227
|
+
const serializedLen = estimateArraySize(value);
|
|
1228
|
+
if (serializedLen <= maxSize) {
|
|
1229
|
+
return value;
|
|
1230
|
+
}
|
|
1231
|
+
} else if (value.every((v) => v == null || typeof v === "string")) {
|
|
1232
|
+
const serializedLen = value.reduce(
|
|
1233
|
+
(sum, s) => sum + (s == null ? 4 : s.length + 2),
|
|
1234
|
+
2 + Math.max(0, value.length - 1)
|
|
1235
|
+
);
|
|
1236
|
+
if (serializedLen <= maxSize) {
|
|
1237
|
+
return value;
|
|
1238
|
+
}
|
|
1239
|
+
}
|
|
1240
|
+
}
|
|
1241
|
+
const serialized = safeStringify(value);
|
|
1242
|
+
return truncateString(serialized, maxSize);
|
|
1243
|
+
}
|
|
1244
|
+
function estimateArraySize(arr) {
|
|
1245
|
+
let size = 2;
|
|
1246
|
+
for (let i = 0; i < arr.length; i++) {
|
|
1247
|
+
if (i > 0) size += 1;
|
|
1248
|
+
const v = arr[i];
|
|
1249
|
+
if (v == null) size += 4;
|
|
1250
|
+
else size += String(v).length;
|
|
1133
1251
|
}
|
|
1134
|
-
return
|
|
1252
|
+
return size;
|
|
1135
1253
|
}
|
|
1254
|
+
var TruncatingSerializer = class {
|
|
1255
|
+
constructor(config) {
|
|
1256
|
+
const merged = { ...DEFAULT_CONFIG, ...config };
|
|
1257
|
+
this.maxAttributeSize = merged.maxAttributeSize;
|
|
1258
|
+
}
|
|
1259
|
+
serializeAttribute(value, budget) {
|
|
1260
|
+
return serializeAttribute(value, budget ?? this.maxAttributeSize);
|
|
1261
|
+
}
|
|
1262
|
+
};
|
|
1136
1263
|
|
|
1137
1264
|
// src/session-manager.ts
|
|
1138
1265
|
var MODULE_NAME = "netra.session-manager";
|
|
@@ -1246,7 +1373,7 @@ var SessionManager = class _SessionManager {
|
|
|
1246
1373
|
try {
|
|
1247
1374
|
const span2 = trace.getActiveSpan();
|
|
1248
1375
|
if (span2?.isRecording()) {
|
|
1249
|
-
span2.setAttribute(key, typeof value === "string" ? value :
|
|
1376
|
+
span2.setAttribute(key, typeof value === "string" ? value : safeStringify(value));
|
|
1250
1377
|
} else {
|
|
1251
1378
|
Logger.warn(`setAttributeOnActiveSpan: no recording span for key '${key}'`);
|
|
1252
1379
|
}
|
|
@@ -1263,7 +1390,7 @@ var SessionManager = class _SessionManager {
|
|
|
1263
1390
|
try {
|
|
1264
1391
|
_SessionManager.setAttributeOnActiveSpan(
|
|
1265
1392
|
"netra.user.input",
|
|
1266
|
-
|
|
1393
|
+
safeStringify(value)
|
|
1267
1394
|
);
|
|
1268
1395
|
} catch (e) {
|
|
1269
1396
|
Logger.error("setInput failed:", e);
|
|
@@ -1278,7 +1405,7 @@ var SessionManager = class _SessionManager {
|
|
|
1278
1405
|
try {
|
|
1279
1406
|
_SessionManager.setAttributeOnActiveSpan(
|
|
1280
1407
|
"netra.user.output",
|
|
1281
|
-
|
|
1408
|
+
safeStringify(value)
|
|
1282
1409
|
);
|
|
1283
1410
|
} catch (e) {
|
|
1284
1411
|
Logger.error("setOutput failed:", e);
|
|
@@ -1293,7 +1420,7 @@ var SessionManager = class _SessionManager {
|
|
|
1293
1420
|
try {
|
|
1294
1421
|
RootSpanProcessor.setAttributeOnRootSpan(
|
|
1295
1422
|
"netra.root.input",
|
|
1296
|
-
|
|
1423
|
+
safeStringify(value)
|
|
1297
1424
|
);
|
|
1298
1425
|
} catch (e) {
|
|
1299
1426
|
Logger.error("setRootInput failed:", e);
|
|
@@ -1308,7 +1435,7 @@ var SessionManager = class _SessionManager {
|
|
|
1308
1435
|
try {
|
|
1309
1436
|
RootSpanProcessor.setAttributeOnRootSpan(
|
|
1310
1437
|
"netra.root.output",
|
|
1311
|
-
|
|
1438
|
+
safeStringify(value)
|
|
1312
1439
|
);
|
|
1313
1440
|
} catch (e) {
|
|
1314
1441
|
Logger.error("setRootOutput failed:", e);
|
|
@@ -1341,8 +1468,8 @@ var SessionManager = class _SessionManager {
|
|
|
1341
1468
|
*
|
|
1342
1469
|
* Reads and re-serialises the existing JSON array so entries accumulate
|
|
1343
1470
|
* rather than overwrite — matching the Python SDK's behaviour.
|
|
1344
|
-
*
|
|
1345
|
-
*
|
|
1471
|
+
* Uses span.setAttribute so the value flows through the processor pipeline
|
|
1472
|
+
* including the SerializationSpanProcessor for proper truncation.
|
|
1346
1473
|
*/
|
|
1347
1474
|
static addConversation(conversationType, role, content) {
|
|
1348
1475
|
if (!role || !content) {
|
|
@@ -1357,29 +1484,26 @@ var SessionManager = class _SessionManager {
|
|
|
1357
1484
|
}
|
|
1358
1485
|
let existing = [];
|
|
1359
1486
|
try {
|
|
1360
|
-
const raw = span2.
|
|
1487
|
+
const raw = span2.attributes?.["conversation"];
|
|
1361
1488
|
if (typeof raw === "string") {
|
|
1362
1489
|
const parsed = JSON.parse(raw);
|
|
1363
|
-
if (Array.isArray(parsed))
|
|
1490
|
+
if (Array.isArray(parsed)) {
|
|
1491
|
+
existing = parsed.filter(
|
|
1492
|
+
(entry) => !(entry && typeof entry === "object" && entry.__truncated__ === true && Object.keys(entry).length === 1)
|
|
1493
|
+
);
|
|
1494
|
+
}
|
|
1364
1495
|
}
|
|
1365
1496
|
} catch (e) {
|
|
1366
1497
|
Logger.warn("addConversation: failed to parse existing conversation, starting fresh:", e);
|
|
1367
1498
|
}
|
|
1368
|
-
const maxLen = Config.CONVERSATION_MAX_LEN;
|
|
1369
|
-
const processedContent = typeof content === "string" ? content.substring(0, maxLen) : content;
|
|
1370
1499
|
existing.push({
|
|
1371
1500
|
type: conversationType,
|
|
1372
1501
|
role,
|
|
1373
|
-
content
|
|
1374
|
-
format: typeof
|
|
1502
|
+
content,
|
|
1503
|
+
format: typeof content === "string" ? "text" : "json"
|
|
1375
1504
|
});
|
|
1376
1505
|
const payload = JSON.stringify(existing);
|
|
1377
|
-
|
|
1378
|
-
if (internalAttrs && typeof internalAttrs === "object") {
|
|
1379
|
-
internalAttrs["conversation"] = payload;
|
|
1380
|
-
} else {
|
|
1381
|
-
span2.setAttribute("conversation", payload);
|
|
1382
|
-
}
|
|
1506
|
+
span2.setAttribute("conversation", payload);
|
|
1383
1507
|
} catch (e) {
|
|
1384
1508
|
Logger.error("addConversation failed:", e);
|
|
1385
1509
|
}
|
|
@@ -2876,58 +3000,6 @@ var Prompts = class {
|
|
|
2876
3000
|
}
|
|
2877
3001
|
};
|
|
2878
3002
|
|
|
2879
|
-
// src/processors/attribute-size-limit-processor.ts
|
|
2880
|
-
var DEFAULT_MAX_ATTRIBUTE_SIZE = 32e3;
|
|
2881
|
-
var AttributeSizeLimitProcessor = class {
|
|
2882
|
-
constructor(maxAttributeSize) {
|
|
2883
|
-
this.maxAttributeSize = maxAttributeSize ?? DEFAULT_MAX_ATTRIBUTE_SIZE;
|
|
2884
|
-
}
|
|
2885
|
-
onStart(span2, _parentContext) {
|
|
2886
|
-
try {
|
|
2887
|
-
this._wrapSetAttribute(span2);
|
|
2888
|
-
} catch (e) {
|
|
2889
|
-
Logger.debug("AttributeSizeLimitProcessor.onStart error:", e);
|
|
2890
|
-
}
|
|
2891
|
-
}
|
|
2892
|
-
onEnd(_span) {
|
|
2893
|
-
}
|
|
2894
|
-
shutdown() {
|
|
2895
|
-
return Promise.resolve();
|
|
2896
|
-
}
|
|
2897
|
-
forceFlush() {
|
|
2898
|
-
return Promise.resolve();
|
|
2899
|
-
}
|
|
2900
|
-
_wrapSetAttribute(span2) {
|
|
2901
|
-
const original = span2.setAttribute.bind(span2);
|
|
2902
|
-
const maxLen = this.maxAttributeSize;
|
|
2903
|
-
const patched = (key, value) => {
|
|
2904
|
-
try {
|
|
2905
|
-
return original(key, truncateValue(value, maxLen));
|
|
2906
|
-
} catch {
|
|
2907
|
-
try {
|
|
2908
|
-
return original(key, value);
|
|
2909
|
-
} catch {
|
|
2910
|
-
return span2;
|
|
2911
|
-
}
|
|
2912
|
-
}
|
|
2913
|
-
};
|
|
2914
|
-
span2.setAttribute = patched;
|
|
2915
|
-
}
|
|
2916
|
-
};
|
|
2917
|
-
function truncateValue(value, maxLen) {
|
|
2918
|
-
if (typeof value === "string") {
|
|
2919
|
-
return value.length > maxLen ? value.substring(0, maxLen) : value;
|
|
2920
|
-
}
|
|
2921
|
-
if (Array.isArray(value)) {
|
|
2922
|
-
const serialized = JSON.stringify(value);
|
|
2923
|
-
if (serialized.length > maxLen) {
|
|
2924
|
-
return serialized.substring(0, maxLen);
|
|
2925
|
-
}
|
|
2926
|
-
return value;
|
|
2927
|
-
}
|
|
2928
|
-
return value;
|
|
2929
|
-
}
|
|
2930
|
-
|
|
2931
3003
|
// src/processors/instrumentation-span-processor.ts
|
|
2932
3004
|
var ALLOWED_INSTRUMENTATION_NAMES = /* @__PURE__ */ new Set([
|
|
2933
3005
|
"openai",
|
|
@@ -2961,12 +3033,6 @@ var ALLOWED_INSTRUMENTATION_NAMES = /* @__PURE__ */ new Set([
|
|
|
2961
3033
|
"elevenlabs"
|
|
2962
3034
|
]);
|
|
2963
3035
|
var InstrumentationSpanProcessor = class {
|
|
2964
|
-
constructor(maxAttributeLength) {
|
|
2965
|
-
this.maxAttributeLength = maxAttributeLength ?? Config.ATTRIBUTE_MAX_LEN;
|
|
2966
|
-
}
|
|
2967
|
-
/**
|
|
2968
|
-
* Detect the raw instrumentation name from the span's instrumentation scope.
|
|
2969
|
-
*/
|
|
2970
3036
|
detectRawInstrumentationName(span2) {
|
|
2971
3037
|
try {
|
|
2972
3038
|
const spanAny = span2;
|
|
@@ -2982,60 +3048,19 @@ var InstrumentationSpanProcessor = class {
|
|
|
2982
3048
|
return base;
|
|
2983
3049
|
}
|
|
2984
3050
|
} catch {
|
|
3051
|
+
Logger.debug("InstrumentationSpanProcessor: Error extracting base name:", name);
|
|
2985
3052
|
}
|
|
2986
3053
|
}
|
|
2987
3054
|
return name;
|
|
2988
3055
|
}
|
|
2989
3056
|
}
|
|
2990
3057
|
} catch {
|
|
3058
|
+
Logger.debug("InstrumentationSpanProcessor: Error detecting instrumentation name");
|
|
2991
3059
|
}
|
|
2992
3060
|
return null;
|
|
2993
3061
|
}
|
|
2994
|
-
|
|
2995
|
-
* Truncate a value to the maximum allowed length.
|
|
2996
|
-
* Handles strings, bytes, and recursively handles lists and objects.
|
|
2997
|
-
*/
|
|
2998
|
-
truncateValue(value) {
|
|
2999
|
-
try {
|
|
3000
|
-
if (typeof value === "string") {
|
|
3001
|
-
return value.length <= this.maxAttributeLength ? value : value.substring(0, this.maxAttributeLength);
|
|
3002
|
-
}
|
|
3003
|
-
if (Array.isArray(value)) {
|
|
3004
|
-
return value.map(
|
|
3005
|
-
(v) => typeof v === "string" ? this.truncateValue(v) : v
|
|
3006
|
-
);
|
|
3007
|
-
}
|
|
3008
|
-
if (typeof value === "object" && value !== null) {
|
|
3009
|
-
const result = {};
|
|
3010
|
-
for (const [k, v] of Object.entries(value)) {
|
|
3011
|
-
result[k] = typeof v === "string" ? this.truncateValue(v) : v;
|
|
3012
|
-
}
|
|
3013
|
-
return result;
|
|
3014
|
-
}
|
|
3015
|
-
} catch {
|
|
3016
|
-
return value;
|
|
3017
|
-
}
|
|
3018
|
-
return value;
|
|
3019
|
-
}
|
|
3020
|
-
/**
|
|
3021
|
-
* Called when a span starts. Wraps setAttribute to truncate values
|
|
3022
|
-
* and records the instrumentation name.
|
|
3023
|
-
*/
|
|
3024
|
-
onStart(span2, parentContext) {
|
|
3062
|
+
onStart(span2, _parentContext) {
|
|
3025
3063
|
try {
|
|
3026
|
-
const originalSetAttribute = span2.setAttribute.bind(span2);
|
|
3027
|
-
span2.setAttribute = (key, value) => {
|
|
3028
|
-
try {
|
|
3029
|
-
const truncated = this.truncateValue(value);
|
|
3030
|
-
return originalSetAttribute(key, truncated);
|
|
3031
|
-
} catch {
|
|
3032
|
-
try {
|
|
3033
|
-
return originalSetAttribute(key, value);
|
|
3034
|
-
} catch {
|
|
3035
|
-
return span2;
|
|
3036
|
-
}
|
|
3037
|
-
}
|
|
3038
|
-
};
|
|
3039
3064
|
const name = this.detectRawInstrumentationName(span2);
|
|
3040
3065
|
if (name && ALLOWED_INSTRUMENTATION_NAMES.has(name.toLowerCase())) {
|
|
3041
3066
|
span2.setAttribute(`${Config.LIBRARY_NAME}.instrumentation.name`, name);
|
|
@@ -3047,20 +3072,11 @@ var InstrumentationSpanProcessor = class {
|
|
|
3047
3072
|
);
|
|
3048
3073
|
}
|
|
3049
3074
|
}
|
|
3050
|
-
|
|
3051
|
-
* Called when a span ends. No-op for this processor.
|
|
3052
|
-
*/
|
|
3053
|
-
onEnd(span2) {
|
|
3075
|
+
onEnd(_span) {
|
|
3054
3076
|
}
|
|
3055
|
-
/**
|
|
3056
|
-
* Shuts down the processor.
|
|
3057
|
-
*/
|
|
3058
3077
|
shutdown() {
|
|
3059
3078
|
return Promise.resolve();
|
|
3060
3079
|
}
|
|
3061
|
-
/**
|
|
3062
|
-
* Forces a flush of any pending spans.
|
|
3063
|
-
*/
|
|
3064
3080
|
forceFlush() {
|
|
3065
3081
|
return Promise.resolve();
|
|
3066
3082
|
}
|
|
@@ -3172,119 +3188,128 @@ var SENSITIVE_KEYS = /* @__PURE__ */ new Set([
|
|
|
3172
3188
|
"span"
|
|
3173
3189
|
]);
|
|
3174
3190
|
var SCRUB_REPLACEMENT = "[SCRUBBED]";
|
|
3175
|
-
|
|
3176
|
-
|
|
3177
|
-
|
|
3178
|
-
|
|
3179
|
-
|
|
3180
|
-
const keyLower = key.toLowerCase();
|
|
3181
|
-
for (const sensitiveKey of SENSITIVE_KEYS) {
|
|
3182
|
-
if (keyLower.includes(sensitiveKey)) {
|
|
3183
|
-
return true;
|
|
3184
|
-
}
|
|
3191
|
+
function isSensitiveKey(key) {
|
|
3192
|
+
const keyLower = key.toLowerCase();
|
|
3193
|
+
for (const sensitiveKey of SENSITIVE_KEYS) {
|
|
3194
|
+
if (keyLower.includes(sensitiveKey)) {
|
|
3195
|
+
return true;
|
|
3185
3196
|
}
|
|
3186
|
-
return false;
|
|
3187
3197
|
}
|
|
3188
|
-
|
|
3189
|
-
|
|
3190
|
-
|
|
3191
|
-
|
|
3192
|
-
|
|
3193
|
-
|
|
3194
|
-
|
|
3198
|
+
return false;
|
|
3199
|
+
}
|
|
3200
|
+
function scrubStringValue(value) {
|
|
3201
|
+
let scrubbed = value;
|
|
3202
|
+
scrubbed = scrubbed.replace(LONG_DIGIT_PATTERN, SCRUB_REPLACEMENT);
|
|
3203
|
+
for (const pattern of Object.values(SENSITIVE_PATTERNS)) {
|
|
3204
|
+
pattern.lastIndex = 0;
|
|
3205
|
+
if (pattern.test(scrubbed)) {
|
|
3195
3206
|
pattern.lastIndex = 0;
|
|
3196
|
-
|
|
3197
|
-
pattern.lastIndex = 0;
|
|
3198
|
-
scrubbed = scrubbed.replace(pattern, SCRUB_REPLACEMENT);
|
|
3199
|
-
}
|
|
3207
|
+
scrubbed = scrubbed.replace(pattern, SCRUB_REPLACEMENT);
|
|
3200
3208
|
}
|
|
3201
|
-
return scrubbed;
|
|
3202
3209
|
}
|
|
3203
|
-
|
|
3204
|
-
|
|
3205
|
-
|
|
3206
|
-
|
|
3207
|
-
|
|
3208
|
-
|
|
3209
|
-
|
|
3210
|
-
|
|
3210
|
+
return scrubbed;
|
|
3211
|
+
}
|
|
3212
|
+
function scrubDict(obj) {
|
|
3213
|
+
const result = {};
|
|
3214
|
+
for (const [k, v] of Object.entries(obj)) {
|
|
3215
|
+
result[k] = scrubAny(k, v);
|
|
3216
|
+
}
|
|
3217
|
+
return result;
|
|
3218
|
+
}
|
|
3219
|
+
function scrubList(arr) {
|
|
3220
|
+
return arr.map((item) => {
|
|
3221
|
+
if (typeof item === "string") return scrubStringValue(item);
|
|
3222
|
+
if (Array.isArray(item)) return scrubList(item);
|
|
3223
|
+
if (typeof item === "object" && item !== null) {
|
|
3224
|
+
return scrubDict(item);
|
|
3211
3225
|
}
|
|
3212
|
-
return
|
|
3226
|
+
return item;
|
|
3227
|
+
});
|
|
3228
|
+
}
|
|
3229
|
+
function scrubAny(key, value) {
|
|
3230
|
+
if (isSensitiveKey(key) && typeof value !== "object" && !Array.isArray(value)) {
|
|
3231
|
+
return SCRUB_REPLACEMENT;
|
|
3213
3232
|
}
|
|
3214
|
-
|
|
3215
|
-
|
|
3216
|
-
|
|
3217
|
-
|
|
3218
|
-
return value.map((item) => {
|
|
3219
|
-
if (typeof item === "string") {
|
|
3220
|
-
return this.scrubStringValue(item);
|
|
3221
|
-
} else if (Array.isArray(item)) {
|
|
3222
|
-
return this.scrubListValue(item);
|
|
3223
|
-
} else if (typeof item === "object" && item !== null) {
|
|
3224
|
-
return this.scrubDictValue(item);
|
|
3225
|
-
}
|
|
3226
|
-
return item;
|
|
3227
|
-
});
|
|
3233
|
+
if (typeof value === "string") return scrubStringValue(value);
|
|
3234
|
+
if (Array.isArray(value)) return scrubList(value);
|
|
3235
|
+
if (typeof value === "object" && value !== null) {
|
|
3236
|
+
return scrubDict(value);
|
|
3228
3237
|
}
|
|
3229
|
-
|
|
3230
|
-
|
|
3231
|
-
|
|
3232
|
-
|
|
3233
|
-
|
|
3234
|
-
|
|
3235
|
-
|
|
3236
|
-
|
|
3237
|
-
|
|
3238
|
-
}
|
|
3239
|
-
|
|
3240
|
-
} else if (typeof value === "object" && value !== null) {
|
|
3241
|
-
return [key, this.scrubDictValue(value)];
|
|
3238
|
+
return value;
|
|
3239
|
+
}
|
|
3240
|
+
function scrubValue(key, value) {
|
|
3241
|
+
return scrubAny(key, value);
|
|
3242
|
+
}
|
|
3243
|
+
var ScrubbingSpanProcessor = class {
|
|
3244
|
+
onStart(span2, _parentContext) {
|
|
3245
|
+
try {
|
|
3246
|
+
this.wrapSetAttribute(span2);
|
|
3247
|
+
} catch (e) {
|
|
3248
|
+
Logger.error("ScrubbingSpanProcessor.onStart error:", e);
|
|
3242
3249
|
}
|
|
3243
|
-
return [key, value];
|
|
3244
3250
|
}
|
|
3245
|
-
|
|
3246
|
-
* Called when a span starts. No-op for this processor.
|
|
3247
|
-
*/
|
|
3248
|
-
onStart(span2, parentContext) {
|
|
3251
|
+
onEnd(_span) {
|
|
3249
3252
|
}
|
|
3250
|
-
|
|
3251
|
-
|
|
3252
|
-
|
|
3253
|
-
|
|
3254
|
-
|
|
3255
|
-
|
|
3256
|
-
|
|
3257
|
-
|
|
3258
|
-
|
|
3259
|
-
|
|
3260
|
-
|
|
3261
|
-
|
|
3262
|
-
|
|
3263
|
-
|
|
3264
|
-
|
|
3265
|
-
|
|
3266
|
-
Object.keys(spanAny.attributes).forEach(
|
|
3267
|
-
(k) => delete spanAny.attributes[k]
|
|
3268
|
-
);
|
|
3269
|
-
Object.assign(spanAny.attributes, scrubbedAttributes);
|
|
3253
|
+
shutdown() {
|
|
3254
|
+
return Promise.resolve();
|
|
3255
|
+
}
|
|
3256
|
+
forceFlush() {
|
|
3257
|
+
return Promise.resolve();
|
|
3258
|
+
}
|
|
3259
|
+
wrapSetAttribute(span2) {
|
|
3260
|
+
const original = span2.setAttribute.bind(span2);
|
|
3261
|
+
const patched = (key, value) => {
|
|
3262
|
+
try {
|
|
3263
|
+
return original(key, scrubValue(key, value));
|
|
3264
|
+
} catch {
|
|
3265
|
+
try {
|
|
3266
|
+
return original(key, value);
|
|
3267
|
+
} catch {
|
|
3268
|
+
return span2;
|
|
3270
3269
|
}
|
|
3271
3270
|
}
|
|
3271
|
+
};
|
|
3272
|
+
span2.setAttribute = patched;
|
|
3273
|
+
}
|
|
3274
|
+
};
|
|
3275
|
+
|
|
3276
|
+
// src/processors/serialization-span-processor.ts
|
|
3277
|
+
var SerializationSpanProcessor = class {
|
|
3278
|
+
constructor(maxAttributeSize) {
|
|
3279
|
+
this.maxAttributeSize = maxAttributeSize ?? Config.SPAN_ATTRIBUTE_MAX_SIZE;
|
|
3280
|
+
}
|
|
3281
|
+
onStart(span2, _parentContext) {
|
|
3282
|
+
try {
|
|
3283
|
+
this.wrapSetAttribute(span2);
|
|
3272
3284
|
} catch (e) {
|
|
3273
|
-
Logger.
|
|
3285
|
+
Logger.debug("SerializationSpanProcessor.onStart error:", e);
|
|
3274
3286
|
}
|
|
3275
3287
|
}
|
|
3276
|
-
|
|
3277
|
-
|
|
3278
|
-
*/
|
|
3288
|
+
onEnd(_span) {
|
|
3289
|
+
}
|
|
3279
3290
|
shutdown() {
|
|
3280
3291
|
return Promise.resolve();
|
|
3281
3292
|
}
|
|
3282
|
-
/**
|
|
3283
|
-
* Forces a flush of any pending spans.
|
|
3284
|
-
*/
|
|
3285
3293
|
forceFlush() {
|
|
3286
3294
|
return Promise.resolve();
|
|
3287
3295
|
}
|
|
3296
|
+
wrapSetAttribute(span2) {
|
|
3297
|
+
const original = span2.setAttribute.bind(span2);
|
|
3298
|
+
const maxSize = this.maxAttributeSize;
|
|
3299
|
+
const patched = (key, value) => {
|
|
3300
|
+
try {
|
|
3301
|
+
const truncated = serializeAttribute(value, maxSize);
|
|
3302
|
+
return original(key, truncated);
|
|
3303
|
+
} catch {
|
|
3304
|
+
try {
|
|
3305
|
+
return original(key, value);
|
|
3306
|
+
} catch {
|
|
3307
|
+
return span2;
|
|
3308
|
+
}
|
|
3309
|
+
}
|
|
3310
|
+
};
|
|
3311
|
+
span2.setAttribute = patched;
|
|
3312
|
+
}
|
|
3288
3313
|
};
|
|
3289
3314
|
function getContextManager() {
|
|
3290
3315
|
try {
|
|
@@ -3394,106 +3419,194 @@ var SessionSpanProcessor = class {
|
|
|
3394
3419
|
return Promise.resolve();
|
|
3395
3420
|
}
|
|
3396
3421
|
};
|
|
3397
|
-
|
|
3422
|
+
|
|
3423
|
+
// src/processors/root-instrument-filter-processor.ts
|
|
3424
|
+
var INVALID_SPAN_ID = "0000000000000000";
|
|
3398
3425
|
var INSTRUMENTATION_PREFIXES = [
|
|
3399
3426
|
"opentelemetry.instrumentation.",
|
|
3400
3427
|
"netra.instrumentation.",
|
|
3401
3428
|
"@opentelemetry/instrumentation-",
|
|
3402
3429
|
"@traceloop/instrumentation-"
|
|
3403
3430
|
];
|
|
3404
|
-
var
|
|
3405
|
-
var
|
|
3431
|
+
var MAX_ROOT_CANDIDATES = 4096;
|
|
3432
|
+
var ROOT_CANDIDATE_TTL_MS = 6e5;
|
|
3433
|
+
var EVICTION_INTERVAL_MS = 1e4;
|
|
3434
|
+
function canonicalInstrumentName(name) {
|
|
3435
|
+
return name.toLowerCase().replace(/_/g, "");
|
|
3436
|
+
}
|
|
3437
|
+
var ROOT_BLOCK_CANDIDATE_FIELD = "_netraRootBlockCandidate";
|
|
3438
|
+
var ROOT_BLOCK_CANDIDATES = /* @__PURE__ */ new Map();
|
|
3439
|
+
function getRootBlockCandidatesFor(seedIds) {
|
|
3440
|
+
const out = /* @__PURE__ */ new Map();
|
|
3441
|
+
const stack = [...seedIds];
|
|
3442
|
+
while (stack.length > 0) {
|
|
3443
|
+
const spanId = stack.pop();
|
|
3444
|
+
if (spanId === void 0 || out.has(spanId)) {
|
|
3445
|
+
continue;
|
|
3446
|
+
}
|
|
3447
|
+
const entry = ROOT_BLOCK_CANDIDATES.get(spanId);
|
|
3448
|
+
if (!entry) {
|
|
3449
|
+
continue;
|
|
3450
|
+
}
|
|
3451
|
+
out.set(spanId, entry.parentCtx);
|
|
3452
|
+
const parentId = entry.parentCtx?.spanId;
|
|
3453
|
+
if (parentId && parentId !== INVALID_SPAN_ID) {
|
|
3454
|
+
stack.push(parentId);
|
|
3455
|
+
}
|
|
3456
|
+
}
|
|
3457
|
+
return out;
|
|
3458
|
+
}
|
|
3459
|
+
function resetRootBlockCandidates() {
|
|
3460
|
+
ROOT_BLOCK_CANDIDATES.clear();
|
|
3461
|
+
}
|
|
3462
|
+
function rootBlockCandidatesContains(spanIds) {
|
|
3463
|
+
if (spanIds.size === 0) {
|
|
3464
|
+
return false;
|
|
3465
|
+
}
|
|
3466
|
+
for (const spanId of spanIds) {
|
|
3467
|
+
if (ROOT_BLOCK_CANDIDATES.has(spanId)) {
|
|
3468
|
+
return true;
|
|
3469
|
+
}
|
|
3470
|
+
}
|
|
3471
|
+
return false;
|
|
3472
|
+
}
|
|
3473
|
+
function isRootBlockCandidate(span2) {
|
|
3474
|
+
return Boolean(span2?.[ROOT_BLOCK_CANDIDATE_FIELD]);
|
|
3475
|
+
}
|
|
3406
3476
|
var RootInstrumentFilterProcessor = class {
|
|
3407
3477
|
constructor(allowedRootInstrumentNames) {
|
|
3408
|
-
this.
|
|
3409
|
-
this._allowed = new Set(
|
|
3478
|
+
this._lastEvictionAt = 0;
|
|
3479
|
+
this._allowed = new Set(
|
|
3480
|
+
[...allowedRootInstrumentNames].map(canonicalInstrumentName)
|
|
3481
|
+
);
|
|
3482
|
+
resetRootBlockCandidates();
|
|
3410
3483
|
}
|
|
3411
|
-
onStart(span2,
|
|
3484
|
+
onStart(span2, _parentContext) {
|
|
3412
3485
|
try {
|
|
3413
|
-
this._processSpanStart(span2
|
|
3486
|
+
this._processSpanStart(span2);
|
|
3414
3487
|
} catch {
|
|
3415
3488
|
}
|
|
3416
3489
|
}
|
|
3417
3490
|
onEnd(span2) {
|
|
3418
3491
|
try {
|
|
3419
|
-
|
|
3492
|
+
const now = Date.now();
|
|
3493
|
+
this._markEnded(span2, now);
|
|
3494
|
+
this._evictStaleCandidates(now);
|
|
3420
3495
|
} catch {
|
|
3421
3496
|
}
|
|
3422
3497
|
}
|
|
3498
|
+
/**
|
|
3499
|
+
* No-op — the candidate registry is deliberately NOT cleared here.
|
|
3500
|
+
*
|
|
3501
|
+
* `MultiSpanProcessor.shutdown()` invokes every registered processor's
|
|
3502
|
+
* `shutdown()` concurrently (`Promise.all`), so clearing the shared registry
|
|
3503
|
+
* here could race with the exporter's final flush still reading it to
|
|
3504
|
+
* reparent buffered blocked roots. Fresh sessions instead reset the registry
|
|
3505
|
+
* on construction (see the constructor); it is also bounded
|
|
3506
|
+
* (`MAX_ROOT_CANDIDATES`) and TTL-evicted, so leaving it intact on shutdown
|
|
3507
|
+
* is safe.
|
|
3508
|
+
*/
|
|
3423
3509
|
shutdown() {
|
|
3424
|
-
this._blockedTraceIds.clear();
|
|
3425
3510
|
return Promise.resolve();
|
|
3426
3511
|
}
|
|
3427
3512
|
forceFlush() {
|
|
3428
3513
|
return Promise.resolve();
|
|
3429
3514
|
}
|
|
3430
|
-
_processSpanStart(span2
|
|
3431
|
-
const parentSpanId = this._resolveParentSpanId(parentContext) ?? this._getParentSpanIdFromSpan(span2);
|
|
3432
|
-
const isChild = parentSpanId !== null && parentSpanId !== "0000000000000000";
|
|
3433
|
-
if (isChild) {
|
|
3434
|
-
this._maybeBlockChild(span2);
|
|
3435
|
-
} else {
|
|
3436
|
-
this._maybeBlockRoot(span2);
|
|
3437
|
-
}
|
|
3438
|
-
}
|
|
3439
|
-
_maybeBlockChild(span2) {
|
|
3440
|
-
const traceId = this._getTraceId(span2);
|
|
3441
|
-
if (!traceId) {
|
|
3442
|
-
return;
|
|
3443
|
-
}
|
|
3444
|
-
if (this._blockedTraceIds.has(traceId)) {
|
|
3445
|
-
this._markBlocked(span2);
|
|
3446
|
-
}
|
|
3447
|
-
}
|
|
3448
|
-
_maybeBlockRoot(span2) {
|
|
3515
|
+
_processSpanStart(span2) {
|
|
3449
3516
|
if (!this._isFromInstrumentationLibrary(span2)) {
|
|
3450
3517
|
return;
|
|
3451
3518
|
}
|
|
3452
3519
|
const instrName = this._extractInstrumentationName(span2);
|
|
3453
|
-
if (instrName === null || this._allowed.has(instrName)) {
|
|
3520
|
+
if (instrName === null || this._allowed.has(canonicalInstrumentName(instrName))) {
|
|
3454
3521
|
return;
|
|
3455
3522
|
}
|
|
3456
|
-
const
|
|
3457
|
-
if (
|
|
3458
|
-
|
|
3459
|
-
this._evictOverflow();
|
|
3523
|
+
const spanId = this._getOwnSpanId(span2);
|
|
3524
|
+
if (spanId === null || spanId === INVALID_SPAN_ID) {
|
|
3525
|
+
return;
|
|
3460
3526
|
}
|
|
3461
|
-
this.
|
|
3527
|
+
const parentCtx = this._getParentSpanContext(span2);
|
|
3528
|
+
this._markCandidate(span2);
|
|
3529
|
+
this._recordCandidate(spanId, parentCtx);
|
|
3462
3530
|
}
|
|
3463
|
-
|
|
3464
|
-
|
|
3465
|
-
|
|
3466
|
-
|
|
3531
|
+
_markCandidate(span2) {
|
|
3532
|
+
try {
|
|
3533
|
+
span2[ROOT_BLOCK_CANDIDATE_FIELD] = true;
|
|
3534
|
+
} catch {
|
|
3467
3535
|
}
|
|
3468
|
-
|
|
3469
|
-
|
|
3470
|
-
|
|
3536
|
+
}
|
|
3537
|
+
/**
|
|
3538
|
+
* Register `spanId` as an active candidate. `move-to-end` semantics
|
|
3539
|
+
* (delete+set) refresh insertion order; overflow drops the oldest entry.
|
|
3540
|
+
*/
|
|
3541
|
+
_recordCandidate(spanId, parentCtx) {
|
|
3542
|
+
ROOT_BLOCK_CANDIDATES.delete(spanId);
|
|
3543
|
+
ROOT_BLOCK_CANDIDATES.set(spanId, { parentCtx, endedAt: null });
|
|
3544
|
+
while (ROOT_BLOCK_CANDIDATES.size > MAX_ROOT_CANDIDATES) {
|
|
3545
|
+
const oldest = ROOT_BLOCK_CANDIDATES.keys().next().value;
|
|
3546
|
+
if (oldest === void 0) {
|
|
3547
|
+
break;
|
|
3548
|
+
}
|
|
3549
|
+
ROOT_BLOCK_CANDIDATES.delete(oldest);
|
|
3471
3550
|
}
|
|
3472
|
-
return sc.spanId;
|
|
3473
3551
|
}
|
|
3474
|
-
|
|
3475
|
-
|
|
3476
|
-
const
|
|
3477
|
-
if (
|
|
3478
|
-
return
|
|
3552
|
+
/** Start the TTL clock for a just-ended candidate, if it has an entry. */
|
|
3553
|
+
_markEnded(span2, now) {
|
|
3554
|
+
const spanId = this._getOwnSpanId(span2);
|
|
3555
|
+
if (spanId === null) {
|
|
3556
|
+
return;
|
|
3557
|
+
}
|
|
3558
|
+
const entry = ROOT_BLOCK_CANDIDATES.get(spanId);
|
|
3559
|
+
if (entry) {
|
|
3560
|
+
entry.endedAt = now;
|
|
3479
3561
|
}
|
|
3480
|
-
return parent;
|
|
3481
3562
|
}
|
|
3482
|
-
|
|
3483
|
-
|
|
3484
|
-
|
|
3485
|
-
|
|
3486
|
-
|
|
3563
|
+
/**
|
|
3564
|
+
* Evict entries whose span ended more than `ROOT_CANDIDATE_TTL_MS` ago.
|
|
3565
|
+
* Active candidates (`endedAt === null`) are skipped — never evicted while the
|
|
3566
|
+
* span is still open.
|
|
3567
|
+
*
|
|
3568
|
+
* The scan cannot break early: the registry is ordered by span *start*
|
|
3569
|
+
* (insertion) whereas staleness is measured from span *end*, and those two
|
|
3570
|
+
* orders do not coincide (a long-lived active root sits at the head while
|
|
3571
|
+
* short spans behind it may already be stale). A full sweep is therefore
|
|
3572
|
+
* required, but it is time-throttled (`EVICTION_INTERVAL_MS`) so it does not
|
|
3573
|
+
* run on every span end.
|
|
3574
|
+
*/
|
|
3575
|
+
_evictStaleCandidates(now) {
|
|
3576
|
+
if (now - this._lastEvictionAt < EVICTION_INTERVAL_MS) {
|
|
3577
|
+
return;
|
|
3578
|
+
}
|
|
3579
|
+
this._lastEvictionAt = now;
|
|
3580
|
+
const cutoff = now - ROOT_CANDIDATE_TTL_MS;
|
|
3581
|
+
for (const [spanId, entry] of ROOT_BLOCK_CANDIDATES) {
|
|
3582
|
+
if (entry.endedAt !== null && entry.endedAt <= cutoff) {
|
|
3583
|
+
ROOT_BLOCK_CANDIDATES.delete(spanId);
|
|
3487
3584
|
}
|
|
3488
|
-
} catch {
|
|
3489
3585
|
}
|
|
3490
|
-
return null;
|
|
3491
3586
|
}
|
|
3492
|
-
|
|
3587
|
+
_getOwnSpanId(span2) {
|
|
3493
3588
|
try {
|
|
3494
|
-
span2.
|
|
3589
|
+
const sc = span2.spanContext?.() ?? span2.spanContext;
|
|
3590
|
+
const spanId = sc?.spanId;
|
|
3591
|
+
return typeof spanId === "string" && spanId ? spanId : null;
|
|
3495
3592
|
} catch {
|
|
3593
|
+
return null;
|
|
3594
|
+
}
|
|
3595
|
+
}
|
|
3596
|
+
/**
|
|
3597
|
+
* Resolve the parent `SpanContext` recorded on the span, normalizing an
|
|
3598
|
+
* invalid/sentinel parent to `undefined` (= trace root).
|
|
3599
|
+
*/
|
|
3600
|
+
_getParentSpanContext(span2) {
|
|
3601
|
+
const spanAny = span2;
|
|
3602
|
+
const parent = spanAny.parentSpanContext ?? spanAny.parent;
|
|
3603
|
+
if (!parent) {
|
|
3604
|
+
return void 0;
|
|
3605
|
+
}
|
|
3606
|
+
if (!parent.spanId || parent.spanId === INVALID_SPAN_ID) {
|
|
3607
|
+
return void 0;
|
|
3496
3608
|
}
|
|
3609
|
+
return parent;
|
|
3497
3610
|
}
|
|
3498
3611
|
_isFromInstrumentationLibrary(span2) {
|
|
3499
3612
|
const spanAny = span2;
|
|
@@ -3522,30 +3635,11 @@ var RootInstrumentFilterProcessor = class {
|
|
|
3522
3635
|
const segments = name.split(/[./\-]/);
|
|
3523
3636
|
const base = segments[segments.length - 1]?.trim();
|
|
3524
3637
|
if (base) {
|
|
3525
|
-
return base;
|
|
3526
|
-
}
|
|
3527
|
-
}
|
|
3528
|
-
}
|
|
3529
|
-
return name;
|
|
3530
|
-
}
|
|
3531
|
-
_evictStaleTraces() {
|
|
3532
|
-
const cutoff = Date.now() - BLOCKED_TRACE_TTL_MS;
|
|
3533
|
-
for (const [traceId, entry] of this._blockedTraceIds) {
|
|
3534
|
-
if (entry.timestamp > cutoff) {
|
|
3535
|
-
break;
|
|
3536
|
-
}
|
|
3537
|
-
this._blockedTraceIds.delete(traceId);
|
|
3538
|
-
}
|
|
3539
|
-
}
|
|
3540
|
-
_evictOverflow() {
|
|
3541
|
-
while (this._blockedTraceIds.size > MAX_BLOCKED_TRACES) {
|
|
3542
|
-
const first = this._blockedTraceIds.keys().next().value;
|
|
3543
|
-
if (first !== void 0) {
|
|
3544
|
-
this._blockedTraceIds.delete(first);
|
|
3545
|
-
} else {
|
|
3546
|
-
break;
|
|
3638
|
+
return base;
|
|
3639
|
+
}
|
|
3547
3640
|
}
|
|
3548
3641
|
}
|
|
3642
|
+
return name;
|
|
3549
3643
|
}
|
|
3550
3644
|
};
|
|
3551
3645
|
|
|
@@ -4069,7 +4163,7 @@ function buildInputMessages(kwargs, requestType) {
|
|
|
4069
4163
|
tool_use_id: block.tool_use_id,
|
|
4070
4164
|
content: block.content,
|
|
4071
4165
|
is_error: block.is_error ?? false
|
|
4072
|
-
}
|
|
4166
|
+
})
|
|
4073
4167
|
});
|
|
4074
4168
|
}
|
|
4075
4169
|
}
|
|
@@ -4099,7 +4193,7 @@ function buildInputMessages(kwargs, requestType) {
|
|
|
4099
4193
|
} else {
|
|
4100
4194
|
const input = kwargs.input ?? kwargs.inputs;
|
|
4101
4195
|
if (hasContent(input)) {
|
|
4102
|
-
const content = safeStringify(input
|
|
4196
|
+
const content = safeStringify(input);
|
|
4103
4197
|
messages.push({ role: "user", content });
|
|
4104
4198
|
}
|
|
4105
4199
|
}
|
|
@@ -4236,7 +4330,7 @@ function setRequestAttributes(span2, kwargs, requestType, system) {
|
|
|
4236
4330
|
}
|
|
4237
4331
|
setModelParams(span2, kwargs);
|
|
4238
4332
|
if (Array.isArray(kwargs.tools)) {
|
|
4239
|
-
span2.setAttribute("tools", safeStringify(kwargs.tools
|
|
4333
|
+
span2.setAttribute("tools", safeStringify(kwargs.tools));
|
|
4240
4334
|
}
|
|
4241
4335
|
if (kwargs.reasoning !== void 0) {
|
|
4242
4336
|
span2.setAttribute(
|
|
@@ -4250,7 +4344,7 @@ function setRequestAttributes(span2, kwargs, requestType, system) {
|
|
|
4250
4344
|
if (kwargs.suffix !== void 0) {
|
|
4251
4345
|
span2.setAttribute(
|
|
4252
4346
|
"llm.request.suffix",
|
|
4253
|
-
safeStringify(kwargs.suffix
|
|
4347
|
+
safeStringify(kwargs.suffix)
|
|
4254
4348
|
);
|
|
4255
4349
|
}
|
|
4256
4350
|
}
|
|
@@ -4542,7 +4636,6 @@ var TRACKED_STREAM_EVENTS = /* @__PURE__ */ new Set([
|
|
|
4542
4636
|
"text",
|
|
4543
4637
|
"finalMessage"
|
|
4544
4638
|
]);
|
|
4545
|
-
var MAX_TOOL_ATTR_LENGTH = 4096;
|
|
4546
4639
|
function wrapRunnableTools(tools, tracer, parentContext) {
|
|
4547
4640
|
return tools.map((tool) => {
|
|
4548
4641
|
if (typeof tool.run !== "function") return tool;
|
|
@@ -4557,7 +4650,7 @@ function wrapRunnableTools(tools, tracer, parentContext) {
|
|
|
4557
4650
|
};
|
|
4558
4651
|
if (toolUseId) attrs[SpanAttributes2.LLM_REQUEST_TOOL_ID] = toolUseId;
|
|
4559
4652
|
if (traceContent) {
|
|
4560
|
-
attrs.input = safeStringify(input
|
|
4653
|
+
attrs.input = safeStringify(input);
|
|
4561
4654
|
}
|
|
4562
4655
|
const span2 = tracer.startSpan(
|
|
4563
4656
|
toolName,
|
|
@@ -4571,10 +4664,7 @@ function wrapRunnableTools(tools, tracer, parentContext) {
|
|
|
4571
4664
|
() => originalRun.call(this, input, runContext)
|
|
4572
4665
|
);
|
|
4573
4666
|
if (traceContent) {
|
|
4574
|
-
span2.setAttribute(
|
|
4575
|
-
"output",
|
|
4576
|
-
safeStringify(result, MAX_TOOL_ATTR_LENGTH)
|
|
4577
|
-
);
|
|
4667
|
+
span2.setAttribute("output", safeStringify(result));
|
|
4578
4668
|
}
|
|
4579
4669
|
span2.setStatus({ code: SpanStatusCode.OK });
|
|
4580
4670
|
return result;
|
|
@@ -5569,7 +5659,7 @@ function extractModelName(model) {
|
|
|
5569
5659
|
function buildGoogleInputMessages(params, cfg) {
|
|
5570
5660
|
const messages = [];
|
|
5571
5661
|
if (hasContent(cfg.systemInstruction)) {
|
|
5572
|
-
const sysContent = typeof cfg.systemInstruction === "string" ? cfg.systemInstruction : safeStringify(cfg.systemInstruction
|
|
5662
|
+
const sysContent = typeof cfg.systemInstruction === "string" ? cfg.systemInstruction : safeStringify(cfg.systemInstruction);
|
|
5573
5663
|
messages.push({ role: "system", content: sysContent });
|
|
5574
5664
|
}
|
|
5575
5665
|
const history = params._history;
|
|
@@ -5602,7 +5692,7 @@ function buildGoogleInputMessages(params, cfg) {
|
|
|
5602
5692
|
} else {
|
|
5603
5693
|
messages.push({
|
|
5604
5694
|
role: "user",
|
|
5605
|
-
content: safeStringify(item
|
|
5695
|
+
content: safeStringify(item)
|
|
5606
5696
|
});
|
|
5607
5697
|
}
|
|
5608
5698
|
}
|
|
@@ -5615,7 +5705,7 @@ function buildGoogleInputMessages(params, cfg) {
|
|
|
5615
5705
|
} else {
|
|
5616
5706
|
messages.push({
|
|
5617
5707
|
role: "user",
|
|
5618
|
-
content: safeStringify(contents
|
|
5708
|
+
content: safeStringify(contents)
|
|
5619
5709
|
});
|
|
5620
5710
|
}
|
|
5621
5711
|
return messages;
|
|
@@ -5631,10 +5721,10 @@ function extractTextFromParts(parts) {
|
|
|
5631
5721
|
if (typeof part.text === "string") {
|
|
5632
5722
|
texts.push(part.text);
|
|
5633
5723
|
} else if (part.functionCall) {
|
|
5634
|
-
texts.push(safeStringify(part.functionCall
|
|
5724
|
+
texts.push(safeStringify(part.functionCall));
|
|
5635
5725
|
} else if (part.functionResponse) {
|
|
5636
5726
|
texts.push(
|
|
5637
|
-
safeStringify(part.functionResponse
|
|
5727
|
+
safeStringify(part.functionResponse)
|
|
5638
5728
|
);
|
|
5639
5729
|
}
|
|
5640
5730
|
}
|
|
@@ -5756,8 +5846,7 @@ function buildGoogleOutputMessages(response) {
|
|
|
5756
5846
|
messages.push({
|
|
5757
5847
|
role: "tool",
|
|
5758
5848
|
content: safeStringify(
|
|
5759
|
-
{ name: fc.name, arguments: fc.args }
|
|
5760
|
-
Config.CONVERSATION_MAX_LEN
|
|
5849
|
+
{ name: fc.name, arguments: fc.args }
|
|
5761
5850
|
)
|
|
5762
5851
|
});
|
|
5763
5852
|
}
|
|
@@ -5777,8 +5866,7 @@ function buildGoogleOutputMessages(response) {
|
|
|
5777
5866
|
messages.push({
|
|
5778
5867
|
role: "tool",
|
|
5779
5868
|
content: safeStringify(
|
|
5780
|
-
{ name: fc.name, arguments: fc.args }
|
|
5781
|
-
Config.CONVERSATION_MAX_LEN
|
|
5869
|
+
{ name: fc.name, arguments: fc.args }
|
|
5782
5870
|
)
|
|
5783
5871
|
});
|
|
5784
5872
|
}
|
|
@@ -6314,10 +6402,7 @@ function _setPromptAttributes(span2, kwargs, args) {
|
|
|
6314
6402
|
promptIndex++;
|
|
6315
6403
|
}
|
|
6316
6404
|
if (inlineDataParts.length > 0) {
|
|
6317
|
-
span2.setAttribute(
|
|
6318
|
-
`gen_ai.prompt.${slotIndex}.has_inline_data`,
|
|
6319
|
-
true
|
|
6320
|
-
);
|
|
6405
|
+
span2.setAttribute(`gen_ai.prompt.${slotIndex}.has_inline_data`, true);
|
|
6321
6406
|
span2.setAttribute(
|
|
6322
6407
|
`gen_ai.prompt.${slotIndex}.inline_data_count`,
|
|
6323
6408
|
inlineDataParts.length
|
|
@@ -9689,7 +9774,6 @@ var openAIInstrumentor = new NetraOpenAIInstrumentor();
|
|
|
9689
9774
|
var INSTRUMENTATION_NAME6 = "netra.instrumentation.openai_agents";
|
|
9690
9775
|
var DEFAULT_LLM_SYSTEM = "openai";
|
|
9691
9776
|
var MAX_INDEXED_MESSAGES = 128;
|
|
9692
|
-
var MAX_STRINGIFY_LENGTH = 65536;
|
|
9693
9777
|
var NETRA_SPAN_TYPE_ATTR = "netra.span.type";
|
|
9694
9778
|
var NETRA_WORKFLOW_NAME = "netra.workflow.name";
|
|
9695
9779
|
var NETRA_AGENT_NAME = "netra.agent.name";
|
|
@@ -9713,17 +9797,6 @@ var GEN_AI_TOOL_NAME = "gen_ai.tool.name";
|
|
|
9713
9797
|
var GEN_AI_RESPONSE_ID = "gen_ai.response.id";
|
|
9714
9798
|
|
|
9715
9799
|
// src/instrumentation/openai-agents/utils.ts
|
|
9716
|
-
function safeJsonStringify(obj, maxLength = MAX_STRINGIFY_LENGTH) {
|
|
9717
|
-
try {
|
|
9718
|
-
if (typeof obj === "string") {
|
|
9719
|
-
return maxLength > 0 && obj.length > maxLength ? obj.slice(0, maxLength) : obj;
|
|
9720
|
-
}
|
|
9721
|
-
const s = JSON.stringify(obj);
|
|
9722
|
-
return maxLength > 0 && s.length > maxLength ? s.slice(0, maxLength) : s;
|
|
9723
|
-
} catch {
|
|
9724
|
-
return String(obj);
|
|
9725
|
-
}
|
|
9726
|
-
}
|
|
9727
9800
|
function getNetraSpanType(data) {
|
|
9728
9801
|
switch (data.type) {
|
|
9729
9802
|
case "agent":
|
|
@@ -9745,7 +9818,8 @@ function getNetraSpanType(data) {
|
|
|
9745
9818
|
function getSpanName(agentSpan) {
|
|
9746
9819
|
const data = agentSpan.spanData;
|
|
9747
9820
|
if (data.name) return data.name;
|
|
9748
|
-
if (data.type === "handoff" && data.to_agent)
|
|
9821
|
+
if (data.type === "handoff" && data.to_agent)
|
|
9822
|
+
return `handoff to ${data.to_agent}`;
|
|
9749
9823
|
return `openai.agents.${data.type}`;
|
|
9750
9824
|
}
|
|
9751
9825
|
function extractContentString(content) {
|
|
@@ -9761,7 +9835,7 @@ function extractContentString(content) {
|
|
|
9761
9835
|
}
|
|
9762
9836
|
}
|
|
9763
9837
|
}
|
|
9764
|
-
return texts.length > 0 ? texts.join(" ") :
|
|
9838
|
+
return texts.length > 0 ? texts.join(" ") : safeStringify(content);
|
|
9765
9839
|
}
|
|
9766
9840
|
return String(content);
|
|
9767
9841
|
}
|
|
@@ -9848,12 +9922,12 @@ function setGenerationAttributes(span2, data, systemName) {
|
|
|
9848
9922
|
span2.setAttribute(SpanAttributes2.LLM_PRESENCE_PENALTY, Number(config.presence_penalty));
|
|
9849
9923
|
}
|
|
9850
9924
|
if (config.stop !== void 0) {
|
|
9851
|
-
span2.setAttribute(SpanAttributes2.LLM_CHAT_STOP_SEQUENCES,
|
|
9925
|
+
span2.setAttribute(SpanAttributes2.LLM_CHAT_STOP_SEQUENCES, safeStringify(config.stop));
|
|
9852
9926
|
}
|
|
9853
9927
|
if (config.reasoning_effort !== void 0) {
|
|
9854
9928
|
span2.setAttribute(SpanAttributes2.LLM_REQUEST_REASONING_EFFORT, String(config.reasoning_effort));
|
|
9855
9929
|
} else if (config.reasoning !== void 0) {
|
|
9856
|
-
span2.setAttribute(SpanAttributes2.LLM_REQUEST_REASONING_EFFORT,
|
|
9930
|
+
span2.setAttribute(SpanAttributes2.LLM_REQUEST_REASONING_EFFORT, safeStringify(config.reasoning));
|
|
9857
9931
|
}
|
|
9858
9932
|
}
|
|
9859
9933
|
const effectiveOutput = unwrapGenerationOutput(data.output);
|
|
@@ -9913,11 +9987,11 @@ function setFunctionAttributes(span2, data) {
|
|
|
9913
9987
|
}
|
|
9914
9988
|
if (data.input !== void 0) {
|
|
9915
9989
|
span2.setAttribute(`${SpanAttributes2.LLM_PROMPTS}.0.role`, "tool");
|
|
9916
|
-
span2.setAttribute(`${SpanAttributes2.LLM_PROMPTS}.0.content`,
|
|
9990
|
+
span2.setAttribute(`${SpanAttributes2.LLM_PROMPTS}.0.content`, safeStringify(data.input));
|
|
9917
9991
|
}
|
|
9918
9992
|
if (data.output !== void 0) {
|
|
9919
9993
|
span2.setAttribute(`${SpanAttributes2.LLM_COMPLETIONS}.0.role`, "tool");
|
|
9920
|
-
span2.setAttribute(`${SpanAttributes2.LLM_COMPLETIONS}.0.content`,
|
|
9994
|
+
span2.setAttribute(`${SpanAttributes2.LLM_COMPLETIONS}.0.content`, safeStringify(data.output));
|
|
9921
9995
|
}
|
|
9922
9996
|
}
|
|
9923
9997
|
function setHandoffAttributes(span2, data) {
|
|
@@ -9947,7 +10021,7 @@ function setCustomAttributes(span2, data) {
|
|
|
9947
10021
|
span2.setAttribute(NETRA_SPAN_NAME, data.name);
|
|
9948
10022
|
}
|
|
9949
10023
|
if (data.data !== void 0) {
|
|
9950
|
-
span2.setAttribute(NETRA_CUSTOM_DATA,
|
|
10024
|
+
span2.setAttribute(NETRA_CUSTOM_DATA, safeStringify(data.data));
|
|
9951
10025
|
}
|
|
9952
10026
|
}
|
|
9953
10027
|
function setUsageAttributes3(span2, usage) {
|
|
@@ -10013,7 +10087,7 @@ function setResponseObjectAttributes(span2, response) {
|
|
|
10013
10087
|
span2.setAttribute(SpanAttributes2.LLM_PRESENCE_PENALTY, resp.presence_penalty);
|
|
10014
10088
|
}
|
|
10015
10089
|
if (resp.reasoning !== void 0) {
|
|
10016
|
-
span2.setAttribute(SpanAttributes2.LLM_REQUEST_REASONING_EFFORT,
|
|
10090
|
+
span2.setAttribute(SpanAttributes2.LLM_REQUEST_REASONING_EFFORT, safeStringify(resp.reasoning));
|
|
10017
10091
|
}
|
|
10018
10092
|
if (resp.usage) {
|
|
10019
10093
|
setResponseObjectUsageAttributes(span2, resp.usage);
|
|
@@ -10059,7 +10133,7 @@ function setIndexedPromptAttributes(span2, input, startIndex = 0) {
|
|
|
10059
10133
|
span2.setAttribute(`${SpanAttributes2.LLM_PROMPTS}.${index}.role`, "assistant");
|
|
10060
10134
|
span2.setAttribute(
|
|
10061
10135
|
`${SpanAttributes2.LLM_PROMPTS}.${index}.content`,
|
|
10062
|
-
|
|
10136
|
+
safeStringify({ name: msg.name, arguments: msg.arguments })
|
|
10063
10137
|
);
|
|
10064
10138
|
} else if (msgType === "function_call_output" || msgType === "function_call_result") {
|
|
10065
10139
|
span2.setAttribute(`${SpanAttributes2.LLM_PROMPTS}.${index}.role`, "tool");
|
|
@@ -10103,7 +10177,7 @@ function setIndexedCompletionAttributes(span2, responseData) {
|
|
|
10103
10177
|
span2.setAttribute(`${SpanAttributes2.LLM_COMPLETIONS}.${index}.role`, "assistant");
|
|
10104
10178
|
span2.setAttribute(
|
|
10105
10179
|
`${SpanAttributes2.LLM_COMPLETIONS}.${index}.content`,
|
|
10106
|
-
|
|
10180
|
+
safeStringify({ name: element.name, arguments: element.arguments })
|
|
10107
10181
|
);
|
|
10108
10182
|
const toolCallId = element.call_id || element.id;
|
|
10109
10183
|
if (toolCallId) {
|
|
@@ -10140,7 +10214,7 @@ function setIndexedCompletionAttributes(span2, responseData) {
|
|
|
10140
10214
|
span2.setAttribute(`${SpanAttributes2.LLM_COMPLETIONS}.${index}.role`, "assistant");
|
|
10141
10215
|
span2.setAttribute(
|
|
10142
10216
|
`${SpanAttributes2.LLM_COMPLETIONS}.${index}.content`,
|
|
10143
|
-
|
|
10217
|
+
safeStringify({ name: func.name ?? "", arguments: func.arguments ?? "" })
|
|
10144
10218
|
);
|
|
10145
10219
|
if (tc.id) {
|
|
10146
10220
|
span2.setAttribute(`${SpanAttributes2.LLM_COMPLETIONS}.${index}.tool_call_id`, String(tc.id));
|
|
@@ -10243,7 +10317,7 @@ var _NetraAgentsTracingProcessor = class _NetraAgentsTracingProcessor {
|
|
|
10243
10317
|
span2.setAttribute(NETRA_AGENTS_GROUP_ID, agentTrace.groupId);
|
|
10244
10318
|
}
|
|
10245
10319
|
if (agentTrace.metadata) {
|
|
10246
|
-
span2.setAttribute(NETRA_AGENTS_METADATA,
|
|
10320
|
+
span2.setAttribute(NETRA_AGENTS_METADATA, safeStringify(agentTrace.metadata));
|
|
10247
10321
|
}
|
|
10248
10322
|
this._rootSpans.set(agentTrace.traceId, span2);
|
|
10249
10323
|
}
|
|
@@ -10329,7 +10403,8 @@ var _NetraAgentsTracingProcessor = class _NetraAgentsTracingProcessor {
|
|
|
10329
10403
|
}
|
|
10330
10404
|
}
|
|
10331
10405
|
if (agentSpan.error) {
|
|
10332
|
-
const
|
|
10406
|
+
const MAX_ERROR_DATA_LEN = 4096;
|
|
10407
|
+
const errorMsg = agentSpan.error.data ? `${agentSpan.error.message}: ${safeStringify(agentSpan.error.data, { maxLength: MAX_ERROR_DATA_LEN })}` : agentSpan.error.message;
|
|
10333
10408
|
span2.setStatus({ code: SpanStatusCode.ERROR, message: errorMsg });
|
|
10334
10409
|
span2.recordException(new Error(agentSpan.error.message));
|
|
10335
10410
|
this._traceErrors.add(agentSpan.traceId);
|
|
@@ -10983,6 +11058,131 @@ function getTraceId(span2) {
|
|
|
10983
11058
|
return "";
|
|
10984
11059
|
}
|
|
10985
11060
|
}
|
|
11061
|
+
function getSpanId(span2) {
|
|
11062
|
+
try {
|
|
11063
|
+
const spanId = span2.spanContext().spanId;
|
|
11064
|
+
return typeof spanId === "string" && spanId ? spanId : null;
|
|
11065
|
+
} catch {
|
|
11066
|
+
return null;
|
|
11067
|
+
}
|
|
11068
|
+
}
|
|
11069
|
+
function normalizeParent(parent) {
|
|
11070
|
+
if (!parent) {
|
|
11071
|
+
return void 0;
|
|
11072
|
+
}
|
|
11073
|
+
if (!parent.spanId || parent.spanId === INVALID_SPAN_ID) {
|
|
11074
|
+
return void 0;
|
|
11075
|
+
}
|
|
11076
|
+
return parent;
|
|
11077
|
+
}
|
|
11078
|
+
function findRootSpansBlocked(spans, parentsOfSpansBlockedByName) {
|
|
11079
|
+
const candidates = collectRootBlockCandidates(spans);
|
|
11080
|
+
if (candidates.size === 0) {
|
|
11081
|
+
return { rootConnectedIds: /* @__PURE__ */ new Set(), parentsOfRootSpansBlocked: /* @__PURE__ */ new Map() };
|
|
11082
|
+
}
|
|
11083
|
+
if (parentsOfSpansBlockedByName) {
|
|
11084
|
+
for (const [spanId, parentCtx] of parentsOfSpansBlockedByName) {
|
|
11085
|
+
if (!candidates.has(spanId)) {
|
|
11086
|
+
candidates.set(spanId, parentCtx);
|
|
11087
|
+
}
|
|
11088
|
+
}
|
|
11089
|
+
}
|
|
11090
|
+
const rootConnectedIds = findRootConnectedCandidates(spans, candidates);
|
|
11091
|
+
const parentsOfRootSpansBlocked = /* @__PURE__ */ new Map();
|
|
11092
|
+
for (const spanId of rootConnectedIds) {
|
|
11093
|
+
parentsOfRootSpansBlocked.set(spanId, candidates.get(spanId));
|
|
11094
|
+
}
|
|
11095
|
+
return { rootConnectedIds, parentsOfRootSpansBlocked };
|
|
11096
|
+
}
|
|
11097
|
+
function collectRootBlockCandidates(spans) {
|
|
11098
|
+
const inBatch = /* @__PURE__ */ new Map();
|
|
11099
|
+
const parentIds = /* @__PURE__ */ new Set();
|
|
11100
|
+
for (const span2 of spans) {
|
|
11101
|
+
const spanId = getSpanId(span2);
|
|
11102
|
+
if (isRootBlockCandidate(span2) && spanId !== null && spanId !== INVALID_SPAN_ID) {
|
|
11103
|
+
inBatch.set(spanId, normalizeParent(span2.parentSpanContext));
|
|
11104
|
+
}
|
|
11105
|
+
const parent = span2.parentSpanContext;
|
|
11106
|
+
const parentId = parent?.spanId;
|
|
11107
|
+
if (parentId && parentId !== INVALID_SPAN_ID) {
|
|
11108
|
+
parentIds.add(parentId);
|
|
11109
|
+
}
|
|
11110
|
+
}
|
|
11111
|
+
const unresolvedParents = /* @__PURE__ */ new Set();
|
|
11112
|
+
for (const parentId of parentIds) {
|
|
11113
|
+
if (!inBatch.has(parentId)) {
|
|
11114
|
+
unresolvedParents.add(parentId);
|
|
11115
|
+
}
|
|
11116
|
+
}
|
|
11117
|
+
if (!rootBlockCandidatesContains(unresolvedParents)) {
|
|
11118
|
+
return inBatch;
|
|
11119
|
+
}
|
|
11120
|
+
const candidates = getRootBlockCandidatesFor(unresolvedParents);
|
|
11121
|
+
for (const [spanId, parentCtx] of inBatch) {
|
|
11122
|
+
candidates.set(spanId, parentCtx);
|
|
11123
|
+
}
|
|
11124
|
+
return candidates;
|
|
11125
|
+
}
|
|
11126
|
+
function findRootConnectedCandidates(spans, candidates) {
|
|
11127
|
+
const memo = /* @__PURE__ */ new Map();
|
|
11128
|
+
const rootConnectedIds = /* @__PURE__ */ new Set();
|
|
11129
|
+
const resolvesToRoot = (startId) => {
|
|
11130
|
+
const walkedIds = [];
|
|
11131
|
+
const seenIds = /* @__PURE__ */ new Set();
|
|
11132
|
+
let currentId = startId;
|
|
11133
|
+
let reachesRoot = false;
|
|
11134
|
+
while (true) {
|
|
11135
|
+
const memoized = memo.get(currentId);
|
|
11136
|
+
if (memoized !== void 0) {
|
|
11137
|
+
reachesRoot = memoized;
|
|
11138
|
+
break;
|
|
11139
|
+
}
|
|
11140
|
+
if (!candidates.has(currentId)) {
|
|
11141
|
+
reachesRoot = false;
|
|
11142
|
+
break;
|
|
11143
|
+
}
|
|
11144
|
+
if (seenIds.has(currentId)) {
|
|
11145
|
+
reachesRoot = false;
|
|
11146
|
+
break;
|
|
11147
|
+
}
|
|
11148
|
+
walkedIds.push(currentId);
|
|
11149
|
+
seenIds.add(currentId);
|
|
11150
|
+
const parentCtx = candidates.get(currentId);
|
|
11151
|
+
if (!parentCtx) {
|
|
11152
|
+
reachesRoot = true;
|
|
11153
|
+
break;
|
|
11154
|
+
}
|
|
11155
|
+
if (parentCtx.isRemote) {
|
|
11156
|
+
reachesRoot = false;
|
|
11157
|
+
break;
|
|
11158
|
+
}
|
|
11159
|
+
const parentId = parentCtx.spanId;
|
|
11160
|
+
if (!parentId || parentId === INVALID_SPAN_ID) {
|
|
11161
|
+
reachesRoot = true;
|
|
11162
|
+
break;
|
|
11163
|
+
}
|
|
11164
|
+
currentId = parentId;
|
|
11165
|
+
}
|
|
11166
|
+
for (const spanId of walkedIds) {
|
|
11167
|
+
memo.set(spanId, reachesRoot);
|
|
11168
|
+
if (reachesRoot) {
|
|
11169
|
+
rootConnectedIds.add(spanId);
|
|
11170
|
+
}
|
|
11171
|
+
}
|
|
11172
|
+
return reachesRoot;
|
|
11173
|
+
};
|
|
11174
|
+
for (const span2 of spans) {
|
|
11175
|
+
const spanId = getSpanId(span2);
|
|
11176
|
+
if (spanId !== null && spanId !== INVALID_SPAN_ID) {
|
|
11177
|
+
resolvesToRoot(spanId);
|
|
11178
|
+
}
|
|
11179
|
+
const parentId = span2.parentSpanContext?.spanId;
|
|
11180
|
+
if (parentId && parentId !== INVALID_SPAN_ID) {
|
|
11181
|
+
resolvesToRoot(parentId);
|
|
11182
|
+
}
|
|
11183
|
+
}
|
|
11184
|
+
return rootConnectedIds;
|
|
11185
|
+
}
|
|
10986
11186
|
|
|
10987
11187
|
// src/exporters/filteringSpanExporter.ts
|
|
10988
11188
|
var ReparentedSpan = class {
|
|
@@ -11055,63 +11255,139 @@ var _FilteringSpanExporter = class _FilteringSpanExporter {
|
|
|
11055
11255
|
this.localPatternCache = /* @__PURE__ */ new Map();
|
|
11056
11256
|
this.compiled = compilePatterns(globalPatterns);
|
|
11057
11257
|
}
|
|
11258
|
+
/**
|
|
11259
|
+
* Filter `spans`, reparent survivors, and forward them to the wrapped exporter.
|
|
11260
|
+
*
|
|
11261
|
+
* While a trial/quota block is active the whole batch is dropped and its trace
|
|
11262
|
+
* ids are remembered so their later spans are dropped too. Otherwise the batch
|
|
11263
|
+
* is classified into name/local drops and root-instrument drops, the survivors
|
|
11264
|
+
* are reparented past any dropped ancestor, and only they are forwarded.
|
|
11265
|
+
*/
|
|
11058
11266
|
export(spans, resultCallback) {
|
|
11059
11267
|
if (isTrialBlocked()) {
|
|
11060
|
-
|
|
11061
|
-
const traceId = getTraceId(span2);
|
|
11062
|
-
if (traceId) addBlockedTraceId(traceId);
|
|
11063
|
-
}
|
|
11268
|
+
this.recordBlockedTraceIds(spans);
|
|
11064
11269
|
resultCallback({ code: ExportResultCode.SUCCESS });
|
|
11065
11270
|
return;
|
|
11066
11271
|
}
|
|
11067
|
-
const filtered = [];
|
|
11068
|
-
const batchBlockedMap = /* @__PURE__ */ new Map();
|
|
11069
11272
|
const localBlockedSnapshot = this.localBlockedMap ? new Map(this.localBlockedMap) : void 0;
|
|
11273
|
+
const parentsOfSpansBlockedByName = this.findSpansBlockedByName(spans);
|
|
11274
|
+
const { rootConnectedIds: rootSpansBlocked, parentsOfRootSpansBlocked } = findRootSpansBlocked(spans, parentsOfSpansBlockedByName);
|
|
11275
|
+
const allBlockedSpanIds = /* @__PURE__ */ new Set([
|
|
11276
|
+
...parentsOfSpansBlockedByName.keys(),
|
|
11277
|
+
...rootSpansBlocked
|
|
11278
|
+
]);
|
|
11279
|
+
const survivingSpans = this.collectSurvivors(spans, allBlockedSpanIds);
|
|
11280
|
+
const reparentMap = this.buildReparentMap(
|
|
11281
|
+
parentsOfRootSpansBlocked,
|
|
11282
|
+
parentsOfSpansBlockedByName,
|
|
11283
|
+
localBlockedSnapshot
|
|
11284
|
+
);
|
|
11285
|
+
if (reparentMap.size > 0) {
|
|
11286
|
+
this.reparentSpans(survivingSpans, reparentMap);
|
|
11287
|
+
}
|
|
11288
|
+
this.evictRememberedIfNeeded();
|
|
11289
|
+
if (survivingSpans.length === 0) {
|
|
11290
|
+
resultCallback({ code: ExportResultCode.SUCCESS });
|
|
11291
|
+
return;
|
|
11292
|
+
}
|
|
11293
|
+
this.exporter.export(survivingSpans, resultCallback);
|
|
11294
|
+
}
|
|
11295
|
+
shutdown() {
|
|
11296
|
+
this.rememberedBlockedParentMap.clear();
|
|
11297
|
+
this.localPatternCache.clear();
|
|
11298
|
+
return this.exporter.shutdown();
|
|
11299
|
+
}
|
|
11300
|
+
forceFlush() {
|
|
11301
|
+
return this.exporter.forceFlush?.() ?? Promise.resolve();
|
|
11302
|
+
}
|
|
11303
|
+
/**
|
|
11304
|
+
* Remember the trace ids seen during a block so their later spans are dropped
|
|
11305
|
+
* too, even after the block expires.
|
|
11306
|
+
*/
|
|
11307
|
+
recordBlockedTraceIds(spans) {
|
|
11308
|
+
for (const span2 of spans) {
|
|
11309
|
+
const traceId = getTraceId(span2);
|
|
11310
|
+
if (traceId) addBlockedTraceId(traceId);
|
|
11311
|
+
}
|
|
11312
|
+
}
|
|
11313
|
+
/**
|
|
11314
|
+
* Find the spans dropped unconditionally by a global or local name rule.
|
|
11315
|
+
*
|
|
11316
|
+
* Trace-blocked spans are skipped entirely (dropped without reparenting). Each
|
|
11317
|
+
* dropped span is also recorded in the cross-batch remembered map so a child
|
|
11318
|
+
* arriving in a later batch can still be reparented past it. The returned map
|
|
11319
|
+
* feeds both the root-connected candidate walk — as transparent dropped
|
|
11320
|
+
* ancestors — and the reparent map.
|
|
11321
|
+
*
|
|
11322
|
+
* @returns A `{droppedSpanId -> normalizedParent}` map for the name/locally
|
|
11323
|
+
* blocked spans in this batch.
|
|
11324
|
+
*/
|
|
11325
|
+
findSpansBlockedByName(spans) {
|
|
11326
|
+
const parentMap = /* @__PURE__ */ new Map();
|
|
11070
11327
|
for (const span2 of spans) {
|
|
11071
11328
|
const traceId = getTraceId(span2);
|
|
11072
11329
|
if (traceId && isTraceIdBlocked(traceId)) continue;
|
|
11073
11330
|
const name = span2.name;
|
|
11074
11331
|
const globallyBlocked = matchesAnyPattern(name, this.compiled);
|
|
11075
|
-
|
|
11076
|
-
const locallyBlocked = localPatterns.length > 0 && matchesAnyPattern(name, this.getCompiledLocalPatterns(localPatterns)) || this.hasLocalBlockFlag(span2);
|
|
11077
|
-
if (!globallyBlocked && !locallyBlocked) {
|
|
11078
|
-
filtered.push(span2);
|
|
11079
|
-
continue;
|
|
11080
|
-
}
|
|
11332
|
+
if (!globallyBlocked && !this.isLocallyBlocked(span2, name)) continue;
|
|
11081
11333
|
const spanId = span2.spanContext().spanId;
|
|
11082
|
-
const parentCtx = span2.parentSpanContext;
|
|
11083
|
-
|
|
11334
|
+
const parentCtx = normalizeParent(span2.parentSpanContext);
|
|
11335
|
+
parentMap.set(spanId, parentCtx);
|
|
11084
11336
|
this.rememberedBlockedParentMap.set(spanId, parentCtx);
|
|
11085
11337
|
}
|
|
11086
|
-
|
|
11338
|
+
return parentMap;
|
|
11339
|
+
}
|
|
11340
|
+
/**
|
|
11341
|
+
* Check whether `span` is blocked by its per-span local rules — either its
|
|
11342
|
+
* name matches a local pattern or it carries the local-block flag.
|
|
11343
|
+
*/
|
|
11344
|
+
isLocallyBlocked(span2, name) {
|
|
11345
|
+
const localPatterns = this.readLocalBlockPatterns(span2);
|
|
11346
|
+
if (localPatterns.length > 0 && matchesAnyPattern(name, this.getCompiledLocalPatterns(localPatterns))) {
|
|
11347
|
+
return true;
|
|
11348
|
+
}
|
|
11349
|
+
return this.hasLocalBlockFlag(span2);
|
|
11350
|
+
}
|
|
11351
|
+
/**
|
|
11352
|
+
* Return the spans that survive filtering: not trace-blocked and not in
|
|
11353
|
+
* `allBlockedSpanIds` (name/local drops or the root-instrument policy).
|
|
11354
|
+
*/
|
|
11355
|
+
collectSurvivors(spans, allBlockedSpanIds) {
|
|
11356
|
+
const survivingSpans = [];
|
|
11357
|
+
for (const span2 of spans) {
|
|
11358
|
+
const traceId = getTraceId(span2);
|
|
11359
|
+
if (traceId && isTraceIdBlocked(traceId)) continue;
|
|
11360
|
+
if (allBlockedSpanIds.has(span2.spanContext().spanId)) continue;
|
|
11361
|
+
survivingSpans.push(span2);
|
|
11362
|
+
}
|
|
11363
|
+
return survivingSpans;
|
|
11364
|
+
}
|
|
11365
|
+
/**
|
|
11366
|
+
* Merge the cross-batch remembered map with this batch's dropped-parent maps.
|
|
11367
|
+
*
|
|
11368
|
+
* Ordering matters — later wins on conflict: the remembered map and the
|
|
11369
|
+
* injected local-block snapshot are the base, overlaid by root-blocked
|
|
11370
|
+
* parents, then this batch's name/local blocks, so in-batch drops win.
|
|
11371
|
+
*
|
|
11372
|
+
* @returns The merged `{droppedSpanId -> parent}` map used for reparenting.
|
|
11373
|
+
*/
|
|
11374
|
+
buildReparentMap(parentsOfRootSpansBlocked, parentsOfSpansBlockedByName, localBlockedSnapshot) {
|
|
11375
|
+
const reparentMap = /* @__PURE__ */ new Map();
|
|
11087
11376
|
for (const [k, v] of this.rememberedBlockedParentMap) {
|
|
11088
|
-
|
|
11377
|
+
reparentMap.set(k, v);
|
|
11089
11378
|
}
|
|
11090
11379
|
if (localBlockedSnapshot) {
|
|
11091
11380
|
for (const [k, v] of localBlockedSnapshot) {
|
|
11092
|
-
|
|
11381
|
+
reparentMap.set(k, v);
|
|
11093
11382
|
}
|
|
11094
11383
|
}
|
|
11095
|
-
for (const [k, v] of
|
|
11096
|
-
|
|
11097
|
-
}
|
|
11098
|
-
if (merged.size > 0) {
|
|
11099
|
-
this.reparentBlockedChildren(filtered, merged);
|
|
11384
|
+
for (const [k, v] of parentsOfRootSpansBlocked) {
|
|
11385
|
+
reparentMap.set(k, v);
|
|
11100
11386
|
}
|
|
11101
|
-
|
|
11102
|
-
|
|
11103
|
-
resultCallback({ code: ExportResultCode.SUCCESS });
|
|
11104
|
-
return;
|
|
11387
|
+
for (const [k, v] of parentsOfSpansBlockedByName) {
|
|
11388
|
+
reparentMap.set(k, v);
|
|
11105
11389
|
}
|
|
11106
|
-
|
|
11107
|
-
}
|
|
11108
|
-
shutdown() {
|
|
11109
|
-
this.rememberedBlockedParentMap.clear();
|
|
11110
|
-
this.localPatternCache.clear();
|
|
11111
|
-
return this.exporter.shutdown();
|
|
11112
|
-
}
|
|
11113
|
-
forceFlush() {
|
|
11114
|
-
return this.exporter.forceFlush?.() ?? Promise.resolve();
|
|
11390
|
+
return reparentMap;
|
|
11115
11391
|
}
|
|
11116
11392
|
getCompiledLocalPatterns(patterns) {
|
|
11117
11393
|
const key = patterns.join("\0");
|
|
@@ -11139,23 +11415,30 @@ var _FilteringSpanExporter = class _FilteringSpanExporter {
|
|
|
11139
11415
|
this.rememberedBlockedParentMap.delete(key);
|
|
11140
11416
|
}
|
|
11141
11417
|
}
|
|
11142
|
-
|
|
11418
|
+
/**
|
|
11419
|
+
* Read the per-span local-block patterns set by `LocalFilteringSpanProcessor`,
|
|
11420
|
+
* or an empty list when none are set.
|
|
11421
|
+
*/
|
|
11422
|
+
readLocalBlockPatterns(span2) {
|
|
11143
11423
|
const value = span2.attributes?.["netra.local_blocked_spans"];
|
|
11144
11424
|
if (Array.isArray(value) && value.every((v) => typeof v === "string")) {
|
|
11145
11425
|
return value.filter((v) => v !== "");
|
|
11146
11426
|
}
|
|
11147
11427
|
return [];
|
|
11148
11428
|
}
|
|
11429
|
+
/** Check whether the processor explicitly flagged `span` as locally blocked. */
|
|
11149
11430
|
hasLocalBlockFlag(span2) {
|
|
11150
11431
|
return span2.attributes?.["netra.local_blocked"] === true;
|
|
11151
11432
|
}
|
|
11152
11433
|
/**
|
|
11153
|
-
*
|
|
11154
|
-
* with a ReparentedSpan pointing to the nearest non-blocked ancestor.
|
|
11434
|
+
* Reparent each span past any dropped ancestor onto its first surviving one.
|
|
11155
11435
|
*
|
|
11156
|
-
*
|
|
11436
|
+
* Walks the chain of dropped parents (following `blockedMap`) until a surviving
|
|
11437
|
+
* parent — or `undefined` (promote to root) — is reached, then wraps the span
|
|
11438
|
+
* in a `ReparentedSpan` pointing there. A cycle guard (visited set) prevents
|
|
11439
|
+
* infinite loops in malformed traces.
|
|
11157
11440
|
*/
|
|
11158
|
-
|
|
11441
|
+
reparentSpans(spans, blockedMap) {
|
|
11159
11442
|
for (let i = 0; i < spans.length; i++) {
|
|
11160
11443
|
const span2 = spans[i];
|
|
11161
11444
|
let parent = span2.parentSpanContext;
|
|
@@ -11756,24 +12039,22 @@ function addCustomSpanProcessors(tracerProvider, config, rootInstrumentNames) {
|
|
|
11756
12039
|
);
|
|
11757
12040
|
provider.addSpanProcessor(rootFilterProcessor);
|
|
11758
12041
|
}
|
|
12042
|
+
if (config.enableScrubbing) {
|
|
12043
|
+
const scrubbingProcessor = new ScrubbingSpanProcessor();
|
|
12044
|
+
provider.addSpanProcessor(scrubbingProcessor);
|
|
12045
|
+
}
|
|
12046
|
+
const serializationProcessor = new SerializationSpanProcessor();
|
|
12047
|
+
provider.addSpanProcessor(serializationProcessor);
|
|
12048
|
+
const spanIOProcessor = new SpanIOProcessor();
|
|
12049
|
+
provider.addSpanProcessor(spanIOProcessor);
|
|
11759
12050
|
const instrumentationProcessor = new InstrumentationSpanProcessor();
|
|
11760
12051
|
provider.addSpanProcessor(instrumentationProcessor);
|
|
11761
12052
|
const sessionProcessor = new SessionSpanProcessor(config.environment);
|
|
11762
12053
|
provider.addSpanProcessor(sessionProcessor);
|
|
11763
|
-
const spanIOProcessor = new SpanIOProcessor();
|
|
11764
|
-
provider.addSpanProcessor(spanIOProcessor);
|
|
11765
12054
|
const llmTraceProcessor = new LlmTraceIdentifierSpanProcessor();
|
|
11766
12055
|
provider.addSpanProcessor(llmTraceProcessor);
|
|
11767
12056
|
const rootSpanProcessor = new RootSpanProcessor();
|
|
11768
12057
|
provider.addSpanProcessor(rootSpanProcessor);
|
|
11769
|
-
if (config.enableScrubbing) {
|
|
11770
|
-
const scrubbingProcessor = new ScrubbingSpanProcessor();
|
|
11771
|
-
provider.addSpanProcessor(scrubbingProcessor);
|
|
11772
|
-
}
|
|
11773
|
-
const sizeLimitProcessor = new AttributeSizeLimitProcessor(
|
|
11774
|
-
Config.SPAN_ATTRIBUTE_MAX_SIZE
|
|
11775
|
-
);
|
|
11776
|
-
provider.addSpanProcessor(sizeLimitProcessor);
|
|
11777
12058
|
Logger.debug("Custom span processors registered successfully");
|
|
11778
12059
|
return provider;
|
|
11779
12060
|
} catch (e) {
|
|
@@ -11970,7 +12251,7 @@ async function processFiles(files) {
|
|
|
11970
12251
|
return null;
|
|
11971
12252
|
}
|
|
11972
12253
|
const timeoutMs = _getFileDownloadTimeout();
|
|
11973
|
-
const limit =
|
|
12254
|
+
const limit = pLimit2(MAX_FILE_DOWNLOAD_WORKERS);
|
|
11974
12255
|
const controller = new AbortController();
|
|
11975
12256
|
const downloadPromises = files.map(
|
|
11976
12257
|
(file) => limit(() => _downloadSingleFile(file, timeoutMs, controller.signal))
|
|
@@ -11983,9 +12264,9 @@ async function processFiles(files) {
|
|
|
11983
12264
|
throw error;
|
|
11984
12265
|
}
|
|
11985
12266
|
}
|
|
11986
|
-
async function executeTask2(task2, message, sessionId, rawFiles) {
|
|
12267
|
+
async function executeTask2(task2, message, sessionId, rawFiles, setupContext) {
|
|
11987
12268
|
const processedFiles = rawFiles && rawFiles.length > 0 ? await processFiles(rawFiles) : null;
|
|
11988
|
-
const result = task2.run(message, sessionId, processedFiles);
|
|
12269
|
+
const result = task2.run(message, sessionId, processedFiles, setupContext);
|
|
11989
12270
|
const resolvedResult = result instanceof Promise ? await result : result;
|
|
11990
12271
|
if (typeof resolvedResult === "object" && resolvedResult !== null && "message" in resolvedResult && "sessionId" in resolvedResult) {
|
|
11991
12272
|
return [resolvedResult.message, resolvedResult.sessionId];
|
|
@@ -12073,44 +12354,76 @@ var SimulationHttpClient = class {
|
|
|
12073
12354
|
return timeout * 1e3;
|
|
12074
12355
|
}
|
|
12075
12356
|
/**
|
|
12076
|
-
*
|
|
12357
|
+
* Initialize a simulation run without generating first user messages.
|
|
12358
|
+
*
|
|
12359
|
+
* Used in the two-phase flow so that beforeAll/before hooks can run
|
|
12360
|
+
* before any LLM spend.
|
|
12077
12361
|
*/
|
|
12078
|
-
async
|
|
12362
|
+
async initializeRun(name, datasetId, context17, hooksMeta) {
|
|
12079
12363
|
if (!this.client) {
|
|
12080
12364
|
Logger.error(`${LOG_PREFIX5}: Client not initialized`);
|
|
12081
12365
|
return null;
|
|
12082
12366
|
}
|
|
12083
12367
|
try {
|
|
12084
|
-
const url = "/evaluations/test_run/multi-turn";
|
|
12368
|
+
const url = "/evaluations/test_run/multi-turn/initialize";
|
|
12085
12369
|
const payload = {
|
|
12086
12370
|
name,
|
|
12087
12371
|
datasetId,
|
|
12088
12372
|
context: context17 || {}
|
|
12089
12373
|
};
|
|
12374
|
+
if (hooksMeta) {
|
|
12375
|
+
payload.lifecycleHooks = hooksMeta;
|
|
12376
|
+
}
|
|
12090
12377
|
const response = await this.client.post(url, payload);
|
|
12091
12378
|
const data = response.data;
|
|
12092
12379
|
const responseData = data.data || {};
|
|
12093
|
-
const
|
|
12094
|
-
if (
|
|
12095
|
-
Logger.warn(`${LOG_PREFIX5}: No
|
|
12380
|
+
const items = responseData.items || [];
|
|
12381
|
+
if (items.length === 0) {
|
|
12382
|
+
Logger.warn(`${LOG_PREFIX5}: No items returned from initialize_run`);
|
|
12096
12383
|
return null;
|
|
12097
12384
|
}
|
|
12098
12385
|
const runId = responseData.id || "";
|
|
12099
|
-
const simulationItems = userMessages.map(
|
|
12100
|
-
(msg) => ({
|
|
12101
|
-
runItemId: msg.testRunItemId || "",
|
|
12102
|
-
message: msg.userMessage || "",
|
|
12103
|
-
turnId: msg.turnId || "",
|
|
12104
|
-
files: parseFiles(msg.attachments)
|
|
12105
|
-
})
|
|
12106
|
-
);
|
|
12107
12386
|
return {
|
|
12108
12387
|
runId,
|
|
12109
|
-
|
|
12388
|
+
items: items.map((item) => ({
|
|
12389
|
+
runItemId: item.testRunItemId || "",
|
|
12390
|
+
datasetItemId: item.datasetItemId || ""
|
|
12391
|
+
}))
|
|
12392
|
+
};
|
|
12393
|
+
} catch (error) {
|
|
12394
|
+
const errorMsg = this._extractErrorMessage(error);
|
|
12395
|
+
Logger.error(`${LOG_PREFIX5}: Failed to initialize run:`, errorMsg);
|
|
12396
|
+
return null;
|
|
12397
|
+
}
|
|
12398
|
+
}
|
|
12399
|
+
/**
|
|
12400
|
+
* Generate the first user message for a single test run item.
|
|
12401
|
+
*
|
|
12402
|
+
* Used in the two-phase flow after hooks have been executed.
|
|
12403
|
+
*/
|
|
12404
|
+
async generateFirstTurn(runId, runItemId) {
|
|
12405
|
+
if (!this.client) {
|
|
12406
|
+
Logger.error(`${LOG_PREFIX5}: Client not initialized`);
|
|
12407
|
+
return null;
|
|
12408
|
+
}
|
|
12409
|
+
try {
|
|
12410
|
+
const url = `/evaluations/run/${runId}/item/${runItemId}/first-turn`;
|
|
12411
|
+
const response = await this.client.post(url, {});
|
|
12412
|
+
const data = response.data;
|
|
12413
|
+
const responseData = data.data || {};
|
|
12414
|
+
return {
|
|
12415
|
+
runItemId,
|
|
12416
|
+
datasetItemId: responseData.datasetItemId || "",
|
|
12417
|
+
message: responseData.userMessage || "",
|
|
12418
|
+
turnId: responseData.turnId || "",
|
|
12419
|
+
files: parseFiles(responseData.attachments)
|
|
12110
12420
|
};
|
|
12111
12421
|
} catch (error) {
|
|
12112
12422
|
const errorMsg = this._extractErrorMessage(error);
|
|
12113
|
-
Logger.error(
|
|
12423
|
+
Logger.error(
|
|
12424
|
+
`${LOG_PREFIX5}: Failed to generate first turn for item ${runItemId}:`,
|
|
12425
|
+
errorMsg
|
|
12426
|
+
);
|
|
12114
12427
|
return null;
|
|
12115
12428
|
}
|
|
12116
12429
|
}
|
|
@@ -12162,14 +12475,14 @@ var SimulationHttpClient = class {
|
|
|
12162
12475
|
/**
|
|
12163
12476
|
* Report a task execution failure to the backend.
|
|
12164
12477
|
*/
|
|
12165
|
-
async reportFailure(runId, runItemId, error) {
|
|
12478
|
+
async reportFailure(runId, runItemId, error, status = "failed") {
|
|
12166
12479
|
if (!this.client) {
|
|
12167
12480
|
Logger.error(`${LOG_PREFIX5}: Client not initialized`);
|
|
12168
12481
|
return;
|
|
12169
12482
|
}
|
|
12170
12483
|
try {
|
|
12171
12484
|
const url = `/evaluations/run/${runId}/item/${runItemId}/status`;
|
|
12172
|
-
const payload = { status
|
|
12485
|
+
const payload = { status, failureReason: error };
|
|
12173
12486
|
await this.client.patch(url, payload);
|
|
12174
12487
|
Logger.info(`${LOG_PREFIX5}: Reported failure - ${error}`);
|
|
12175
12488
|
} catch (err) {
|
|
@@ -12224,8 +12537,144 @@ var SimulationHttpClient = class {
|
|
|
12224
12537
|
}
|
|
12225
12538
|
};
|
|
12226
12539
|
|
|
12227
|
-
// src/simulation/
|
|
12540
|
+
// src/simulation/hooks.ts
|
|
12228
12541
|
var LOG_PREFIX6 = "netra.simulation";
|
|
12542
|
+
function describeHooks(hooks) {
|
|
12543
|
+
const descFn = (fn) => {
|
|
12544
|
+
if (!fn) return null;
|
|
12545
|
+
const description = typeof fn.description === "string" ? String(fn.description).slice(0, 200) : null;
|
|
12546
|
+
return {
|
|
12547
|
+
configured: true,
|
|
12548
|
+
name: fn.name || null,
|
|
12549
|
+
description
|
|
12550
|
+
};
|
|
12551
|
+
};
|
|
12552
|
+
const payload = {};
|
|
12553
|
+
const beforeAllDesc = descFn(hooks.beforeAll);
|
|
12554
|
+
const beforeEachDesc = descFn(hooks.beforeEach);
|
|
12555
|
+
const afterEachDesc = descFn(hooks.afterEach);
|
|
12556
|
+
const afterAllDesc = descFn(hooks.afterAll);
|
|
12557
|
+
if (beforeAllDesc) payload.beforeAll = beforeAllDesc;
|
|
12558
|
+
if (beforeEachDesc) payload.beforeEach = beforeEachDesc;
|
|
12559
|
+
if (afterEachDesc) payload.afterEach = afterEachDesc;
|
|
12560
|
+
if (afterAllDesc) payload.afterAll = afterAllDesc;
|
|
12561
|
+
const itemIds = /* @__PURE__ */ new Set([
|
|
12562
|
+
...Object.keys(hooks.before || {}),
|
|
12563
|
+
...Object.keys(hooks.after || {})
|
|
12564
|
+
]);
|
|
12565
|
+
if (itemIds.size > 0) {
|
|
12566
|
+
const items = [];
|
|
12567
|
+
for (const itemId of itemIds) {
|
|
12568
|
+
const entry = { datasetItemId: itemId };
|
|
12569
|
+
const beforeDesc = descFn(hooks.before?.[itemId]);
|
|
12570
|
+
const afterDesc = descFn(hooks.after?.[itemId]);
|
|
12571
|
+
if (beforeDesc) entry.before = beforeDesc;
|
|
12572
|
+
if (afterDesc) entry.after = afterDesc;
|
|
12573
|
+
if (entry.before || entry.after) {
|
|
12574
|
+
items.push(entry);
|
|
12575
|
+
}
|
|
12576
|
+
}
|
|
12577
|
+
if (items.length > 0) {
|
|
12578
|
+
payload.items = items;
|
|
12579
|
+
}
|
|
12580
|
+
}
|
|
12581
|
+
return payload;
|
|
12582
|
+
}
|
|
12583
|
+
async function runBeforeAll(hooks) {
|
|
12584
|
+
if (!hooks?.beforeAll) return null;
|
|
12585
|
+
Logger.info(`${LOG_PREFIX6}: running beforeAll hook`);
|
|
12586
|
+
const result = await hooks.beforeAll();
|
|
12587
|
+
if (result !== null && result !== void 0 && typeof result !== "object") {
|
|
12588
|
+
Logger.warn(
|
|
12589
|
+
`${LOG_PREFIX6}: beforeAll returned ${typeof result} (expected object or null); ignoring value`
|
|
12590
|
+
);
|
|
12591
|
+
return null;
|
|
12592
|
+
}
|
|
12593
|
+
return result ?? null;
|
|
12594
|
+
}
|
|
12595
|
+
async function runBefore(hooks, datasetItemId, sharedContext) {
|
|
12596
|
+
if (hooks?.before && datasetItemId in hooks.before) {
|
|
12597
|
+
Logger.info(
|
|
12598
|
+
`${LOG_PREFIX6}: running before hook for datasetItemId=${datasetItemId}`
|
|
12599
|
+
);
|
|
12600
|
+
const itemHook = hooks.before[datasetItemId];
|
|
12601
|
+
const result = await itemHook(sharedContext);
|
|
12602
|
+
const base = { ...sharedContext || {} };
|
|
12603
|
+
if (result !== null && result !== void 0) {
|
|
12604
|
+
if (typeof result === "object") {
|
|
12605
|
+
Object.assign(base, result);
|
|
12606
|
+
} else {
|
|
12607
|
+
Logger.warn(
|
|
12608
|
+
`${LOG_PREFIX6}: before hook returned ${typeof result} (expected object or null); ignoring value`
|
|
12609
|
+
);
|
|
12610
|
+
}
|
|
12611
|
+
}
|
|
12612
|
+
return Object.keys(base).length > 0 ? base : null;
|
|
12613
|
+
}
|
|
12614
|
+
return sharedContext;
|
|
12615
|
+
}
|
|
12616
|
+
async function runBeforeEach(hooks, datasetItemId, sharedContext) {
|
|
12617
|
+
if (!hooks?.beforeEach) return sharedContext;
|
|
12618
|
+
Logger.info(
|
|
12619
|
+
`${LOG_PREFIX6}: running beforeEach hook for datasetItemId=${datasetItemId}`
|
|
12620
|
+
);
|
|
12621
|
+
const result = await hooks.beforeEach(sharedContext);
|
|
12622
|
+
const base = { ...sharedContext || {} };
|
|
12623
|
+
if (result !== null && result !== void 0) {
|
|
12624
|
+
if (typeof result === "object") {
|
|
12625
|
+
Object.assign(base, result);
|
|
12626
|
+
} else {
|
|
12627
|
+
Logger.warn(
|
|
12628
|
+
`${LOG_PREFIX6}: beforeEach hook returned ${typeof result} (expected object or null); ignoring value`
|
|
12629
|
+
);
|
|
12630
|
+
}
|
|
12631
|
+
}
|
|
12632
|
+
return Object.keys(base).length > 0 ? base : null;
|
|
12633
|
+
}
|
|
12634
|
+
async function runAfter(hooks, datasetItemId, itemResult, setupContext) {
|
|
12635
|
+
if (hooks?.after && datasetItemId in hooks.after) {
|
|
12636
|
+
Logger.info(
|
|
12637
|
+
`${LOG_PREFIX6}: running after hook for datasetItemId=${datasetItemId}`
|
|
12638
|
+
);
|
|
12639
|
+
try {
|
|
12640
|
+
await hooks.after[datasetItemId](itemResult, setupContext);
|
|
12641
|
+
} catch (error) {
|
|
12642
|
+
Logger.warn(
|
|
12643
|
+
`${LOG_PREFIX6}: after hook raised an exception for datasetItemId=${datasetItemId} (ignored):`,
|
|
12644
|
+
error
|
|
12645
|
+
);
|
|
12646
|
+
}
|
|
12647
|
+
}
|
|
12648
|
+
}
|
|
12649
|
+
async function runAfterEach(hooks, datasetItemId, itemResult, setupContext) {
|
|
12650
|
+
if (!hooks?.afterEach) return;
|
|
12651
|
+
Logger.info(
|
|
12652
|
+
`${LOG_PREFIX6}: running afterEach hook for datasetItemId=${datasetItemId}`
|
|
12653
|
+
);
|
|
12654
|
+
try {
|
|
12655
|
+
await hooks.afterEach(itemResult, setupContext);
|
|
12656
|
+
} catch (error) {
|
|
12657
|
+
Logger.warn(
|
|
12658
|
+
`${LOG_PREFIX6}: afterEach hook raised an exception for datasetItemId=${datasetItemId} (ignored):`,
|
|
12659
|
+
error
|
|
12660
|
+
);
|
|
12661
|
+
}
|
|
12662
|
+
}
|
|
12663
|
+
async function runAfterAll(hooks, results, sharedContext) {
|
|
12664
|
+
if (!hooks?.afterAll) return;
|
|
12665
|
+
Logger.info(`${LOG_PREFIX6}: running afterAll hook`);
|
|
12666
|
+
try {
|
|
12667
|
+
await hooks.afterAll(results, sharedContext);
|
|
12668
|
+
} catch (error) {
|
|
12669
|
+
Logger.warn(
|
|
12670
|
+
`${LOG_PREFIX6}: afterAll hook raised an exception (ignored):`,
|
|
12671
|
+
error
|
|
12672
|
+
);
|
|
12673
|
+
}
|
|
12674
|
+
}
|
|
12675
|
+
|
|
12676
|
+
// src/simulation/api.ts
|
|
12677
|
+
var LOG_PREFIX7 = "netra.simulation";
|
|
12229
12678
|
var SPAN_NAME = "Netra.Simulation.TestRun";
|
|
12230
12679
|
var Simulation = class {
|
|
12231
12680
|
constructor(config) {
|
|
@@ -12235,6 +12684,12 @@ var Simulation = class {
|
|
|
12235
12684
|
/**
|
|
12236
12685
|
* Run a multi-turn conversation simulation.
|
|
12237
12686
|
*
|
|
12687
|
+
* Uses the two-phase API flow:
|
|
12688
|
+
* 1. initializeRun (no LLM cost) — with optional lifecycle hooks metadata
|
|
12689
|
+
* 2. beforeAll hook (if configured)
|
|
12690
|
+
* 3. Per-item: before hook -> generateFirstTurn -> conversation loop -> after hook
|
|
12691
|
+
* 4. afterAll hook (if configured)
|
|
12692
|
+
*
|
|
12238
12693
|
* @param options - Simulation configuration options
|
|
12239
12694
|
* @returns Dictionary with simulation results, or null on failure
|
|
12240
12695
|
*/
|
|
@@ -12244,19 +12699,26 @@ var Simulation = class {
|
|
|
12244
12699
|
datasetId,
|
|
12245
12700
|
task: task2,
|
|
12246
12701
|
context: context17,
|
|
12247
|
-
maxConcurrency = 5
|
|
12702
|
+
maxConcurrency = 5,
|
|
12703
|
+
hooks
|
|
12248
12704
|
} = options;
|
|
12249
12705
|
if (!validateSimulationInputs(datasetId, task2)) {
|
|
12250
12706
|
return null;
|
|
12251
12707
|
}
|
|
12252
12708
|
const startTime = Date.now();
|
|
12253
|
-
const
|
|
12254
|
-
|
|
12709
|
+
const hooksMeta = hooks ? describeHooks(hooks) : null;
|
|
12710
|
+
const initResult = await this._client.initializeRun(
|
|
12711
|
+
name,
|
|
12712
|
+
datasetId,
|
|
12713
|
+
context17,
|
|
12714
|
+
hooksMeta && Object.keys(hooksMeta).length > 0 ? hooksMeta : null
|
|
12715
|
+
);
|
|
12716
|
+
if (!initResult) {
|
|
12255
12717
|
return null;
|
|
12256
12718
|
}
|
|
12257
|
-
const { runId,
|
|
12258
|
-
if (!
|
|
12259
|
-
Logger.error(`${
|
|
12719
|
+
const { runId, items } = initResult;
|
|
12720
|
+
if (!items || items.length === 0) {
|
|
12721
|
+
Logger.error(`${LOG_PREFIX7}: No items returned from initialize_run`);
|
|
12260
12722
|
return null;
|
|
12261
12723
|
}
|
|
12262
12724
|
let interrupted = false;
|
|
@@ -12291,25 +12753,120 @@ var Simulation = class {
|
|
|
12291
12753
|
proc.once("uncaughtException", handleException);
|
|
12292
12754
|
proc.once("unhandledRejection", handleRejection);
|
|
12293
12755
|
}
|
|
12294
|
-
Logger.info(
|
|
12295
|
-
`${LOG_PREFIX6}: Starting simulation with ${simulationItems.length} items`
|
|
12296
|
-
);
|
|
12297
12756
|
try {
|
|
12298
|
-
|
|
12299
|
-
|
|
12300
|
-
|
|
12301
|
-
|
|
12302
|
-
|
|
12303
|
-
|
|
12304
|
-
|
|
12305
|
-
|
|
12306
|
-
|
|
12757
|
+
let sharedContext = null;
|
|
12758
|
+
if (hooks?.beforeAll) {
|
|
12759
|
+
try {
|
|
12760
|
+
sharedContext = await runBeforeAll(hooks);
|
|
12761
|
+
} catch (error) {
|
|
12762
|
+
const errorMsg = `beforeAll hook failed: ${error instanceof Error ? error.message : String(error)}`;
|
|
12763
|
+
Logger.error(`${LOG_PREFIX7}: ${errorMsg} \u2014 aborting run (no LLM spent)`);
|
|
12764
|
+
for (const item of items) {
|
|
12765
|
+
await this._client.reportFailure(
|
|
12766
|
+
runId,
|
|
12767
|
+
item.runItemId,
|
|
12768
|
+
errorMsg,
|
|
12769
|
+
"prescript_failed"
|
|
12770
|
+
);
|
|
12771
|
+
}
|
|
12772
|
+
const results = {
|
|
12773
|
+
success: false,
|
|
12774
|
+
completed: [],
|
|
12775
|
+
failed: items.map((item) => ({
|
|
12776
|
+
runItemId: item.runItemId,
|
|
12777
|
+
success: false,
|
|
12778
|
+
error: errorMsg
|
|
12779
|
+
})),
|
|
12780
|
+
totalItems: items.length
|
|
12781
|
+
};
|
|
12782
|
+
await runAfterAll(hooks, results, null);
|
|
12783
|
+
await this._client.postRunStatus(runId, "completed");
|
|
12784
|
+
return results;
|
|
12785
|
+
}
|
|
12786
|
+
}
|
|
12787
|
+
const setupContexts = /* @__PURE__ */ new Map();
|
|
12788
|
+
const simulationItems = [];
|
|
12789
|
+
const failedItems = [];
|
|
12790
|
+
const limit = pLimit2(Math.min(5, maxConcurrency));
|
|
12791
|
+
const setupPromises = items.map(
|
|
12792
|
+
(item) => limit(async () => {
|
|
12793
|
+
const { runItemId, datasetItemId } = item;
|
|
12794
|
+
const hasBeforeHook = hooks?.before && datasetItemId in hooks.before;
|
|
12795
|
+
const hasBeforeEachHook = !!hooks?.beforeEach;
|
|
12796
|
+
let setupContext = sharedContext;
|
|
12797
|
+
if (hasBeforeEachHook || hasBeforeHook) {
|
|
12798
|
+
try {
|
|
12799
|
+
setupContext = await runBeforeEach(hooks, datasetItemId, setupContext);
|
|
12800
|
+
setupContext = await runBefore(hooks, datasetItemId, setupContext);
|
|
12801
|
+
setupContexts.set(runItemId, setupContext);
|
|
12802
|
+
} catch (error) {
|
|
12803
|
+
const errorMsg = `before hook failed: ${error instanceof Error ? error.message : String(error)}`;
|
|
12804
|
+
Logger.error(`${LOG_PREFIX7}: ${errorMsg} for runItemId=${runItemId}`);
|
|
12805
|
+
await this._client.reportFailure(runId, runItemId, errorMsg, "prescript_failed");
|
|
12806
|
+
const itemResult = {
|
|
12807
|
+
runItemId,
|
|
12808
|
+
success: false,
|
|
12809
|
+
error: errorMsg
|
|
12810
|
+
};
|
|
12811
|
+
failedItems.push(itemResult);
|
|
12812
|
+
await runAfter(hooks, datasetItemId, itemResult, setupContext);
|
|
12813
|
+
await runAfterEach(hooks, datasetItemId, itemResult, setupContext);
|
|
12814
|
+
return;
|
|
12815
|
+
}
|
|
12816
|
+
} else {
|
|
12817
|
+
setupContexts.set(runItemId, setupContext);
|
|
12818
|
+
}
|
|
12819
|
+
const simItem = await this._client.generateFirstTurn(runId, runItemId);
|
|
12820
|
+
if (!simItem) {
|
|
12821
|
+
Logger.warn(`${LOG_PREFIX7}: Failed to generate first turn for item ${runItemId}, marking failed`);
|
|
12822
|
+
await this._client.reportFailure(runId, runItemId, "Failed to generate first user message");
|
|
12823
|
+
const itemResult = {
|
|
12824
|
+
runItemId,
|
|
12825
|
+
success: false,
|
|
12826
|
+
error: "Failed to generate first user message"
|
|
12827
|
+
};
|
|
12828
|
+
failedItems.push(itemResult);
|
|
12829
|
+
await runAfter(hooks, datasetItemId, itemResult, setupContexts.get(runItemId) ?? null);
|
|
12830
|
+
await runAfterEach(hooks, datasetItemId, itemResult, setupContexts.get(runItemId) ?? null);
|
|
12831
|
+
return;
|
|
12832
|
+
}
|
|
12833
|
+
simulationItems.push(simItem);
|
|
12834
|
+
})
|
|
12307
12835
|
);
|
|
12308
|
-
|
|
12309
|
-
|
|
12310
|
-
|
|
12311
|
-
|
|
12312
|
-
|
|
12836
|
+
await Promise.all(setupPromises);
|
|
12837
|
+
if (simulationItems.length === 0) {
|
|
12838
|
+
Logger.error(`${LOG_PREFIX7}: All items failed during setup/generation`);
|
|
12839
|
+
const results = {
|
|
12840
|
+
success: false,
|
|
12841
|
+
completed: [],
|
|
12842
|
+
failed: failedItems,
|
|
12843
|
+
totalItems: items.length
|
|
12844
|
+
};
|
|
12845
|
+
await runAfterAll(hooks, results, sharedContext);
|
|
12846
|
+
await this._client.postRunStatus(runId, "completed");
|
|
12847
|
+
return results;
|
|
12848
|
+
}
|
|
12849
|
+
Logger.info(`${LOG_PREFIX7}: Starting simulation with ${simulationItems.length} items`);
|
|
12850
|
+
try {
|
|
12851
|
+
const result = await this._runSimulationAsync(
|
|
12852
|
+
runId,
|
|
12853
|
+
simulationItems,
|
|
12854
|
+
task2,
|
|
12855
|
+
maxConcurrency,
|
|
12856
|
+
hooks,
|
|
12857
|
+
sharedContext,
|
|
12858
|
+
setupContexts,
|
|
12859
|
+
failedItems
|
|
12860
|
+
);
|
|
12861
|
+
const elapsedTime = ((Date.now() - startTime) / 1e3).toFixed(2);
|
|
12862
|
+
Logger.info(`${LOG_PREFIX7}: Simulation completed in ${elapsedTime} seconds`);
|
|
12863
|
+
await this._client.postRunStatus(runId, "completed");
|
|
12864
|
+
return result;
|
|
12865
|
+
} catch (error) {
|
|
12866
|
+
Logger.error(`${LOG_PREFIX7}: Run simulation failed`);
|
|
12867
|
+
await this._client.postRunStatus(runId, "failed");
|
|
12868
|
+
throw error;
|
|
12869
|
+
}
|
|
12313
12870
|
} finally {
|
|
12314
12871
|
if (proc && typeof proc.removeListener === "function") {
|
|
12315
12872
|
proc.removeListener("SIGINT", handleSignal);
|
|
@@ -12320,20 +12877,27 @@ var Simulation = class {
|
|
|
12320
12877
|
}
|
|
12321
12878
|
}
|
|
12322
12879
|
/**
|
|
12323
|
-
*
|
|
12880
|
+
* Orchestrate concurrent simulation execution with hooks support.
|
|
12324
12881
|
*/
|
|
12325
|
-
async _runSimulationAsync(runId, runItems, task2, maxConcurrency) {
|
|
12882
|
+
async _runSimulationAsync(runId, runItems, task2, maxConcurrency, hooks, sharedContext, setupContexts, setupFailedItems) {
|
|
12326
12883
|
const results = {
|
|
12327
12884
|
success: true,
|
|
12328
12885
|
completed: [],
|
|
12329
12886
|
failed: [],
|
|
12330
|
-
totalItems: runItems.length
|
|
12887
|
+
totalItems: runItems.length + setupFailedItems.length
|
|
12331
12888
|
};
|
|
12332
12889
|
let processedCount = 0;
|
|
12333
|
-
const limit =
|
|
12890
|
+
const limit = pLimit2(Math.min(5, maxConcurrency));
|
|
12334
12891
|
const promises = runItems.map(
|
|
12335
12892
|
(runItem) => limit(async () => {
|
|
12336
|
-
const
|
|
12893
|
+
const setupContext = setupContexts.get(runItem.runItemId) ?? null;
|
|
12894
|
+
const result = await this._executeConversation(
|
|
12895
|
+
runId,
|
|
12896
|
+
runItem,
|
|
12897
|
+
task2,
|
|
12898
|
+
hooks,
|
|
12899
|
+
setupContext
|
|
12900
|
+
);
|
|
12337
12901
|
if (result.success) {
|
|
12338
12902
|
results.completed.push(result);
|
|
12339
12903
|
} else {
|
|
@@ -12341,34 +12905,39 @@ var Simulation = class {
|
|
|
12341
12905
|
}
|
|
12342
12906
|
processedCount++;
|
|
12343
12907
|
Logger.info(
|
|
12344
|
-
`${
|
|
12908
|
+
`${LOG_PREFIX7}: ${processedCount}/${runItems.length} processed (run_item_id=${runItem.runItemId})`
|
|
12345
12909
|
);
|
|
12346
12910
|
return result;
|
|
12347
12911
|
})
|
|
12348
12912
|
);
|
|
12349
12913
|
await Promise.all(promises);
|
|
12914
|
+
results.failed.push(...setupFailedItems);
|
|
12915
|
+
await runAfterAll(hooks, results, sharedContext);
|
|
12350
12916
|
Logger.info(
|
|
12351
|
-
`${
|
|
12917
|
+
`${LOG_PREFIX7}: Completed=${results.completed.length}, Failed=${results.failed.length}`
|
|
12352
12918
|
);
|
|
12353
|
-
await this._client.postRunStatus(runId, "completed");
|
|
12354
12919
|
return results;
|
|
12355
12920
|
}
|
|
12356
12921
|
/**
|
|
12357
12922
|
* Execute a multi-turn conversation for a single simulation item.
|
|
12923
|
+
*
|
|
12924
|
+
* The per-item before hook has already been executed by the caller;
|
|
12925
|
+
* the merged setupContext is passed directly to executeTask.
|
|
12926
|
+
* The after hook runs when the conversation ends (success or failure).
|
|
12358
12927
|
*/
|
|
12359
|
-
async _executeConversation(runId, runItem, task2) {
|
|
12360
|
-
const { runItemId, message: initialMessage, turnId: initialTurnId, files: initialFiles } = runItem;
|
|
12928
|
+
async _executeConversation(runId, runItem, task2, hooks, setupContext) {
|
|
12929
|
+
const { runItemId, datasetItemId, message: initialMessage, turnId: initialTurnId, files: initialFiles } = runItem;
|
|
12361
12930
|
let message = initialMessage;
|
|
12362
12931
|
let turnId = initialTurnId;
|
|
12363
12932
|
let sessionId = null;
|
|
12364
12933
|
let rawFiles = initialFiles ?? [];
|
|
12365
12934
|
while (true) {
|
|
12366
|
-
const span2 = new SpanWrapper(SPAN_NAME, {},
|
|
12935
|
+
const span2 = new SpanWrapper(SPAN_NAME, {}, LOG_PREFIX7);
|
|
12367
12936
|
span2.start();
|
|
12368
12937
|
try {
|
|
12369
12938
|
const traceId = span2.getCurrentSpan()?.spanContext().traceId ?? "";
|
|
12370
12939
|
const [responseMessage, taskSessionId] = await span2.withActive(
|
|
12371
|
-
() => executeTask2(task2, message, sessionId, rawFiles)
|
|
12940
|
+
() => executeTask2(task2, message, sessionId, rawFiles, setupContext)
|
|
12372
12941
|
);
|
|
12373
12942
|
if (taskSessionId) {
|
|
12374
12943
|
sessionId = taskSessionId;
|
|
@@ -12382,23 +12951,28 @@ var Simulation = class {
|
|
|
12382
12951
|
)
|
|
12383
12952
|
);
|
|
12384
12953
|
if (response === null) {
|
|
12385
|
-
const
|
|
12386
|
-
return {
|
|
12954
|
+
const itemResult = {
|
|
12387
12955
|
runItemId,
|
|
12388
12956
|
success: false,
|
|
12389
|
-
error:
|
|
12957
|
+
error: "Failed to get conversation response",
|
|
12390
12958
|
turnId
|
|
12391
12959
|
};
|
|
12960
|
+
await runAfter(hooks, datasetItemId, itemResult, setupContext);
|
|
12961
|
+
await runAfterEach(hooks, datasetItemId, itemResult, setupContext);
|
|
12962
|
+
return itemResult;
|
|
12392
12963
|
}
|
|
12393
12964
|
if (response.decision === "stop") {
|
|
12394
12965
|
Logger.info(
|
|
12395
|
-
`${
|
|
12966
|
+
`${LOG_PREFIX7}: Completed run_item_id=${runItemId} reason=${response.reason}`
|
|
12396
12967
|
);
|
|
12397
|
-
|
|
12968
|
+
const itemResult = {
|
|
12398
12969
|
runItemId,
|
|
12399
12970
|
success: true,
|
|
12400
12971
|
finalTurnId: turnId
|
|
12401
12972
|
};
|
|
12973
|
+
await runAfter(hooks, datasetItemId, itemResult, setupContext);
|
|
12974
|
+
await runAfterEach(hooks, datasetItemId, itemResult, setupContext);
|
|
12975
|
+
return itemResult;
|
|
12402
12976
|
}
|
|
12403
12977
|
message = response.nextUserMessage;
|
|
12404
12978
|
turnId = response.nextTurnId;
|
|
@@ -12406,15 +12980,18 @@ var Simulation = class {
|
|
|
12406
12980
|
} catch (error) {
|
|
12407
12981
|
const errorMsg = error instanceof Error ? error.message : String(error);
|
|
12408
12982
|
Logger.error(
|
|
12409
|
-
`${
|
|
12983
|
+
`${LOG_PREFIX7}: Task failed run_item_id=${runItemId}, turn_id=${turnId}: ${errorMsg}`
|
|
12410
12984
|
);
|
|
12411
12985
|
await this._client.reportFailure(runId, runItemId, errorMsg);
|
|
12412
|
-
|
|
12986
|
+
const itemResult = {
|
|
12413
12987
|
runItemId,
|
|
12414
12988
|
success: false,
|
|
12415
12989
|
error: errorMsg,
|
|
12416
12990
|
turnId
|
|
12417
12991
|
};
|
|
12992
|
+
await runAfter(hooks, datasetItemId, itemResult, setupContext);
|
|
12993
|
+
await runAfterEach(hooks, datasetItemId, itemResult, setupContext);
|
|
12994
|
+
return itemResult;
|
|
12418
12995
|
} finally {
|
|
12419
12996
|
span2.end();
|
|
12420
12997
|
}
|
|
@@ -12444,13 +13021,13 @@ function spanHasOutput(span2) {
|
|
|
12444
13021
|
function addInputAttributes(span2, args, entityType) {
|
|
12445
13022
|
span2.setAttribute(`${Config.LIBRARY_NAME}.entity.type`, entityType);
|
|
12446
13023
|
if (args.length > 0) {
|
|
12447
|
-
span2.setAttribute("input", safeStringify(args
|
|
13024
|
+
span2.setAttribute("input", safeStringify(args));
|
|
12448
13025
|
}
|
|
12449
13026
|
}
|
|
12450
13027
|
function addOutputAttributes(span2, result) {
|
|
12451
13028
|
if (result === void 0 || spanHasOutput(span2)) return;
|
|
12452
13029
|
try {
|
|
12453
|
-
span2.setAttribute("output",
|
|
13030
|
+
span2.setAttribute("output", safeStringify(result));
|
|
12454
13031
|
} catch (e) {
|
|
12455
13032
|
span2.setAttribute("output_error", String(e));
|
|
12456
13033
|
}
|
|
@@ -12927,6 +13504,6 @@ Netra._metricsEnabled = false;
|
|
|
12927
13504
|
Netra.withBlockedSpansLocal = withBlockedSpansLocal;
|
|
12928
13505
|
var index_default = Netra;
|
|
12929
13506
|
|
|
12930
|
-
export { Aggregation,
|
|
13507
|
+
export { Aggregation, BaseTask, ChartType, Config, ConversationType, DEFAULT_INSTRUMENTS, DEFAULT_INSTRUMENTS_FOR_ROOT, Dashboard, DimensionField, EntryStatus, Evaluation, FilterField, FilterType, FilteringSpanExporter, GroupBy, InstrumentationSpanProcessor, Measure, Netra, NetraAgentsTracingProcessor, NetraInstruments, NetraOpenAIAgentsInstrumentor, Operator, Prompts, RunEntryContext, RunStatus, Scope, ScrubbingSpanProcessor, SerializationSpanProcessor, SessionSpanProcessor, Simulation, SpanIOProcessor, SpanType, TrialAwareOTLPExporter, TruncatingSerializer, Usage, agent, index_default as default, metadataField, mistralAIInstrumentor, netraExpressMiddleware, openaiAgentsInstrumentor, runWithExtractedContext, safeStringify, span, task, workflow };
|
|
12931
13508
|
//# sourceMappingURL=index.js.map
|
|
12932
13509
|
//# sourceMappingURL=index.js.map
|