@speeq/testing 0.0.0-stage → 0.2.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 +21 -0
- package/README.md +38 -2
- package/dist/index.cjs +300 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +183 -0
- package/dist/index.d.ts +183 -0
- package/dist/index.js +265 -0
- package/dist/index.js.map +1 -0
- package/dist/store-contract.cjs +166 -0
- package/dist/store-contract.cjs.map +1 -0
- package/dist/store-contract.d.cts +15 -0
- package/dist/store-contract.d.ts +15 -0
- package/dist/store-contract.js +141 -0
- package/dist/store-contract.js.map +1 -0
- package/package.json +77 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 speeq contributors
|
|
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,39 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @speeq/testing
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Test doubles for [speeq](../../README.md).
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
pnpm add -D @speeq/testing@next
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
| Export | Use it for |
|
|
10
|
+
| ---------------------------------------------------------------- | ----------------------------------------------------------------------- |
|
|
11
|
+
| `FakeLLMProvider` | Scripted model replies (text, tool calls, errors) and recorded requests |
|
|
12
|
+
| `createMockLLMProvider` | Keyword rules that act like a model, for **mock mode** with no API key |
|
|
13
|
+
| `FakeSpeechInput` / `FakeSpeechOutput` | Driving the browser client without a microphone or speakers |
|
|
14
|
+
| `startSession`, `readSseEvents`, `jsonRequest` | Calling a speeq handler in tests and collecting SSE events |
|
|
15
|
+
| `runConversationStoreContract` (`@speeq/testing/store-contract`) | Checking that a store adapter behaves correctly |
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
import { createMemoryStore } from "@speeq/store-memory";
|
|
19
|
+
import { createSpeeq } from "@speeq/server";
|
|
20
|
+
import { FakeLLMProvider, startSession } from "@speeq/testing";
|
|
21
|
+
|
|
22
|
+
const llm = new FakeLLMProvider([
|
|
23
|
+
{ toolCalls: [{ name: "navigate", arguments: { routeId: "pricing" } }] },
|
|
24
|
+
{ text: "Opening pricing." },
|
|
25
|
+
]);
|
|
26
|
+
const speeq = createSpeeq({
|
|
27
|
+
agent: { name: "Helper", instructions: "Help visitors." },
|
|
28
|
+
llm,
|
|
29
|
+
routes: [{ id: "pricing", path: "/pricing", title: "Pricing" }],
|
|
30
|
+
store: createMemoryStore(),
|
|
31
|
+
});
|
|
32
|
+
const session = await startSession(speeq.handler);
|
|
33
|
+
const events = await session.turn("take me to pricing");
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
The main entry has no Vitest dependency, so apps can use `createMockLLMProvider` at runtime.
|
|
37
|
+
The store contract needs Vitest (an optional peer dependency).
|
|
38
|
+
|
|
39
|
+
[Related guide or reference](../../docs/guides/testing.md)
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var src_exports = {};
|
|
22
|
+
__export(src_exports, {
|
|
23
|
+
FakeLLMProvider: () => FakeLLMProvider,
|
|
24
|
+
FakeSpeechInput: () => FakeSpeechInput,
|
|
25
|
+
FakeSpeechOutput: () => FakeSpeechOutput,
|
|
26
|
+
assistantText: () => assistantText,
|
|
27
|
+
createMockLLMProvider: () => createMockLLMProvider,
|
|
28
|
+
jsonRequest: () => jsonRequest,
|
|
29
|
+
playStep: () => playStep,
|
|
30
|
+
readSseEvents: () => readSseEvents,
|
|
31
|
+
startSession: () => startSession
|
|
32
|
+
});
|
|
33
|
+
module.exports = __toCommonJS(src_exports);
|
|
34
|
+
|
|
35
|
+
// src/fake-llm.ts
|
|
36
|
+
var import_utils = require("@speeq/core/utils");
|
|
37
|
+
var FakeLLMProvider = class {
|
|
38
|
+
kind;
|
|
39
|
+
model;
|
|
40
|
+
/** Every request received, in order. */
|
|
41
|
+
requests = [];
|
|
42
|
+
script;
|
|
43
|
+
constructor(script, options = {}) {
|
|
44
|
+
this.script = script;
|
|
45
|
+
this.kind = options.kind ?? "fake";
|
|
46
|
+
this.model = options.model ?? "fake-model";
|
|
47
|
+
}
|
|
48
|
+
/** Number of LLM calls made so far. */
|
|
49
|
+
get callCount() {
|
|
50
|
+
return this.requests.length;
|
|
51
|
+
}
|
|
52
|
+
async *stream(request) {
|
|
53
|
+
const index = this.requests.length;
|
|
54
|
+
this.requests.push(structuredClone({ ...request, signal: void 0 }));
|
|
55
|
+
const step = typeof this.script === "function" ? this.script(request, index) : this.script[index] ?? { text: "" };
|
|
56
|
+
yield* playStep(step, request.signal);
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
async function* playStep(step, signal) {
|
|
60
|
+
if (step.text) {
|
|
61
|
+
for (const piece of step.text.match(/\S+\s*|\s+/g) ?? []) {
|
|
62
|
+
if (step.delayMs) await (0, import_utils.sleep)(step.delayMs, signal);
|
|
63
|
+
signal?.throwIfAborted();
|
|
64
|
+
yield { type: "text-delta", text: piece };
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
if (step.error !== void 0) throw step.error;
|
|
68
|
+
const calls = step.toolCalls ?? [];
|
|
69
|
+
for (const call of calls) {
|
|
70
|
+
yield { type: "tool-call", call: { ...call, id: call.id ?? (0, import_utils.createId)("call") } };
|
|
71
|
+
}
|
|
72
|
+
const finish = {
|
|
73
|
+
type: "finish",
|
|
74
|
+
reason: calls.length > 0 ? "tool_calls" : "stop"
|
|
75
|
+
};
|
|
76
|
+
if (step.usage) finish.usage = step.usage;
|
|
77
|
+
yield finish;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// src/fake-speech.ts
|
|
81
|
+
var FakeSpeechInput = class {
|
|
82
|
+
supported;
|
|
83
|
+
/** Options of every `start()` call. */
|
|
84
|
+
starts = [];
|
|
85
|
+
handlers = null;
|
|
86
|
+
pendingFinal = "";
|
|
87
|
+
constructor(options = {}) {
|
|
88
|
+
this.supported = options.supported ?? true;
|
|
89
|
+
}
|
|
90
|
+
/** True while recognition is active. */
|
|
91
|
+
get listening() {
|
|
92
|
+
return this.handlers !== null;
|
|
93
|
+
}
|
|
94
|
+
start(options, handlers) {
|
|
95
|
+
this.starts.push(options);
|
|
96
|
+
this.handlers = handlers;
|
|
97
|
+
}
|
|
98
|
+
/** Simulates speech: emits interim transcripts, then the final one, then ends. */
|
|
99
|
+
say(final, interim = []) {
|
|
100
|
+
const h = this.handlers;
|
|
101
|
+
if (!h) throw new Error("FakeSpeechInput.say() called while not listening");
|
|
102
|
+
for (const partial of interim) h.onInterim?.(partial);
|
|
103
|
+
h.onFinal(final);
|
|
104
|
+
this.end();
|
|
105
|
+
}
|
|
106
|
+
/** Simulates an interim transcript only (user still speaking). */
|
|
107
|
+
partial(text) {
|
|
108
|
+
this.pendingFinal = text;
|
|
109
|
+
this.handlers?.onInterim?.(text);
|
|
110
|
+
}
|
|
111
|
+
/** Simulates a recognition error. */
|
|
112
|
+
fail(code) {
|
|
113
|
+
this.handlers?.onError?.({ code, message: code });
|
|
114
|
+
this.end();
|
|
115
|
+
}
|
|
116
|
+
stop() {
|
|
117
|
+
const h = this.handlers;
|
|
118
|
+
if (h && this.pendingFinal) h.onFinal(this.pendingFinal);
|
|
119
|
+
this.end();
|
|
120
|
+
}
|
|
121
|
+
abort() {
|
|
122
|
+
this.pendingFinal = "";
|
|
123
|
+
this.end();
|
|
124
|
+
}
|
|
125
|
+
end() {
|
|
126
|
+
const h = this.handlers;
|
|
127
|
+
this.handlers = null;
|
|
128
|
+
this.pendingFinal = "";
|
|
129
|
+
h?.onEnd?.();
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
var FakeSpeechOutput = class {
|
|
133
|
+
supported;
|
|
134
|
+
/** Every text passed to `speak()`, in order, with its language. */
|
|
135
|
+
spoken = [];
|
|
136
|
+
/** Number of `cancel()` calls. */
|
|
137
|
+
cancelCount = 0;
|
|
138
|
+
voices;
|
|
139
|
+
speakMs;
|
|
140
|
+
/**
|
|
141
|
+
* @param options.voices - Languages that have a voice. Omit to have voices for every language.
|
|
142
|
+
* @param options.speakMs - How long each `speak()` takes. Default 0.
|
|
143
|
+
*/
|
|
144
|
+
constructor(options = {}) {
|
|
145
|
+
this.supported = options.supported ?? true;
|
|
146
|
+
this.voices = options.voices ? new Set(options.voices) : null;
|
|
147
|
+
this.speakMs = options.speakMs ?? 0;
|
|
148
|
+
}
|
|
149
|
+
async hasVoiceFor(language) {
|
|
150
|
+
return this.supported && (this.voices === null || this.voices.has(language));
|
|
151
|
+
}
|
|
152
|
+
async speak(text, options) {
|
|
153
|
+
this.spoken.push({ text, language: options.language });
|
|
154
|
+
if (this.speakMs > 0) await new Promise((r) => setTimeout(r, this.speakMs));
|
|
155
|
+
}
|
|
156
|
+
cancel() {
|
|
157
|
+
this.cancelCount += 1;
|
|
158
|
+
}
|
|
159
|
+
};
|
|
160
|
+
|
|
161
|
+
// src/http.ts
|
|
162
|
+
var import_core = require("@speeq/core");
|
|
163
|
+
function jsonRequest(path, options = {}) {
|
|
164
|
+
const headers = new Headers(options.headers);
|
|
165
|
+
if (options.body !== void 0) headers.set("content-type", "application/json");
|
|
166
|
+
if (options.token) headers.set("authorization", `Bearer ${options.token}`);
|
|
167
|
+
const init = {
|
|
168
|
+
method: options.method ?? (options.body === void 0 ? "GET" : "POST"),
|
|
169
|
+
headers
|
|
170
|
+
};
|
|
171
|
+
if (options.body !== void 0) init.body = JSON.stringify(options.body);
|
|
172
|
+
return new Request(`http://localhost${path}`, init);
|
|
173
|
+
}
|
|
174
|
+
async function readSseEvents(response) {
|
|
175
|
+
if (!response.body) return [];
|
|
176
|
+
const parser = new import_core.SseParser();
|
|
177
|
+
const decoder = new TextDecoder();
|
|
178
|
+
const events = [];
|
|
179
|
+
const reader = response.body.getReader();
|
|
180
|
+
for (; ; ) {
|
|
181
|
+
const { value, done } = await reader.read();
|
|
182
|
+
const messages = done ? parser.end() : parser.push(decoder.decode(value, { stream: true }));
|
|
183
|
+
for (const m of messages) events.push(import_core.ProtocolEventSchema.parse(JSON.parse(m.data)));
|
|
184
|
+
if (done) break;
|
|
185
|
+
}
|
|
186
|
+
return events;
|
|
187
|
+
}
|
|
188
|
+
function assistantText(events) {
|
|
189
|
+
return events.filter((e) => e.type === "assistant.message").map((e) => e.type === "assistant.message" ? e.text : "").join(" ");
|
|
190
|
+
}
|
|
191
|
+
async function startSession(handler, options = {}) {
|
|
192
|
+
const base = options.basePath ?? "/api/speeq";
|
|
193
|
+
const language = options.language ?? "en-IN";
|
|
194
|
+
const res = await handler(
|
|
195
|
+
jsonRequest(`${base}/session`, { body: { language }, headers: options.headers ?? {} })
|
|
196
|
+
);
|
|
197
|
+
if (!res.ok) throw new Error(`session failed: ${res.status} ${await res.text()}`);
|
|
198
|
+
const { sessionId, sessionToken } = await res.json();
|
|
199
|
+
return {
|
|
200
|
+
sessionId,
|
|
201
|
+
token: sessionToken,
|
|
202
|
+
async turn(text, extra = {}) {
|
|
203
|
+
const body = { text, language: extra.language ?? language, context: extra.context };
|
|
204
|
+
const r = await handler(
|
|
205
|
+
jsonRequest(`${base}/session/${sessionId}/turn`, {
|
|
206
|
+
body,
|
|
207
|
+
token: sessionToken,
|
|
208
|
+
headers: { ...options.headers, ...extra.headers }
|
|
209
|
+
})
|
|
210
|
+
);
|
|
211
|
+
return readSseEvents(r);
|
|
212
|
+
},
|
|
213
|
+
async confirm(confirmationId, approved, headers) {
|
|
214
|
+
const r = await handler(
|
|
215
|
+
jsonRequest(`${base}/session/${sessionId}/confirm`, {
|
|
216
|
+
body: { confirmationId, approved },
|
|
217
|
+
token: sessionToken,
|
|
218
|
+
headers: { ...options.headers, ...headers }
|
|
219
|
+
})
|
|
220
|
+
);
|
|
221
|
+
return readSseEvents(r);
|
|
222
|
+
}
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
// src/mock-llm.ts
|
|
227
|
+
function createMockLLMProvider(options) {
|
|
228
|
+
return {
|
|
229
|
+
kind: "mock",
|
|
230
|
+
model: "mock-keywords",
|
|
231
|
+
async *stream(request) {
|
|
232
|
+
const step = decide(request, options);
|
|
233
|
+
yield* playStep(
|
|
234
|
+
options.delayMs ? { ...step, delayMs: options.delayMs } : step,
|
|
235
|
+
request.signal
|
|
236
|
+
);
|
|
237
|
+
}
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
function decide(request, options) {
|
|
241
|
+
const messages = request.messages;
|
|
242
|
+
const last = messages.at(-1);
|
|
243
|
+
const userText = lastUserText(messages);
|
|
244
|
+
if (last?.role === "tool") {
|
|
245
|
+
const results = trailingToolMessages(messages);
|
|
246
|
+
const summarize = options.afterTool ?? defaultAfterTool;
|
|
247
|
+
const parts = results.map(
|
|
248
|
+
(m) => summarize({ toolName: m.name, result: m.content, userText, request }).text ?? ""
|
|
249
|
+
);
|
|
250
|
+
return { text: parts.filter(Boolean).join(" ") || "Done." };
|
|
251
|
+
}
|
|
252
|
+
const input = {
|
|
253
|
+
text: userText,
|
|
254
|
+
normalized: userText.toLowerCase().trim(),
|
|
255
|
+
request,
|
|
256
|
+
hasTool: (name) => request.tools.some((t) => t.name === name)
|
|
257
|
+
};
|
|
258
|
+
for (const rule of options.rules) {
|
|
259
|
+
if (typeof rule.match === "function") {
|
|
260
|
+
if (rule.match(input)) return rule.respond(input, null);
|
|
261
|
+
continue;
|
|
262
|
+
}
|
|
263
|
+
const m = input.normalized.match(rule.match);
|
|
264
|
+
if (m) return rule.respond(input, m);
|
|
265
|
+
}
|
|
266
|
+
return options.fallback?.(input) ?? { text: "Sorry, I did not understand that (mock mode)." };
|
|
267
|
+
}
|
|
268
|
+
function lastUserText(messages) {
|
|
269
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
270
|
+
const m = messages[i];
|
|
271
|
+
if (m?.role === "user") return m.content;
|
|
272
|
+
}
|
|
273
|
+
return "";
|
|
274
|
+
}
|
|
275
|
+
function trailingToolMessages(messages) {
|
|
276
|
+
const out = [];
|
|
277
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
278
|
+
const m = messages[i];
|
|
279
|
+
if (m?.role !== "tool") break;
|
|
280
|
+
out.unshift(m);
|
|
281
|
+
}
|
|
282
|
+
return out;
|
|
283
|
+
}
|
|
284
|
+
function defaultAfterTool({ toolName, result }) {
|
|
285
|
+
if (toolName === "navigate") return { text: "Done, opening it now." };
|
|
286
|
+
return { text: `Here is what I found: ${result.slice(0, 300)}` };
|
|
287
|
+
}
|
|
288
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
289
|
+
0 && (module.exports = {
|
|
290
|
+
FakeLLMProvider,
|
|
291
|
+
FakeSpeechInput,
|
|
292
|
+
FakeSpeechOutput,
|
|
293
|
+
assistantText,
|
|
294
|
+
createMockLLMProvider,
|
|
295
|
+
jsonRequest,
|
|
296
|
+
playStep,
|
|
297
|
+
readSseEvents,
|
|
298
|
+
startSession
|
|
299
|
+
});
|
|
300
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/fake-llm.ts","../src/fake-speech.ts","../src/http.ts","../src/mock-llm.ts"],"sourcesContent":["/**\n * `@speeq/testing`: test doubles for speeq. The main entry has no test-runner dependency, so the\n * {@link createMockLLMProvider} can also power \"mock mode\" in apps. The store contract suite\n * (which needs Vitest) lives at `@speeq/testing/store-contract`.\n * @packageDocumentation\n */\nexport { FakeLLMProvider, type FakeScript, type FakeStep, playStep } from \"./fake-llm.js\";\nexport { FakeSpeechInput, FakeSpeechOutput } from \"./fake-speech.js\";\nexport {\n assistantText,\n type FetchHandler,\n type JsonRequestOptions,\n jsonRequest,\n readSseEvents,\n startSession,\n type TestSession,\n} from \"./http.js\";\nexport {\n createMockLLMProvider,\n type MockAfterToolInput,\n type MockLLMOptions,\n type MockRule,\n type MockRuleInput,\n} from \"./mock-llm.js\";\n","import type { LLMProvider, LLMRequest, LLMStreamChunk, LLMToolCall, Usage } from \"@speeq/core\";\nimport { createId, sleep } from \"@speeq/core/utils\";\n\n/** One scripted model reply for {@link FakeLLMProvider}. */\nexport interface FakeStep {\n /** Text to stream (split into word-sized deltas). */\n text?: string;\n /** Tool calls to emit after the text. `id` is generated when omitted. */\n toolCalls?: Array<Omit<LLMToolCall, \"id\"> & { id?: string }>;\n /** Throw this error instead of replying (after streaming `text`, if any). */\n error?: unknown;\n usage?: Usage;\n /** Wait this long before each delta (to test latency and aborts). */\n delayMs?: number;\n}\n\n/** A script: a fixed list of steps (one per LLM call), or a function of the request. */\nexport type FakeScript = FakeStep[] | ((request: LLMRequest, callIndex: number) => FakeStep);\n\n/**\n * An {@link LLMProvider} that replays a script. Every request is recorded in `requests` so tests\n * can assert on prompts, tool definitions and history.\n *\n * @example\n * const llm = new FakeLLMProvider([\n * { toolCalls: [{ name: \"navigate\", arguments: { routeId: \"pricing\" } }] },\n * { text: \"Opening pricing.\" },\n * ]);\n */\nexport class FakeLLMProvider implements LLMProvider {\n readonly kind: string;\n readonly model: string;\n /** Every request received, in order. */\n readonly requests: LLMRequest[] = [];\n private readonly script: FakeScript;\n\n constructor(script: FakeScript, options: { kind?: string; model?: string } = {}) {\n this.script = script;\n this.kind = options.kind ?? \"fake\";\n this.model = options.model ?? \"fake-model\";\n }\n\n /** Number of LLM calls made so far. */\n get callCount(): number {\n return this.requests.length;\n }\n\n async *stream(request: LLMRequest): AsyncIterable<LLMStreamChunk> {\n const index = this.requests.length;\n this.requests.push(structuredClone({ ...request, signal: undefined }));\n const step =\n typeof this.script === \"function\"\n ? this.script(request, index)\n : (this.script[index] ?? { text: \"\" });\n yield* playStep(step, request.signal);\n }\n}\n\n/** Streams one {@link FakeStep} as normalized chunks. Shared with the mock provider. */\nexport async function* playStep(\n step: FakeStep,\n signal?: AbortSignal,\n): AsyncIterable<LLMStreamChunk> {\n if (step.text) {\n for (const piece of step.text.match(/\\S+\\s*|\\s+/g) ?? []) {\n if (step.delayMs) await sleep(step.delayMs, signal);\n signal?.throwIfAborted();\n yield { type: \"text-delta\", text: piece };\n }\n }\n if (step.error !== undefined) throw step.error;\n const calls = step.toolCalls ?? [];\n for (const call of calls) {\n yield { type: \"tool-call\", call: { ...call, id: call.id ?? createId(\"call\") } };\n }\n const finish: LLMStreamChunk = {\n type: \"finish\",\n reason: calls.length > 0 ? \"tool_calls\" : \"stop\",\n };\n if (step.usage) finish.usage = step.usage;\n yield finish;\n}\n","import type {\n SpeakOptions,\n SpeechInput,\n SpeechInputHandlers,\n SpeechInputOptions,\n SpeechOutput,\n} from \"@speeq/core\";\n\n/**\n * A scriptable {@link SpeechInput}. Call {@link FakeSpeechInput.say} to simulate the user speaking\n * while recognition is active.\n */\nexport class FakeSpeechInput implements SpeechInput {\n readonly supported: boolean;\n /** Options of every `start()` call. */\n readonly starts: SpeechInputOptions[] = [];\n private handlers: SpeechInputHandlers | null = null;\n private pendingFinal = \"\";\n\n constructor(options: { supported?: boolean } = {}) {\n this.supported = options.supported ?? true;\n }\n\n /** True while recognition is active. */\n get listening(): boolean {\n return this.handlers !== null;\n }\n\n start(options: SpeechInputOptions, handlers: SpeechInputHandlers): void {\n this.starts.push(options);\n this.handlers = handlers;\n }\n\n /** Simulates speech: emits interim transcripts, then the final one, then ends. */\n say(final: string, interim: string[] = []): void {\n const h = this.handlers;\n if (!h) throw new Error(\"FakeSpeechInput.say() called while not listening\");\n for (const partial of interim) h.onInterim?.(partial);\n h.onFinal(final);\n this.end();\n }\n\n /** Simulates an interim transcript only (user still speaking). */\n partial(text: string): void {\n this.pendingFinal = text;\n this.handlers?.onInterim?.(text);\n }\n\n /** Simulates a recognition error. */\n fail(code: Parameters<NonNullable<SpeechInputHandlers[\"onError\"]>>[0][\"code\"]): void {\n this.handlers?.onError?.({ code, message: code });\n this.end();\n }\n\n stop(): void {\n const h = this.handlers;\n if (h && this.pendingFinal) h.onFinal(this.pendingFinal);\n this.end();\n }\n\n abort(): void {\n this.pendingFinal = \"\";\n this.end();\n }\n\n private end(): void {\n const h = this.handlers;\n this.handlers = null;\n this.pendingFinal = \"\";\n h?.onEnd?.();\n }\n}\n\n/** A {@link SpeechOutput} that records what would be spoken. */\nexport class FakeSpeechOutput implements SpeechOutput {\n readonly supported: boolean;\n /** Every text passed to `speak()`, in order, with its language. */\n readonly spoken: Array<{ text: string; language: string }> = [];\n /** Number of `cancel()` calls. */\n cancelCount = 0;\n private readonly voices: Set<string> | null;\n private readonly speakMs: number;\n\n /**\n * @param options.voices - Languages that have a voice. Omit to have voices for every language.\n * @param options.speakMs - How long each `speak()` takes. Default 0.\n */\n constructor(options: { supported?: boolean; voices?: string[]; speakMs?: number } = {}) {\n this.supported = options.supported ?? true;\n this.voices = options.voices ? new Set(options.voices) : null;\n this.speakMs = options.speakMs ?? 0;\n }\n\n async hasVoiceFor(language: string): Promise<boolean> {\n return this.supported && (this.voices === null || this.voices.has(language));\n }\n\n async speak(text: string, options: SpeakOptions): Promise<void> {\n this.spoken.push({ text, language: options.language });\n if (this.speakMs > 0) await new Promise((r) => setTimeout(r, this.speakMs));\n }\n\n cancel(): void {\n this.cancelCount += 1;\n }\n}\n","import { type ProtocolEvent, ProtocolEventSchema, SseParser } from \"@speeq/core\";\n\n/** A web-standard request handler, such as the one returned by `createSpeeq()`. */\nexport type FetchHandler = (request: Request) => Promise<Response>;\n\n/** Options for {@link jsonRequest}. */\nexport interface JsonRequestOptions {\n method?: string;\n body?: unknown;\n token?: string;\n headers?: Record<string, string>;\n}\n\n/** Builds a JSON `Request` for `http://localhost{path}`. */\nexport function jsonRequest(path: string, options: JsonRequestOptions = {}): Request {\n const headers = new Headers(options.headers);\n if (options.body !== undefined) headers.set(\"content-type\", \"application/json\");\n if (options.token) headers.set(\"authorization\", `Bearer ${options.token}`);\n const init: RequestInit = {\n method: options.method ?? (options.body === undefined ? \"GET\" : \"POST\"),\n headers,\n };\n if (options.body !== undefined) init.body = JSON.stringify(options.body);\n return new Request(`http://localhost${path}`, init);\n}\n\n/**\n * Reads an SSE `Response` to the end and returns every protocol event, validated against\n * `ProtocolEventSchema` (an invalid event fails the test).\n */\nexport async function readSseEvents(response: Response): Promise<ProtocolEvent[]> {\n if (!response.body) return [];\n const parser = new SseParser();\n const decoder = new TextDecoder();\n const events: ProtocolEvent[] = [];\n const reader = response.body.getReader();\n for (;;) {\n const { value, done } = await reader.read();\n const messages = done ? parser.end() : parser.push(decoder.decode(value, { stream: true }));\n for (const m of messages) events.push(ProtocolEventSchema.parse(JSON.parse(m.data)));\n if (done) break;\n }\n return events;\n}\n\n/** Convenience: the concatenated `assistant.message` texts of a list of events. */\nexport function assistantText(events: ProtocolEvent[]): string {\n return events\n .filter((e) => e.type === \"assistant.message\")\n .map((e) => (e.type === \"assistant.message\" ? e.text : \"\"))\n .join(\" \");\n}\n\n/** Session handle returned by {@link startSession}. */\nexport interface TestSession {\n sessionId: string;\n token: string;\n /** Sends a turn and returns all streamed events. */\n turn(\n text: string,\n extra?: { language?: string; context?: unknown; headers?: Record<string, string> },\n ): Promise<ProtocolEvent[]>;\n /** Answers a confirmation and returns all streamed events. */\n confirm(\n confirmationId: string,\n approved: boolean,\n headers?: Record<string, string>,\n ): Promise<ProtocolEvent[]>;\n}\n\n/**\n * Starts a session against `handler` (mounted at `basePath`) and returns helpers to send turns.\n * Throws if session creation fails.\n */\nexport async function startSession(\n handler: FetchHandler,\n options: { basePath?: string; language?: string; headers?: Record<string, string> } = {},\n): Promise<TestSession> {\n const base = options.basePath ?? \"/api/speeq\";\n const language = options.language ?? \"en-IN\";\n const res = await handler(\n jsonRequest(`${base}/session`, { body: { language }, headers: options.headers ?? {} }),\n );\n if (!res.ok) throw new Error(`session failed: ${res.status} ${await res.text()}`);\n const { sessionId, sessionToken } = (await res.json()) as {\n sessionId: string;\n sessionToken: string;\n };\n return {\n sessionId,\n token: sessionToken,\n async turn(text, extra = {}) {\n const body = { text, language: extra.language ?? language, context: extra.context };\n const r = await handler(\n jsonRequest(`${base}/session/${sessionId}/turn`, {\n body,\n token: sessionToken,\n headers: { ...options.headers, ...extra.headers },\n }),\n );\n return readSseEvents(r);\n },\n async confirm(confirmationId, approved, headers) {\n const r = await handler(\n jsonRequest(`${base}/session/${sessionId}/confirm`, {\n body: { confirmationId, approved },\n token: sessionToken,\n headers: { ...options.headers, ...headers },\n }),\n );\n return readSseEvents(r);\n },\n };\n}\n","import type { LLMMessage, LLMProvider, LLMRequest, LLMStreamChunk } from \"@speeq/core\";\nimport { type FakeStep, playStep } from \"./fake-llm.js\";\n\n/** What a {@link MockRule} sees when deciding how to reply. */\nexport interface MockRuleInput {\n /** The latest user message text. */\n text: string;\n /** The same text, lower-cased and trimmed. */\n normalized: string;\n /** The full request (messages, tools). */\n request: LLMRequest;\n /** True if a tool with this name is offered in the request. */\n hasTool(name: string): boolean;\n}\n\n/** One keyword rule: when `match` hits, reply with `respond`. */\nexport interface MockRule {\n /** A regex tested against the normalized text, or a predicate. */\n match: RegExp | ((input: MockRuleInput) => boolean);\n respond(input: MockRuleInput, match: RegExpMatchArray | null): FakeStep;\n}\n\n/** What {@link MockLLMOptions.afterTool} sees after a tool ran. */\nexport interface MockAfterToolInput {\n toolName: string;\n /** The tool result text the model would see (JSON string or error message). */\n result: string;\n /** The user's original text in this turn. */\n userText: string;\n request: LLMRequest;\n}\n\n/** Options for {@link createMockLLMProvider}. */\nexport interface MockLLMOptions {\n rules: MockRule[];\n /** Reply when no rule matches. */\n fallback?: (input: MockRuleInput) => FakeStep;\n /** Reply after tool results arrive. Defaults to a short generic summary. */\n afterTool?: (input: MockAfterToolInput) => FakeStep;\n /** Delay per streamed word, to feel like a real model. Default 0. */\n delayMs?: number;\n}\n\n/**\n * A keyword-based {@link LLMProvider} so apps can run with no API key (\"mock mode\"). It is\n * deterministic: rules are checked in order against the latest user message. After tool results\n * it calls `afterTool`. It is not a real model. Use it for demos, e2e tests and first-run setup.\n */\nexport function createMockLLMProvider(options: MockLLMOptions): LLMProvider {\n return {\n kind: \"mock\",\n model: \"mock-keywords\",\n async *stream(request: LLMRequest): AsyncIterable<LLMStreamChunk> {\n const step = decide(request, options);\n yield* playStep(\n options.delayMs ? { ...step, delayMs: options.delayMs } : step,\n request.signal,\n );\n },\n };\n}\n\nfunction decide(request: LLMRequest, options: MockLLMOptions): FakeStep {\n const messages = request.messages;\n const last = messages.at(-1);\n const userText = lastUserText(messages);\n if (last?.role === \"tool\") {\n const results = trailingToolMessages(messages);\n const summarize = options.afterTool ?? defaultAfterTool;\n const parts = results.map(\n (m) => summarize({ toolName: m.name, result: m.content, userText, request }).text ?? \"\",\n );\n return { text: parts.filter(Boolean).join(\" \") || \"Done.\" };\n }\n const input: MockRuleInput = {\n text: userText,\n normalized: userText.toLowerCase().trim(),\n request,\n hasTool: (name) => request.tools.some((t) => t.name === name),\n };\n for (const rule of options.rules) {\n if (typeof rule.match === \"function\") {\n if (rule.match(input)) return rule.respond(input, null);\n continue;\n }\n const m = input.normalized.match(rule.match);\n if (m) return rule.respond(input, m);\n }\n return options.fallback?.(input) ?? { text: \"Sorry, I did not understand that (mock mode).\" };\n}\n\nfunction lastUserText(messages: LLMMessage[]): string {\n for (let i = messages.length - 1; i >= 0; i--) {\n const m = messages[i];\n if (m?.role === \"user\") return m.content;\n }\n return \"\";\n}\n\nfunction trailingToolMessages(messages: LLMMessage[]) {\n const out: Array<Extract<LLMMessage, { role: \"tool\" }>> = [];\n for (let i = messages.length - 1; i >= 0; i--) {\n const m = messages[i];\n if (m?.role !== \"tool\") break;\n out.unshift(m);\n }\n return out;\n}\n\nfunction defaultAfterTool({ toolName, result }: MockAfterToolInput): FakeStep {\n if (toolName === \"navigate\") return { text: \"Done, opening it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utput, SpeakOptions, ProtocolEvent } from '@speeq/core';
|
|
2
|
+
|
|
3
|
+
/** One scripted model reply for {@link FakeLLMProvider}. */
|
|
4
|
+
interface FakeStep {
|
|
5
|
+
/** Text to stream (split into word-sized deltas). */
|
|
6
|
+
text?: string;
|
|
7
|
+
/** Tool calls to emit after the text. `id` is generated when omitted. */
|
|
8
|
+
toolCalls?: Array<Omit<LLMToolCall, "id"> & {
|
|
9
|
+
id?: string;
|
|
10
|
+
}>;
|
|
11
|
+
/** Throw this error instead of replying (after streaming `text`, if any). */
|
|
12
|
+
error?: unknown;
|
|
13
|
+
usage?: Usage;
|
|
14
|
+
/** Wait this long before each delta (to test latency and aborts). */
|
|
15
|
+
delayMs?: number;
|
|
16
|
+
}
|
|
17
|
+
/** A script: a fixed list of steps (one per LLM call), or a function of the request. */
|
|
18
|
+
type FakeScript = FakeStep[] | ((request: LLMRequest, callIndex: number) => FakeStep);
|
|
19
|
+
/**
|
|
20
|
+
* An {@link LLMProvider} that replays a script. Every request is recorded in `requests` so tests
|
|
21
|
+
* can assert on prompts, tool definitions and history.
|
|
22
|
+
*
|
|
23
|
+
* @example
|
|
24
|
+
* const llm = new FakeLLMProvider([
|
|
25
|
+
* { toolCalls: [{ name: "navigate", arguments: { routeId: "pricing" } }] },
|
|
26
|
+
* { text: "Opening pricing." },
|
|
27
|
+
* ]);
|
|
28
|
+
*/
|
|
29
|
+
declare class FakeLLMProvider implements LLMProvider {
|
|
30
|
+
readonly kind: string;
|
|
31
|
+
readonly model: string;
|
|
32
|
+
/** Every request received, in order. */
|
|
33
|
+
readonly requests: LLMRequest[];
|
|
34
|
+
private readonly script;
|
|
35
|
+
constructor(script: FakeScript, options?: {
|
|
36
|
+
kind?: string;
|
|
37
|
+
model?: string;
|
|
38
|
+
});
|
|
39
|
+
/** Number of LLM calls made so far. */
|
|
40
|
+
get callCount(): number;
|
|
41
|
+
stream(request: LLMRequest): AsyncIterable<LLMStreamChunk>;
|
|
42
|
+
}
|
|
43
|
+
/** Streams one {@link FakeStep} as normalized chunks. Shared with the mock provider. */
|
|
44
|
+
declare function playStep(step: FakeStep, signal?: AbortSignal): AsyncIterable<LLMStreamChunk>;
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* A scriptable {@link SpeechInput}. Call {@link FakeSpeechInput.say} to simulate the user speaking
|
|
48
|
+
* while recognition is active.
|
|
49
|
+
*/
|
|
50
|
+
declare class FakeSpeechInput implements SpeechInput {
|
|
51
|
+
readonly supported: boolean;
|
|
52
|
+
/** Options of every `start()` call. */
|
|
53
|
+
readonly starts: SpeechInputOptions[];
|
|
54
|
+
private handlers;
|
|
55
|
+
private pendingFinal;
|
|
56
|
+
constructor(options?: {
|
|
57
|
+
supported?: boolean;
|
|
58
|
+
});
|
|
59
|
+
/** True while recognition is active. */
|
|
60
|
+
get listening(): boolean;
|
|
61
|
+
start(options: SpeechInputOptions, handlers: SpeechInputHandlers): void;
|
|
62
|
+
/** Simulates speech: emits interim transcripts, then the final one, then ends. */
|
|
63
|
+
say(final: string, interim?: string[]): void;
|
|
64
|
+
/** Simulates an interim transcript only (user still speaking). */
|
|
65
|
+
partial(text: string): void;
|
|
66
|
+
/** Simulates a recognition error. */
|
|
67
|
+
fail(code: Parameters<NonNullable<SpeechInputHandlers["onError"]>>[0]["code"]): void;
|
|
68
|
+
stop(): void;
|
|
69
|
+
abort(): void;
|
|
70
|
+
private end;
|
|
71
|
+
}
|
|
72
|
+
/** A {@link SpeechOutput} that records what would be spoken. */
|
|
73
|
+
declare class FakeSpeechOutput implements SpeechOutput {
|
|
74
|
+
readonly supported: boolean;
|
|
75
|
+
/** Every text passed to `speak()`, in order, with its language. */
|
|
76
|
+
readonly spoken: Array<{
|
|
77
|
+
text: string;
|
|
78
|
+
language: string;
|
|
79
|
+
}>;
|
|
80
|
+
/** Number of `cancel()` calls. */
|
|
81
|
+
cancelCount: number;
|
|
82
|
+
private readonly voices;
|
|
83
|
+
private readonly speakMs;
|
|
84
|
+
/**
|
|
85
|
+
* @param options.voices - Languages that have a voice. Omit to have voices for every language.
|
|
86
|
+
* @param options.speakMs - How long each `speak()` takes. Default 0.
|
|
87
|
+
*/
|
|
88
|
+
constructor(options?: {
|
|
89
|
+
supported?: boolean;
|
|
90
|
+
voices?: string[];
|
|
91
|
+
speakMs?: number;
|
|
92
|
+
});
|
|
93
|
+
hasVoiceFor(language: string): Promise<boolean>;
|
|
94
|
+
speak(text: string, options: SpeakOptions): Promise<void>;
|
|
95
|
+
cancel(): void;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** A web-standard request handler, such as the one returned by `createSpeeq()`. */
|
|
99
|
+
type FetchHandler = (request: Request) => Promise<Response>;
|
|
100
|
+
/** Options for {@link jsonRequest}. */
|
|
101
|
+
interface JsonRequestOptions {
|
|
102
|
+
method?: string;
|
|
103
|
+
body?: unknown;
|
|
104
|
+
token?: string;
|
|
105
|
+
headers?: Record<string, string>;
|
|
106
|
+
}
|
|
107
|
+
/** Builds a JSON `Request` for `http://localhost{path}`. */
|
|
108
|
+
declare function jsonRequest(path: string, options?: JsonRequestOptions): Request;
|
|
109
|
+
/**
|
|
110
|
+
* Reads an SSE `Response` to the end and returns every protocol event, validated against
|
|
111
|
+
* `ProtocolEventSchema` (an invalid event fails the test).
|
|
112
|
+
*/
|
|
113
|
+
declare function readSseEvents(response: Response): Promise<ProtocolEvent[]>;
|
|
114
|
+
/** Convenience: the concatenated `assistant.message` texts of a list of events. */
|
|
115
|
+
declare function assistantText(events: ProtocolEvent[]): string;
|
|
116
|
+
/** Session handle returned by {@link startSession}. */
|
|
117
|
+
interface TestSession {
|
|
118
|
+
sessionId: string;
|
|
119
|
+
token: string;
|
|
120
|
+
/** Sends a turn and returns all streamed events. */
|
|
121
|
+
turn(text: string, extra?: {
|
|
122
|
+
language?: string;
|
|
123
|
+
context?: unknown;
|
|
124
|
+
headers?: Record<string, string>;
|
|
125
|
+
}): Promise<ProtocolEvent[]>;
|
|
126
|
+
/** Answers a confirmation and returns all streamed events. */
|
|
127
|
+
confirm(confirmationId: string, approved: boolean, headers?: Record<string, string>): Promise<ProtocolEvent[]>;
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Starts a session against `handler` (mounted at `basePath`) and returns helpers to send turns.
|
|
131
|
+
* Throws if session creation fails.
|
|
132
|
+
*/
|
|
133
|
+
declare function startSession(handler: FetchHandler, options?: {
|
|
134
|
+
basePath?: string;
|
|
135
|
+
language?: string;
|
|
136
|
+
headers?: Record<string, string>;
|
|
137
|
+
}): Promise<TestSession>;
|
|
138
|
+
|
|
139
|
+
/** What a {@link MockRule} sees when deciding how to reply. */
|
|
140
|
+
interface MockRuleInput {
|
|
141
|
+
/** The latest user message text. */
|
|
142
|
+
text: string;
|
|
143
|
+
/** The same text, lower-cased and trimmed. */
|
|
144
|
+
normalized: string;
|
|
145
|
+
/** The full request (messages, tools). */
|
|
146
|
+
request: LLMRequest;
|
|
147
|
+
/** True if a tool with this name is offered in the request. */
|
|
148
|
+
hasTool(name: string): boolean;
|
|
149
|
+
}
|
|
150
|
+
/** One keyword rule: when `match` hits, reply with `respond`. */
|
|
151
|
+
interface MockRule {
|
|
152
|
+
/** A regex tested against the normalized text, or a predicate. */
|
|
153
|
+
match: RegExp | ((input: MockRuleInput) => boolean);
|
|
154
|
+
respond(input: MockRuleInput, match: RegExpMatchArray | null): FakeStep;
|
|
155
|
+
}
|
|
156
|
+
/** What {@link MockLLMOptions.afterTool} sees after a tool ran. */
|
|
157
|
+
interface MockAfterToolInput {
|
|
158
|
+
toolName: string;
|
|
159
|
+
/** The tool result text the model would see (JSON string or error message). */
|
|
160
|
+
result: string;
|
|
161
|
+
/** The user's original text in this turn. */
|
|
162
|
+
userText: string;
|
|
163
|
+
request: LLMRequest;
|
|
164
|
+
}
|
|
165
|
+
/** Options for {@link createMockLLMProvider}. */
|
|
166
|
+
interface MockLLMOptions {
|
|
167
|
+
rules: MockRule[];
|
|
168
|
+
/** Reply when no rule matches. */
|
|
169
|
+
fallback?: (input: MockRuleInput) => FakeStep;
|
|
170
|
+
/** Reply after tool results arrive. Defaults to a short generic summary. */
|
|
171
|
+
afterTool?: (input: MockAfterToolInput) => FakeStep;
|
|
172
|
+
/** Delay per streamed word, to feel like a real model. Default 0. */
|
|
173
|
+
delayMs?: number;
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* A keyword-based {@link LLMProvider} so apps can run with no API key ("mock mode"). It is
|
|
177
|
+
* deterministic: rules are checked in order against the latest user message. After tool results
|
|
178
|
+
* it calls `afterTool`. It is not a real model. Use it for demos, e2e tests and first-run setup.
|
|
179
|
+
*/
|
|
180
|
+
declare function createMockLLMProvider(options: MockLLMOptions): LLMProvider;
|
|
181
|
+
|
|
182
|
+
export { FakeLLMProvider, FakeSpeechInput, FakeSpeechOutput, assistantText, createMockLLMProvider, jsonRequest, playStep, readSseEvents, startSession };
|
|
183
|
+
export type { FakeScript, FakeStep, FetchHandler, JsonRequestOptions, MockAfterToolInput, MockLLMOptions, MockRule, MockRuleInput, TestSession };
|