@wraith-ai/testing 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 xFroty
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,22 @@
1
- # Temporary Holding Version
1
+ # @wraith-ai/testing
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Test helpers for code built on [`@wraith-ai/core`](https://www.npmjs.com/package/@wraith-ai/core):
4
+ scripted models that answer a fixed sequence of steps, tool runners that record
5
+ what they were asked, a fake terminal, temporary directories, and
6
+ `sessionBackendContract`, the suite a session backend of your own must pass.
7
+
8
+ ```bash
9
+ npm i -D @wraith-ai/testing
10
+ ```
11
+
12
+ ```ts
13
+ import { createAgent, createSession, run } from "@wraith-ai/core";
14
+ import { collect, scriptedModel, testModel } from "@wraith-ai/testing";
15
+
16
+ const scripted = scriptedModel([{ text: "hello" }]);
17
+ const agent = createAgent({ model: testModel(scripted.model) });
18
+ const { types } = await collect(run(agent, { session: createSession("s1"), prompt: "hi" }));
19
+ // types: ["run-start", "step-start", …, "run-finish"]
20
+ ```
21
+
22
+ MIT
@@ -0,0 +1,250 @@
1
+ /**
2
+ * Fixtures shared across test suites: scripted models, event collectors and
3
+ * deterministic clocks. Tests build them from here, never by reaching into
4
+ * another package's internals.
5
+ */
6
+ import { MockLanguageModelV4 } from "ai/test";
7
+ import { AgentEvent, AgentEventType, AgentLanguageModel, Model, SerializedError, SessionBackend, SessionRecordInput, ToolCall, ToolContext, ToolRunner } from "@wraith-ai/core";
8
+ /**
9
+ * A model whose answers are written in advance.
10
+ *
11
+ * Our loop calls the model once per step, so a scripted model needs a
12
+ * different reply per call. That makes multi-step behaviour testable without
13
+ * a network, a key, or a bill.
14
+ *
15
+ * The chunk shapes here are the provider-side ones: `finishReason` is an
16
+ * object, and usage counts are nested under `total`.
17
+ */
18
+ interface ScriptedToolCall {
19
+ toolCallId: string;
20
+ toolName: string;
21
+ input: unknown;
22
+ }
23
+ interface ScriptedStep {
24
+ /** One delta, or one per element — the way a provider streams a longer answer. */
25
+ text?: string | readonly string[];
26
+ reasoning?: string;
27
+ toolCalls?: readonly ScriptedToolCall[];
28
+ inputTokens?: number;
29
+ outputTokens?: number;
30
+ /** Prompt-cache counters, as a provider reports them under input tokens. */
31
+ cacheReadTokens?: number;
32
+ cacheWriteTokens?: number;
33
+ /** Defaults to "tool-calls" when the step calls tools, "stop" otherwise. */
34
+ finishReason?: string;
35
+ /**
36
+ * Vendor bookkeeping on the finish chunk: the real cost of the call and
37
+ * which upstream served it.
38
+ */
39
+ providerMetadata?: Record<string, Record<string, unknown>>;
40
+ }
41
+ /** One call as the provider saw it. `tools` matters to prefix stability. */
42
+ interface ScriptedRequest {
43
+ prompt: unknown;
44
+ tools: unknown;
45
+ /**
46
+ * Everything else the SDK passed down. A per-call setting that quietly stops
47
+ * being sent has no other symptom.
48
+ */
49
+ options?: Record<string, unknown>;
50
+ }
51
+ interface ScriptedModel {
52
+ model: MockLanguageModelV4;
53
+ /** Prompts the model was called with, in order — for asserting on history. */
54
+ readonly calls: unknown[];
55
+ /** The same calls with everything else that shapes the request body. */
56
+ readonly requests: ScriptedRequest[];
57
+ }
58
+ interface ScriptedSummaryOptions {
59
+ inputTokens?: number;
60
+ outputTokens?: number;
61
+ }
62
+ /**
63
+ * A model that answers a single non-streaming call.
64
+ *
65
+ * Compaction asks for one summary with `generateText`, so it needs
66
+ * `doGenerate` rather than the streaming script above.
67
+ */
68
+ export declare function scriptedSummary(text: string, options?: ScriptedSummaryOptions): ScriptedModel;
69
+ interface ScriptedAnswer {
70
+ text?: string;
71
+ /** Thrown instead of answering. */
72
+ error?: Error;
73
+ inputTokens?: number;
74
+ outputTokens?: number;
75
+ }
76
+ /** A model that answers a sequence of non-streaming calls, one answer per call. */
77
+ export declare function scriptedAnswers(answers: readonly ScriptedAnswer[]): ScriptedModel;
78
+ export declare function scriptedModel(steps: readonly ScriptedStep[]): ScriptedModel;
79
+ /**
80
+ * A scripted model as the `Model` a registry would hand out. The ids are fixed
81
+ * because a session records them, and tests assert on the journal.
82
+ */
83
+ export declare function testModel(languageModel: AgentLanguageModel, fields?: Partial<Model>): Model;
84
+ /**
85
+ * Drains an event stream into something assertable.
86
+ *
87
+ * Tests compare the *sequence of event types* plus a few chosen fields, never
88
+ * whole objects — otherwise every cosmetic change to an event breaks the suite.
89
+ *
90
+ * `record` events go to `records`, not to `events`: they are the journal, and a
91
+ * test of what a run shows would otherwise list one after nearly every event.
92
+ */
93
+ interface Collected<TResult> {
94
+ events: AgentEvent[];
95
+ types: AgentEventType[];
96
+ records: SessionRecordInput[];
97
+ result: TResult;
98
+ }
99
+ export declare function collect<TResult>(stream: AsyncGenerator<AgentEvent, TResult>): Promise<Collected<TResult>>;
100
+ export declare function eventsOfType<TType extends AgentEventType>(events: readonly AgentEvent[], type: TType): Extract<AgentEvent, {
101
+ type: TType;
102
+ }>[];
103
+ /**
104
+ * A terminal that is not one: streams a full-screen application can be driven
105
+ * through from a test.
106
+ *
107
+ * `useInput` needs raw mode, which needs a tty, so the input stream reports
108
+ * itself as one. Tests run the real component tree, turn loop and SDK
109
+ * through it. The TUI and CLI chat tests both use it.
110
+ */
111
+ interface FakeTerminal {
112
+ stdin: NodeJS.ReadStream;
113
+ stdout: NodeJS.WriteStream;
114
+ /** Every write, in order. Ink emits one per committed frame. */
115
+ frames(): string[];
116
+ /** The last frame, or an empty string before the first one. */
117
+ lastFrame(): string;
118
+ /** Everything ever written, concatenated — for text that has scrolled away. */
119
+ output(): string;
120
+ /** Feeds keystrokes the way a terminal delivers them. */
121
+ type(text: string): void;
122
+ resize(columns: number, rows: number): void;
123
+ }
124
+ interface FakeTerminalOptions {
125
+ columns?: number;
126
+ rows?: number;
127
+ }
128
+ export declare function fakeTerminal(options?: FakeTerminalOptions): FakeTerminal;
129
+ /**
130
+ * Strips ANSI so an assertion reads like the text on screen.
131
+ *
132
+ * A test matching on escape codes fails when a colour changes, not when
133
+ * anything broke.
134
+ */
135
+ export declare function plainText(frame: string): string;
136
+ /**
137
+ * What the terminal would be showing, from the bytes a front end wrote.
138
+ *
139
+ * Replays the escapes onto a grid the way a terminal does, so an assertion
140
+ * checks what is on screen now. Covers the sequences Ink emits and nothing
141
+ * else; unrecognised sequences are skipped rather than drawn as text.
142
+ */
143
+ interface ScreenOptions {
144
+ columns?: number;
145
+ rows?: number;
146
+ }
147
+ interface Screen {
148
+ /** Every row, top to bottom, right-trimmed. */
149
+ rows: string[];
150
+ /** The rows as one string, for `toContain` and for a failure message. */
151
+ text: string;
152
+ }
153
+ export declare function screenOf(written: string, options?: ScreenOptions): Screen;
154
+ /**
155
+ * Events carry a timestamp and a run id. The agent takes both as injected
156
+ * functions; these are the ones tests inject, so event streams can be pinned.
157
+ */
158
+ /** A clock that advances by a fixed step on every read. */
159
+ export declare function fixedClock(start?: number, stepMs?: number): () => number;
160
+ /** Ids that are stable across runs: run-1, run-2, … */
161
+ export declare function sequentialIds(): (prefix: string) => string;
162
+ /**
163
+ * A tool runner for tests, built the way the real registry builds one: the
164
+ * definitions handed to the model carry a schema but no execute function, so
165
+ * the SDK validates arguments and returns the call to the loop.
166
+ *
167
+ * Hand-rolled placeholder objects do not work: the SDK inspects the schema.
168
+ */
169
+ interface StubToolRunner extends ToolRunner {
170
+ /** Calls the loop asked this runner to execute, in order. */
171
+ readonly seen: ToolCall[];
172
+ }
173
+ interface StubToolOptions {
174
+ /** Tool names exposed to the model. Defaults to a single `read_file`. */
175
+ names?: readonly string[];
176
+ /** What a successful execution returns. */
177
+ output?: unknown;
178
+ /** When set, every execution fails with this instead. */
179
+ error?: SerializedError;
180
+ }
181
+ export declare function stubToolRunner(options?: StubToolOptions): StubToolRunner;
182
+ /**
183
+ * A real directory for tool tests.
184
+ *
185
+ * File tools are tested against a real filesystem, not a mock.
186
+ */
187
+ interface TempDir {
188
+ readonly path: string;
189
+ /** Writes a file, creating parents. Keys are posix-style relative paths. */
190
+ write(files: Record<string, string>): void;
191
+ file(relative: string): string;
192
+ cleanup(): void;
193
+ }
194
+ export declare function makeTempDir(prefix?: string): TempDir;
195
+ /** Posix spelling of a path inside the temp dir, for asserting on results. */
196
+ export declare function posixPath(path: string): string;
197
+ /**
198
+ * A tool's context, filled in with the parts a test rarely cares about.
199
+ *
200
+ * Tools are plain functions, so this context is all the setup a test needs.
201
+ */
202
+ interface ToolContextOptions {
203
+ cwd: string;
204
+ signal?: AbortSignal;
205
+ sessionId?: string;
206
+ runId?: string;
207
+ /** Receives what a write reports for the screen; ignored when absent. */
208
+ showChange?: ToolContext["showChange"];
209
+ /** Receives the images a tool returns to the model; ignored when absent. */
210
+ attach?: ToolContext["attach"];
211
+ /** Directories outside `cwd` the tool may use. */
212
+ roots?: NonNullable<ToolContext["roots"]>;
213
+ /** Where an oversized result is saved; without it the tool cuts in place. */
214
+ resultsDir?: string;
215
+ /** The task this call may become; absent for a call that cannot be deferred. */
216
+ task?: NonNullable<ToolContext["task"]>;
217
+ }
218
+ export declare function toolContext(options: ToolContextOptions): ToolContext;
219
+ /**
220
+ * Image files small enough to write inline. Only the header is real: the core
221
+ * reads the type and size from it and never decodes the pixels.
222
+ */
223
+ /** A PNG of the given size: the signature and an IHDR chunk. */
224
+ export declare function pngBytes(width?: number, height?: number): Uint8Array;
225
+ /** A JPEG of the given size: start of image, one metadata segment, a start of frame. */
226
+ export declare function jpegBytes(width?: number, height?: number): Uint8Array;
227
+ /** The same image as an attachment, base64 as the core keeps it. */
228
+ export declare function pngAttachment(width?: number, height?: number): {
229
+ data: string;
230
+ mediaType: string;
231
+ };
232
+ interface SessionBackendHarness {
233
+ backend: SessionBackend;
234
+ /** A second handle on the same data, as a restarted process would see it. */
235
+ reopen(): SessionBackend;
236
+ cleanup?(): void | Promise<void>;
237
+ }
238
+ /** One rule of the contract. `run` builds its own harness and throws when the rule is broken. */
239
+ interface SessionBackendCheck {
240
+ name: string;
241
+ run(): Promise<void>;
242
+ }
243
+ /**
244
+ * What every `SessionBackend` owes `createSessionStore`, as checks any test
245
+ * runner can run: `for (const check of sessionBackendContract(make))
246
+ * test(check.name, check.run)`. A backend that passes can replace the file
247
+ * and memory ones under a store.
248
+ */
249
+ export declare function sessionBackendContract(make: () => SessionBackendHarness | Promise<SessionBackendHarness>): SessionBackendCheck[];
250
+ export type { Collected, FakeTerminal, FakeTerminalOptions, Screen, ScreenOptions, ScriptedAnswer, ScriptedModel, ScriptedRequest, ScriptedStep, ScriptedSummaryOptions, ScriptedToolCall, SessionBackendCheck, SessionBackendHarness, StubToolOptions, StubToolRunner, TempDir, ToolContextOptions };
package/dist/index.mjs ADDED
@@ -0,0 +1,740 @@
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 };
package/package.json CHANGED
@@ -1,6 +1,30 @@
1
1
  {
2
2
  "name": "@wraith-ai/testing",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Scripted models, a fake terminal and temporary directories for testing code built on @wraith-ai/core.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/xFroty/wraith.git",
9
+ "directory": "packages/testing"
10
+ },
11
+ "homepage": "https://github.com/xFroty/wraith#readme",
12
+ "type": "module",
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/index.d.mts",
16
+ "default": "./dist/index.mjs"
17
+ }
18
+ },
19
+ "files": [
20
+ "dist"
21
+ ],
22
+ "engines": {
23
+ "node": ">=22"
24
+ },
25
+ "dependencies": {
26
+ "@wraith-ai/core": "0.1.0",
27
+ "ai": "^7.0.173",
28
+ "zod": "^4.4.3"
29
+ }
30
+ }