@wraith-ai/testing 0.0.0-stage → 0.1.1
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/LICENSE +21 -0
- package/README.md +21 -2
- package/dist/index.d.mts +251 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +742 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +29 -4
- package/src/collect.ts +41 -0
- package/src/determinism.ts +23 -0
- package/src/fake-tty.ts +109 -0
- package/src/images.ts +33 -0
- package/src/index.ts +46 -0
- package/src/mock-model.ts +222 -0
- package/src/screen.ts +205 -0
- package/src/session-backend-contract.ts +185 -0
- package/src/stub-tools.ts +49 -0
- package/src/test-model.ts +9 -0
- package/src/tmp-dir.ts +43 -0
- package/src/tool-context.ts +44 -0
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,742 @@
|
|
|
1
|
+
import { MockLanguageModelV4, simulateReadableStream } from "ai/test";
|
|
2
|
+
import { createMemorySessionBackend, createSessionStore, isAgentError, toModel, userMessage } from "@wraith-ai/core";
|
|
3
|
+
import { EventEmitter } from "node:events";
|
|
4
|
+
import { PassThrough } from "node:stream";
|
|
5
|
+
import { tool } from "ai";
|
|
6
|
+
import { z } from "zod";
|
|
7
|
+
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
8
|
+
import { tmpdir } from "node:os";
|
|
9
|
+
import { dirname, join, sep } from "node:path";
|
|
10
|
+
import assert from "node:assert/strict";
|
|
11
|
+
// src/mock-model.ts
|
|
12
|
+
function chunksFor(step, index) {
|
|
13
|
+
const chunks = [{
|
|
14
|
+
type: "stream-start",
|
|
15
|
+
warnings: []
|
|
16
|
+
}];
|
|
17
|
+
if (step.reasoning !== void 0) {
|
|
18
|
+
const id = `r${index}`;
|
|
19
|
+
chunks.push({
|
|
20
|
+
type: "reasoning-start",
|
|
21
|
+
id
|
|
22
|
+
}, {
|
|
23
|
+
type: "reasoning-delta",
|
|
24
|
+
id,
|
|
25
|
+
delta: step.reasoning
|
|
26
|
+
}, {
|
|
27
|
+
type: "reasoning-end",
|
|
28
|
+
id
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
if (step.text !== void 0) {
|
|
32
|
+
const id = `t${index}`;
|
|
33
|
+
const deltas = typeof step.text === "string" ? [step.text] : step.text;
|
|
34
|
+
chunks.push({
|
|
35
|
+
type: "text-start",
|
|
36
|
+
id
|
|
37
|
+
}, ...deltas.map((delta) => ({
|
|
38
|
+
type: "text-delta",
|
|
39
|
+
id,
|
|
40
|
+
delta
|
|
41
|
+
})), {
|
|
42
|
+
type: "text-end",
|
|
43
|
+
id
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
for (const call of step.toolCalls ?? []) {
|
|
47
|
+
chunks.push({
|
|
48
|
+
type: "tool-input-start",
|
|
49
|
+
id: call.toolCallId,
|
|
50
|
+
toolName: call.toolName
|
|
51
|
+
}, {
|
|
52
|
+
type: "tool-input-delta",
|
|
53
|
+
id: call.toolCallId,
|
|
54
|
+
delta: JSON.stringify(call.input)
|
|
55
|
+
}, {
|
|
56
|
+
type: "tool-input-end",
|
|
57
|
+
id: call.toolCallId
|
|
58
|
+
});
|
|
59
|
+
chunks.push({
|
|
60
|
+
type: "tool-call",
|
|
61
|
+
toolCallId: call.toolCallId,
|
|
62
|
+
toolName: call.toolName,
|
|
63
|
+
input: JSON.stringify(call.input)
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
const calledTools = (step.toolCalls ?? []).length > 0;
|
|
67
|
+
chunks.push({
|
|
68
|
+
type: "finish",
|
|
69
|
+
finishReason: {
|
|
70
|
+
unified: step.finishReason ?? (calledTools ? "tool-calls" : "stop"),
|
|
71
|
+
raw: void 0
|
|
72
|
+
},
|
|
73
|
+
usage: {
|
|
74
|
+
inputTokens: {
|
|
75
|
+
total: step.inputTokens ?? 0,
|
|
76
|
+
...step.cacheReadTokens === void 0 ? {} : { cacheRead: step.cacheReadTokens },
|
|
77
|
+
...step.cacheWriteTokens === void 0 ? {} : { cacheWrite: step.cacheWriteTokens }
|
|
78
|
+
},
|
|
79
|
+
outputTokens: { total: step.outputTokens ?? 0 }
|
|
80
|
+
},
|
|
81
|
+
...step.providerMetadata === void 0 ? {} : { providerMetadata: step.providerMetadata }
|
|
82
|
+
});
|
|
83
|
+
return chunks;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* A model that answers a single non-streaming call.
|
|
87
|
+
*
|
|
88
|
+
* Compaction asks for one summary with `generateText`, so it needs
|
|
89
|
+
* `doGenerate` rather than the streaming script above.
|
|
90
|
+
*/
|
|
91
|
+
function scriptedSummary(text, options = {}) {
|
|
92
|
+
const calls = [];
|
|
93
|
+
const requests = [];
|
|
94
|
+
return {
|
|
95
|
+
model: new MockLanguageModelV4({ doGenerate: async (callOptions) => {
|
|
96
|
+
calls.push(callOptions.prompt);
|
|
97
|
+
requests.push({
|
|
98
|
+
prompt: callOptions.prompt,
|
|
99
|
+
tools: callOptions.tools,
|
|
100
|
+
options: callOptions
|
|
101
|
+
});
|
|
102
|
+
return {
|
|
103
|
+
content: [{
|
|
104
|
+
type: "text",
|
|
105
|
+
text
|
|
106
|
+
}],
|
|
107
|
+
finishReason: {
|
|
108
|
+
unified: "stop",
|
|
109
|
+
raw: void 0
|
|
110
|
+
},
|
|
111
|
+
usage: {
|
|
112
|
+
inputTokens: { total: options.inputTokens ?? 0 },
|
|
113
|
+
outputTokens: { total: options.outputTokens ?? 0 }
|
|
114
|
+
},
|
|
115
|
+
warnings: []
|
|
116
|
+
};
|
|
117
|
+
} }),
|
|
118
|
+
calls,
|
|
119
|
+
requests
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
/** A model that answers a sequence of non-streaming calls, one answer per call. */
|
|
123
|
+
function scriptedAnswers(answers) {
|
|
124
|
+
const calls = [];
|
|
125
|
+
const requests = [];
|
|
126
|
+
let index = 0;
|
|
127
|
+
return {
|
|
128
|
+
model: new MockLanguageModelV4({ doGenerate: async (callOptions) => {
|
|
129
|
+
calls.push(callOptions.prompt);
|
|
130
|
+
requests.push({
|
|
131
|
+
prompt: callOptions.prompt,
|
|
132
|
+
tools: callOptions.tools,
|
|
133
|
+
options: callOptions
|
|
134
|
+
});
|
|
135
|
+
const answer = answers[Math.min(index, answers.length - 1)];
|
|
136
|
+
index += 1;
|
|
137
|
+
if (answer === void 0) throw new Error("scriptedAnswers needs at least one answer");
|
|
138
|
+
if (answer.error !== void 0) throw answer.error;
|
|
139
|
+
return {
|
|
140
|
+
content: [{
|
|
141
|
+
type: "text",
|
|
142
|
+
text: answer.text ?? ""
|
|
143
|
+
}],
|
|
144
|
+
finishReason: {
|
|
145
|
+
unified: "stop",
|
|
146
|
+
raw: void 0
|
|
147
|
+
},
|
|
148
|
+
usage: {
|
|
149
|
+
inputTokens: { total: answer.inputTokens ?? 0 },
|
|
150
|
+
outputTokens: { total: answer.outputTokens ?? 0 }
|
|
151
|
+
},
|
|
152
|
+
warnings: []
|
|
153
|
+
};
|
|
154
|
+
} }),
|
|
155
|
+
calls,
|
|
156
|
+
requests
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
function scriptedModel(steps) {
|
|
160
|
+
const calls = [];
|
|
161
|
+
const requests = [];
|
|
162
|
+
let index = 0;
|
|
163
|
+
return {
|
|
164
|
+
model: new MockLanguageModelV4({ doStream: async (options) => {
|
|
165
|
+
calls.push(options.prompt);
|
|
166
|
+
requests.push({
|
|
167
|
+
prompt: options.prompt,
|
|
168
|
+
tools: options.tools,
|
|
169
|
+
options
|
|
170
|
+
});
|
|
171
|
+
const step = steps[Math.min(index, steps.length - 1)];
|
|
172
|
+
index += 1;
|
|
173
|
+
if (step === void 0) throw new Error("scriptedModel needs at least one step");
|
|
174
|
+
return { stream: simulateReadableStream({ chunks: chunksFor(step, index) }) };
|
|
175
|
+
} }),
|
|
176
|
+
calls,
|
|
177
|
+
requests
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
// src/test-model.ts
|
|
181
|
+
/**
|
|
182
|
+
* A scripted model as the `Model` a registry would hand out. The ids are fixed
|
|
183
|
+
* because a session records them, and tests assert on the journal.
|
|
184
|
+
*/
|
|
185
|
+
function testModel(languageModel, fields = {}) {
|
|
186
|
+
return {
|
|
187
|
+
...toModel(languageModel),
|
|
188
|
+
providerName: "stub",
|
|
189
|
+
modelId: "vendor/model",
|
|
190
|
+
...fields
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
// src/collect.ts
|
|
194
|
+
async function collect(stream) {
|
|
195
|
+
const events = [];
|
|
196
|
+
const records = [];
|
|
197
|
+
let next = await stream.next();
|
|
198
|
+
while (!next.done) {
|
|
199
|
+
if (next.value.type === "record") records.push(next.value.record);
|
|
200
|
+
else events.push(next.value);
|
|
201
|
+
next = await stream.next();
|
|
202
|
+
}
|
|
203
|
+
return {
|
|
204
|
+
events,
|
|
205
|
+
types: events.map((event) => event.type),
|
|
206
|
+
records,
|
|
207
|
+
result: next.value
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
function eventsOfType(events, type) {
|
|
211
|
+
return events.filter((event) => event.type === type);
|
|
212
|
+
}
|
|
213
|
+
// src/fake-tty.ts
|
|
214
|
+
var FakeOutput = class extends EventEmitter {
|
|
215
|
+
columns;
|
|
216
|
+
rows;
|
|
217
|
+
written = [];
|
|
218
|
+
isTTY = true;
|
|
219
|
+
constructor(columns, rows) {
|
|
220
|
+
super();
|
|
221
|
+
this.columns = columns;
|
|
222
|
+
this.rows = rows;
|
|
223
|
+
}
|
|
224
|
+
write(data) {
|
|
225
|
+
this.written.push(data);
|
|
226
|
+
return true;
|
|
227
|
+
}
|
|
228
|
+
};
|
|
229
|
+
/**
|
|
230
|
+
* A real stream wearing a terminal's clothes. Ink reads keys through
|
|
231
|
+
* `readable`, not `data`, so an emitter that only fires `data` answers no
|
|
232
|
+
* keystroke. Only `isTTY`, which Ink checks before offering raw mode, and
|
|
233
|
+
* `setRawMode` are added.
|
|
234
|
+
*/
|
|
235
|
+
var FakeInput = class extends PassThrough {
|
|
236
|
+
isTTY = true;
|
|
237
|
+
isRaw = false;
|
|
238
|
+
setRawMode(raw) {
|
|
239
|
+
this.isRaw = raw;
|
|
240
|
+
return this;
|
|
241
|
+
}
|
|
242
|
+
ref() {
|
|
243
|
+
return this;
|
|
244
|
+
}
|
|
245
|
+
unref() {
|
|
246
|
+
return this;
|
|
247
|
+
}
|
|
248
|
+
};
|
|
249
|
+
function fakeTerminal(options = {}) {
|
|
250
|
+
const output = new FakeOutput(options.columns ?? 80, options.rows ?? 24);
|
|
251
|
+
const input = new FakeInput();
|
|
252
|
+
return {
|
|
253
|
+
stdin: input,
|
|
254
|
+
stdout: output,
|
|
255
|
+
frames: () => [...output.written],
|
|
256
|
+
lastFrame: () => output.written[output.written.length - 1] ?? "",
|
|
257
|
+
output: () => output.written.join(""),
|
|
258
|
+
type: (text) => void input.write(text),
|
|
259
|
+
resize: (columns, rows) => {
|
|
260
|
+
output.columns = columns;
|
|
261
|
+
output.rows = rows;
|
|
262
|
+
output.emit("resize");
|
|
263
|
+
}
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
const ESC$1 = String.fromCharCode(27);
|
|
267
|
+
const BEL = String.fromCharCode(7);
|
|
268
|
+
const ANSI = new RegExp(`${ESC$1}\\[[0-9;?]*[ -/]*[@-~]|${ESC$1}\\][^${BEL}${ESC$1}]*(?:${BEL}|${ESC$1}\\\\)?|${ESC$1}[@-Z\\\\-_]`, "g");
|
|
269
|
+
/**
|
|
270
|
+
* Strips ANSI so an assertion reads like the text on screen.
|
|
271
|
+
*
|
|
272
|
+
* A test matching on escape codes fails when a colour changes, not when
|
|
273
|
+
* anything broke.
|
|
274
|
+
*/
|
|
275
|
+
function plainText(frame) {
|
|
276
|
+
return frame.replace(ANSI, "");
|
|
277
|
+
}
|
|
278
|
+
// src/screen.ts
|
|
279
|
+
/**
|
|
280
|
+
* What the terminal would be showing, from the bytes a front end wrote.
|
|
281
|
+
*
|
|
282
|
+
* Replays the escapes onto a grid the way a terminal does, so an assertion
|
|
283
|
+
* checks what is on screen now. Covers the sequences Ink emits and nothing
|
|
284
|
+
* else; unrecognised sequences are skipped rather than drawn as text.
|
|
285
|
+
*/
|
|
286
|
+
const ESC = String.fromCharCode(27);
|
|
287
|
+
function blankRow(columns) {
|
|
288
|
+
return Array.from({ length: columns }, () => " ");
|
|
289
|
+
}
|
|
290
|
+
function scroll(grid) {
|
|
291
|
+
grid.cells.shift();
|
|
292
|
+
grid.cells.push(blankRow(grid.columns));
|
|
293
|
+
grid.row = grid.rows - 1;
|
|
294
|
+
}
|
|
295
|
+
function put(grid, character) {
|
|
296
|
+
if (grid.column >= grid.columns) {
|
|
297
|
+
grid.column = 0;
|
|
298
|
+
grid.row += 1;
|
|
299
|
+
if (grid.row >= grid.rows) scroll(grid);
|
|
300
|
+
}
|
|
301
|
+
const row = grid.cells[grid.row];
|
|
302
|
+
if (row !== void 0) row[grid.column] = character;
|
|
303
|
+
grid.column += 1;
|
|
304
|
+
}
|
|
305
|
+
function eraseRow(grid, from, to) {
|
|
306
|
+
const row = grid.cells[grid.row];
|
|
307
|
+
if (row === void 0) return;
|
|
308
|
+
for (let column = from; column <= to && column < grid.columns; column += 1) row[column] = " ";
|
|
309
|
+
}
|
|
310
|
+
/** A CSI sequence's numeric parameters, with a default for an omitted one. */
|
|
311
|
+
function parameters(raw, fallback) {
|
|
312
|
+
if (raw === "") return [fallback];
|
|
313
|
+
return raw.split(";").map((value) => value === "" ? fallback : Number(value));
|
|
314
|
+
}
|
|
315
|
+
function screenOf(written, options = {}) {
|
|
316
|
+
const columns = options.columns ?? 80;
|
|
317
|
+
const rows = options.rows ?? 24;
|
|
318
|
+
const grid = {
|
|
319
|
+
cells: Array.from({ length: rows }, () => blankRow(columns)),
|
|
320
|
+
columns,
|
|
321
|
+
rows,
|
|
322
|
+
row: 0,
|
|
323
|
+
column: 0
|
|
324
|
+
};
|
|
325
|
+
let index = 0;
|
|
326
|
+
while (index < written.length) {
|
|
327
|
+
const character = written[index] ?? "";
|
|
328
|
+
if (character === ESC) {
|
|
329
|
+
const next = written[index + 1];
|
|
330
|
+
if (next === "]") {
|
|
331
|
+
const end = written.indexOf(String.fromCharCode(7), index);
|
|
332
|
+
const st = written.indexOf(`${ESC}\\`, index);
|
|
333
|
+
const stop = end === -1 ? st : st === -1 ? end : Math.min(end, st);
|
|
334
|
+
index = stop === -1 ? written.length : stop + (stop === st ? 2 : 1);
|
|
335
|
+
continue;
|
|
336
|
+
}
|
|
337
|
+
if (next !== "[") {
|
|
338
|
+
index += 2;
|
|
339
|
+
continue;
|
|
340
|
+
}
|
|
341
|
+
const match = /^\[([?0-9;]*)([@-~])/.exec(written.slice(index));
|
|
342
|
+
if (match === null) {
|
|
343
|
+
index += 2;
|
|
344
|
+
continue;
|
|
345
|
+
}
|
|
346
|
+
const raw = match[1] ?? "";
|
|
347
|
+
const final = match[2] ?? "";
|
|
348
|
+
index += match[0].length;
|
|
349
|
+
if (raw.startsWith("?")) {
|
|
350
|
+
if ((raw === "?1049" || raw === "?47") && (final === "h" || final === "l")) {
|
|
351
|
+
grid.cells = Array.from({ length: rows }, () => blankRow(columns));
|
|
352
|
+
grid.row = 0;
|
|
353
|
+
grid.column = 0;
|
|
354
|
+
}
|
|
355
|
+
continue;
|
|
356
|
+
}
|
|
357
|
+
const values = parameters(raw, final === "J" || final === "K" ? 0 : 1);
|
|
358
|
+
const first = values[0] ?? 1;
|
|
359
|
+
switch (final) {
|
|
360
|
+
case "A":
|
|
361
|
+
grid.row = Math.max(0, grid.row - first);
|
|
362
|
+
break;
|
|
363
|
+
case "B":
|
|
364
|
+
grid.row = Math.min(rows - 1, grid.row + first);
|
|
365
|
+
break;
|
|
366
|
+
case "C":
|
|
367
|
+
grid.column = Math.min(columns - 1, grid.column + first);
|
|
368
|
+
break;
|
|
369
|
+
case "D":
|
|
370
|
+
grid.column = Math.max(0, grid.column - first);
|
|
371
|
+
break;
|
|
372
|
+
case "E":
|
|
373
|
+
grid.row = Math.min(rows - 1, grid.row + first);
|
|
374
|
+
grid.column = 0;
|
|
375
|
+
break;
|
|
376
|
+
case "F":
|
|
377
|
+
grid.row = Math.max(0, grid.row - first);
|
|
378
|
+
grid.column = 0;
|
|
379
|
+
break;
|
|
380
|
+
case "G":
|
|
381
|
+
grid.column = Math.max(0, Math.min(columns - 1, first - 1));
|
|
382
|
+
break;
|
|
383
|
+
case "H":
|
|
384
|
+
case "f":
|
|
385
|
+
grid.row = Math.max(0, Math.min(rows - 1, first - 1));
|
|
386
|
+
grid.column = Math.max(0, Math.min(columns - 1, (values[1] ?? 1) - 1));
|
|
387
|
+
break;
|
|
388
|
+
case "J": {
|
|
389
|
+
const mode = values[0] ?? 0;
|
|
390
|
+
if (mode === 2 || mode === 3) {
|
|
391
|
+
grid.cells = Array.from({ length: rows }, () => blankRow(columns));
|
|
392
|
+
grid.row = 0;
|
|
393
|
+
grid.column = 0;
|
|
394
|
+
break;
|
|
395
|
+
}
|
|
396
|
+
if (mode === 0) {
|
|
397
|
+
eraseRow(grid, grid.column, columns - 1);
|
|
398
|
+
for (let row = grid.row + 1; row < rows; row += 1) grid.cells[row] = blankRow(columns);
|
|
399
|
+
break;
|
|
400
|
+
}
|
|
401
|
+
eraseRow(grid, 0, grid.column);
|
|
402
|
+
for (let row = 0; row < grid.row; row += 1) grid.cells[row] = blankRow(columns);
|
|
403
|
+
break;
|
|
404
|
+
}
|
|
405
|
+
case "K": {
|
|
406
|
+
const mode = values[0] ?? 0;
|
|
407
|
+
if (mode === 0) eraseRow(grid, grid.column, columns - 1);
|
|
408
|
+
else if (mode === 1) eraseRow(grid, 0, grid.column);
|
|
409
|
+
else eraseRow(grid, 0, columns - 1);
|
|
410
|
+
break;
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
continue;
|
|
414
|
+
}
|
|
415
|
+
if (character === "\n") {
|
|
416
|
+
grid.row += 1;
|
|
417
|
+
grid.column = 0;
|
|
418
|
+
if (grid.row >= rows) scroll(grid);
|
|
419
|
+
index += 1;
|
|
420
|
+
continue;
|
|
421
|
+
}
|
|
422
|
+
if (character === "\r") {
|
|
423
|
+
grid.column = 0;
|
|
424
|
+
index += 1;
|
|
425
|
+
continue;
|
|
426
|
+
}
|
|
427
|
+
if (character.charCodeAt(0) >= 32) put(grid, character);
|
|
428
|
+
index += 1;
|
|
429
|
+
}
|
|
430
|
+
const lines = grid.cells.map((row) => row.join("").replace(/\s+$/, ""));
|
|
431
|
+
return {
|
|
432
|
+
rows: lines,
|
|
433
|
+
text: lines.join("\n")
|
|
434
|
+
};
|
|
435
|
+
}
|
|
436
|
+
// src/determinism.ts
|
|
437
|
+
/**
|
|
438
|
+
* Events carry a timestamp and a run id. The agent takes both as injected
|
|
439
|
+
* functions; these are the ones tests inject, so event streams can be pinned.
|
|
440
|
+
*/
|
|
441
|
+
/** A clock that advances by a fixed step on every read. */
|
|
442
|
+
function fixedClock(start = 1e3, stepMs = 1) {
|
|
443
|
+
let current = start - stepMs;
|
|
444
|
+
return () => {
|
|
445
|
+
current += stepMs;
|
|
446
|
+
return current;
|
|
447
|
+
};
|
|
448
|
+
}
|
|
449
|
+
/** Ids that are stable across runs: run-1, run-2, … */
|
|
450
|
+
function sequentialIds() {
|
|
451
|
+
const counters = /* @__PURE__ */ new Map();
|
|
452
|
+
return (prefix) => {
|
|
453
|
+
const next = (counters.get(prefix) ?? 0) + 1;
|
|
454
|
+
counters.set(prefix, next);
|
|
455
|
+
return `${prefix}-${next}`;
|
|
456
|
+
};
|
|
457
|
+
}
|
|
458
|
+
// src/stub-tools.ts
|
|
459
|
+
function stubToolRunner(options = {}) {
|
|
460
|
+
const names = options.names ?? ["read_file"];
|
|
461
|
+
const seen = [];
|
|
462
|
+
const modelTools = {};
|
|
463
|
+
for (const name of names) modelTools[name] = tool({
|
|
464
|
+
description: `Test tool ${name}`,
|
|
465
|
+
inputSchema: z.record(z.string(), z.unknown())
|
|
466
|
+
});
|
|
467
|
+
return {
|
|
468
|
+
seen,
|
|
469
|
+
modelTools,
|
|
470
|
+
execute: async (call) => {
|
|
471
|
+
seen.push(call);
|
|
472
|
+
return options.error === void 0 ? {
|
|
473
|
+
toolCallId: call.toolCallId,
|
|
474
|
+
toolName: call.toolName,
|
|
475
|
+
output: options.output ?? "ok"
|
|
476
|
+
} : {
|
|
477
|
+
toolCallId: call.toolCallId,
|
|
478
|
+
toolName: call.toolName,
|
|
479
|
+
error: options.error
|
|
480
|
+
};
|
|
481
|
+
}
|
|
482
|
+
};
|
|
483
|
+
}
|
|
484
|
+
// src/tmp-dir.ts
|
|
485
|
+
function makeTempDir(prefix = "wraith-test-") {
|
|
486
|
+
const path = mkdtempSync(join(tmpdir(), prefix));
|
|
487
|
+
const file = (relative) => join(path, ...relative.split("/"));
|
|
488
|
+
return {
|
|
489
|
+
path,
|
|
490
|
+
file,
|
|
491
|
+
write(files) {
|
|
492
|
+
for (const [relative, contents] of Object.entries(files)) {
|
|
493
|
+
const target = file(relative);
|
|
494
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
495
|
+
writeFileSync(target, contents, "utf8");
|
|
496
|
+
}
|
|
497
|
+
},
|
|
498
|
+
cleanup() {
|
|
499
|
+
rmSync(path, {
|
|
500
|
+
recursive: true,
|
|
501
|
+
force: true
|
|
502
|
+
});
|
|
503
|
+
}
|
|
504
|
+
};
|
|
505
|
+
}
|
|
506
|
+
/** Posix spelling of a path inside the temp dir, for asserting on results. */
|
|
507
|
+
function posixPath(path) {
|
|
508
|
+
return path.split(sep).join("/");
|
|
509
|
+
}
|
|
510
|
+
// src/tool-context.ts
|
|
511
|
+
function toolContext(options) {
|
|
512
|
+
return {
|
|
513
|
+
cwd: options.cwd,
|
|
514
|
+
signal: options.signal ?? new AbortController().signal,
|
|
515
|
+
logger: {
|
|
516
|
+
error: () => {},
|
|
517
|
+
warn: () => {},
|
|
518
|
+
info: () => {},
|
|
519
|
+
debug: () => {}
|
|
520
|
+
},
|
|
521
|
+
sessionId: options.sessionId ?? "session-test",
|
|
522
|
+
runId: options.runId ?? "run-test",
|
|
523
|
+
showChange: options.showChange ?? (() => {}),
|
|
524
|
+
attach: options.attach ?? (() => {}),
|
|
525
|
+
...options.roots === void 0 ? {} : { roots: options.roots },
|
|
526
|
+
...options.resultsDir === void 0 ? {} : { resultsDir: options.resultsDir },
|
|
527
|
+
...options.task === void 0 ? {} : { task: options.task }
|
|
528
|
+
};
|
|
529
|
+
}
|
|
530
|
+
// src/images.ts
|
|
531
|
+
/**
|
|
532
|
+
* Image files small enough to write inline. Only the header is real: the core
|
|
533
|
+
* reads the type and size from it and never decodes the pixels.
|
|
534
|
+
*/
|
|
535
|
+
/** A PNG of the given size: the signature and an IHDR chunk. */
|
|
536
|
+
function pngBytes(width = 1, height = 1) {
|
|
537
|
+
const bytes = /* @__PURE__ */ new Uint8Array(33);
|
|
538
|
+
const view = new DataView(bytes.buffer);
|
|
539
|
+
bytes.set([
|
|
540
|
+
137,
|
|
541
|
+
80,
|
|
542
|
+
78,
|
|
543
|
+
71,
|
|
544
|
+
13,
|
|
545
|
+
10,
|
|
546
|
+
26,
|
|
547
|
+
10
|
|
548
|
+
], 0);
|
|
549
|
+
view.setUint32(8, 13);
|
|
550
|
+
bytes.set([
|
|
551
|
+
73,
|
|
552
|
+
72,
|
|
553
|
+
68,
|
|
554
|
+
82
|
|
555
|
+
], 12);
|
|
556
|
+
view.setUint32(16, width);
|
|
557
|
+
view.setUint32(20, height);
|
|
558
|
+
bytes.set([
|
|
559
|
+
8,
|
|
560
|
+
6,
|
|
561
|
+
0,
|
|
562
|
+
0,
|
|
563
|
+
0
|
|
564
|
+
], 24);
|
|
565
|
+
return bytes;
|
|
566
|
+
}
|
|
567
|
+
/** A JPEG of the given size: start of image, one metadata segment, a start of frame. */
|
|
568
|
+
function jpegBytes(width = 1, height = 1) {
|
|
569
|
+
const bytes = new Uint8Array([
|
|
570
|
+
255,
|
|
571
|
+
216,
|
|
572
|
+
255,
|
|
573
|
+
224,
|
|
574
|
+
0,
|
|
575
|
+
6,
|
|
576
|
+
74,
|
|
577
|
+
70,
|
|
578
|
+
73,
|
|
579
|
+
70,
|
|
580
|
+
255,
|
|
581
|
+
192,
|
|
582
|
+
0,
|
|
583
|
+
17,
|
|
584
|
+
8,
|
|
585
|
+
0,
|
|
586
|
+
0,
|
|
587
|
+
0,
|
|
588
|
+
0,
|
|
589
|
+
3
|
|
590
|
+
]);
|
|
591
|
+
const view = new DataView(bytes.buffer);
|
|
592
|
+
view.setUint16(15, height);
|
|
593
|
+
view.setUint16(17, width);
|
|
594
|
+
return bytes;
|
|
595
|
+
}
|
|
596
|
+
/** The same image as an attachment, base64 as the core keeps it. */
|
|
597
|
+
function pngAttachment(width = 1, height = 1) {
|
|
598
|
+
return {
|
|
599
|
+
data: Buffer.from(pngBytes(width, height)).toString("base64"),
|
|
600
|
+
mediaType: "image/png"
|
|
601
|
+
};
|
|
602
|
+
}
|
|
603
|
+
// src/session-backend-contract.ts
|
|
604
|
+
/** A real log for `id`: a header, then one message per text, each append closed by a checkpoint. */
|
|
605
|
+
async function logOf(id, texts) {
|
|
606
|
+
let clock = 1e3;
|
|
607
|
+
const scratch = createSessionStore(createMemorySessionBackend(), {
|
|
608
|
+
newId: () => id,
|
|
609
|
+
now: () => clock += 10
|
|
610
|
+
});
|
|
611
|
+
await scratch.create();
|
|
612
|
+
for (const text of texts) await scratch.append(id, [{
|
|
613
|
+
type: "message",
|
|
614
|
+
message: userMessage(text)
|
|
615
|
+
}]);
|
|
616
|
+
return await scratch.records(id) ?? [];
|
|
617
|
+
}
|
|
618
|
+
async function codeOf(attempt) {
|
|
619
|
+
return attempt.then(() => null, (error) => isAgentError(error) ? error.code : String(error));
|
|
620
|
+
}
|
|
621
|
+
/**
|
|
622
|
+
* What every `SessionBackend` owes `createSessionStore`, as checks any test
|
|
623
|
+
* runner can run: `for (const check of sessionBackendContract(make))
|
|
624
|
+
* test(check.name, check.run)`. A backend that passes can replace the file
|
|
625
|
+
* and memory ones under a store.
|
|
626
|
+
*/
|
|
627
|
+
function sessionBackendContract(make) {
|
|
628
|
+
const check = (name, body) => ({
|
|
629
|
+
name,
|
|
630
|
+
async run() {
|
|
631
|
+
const harness = await make();
|
|
632
|
+
try {
|
|
633
|
+
await body(harness);
|
|
634
|
+
} finally {
|
|
635
|
+
await harness.cleanup?.();
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
});
|
|
639
|
+
return [
|
|
640
|
+
check("keeps a new session's records and hands them back unchanged", async ({ backend }) => {
|
|
641
|
+
const log = await logOf("one", ["hello"]);
|
|
642
|
+
await backend.create("one", log);
|
|
643
|
+
assert.deepEqual(await backend.read("one"), log);
|
|
644
|
+
assert.deepEqual(await backend.ends("one"), {
|
|
645
|
+
first: log[0],
|
|
646
|
+
last: log[log.length - 1]
|
|
647
|
+
});
|
|
648
|
+
}),
|
|
649
|
+
check("an unknown id reads as nothing", async ({ backend }) => {
|
|
650
|
+
assert.equal(await backend.read("nope"), null);
|
|
651
|
+
assert.equal(await backend.ends("nope"), null);
|
|
652
|
+
assert.equal(await backend.delete("nope"), false);
|
|
653
|
+
}),
|
|
654
|
+
check("refuses to create over a taken id, and leaves what was there", async ({ backend }) => {
|
|
655
|
+
const log = await logOf("one", ["hello"]);
|
|
656
|
+
await backend.create("one", log);
|
|
657
|
+
const other = await logOf("one", ["someone else"]);
|
|
658
|
+
assert.equal(await codeOf(backend.create("one", other)), "session/exists");
|
|
659
|
+
assert.deepEqual(await backend.read("one"), log);
|
|
660
|
+
}),
|
|
661
|
+
check("refuses to append to an unknown id", async ({ backend }) => {
|
|
662
|
+
const log = await logOf("nope", ["hello"]);
|
|
663
|
+
assert.equal(await codeOf(backend.append("nope", log.slice(2))), "session/not-found");
|
|
664
|
+
assert.equal(await backend.read("nope"), null);
|
|
665
|
+
}),
|
|
666
|
+
check("appends after what it already keeps, in the order given", async ({ backend }) => {
|
|
667
|
+
const log = await logOf("one", ["first", "second"]);
|
|
668
|
+
await backend.create("one", log.slice(0, 2));
|
|
669
|
+
await backend.append("one", log.slice(2, 4));
|
|
670
|
+
await backend.append("one", log.slice(4));
|
|
671
|
+
assert.deepEqual(await backend.read("one"), log);
|
|
672
|
+
assert.deepEqual((await backend.ends("one"))?.last, log[log.length - 1]);
|
|
673
|
+
}),
|
|
674
|
+
check("lists the ends of every session", async ({ backend }) => {
|
|
675
|
+
const older = await logOf("older", ["hello"]);
|
|
676
|
+
const newer = await logOf("newer", ["hi"]);
|
|
677
|
+
await backend.create("older", older);
|
|
678
|
+
await backend.create("newer", newer.slice(0, 2));
|
|
679
|
+
await backend.append("newer", newer.slice(2));
|
|
680
|
+
const idOf = ({ first }) => first.type === "header" ? first.id : "";
|
|
681
|
+
const listed = await backend.list();
|
|
682
|
+
assert.deepEqual(listed.map(idOf).sort(), ["newer", "older"]);
|
|
683
|
+
assert.deepEqual(listed.find((ends) => idOf(ends) === "older"), {
|
|
684
|
+
first: older[0],
|
|
685
|
+
last: older[older.length - 1]
|
|
686
|
+
});
|
|
687
|
+
const limited = await backend.list(1);
|
|
688
|
+
assert.deepEqual(limited.find((ends) => idOf(ends) === "newer")?.last, newer[newer.length - 1]);
|
|
689
|
+
}),
|
|
690
|
+
check("a deleted session is gone", async ({ backend }) => {
|
|
691
|
+
await backend.create("one", await logOf("one", ["hello"]));
|
|
692
|
+
assert.equal(await backend.delete("one"), true);
|
|
693
|
+
assert.equal(await backend.read("one"), null);
|
|
694
|
+
assert.deepEqual(await backend.list(), []);
|
|
695
|
+
assert.equal(await backend.delete("one"), false);
|
|
696
|
+
}),
|
|
697
|
+
check("keeps its own copy, whatever the caller does to the records", async ({ backend }) => {
|
|
698
|
+
const log = await logOf("one", ["original"]);
|
|
699
|
+
const expected = structuredClone(log);
|
|
700
|
+
await backend.create("one", log);
|
|
701
|
+
for (const records of [log, await backend.read("one") ?? []]) {
|
|
702
|
+
const message = records[2];
|
|
703
|
+
if (message?.type === "message") message.message.content = "tampered";
|
|
704
|
+
}
|
|
705
|
+
assert.deepEqual(await backend.read("one"), expected);
|
|
706
|
+
}),
|
|
707
|
+
check("a second handle sees what the first wrote, and appends after it", async (harness) => {
|
|
708
|
+
const log = await logOf("one", ["before", "after"]);
|
|
709
|
+
await harness.backend.create("one", log.slice(0, 4));
|
|
710
|
+
const reopened = harness.reopen();
|
|
711
|
+
assert.deepEqual(await reopened.read("one"), log.slice(0, 4));
|
|
712
|
+
assert.equal((await reopened.list()).length, 1);
|
|
713
|
+
await reopened.append("one", log.slice(4));
|
|
714
|
+
assert.deepEqual(await reopened.read("one"), log);
|
|
715
|
+
}),
|
|
716
|
+
check("carries a store across a restart: seq goes on and the totals with it", async (harness) => {
|
|
717
|
+
const first = createSessionStore(harness.backend);
|
|
718
|
+
const created = await first.create({ messages: [userMessage("before")] });
|
|
719
|
+
await first.append(created.id, [{
|
|
720
|
+
type: "usage",
|
|
721
|
+
usage: { inputTokens: 10 }
|
|
722
|
+
}]);
|
|
723
|
+
const second = createSessionStore(harness.reopen());
|
|
724
|
+
await second.append(created.id, [{
|
|
725
|
+
type: "message",
|
|
726
|
+
message: userMessage("after")
|
|
727
|
+
}, {
|
|
728
|
+
type: "usage",
|
|
729
|
+
usage: { inputTokens: 5 }
|
|
730
|
+
}]);
|
|
731
|
+
const records = await second.records(created.id) ?? [];
|
|
732
|
+
assert.deepEqual(records.map((record) => record.seq), records.map((_, index) => index));
|
|
733
|
+
const session = await second.get(created.id);
|
|
734
|
+
assert.equal(session?.messages.length, 2);
|
|
735
|
+
assert.deepEqual(session?.usage, { inputTokens: 15 });
|
|
736
|
+
assert.equal((await second.list())[0]?.messageCount, 2);
|
|
737
|
+
})
|
|
738
|
+
];
|
|
739
|
+
}
|
|
740
|
+
export { collect, eventsOfType, fakeTerminal, fixedClock, jpegBytes, makeTempDir, plainText, pngAttachment, pngBytes, posixPath, screenOf, scriptedAnswers, scriptedModel, scriptedSummary, sequentialIds, sessionBackendContract, stubToolRunner, testModel, toolContext };
|
|
741
|
+
|
|
742
|
+
//# sourceMappingURL=index.mjs.map
|