@withgateway/sdk 0.1.4 → 0.1.6
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-DnowA8MG.d.mts +447 -0
- package/dist/index-DnowA8MG.d.ts +447 -0
- package/dist/index.d.mts +6 -1
- package/dist/index.d.ts +6 -1
- package/dist/index.js +1551 -33
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1511 -27
- package/dist/index.mjs.map +1 -1
- package/dist/personas/index.d.mts +102 -0
- package/dist/personas/index.d.ts +102 -0
- package/dist/personas/index.js +205 -0
- package/dist/personas/index.js.map +1 -0
- package/dist/personas/index.mjs +180 -0
- package/dist/personas/index.mjs.map +1 -0
- package/dist/replay/index.d.mts +351 -0
- package/dist/replay/index.d.ts +351 -0
- package/dist/replay/index.js +1094 -0
- package/dist/replay/index.js.map +1 -0
- package/dist/replay/index.mjs +1057 -0
- package/dist/replay/index.mjs.map +1 -0
- package/dist/sessions/index.d.mts +143 -0
- package/dist/sessions/index.d.ts +143 -0
- package/dist/sessions/index.js +320 -0
- package/dist/sessions/index.js.map +1 -0
- package/dist/sessions/index.mjs +288 -0
- package/dist/sessions/index.mjs.map +1 -0
- package/dist/tracing/index.d.mts +3 -1
- package/dist/tracing/index.d.ts +3 -1
- package/dist/tracing/index.js +277 -31
- package/dist/tracing/index.js.map +1 -1
- package/dist/tracing/index.mjs +266 -26
- package/dist/tracing/index.mjs.map +1 -1
- package/dist/users/index.d.mts +81 -0
- package/dist/users/index.d.ts +81 -0
- package/dist/users/index.js +168 -0
- package/dist/users/index.js.map +1 -0
- package/dist/users/index.mjs +144 -0
- package/dist/users/index.mjs.map +1 -0
- package/package.json +21 -1
- package/dist/index-yJgb8wh6.d.mts +0 -273
- package/dist/index-yJgb8wh6.d.ts +0 -273
|
@@ -0,0 +1,1057 @@
|
|
|
1
|
+
import { createRequire as __gatewayCreateRequire } from "module";
|
|
2
|
+
const require = __gatewayCreateRequire(import.meta.url);
|
|
3
|
+
|
|
4
|
+
// src/sessions/index.ts
|
|
5
|
+
import { mkdirSync, writeFileSync } from "fs";
|
|
6
|
+
import { dirname } from "path";
|
|
7
|
+
var ENV_GATEWAY_HOST = "GATEWAY_HOST";
|
|
8
|
+
var ENV_GATEWAY_PUBLIC_KEY = "GATEWAY_PUBLIC_KEY";
|
|
9
|
+
var ENV_GATEWAY_SECRET_KEY = "GATEWAY_SECRET_KEY";
|
|
10
|
+
var DEFAULT_TIMEOUT_SECONDS = 30;
|
|
11
|
+
var SessionLoadError = class extends Error {
|
|
12
|
+
constructor(message, options) {
|
|
13
|
+
super(message);
|
|
14
|
+
this.name = "SessionLoadError";
|
|
15
|
+
this.cause = options?.cause;
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
function sessionObservationFromApi(raw) {
|
|
19
|
+
return {
|
|
20
|
+
id: String(raw.id ?? ""),
|
|
21
|
+
type: asStringOrNull(raw.type),
|
|
22
|
+
name: asStringOrNull(raw.name),
|
|
23
|
+
level: asStringOrNull(raw.level),
|
|
24
|
+
statusMessage: asStringOrNull(raw.statusMessage),
|
|
25
|
+
model: asStringOrNull(raw.model),
|
|
26
|
+
input: raw.input,
|
|
27
|
+
output: raw.output,
|
|
28
|
+
metadata: raw.metadata ?? null,
|
|
29
|
+
parentObservationId: asStringOrNull(raw.parentObservationId),
|
|
30
|
+
startTime: raw.startTime ? String(raw.startTime) : null,
|
|
31
|
+
endTime: raw.endTime ? String(raw.endTime) : null
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
var SessionTrace = class _SessionTrace {
|
|
35
|
+
id;
|
|
36
|
+
name;
|
|
37
|
+
timestamp;
|
|
38
|
+
input;
|
|
39
|
+
output;
|
|
40
|
+
metadata;
|
|
41
|
+
tags;
|
|
42
|
+
observations;
|
|
43
|
+
constructor(fields) {
|
|
44
|
+
this.id = fields.id;
|
|
45
|
+
this.name = fields.name;
|
|
46
|
+
this.timestamp = fields.timestamp;
|
|
47
|
+
this.input = fields.input;
|
|
48
|
+
this.output = fields.output;
|
|
49
|
+
this.metadata = fields.metadata ?? null;
|
|
50
|
+
this.tags = fields.tags ?? [];
|
|
51
|
+
this.observations = fields.observations ?? [];
|
|
52
|
+
}
|
|
53
|
+
get toolCalls() {
|
|
54
|
+
return this.observations.filter(
|
|
55
|
+
(o) => (o.type ?? "").toUpperCase() === "TOOL"
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
get generations() {
|
|
59
|
+
return this.observations.filter(
|
|
60
|
+
(o) => (o.type ?? "").toUpperCase() === "GENERATION"
|
|
61
|
+
);
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* The user message that started this turn.
|
|
65
|
+
*
|
|
66
|
+
* Handles the common recorded shapes: a plain string input, an OpenAI
|
|
67
|
+
* message list (last role=user entry wins — earlier ones are carried
|
|
68
|
+
* history), or an object with a content/input field.
|
|
69
|
+
*/
|
|
70
|
+
userMessage() {
|
|
71
|
+
const value = this.input;
|
|
72
|
+
if (typeof value === "string") {
|
|
73
|
+
return value;
|
|
74
|
+
}
|
|
75
|
+
if (Array.isArray(value)) {
|
|
76
|
+
for (let i = value.length - 1; i >= 0; i--) {
|
|
77
|
+
const entry = value[i];
|
|
78
|
+
if (isPlainObject(entry) && entry.role === "user") {
|
|
79
|
+
const content = entry.content;
|
|
80
|
+
if (typeof content === "string") {
|
|
81
|
+
return content;
|
|
82
|
+
}
|
|
83
|
+
if (Array.isArray(content)) {
|
|
84
|
+
const parts = content.filter(isPlainObject).map((part) => typeof part.text === "string" ? part.text : "");
|
|
85
|
+
return parts.join("") || null;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
if (isPlainObject(value)) {
|
|
92
|
+
for (const key of ["content", "input", "text", "message"]) {
|
|
93
|
+
if (typeof value[key] === "string") {
|
|
94
|
+
return value[key];
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
static fromApi(raw) {
|
|
101
|
+
return new _SessionTrace({
|
|
102
|
+
id: String(raw.id ?? ""),
|
|
103
|
+
name: asStringOrNull(raw.name),
|
|
104
|
+
timestamp: raw.timestamp ? String(raw.timestamp) : null,
|
|
105
|
+
input: raw.input,
|
|
106
|
+
output: raw.output,
|
|
107
|
+
metadata: raw.metadata ?? null,
|
|
108
|
+
tags: Array.isArray(raw.tags) ? raw.tags.map(String) : [],
|
|
109
|
+
observations: (Array.isArray(raw.observations) ? raw.observations : []).filter(isPlainObject).map(sessionObservationFromApi)
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
var SessionRecording = class _SessionRecording {
|
|
114
|
+
sessionId;
|
|
115
|
+
projectId;
|
|
116
|
+
environment;
|
|
117
|
+
traces;
|
|
118
|
+
constructor(fields) {
|
|
119
|
+
this.sessionId = fields.sessionId;
|
|
120
|
+
this.projectId = fields.projectId;
|
|
121
|
+
this.environment = fields.environment;
|
|
122
|
+
this.traces = fields.traces ?? [];
|
|
123
|
+
}
|
|
124
|
+
/** Traces in chronological order — one per agent turn. */
|
|
125
|
+
turns() {
|
|
126
|
+
return [...this.traces].sort((a, b) => {
|
|
127
|
+
const left = a.timestamp ?? "";
|
|
128
|
+
const right = b.timestamp ?? "";
|
|
129
|
+
return left < right ? -1 : left > right ? 1 : 0;
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
/** The nth chronological turn (negative indices allowed). */
|
|
133
|
+
turn(index) {
|
|
134
|
+
const ordered = this.turns();
|
|
135
|
+
const found = ordered.at(index);
|
|
136
|
+
if (!found) {
|
|
137
|
+
throw new RangeError(
|
|
138
|
+
`Turn index ${index} out of range (session has ${ordered.length} turns)`
|
|
139
|
+
);
|
|
140
|
+
}
|
|
141
|
+
return found;
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* The user message of each turn, in order — feed these back to an agent
|
|
145
|
+
* to re-drive the recorded conversation.
|
|
146
|
+
*/
|
|
147
|
+
userMessages() {
|
|
148
|
+
return this.turns().map((trace) => trace.userMessage());
|
|
149
|
+
}
|
|
150
|
+
/** Output of the last chronological turn (null when empty). */
|
|
151
|
+
finalOutput() {
|
|
152
|
+
const ordered = this.turns();
|
|
153
|
+
return ordered.length > 0 ? ordered[ordered.length - 1].output : null;
|
|
154
|
+
}
|
|
155
|
+
/** Every TOOL observation across the session, chronological. */
|
|
156
|
+
toolCalls() {
|
|
157
|
+
return this.select({ type: "TOOL" });
|
|
158
|
+
}
|
|
159
|
+
/** Every GENERATION observation across the session, chronological. */
|
|
160
|
+
generations() {
|
|
161
|
+
return this.select({ type: "GENERATION" });
|
|
162
|
+
}
|
|
163
|
+
/** Filter observations across all turns (chronological order). */
|
|
164
|
+
select(filter = {}) {
|
|
165
|
+
const selected = [];
|
|
166
|
+
for (const trace of this.turns()) {
|
|
167
|
+
for (const observation of trace.observations) {
|
|
168
|
+
if (filter.type && (observation.type ?? "").toUpperCase() !== filter.type.toUpperCase()) {
|
|
169
|
+
continue;
|
|
170
|
+
}
|
|
171
|
+
if (filter.name && observation.name !== filter.name) {
|
|
172
|
+
continue;
|
|
173
|
+
}
|
|
174
|
+
if (filter.level && (observation.level ?? "").toUpperCase() !== filter.level.toUpperCase()) {
|
|
175
|
+
continue;
|
|
176
|
+
}
|
|
177
|
+
selected.push(observation);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
return selected;
|
|
181
|
+
}
|
|
182
|
+
toJSON() {
|
|
183
|
+
return {
|
|
184
|
+
sessionId: this.sessionId,
|
|
185
|
+
projectId: this.projectId,
|
|
186
|
+
environment: this.environment,
|
|
187
|
+
traces: this.turns().map((trace) => ({
|
|
188
|
+
id: trace.id,
|
|
189
|
+
name: trace.name,
|
|
190
|
+
timestamp: trace.timestamp,
|
|
191
|
+
input: trace.input,
|
|
192
|
+
output: trace.output,
|
|
193
|
+
metadata: trace.metadata,
|
|
194
|
+
tags: trace.tags,
|
|
195
|
+
observations: trace.observations.map((o) => ({ ...o }))
|
|
196
|
+
}))
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
/** Dump the full session as a JSON fixture (for regression tests). */
|
|
200
|
+
toFixture(path) {
|
|
201
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
202
|
+
writeFileSync(path, JSON.stringify(this.toJSON(), null, 2), "utf-8");
|
|
203
|
+
return path;
|
|
204
|
+
}
|
|
205
|
+
static fromApi(raw) {
|
|
206
|
+
return new _SessionRecording({
|
|
207
|
+
sessionId: String(raw.id ?? ""),
|
|
208
|
+
projectId: asStringOrNull(raw.projectId),
|
|
209
|
+
environment: asStringOrNull(raw.environment),
|
|
210
|
+
traces: (Array.isArray(raw.traces) ? raw.traces : []).filter(isPlainObject).map(SessionTrace.fromApi)
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
};
|
|
214
|
+
async function loadSession(sessionId, options = {}) {
|
|
215
|
+
const host = (options.host ?? process.env[ENV_GATEWAY_HOST] ?? "").replace(
|
|
216
|
+
/\/+$/,
|
|
217
|
+
""
|
|
218
|
+
);
|
|
219
|
+
const publicKey = options.publicKey ?? process.env[ENV_GATEWAY_PUBLIC_KEY] ?? "";
|
|
220
|
+
const secretKey = options.secretKey ?? process.env[ENV_GATEWAY_SECRET_KEY] ?? "";
|
|
221
|
+
const timeoutSeconds = options.timeoutSeconds ?? DEFAULT_TIMEOUT_SECONDS;
|
|
222
|
+
if (!host || !publicKey || !secretKey) {
|
|
223
|
+
throw new SessionLoadError(
|
|
224
|
+
"Gateway is not configured \u2014 set GATEWAY_HOST, GATEWAY_PUBLIC_KEY and GATEWAY_SECRET_KEY (or pass host/publicKey/secretKey)."
|
|
225
|
+
);
|
|
226
|
+
}
|
|
227
|
+
const url = `${host}/api/public/sessions/${encodeURIComponent(sessionId)}?includeIO=true`;
|
|
228
|
+
let response;
|
|
229
|
+
try {
|
|
230
|
+
response = await fetch(url, {
|
|
231
|
+
method: "GET",
|
|
232
|
+
headers: { Authorization: basicAuthHeader(publicKey, secretKey) },
|
|
233
|
+
signal: AbortSignal.timeout(timeoutSeconds * 1e3)
|
|
234
|
+
});
|
|
235
|
+
} catch (error) {
|
|
236
|
+
throw new SessionLoadError(
|
|
237
|
+
`Failed to load session ${sessionId}: ${error instanceof Error ? error.message : String(error)}`,
|
|
238
|
+
{ cause: error }
|
|
239
|
+
);
|
|
240
|
+
}
|
|
241
|
+
if (response.status === 404) {
|
|
242
|
+
throw new SessionLoadError(`Session not found: ${sessionId}`);
|
|
243
|
+
}
|
|
244
|
+
const text = await response.text();
|
|
245
|
+
if (!response.ok) {
|
|
246
|
+
throw new SessionLoadError(
|
|
247
|
+
`Failed to load session ${sessionId}: HTTP ${response.status} \u2014 ${text.slice(0, 300)}`
|
|
248
|
+
);
|
|
249
|
+
}
|
|
250
|
+
let payload;
|
|
251
|
+
try {
|
|
252
|
+
payload = JSON.parse(text);
|
|
253
|
+
} catch (error) {
|
|
254
|
+
throw new SessionLoadError(
|
|
255
|
+
`Failed to load session ${sessionId}: response is not valid JSON`,
|
|
256
|
+
{ cause: error }
|
|
257
|
+
);
|
|
258
|
+
}
|
|
259
|
+
return SessionRecording.fromApi(
|
|
260
|
+
isPlainObject(payload) ? payload : {}
|
|
261
|
+
);
|
|
262
|
+
}
|
|
263
|
+
function basicAuthHeader(publicKey, secretKey) {
|
|
264
|
+
return `Basic ${Buffer.from(`${publicKey}:${secretKey}`).toString("base64")}`;
|
|
265
|
+
}
|
|
266
|
+
function asStringOrNull(value) {
|
|
267
|
+
return typeof value === "string" ? value : null;
|
|
268
|
+
}
|
|
269
|
+
function isPlainObject(value) {
|
|
270
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
// src/replay/index.ts
|
|
274
|
+
import { join } from "path";
|
|
275
|
+
var ReplayError = class extends Error {
|
|
276
|
+
constructor(message, options) {
|
|
277
|
+
super(message);
|
|
278
|
+
this.name = "ReplayError";
|
|
279
|
+
this.cause = options?.cause;
|
|
280
|
+
}
|
|
281
|
+
};
|
|
282
|
+
var StubMissError = class extends Error {
|
|
283
|
+
constructor(message) {
|
|
284
|
+
super(message);
|
|
285
|
+
this.name = "StubMissError";
|
|
286
|
+
}
|
|
287
|
+
};
|
|
288
|
+
var DriftError = class extends ReplayError {
|
|
289
|
+
constructor(message) {
|
|
290
|
+
super(message);
|
|
291
|
+
this.name = "DriftError";
|
|
292
|
+
}
|
|
293
|
+
};
|
|
294
|
+
var WRAPPER_KEYS = ["args_json", "arguments", "kwargs", "args", "input"];
|
|
295
|
+
function canonicalize(value) {
|
|
296
|
+
if (typeof value === "string") {
|
|
297
|
+
const stripped = value.trim();
|
|
298
|
+
if (stripped.startsWith("{") || stripped.startsWith("[")) {
|
|
299
|
+
try {
|
|
300
|
+
return canonicalize(JSON.parse(stripped));
|
|
301
|
+
} catch {
|
|
302
|
+
return value;
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
return value;
|
|
306
|
+
}
|
|
307
|
+
if (Array.isArray(value)) {
|
|
308
|
+
return value.map(canonicalize);
|
|
309
|
+
}
|
|
310
|
+
if (isPlainObject2(value)) {
|
|
311
|
+
const entries = Object.entries(value);
|
|
312
|
+
if (entries.length === 1 && WRAPPER_KEYS.includes(entries[0][0])) {
|
|
313
|
+
return canonicalize(entries[0][1]);
|
|
314
|
+
}
|
|
315
|
+
return Object.fromEntries(
|
|
316
|
+
entries.map(([key, inner]) => [key, canonicalize(inner)])
|
|
317
|
+
);
|
|
318
|
+
}
|
|
319
|
+
return value;
|
|
320
|
+
}
|
|
321
|
+
function sortKeysDeep(value) {
|
|
322
|
+
if (Array.isArray(value)) {
|
|
323
|
+
return value.map(sortKeysDeep);
|
|
324
|
+
}
|
|
325
|
+
if (isPlainObject2(value)) {
|
|
326
|
+
const sorted = {};
|
|
327
|
+
for (const key of Object.keys(value).sort()) {
|
|
328
|
+
sorted[key] = sortKeysDeep(value[key]);
|
|
329
|
+
}
|
|
330
|
+
return sorted;
|
|
331
|
+
}
|
|
332
|
+
return value;
|
|
333
|
+
}
|
|
334
|
+
function normalizeInput(value) {
|
|
335
|
+
try {
|
|
336
|
+
return JSON.stringify(sortKeysDeep(canonicalize(value ?? null))) ?? "null";
|
|
337
|
+
} catch {
|
|
338
|
+
return String(value);
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
var ToolStubRegistry = class _ToolStubRegistry {
|
|
342
|
+
callLog = [];
|
|
343
|
+
driftEvents = [];
|
|
344
|
+
recorded;
|
|
345
|
+
consumed = /* @__PURE__ */ new Set();
|
|
346
|
+
consumptionOrder = [];
|
|
347
|
+
missPolicy;
|
|
348
|
+
fallback;
|
|
349
|
+
local;
|
|
350
|
+
constructor(calls, options = {}) {
|
|
351
|
+
const missPolicy = options.missPolicy ?? "error";
|
|
352
|
+
if (!["error", "reuse", "passthrough"].includes(missPolicy)) {
|
|
353
|
+
throw new ReplayError(`Unknown missPolicy: ${missPolicy}`);
|
|
354
|
+
}
|
|
355
|
+
this.recorded = calls;
|
|
356
|
+
this.missPolicy = missPolicy;
|
|
357
|
+
this.fallback = options.fallback ?? null;
|
|
358
|
+
this.local = { ...options.local ?? {} };
|
|
359
|
+
}
|
|
360
|
+
static fromSession(session, options = {}) {
|
|
361
|
+
const calls = session.toolCalls().map(
|
|
362
|
+
(observation) => ({
|
|
363
|
+
name: observation.name ?? "",
|
|
364
|
+
input: observation.input,
|
|
365
|
+
output: observation.output,
|
|
366
|
+
observationId: observation.id
|
|
367
|
+
})
|
|
368
|
+
);
|
|
369
|
+
return new _ToolStubRegistry(calls, options);
|
|
370
|
+
}
|
|
371
|
+
/** Resolve a tool call against the recorded world. */
|
|
372
|
+
lookup(toolName, toolInput = null) {
|
|
373
|
+
if (toolName in this.local) {
|
|
374
|
+
this.callLog.push({ tool: toolName, match: "local", input: toolInput });
|
|
375
|
+
return this.local[toolName](toolInput);
|
|
376
|
+
}
|
|
377
|
+
const normalized = normalizeInput(toolInput);
|
|
378
|
+
for (let index = 0; index < this.recorded.length; index++) {
|
|
379
|
+
const record = this.recorded[index];
|
|
380
|
+
if (!this.consumed.has(index) && record.name === toolName && normalizeInput(record.input) === normalized) {
|
|
381
|
+
this.consumed.add(index);
|
|
382
|
+
this.consumptionOrder.push(index);
|
|
383
|
+
this.callLog.push({ tool: toolName, match: "exact", input: toolInput });
|
|
384
|
+
return record.output;
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
for (let index = this.recorded.length - 1; index >= 0; index--) {
|
|
388
|
+
const record = this.recorded[index];
|
|
389
|
+
if (record.name === toolName && normalizeInput(record.input) === normalized) {
|
|
390
|
+
this.callLog.push({
|
|
391
|
+
tool: toolName,
|
|
392
|
+
match: "exact-repeat",
|
|
393
|
+
input: toolInput
|
|
394
|
+
});
|
|
395
|
+
return record.output;
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
for (let index = 0; index < this.recorded.length; index++) {
|
|
399
|
+
const record = this.recorded[index];
|
|
400
|
+
if (!this.consumed.has(index) && record.name === toolName) {
|
|
401
|
+
this.consumed.add(index);
|
|
402
|
+
this.consumptionOrder.push(index);
|
|
403
|
+
this.callLog.push({
|
|
404
|
+
tool: toolName,
|
|
405
|
+
match: "ordinal",
|
|
406
|
+
input: toolInput
|
|
407
|
+
});
|
|
408
|
+
return record.output;
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
if (this.missPolicy === "reuse") {
|
|
412
|
+
for (let index = this.recorded.length - 1; index >= 0; index--) {
|
|
413
|
+
const record = this.recorded[index];
|
|
414
|
+
if (record.name === toolName) {
|
|
415
|
+
this.driftEvents.push(
|
|
416
|
+
`recordings for tool '${toolName}' exhausted \u2014 replayed the last one again (reuse policy)`
|
|
417
|
+
);
|
|
418
|
+
this.callLog.push({
|
|
419
|
+
tool: toolName,
|
|
420
|
+
match: "reuse",
|
|
421
|
+
input: toolInput
|
|
422
|
+
});
|
|
423
|
+
return record.output;
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
const recordedNames = [...new Set(this.recorded.map((r) => r.name))].sort();
|
|
428
|
+
const drift = `no recording for tool '${toolName}' (recorded tools: ${JSON.stringify(recordedNames)})`;
|
|
429
|
+
this.driftEvents.push(drift);
|
|
430
|
+
this.callLog.push({ tool: toolName, match: "miss", input: toolInput });
|
|
431
|
+
if (this.fallback !== null && (this.missPolicy === "passthrough" || this.missPolicy === "reuse")) {
|
|
432
|
+
return this.fallback(toolName, toolInput);
|
|
433
|
+
}
|
|
434
|
+
throw new StubMissError(drift);
|
|
435
|
+
}
|
|
436
|
+
/**
|
|
437
|
+
* Mapping of toolName → callable, drop-in for most agent tool layers.
|
|
438
|
+
*
|
|
439
|
+
* `local` merges in tools that should ALWAYS run live (new tools the
|
|
440
|
+
* recording predates, or deterministic/pure helpers) — they're logged for
|
|
441
|
+
* the contract check but never count as drift.
|
|
442
|
+
*
|
|
443
|
+
* UNKNOWN tool names also resolve (to a stub that routes through
|
|
444
|
+
* `lookup()`), so a call to an un-recorded tool is LOGGED and follows the
|
|
445
|
+
* miss policy instead of dying on an undefined lookup — that log is what
|
|
446
|
+
* lets `check()` classify a forbidden-but-unrecorded call as FAIL.
|
|
447
|
+
*/
|
|
448
|
+
asRegistry(options = {}) {
|
|
449
|
+
if (options.fallback) {
|
|
450
|
+
this.fallback = options.fallback;
|
|
451
|
+
this.missPolicy = "passthrough";
|
|
452
|
+
}
|
|
453
|
+
if (options.local) {
|
|
454
|
+
Object.assign(this.local, options.local);
|
|
455
|
+
}
|
|
456
|
+
const make = (name) => (toolInput) => this.lookup(name, toolInput === void 0 ? {} : toolInput);
|
|
457
|
+
const target = {};
|
|
458
|
+
const names = /* @__PURE__ */ new Set([
|
|
459
|
+
...this.recorded.map((record) => record.name),
|
|
460
|
+
...Object.keys(this.local)
|
|
461
|
+
]);
|
|
462
|
+
for (const name of names) {
|
|
463
|
+
if (name) {
|
|
464
|
+
target[name] = make(name);
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
return new Proxy(target, {
|
|
468
|
+
get(current, prop, receiver) {
|
|
469
|
+
if (typeof prop !== "string" || prop in current) {
|
|
470
|
+
return Reflect.get(current, prop, receiver);
|
|
471
|
+
}
|
|
472
|
+
return make(prop);
|
|
473
|
+
}
|
|
474
|
+
});
|
|
475
|
+
}
|
|
476
|
+
calledNames() {
|
|
477
|
+
return this.callLog.map((entry) => entry.tool);
|
|
478
|
+
}
|
|
479
|
+
/**
|
|
480
|
+
* 1:1 comparison of this replay against the recorded trace.
|
|
481
|
+
*
|
|
482
|
+
* The recording is the expectation: every recorded tool call should be
|
|
483
|
+
* replayed exactly once, in order, with nothing extra. Use for strict
|
|
484
|
+
* did-it-do-everything-the-original-did checks (`mode: "exact"`).
|
|
485
|
+
*
|
|
486
|
+
* `includeLocal`: count local-tool calls as extras (default false — local
|
|
487
|
+
* tools are declared live on purpose; their recorded calls are likewise
|
|
488
|
+
* excluded from "missing", since local bypasses recordings).
|
|
489
|
+
*/
|
|
490
|
+
compare(options = {}) {
|
|
491
|
+
const includeLocal = options.includeLocal ?? false;
|
|
492
|
+
const missing = this.recorded.map((record, index) => ({ record, index })).filter(
|
|
493
|
+
({ record, index }) => !this.consumed.has(index) && (includeLocal || !(record.name in this.local))
|
|
494
|
+
).map(({ record }) => `${record.name}(${normalizeInput(record.input)})`);
|
|
495
|
+
const extra = [];
|
|
496
|
+
for (const entry of this.callLog) {
|
|
497
|
+
if (["miss", "reuse", "exact-repeat"].includes(entry.match) || includeLocal && entry.match === "local") {
|
|
498
|
+
extra.push(
|
|
499
|
+
`${entry.tool}(${normalizeInput(entry.input)}) [${entry.match}]`
|
|
500
|
+
);
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
const outOfOrder = [];
|
|
504
|
+
let last = -1;
|
|
505
|
+
for (const index of this.consumptionOrder) {
|
|
506
|
+
if (index < last) {
|
|
507
|
+
const record = this.recorded[index];
|
|
508
|
+
outOfOrder.push(`${record.name}(${normalizeInput(record.input)})`);
|
|
509
|
+
} else {
|
|
510
|
+
last = index;
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
const matched = this.consumptionOrder.map(
|
|
514
|
+
(index) => this.recorded[index].name
|
|
515
|
+
);
|
|
516
|
+
return new TraceDiff({ matched, missing, extra, outOfOrder });
|
|
517
|
+
}
|
|
518
|
+
get drifted() {
|
|
519
|
+
return this.driftEvents.length > 0;
|
|
520
|
+
}
|
|
521
|
+
};
|
|
522
|
+
var TraceDiff = class {
|
|
523
|
+
matched;
|
|
524
|
+
missing;
|
|
525
|
+
extra;
|
|
526
|
+
outOfOrder;
|
|
527
|
+
constructor(fields = {}) {
|
|
528
|
+
this.matched = fields.matched ?? [];
|
|
529
|
+
this.missing = fields.missing ?? [];
|
|
530
|
+
this.extra = fields.extra ?? [];
|
|
531
|
+
this.outOfOrder = fields.outOfOrder ?? [];
|
|
532
|
+
}
|
|
533
|
+
get identical() {
|
|
534
|
+
return this.missing.length === 0 && this.extra.length === 0 && this.outOfOrder.length === 0;
|
|
535
|
+
}
|
|
536
|
+
explain() {
|
|
537
|
+
if (this.identical) {
|
|
538
|
+
return `1:1 replay \u2014 all ${this.matched.length} recorded tool calls reproduced in order`;
|
|
539
|
+
}
|
|
540
|
+
const lines = [
|
|
541
|
+
`trace diverges from recording (${this.matched.length} matched):`
|
|
542
|
+
];
|
|
543
|
+
lines.push(...this.missing.map((item) => ` not reproduced: ${item}`));
|
|
544
|
+
lines.push(...this.extra.map((item) => ` extra call: ${item}`));
|
|
545
|
+
lines.push(...this.outOfOrder.map((item) => ` out of order: ${item}`));
|
|
546
|
+
return lines.join("\n");
|
|
547
|
+
}
|
|
548
|
+
};
|
|
549
|
+
var ReplayTask = class _ReplayTask {
|
|
550
|
+
id;
|
|
551
|
+
name;
|
|
552
|
+
prompt;
|
|
553
|
+
expectedOutput;
|
|
554
|
+
metadata;
|
|
555
|
+
constructor(fields) {
|
|
556
|
+
this.id = fields.id;
|
|
557
|
+
this.name = fields.name ?? null;
|
|
558
|
+
this.prompt = fields.prompt;
|
|
559
|
+
this.expectedOutput = fields.expectedOutput;
|
|
560
|
+
this.metadata = fields.metadata ?? {};
|
|
561
|
+
}
|
|
562
|
+
get sourceSessionId() {
|
|
563
|
+
const value = this.metadata.sourceSessionId;
|
|
564
|
+
return value ? String(value) : null;
|
|
565
|
+
}
|
|
566
|
+
get sourceTraceId() {
|
|
567
|
+
const value = this.metadata.sourceTraceId;
|
|
568
|
+
return value ? String(value) : null;
|
|
569
|
+
}
|
|
570
|
+
static fromApi(raw) {
|
|
571
|
+
const metadata = raw.metadata;
|
|
572
|
+
return new _ReplayTask({
|
|
573
|
+
id: String(raw.id ?? ""),
|
|
574
|
+
name: typeof raw.name === "string" ? raw.name : null,
|
|
575
|
+
prompt: raw.prompt,
|
|
576
|
+
expectedOutput: raw.expectedOutput,
|
|
577
|
+
metadata: isPlainObject2(metadata) ? { ...metadata } : {}
|
|
578
|
+
});
|
|
579
|
+
}
|
|
580
|
+
};
|
|
581
|
+
var ReplayCheck = class {
|
|
582
|
+
status;
|
|
583
|
+
failures;
|
|
584
|
+
drift;
|
|
585
|
+
traceDiff;
|
|
586
|
+
constructor(status, fields = {}) {
|
|
587
|
+
this.status = status;
|
|
588
|
+
this.failures = fields.failures ?? [];
|
|
589
|
+
this.drift = fields.drift ?? [];
|
|
590
|
+
this.traceDiff = fields.traceDiff ?? null;
|
|
591
|
+
}
|
|
592
|
+
get passed() {
|
|
593
|
+
return this.status === "PASS";
|
|
594
|
+
}
|
|
595
|
+
get drifted() {
|
|
596
|
+
return this.status === "DRIFT";
|
|
597
|
+
}
|
|
598
|
+
explain() {
|
|
599
|
+
if (this.status === "PASS") {
|
|
600
|
+
return "PASS";
|
|
601
|
+
}
|
|
602
|
+
const lines = [this.status];
|
|
603
|
+
lines.push(...this.failures.map((failure) => ` FAIL: ${failure}`));
|
|
604
|
+
for (const event of this.drift) {
|
|
605
|
+
if (event.includes("reuse policy")) {
|
|
606
|
+
lines.push(
|
|
607
|
+
` DRIFT: ${event} \u2014 recording under-covers this run; re-record for exact coverage or keep the reuse policy.`
|
|
608
|
+
);
|
|
609
|
+
} else {
|
|
610
|
+
lines.push(
|
|
611
|
+
` DRIFT: ${event} \u2014 the test is stale, not the agent; re-record the session (or declare the tool local).`
|
|
612
|
+
);
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
return lines.join("\n");
|
|
616
|
+
}
|
|
617
|
+
};
|
|
618
|
+
var ReplayCase = class {
|
|
619
|
+
task;
|
|
620
|
+
loader;
|
|
621
|
+
_recording = null;
|
|
622
|
+
_stubs = null;
|
|
623
|
+
constructor(task, options) {
|
|
624
|
+
this.task = task;
|
|
625
|
+
this.loader = options.loader;
|
|
626
|
+
}
|
|
627
|
+
// -- identity ------------------------------------------------------------
|
|
628
|
+
get id() {
|
|
629
|
+
return this.task.id;
|
|
630
|
+
}
|
|
631
|
+
get name() {
|
|
632
|
+
return this.task.name ?? this.task.id;
|
|
633
|
+
}
|
|
634
|
+
get prompt() {
|
|
635
|
+
return this.task.prompt;
|
|
636
|
+
}
|
|
637
|
+
get expected() {
|
|
638
|
+
return this.task.expectedOutput;
|
|
639
|
+
}
|
|
640
|
+
// -- recorded source session ----------------------------------------------
|
|
641
|
+
/** The full recorded session this case was filed from. */
|
|
642
|
+
async recording() {
|
|
643
|
+
if (this._recording === null) {
|
|
644
|
+
const source = this.task.sourceSessionId;
|
|
645
|
+
if (!source) {
|
|
646
|
+
throw new DriftError(
|
|
647
|
+
`Task ${this.name} has no sourceSessionId provenance \u2014 file it from a session (add_session_to_task_set) or set metadata.sourceSessionId.`
|
|
648
|
+
);
|
|
649
|
+
}
|
|
650
|
+
this._recording = await this.loader(source);
|
|
651
|
+
}
|
|
652
|
+
return this._recording;
|
|
653
|
+
}
|
|
654
|
+
async stubs(options = {}) {
|
|
655
|
+
this._stubs = ToolStubRegistry.fromSession(await this.recording(), options);
|
|
656
|
+
return this._stubs;
|
|
657
|
+
}
|
|
658
|
+
/**
|
|
659
|
+
* The recorded conversation's user messages, one per turn — feed them to
|
|
660
|
+
* your agent in order to re-drive the full session (each turn was one
|
|
661
|
+
* trace in the recording).
|
|
662
|
+
*/
|
|
663
|
+
async conversation() {
|
|
664
|
+
const messages = (await this.recording()).userMessages();
|
|
665
|
+
const found = messages.filter(
|
|
666
|
+
(message) => Boolean(message)
|
|
667
|
+
);
|
|
668
|
+
return found.length > 0 ? found : [String(this.prompt)];
|
|
669
|
+
}
|
|
670
|
+
// -- grading ---------------------------------------------------------------
|
|
671
|
+
/**
|
|
672
|
+
* Contract invariants + drift triage.
|
|
673
|
+
*
|
|
674
|
+
* Invariants come from task metadata (the workbench-style contract):
|
|
675
|
+
* metadata.expectTools — every listed tool MUST have been called
|
|
676
|
+
* metadata.mustNotCall — none of these may have been called
|
|
677
|
+
* Semantic grading stays with the caller (assert on `output` /
|
|
678
|
+
* `case.expected`, or run a platform judge on the replay trace).
|
|
679
|
+
*
|
|
680
|
+
* `mode` (or task `metadata.replayMode`):
|
|
681
|
+
* "contract" (default) — grade only the invariants above
|
|
682
|
+
* "exact" — true 1:1 replay: the agent must reproduce EVERY
|
|
683
|
+
* recorded tool call, in order, with nothing extra
|
|
684
|
+
* (see TraceDiff); any divergence is a FAIL. The
|
|
685
|
+
* full diff lands in the failure reasons and
|
|
686
|
+
* `traceDiff`.
|
|
687
|
+
*/
|
|
688
|
+
check(output = void 0, options = {}) {
|
|
689
|
+
const registry = options.stubs ?? this._stubs;
|
|
690
|
+
const drift = registry ? [...registry.driftEvents] : [];
|
|
691
|
+
const called = options.calledTools ?? (registry ? registry.calledNames() : []);
|
|
692
|
+
const violations = [];
|
|
693
|
+
const omissions = [];
|
|
694
|
+
const expectTools = this.task.metadata.expectTools;
|
|
695
|
+
if (Array.isArray(expectTools)) {
|
|
696
|
+
for (const toolName of expectTools) {
|
|
697
|
+
if (!called.includes(toolName)) {
|
|
698
|
+
omissions.push(`expected tool not called: ${toolName}`);
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
const mustNot = this.task.metadata.mustNotCall;
|
|
703
|
+
if (Array.isArray(mustNot)) {
|
|
704
|
+
for (const toolName of mustNot) {
|
|
705
|
+
if (called.includes(toolName)) {
|
|
706
|
+
violations.push(`must_not_call violated: ${toolName}`);
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
if (typeof this.expected === "string" && this.expected.trim() && typeof output === "string" && this.task.metadata.outputExact === true && output.trim() !== this.expected.trim()) {
|
|
711
|
+
violations.push("output does not exactly match expectedOutput");
|
|
712
|
+
}
|
|
713
|
+
const replayMode = options.mode ?? this.task.metadata.replayMode ?? "contract";
|
|
714
|
+
let traceDiff = null;
|
|
715
|
+
if (registry) {
|
|
716
|
+
traceDiff = registry.compare();
|
|
717
|
+
}
|
|
718
|
+
if (replayMode === "exact" && traceDiff && !traceDiff.identical) {
|
|
719
|
+
violations.push(
|
|
720
|
+
...[
|
|
721
|
+
...traceDiff.missing.map((item) => `not reproduced: ${item}`),
|
|
722
|
+
...traceDiff.extra.map((item) => `extra call: ${item}`),
|
|
723
|
+
...traceDiff.outOfOrder.map((item) => `out of order: ${item}`)
|
|
724
|
+
].map((line) => `1:1 replay diverged \u2014 ${line}`)
|
|
725
|
+
);
|
|
726
|
+
}
|
|
727
|
+
if (violations.length > 0) {
|
|
728
|
+
return new ReplayCheck("FAIL", {
|
|
729
|
+
failures: [...violations, ...drift.length > 0 ? [] : omissions],
|
|
730
|
+
drift,
|
|
731
|
+
traceDiff
|
|
732
|
+
});
|
|
733
|
+
}
|
|
734
|
+
if (drift.length > 0) {
|
|
735
|
+
return new ReplayCheck("DRIFT", { drift, traceDiff });
|
|
736
|
+
}
|
|
737
|
+
if (omissions.length > 0) {
|
|
738
|
+
return new ReplayCheck("FAIL", { failures: omissions, traceDiff });
|
|
739
|
+
}
|
|
740
|
+
return new ReplayCheck("PASS", { traceDiff });
|
|
741
|
+
}
|
|
742
|
+
};
|
|
743
|
+
var ReplaySuite = class _ReplaySuite {
|
|
744
|
+
taskSetId;
|
|
745
|
+
taskSetName;
|
|
746
|
+
cases;
|
|
747
|
+
/** Credentials for recording replay runs back to the platform. */
|
|
748
|
+
credentials;
|
|
749
|
+
constructor(fields) {
|
|
750
|
+
this.taskSetId = fields.taskSetId;
|
|
751
|
+
this.taskSetName = fields.taskSetName;
|
|
752
|
+
this.cases = fields.cases;
|
|
753
|
+
this.credentials = fields.credentials ?? null;
|
|
754
|
+
}
|
|
755
|
+
[Symbol.iterator]() {
|
|
756
|
+
return this.cases[Symbol.iterator]();
|
|
757
|
+
}
|
|
758
|
+
get length() {
|
|
759
|
+
return this.cases.length;
|
|
760
|
+
}
|
|
761
|
+
/** Look up a case by id or name (throws when absent). */
|
|
762
|
+
get(key) {
|
|
763
|
+
for (const testCase of this.cases) {
|
|
764
|
+
if (testCase.id === key || testCase.name === key) {
|
|
765
|
+
return testCase;
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
throw new ReplayError(
|
|
769
|
+
`No case '${key}' in task set ${this.taskSetName} (cases: ${JSON.stringify(this.cases.map((c) => c.name))})`
|
|
770
|
+
);
|
|
771
|
+
}
|
|
772
|
+
static async fromTaskSet(nameOrId, options = {}) {
|
|
773
|
+
const host = (options.host ?? process.env[ENV_GATEWAY_HOST] ?? "").replace(
|
|
774
|
+
/\/+$/,
|
|
775
|
+
""
|
|
776
|
+
);
|
|
777
|
+
const publicKey = options.publicKey ?? process.env[ENV_GATEWAY_PUBLIC_KEY] ?? "";
|
|
778
|
+
const secretKey = options.secretKey ?? process.env[ENV_GATEWAY_SECRET_KEY] ?? "";
|
|
779
|
+
const timeoutSeconds = options.timeoutSeconds ?? DEFAULT_TIMEOUT_SECONDS;
|
|
780
|
+
if (!host || !publicKey || !secretKey) {
|
|
781
|
+
throw new SessionLoadError(
|
|
782
|
+
"Gateway is not configured \u2014 set GATEWAY_HOST, GATEWAY_PUBLIC_KEY and GATEWAY_SECRET_KEY."
|
|
783
|
+
);
|
|
784
|
+
}
|
|
785
|
+
const headers = { Authorization: basicAuthHeader(publicKey, secretKey) };
|
|
786
|
+
const fetchTasks = async (datasetId) => {
|
|
787
|
+
const tasks = [];
|
|
788
|
+
let page = 0;
|
|
789
|
+
for (; ; ) {
|
|
790
|
+
const response = await fetch(
|
|
791
|
+
`${host}/api/public/task-sets/${encodeURIComponent(datasetId)}/tasks?page=${page}&limit=200`,
|
|
792
|
+
{ headers, signal: AbortSignal.timeout(timeoutSeconds * 1e3) }
|
|
793
|
+
);
|
|
794
|
+
if (response.status === 404) {
|
|
795
|
+
return null;
|
|
796
|
+
}
|
|
797
|
+
const text = await response.text();
|
|
798
|
+
if (!response.ok) {
|
|
799
|
+
throw new ReplayError(
|
|
800
|
+
`Failed to list tasks for ${datasetId}: HTTP ${response.status} \u2014 ${text.slice(0, 300)}`
|
|
801
|
+
);
|
|
802
|
+
}
|
|
803
|
+
const payload = parseJsonObject(text);
|
|
804
|
+
const pageTasks = Array.isArray(payload.tasks) ? payload.tasks : [];
|
|
805
|
+
tasks.push(...pageTasks.filter(isPlainObject2));
|
|
806
|
+
if (tasks.length >= Number(payload.totalTasks ?? 0)) {
|
|
807
|
+
return tasks;
|
|
808
|
+
}
|
|
809
|
+
page += 1;
|
|
810
|
+
}
|
|
811
|
+
};
|
|
812
|
+
let taskSetId = nameOrId;
|
|
813
|
+
let taskSetName = nameOrId;
|
|
814
|
+
let rawTasks = await fetchTasks(nameOrId);
|
|
815
|
+
if (rawTasks === null) {
|
|
816
|
+
const response = await fetch(
|
|
817
|
+
`${host}/api/public/task-sets?name=${encodeURIComponent(nameOrId)}`,
|
|
818
|
+
{ headers, signal: AbortSignal.timeout(timeoutSeconds * 1e3) }
|
|
819
|
+
);
|
|
820
|
+
const text = await response.text();
|
|
821
|
+
if (!response.ok) {
|
|
822
|
+
throw new ReplayError(
|
|
823
|
+
`Failed to resolve task set '${nameOrId}': HTTP ${response.status} \u2014 ${text.slice(0, 300)}`
|
|
824
|
+
);
|
|
825
|
+
}
|
|
826
|
+
const payload = parseJsonObject(text);
|
|
827
|
+
const matches = Array.isArray(payload.taskSets) ? payload.taskSets.filter(isPlainObject2) : [];
|
|
828
|
+
if (matches.length === 0) {
|
|
829
|
+
throw new ReplayError(`Task set not found: ${nameOrId}`);
|
|
830
|
+
}
|
|
831
|
+
taskSetId = String(matches[0].datasetId);
|
|
832
|
+
taskSetName = String(matches[0].name);
|
|
833
|
+
rawTasks = await fetchTasks(taskSetId) ?? [];
|
|
834
|
+
}
|
|
835
|
+
const loader = (sessionId) => loadSession(sessionId, { host, publicKey, secretKey, timeoutSeconds });
|
|
836
|
+
const cases = rawTasks.map(
|
|
837
|
+
(raw) => new ReplayCase(ReplayTask.fromApi(raw), { loader })
|
|
838
|
+
);
|
|
839
|
+
return new _ReplaySuite({
|
|
840
|
+
taskSetId,
|
|
841
|
+
taskSetName,
|
|
842
|
+
cases,
|
|
843
|
+
credentials: { host, publicKey, secretKey, timeoutSeconds }
|
|
844
|
+
});
|
|
845
|
+
}
|
|
846
|
+
/** Run the whole suite against `agent` — see `runSuite()`. */
|
|
847
|
+
run(agent, options = {}) {
|
|
848
|
+
return runSuite(this, agent, options);
|
|
849
|
+
}
|
|
850
|
+
/** Pin every case's recorded session into the repo as JSON fixtures. */
|
|
851
|
+
async snapshot(directory) {
|
|
852
|
+
const written = [];
|
|
853
|
+
for (const testCase of this.cases) {
|
|
854
|
+
if (!testCase.task.sourceSessionId) {
|
|
855
|
+
continue;
|
|
856
|
+
}
|
|
857
|
+
const recording = await testCase.recording();
|
|
858
|
+
written.push(
|
|
859
|
+
recording.toFixture(join(directory, `${testCase.name}.recording.json`))
|
|
860
|
+
);
|
|
861
|
+
}
|
|
862
|
+
return written;
|
|
863
|
+
}
|
|
864
|
+
};
|
|
865
|
+
var ReplayReport = class {
|
|
866
|
+
results;
|
|
867
|
+
runName;
|
|
868
|
+
recordingErrors;
|
|
869
|
+
constructor(results, fields = {}) {
|
|
870
|
+
this.results = results;
|
|
871
|
+
this.runName = fields.runName ?? null;
|
|
872
|
+
this.recordingErrors = fields.recordingErrors ?? [];
|
|
873
|
+
}
|
|
874
|
+
get passed() {
|
|
875
|
+
return this.count("PASS");
|
|
876
|
+
}
|
|
877
|
+
get failed() {
|
|
878
|
+
return this.count("FAIL");
|
|
879
|
+
}
|
|
880
|
+
get drifted() {
|
|
881
|
+
return this.count("DRIFT");
|
|
882
|
+
}
|
|
883
|
+
/** True when nothing FAILED (drift is stale-test signal, not failure). */
|
|
884
|
+
get ok() {
|
|
885
|
+
return this.failed === 0;
|
|
886
|
+
}
|
|
887
|
+
explain() {
|
|
888
|
+
const lines = [
|
|
889
|
+
`${this.passed} PASS \xB7 ${this.failed} FAIL \xB7 ${this.drifted} DRIFT` + (this.runName ? ` \xB7 run '${this.runName}'` : "")
|
|
890
|
+
];
|
|
891
|
+
for (const [name, check] of Object.entries(this.results)) {
|
|
892
|
+
if (check.status !== "PASS") {
|
|
893
|
+
lines.push(`${name}: ${check.explain()}`);
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
for (const error of this.recordingErrors) {
|
|
897
|
+
lines.push(`recording: ${error}`);
|
|
898
|
+
}
|
|
899
|
+
return lines.join("\n");
|
|
900
|
+
}
|
|
901
|
+
count(status) {
|
|
902
|
+
return Object.values(this.results).filter(
|
|
903
|
+
(check) => check.status === status
|
|
904
|
+
).length;
|
|
905
|
+
}
|
|
906
|
+
};
|
|
907
|
+
var REPLAY_ENVIRONMENT = "gateway-replay";
|
|
908
|
+
async function recordRunItem(suiteToRecord, testCase, runName, traceId, triage, options = {}) {
|
|
909
|
+
const retries = options.retries ?? 10;
|
|
910
|
+
const retryDelaySeconds = options.retryDelaySeconds ?? 3;
|
|
911
|
+
const credentials = suiteToRecord.credentials;
|
|
912
|
+
if (!credentials) {
|
|
913
|
+
return "suite has no platform credentials";
|
|
914
|
+
}
|
|
915
|
+
const payload = {
|
|
916
|
+
runName,
|
|
917
|
+
runDescription: `gatewaysdk.replay run over '${suiteToRecord.taskSetName}'`,
|
|
918
|
+
datasetItemId: testCase.id,
|
|
919
|
+
traceId: traceId ?? randomHex(),
|
|
920
|
+
metadata: {
|
|
921
|
+
replay: true,
|
|
922
|
+
status: triage.status,
|
|
923
|
+
failures: triage.failures,
|
|
924
|
+
drift: triage.drift,
|
|
925
|
+
sourceSessionId: testCase.task.sourceSessionId
|
|
926
|
+
}
|
|
927
|
+
};
|
|
928
|
+
let lastError = "unknown";
|
|
929
|
+
for (let attempt = 0; attempt < retries; attempt++) {
|
|
930
|
+
try {
|
|
931
|
+
const response = await fetch(
|
|
932
|
+
`${credentials.host}/api/public/dataset-run-items`,
|
|
933
|
+
{
|
|
934
|
+
method: "POST",
|
|
935
|
+
headers: {
|
|
936
|
+
Authorization: basicAuthHeader(
|
|
937
|
+
credentials.publicKey,
|
|
938
|
+
credentials.secretKey
|
|
939
|
+
),
|
|
940
|
+
"Content-Type": "application/json"
|
|
941
|
+
},
|
|
942
|
+
body: JSON.stringify(payload),
|
|
943
|
+
signal: AbortSignal.timeout(DEFAULT_TIMEOUT_SECONDS * 1e3)
|
|
944
|
+
}
|
|
945
|
+
);
|
|
946
|
+
if (response.status === 200) {
|
|
947
|
+
return null;
|
|
948
|
+
}
|
|
949
|
+
const text = await response.text();
|
|
950
|
+
lastError = `HTTP ${response.status}: ${text.slice(0, 200)}`;
|
|
951
|
+
if (response.status !== 404) {
|
|
952
|
+
return lastError;
|
|
953
|
+
}
|
|
954
|
+
} catch (error) {
|
|
955
|
+
lastError = error instanceof Error ? error.message : String(error);
|
|
956
|
+
}
|
|
957
|
+
if (attempt < retries - 1) {
|
|
958
|
+
await sleep(retryDelaySeconds * 1e3);
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
return lastError;
|
|
962
|
+
}
|
|
963
|
+
async function runSuite(suiteToRun, agent, options = {}) {
|
|
964
|
+
const missPolicy = options.missPolicy ?? "error";
|
|
965
|
+
const record = options.record ?? Boolean(suiteToRun.credentials);
|
|
966
|
+
const runName = options.runName ?? `replay-${randomHex().slice(0, 8)}`;
|
|
967
|
+
const results = {};
|
|
968
|
+
const pendingRecords = [];
|
|
969
|
+
for (const testCase of suiteToRun) {
|
|
970
|
+
try {
|
|
971
|
+
const stubs = await testCase.stubs({ missPolicy });
|
|
972
|
+
const output = await agent(
|
|
973
|
+
testCase.prompt,
|
|
974
|
+
stubs.asRegistry(),
|
|
975
|
+
testCase
|
|
976
|
+
);
|
|
977
|
+
results[testCase.name] = testCase.check(output);
|
|
978
|
+
} catch (error) {
|
|
979
|
+
if (error instanceof StubMissError) {
|
|
980
|
+
let triage = testCase.check();
|
|
981
|
+
if (triage.status !== "FAIL") {
|
|
982
|
+
triage = new ReplayCheck("DRIFT", {
|
|
983
|
+
drift: triage.drift.length > 0 ? triage.drift : [error.message]
|
|
984
|
+
});
|
|
985
|
+
}
|
|
986
|
+
results[testCase.name] = triage;
|
|
987
|
+
} else if (error instanceof DriftError) {
|
|
988
|
+
results[testCase.name] = new ReplayCheck("DRIFT", {
|
|
989
|
+
drift: [error.message]
|
|
990
|
+
});
|
|
991
|
+
} else {
|
|
992
|
+
throw error;
|
|
993
|
+
}
|
|
994
|
+
}
|
|
995
|
+
if (record) {
|
|
996
|
+
pendingRecords.push([testCase, null, results[testCase.name]]);
|
|
997
|
+
}
|
|
998
|
+
}
|
|
999
|
+
const recordingErrors = [];
|
|
1000
|
+
for (const [testCase, traceId, triage] of pendingRecords) {
|
|
1001
|
+
const error = await recordRunItem(
|
|
1002
|
+
suiteToRun,
|
|
1003
|
+
testCase,
|
|
1004
|
+
runName,
|
|
1005
|
+
traceId,
|
|
1006
|
+
triage
|
|
1007
|
+
);
|
|
1008
|
+
if (error) {
|
|
1009
|
+
recordingErrors.push(`${testCase.name}: ${error}`);
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
1012
|
+
return new ReplayReport(results, {
|
|
1013
|
+
runName: record ? runName : null,
|
|
1014
|
+
recordingErrors
|
|
1015
|
+
});
|
|
1016
|
+
}
|
|
1017
|
+
function suite(nameOrId, options = {}) {
|
|
1018
|
+
return ReplaySuite.fromTaskSet(nameOrId, options);
|
|
1019
|
+
}
|
|
1020
|
+
function isPlainObject2(value) {
|
|
1021
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1022
|
+
}
|
|
1023
|
+
function parseJsonObject(text) {
|
|
1024
|
+
try {
|
|
1025
|
+
const parsed = JSON.parse(text);
|
|
1026
|
+
return isPlainObject2(parsed) ? parsed : {};
|
|
1027
|
+
} catch {
|
|
1028
|
+
return {};
|
|
1029
|
+
}
|
|
1030
|
+
}
|
|
1031
|
+
function randomHex() {
|
|
1032
|
+
return crypto.randomUUID().replace(/-/g, "");
|
|
1033
|
+
}
|
|
1034
|
+
function sleep(ms) {
|
|
1035
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
1036
|
+
}
|
|
1037
|
+
var replay = {
|
|
1038
|
+
suite,
|
|
1039
|
+
run: runSuite
|
|
1040
|
+
};
|
|
1041
|
+
export {
|
|
1042
|
+
DriftError,
|
|
1043
|
+
REPLAY_ENVIRONMENT,
|
|
1044
|
+
ReplayCase,
|
|
1045
|
+
ReplayCheck,
|
|
1046
|
+
ReplayError,
|
|
1047
|
+
ReplayReport,
|
|
1048
|
+
ReplaySuite,
|
|
1049
|
+
ReplayTask,
|
|
1050
|
+
StubMissError,
|
|
1051
|
+
ToolStubRegistry,
|
|
1052
|
+
TraceDiff,
|
|
1053
|
+
replay,
|
|
1054
|
+
runSuite,
|
|
1055
|
+
suite
|
|
1056
|
+
};
|
|
1057
|
+
//# sourceMappingURL=index.mjs.map
|