@withgateway/sdk 0.1.3 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist/context/index.mjs +3 -0
  2. package/dist/context/index.mjs.map +1 -1
  3. package/dist/experiments/index.mjs +2 -0
  4. package/dist/experiments/index.mjs.map +1 -1
  5. package/dist/index-DnowA8MG.d.mts +447 -0
  6. package/dist/index-DnowA8MG.d.ts +447 -0
  7. package/dist/index.d.mts +6 -1
  8. package/dist/index.d.ts +6 -1
  9. package/dist/index.js +1715 -20
  10. package/dist/index.js.map +1 -1
  11. package/dist/index.mjs +1686 -19
  12. package/dist/index.mjs.map +1 -1
  13. package/dist/memory/index.mjs +3 -0
  14. package/dist/memory/index.mjs.map +1 -1
  15. package/dist/personas/index.d.mts +102 -0
  16. package/dist/personas/index.d.ts +102 -0
  17. package/dist/personas/index.js +205 -0
  18. package/dist/personas/index.js.map +1 -0
  19. package/dist/personas/index.mjs +180 -0
  20. package/dist/personas/index.mjs.map +1 -0
  21. package/dist/replay/index.d.mts +351 -0
  22. package/dist/replay/index.d.ts +351 -0
  23. package/dist/replay/index.js +1094 -0
  24. package/dist/replay/index.js.map +1 -0
  25. package/dist/replay/index.mjs +1057 -0
  26. package/dist/replay/index.mjs.map +1 -0
  27. package/dist/security/index.mjs +2 -0
  28. package/dist/security/index.mjs.map +1 -1
  29. package/dist/sessions/index.d.mts +143 -0
  30. package/dist/sessions/index.d.ts +143 -0
  31. package/dist/sessions/index.js +320 -0
  32. package/dist/sessions/index.js.map +1 -0
  33. package/dist/sessions/index.mjs +288 -0
  34. package/dist/sessions/index.mjs.map +1 -0
  35. package/dist/tracing/index.d.mts +3 -1
  36. package/dist/tracing/index.d.ts +3 -1
  37. package/dist/tracing/index.js +435 -8
  38. package/dist/tracing/index.js.map +1 -1
  39. package/dist/tracing/index.mjs +431 -8
  40. package/dist/tracing/index.mjs.map +1 -1
  41. package/dist/users/index.d.mts +81 -0
  42. package/dist/users/index.d.ts +81 -0
  43. package/dist/users/index.js +168 -0
  44. package/dist/users/index.js.map +1 -0
  45. package/dist/users/index.mjs +144 -0
  46. package/dist/users/index.mjs.map +1 -0
  47. package/package.json +25 -1
  48. package/dist/index-Caw3XVub.d.mts +0 -193
  49. package/dist/index-Caw3XVub.d.ts +0 -193
package/dist/index.js CHANGED
@@ -20,6 +20,11 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/index.ts
21
21
  var src_exports = {};
