@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 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,251 @@
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 };
251
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/mock-model.ts","../src/test-model.ts","../src/collect.ts","../src/fake-tty.ts","../src/screen.ts","../src/determinism.ts","../src/stub-tools.ts","../src/tmp-dir.ts","../src/tool-context.ts","../src/images.ts","../src/session-backend-contract.ts"],"mappings":";;;;;;;;;;;;;;;;;UAaiB;EACf;EACA;EACA;;UAGe;;EAEf;EACA;EACA,qBAAqB;EACrB;EACA;;EAEA;EACA;;EAEA;;;;;EAKA,mBAAmB,eAAe;;;UAgEnB;EACf;EACA;;;;;EAKA,UAAU;;UAGK;EACf,OAAO;;WAEE;;WAEA,UAAU;;UAGJ;EACf;EACA;;;;;;;;wBASc,gBACd,cACA,UAAS,yBACR;UA2Bc;EACf;;EAEA,QAAQ;EACR;EACA;;;wBAIc,gBAAgB,kBAAkB,mBAAmB;wBAiCrD,cAAc,gBAAgB,iBAAiB;;;;;wBClM/C,UAAU,eAAe,oBAAoB,SAAQ,QAAQ,SAAc;;;;;;;;;;UCM1E,UAAU;EACzB,QAAQ;EACR,OAAO;EACP,SAAS;EACT,QAAQ;;wBAGY,QAAQ,SAC5B,QAAQ,eAAe,YAAY,WAClC,QAAQ,UAAU;wBAcL,aAAa,cAAc,gBACzC,iBAAiB,cACjB,MAAM,QACL,QAAQ;EAAc,MAAM;;;;;;;;;;UC1Bd;EACf,OAAO,OAAO;EACd,QAAQ,OAAO;;EAEf;;EAEA;;EAEA;;EAEA,KAAK;EACL,OAAO,iBAAiB;;UA4CT;EACf;EACA;;wBAGc,aAAa,UAAS,sBAA2B;;;;;;;wBAkCjD,UAAU;;;;;;;;UChGT;EACf;EACA;;UAGe;;EAEf;;EAEA;;wBA8Cc,SAAS,iBAAiB,UAAS,gBAAqB;;;;;;wBC3DxD,WAAW,gBAAe;;wBAS1B,kBAAkB;;;;;;;;UCHjB,uBAAuB;;WAE7B,MAAM;;UAGA;;EAEf;;EAEA;;EAEA,QAAQ;;wBAGM,eAAe,UAAS,kBAAuB;;;;;;UChB9C;WACN;;EAET,MAAM,OAAO;EACb,KAAK;EACL;;wBAGc,YAAY,kBAA0B;;wBAsBtC,UAAU;;;;;;UChCT;EACf;EACA,SAAS;EACT;EACA;;EAEA,aAAa;;EAEb,SAAS;;EAET,QAAQ,YAAY;;EAEpB;;EAEA,OAAO,YAAY;;wBAGL,YAAY,SAAS,qBAAqB;;;;;;wBCnB1C,SAAS,gBAAW,kBAAa;;wBAajC,UAAU,gBAAW,kBAAa;;wBAWlC,cAAc,gBAAW;EAAe;EAAc;;UCnBrD;EACf,SAAS;;EAET,UAAU;EACV,mBAAmB;;;UAIJ;EACf;EACA,OAAO;;;;;;;;wBA8BO,uBACd,YAAY,wBAAwB,QAAQ,yBAC3C"}