@autumnsgrove/lyra 0.1.0 → 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.
Files changed (52) hide show
  1. package/dist/adapters/openai/errors.d.ts +36 -0
  2. package/dist/adapters/openai/errors.d.ts.map +1 -0
  3. package/dist/adapters/openai/errors.js +117 -0
  4. package/dist/adapters/openai/errors.js.map +1 -0
  5. package/dist/adapters/openai/index.d.ts +18 -0
  6. package/dist/adapters/openai/index.d.ts.map +1 -0
  7. package/dist/adapters/openai/index.js +18 -0
  8. package/dist/adapters/openai/index.js.map +1 -0
  9. package/dist/adapters/openai/model.d.ts +50 -0
  10. package/dist/adapters/openai/model.d.ts.map +1 -0
  11. package/dist/adapters/openai/model.js +169 -0
  12. package/dist/adapters/openai/model.js.map +1 -0
  13. package/dist/adapters/openai/presets.d.ts +36 -0
  14. package/dist/adapters/openai/presets.d.ts.map +1 -0
  15. package/dist/adapters/openai/presets.js +43 -0
  16. package/dist/adapters/openai/presets.js.map +1 -0
  17. package/dist/adapters/openai/request.d.ts +47 -0
  18. package/dist/adapters/openai/request.d.ts.map +1 -0
  19. package/dist/adapters/openai/request.js +93 -0
  20. package/dist/adapters/openai/request.js.map +1 -0
  21. package/dist/adapters/openai/sse.d.ts +44 -0
  22. package/dist/adapters/openai/sse.d.ts.map +1 -0
  23. package/dist/adapters/openai/sse.js +410 -0
  24. package/dist/adapters/openai/sse.js.map +1 -0
  25. package/dist/core/system-clock.d.ts.map +1 -1
  26. package/dist/core/system-clock.js +5 -1
  27. package/dist/core/system-clock.js.map +1 -1
  28. package/dist/testkit/cassette.d.ts +91 -0
  29. package/dist/testkit/cassette.d.ts.map +1 -0
  30. package/dist/testkit/cassette.js +250 -0
  31. package/dist/testkit/cassette.js.map +1 -0
  32. package/dist/testkit/fake-model-server.d.ts +87 -0
  33. package/dist/testkit/fake-model-server.d.ts.map +1 -0
  34. package/dist/testkit/fake-model-server.js +225 -0
  35. package/dist/testkit/fake-model-server.js.map +1 -0
  36. package/dist/testkit/index.d.ts +4 -1
  37. package/dist/testkit/index.d.ts.map +1 -1
  38. package/dist/testkit/index.js +4 -1
  39. package/dist/testkit/index.js.map +1 -1
  40. package/dist/testkit/misbehaving-model.d.ts +40 -0
  41. package/dist/testkit/misbehaving-model.d.ts.map +1 -0
  42. package/dist/testkit/misbehaving-model.js +134 -0
  43. package/dist/testkit/misbehaving-model.js.map +1 -0
  44. package/dist/testkit/model.d.ts +2 -0
  45. package/dist/testkit/model.d.ts.map +1 -1
  46. package/dist/testkit/model.js +3 -2
  47. package/dist/testkit/model.js.map +1 -1
  48. package/dist/testkit/scenario.d.ts +11 -1
  49. package/dist/testkit/scenario.d.ts.map +1 -1
  50. package/dist/testkit/scenario.js +4 -2
  51. package/dist/testkit/scenario.js.map +1 -1
  52. package/package.json +5 -1
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Cassettes: a real exchange, recorded once and replayed free (decision 65).
3
+ *
4
+ * A live run records what it sent and what came back, with auth headers and
5
+ * key-shaped strings removed at record time, so the file can be committed. CI
6
+ * replays it as a `fetch`, which means the same run is tested against a real
7
+ * provider's bytes with no network and no allowance spent.
8
+ *
9
+ * Everything here is web-standard: the recorder wraps a `fetch` and the replayer
10
+ * is one. Writing the file to disk is the live suite's job, because that needs
11
+ * `node:fs`, which nothing under `src/` may import.
12
+ */
13
+ import { type Result } from "../core/result.js";
14
+ /** What a live run sends, with anything secret already removed. */
15
+ export interface RecordedRequest {
16
+ url: string;
17
+ method: string;
18
+ headers: Record<string, string>;
19
+ body: string;
20
+ }
21
+ export interface RecordedResponse {
22
+ status: number;
23
+ headers: Record<string, string>;
24
+ body: string;
25
+ }
26
+ export interface RecordedExchange {
27
+ request: RecordedRequest;
28
+ response: RecordedResponse;
29
+ }
30
+ export interface Cassette {
31
+ /** Why this file exists, and whether it came from a real call or a fake one. */
32
+ note?: string;
33
+ exchanges: RecordedExchange[];
34
+ }
35
+ /** What `fetch` is called with, spelled here so this file needs no platform type. */
36
+ export interface CassetteFetchInit {
37
+ method?: string;
38
+ headers?: Record<string, string>;
39
+ body?: string;
40
+ signal?: AbortSignal;
41
+ }
42
+ export interface SecretHit {
43
+ /** What it looked like: `an sk- key`, a supplied key's name, or a pattern's name. */
44
+ what: string;
45
+ /** Where it was found, so a failure names the file and the field. */
46
+ where: string;
47
+ }
48
+ /**
49
+ * Every key-shaped string in a text, with the exact values a caller names. The
50
+ * check is deliberately blunt: a false positive costs a re-record, and a false
51
+ * negative puts a key in a public repository.
52
+ */
53
+ export declare function scanForSecrets(text: string, options?: {
54
+ keys?: readonly {
55
+ name: string;
56
+ value: string;
57
+ }[];
58
+ }): SecretHit[];
59
+ /** A recorded exchange with its credentials taken out, ready to be committed. */
60
+ export declare function scrubExchange(exchange: RecordedExchange): RecordedExchange;
61
+ /** A cassette from a parsed JSON file, refused with the field that is wrong. */
62
+ export declare function decodeCassette(value: unknown): Result<Cassette>;
63
+ export declare function encodeCassette(cassette: Cassette): string;
64
+ export interface CassetteReplay {
65
+ (url: string, init?: CassetteFetchInit): Promise<Response>;
66
+ /** Exchanges nothing has asked for yet, which a test can assert is none. */
67
+ unused(): RecordedExchange[];
68
+ }
69
+ /**
70
+ * A cassette as a `fetch`. A request is matched to the first unused exchange with
71
+ * the same method, URL and body, so a retried turn replays its own recording. A
72
+ * request with no exchange is a loud failure rather than a quiet call to the
73
+ * network, because a test that silently reached a provider would pass for the
74
+ * wrong reason and cost money.
75
+ */
76
+ export declare function replayCassette(cassette: Cassette): CassetteReplay;
77
+ export interface RecordingFetch {
78
+ (url: string, init?: CassetteFetchInit): Promise<Response>;
79
+ /** Every exchange so far, already scrubbed. */
80
+ exchanges: RecordedExchange[];
81
+ cassette(): Cassette;
82
+ }
83
+ /**
84
+ * A `fetch` that records what it was asked and what came back, scrubbed as it
85
+ * goes: auth headers are dropped and the body's text is kept as it is, because a
86
+ * cassette is worth nothing if it cannot be read.
87
+ */
88
+ export declare function recordingFetch(inner: (url: string, init?: CassetteFetchInit) => Promise<Response>, options?: {
89
+ note?: string;
90
+ }): RecordingFetch;
91
+ //# sourceMappingURL=cassette.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cassette.d.ts","sourceRoot":"","sources":["../../src/testkit/cassette.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAGH,OAAO,EAAY,KAAK,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAE1D,mEAAmE;AACnE,MAAM,WAAW,eAAe;IAC/B,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAChC,IAAI,EAAE,MAAM,CAAC;CACb;AAED,MAAM,WAAW,gBAAgB;IAChC,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAChC,IAAI,EAAE,MAAM,CAAC;CACb;AAED,MAAM,WAAW,gBAAgB;IAChC,OAAO,EAAE,eAAe,CAAC;IACzB,QAAQ,EAAE,gBAAgB,CAAC;CAC3B;AAED,MAAM,WAAW,QAAQ;IACxB,gFAAgF;IAChF,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,gBAAgB,EAAE,CAAC;CAC9B;AAED,qFAAqF;AACrF,MAAM,WAAW,iBAAiB;IACjC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,MAAM,CAAC,EAAE,WAAW,CAAC;CACrB;AAqBD,MAAM,WAAW,SAAS;IACzB,qFAAqF;IACrF,IAAI,EAAE,MAAM,CAAC;IACb,qEAAqE;IACrE,KAAK,EAAE,MAAM,CAAC;CACd;AAED;;;;GAIG;AACH,wBAAgB,cAAc,CAC7B,IAAI,EAAE,MAAM,EACZ,OAAO,GAAE;IAAE,IAAI,CAAC,EAAE,SAAS;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,EAAE,CAAA;CAAO,GACjE,SAAS,EAAE,CAab;AAED,iFAAiF;AACjF,wBAAgB,aAAa,CAAC,QAAQ,EAAE,gBAAgB,GAAG,gBAAgB,CAqB1E;AA2BD,gFAAgF;AAChF,wBAAgB,cAAc,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAAC,QAAQ,CAAC,CAsE/D;AAED,wBAAgB,cAAc,CAAC,QAAQ,EAAE,QAAQ,GAAG,MAAM,CAOzD;AAcD,MAAM,WAAW,cAAc;IAC9B,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,iBAAiB,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;IAC3D,4EAA4E;IAC5E,MAAM,IAAI,gBAAgB,EAAE,CAAC;CAC7B;AAED;;;;;;GAMG;AACH,wBAAgB,cAAc,CAAC,QAAQ,EAAE,QAAQ,GAAG,cAAc,CA4BjE;AAED,MAAM,WAAW,cAAc;IAC9B,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,iBAAiB,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;IAC3D,+CAA+C;IAC/C,SAAS,EAAE,gBAAgB,EAAE,CAAC;IAC9B,QAAQ,IAAI,QAAQ,CAAC;CACrB;AAED;;;;GAIG;AACH,wBAAgB,cAAc,CAC7B,KAAK,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,iBAAiB,KAAK,OAAO,CAAC,QAAQ,CAAC,EACnE,OAAO,GAAE;IAAE,IAAI,CAAC,EAAE,MAAM,CAAA;CAAO,GAC7B,cAAc,CAgChB"}
@@ -0,0 +1,250 @@
1
+ /**
2
+ * Cassettes: a real exchange, recorded once and replayed free (decision 65).
3
+ *
4
+ * A live run records what it sent and what came back, with auth headers and
5
+ * key-shaped strings removed at record time, so the file can be committed. CI
6
+ * replays it as a `fetch`, which means the same run is tested against a real
7
+ * provider's bytes with no network and no allowance spent.
8
+ *
9
+ * Everything here is web-standard: the recorder wraps a `fetch` and the replayer
10
+ * is one. Writing the file to disk is the live suite's job, because that needs
11
+ * `node:fs`, which nothing under `src/` may import.
12
+ */
13
+ import { isPlainObject } from "../core/json.js";
14
+ import { fail, ok } from "../core/result.js";
15
+ /** Headers that carry a credential, whatever the provider calls them. */
16
+ const SECRET_HEADERS = new Set([
17
+ "authorization",
18
+ "x-api-key",
19
+ "api-key",
20
+ "x-auth-token",
21
+ "cookie",
22
+ "set-cookie",
23
+ ]);
24
+ /** What a key or a token looks like in a body: long, random and distinctive. */
25
+ const SECRET_PATTERNS = [
26
+ { name: "an sk- key", pattern: /\bsk-[A-Za-z0-9_-]{12,}/ },
27
+ { name: "a bearer token", pattern: /\bBearer\s+[A-Za-z0-9._~+/=-]{16,}/ },
28
+ { name: "a long base64 run", pattern: /[A-Za-z0-9+/]{60,}={0,2}/ },
29
+ { name: "a long hex run", pattern: /\b[0-9a-f]{48,}\b/ },
30
+ { name: "an OpenRouter or OpenCode key shape", pattern: /\b(?:or|oc)-v1-[A-Za-z0-9-]{12,}/ },
31
+ ];
32
+ /**
33
+ * Every key-shaped string in a text, with the exact values a caller names. The
34
+ * check is deliberately blunt: a false positive costs a re-record, and a false
35
+ * negative puts a key in a public repository.
36
+ */
37
+ export function scanForSecrets(text, options = {}) {
38
+ const hits = [];
39
+ for (const { name, pattern } of SECRET_PATTERNS) {
40
+ if (pattern.test(text)) {
41
+ hits.push({ what: name, where: "the text" });
42
+ }
43
+ }
44
+ for (const key of options.keys ?? []) {
45
+ if (key.value !== "" && text.includes(key.value)) {
46
+ hits.push({ what: `the value of ${key.name}`, where: "the text" });
47
+ }
48
+ }
49
+ return hits;
50
+ }
51
+ /** A recorded exchange with its credentials taken out, ready to be committed. */
52
+ export function scrubExchange(exchange) {
53
+ const headers = {};
54
+ for (const [name, value] of Object.entries(exchange.request.headers)) {
55
+ if (SECRET_HEADERS.has(name.toLowerCase())) {
56
+ continue;
57
+ }
58
+ headers[name.toLowerCase()] = value;
59
+ }
60
+ const responseHeaders = {};
61
+ for (const [name, value] of Object.entries(exchange.response.headers)) {
62
+ // A response can carry a credential too: `set-cookie` is how a provider hands
63
+ // one back, and a cookie value need not look like a key to the scan.
64
+ if (SECRET_HEADERS.has(name.toLowerCase())) {
65
+ continue;
66
+ }
67
+ responseHeaders[name.toLowerCase()] = value;
68
+ }
69
+ return {
70
+ request: { ...exchange.request, headers },
71
+ response: { ...exchange.response, headers: responseHeaders },
72
+ };
73
+ }
74
+ function stringRecord(value, where) {
75
+ if (value === undefined) {
76
+ return ok({});
77
+ }
78
+ if (!isPlainObject(value)) {
79
+ return fail("bad_request", `${where} must be an object of strings`);
80
+ }
81
+ const record = {};
82
+ for (const [key, entry] of Object.entries(value)) {
83
+ if (typeof entry !== "string") {
84
+ return fail("bad_request", `${where}.${key} must be a string`);
85
+ }
86
+ record[key] = entry;
87
+ }
88
+ return ok(record);
89
+ }
90
+ function textOf(value, key, where) {
91
+ const field = value[key];
92
+ if (typeof field !== "string") {
93
+ return fail("bad_request", `${where}.${key} must be a string`);
94
+ }
95
+ return ok(field);
96
+ }
97
+ /** A cassette from a parsed JSON file, refused with the field that is wrong. */
98
+ export function decodeCassette(value) {
99
+ if (!isPlainObject(value)) {
100
+ return fail("bad_request", "a cassette must be an object");
101
+ }
102
+ const exchanges = value["exchanges"];
103
+ if (!Array.isArray(exchanges)) {
104
+ return fail("bad_request", "a cassette must have an exchanges list");
105
+ }
106
+ const decoded = [];
107
+ for (const [index, raw] of exchanges.entries()) {
108
+ const where = `exchanges[${index}]`;
109
+ if (!isPlainObject(raw)) {
110
+ return fail("bad_request", `${where} must be an object`);
111
+ }
112
+ const rawRequest = raw["request"];
113
+ const rawResponse = raw["response"];
114
+ if (!isPlainObject(rawRequest)) {
115
+ return fail("bad_request", `${where}.request must be an object`);
116
+ }
117
+ if (!isPlainObject(rawResponse)) {
118
+ return fail("bad_request", `${where}.response must be an object`);
119
+ }
120
+ const url = textOf(rawRequest, "url", `${where}.request`);
121
+ if (!url.ok) {
122
+ return url;
123
+ }
124
+ const method = textOf(rawRequest, "method", `${where}.request`);
125
+ if (!method.ok) {
126
+ return method;
127
+ }
128
+ const body = textOf(rawRequest, "body", `${where}.request`);
129
+ if (!body.ok) {
130
+ return body;
131
+ }
132
+ const headers = stringRecord(rawRequest["headers"], `${where}.request.headers`);
133
+ if (!headers.ok) {
134
+ return headers;
135
+ }
136
+ const responseBody = textOf(rawResponse, "body", `${where}.response`);
137
+ if (!responseBody.ok) {
138
+ return responseBody;
139
+ }
140
+ const responseHeaders = stringRecord(rawResponse["headers"], `${where}.response.headers`);
141
+ if (!responseHeaders.ok) {
142
+ return responseHeaders;
143
+ }
144
+ const status = rawResponse["status"];
145
+ if (typeof status !== "number" || !Number.isSafeInteger(status)) {
146
+ return fail("bad_request", `${where}.response.status must be a whole number`);
147
+ }
148
+ decoded.push({
149
+ request: {
150
+ url: url.value,
151
+ method: method.value,
152
+ headers: headers.value,
153
+ body: body.value,
154
+ },
155
+ response: {
156
+ status,
157
+ headers: responseHeaders.value,
158
+ body: responseBody.value,
159
+ },
160
+ });
161
+ }
162
+ const cassette = { exchanges: decoded };
163
+ const note = value["_note"];
164
+ if (typeof note === "string") {
165
+ cassette.note = note;
166
+ }
167
+ return ok(cassette);
168
+ }
169
+ export function encodeCassette(cassette) {
170
+ // The note goes first in the file, because it is what a reader needs first.
171
+ const value = cassette.note === undefined
172
+ ? { exchanges: cassette.exchanges }
173
+ : { _note: cassette.note, exchanges: cassette.exchanges };
174
+ return `${JSON.stringify(value, null, "\t")}\n`;
175
+ }
176
+ /** Two JSON bodies are the same request when they parse to the same value. */
177
+ function sameBody(left, right) {
178
+ if (left === right) {
179
+ return true;
180
+ }
181
+ try {
182
+ return JSON.stringify(JSON.parse(left)) === JSON.stringify(JSON.parse(right));
183
+ }
184
+ catch {
185
+ return false;
186
+ }
187
+ }
188
+ /**
189
+ * A cassette as a `fetch`. A request is matched to the first unused exchange with
190
+ * the same method, URL and body, so a retried turn replays its own recording. A
191
+ * request with no exchange is a loud failure rather than a quiet call to the
192
+ * network, because a test that silently reached a provider would pass for the
193
+ * wrong reason and cost money.
194
+ */
195
+ export function replayCassette(cassette) {
196
+ const exchanges = cassette.exchanges.map((exchange) => ({ exchange, used: false }));
197
+ const replay = async (url, init) => {
198
+ const method = init?.method ?? "GET";
199
+ const body = init?.body ?? "";
200
+ const match = exchanges.find((candidate) => !candidate.used &&
201
+ candidate.exchange.request.url === url &&
202
+ candidate.exchange.request.method.toUpperCase() === method.toUpperCase() &&
203
+ sameBody(candidate.exchange.request.body, body));
204
+ if (match === undefined) {
205
+ throw new Error(`the cassette has no exchange for ${method.toUpperCase()} ${url}: record it again with pnpm test:live, or fix the request the test sends`);
206
+ }
207
+ match.used = true;
208
+ return new Response(match.exchange.response.body, {
209
+ status: match.exchange.response.status,
210
+ headers: match.exchange.response.headers,
211
+ });
212
+ };
213
+ return Object.assign(replay, {
214
+ unused: () => exchanges.filter((candidate) => !candidate.used).map((c) => c.exchange),
215
+ });
216
+ }
217
+ /**
218
+ * A `fetch` that records what it was asked and what came back, scrubbed as it
219
+ * goes: auth headers are dropped and the body's text is kept as it is, because a
220
+ * cassette is worth nothing if it cannot be read.
221
+ */
222
+ export function recordingFetch(inner, options = {}) {
223
+ const exchanges = [];
224
+ const record = async (url, init) => {
225
+ const response = await inner(url, init);
226
+ // The body is read here and handed on, because a response can be read once.
227
+ const body = await response.text();
228
+ exchanges.push(scrubExchange({
229
+ request: {
230
+ url,
231
+ method: init?.method ?? "GET",
232
+ headers: { ...init?.headers },
233
+ body: init?.body ?? "",
234
+ },
235
+ response: {
236
+ status: response.status,
237
+ headers: Object.fromEntries([...response.headers]),
238
+ body,
239
+ },
240
+ }));
241
+ return new Response(body, { status: response.status, headers: response.headers });
242
+ };
243
+ return Object.assign(record, {
244
+ exchanges,
245
+ cassette: () => options.note === undefined
246
+ ? { exchanges: [...exchanges] }
247
+ : { note: options.note, exchanges: [...exchanges] },
248
+ });
249
+ }
250
+ //# sourceMappingURL=cassette.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cassette.js","sourceRoot":"","sources":["../../src/testkit/cassette.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,EAAE,IAAI,EAAE,EAAE,EAAe,MAAM,mBAAmB,CAAC;AAmC1D,yEAAyE;AACzE,MAAM,cAAc,GAAG,IAAI,GAAG,CAAC;IAC9B,eAAe;IACf,WAAW;IACX,SAAS;IACT,cAAc;IACd,QAAQ;IACR,YAAY;CACZ,CAAC,CAAC;AAEH,gFAAgF;AAChF,MAAM,eAAe,GAAiD;IACrE,EAAE,IAAI,EAAE,YAAY,EAAE,OAAO,EAAE,yBAAyB,EAAE;IAC1D,EAAE,IAAI,EAAE,gBAAgB,EAAE,OAAO,EAAE,oCAAoC,EAAE;IACzE,EAAE,IAAI,EAAE,mBAAmB,EAAE,OAAO,EAAE,0BAA0B,EAAE;IAClE,EAAE,IAAI,EAAE,gBAAgB,EAAE,OAAO,EAAE,mBAAmB,EAAE;IACxD,EAAE,IAAI,EAAE,qCAAqC,EAAE,OAAO,EAAE,kCAAkC,EAAE;CAC5F,CAAC;AASF;;;;GAIG;AACH,MAAM,UAAU,cAAc,CAC7B,IAAY,EACZ,OAAO,GAA0D,EAAE;IAEnE,MAAM,IAAI,GAAgB,EAAE,CAAC;IAC7B,KAAK,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,eAAe,EAAE,CAAC;QACjD,IAAI,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;YACxB,IAAI,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,UAAU,EAAE,CAAC,CAAC;QAC9C,CAAC;IACF,CA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AS,EAAE,CAAC,GAAG,SAAS,CAAC,EAAE;KACrD,CAAC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,87 @@
1
+ /**
2
+ * The fake model server (docs/engineering-practices.md, KIT09 to KIT11).
3
+ *
4
+ * It is `fetch`, not a socket. The adapter takes an injectable `fetch`, so a
5
+ * server that is a function proves everything a real one would except a genuine
6
+ * TCP failure, and those are simulated the way the platform produces them: a
7
+ * `fetch` that rejects, and a body that errors while it is being read. A socket
8
+ * would need `node:net`, which `importcheck` refuses everywhere under `src/`,
9
+ * and it would test the runtime's networking rather than Lyra.
10
+ *
11
+ * The scripts are the same `ScriptedTurn`s the in-process scripted model reads,
12
+ * so one scenario can run either way. What differs is the wire: here a turn
13
+ * becomes real server-sent-event bytes, with the text split across chunks and
14
+ * each tool call's name in one and its arguments in the next, which is what a
15
+ * provider actually sends.
16
+ */
17
+ import { type ScriptedTurn } from "./model.js";
18
+ /** One request the server saw, kept so a test can assert what the adapter sent. */
19
+ export interface FakeModelRequest {
20
+ url: string;
21
+ method: string;
22
+ headers: Record<string, string>;
23
+ /** The parsed JSON body, or the raw text when it was not JSON. */
24
+ body: unknown;
25
+ }
26
+ /**
27
+ * How the server misbehaves on one request (the failure-mode catalog's list). A
28
+ * request with no fault at its position answers the script.
29
+ */
30
+ export type FakeModelFault = {
31
+ kind: "status";
32
+ status: number;
33
+ retryAfter?: string;
34
+ body?: string;
35
+ } | {
36
+ kind: "cut";
37
+ } | {
38
+ kind: "malformed";
39
+ } | {
40
+ kind: "stall";
41
+ } | {
42
+ kind: "error-body";
43
+ message?: string;
44
+ } | {
45
+ kind: "non-json";
46
+ } | {
47
+ kind: "mid-stream-error";
48
+ status?: number;
49
+ message?: string;
50
+ } | {
51
+ kind: "body-error";
52
+ message?: string;
53
+ } | {
54
+ kind: "huge";
55
+ bytes?: number;
56
+ }
57
+ /** A test that needs a stream the named faults cannot make. */
58
+ | {
59
+ kind: "custom";
60
+ answer(): Response | Promise<Response>;
61
+ };
62
+ export interface FakeModelServerOptions {
63
+ /** The name a reply reports. Defaults to `scripted/model`. */
64
+ model?: string;
65
+ /** One fault per request, by the request's position; a hole answers the script. */
66
+ faults?: (FakeModelFault | undefined)[];
67
+ }
68
+ /**
69
+ * What `fetch` is called with, spelled out here rather than named from
70
+ * `platform.d.ts`: the testkit is imported by the workerd program too, which
71
+ * gets its globals from the Workers types instead.
72
+ */
73
+ export interface FakeFetchInit {
74
+ method?: string;
75
+ headers?: Record<string, string>;
76
+ body?: string;
77
+ signal?: AbortSignal;
78
+ }
79
+ export interface FakeModelServer {
80
+ (options: string, init?: FakeFetchInit): Promise<Response>;
81
+ /** Every request received, in order. */
82
+ requests: FakeModelRequest[];
83
+ }
84
+ /** A scripted turn as the bytes a provider would send for it. */
85
+ export declare function sseFor(turn: ScriptedTurn, model: string): string;
86
+ export declare function fakeModelServer(turns: readonly ScriptedTurn[], options?: FakeModelServerOptions): FakeModelServer;
87
+ //# sourceMappingURL=fake-model-server.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fake-model-server.d.ts","sourceRoot":"","sources":["../../src/testkit/fake-model-server.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAGH,OAAO,EAAqB,KAAK,YAAY,EAAE,MAAM,YAAY,CAAC;AAElE,mFAAmF;AACnF,MAAM,WAAW,gBAAgB;IAChC,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAChC,kEAAkE;IAClE,IAAI,EAAE,OAAO,CAAC;CACd;AAED;;;GAGG;AACH,MAAM,MAAM,cAAc,GACvB;IAAE,IAAI,EAAE,QAAQ,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,UAAU,CAAC,EAAE,MAAM,CAAC;IAAC,IAAI,CAAC,EAAE,MAAM,CAAA;CAAE,GACtE;IAAE,IAAI,EAAE,KAAK,CAAA;CAAE,GACf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E,KAAK,EAAE,MAAM,GAAG,MAAM,CA8ChE;AA8ID,wBAAgB,eAAe,CAC9B,KAAK,EAAE,SAAS,YAAY,EAAE,EAC9B,OAAO,GAAE,sBAA2B,GAClC,eAAe,CAqCjB"}
@@ -0,0 +1,225 @@
1
+ /**
2
+ * The fake model server (docs/engineering-practices.md, KIT09 to KIT11).
3
+ *
4
+ * It is `fetch`, not a socket. The adapter takes an injectable `fetch`, so a
5
+ * server that is a function proves everything a real one would except a genuine
6
+ * TCP failure, and those are simulated the way the platform produces them: a
7
+ * `fetch` that rejects, and a body that errors while it is being read. A socket
8
+ * would need `node:net`, which `importcheck` refuses everywhere under `src/`,
9
+ * and it would test the runtime's networking rather than Lyra.
10
+ *
11
+ * The scripts are the same `ScriptedTurn`s the in-process scripted model reads,
12
+ * so one scenario can run either way. What differs is the wire: here a turn
13
+ * becomes real server-sent-event bytes, with the text split across chunks and
14
+ * each tool call's name in one and its arguments in the next, which is what a
15
+ * provider actually sends.
16
+ */
17
+ import { isPlainObject } from "../core/json.js";
18
+ import { scriptedArguments } from "./model.js";
19
+ function abortError() {
20
+ const error = new Error("the request was aborted");
21
+ error.name = "AbortError";
22
+ return error;
23
+ }
24
+ function payload(chunk) {
25
+ return `data: ${JSON.stringify(chunk)}\n\n`;
26
+ }
27
+ function chunkOf(model, delta) {
28
+ return payload({
29
+ id: "gen-fake",
30
+ object: "chat.completion.chunk",
31
+ created: 0,
32
+ model,
33
+ choices: [{ index: 0, delta, finish_reason: null }],
34
+ });
35
+ }
36
+ /** A scripted turn as the bytes a provider would send for it. */
37
+ export function sseFor(turn, model) {
38
+ const pieces = [];
39
+ if (turn.reasoning !== undefined && turn.reasoning !== "") {
40
+ pieces.push(chunkOf(model, { role: "assistant", reasoning: turn.reasoning }));
41
+ }
42
+ const text = turn.text ?? "";
43
+ if (text !== "") {
44
+ // Half now and half in the next chunk, because that is how text arrives.
45
+ const half = Math.floor(text.length / 2);
46
+ pieces.push(chunkOf(model, { content: text.slice(0, half) }));
47
+ pieces.push(chunkOf(model, { content: text.slice(half) }));
48
+ }
49
+ const calls = turn.toolCalls ?? [];
50
+ for (const [index, call] of calls.entries()) {
51
+ pieces.push(chunkOf(model, {
52
+ tool_calls: [
53
+ { index, id: call.id, type: "function", function: { name: call.name } },
54
+ ],
55
+ }));
56
+ pieces.push(chunkOf(model, {
57
+ tool_calls: [{ index, function: { arguments: scriptedArguments(call.args) } }],
58
+ }));
59
+ }
60
+ const finish = turn.finishReason ?? (calls.length > 0 ? "tool_calls" : "stop");
61
+ pieces.push(payload({
62
+ id: "gen-fake",
63
+ model,
64
+ choices: [{ index: 0, delta: {}, finish_reason: finish }],
65
+ }));
66
+ const usage = turn.usage ?? { inputTokens: 0, outputTokens: 0 };
67
+ const reported = {
68
+ prompt_tokens: usage.inputTokens,
69
+ completion_tokens: usage.outputTokens,
70
+ };
71
+ if (usage.cost !== undefined) {
72
+ reported["cost"] = usage.cost.amount;
73
+ }
74
+ pieces.push(payload({ id: "gen-fake", model, choices: [], usage: reported }));
75
+ pieces.push("data: [DONE]\n\n");
76
+ return pieces.join("");
77
+ }
78
+ function streamOf(pieces) {
79
+ const encoder = new TextEncoder();
80
+ return new ReadableStream({
81
+ start(controller) {
82
+ for (const piece of pieces) {
83
+ controller.enqueue(encoder.encode(piece));
84
+ }
85
+ controller.close();
86
+ },
87
+ });
88
+ }
89
+ function streamed(text) {
90
+ return new Response(streamOf([text]), {
91
+ status: 200,
92
+ headers: { "content-type": "text/event-stream" },
93
+ });
94
+ }
95
+ /** A stream that fails while it is being read, which a dropped connection does. */
96
+ function broken(message) {
97
+ const encoder = new TextEncoder();
98
+ return new Response(new ReadableStream({
99
+ start(controller) {
100
+ controller.enqueue(encoder.encode(chunkOf("scripted/model", { content: "part" })));
101
+ controller.error(new Error(message));
102
+ },
103
+ }), { status: 200, headers: { "content-type": "text/event-stream" } });
104
+ }
105
+ function json(body, status, headers = {}) {
106
+ return new Response(JSON.stringify(body), {
107
+ status,
108
+ headers: { "content-type": "application/json", ...headers },
109
+ });
110
+ }
111
+ /** A request that is never answered, which is what the adapter's deadline is for. */
112
+ function stall(signal) {
113
+ return new Promise((_, reject) => {
114
+ if (signal === undefined) {
115
+ return;
116
+ }
117
+ const stop = () => reject(abortError());
118
+ if (signal.aborted) {
119
+ stop();
120
+ return;
121
+ }
122
+ signal.addEventListener("abort", stop, { once: true });
123
+ });
124
+ }
125
+ function answer(fault, signal) {
126
+ switch (fault.kind) {
127
+ case "status": {
128
+ const headers = {};
129
+ if (fault.retryAfter !== undefined) {
130
+ headers["retry-after"] = fault.retryAfter;
131
+ }
132
+ if (typeof fault.body === "string") {
133
+ // A body that is not JSON is what a proxy in front of a provider sends.
134
+ return new Response(fault.body, { status: fault.status, headers });
135
+ }
136
+ return json(fault.body ?? { error: { message: `the fake server answered ${fault.status}` } }, fault.status, headers);
137
+ }
138
+ case "cut":
139
+ return streamed('data: {"choices":[{"index":0,"delta":{"content":"half a rep');
140
+ case "malformed":
141
+ return streamed("data: {not json at all\n\n");
142
+ case "stall":
143
+ return stall(signal);
144
+ case "error-body":
145
+ return json({ error: { message: fault.message ?? "the model could not be reached" } }, 200);
146
+ case "non-json":
147
+ return new Response("<html>bad gateway</html>", {
148
+ status: 500,
149
+ headers: { "content-type": "text/html" },
150
+ });
151
+ case "mid-stream-error":
152
+ return streamed(chunkOf("scripted/model", { content: "part" }) +
153
+ payload({
154
+ id: "gen-fake",
155
+ model: "scripted/model",
156
+ error: {
157
+ code: fault.status ?? 429,
158
+ message: fault.message ?? "the provider gave up",
159
+ },
160
+ choices: [{ index: 0, delta: { content: "" }, finish_reason: "error" }],
161
+ }));
162
+ case "body-error":
163
+ return broken(fault.message ?? "the connection was reset");
164
+ case "huge":
165
+ return streamed(chunkOf("scripted/model", { content: "x".repeat(fault.bytes ?? 1_200_000) }) +
166
+ chunkOf("scripted/model", { content: "end" }) +
167
+ "data: [DONE]\n\n");
168
+ case "custom":
169
+ return fault.answer();
170
+ }
171
+ }
172
+ function assistantMessages(body) {
173
+ if (!isPlainObject(body)) {
174
+ return 0;
175
+ }
176
+ const messages = body["messages"];
177
+ if (!Array.isArray(messages)) {
178
+ return 0;
179
+ }
180
+ return messages.filter((message) => isPlainObject(message) && message["role"] === "assistant")
181
+ .length;
182
+ }
183
+ function parseBody(body) {
184
+ if (body === undefined) {
185
+ return undefined;
186
+ }
187
+ try {
188
+ return JSON.parse(body);
189
+ }
190
+ catch {
191
+ return body;
192
+ }
193
+ }
194
+ export function fakeModelServer(turns, options = {}) {
195
+ const model = options.model ?? "scripted/model";
196
+ const faults = [...(options.faults ?? [])];
197
+ const requests = [];
198
+ const serve = async (url, init) => {
199
+ const position = requests.length;
200
+ const body = parseBody(init?.body);
201
+ requests.push({
202
+ url,
203
+ method: init?.method ?? "GET",
204
+ headers: { ...init?.headers },
205
+ body,
206
+ });
207
+ const fault = faults[position];
208
+ if (fault !== undefined) {
209
+ return answer(fault, init?.signal);
210
+ }
211
+ // The reply comes from the turn whose position matches the assistant messages
212
+ // already in the request, exactly as the in-process scripted model does.
213
+ const turn = turns[assistantMessages(body)];
214
+ if (turn === undefined) {
215
+ return json({
216
+ error: {
217
+ message: `the fake server has no turn ${assistantMessages(body) + 1}`,
218
+ },
219
+ }, 500);
220
+ }
221
+ return streamed(sseFor(turn, model));
222
+ };
223
+ return Object.assign(serve, { requests });
224
+ }
225
+ //# sourceMappingURL=fake-model-server.js.map