22
22
  __export(src_exports, {
23
+ DEFAULT_TIMEOUT_SECONDS: () => DEFAULT_TIMEOUT_SECONDS,
24
+ DriftError: () => DriftError,
25
+ ENV_GATEWAY_HOST: () => ENV_GATEWAY_HOST,
26
+ ENV_GATEWAY_PUBLIC_KEY: () => ENV_GATEWAY_PUBLIC_KEY,
27
+ ENV_GATEWAY_SECRET_KEY: () => ENV_GATEWAY_SECRET_KEY,
23
28
  EXPERIMENT_ATTRIBUTES: () => EXPERIMENT_ATTRIBUTES,
24
29
  ExperimentClient: () => ExperimentClient,
25
30
  ExperimentSpanProcessor: () => ExperimentSpanProcessor,
@@ -34,8 +39,27 @@ __export(src_exports, {
34
39
  GatewaySecurityError: () => GatewaySecurityError,
35
40
  GatewayToolApprovalRequiredError: () => GatewayToolApprovalRequiredError,
36
41
  GatewayToolBlockedError: () => GatewayToolBlockedError,
42
+ Persona: () => Persona,
43
+ PersonaError: () => PersonaError,
44
+ PersonasClient: () => PersonasClient,
45
+ REPLAY_ENVIRONMENT: () => REPLAY_ENVIRONMENT,
46
+ ReplayCase: () => ReplayCase,
47
+ ReplayCheck: () => ReplayCheck,
48
+ ReplayError: () => ReplayError,
49
+ ReplayReport: () => ReplayReport,
50
+ ReplaySuite: () => ReplaySuite,
51
+ ReplayTask: () => ReplayTask,
52
+ SessionLoadError: () => SessionLoadError,
53
+ SessionRecording: () => SessionRecording,
54
+ SessionTrace: () => SessionTrace,
55
+ StubMissError: () => StubMissError,
56
+ ToolStubRegistry: () => ToolStubRegistry,
57
+ TraceDiff: () => TraceDiff,
58
+ UserProfileError: () => UserProfileError,
59
+ UsersClient: () => UsersClient,
37
60
  addExperimentAttributes: () => addExperimentAttributes,
38
61
  assignVariant: () => assignVariant,
62
+ basicAuthHeader: () => basicAuthHeader,
39
63
  clearExperimentContext: () => clearExperimentContext,
40
64
  computeHash: () => computeHash,
41
65
  context: () => context,
@@ -43,11 +67,21 @@ __export(src_exports, {
43
67
  experiments: () => singleton_exports,
44
68
  gateway: () => gateway,
45
69
  getExperimentContext: () => getExperimentContext,
70
+ identify: () => identify,
71
+ loadSession: () => loadSession,
46
72
  memory: () => memory,
73
+ personas: () => personas,
47
74
  renderAgentSystem: () => renderAgentSystem,
75
+ replay: () => replay,
76
+ resolveUserId: () => resolveUserId,
77
+ runSuite: () => runSuite,
48
78
  runWithExperimentContext: () => runWithExperimentContext,
79
+ sessionObservationFromApi: () => sessionObservationFromApi,
80
+ sessions: () => sessions,
49
81
  setExperimentContext: () => setExperimentContext,
50
- tracing: () => tracing
82
+ suite: () => suite,
83
+ tracing: () => tracing,
84
+ users: () => users
51
85
  });
52
86
  module.exports = __toCommonJS(src_exports);
53
87
 
@@ -87,14 +121,14 @@ var experimentContextStorage = new import_async_hooks.AsyncLocalStorage();
87
121
  function getExperimentContext() {
88
122
  return experimentContextStorage.getStore();
89
123
  }
90
- function setExperimentContext(context2) {
91
- experimentContextStorage.enterWith(context2);
124
+ function setExperimentContext(context4) {
125
+ experimentContextStorage.enterWith(context4);
92
126
  }
93
127
  function clearExperimentContext() {
94
128
  experimentContextStorage.enterWith(void 0);
95
129
  }
96
- function runWithExperimentContext(context2, fn) {
97
- return experimentContextStorage.run(context2, fn);
130
+ function runWithExperimentContext(context4, fn) {
131
+ return experimentContextStorage.run(context4, fn);
98
132
  }
99
133
 
100
134
  // src/experiments/exposure-logger.ts
@@ -274,17 +308,17 @@ var ExperimentClient = class {
274
308
  variantKey: variant.key,
275
309
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
276
310
  });
277
- const context2 = {
311
+ const context4 = {
278
312
  experimentId: experimentKey,
279
313
  variantKey: variant.key,
280
314
  userId
281
315
  };
282
- setExperimentContext(context2);
316
+ setExperimentContext(context4);
283
317
  return {
284
318
  variant,
285
319
  inExperiment: true,
286
320
  experimentKey,
287
- run: (fn) => runWithExperimentContext(context2, fn)
321
+ run: (fn) => runWithExperimentContext(context4, fn)
288
322
  };
289
323
  }
290
324
  getConfig(experimentKey) {
@@ -966,6 +1000,1218 @@ var memory = {
966
1000
  fromEnv: GatewayMemory.fromEnv
967
1001
  };
968
1002
 
1003
+ // src/personas/index.ts
1004
+ var PersonaError = class extends Error {
1005
+ constructor(message, options) {
1006
+ super(message);
1007
+ this.name = "PersonaError";
1008
+ this.cause = options?.cause;
1009
+ }
1010
+ };
1011
+ var Persona = class {
1012
+ id;
1013
+ name;
1014
+ description;
1015
+ version;
1016
+ instructions;
1017
+ examples;
1018
+ client;
1019
+ constructor(fields) {
1020
+ this.id = fields.id;
1021
+ this.name = fields.name;
1022
+ this.description = fields.description;
1023
+ this.version = fields.version;
1024
+ this.instructions = fields.instructions;
1025
+ this.examples = fields.examples ?? [];
1026
+ this.client = fields.client ?? null;
1027
+ }
1028
+ /**
1029
+ * Get the persona's next user message for a conversation.
1030
+ *
1031
+ * `messages` use your agent's perspective: role `user` for the simulated
1032
+ * user's prior turns, `assistant` for your agent's turns.
1033
+ * `done` is true when the persona considers its goal met.
1034
+ */
1035
+ respond(messages) {
1036
+ if (this.client === null) {
1037
+ throw new PersonaError("Persona is not bound to a client.");
1038
+ }
1039
+ return this.client.chat(this.id, messages);
1040
+ }
1041
+ };
1042
+ var PersonasClient = class _PersonasClient {
1043
+ host;
1044
+ publicKey;
1045
+ secretKey;
1046
+ timeoutSeconds;
1047
+ debug;
1048
+ constructor(config) {
1049
+ this.host = config.host.replace(/\/$/, "");
1050
+ this.publicKey = config.publicKey;
1051
+ this.secretKey = config.secretKey;
1052
+ this.timeoutSeconds = config.timeoutSeconds ?? 120;
1053
+ this.debug = config.debug ?? false;
1054
+ }
1055
+ /** Create a client from GATEWAY_HOST / GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY. */
1056
+ static fromEnv(config = {}) {
1057
+ const host = config.host ?? process.env.GATEWAY_HOST;
1058
+ const publicKey = config.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;
1059
+ const secretKey = config.secretKey ?? process.env.GATEWAY_SECRET_KEY;
1060
+ const missing = [
1061
+ ["host", host],
1062
+ ["publicKey", publicKey],
1063
+ ["secretKey", secretKey]
1064
+ ].filter(([, value]) => !value).map(([name]) => name);
1065
+ if (missing.length > 0) {
1066
+ throw new PersonaError(
1067
+ `Missing Gateway persona configuration: ${missing.join(", ")}`
1068
+ );
1069
+ }
1070
+ return new _PersonasClient({
1071
+ ...config,
1072
+ host,
1073
+ publicKey,
1074
+ secretKey
1075
+ });
1076
+ }
1077
+ /** List the project's personas (without full instructions). */
1078
+ async list() {
1079
+ const payload = await this.requestJson("GET", "/api/public/personas");
1080
+ const items = Array.isArray(payload.data) ? payload.data : [];
1081
+ return items.filter(isRecord).map(
1082
+ (item) => new Persona({
1083
+ id: String(item.id),
1084
+ name: String(item.name),
1085
+ description: item.description ?? null,
1086
+ version: typeof item.version === "number" ? item.version : 1,
1087
+ instructions: "",
1088
+ client: this
1089
+ })
1090
+ );
1091
+ }
1092
+ /** Fetch a persona (full definition) bound to this client. */
1093
+ async get(personaId) {
1094
+ const item = await this.requestJson(
1095
+ "GET",
1096
+ `/api/public/personas/${encodeURIComponent(personaId)}/chat`
1097
+ );
1098
+ return new Persona({
1099
+ id: String(item.id),
1100
+ name: String(item.name),
1101
+ description: item.description ?? null,
1102
+ version: typeof item.version === "number" ? item.version : 1,
1103
+ instructions: typeof item.instructions === "string" ? item.instructions : "",
1104
+ examples: Array.isArray(item.examples) ? item.examples.map((example) => String(example)) : [],
1105
+ client: this
1106
+ });
1107
+ }
1108
+ /** Play one persona turn. See {@link Persona.respond}. */
1109
+ async chat(personaId, messages) {
1110
+ const payload = await this.requestJson(
1111
+ "POST",
1112
+ `/api/public/personas/${encodeURIComponent(personaId)}/chat`,
1113
+ { messages }
1114
+ );
1115
+ return {
1116
+ content: typeof payload.content === "string" ? payload.content : "",
1117
+ done: Boolean(payload.done)
1118
+ };
1119
+ }
1120
+ async requestJson(method, path, payload) {
1121
+ let response;
1122
+ try {
1123
+ response = await fetch(`${this.host}${path}`, {
1124
+ method,
1125
+ headers: {
1126
+ Authorization: this.authHeader(),
1127
+ "Content-Type": "application/json"
1128
+ },
1129
+ ...payload ? { body: JSON.stringify(payload) } : {},
1130
+ signal: AbortSignal.timeout(this.timeoutSeconds * 1e3)
1131
+ });
1132
+ } catch (error) {
1133
+ const reason = error instanceof Error ? error.message : String(error);
1134
+ throw new PersonaError(`${method} ${path} failed: ${reason}`, {
1135
+ cause: error
1136
+ });
1137
+ }
1138
+ const text = await response.text();
1139
+ if (!response.ok) {
1140
+ const detail = text.slice(0, 500);
1141
+ throw new PersonaError(
1142
+ `${method} ${path} failed (${response.status}): ${detail}`
1143
+ );
1144
+ }
1145
+ this.log("%s %s -> %s", method, path, response.status);
1146
+ return safeJson3(text);
1147
+ }
1148
+ authHeader() {
1149
+ return `Basic ${Buffer.from(`${this.publicKey}:${this.secretKey}`).toString(
1150
+ "base64"
1151
+ )}`;
1152
+ }
1153
+ log(message, ...args) {
1154
+ if (this.debug) {
1155
+ console.log(`[gateway.personas] ${message}`, ...args);
1156
+ }
1157
+ }
1158
+ };
1159
+ function isRecord(value) {
1160
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
1161
+ }
1162
+ function safeJson3(value) {
1163
+ try {
1164
+ const parsed = JSON.parse(value);
1165
+ return isRecord(parsed) ? parsed : {};
1166
+ } catch {
1167
+ return {};
1168
+ }
1169
+ }
1170
+ var personas = {
1171
+ fromEnv: PersonasClient.fromEnv
1172
+ };
1173
+
1174
+ // src/sessions/index.ts
1175
+ var import_node_fs = require("fs");
1176
+ var import_node_path = require("path");
1177
+ var ENV_GATEWAY_HOST = "GATEWAY_HOST";
1178
+ var ENV_GATEWAY_PUBLIC_KEY = "GATEWAY_PUBLIC_KEY";
1179
+ var ENV_GATEWAY_SECRET_KEY = "GATEWAY_SECRET_KEY";
1180
+ var DEFAULT_TIMEOUT_SECONDS = 30;
1181
+ var SessionLoadError = class extends Error {
1182
+ constructor(message, options) {
1183
+ super(message);
1184
+ this.name = "SessionLoadError";
1185
+ this.cause = options?.cause;
1186
+ }
1187
+ };
1188
+ function sessionObservationFromApi(raw) {
1189
+ return {
1190
+ id: String(raw.id ?? ""),
1191
+ type: asStringOrNull(raw.type),
1192
+ name: asStringOrNull(raw.name),
1193
+ level: asStringOrNull(raw.level),
1194
+ statusMessage: asStringOrNull(raw.statusMessage),
1195
+ model: asStringOrNull(raw.model),
1196
+ input: raw.input,
1197
+ output: raw.output,
1198
+ metadata: raw.metadata ?? null,
1199
+ parentObservationId: asStringOrNull(raw.parentObservationId),
1200
+ startTime: raw.startTime ? String(raw.startTime) : null,
1201
+ endTime: raw.endTime ? String(raw.endTime) : null
1202
+ };
1203
+ }
1204
+ var SessionTrace = class _SessionTrace {
1205
+ id;
1206
+ name;
1207
+ timestamp;
1208
+ input;
1209
+ output;
1210
+ metadata;
1211
+ tags;
1212
+ observations;
1213
+ constructor(fields) {
1214
+ this.id = fields.id;
1215
+ this.name = fields.name;
1216
+ this.timestamp = fields.timestamp;
1217
+ this.input = fields.input;
1218
+ this.output = fields.output;
1219
+ this.metadata = fields.metadata ?? null;
1220
+ this.tags = fields.tags ?? [];
1221
+ this.observations = fields.observations ?? [];
1222
+ }
1223
+ get toolCalls() {
1224
+ return this.observations.filter(
1225
+ (o) => (o.type ?? "").toUpperCase() === "TOOL"
1226
+ );
1227
+ }
1228
+ get generations() {
1229
+ return this.observations.filter(
1230
+ (o) => (o.type ?? "").toUpperCase() === "GENERATION"
1231
+ );
1232
+ }
1233
+ /**
1234
+ * The user message that started this turn.
1235
+ *
1236
+ * Handles the common recorded shapes: a plain string input, an OpenAI
1237
+ * message list (last role=user entry wins — earlier ones are carried
1238
+ * history), or an object with a content/input field.
1239
+ */
1240
+ userMessage() {
1241
+ const value = this.input;
1242
+ if (typeof value === "string") {
1243
+ return value;
1244
+ }
1245
+ if (Array.isArray(value)) {
1246
+ for (let i = value.length - 1; i >= 0; i--) {
1247
+ const entry = value[i];
1248
+ if (isPlainObject(entry) && entry.role === "user") {
1249
+ const content = entry.content;
1250
+ if (typeof content === "string") {
1251
+ return content;
1252
+ }
1253
+ if (Array.isArray(content)) {
1254
+ const parts = content.filter(isPlainObject).map((part) => typeof part.text === "string" ? part.text : "");
1255
+ return parts.join("") || null;
1256
+ }
1257
+ }
1258
+ }
1259
+ return null;
1260
+ }
1261
+ if (isPlainObject(value)) {
1262
+ for (const key of ["content", "input", "text", "message"]) {
1263
+ if (typeof value[key] === "string") {
1264
+ return value[key];
1265
+ }
1266
+ }
1267
+ }
1268
+ return null;
1269
+ }
1270
+ static fromApi(raw) {
1271
+ return new _SessionTrace({
1272
+ id: String(raw.id ?? ""),
1273
+ name: asStringOrNull(raw.name),
1274
+ timestamp: raw.timestamp ? String(raw.timestamp) : null,
1275
+ input: raw.input,
1276
+ output: raw.output,
1277
+ metadata: raw.metadata ?? null,
1278
+ tags: Array.isArray(raw.tags) ? raw.tags.map(String) : [],
1279
+ observations: (Array.isArray(raw.observations) ? raw.observations : []).filter(isPlainObject).map(sessionObservationFromApi)
1280
+ });
1281
+ }
1282
+ };
1283
+ var SessionRecording = class _SessionRecording {
1284
+ sessionId;
1285
+ projectId;
1286
+ environment;
1287
+ traces;
1288
+ constructor(fields) {
1289
+ this.sessionId = fields.sessionId;
1290
+ this.projectId = fields.projectId;
1291
+ this.environment = fields.environment;
1292
+ this.traces = fields.traces ?? [];
1293
+ }
1294
+ /** Traces in chronological order — one per agent turn. */
1295
+ turns() {
1296
+ return [...this.traces].sort((a, b) => {
1297
+ const left = a.timestamp ?? "";
1298
+ const right = b.timestamp ?? "";
1299
+ return left < right ? -1 : left > right ? 1 : 0;
1300
+ });
1301
+ }
1302
+ /** The nth chronological turn (negative indices allowed). */
1303
+ turn(index) {
1304
+ const ordered = this.turns();
1305
+ const found = ordered.at(index);
1306
+ if (!found) {
1307
+ throw new RangeError(
1308
+ `Turn index ${index} out of range (session has ${ordered.length} turns)`
1309
+ );
1310
+ }
1311
+ return found;
1312
+ }
1313
+ /**
1314
+ * The user message of each turn, in order — feed these back to an agent
1315
+ * to re-drive the recorded conversation.
1316
+ */
1317
+ userMessages() {
1318
+ return this.turns().map((trace4) => trace4.userMessage());
1319
+ }
1320
+ /** Output of the last chronological turn (null when empty). */
1321
+ finalOutput() {
1322
+ const ordered = this.turns();
1323
+ return ordered.length > 0 ? ordered[ordered.length - 1].output : null;
1324
+ }
1325
+ /** Every TOOL observation across the session, chronological. */
1326
+ toolCalls() {
1327
+ return this.select({ type: "TOOL" });
1328
+ }
1329
+ /** Every GENERATION observation across the session, chronological. */
1330
+ generations() {
1331
+ return this.select({ type: "GENERATION" });
1332
+ }
1333
+ /** Filter observations across all turns (chronological order). */
1334
+ select(filter = {}) {
1335
+ const selected = [];
1336
+ for (const trace4 of this.turns()) {
1337
+ for (const observation of trace4.observations) {
1338
+ if (filter.type && (observation.type ?? "").toUpperCase() !== filter.type.toUpperCase()) {
1339
+ continue;
1340
+ }
1341
+ if (filter.name && observation.name !== filter.name) {
1342
+ continue;
1343
+ }
1344
+ if (filter.level && (observation.level ?? "").toUpperCase() !== filter.level.toUpperCase()) {
1345
+ continue;
1346
+ }
1347
+ selected.push(observation);
1348
+ }
1349
+ }
1350
+ return selected;
1351
+ }
1352
+ toJSON() {
1353
+ return {
1354
+ sessionId: this.sessionId,
1355
+ projectId: this.projectId,
1356
+ environment: this.environment,
1357
+ traces: this.turns().map((trace4) => ({
1358
+ id: trace4.id,
1359
+ name: trace4.name,
1360
+ timestamp: trace4.timestamp,
1361
+ input: trace4.input,
1362
+ output: trace4.output,
1363
+ metadata: trace4.metadata,
1364
+ tags: trace4.tags,
1365
+ observations: trace4.observations.map((o) => ({ ...o }))
1366
+ }))
1367
+ };
1368
+ }
1369
+ /** Dump the full session as a JSON fixture (for regression tests). */
1370
+ toFixture(path) {
1371
+ (0, import_node_fs.mkdirSync)((0, import_node_path.dirname)(path), { recursive: true });
1372
+ (0, import_node_fs.writeFileSync)(path, JSON.stringify(this.toJSON(), null, 2), "utf-8");
1373
+ return path;
1374
+ }
1375
+ static fromApi(raw) {
1376
+ return new _SessionRecording({
1377
+ sessionId: String(raw.id ?? ""),
1378
+ projectId: asStringOrNull(raw.projectId),
1379
+ environment: asStringOrNull(raw.environment),
1380
+ traces: (Array.isArray(raw.traces) ? raw.traces : []).filter(isPlainObject).map(SessionTrace.fromApi)
1381
+ });
1382
+ }
1383
+ };
1384
+ async function loadSession(sessionId, options = {}) {
1385
+ const host = (options.host ?? process.env[ENV_GATEWAY_HOST] ?? "").replace(
1386
+ /\/+$/,
1387
+ ""
1388
+ );
1389
+ const publicKey = options.publicKey ?? process.env[ENV_GATEWAY_PUBLIC_KEY] ?? "";
1390
+ const secretKey = options.secretKey ?? process.env[ENV_GATEWAY_SECRET_KEY] ?? "";
1391
+ const timeoutSeconds = options.timeoutSeconds ?? DEFAULT_TIMEOUT_SECONDS;
1392
+ if (!host || !publicKey || !secretKey) {
1393
+ throw new SessionLoadError(
1394
+ "Gateway is not configured \u2014 set GATEWAY_HOST, GATEWAY_PUBLIC_KEY and GATEWAY_SECRET_KEY (or pass host/publicKey/secretKey)."
1395
+ );
1396
+ }
1397
+ const url = `${host}/api/public/sessions/${encodeURIComponent(sessionId)}?includeIO=true`;
1398
+ let response;
1399
+ try {
1400
+ response = await fetch(url, {
1401
+ method: "GET",
1402
+ headers: { Authorization: basicAuthHeader(publicKey, secretKey) },
1403
+ signal: AbortSignal.timeout(timeoutSeconds * 1e3)
1404
+ });
1405
+ } catch (error) {
1406
+ throw new SessionLoadError(
1407
+ `Failed to load session ${sessionId}: ${error instanceof Error ? error.message : String(error)}`,
1408
+ { cause: error }
1409
+ );
1410
+ }
1411
+ if (response.status === 404) {
1412
+ throw new SessionLoadError(`Session not found: ${sessionId}`);
1413
+ }
1414
+ const text = await response.text();
1415
+ if (!response.ok) {
1416
+ throw new SessionLoadError(
1417
+ `Failed to load session ${sessionId}: HTTP ${response.status} \u2014 ${text.slice(0, 300)}`
1418
+ );
1419
+ }
1420
+ let payload;
1421
+ try {
1422
+ payload = JSON.parse(text);
1423
+ } catch (error) {
1424
+ throw new SessionLoadError(
1425
+ `Failed to load session ${sessionId}: response is not valid JSON`,
1426
+ { cause: error }
1427
+ );
1428
+ }
1429
+ return SessionRecording.fromApi(
1430
+ isPlainObject(payload) ? payload : {}
1431
+ );
1432
+ }
1433
+ function basicAuthHeader(publicKey, secretKey) {
1434
+ return `Basic ${Buffer.from(`${publicKey}:${secretKey}`).toString("base64")}`;
1435
+ }
1436
+ function asStringOrNull(value) {
1437
+ return typeof value === "string" ? value : null;
1438
+ }
1439
+ function isPlainObject(value) {
1440
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1441
+ }
1442
+ var sessions = {
1443
+ load: loadSession
1444
+ };
1445
+
1446
+ // src/replay/index.ts
1447
+ var import_node_path2 = require("path");
1448
+ var ReplayError = class extends Error {
1449
+ constructor(message, options) {
1450
+ super(message);
1451
+ this.name = "ReplayError";
1452
+ this.cause = options?.cause;
1453
+ }
1454
+ };
1455
+ var StubMissError = class extends Error {
1456
+ constructor(message) {
1457
+ super(message);
1458
+ this.name = "StubMissError";
1459
+ }
1460
+ };
1461
+ var DriftError = class extends ReplayError {
1462
+ constructor(message) {
1463
+ super(message);
1464
+ this.name = "DriftError";
1465
+ }
1466
+ };
1467
+ var WRAPPER_KEYS = ["args_json", "arguments", "kwargs", "args", "input"];
1468
+ function canonicalize(value) {
1469
+ if (typeof value === "string") {
1470
+ const stripped = value.trim();
1471
+ if (stripped.startsWith("{") || stripped.startsWith("[")) {
1472
+ try {
1473
+ return canonicalize(JSON.parse(stripped));
1474
+ } catch {
1475
+ return value;
1476
+ }
1477
+ }
1478
+ return value;
1479
+ }
1480
+ if (Array.isArray(value)) {
1481
+ return value.map(canonicalize);
1482
+ }
1483
+ if (isPlainObject2(value)) {
1484
+ const entries = Object.entries(value);
1485
+ if (entries.length === 1 && WRAPPER_KEYS.includes(entries[0][0])) {
1486
+ return canonicalize(entries[0][1]);
1487
+ }
1488
+ return Object.fromEntries(
1489
+ entries.map(([key, inner]) => [key, canonicalize(inner)])
1490
+ );
1491
+ }
1492
+ return value;
1493
+ }
1494
+ function sortKeysDeep(value) {
1495
+ if (Array.isArray(value)) {
1496
+ return value.map(sortKeysDeep);
1497
+ }
1498
+ if (isPlainObject2(value)) {
1499
+ const sorted = {};
1500
+ for (const key of Object.keys(value).sort()) {
1501
+ sorted[key] = sortKeysDeep(value[key]);
1502
+ }
1503
+ return sorted;
1504
+ }
1505
+ return value;
1506
+ }
1507
+ function normalizeInput(value) {
1508
+ try {
1509
+ return JSON.stringify(sortKeysDeep(canonicalize(value ?? null))) ?? "null";
1510
+ } catch {
1511
+ return String(value);
1512
+ }
1513
+ }
1514
+ var ToolStubRegistry = class _ToolStubRegistry {
1515
+ callLog = [];
1516
+ driftEvents = [];
1517
+ recorded;
1518
+ consumed = /* @__PURE__ */ new Set();
1519
+ consumptionOrder = [];
1520
+ missPolicy;
1521
+ fallback;
1522
+ local;
1523
+ constructor(calls, options = {}) {
1524
+ const missPolicy = options.missPolicy ?? "error";
1525
+ if (!["error", "reuse", "passthrough"].includes(missPolicy)) {
1526
+ throw new ReplayError(`Unknown missPolicy: ${missPolicy}`);
1527
+ }
1528
+ this.recorded = calls;
1529
+ this.missPolicy = missPolicy;
1530
+ this.fallback = options.fallback ?? null;
1531
+ this.local = { ...options.local ?? {} };
1532
+ }
1533
+ static fromSession(session, options = {}) {
1534
+ const calls = session.toolCalls().map(
1535
+ (observation) => ({
1536
+ name: observation.name ?? "",
1537
+ input: observation.input,
1538
+ output: observation.output,
1539
+ observationId: observation.id
1540
+ })
1541
+ );
1542
+ return new _ToolStubRegistry(calls, options);
1543
+ }
1544
+ /** Resolve a tool call against the recorded world. */
1545
+ lookup(toolName, toolInput = null) {
1546
+ if (toolName in this.local) {
1547
+ this.callLog.push({ tool: toolName, match: "local", input: toolInput });
1548
+ return this.local[toolName](toolInput);
1549
+ }
1550
+ const normalized = normalizeInput(toolInput);
1551
+ for (let index = 0; index < this.recorded.length; index++) {
1552
+ const record = this.recorded[index];
1553
+ if (!this.consumed.has(index) && record.name === toolName && normalizeInput(record.input) === normalized) {
1554
+ this.consumed.add(index);
1555
+ this.consumptionOrder.push(index);
1556
+ this.callLog.push({ tool: toolName, match: "exact", input: toolInput });
1557
+ return record.output;
1558
+ }
1559
+ }
1560
+ for (let index = this.recorded.length - 1; index >= 0; index--) {
1561
+ const record = this.recorded[index];
1562
+ if (record.name === toolName && normalizeInput(record.input) === normalized) {
1563
+ this.callLog.push({
1564
+ tool: toolName,
1565
+ match: "exact-repeat",
1566
+ input: toolInput
1567
+ });
1568
+ return record.output;
1569
+ }
1570
+ }
1571
+ for (let index = 0; index < this.recorded.length; index++) {
1572
+ const record = this.recorded[index];
1573
+ if (!this.consumed.has(index) && record.name === toolName) {
1574
+ this.consumed.add(index);
1575
+ this.consumptionOrder.push(index);
1576
+ this.callLog.push({
1577
+ tool: toolName,
1578
+ match: "ordinal",
1579
+ input: toolInput
1580
+ });
1581
+ return record.output;
1582
+ }
1583
+ }
1584
+ if (this.missPolicy === "reuse") {
1585
+ for (let index = this.recorded.length - 1; index >= 0; index--) {
1586
+ const record = this.recorded[index];
1587
+ if (record.name === toolName) {
1588
+ this.driftEvents.push(
1589
+ `recordings for tool '${toolName}' exhausted \u2014 replayed the last one again (reuse policy)`
1590
+ );
1591
+ this.callLog.push({
1592
+ tool: toolName,
1593
+ match: "reuse",
1594
+ input: toolInput
1595
+ });
1596
+ return record.output;
1597
+ }
1598
+ }
1599
+ }
1600
+ const recordedNames = [...new Set(this.recorded.map((r) => r.name))].sort();
1601
+ const drift = `no recording for tool '${toolName}' (recorded tools: ${JSON.stringify(recordedNames)})`;
1602
+ this.driftEvents.push(drift);
1603
+ this.callLog.push({ tool: toolName, match: "miss", input: toolInput });
1604
+ if (this.fallback !== null && (this.missPolicy === "passthrough" || this.missPolicy === "reuse")) {
1605
+ return this.fallback(toolName, toolInput);
1606
+ }
1607
+ throw new StubMissError(drift);
1608
+ }
1609
+ /**
1610
+ * Mapping of toolName → callable, drop-in for most agent tool layers.
1611
+ *
1612
+ * `local` merges in tools that should ALWAYS run live (new tools the
1613
+ * recording predates, or deterministic/pure helpers) — they're logged for
1614
+ * the contract check but never count as drift.
1615
+ *
1616
+ * UNKNOWN tool names also resolve (to a stub that routes through
1617
+ * `lookup()`), so a call to an un-recorded tool is LOGGED and follows the
1618
+ * miss policy instead of dying on an undefined lookup — that log is what
1619
+ * lets `check()` classify a forbidden-but-unrecorded call as FAIL.
1620
+ */
1621
+ asRegistry(options = {}) {
1622
+ if (options.fallback) {
1623
+ this.fallback = options.fallback;
1624
+ this.missPolicy = "passthrough";
1625
+ }
1626
+ if (options.local) {
1627
+ Object.assign(this.local, options.local);
1628
+ }
1629
+ const make = (name) => (toolInput) => this.lookup(name, toolInput === void 0 ? {} : toolInput);
1630
+ const target = {};
1631
+ const names = /* @__PURE__ */ new Set([
1632
+ ...this.recorded.map((record) => record.name),
1633
+ ...Object.keys(this.local)
1634
+ ]);
1635
+ for (const name of names) {
1636
+ if (name) {
1637
+ target[name] = make(name);
1638
+ }
1639
+ }
1640
+ return new Proxy(target, {
1641
+ get(current, prop, receiver) {
1642
+ if (typeof prop !== "string" || prop in current) {
1643
+ return Reflect.get(current, prop, receiver);
1644
+ }
1645
+ return make(prop);
1646
+ }
1647
+ });
1648
+ }
1649
+ calledNames() {
1650
+ return this.callLog.map((entry) => entry.tool);
1651
+ }
1652
+ /**
1653
+ * 1:1 comparison of this replay against the recorded trace.
1654
+ *
1655
+ * The recording is the expectation: every recorded tool call should be
1656
+ * replayed exactly once, in order, with nothing extra. Use for strict
1657
+ * did-it-do-everything-the-original-did checks (`mode: "exact"`).
1658
+ *
1659
+ * `includeLocal`: count local-tool calls as extras (default false — local
1660
+ * tools are declared live on purpose; their recorded calls are likewise
1661
+ * excluded from "missing", since local bypasses recordings).
1662
+ */
1663
+ compare(options = {}) {
1664
+ const includeLocal = options.includeLocal ?? false;
1665
+ const missing = this.recorded.map((record, index) => ({ record, index })).filter(
1666
+ ({ record, index }) => !this.consumed.has(index) && (includeLocal || !(record.name in this.local))
1667
+ ).map(({ record }) => `${record.name}(${normalizeInput(record.input)})`);
1668
+ const extra = [];
1669
+ for (const entry of this.callLog) {
1670
+ if (["miss", "reuse", "exact-repeat"].includes(entry.match) || includeLocal && entry.match === "local") {
1671
+ extra.push(
1672
+ `${entry.tool}(${normalizeInput(entry.input)}) [${entry.match}]`
1673
+ );
1674
+ }
1675
+ }
1676
+ const outOfOrder = [];
1677
+ let last = -1;
1678
+ for (const index of this.consumptionOrder) {
1679
+ if (index < last) {
1680
+ const record = this.recorded[index];
1681
+ outOfOrder.push(`${record.name}(${normalizeInput(record.input)})`);
1682
+ } else {
1683
+ last = index;
1684
+ }
1685
+ }
1686
+ const matched = this.consumptionOrder.map(
1687
+ (index) => this.recorded[index].name
1688
+ );
1689
+ return new TraceDiff({ matched, missing, extra, outOfOrder });
1690
+ }
1691
+ get drifted() {
1692
+ return this.driftEvents.length > 0;
1693
+ }
1694
+ };
1695
+ var TraceDiff = class {
1696
+ matched;
1697
+ missing;
1698
+ extra;
1699
+ outOfOrder;
1700
+ constructor(fields = {}) {
1701
+ this.matched = fields.matched ?? [];
1702
+ this.missing = fields.missing ?? [];
1703
+ this.extra = fields.extra ?? [];
1704
+ this.outOfOrder = fields.outOfOrder ?? [];
1705
+ }
1706
+ get identical() {
1707
+ return this.missing.length === 0 && this.extra.length === 0 && this.outOfOrder.length === 0;
1708
+ }
1709
+ explain() {
1710
+ if (this.identical) {
1711
+ return `1:1 replay \u2014 all ${this.matched.length} recorded tool calls reproduced in order`;
1712
+ }
1713
+ const lines = [
1714
+ `trace diverges from recording (${this.matched.length} matched):`
1715
+ ];
1716
+ lines.push(...this.missing.map((item) => ` not reproduced: ${item}`));
1717
+ lines.push(...this.extra.map((item) => ` extra call: ${item}`));
1718
+ lines.push(...this.outOfOrder.map((item) => ` out of order: ${item}`));
1719
+ return lines.join("\n");
1720
+ }
1721
+ };
1722
+ var ReplayTask = class _ReplayTask {
1723
+ id;
1724
+ name;
1725
+ prompt;
1726
+ expectedOutput;
1727
+ metadata;
1728
+ constructor(fields) {
1729
+ this.id = fields.id;
1730
+ this.name = fields.name ?? null;
1731
+ this.prompt = fields.prompt;
1732
+ this.expectedOutput = fields.expectedOutput;
1733
+ this.metadata = fields.metadata ?? {};
1734
+ }
1735
+ get sourceSessionId() {
1736
+ const value = this.metadata.sourceSessionId;
1737
+ return value ? String(value) : null;
1738
+ }
1739
+ get sourceTraceId() {
1740
+ const value = this.metadata.sourceTraceId;
1741
+ return value ? String(value) : null;
1742
+ }
1743
+ static fromApi(raw) {
1744
+ const metadata = raw.metadata;
1745
+ return new _ReplayTask({
1746
+ id: String(raw.id ?? ""),
1747
+ name: typeof raw.name === "string" ? raw.name : null,
1748
+ prompt: raw.prompt,
1749
+ expectedOutput: raw.expectedOutput,
1750
+ metadata: isPlainObject2(metadata) ? { ...metadata } : {}
1751
+ });
1752
+ }
1753
+ };
1754
+ var ReplayCheck = class {
1755
+ status;
1756
+ failures;
1757
+ drift;
1758
+ traceDiff;
1759
+ constructor(status, fields = {}) {
1760
+ this.status = status;
1761
+ this.failures = fields.failures ?? [];
1762
+ this.drift = fields.drift ?? [];
1763
+ this.traceDiff = fields.traceDiff ?? null;
1764
+ }
1765
+ get passed() {
1766
+ return this.status === "PASS";
1767
+ }
1768
+ get drifted() {
1769
+ return this.status === "DRIFT";
1770
+ }
1771
+ explain() {
1772
+ if (this.status === "PASS") {
1773
+ return "PASS";
1774
+ }
1775
+ const lines = [this.status];
1776
+ lines.push(...this.failures.map((failure) => ` FAIL: ${failure}`));
1777
+ for (const event of this.drift) {
1778
+ if (event.includes("reuse policy")) {
1779
+ lines.push(
1780
+ ` DRIFT: ${event} \u2014 recording under-covers this run; re-record for exact coverage or keep the reuse policy.`
1781
+ );
1782
+ } else {
1783
+ lines.push(
1784
+ ` DRIFT: ${event} \u2014 the test is stale, not the agent; re-record the session (or declare the tool local).`
1785
+ );
1786
+ }
1787
+ }
1788
+ return lines.join("\n");
1789
+ }
1790
+ };
1791
+ var ReplayCase = class {
1792
+ task;
1793
+ loader;
1794
+ _recording = null;
1795
+ _stubs = null;
1796
+ constructor(task, options) {
1797
+ this.task = task;
1798
+ this.loader = options.loader;
1799
+ }
1800
+ // -- identity ------------------------------------------------------------
1801
+ get id() {
1802
+ return this.task.id;
1803
+ }
1804
+ get name() {
1805
+ return this.task.name ?? this.task.id;
1806
+ }
1807
+ get prompt() {
1808
+ return this.task.prompt;
1809
+ }
1810
+ get expected() {
1811
+ return this.task.expectedOutput;
1812
+ }
1813
+ // -- recorded source session ----------------------------------------------
1814
+ /** The full recorded session this case was filed from. */
1815
+ async recording() {
1816
+ if (this._recording === null) {
1817
+ const source = this.task.sourceSessionId;
1818
+ if (!source) {
1819
+ throw new DriftError(
1820
+ `Task ${this.name} has no sourceSessionId provenance \u2014 file it from a session (add_session_to_task_set) or set metadata.sourceSessionId.`
1821
+ );
1822
+ }
1823
+ this._recording = await this.loader(source);
1824
+ }
1825
+ return this._recording;
1826
+ }
1827
+ async stubs(options = {}) {
1828
+ this._stubs = ToolStubRegistry.fromSession(await this.recording(), options);
1829
+ return this._stubs;
1830
+ }
1831
+ /**
1832
+ * The recorded conversation's user messages, one per turn — feed them to
1833
+ * your agent in order to re-drive the full session (each turn was one
1834
+ * trace in the recording).
1835
+ */
1836
+ async conversation() {
1837
+ const messages = (await this.recording()).userMessages();
1838
+ const found = messages.filter(
1839
+ (message) => Boolean(message)
1840
+ );
1841
+ return found.length > 0 ? found : [String(this.prompt)];
1842
+ }
1843
+ // -- grading ---------------------------------------------------------------
1844
+ /**
1845
+ * Contract invariants + drift triage.
1846
+ *
1847
+ * Invariants come from task metadata (the workbench-style contract):
1848
+ * metadata.expectTools — every listed tool MUST have been called
1849
+ * metadata.mustNotCall — none of these may have been called
1850
+ * Semantic grading stays with the caller (assert on `output` /
1851
+ * `case.expected`, or run a platform judge on the replay trace).
1852
+ *
1853
+ * `mode` (or task `metadata.replayMode`):
1854
+ * "contract" (default) — grade only the invariants above
1855
+ * "exact" — true 1:1 replay: the agent must reproduce EVERY
1856
+ * recorded tool call, in order, with nothing extra
1857
+ * (see TraceDiff); any divergence is a FAIL. The
1858
+ * full diff lands in the failure reasons and
1859
+ * `traceDiff`.
1860
+ */
1861
+ check(output = void 0, options = {}) {
1862
+ const registry = options.stubs ?? this._stubs;
1863
+ const drift = registry ? [...registry.driftEvents] : [];
1864
+ const called = options.calledTools ?? (registry ? registry.calledNames() : []);
1865
+ const violations = [];
1866
+ const omissions = [];
1867
+ const expectTools = this.task.metadata.expectTools;
1868
+ if (Array.isArray(expectTools)) {
1869
+ for (const toolName of expectTools) {
1870
+ if (!called.includes(toolName)) {
1871
+ omissions.push(`expected tool not called: ${toolName}`);
1872
+ }
1873
+ }
1874
+ }
1875
+ const mustNot = this.task.metadata.mustNotCall;
1876
+ if (Array.isArray(mustNot)) {
1877
+ for (const toolName of mustNot) {
1878
+ if (called.includes(toolName)) {
1879
+ violations.push(`must_not_call violated: ${toolName}`);
1880
+ }
1881
+ }
1882
+ }
1883
+ if (typeof this.expected === "string" && this.expected.trim() && typeof output === "string" && this.task.metadata.outputExact === true && output.trim() !== this.expected.trim()) {
1884
+ violations.push("output does not exactly match expectedOutput");
1885
+ }
1886
+ const replayMode = options.mode ?? this.task.metadata.replayMode ?? "contract";
1887
+ let traceDiff = null;
1888
+ if (registry) {
1889
+ traceDiff = registry.compare();
1890
+ }
1891
+ if (replayMode === "exact" && traceDiff && !traceDiff.identical) {
1892
+ violations.push(
1893
+ ...[
1894
+ ...traceDiff.missing.map((item) => `not reproduced: ${item}`),
1895
+ ...traceDiff.extra.map((item) => `extra call: ${item}`),
1896
+ ...traceDiff.outOfOrder.map((item) => `out of order: ${item}`)
1897
+ ].map((line) => `1:1 replay diverged \u2014 ${line}`)
1898
+ );
1899
+ }
1900
+ if (violations.length > 0) {
1901
+ return new ReplayCheck("FAIL", {
1902
+ failures: [...violations, ...drift.length > 0 ? [] : omissions],
1903
+ drift,
1904
+ traceDiff
1905
+ });
1906
+ }
1907
+ if (drift.length > 0) {
1908
+ return new ReplayCheck("DRIFT", { drift, traceDiff });
1909
+ }
1910
+ if (omissions.length > 0) {
1911
+ return new ReplayCheck("FAIL", { failures: omissions, traceDiff });
1912
+ }
1913
+ return new ReplayCheck("PASS", { traceDiff });
1914
+ }
1915
+ };
1916
+ var ReplaySuite = class _ReplaySuite {
1917
+ taskSetId;
1918
+ taskSetName;
1919
+ cases;
1920
+ /** Credentials for recording replay runs back to the platform. */
1921
+ credentials;
1922
+ constructor(fields) {
1923
+ this.taskSetId = fields.taskSetId;
1924
+ this.taskSetName = fields.taskSetName;
1925
+ this.cases = fields.cases;
1926
+ this.credentials = fields.credentials ?? null;
1927
+ }
1928
+ [Symbol.iterator]() {
1929
+ return this.cases[Symbol.iterator]();
1930
+ }
1931
+ get length() {
1932
+ return this.cases.length;
1933
+ }
1934
+ /** Look up a case by id or name (throws when absent). */
1935
+ get(key) {
1936
+ for (const testCase of this.cases) {
1937
+ if (testCase.id === key || testCase.name === key) {
1938
+ return testCase;
1939
+ }
1940
+ }
1941
+ throw new ReplayError(
1942
+ `No case '${key}' in task set ${this.taskSetName} (cases: ${JSON.stringify(this.cases.map((c) => c.name))})`
1943
+ );
1944
+ }
1945
+ static async fromTaskSet(nameOrId, options = {}) {
1946
+ const host = (options.host ?? process.env[ENV_GATEWAY_HOST] ?? "").replace(
1947
+ /\/+$/,
1948
+ ""
1949
+ );
1950
+ const publicKey = options.publicKey ?? process.env[ENV_GATEWAY_PUBLIC_KEY] ?? "";
1951
+ const secretKey = options.secretKey ?? process.env[ENV_GATEWAY_SECRET_KEY] ?? "";
1952
+ const timeoutSeconds = options.timeoutSeconds ?? DEFAULT_TIMEOUT_SECONDS;
1953
+ if (!host || !publicKey || !secretKey) {
1954
+ throw new SessionLoadError(
1955
+ "Gateway is not configured \u2014 set GATEWAY_HOST, GATEWAY_PUBLIC_KEY and GATEWAY_SECRET_KEY."
1956
+ );
1957
+ }
1958
+ const headers = { Authorization: basicAuthHeader(publicKey, secretKey) };
1959
+ const fetchTasks = async (datasetId) => {
1960
+ const tasks = [];
1961
+ let page = 0;
1962
+ for (; ; ) {
1963
+ const response = await fetch(
1964
+ `${host}/api/public/task-sets/${encodeURIComponent(datasetId)}/tasks?page=${page}&limit=200`,
1965
+ { headers, signal: AbortSignal.timeout(timeoutSeconds * 1e3) }
1966
+ );
1967
+ if (response.status === 404) {
1968
+ return null;
1969
+ }
1970
+ const text = await response.text();
1971
+ if (!response.ok) {
1972
+ throw new ReplayError(
1973
+ `Failed to list tasks for ${datasetId}: HTTP ${response.status} \u2014 ${text.slice(0, 300)}`
1974
+ );
1975
+ }
1976
+ const payload = parseJsonObject(text);
1977
+ const pageTasks = Array.isArray(payload.tasks) ? payload.tasks : [];
1978
+ tasks.push(...pageTasks.filter(isPlainObject2));
1979
+ if (tasks.length >= Number(payload.totalTasks ?? 0)) {
1980
+ return tasks;
1981
+ }
1982
+ page += 1;
1983
+ }
1984
+ };
1985
+ let taskSetId = nameOrId;
1986
+ let taskSetName = nameOrId;
1987
+ let rawTasks = await fetchTasks(nameOrId);
1988
+ if (rawTasks === null) {
1989
+ const response = await fetch(
1990
+ `${host}/api/public/task-sets?name=${encodeURIComponent(nameOrId)}`,
1991
+ { headers, signal: AbortSignal.timeout(timeoutSeconds * 1e3) }
1992
+ );
1993
+ const text = await response.text();
1994
+ if (!response.ok) {
1995
+ throw new ReplayError(
1996
+ `Failed to resolve task set '${nameOrId}': HTTP ${response.status} \u2014 ${text.slice(0, 300)}`
1997
+ );
1998
+ }
1999
+ const payload = parseJsonObject(text);
2000
+ const matches = Array.isArray(payload.taskSets) ? payload.taskSets.filter(isPlainObject2) : [];
2001
+ if (matches.length === 0) {
2002
+ throw new ReplayError(`Task set not found: ${nameOrId}`);
2003
+ }
2004
+ taskSetId = String(matches[0].datasetId);
2005
+ taskSetName = String(matches[0].name);
2006
+ rawTasks = await fetchTasks(taskSetId) ?? [];
2007
+ }
2008
+ const loader = (sessionId) => loadSession(sessionId, { host, publicKey, secretKey, timeoutSeconds });
2009
+ const cases = rawTasks.map(
2010
+ (raw) => new ReplayCase(ReplayTask.fromApi(raw), { loader })
2011
+ );
2012
+ return new _ReplaySuite({
2013
+ taskSetId,
2014
+ taskSetName,
2015
+ cases,
2016
+ credentials: { host, publicKey, secretKey, timeoutSeconds }
2017
+ });
2018
+ }
2019
+ /** Run the whole suite against `agent` — see `runSuite()`. */
2020
+ run(agent, options = {}) {
2021
+ return runSuite(this, agent, options);
2022
+ }
2023
+ /** Pin every case's recorded session into the repo as JSON fixtures. */
2024
+ async snapshot(directory) {
2025
+ const written = [];
2026
+ for (const testCase of this.cases) {
2027
+ if (!testCase.task.sourceSessionId) {
2028
+ continue;
2029
+ }
2030
+ const recording = await testCase.recording();
2031
+ written.push(
2032
+ recording.toFixture((0, import_node_path2.join)(directory, `${testCase.name}.recording.json`))
2033
+ );
2034
+ }
2035
+ return written;
2036
+ }
2037
+ };
2038
+ var ReplayReport = class {
2039
+ results;
2040
+ runName;
2041
+ recordingErrors;
2042
+ constructor(results, fields = {}) {
2043
+ this.results = results;
2044
+ this.runName = fields.runName ?? null;
2045
+ this.recordingErrors = fields.recordingErrors ?? [];
2046
+ }
2047
+ get passed() {
2048
+ return this.count("PASS");
2049
+ }
2050
+ get failed() {
2051
+ return this.count("FAIL");
2052
+ }
2053
+ get drifted() {
2054
+ return this.count("DRIFT");
2055
+ }
2056
+ /** True when nothing FAILED (drift is stale-test signal, not failure). */
2057
+ get ok() {
2058
+ return this.failed === 0;
2059
+ }
2060
+ explain() {
2061
+ const lines = [
2062
+ `${this.passed} PASS \xB7 ${this.failed} FAIL \xB7 ${this.drifted} DRIFT` + (this.runName ? ` \xB7 run '${this.runName}'` : "")
2063
+ ];
2064
+ for (const [name, check] of Object.entries(this.results)) {
2065
+ if (check.status !== "PASS") {
2066
+ lines.push(`${name}: ${check.explain()}`);
2067
+ }
2068
+ }
2069
+ for (const error of this.recordingErrors) {
2070
+ lines.push(`recording: ${error}`);
2071
+ }
2072
+ return lines.join("\n");
2073
+ }
2074
+ count(status) {
2075
+ return Object.values(this.results).filter(
2076
+ (check) => check.status === status
2077
+ ).length;
2078
+ }
2079
+ };
2080
+ var REPLAY_ENVIRONMENT = "gateway-replay";
2081
+ async function recordRunItem(suiteToRecord, testCase, runName, traceId, triage, options = {}) {
2082
+ const retries = options.retries ?? 10;
2083
+ const retryDelaySeconds = options.retryDelaySeconds ?? 3;
2084
+ const credentials = suiteToRecord.credentials;
2085
+ if (!credentials) {
2086
+ return "suite has no platform credentials";
2087
+ }
2088
+ const payload = {
2089
+ runName,
2090
+ runDescription: `gatewaysdk.replay run over '${suiteToRecord.taskSetName}'`,
2091
+ datasetItemId: testCase.id,
2092
+ traceId: traceId ?? randomHex(),
2093
+ metadata: {
2094
+ replay: true,
2095
+ status: triage.status,
2096
+ failures: triage.failures,
2097
+ drift: triage.drift,
2098
+ sourceSessionId: testCase.task.sourceSessionId
2099
+ }
2100
+ };
2101
+ let lastError = "unknown";
2102
+ for (let attempt = 0; attempt < retries; attempt++) {
2103
+ try {
2104
+ const response = await fetch(
2105
+ `${credentials.host}/api/public/dataset-run-items`,
2106
+ {
2107
+ method: "POST",
2108
+ headers: {
2109
+ Authorization: basicAuthHeader(
2110
+ credentials.publicKey,
2111
+ credentials.secretKey
2112
+ ),
2113
+ "Content-Type": "application/json"
2114
+ },
2115
+ body: JSON.stringify(payload),
2116
+ signal: AbortSignal.timeout(DEFAULT_TIMEOUT_SECONDS * 1e3)
2117
+ }
2118
+ );
2119
+ if (response.status === 200) {
2120
+ return null;
2121
+ }
2122
+ const text = await response.text();
2123
+ lastError = `HTTP ${response.status}: ${text.slice(0, 200)}`;
2124
+ if (response.status !== 404) {
2125
+ return lastError;
2126
+ }
2127
+ } catch (error) {
2128
+ lastError = error instanceof Error ? error.message : String(error);
2129
+ }
2130
+ if (attempt < retries - 1) {
2131
+ await sleep(retryDelaySeconds * 1e3);
2132
+ }
2133
+ }
2134
+ return lastError;
2135
+ }
2136
+ async function runSuite(suiteToRun, agent, options = {}) {
2137
+ const missPolicy = options.missPolicy ?? "error";
2138
+ const record = options.record ?? Boolean(suiteToRun.credentials);
2139
+ const runName = options.runName ?? `replay-${randomHex().slice(0, 8)}`;
2140
+ const results = {};
2141
+ const pendingRecords = [];
2142
+ for (const testCase of suiteToRun) {
2143
+ try {
2144
+ const stubs = await testCase.stubs({ missPolicy });
2145
+ const output = await agent(
2146
+ testCase.prompt,
2147
+ stubs.asRegistry(),
2148
+ testCase
2149
+ );
2150
+ results[testCase.name] = testCase.check(output);
2151
+ } catch (error) {
2152
+ if (error instanceof StubMissError) {
2153
+ let triage = testCase.check();
2154
+ if (triage.status !== "FAIL") {
2155
+ triage = new ReplayCheck("DRIFT", {
2156
+ drift: triage.drift.length > 0 ? triage.drift : [error.message]
2157
+ });
2158
+ }
2159
+ results[testCase.name] = triage;
2160
+ } else if (error instanceof DriftError) {
2161
+ results[testCase.name] = new ReplayCheck("DRIFT", {
2162
+ drift: [error.message]
2163
+ });
2164
+ } else {
2165
+ throw error;
2166
+ }
2167
+ }
2168
+ if (record) {
2169
+ pendingRecords.push([testCase, null, results[testCase.name]]);
2170
+ }
2171
+ }
2172
+ const recordingErrors = [];
2173
+ for (const [testCase, traceId, triage] of pendingRecords) {
2174
+ const error = await recordRunItem(
2175
+ suiteToRun,
2176
+ testCase,
2177
+ runName,
2178
+ traceId,
2179
+ triage
2180
+ );
2181
+ if (error) {
2182
+ recordingErrors.push(`${testCase.name}: ${error}`);
2183
+ }
2184
+ }
2185
+ return new ReplayReport(results, {
2186
+ runName: record ? runName : null,
2187
+ recordingErrors
2188
+ });
2189
+ }
2190
+ function suite(nameOrId, options = {}) {
2191
+ return ReplaySuite.fromTaskSet(nameOrId, options);
2192
+ }
2193
+ function isPlainObject2(value) {
2194
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2195
+ }
2196
+ function parseJsonObject(text) {
2197
+ try {
2198
+ const parsed = JSON.parse(text);
2199
+ return isPlainObject2(parsed) ? parsed : {};
2200
+ } catch {
2201
+ return {};
2202
+ }
2203
+ }
2204
+ function randomHex() {
2205
+ return crypto.randomUUID().replace(/-/g, "");
2206
+ }
2207
+ function sleep(ms) {
2208
+ return new Promise((resolve) => setTimeout(resolve, ms));
2209
+ }
2210
+ var replay = {
2211
+ suite,
2212
+ run: runSuite
2213
+ };
2214
+
969
2215
  // src/security/index.ts
970
2216
  var SECURITY_ATTRIBUTES = {
971
2217
  AGENT_ID: "gateway.agent.id",
@@ -1187,10 +2433,10 @@ var GatewaySecurity = class _GatewaySecurity {
1187
2433
  if (resolve.blockedToolIds.includes(toolId)) return false;
1188
2434
  return true;
1189
2435
  }
1190
- normalizeContext(context2) {
2436
+ normalizeContext(context4) {
1191
2437
  return {
1192
- ...context2 ?? {},
1193
- metadata: context2?.metadata ?? {}
2438
+ ...context4 ?? {},
2439
+ metadata: context4?.metadata ?? {}
1194
2440
  };
1195
2441
  }
1196
2442
  authHeader() {
@@ -1227,13 +2473,224 @@ var gateway = {
1227
2473
  fromEnv: GatewaySecurity.fromEnv
1228
2474
  };
1229
2475
 
2476
+ // src/users/index.ts
2477
+ var UserProfileError = class extends Error {
2478
+ constructor(message, options) {
2479
+ super(message);
2480
+ this.name = "UserProfileError";
2481
+ this.cause = options?.cause;
2482
+ }
2483
+ };
2484
+ var UsersClient = class _UsersClient {
2485
+ host;
2486
+ publicKey;
2487
+ secretKey;
2488
+ timeoutSeconds;
2489
+ debug;
2490
+ constructor(config) {
2491
+ this.host = config.host.replace(/\/$/, "");
2492
+ this.publicKey = config.publicKey;
2493
+ this.secretKey = config.secretKey;
2494
+ this.timeoutSeconds = config.timeoutSeconds ?? 15;
2495
+ this.debug = config.debug ?? false;
2496
+ }
2497
+ /** Create a client from GATEWAY_HOST / GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY. */
2498
+ static fromEnv(config = {}) {
2499
+ const host = config.host ?? process.env.GATEWAY_HOST;
2500
+ const publicKey = config.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;
2501
+ const secretKey = config.secretKey ?? process.env.GATEWAY_SECRET_KEY;
2502
+ const missing = [
2503
+ ["host", host],
2504
+ ["publicKey", publicKey],
2505
+ ["secretKey", secretKey]
2506
+ ].filter(([, value]) => !value).map(([name]) => name);
2507
+ if (missing.length > 0) {
2508
+ throw new UserProfileError(
2509
+ `Missing Gateway user-profile configuration: ${missing.join(", ")}`
2510
+ );
2511
+ }
2512
+ return new _UsersClient({
2513
+ ...config,
2514
+ host,
2515
+ publicKey,
2516
+ secretKey
2517
+ });
2518
+ }
2519
+ /** Fetch a user's stored profile. */
2520
+ async get(userId) {
2521
+ return parseProfile(
2522
+ await this.requestJson(
2523
+ "GET",
2524
+ `/api/public/user-profiles/${encodeURIComponent(userId)}`
2525
+ )
2526
+ );
2527
+ }
2528
+ /**
2529
+ * Upsert a user's profile. `attributes` merge with the stored set unless
2530
+ * `merge: false` (which replaces it).
2531
+ */
2532
+ async update(userId, update = {}) {
2533
+ const body = {
2534
+ userId,
2535
+ attributes: update.attributes ?? {},
2536
+ mergeAttributes: update.merge ?? true,
2537
+ ...update.displayName !== void 0 ? { displayName: update.displayName } : {},
2538
+ ...update.email !== void 0 ? { email: update.email } : {},
2539
+ ...update.notes !== void 0 ? { notes: update.notes } : {}
2540
+ };
2541
+ return parseProfile(
2542
+ await this.requestJson("POST", "/api/public/user-profiles", body)
2543
+ );
2544
+ }
2545
+ async requestJson(method, path, payload) {
2546
+ let response;
2547
+ try {
2548
+ response = await fetch(`${this.host}${path}`, {
2549
+ method,
2550
+ headers: {
2551
+ Authorization: this.authHeader(),
2552
+ "Content-Type": "application/json"
2553
+ },
2554
+ ...payload ? { body: JSON.stringify(payload) } : {},
2555
+ signal: AbortSignal.timeout(this.timeoutSeconds * 1e3)
2556
+ });
2557
+ } catch (error) {
2558
+ throw new UserProfileError(
2559
+ `${method} ${path} failed: ${error instanceof Error ? error.message : String(error)}`,
2560
+ { cause: error }
2561
+ );
2562
+ }
2563
+ const text = await response.text();
2564
+ if (!response.ok) {
2565
+ throw new UserProfileError(
2566
+ `${method} ${path} failed (${response.status}): ${text.slice(0, 500)}`
2567
+ );
2568
+ }
2569
+ this.log("%s %s -> %s", method, path, response.status);
2570
+ return safeJson4(text);
2571
+ }
2572
+ authHeader() {
2573
+ return `Basic ${Buffer.from(`${this.publicKey}:${this.secretKey}`).toString(
2574
+ "base64"
2575
+ )}`;
2576
+ }
2577
+ log(message, ...args) {
2578
+ if (this.debug) {
2579
+ console.log(`[gateway.users] ${message}`, ...args);
2580
+ }
2581
+ }
2582
+ };
2583
+ function parseProfile(payload) {
2584
+ return {
2585
+ userId: String(payload.userId ?? ""),
2586
+ displayName: typeof payload.displayName === "string" ? payload.displayName : null,
2587
+ email: typeof payload.email === "string" ? payload.email : null,
2588
+ attributes: parseAttributes(payload.attributes),
2589
+ notes: typeof payload.notes === "string" ? payload.notes : null
2590
+ };
2591
+ }
2592
+ function parseAttributes(value) {
2593
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
2594
+ const attributes = {};
2595
+ for (const [key, entry] of Object.entries(value)) {
2596
+ attributes[key] = String(entry);
2597
+ }
2598
+ return attributes;
2599
+ }
2600
+ function safeJson4(value) {
2601
+ try {
2602
+ const parsed = JSON.parse(value);
2603
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
2604
+ } catch {
2605
+ return {};
2606
+ }
2607
+ }
2608
+ var users = {
2609
+ fromEnv: UsersClient.fromEnv
2610
+ };
2611
+
2612
+ // src/tracing/identity.ts
2613
+ var import_async_hooks2 = require("async_hooks");
2614
+ var import_api = require("@opentelemetry/api");
2615
+ var USER_ID_ATTRIBUTE = "gateway.user.id";
2616
+ var currentUserStorage = new import_async_hooks2.AsyncLocalStorage();
2617
+ function resolveUserId() {
2618
+ const contextual = currentUserStorage.getStore();
2619
+ if (contextual) return contextual;
2620
+ const envUser = process.env.GATEWAY_USER_ID?.trim();
2621
+ return envUser ? envUser : void 0;
2622
+ }
2623
+ function identify(userId, options = {}) {
2624
+ const cleaned = userId.trim();
2625
+ if (!cleaned) return;
2626
+ currentUserStorage.enterWith(cleaned);
2627
+ try {
2628
+ const span = import_api.trace.getActiveSpan();
2629
+ if (span && (0, import_api.isSpanContextValid)(span.spanContext())) {
2630
+ span.setAttribute(USER_ID_ATTRIBUTE, cleaned);
2631
+ }
2632
+ } catch (error) {
2633
+ debugLog("identify(): no active span to stamp", error);
2634
+ }
2635
+ if (options.attributes || options.displayName || options.email) {
2636
+ void pushProfile(cleaned, options);
2637
+ }
2638
+ }
2639
+ async function pushProfile(userId, options) {
2640
+ try {
2641
+ const attributes = {};
2642
+ for (const [key, value] of Object.entries(options.attributes ?? {})) {
2643
+ attributes[key] = String(value);
2644
+ }
2645
+ await UsersClient.fromEnv().update(userId, {
2646
+ ...options.displayName !== void 0 ? { displayName: options.displayName } : {},
2647
+ ...options.email !== void 0 ? { email: options.email } : {},
2648
+ attributes
2649
+ });
2650
+ } catch (error) {
2651
+ debugLog("identify(): profile update failed", error);
2652
+ }
2653
+ }
2654
+ function resetAmbientUser() {
2655
+ currentUserStorage.enterWith(void 0);
2656
+ }
2657
+ var IdentitySpanProcessor = class {
2658
+ onStart(span, _parentContext) {
2659
+ const userId = resolveUserId();
2660
+ if (userId) {
2661
+ span.setAttribute(USER_ID_ATTRIBUTE, userId);
2662
+ }
2663
+ }
2664
+ onEnd(_span) {
2665
+ }
2666
+ async shutdown() {
2667
+ }
2668
+ async forceFlush() {
2669
+ }
2670
+ };
2671
+ function debugLog(message, ...args) {
2672
+ if (process.env.GATEWAY_DEBUG) {
2673
+ console.debug(`[gatewaysdk.tracing] ${message}`, ...args);
2674
+ }
2675
+ }
2676
+
1230
2677
  // src/tracing/index.ts
1231
2678
  var tracing_exports = {};
1232
2679
  __export(tracing_exports, {
2680
+ IdentitySpanProcessor: () => IdentitySpanProcessor,
2681
+ USER_ID_ATTRIBUTE: () => USER_ID_ATTRIBUTE,
1233
2682
  flush: () => flush,
2683
+ identify: () => identify,
1234
2684
  init: () => init2,
2685
+ initIsolated: () => initIsolated,
1235
2686
  isGatewayConfigured: () => isGatewayConfigured,
1236
2687
  isInitialized: () => isInitialized,
2688
+ observe: () => observe,
2689
+ observeAnthropic: () => observeAnthropic,
2690
+ observeClaude: () => observeClaude,
2691
+ observeOpenAI: () => observeOpenAI,
2692
+ resetAmbientUser: () => resetAmbientUser,
2693
+ resolveUserId: () => resolveUserId,
1237
2694
  shutdown: () => shutdown2
1238
2695
  });
1239
2696
 
@@ -1264,12 +2721,7 @@ function log(message, ...args) {
1264
2721
  function warn(message, ...args) {
1265
2722
  console.warn(`[gatewaysdk.tracing] ${message}`, ...args);
1266
2723
  }
1267
- function init2(config = {}) {
1268
- if (state.initialized) {
1269
- log("Tracing already initialized. Call shutdown() first to reinitialize.");
1270
- return;
1271
- }
1272
- state.debug = config.debug ?? false;
2724
+ function buildProvider(config, logFn) {
1273
2725
  const host = config.host ?? getEnv(ENV_VARS.HOST);
1274
2726
  const publicKey = config.publicKey ?? getEnv(ENV_VARS.PUBLIC_KEY);
1275
2727
  const secretKey = config.secretKey ?? getEnv(ENV_VARS.SECRET_KEY);
@@ -1346,17 +2798,18 @@ function init2(config = {}) {
1346
2798
  Authorization: authHeader
1347
2799
  }
1348
2800
  });
1349
- log("Configured Gateway exporter: endpoint=%s", endpoint);
2801
+ logFn("Configured Gateway exporter: endpoint=%s", endpoint);
1350
2802
  const spanProcessors = [];
1351
2803
  if (config.customSpanProcessors) {
1352
2804
  for (const sp of config.customSpanProcessors) {
1353
2805
  spanProcessors.push(sp);
1354
- log(
2806
+ logFn(
1355
2807
  "Added custom span processor: %s",
1356
2808
  sp.constructor?.name ?? "unknown"
1357
2809
  );
1358
2810
  }
1359
2811
  }
2812
+ spanProcessors.push(new IdentitySpanProcessor());
1360
2813
  const batchConfig = {};
1361
2814
  if (config.batch?.maxQueueSize) {
1362
2815
  batchConfig.maxQueueSize = config.batch.maxQueueSize;
@@ -1381,6 +2834,15 @@ function init2(config = {}) {
1381
2834
  spanProcessors
1382
2835
  });
1383
2836
  }
2837
+ return provider;
2838
+ }
2839
+ function init2(config = {}) {
2840
+ if (state.initialized) {
2841
+ log("Tracing already initialized. Call shutdown() first to reinitialize.");
2842
+ return;
2843
+ }
2844
+ state.debug = config.debug ?? false;
2845
+ const provider = buildProvider(config, log);
1384
2846
  provider.register();
1385
2847
  state.provider = provider;
1386
2848
  state.initialized = true;
@@ -1389,6 +2851,33 @@ function init2(config = {}) {
1389
2851
  config.serviceName ?? "gatewaysdk-tracing"
1390
2852
  );
1391
2853
  }
2854
+ function initIsolated(config = {}) {
2855
+ const debugLog2 = config.debug ? (message, ...args) => console.log(`[gatewaysdk.tracing:isolated] ${message}`, ...args) : () => {
2856
+ };
2857
+ const provider = buildProvider(config, debugLog2);
2858
+ const tracer = provider.getTracer("@withgateway/sdk");
2859
+ debugLog2(
2860
+ "Isolated tracing provider created (service=%s)",
2861
+ config.serviceName ?? "gatewaysdk-tracing"
2862
+ );
2863
+ return {
2864
+ tracer,
2865
+ async flush() {
2866
+ try {
2867
+ await provider.forceFlush();
2868
+ } catch (e) {
2869
+ warn("Error during isolated flush:", e);
2870
+ }
2871
+ },
2872
+ async shutdown() {
2873
+ try {
2874
+ await provider.shutdown();
2875
+ } catch (e) {
2876
+ warn("Error during isolated shutdown:", e);
2877
+ }
2878
+ }
2879
+ };
2880
+ }
1392
2881
  async function flush() {
1393
2882
  if (!state.provider) {
1394
2883
  log("No provider to flush");
@@ -1425,6 +2914,178 @@ function isGatewayConfigured() {
1425
2914
  return !!(host && publicKey && secretKey);
1426
2915
  }
1427
2916
 
2917
+ // src/tracing/observe.ts
2918
+ var import_api2 = require("@opentelemetry/api");
2919
+ function asAttr(value) {
2920
+ return typeof value === "string" ? value : JSON.stringify(value);
2921
+ }
2922
+ async function observe(name, fn, options = {}) {
2923
+ const tracer = options.tracer ?? import_api2.trace.getTracer("@withgateway/sdk");
2924
+ const span = tracer.startSpan(name, {
2925
+ attributes: {
2926
+ "openinference.span.kind": options.kind ?? "AGENT",
2927
+ ...options.input !== void 0 ? { "input.value": asAttr(options.input) } : {},
2928
+ ...options.attributes ?? {}
2929
+ }
2930
+ });
2931
+ try {
2932
+ const result = await import_api2.context.with(
2933
+ import_api2.trace.setSpan(import_api2.context.active(), span),
2934
+ fn
2935
+ );
2936
+ if (options.captureOutput !== false && result !== void 0) {
2937
+ span.setAttribute("output.value", asAttr(result));
2938
+ }
2939
+ span.setStatus({ code: import_api2.SpanStatusCode.OK });
2940
+ return result;
2941
+ } catch (error) {
2942
+ span.setStatus({
2943
+ code: import_api2.SpanStatusCode.ERROR,
2944
+ message: error instanceof Error ? error.message : String(error)
2945
+ });
2946
+ throw error;
2947
+ } finally {
2948
+ span.end();
2949
+ }
2950
+ }
2951
+
2952
+ // src/tracing/instrument.ts
2953
+ function warn2(message, ...args) {
2954
+ console.warn(`[gatewaysdk.tracing] ${message}`, ...args);
2955
+ }
2956
+ function observeOpenAI(client2) {
2957
+ try {
2958
+ const {
2959
+ OpenAIInstrumentation
2960
+ } = require("@arizeai/openinference-instrumentation-openai");
2961
+ const OpenAIClass = client2.constructor;
2962
+ new OpenAIInstrumentation().manuallyInstrument({ OpenAI: OpenAIClass });
2963
+ } catch (error) {
2964
+ warn2(
2965
+ "observeOpenAI: could not load @arizeai/openinference-instrumentation-openai \u2014 OpenAI calls will not be traced.",
2966
+ error
2967
+ );
2968
+ }
2969
+ return client2;
2970
+ }
2971
+ function observeAnthropic(client2) {
2972
+ try {
2973
+ const {
2974
+ AnthropicInstrumentation
2975
+ } = require("@arizeai/openinference-instrumentation-anthropic");
2976
+ const AnthropicClass = client2.constructor;
2977
+ new AnthropicInstrumentation().manuallyInstrument({
2978
+ Messages: AnthropicClass.Messages
2979
+ });
2980
+ } catch (error) {
2981
+ warn2(
2982
+ "observeAnthropic: could not load @arizeai/openinference-instrumentation-anthropic \u2014 Anthropic calls will not be traced.",
2983
+ error
2984
+ );
2985
+ }
2986
+ return client2;
2987
+ }
2988
+
2989
+ // src/tracing/claude.ts
2990
+ var import_api3 = require("@opentelemetry/api");
2991
+ function cleanToolName(name) {
2992
+ return name.replace(/^mcp__[^_]+__/, "");
2993
+ }
2994
+ function toolResultText(content) {
2995
+ if (typeof content === "string") return content;
2996
+ if (Array.isArray(content))
2997
+ return content.map(
2998
+ (b) => b && typeof b === "object" && "text" in b ? String(b.text) : JSON.stringify(b)
2999
+ ).join("");
3000
+ return JSON.stringify(content ?? "");
3001
+ }
3002
+ async function* observeClaude(stream, options) {
3003
+ const tracer = options.tracer ?? import_api3.trace.getTracer("@withgateway/sdk");
3004
+ const root = tracer.startSpan(options.name, {
3005
+ attributes: {
3006
+ "openinference.span.kind": "AGENT",
3007
+ ...options.input !== void 0 ? { "input.value": options.input } : {},
3008
+ ...options.attributes ?? {}
3009
+ }
3010
+ });
3011
+ const rootCtx = import_api3.trace.setSpan(import_api3.context.active(), root);
3012
+ const openTools = /* @__PURE__ */ new Map();
3013
+ const model = options.model ?? "claude";
3014
+ let finalText = "";
3015
+ try {
3016
+ for await (const message of stream) {
3017
+ if (message?.type === "assistant") {
3018
+ let turnText = "";
3019
+ const toolUses = [];
3020
+ for (const block of message.message?.content ?? []) {
3021
+ if (block?.type === "text") {
3022
+ finalText += block.text;
3023
+ turnText += block.text;
3024
+ }
3025
+ if (block?.type === "tool_use") {
3026
+ toolUses.push({ id: block.id, name: block.name, input: block.input });
3027
+ }
3028
+ }
3029
+ const gen = tracer.startSpan(
3030
+ "assistant",
3031
+ {
3032
+ attributes: {
3033
+ "openinference.span.kind": "LLM",
3034
+ "llm.model_name": model,
3035
+ "llm.provider": "anthropic",
3036
+ "output.value": turnText || toolUses.map((t) => `\u2192 ${cleanToolName(t.name)}`).join(", ")
3037
+ }
3038
+ },
3039
+ rootCtx
3040
+ );
3041
+ const usage = message.message?.usage;
3042
+ if (usage?.input_tokens != null)
3043
+ gen.setAttribute("llm.token_count.prompt", usage.input_tokens);
3044
+ if (usage?.output_tokens != null)
3045
+ gen.setAttribute("llm.token_count.completion", usage.output_tokens);
3046
+ gen.end();
3047
+ for (const t of toolUses) {
3048
+ const span = tracer.startSpan(
3049
+ `tool.${cleanToolName(t.name)}`,
3050
+ {
3051
+ attributes: {
3052
+ "openinference.span.kind": "TOOL",
3053
+ "tool.name": cleanToolName(t.name),
3054
+ "input.value": JSON.stringify(t.input)
3055
+ }
3056
+ },
3057
+ rootCtx
3058
+ );
3059
+ openTools.set(t.id, span);
3060
+ }
3061
+ }
3062
+ if (message?.type === "user") {
3063
+ const content = message.message?.content;
3064
+ if (Array.isArray(content)) {
3065
+ for (const block of content) {
3066
+ if (block?.type === "tool_result") {
3067
+ const span = openTools.get(block.tool_use_id);
3068
+ if (span) {
3069
+ span.setAttribute("output.value", toolResultText(block.content));
3070
+ span.setStatus({ code: import_api3.SpanStatusCode.OK });
3071
+ span.end();
3072
+ openTools.delete(block.tool_use_id);
3073
+ }
3074
+ }
3075
+ }
3076
+ }
3077
+ }
3078
+ yield message;
3079
+ }
3080
+ } finally {
3081
+ for (const span of openTools.values()) span.end();
3082
+ openTools.clear();
3083
+ root.setAttribute("output.value", finalText);
3084
+ root.setStatus({ code: import_api3.SpanStatusCode.OK });
3085
+ root.end();
3086
+ }
3087
+ }
3088
+
1428
3089
  // src/index.ts
1429
3090
  var tracing = {
1430
3091
  ...tracing_exports,
@@ -1444,6 +3105,11 @@ var tracing = {
1444
3105
  };
1445
3106
  // Annotate the CommonJS export names for ESM import in node:
1446
3107
  0 && (module.exports = {
3108
+ DEFAULT_TIMEOUT_SECONDS,
3109
+ DriftError,
3110
+ ENV_GATEWAY_HOST,
3111
+ ENV_GATEWAY_PUBLIC_KEY,
3112
+ ENV_GATEWAY_SECRET_KEY,
1447
3113
  EXPERIMENT_ATTRIBUTES,
1448
3114
  ExperimentClient,
1449
3115
  ExperimentSpanProcessor,
@@ -1458,8 +3124,27 @@ var tracing = {
1458
3124
  GatewaySecurityError,
1459
3125
  GatewayToolApprovalRequiredError,
1460
3126
  GatewayToolBlockedError,
3127
+ Persona,
3128
+ PersonaError,
3129
+ PersonasClient,
3130
+ REPLAY_ENVIRONMENT,
3131
+ ReplayCase,
3132
+ ReplayCheck,
3133
+ ReplayError,
3134
+ ReplayReport,
3135
+ ReplaySuite,
3136
+ ReplayTask,
3137
+ SessionLoadError,
3138
+ SessionRecording,
3139
+ SessionTrace,
3140
+ StubMissError,
3141
+ ToolStubRegistry,
3142
+ TraceDiff,
3143
+ UserProfileError,
3144
+ UsersClient,
1461
3145
  addExperimentAttributes,
1462
3146
  assignVariant,
3147
+ basicAuthHeader,
1463
3148
  clearExperimentContext,
1464
3149
  computeHash,
1465
3150
  context,
@@ -1467,10 +3152,20 @@ var tracing = {
1467
3152
  experiments,
1468
3153
  gateway,
1469
3154
  getExperimentContext,
3155
+ identify,
3156
+ loadSession,
1470
3157
  memory,
3158
+ personas,
1471
3159
  renderAgentSystem,
3160
+ replay,
3161
+ resolveUserId,
3162
+ runSuite,
1472
3163
  runWithExperimentContext,
3164
+ sessionObservationFromApi,
3165
+ sessions,
1473
3166
  setExperimentContext,
1474
- tracing
3167
+ suite,
3168
+ tracing,
3169
+ users
1475
3170
  });
1476
3171
  //# sourceMappingURL=index.js.map