@wenathlan/getry 2.0.154 → 2.0.155

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.
@@ -0,0 +1,962 @@
1
+ import { access, readdir, readFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { describe, expect, it } from "vitest";
4
+ import type { fetchtransport, transportresponse } from "@wenathlan/devthink/http";
5
+ import { providerfixtures } from "./providerfixtures.ts";
6
+ import {
7
+ adapterof,
8
+ anthropicgatewayadapter,
9
+ capabilityadvertisement,
10
+ composegatewayprompt,
11
+ costestimates,
12
+ defaultbaseurl,
13
+ fetchmodellist,
14
+ gatewayadapters,
15
+ gatewaybudgetcheck,
16
+ gatewaybudgetwarning,
17
+ gatewaycall,
18
+ gatewaycancel,
19
+ gatewaychatstateof,
20
+ gatewayerrorfrom,
21
+ gatewayerrorof,
22
+ gatewayguard,
23
+ gatewayislocal,
24
+ gatewayplanguard,
25
+ gatewaystream,
26
+ gatewaytemplates,
27
+ gatewayurl,
28
+ gatewayusagerecord,
29
+ geminigatewayadapter,
30
+ keyexportcheck,
31
+ maskkey,
32
+ maskrequest,
33
+ ollamalocaladapter,
34
+ openaicompatadapter,
35
+ resolvegatewayroute,
36
+ revokeproviderkey,
37
+ storeproviderkey,
38
+ streamrender,
39
+ usagetotals,
40
+ validategatewayconfig,
41
+ } from "../llm.js";
42
+ import { gatewaybaseurlgate, gatewayconsentgate, gatewaykeyconsentgate, gatewayretrycapvalid } from "@wenathlan/devthink/policy";
43
+ import { gatewaycallreport } from "@wenathlan/devthink/protocol";
44
+ import { inmemoryvault } from "@wenathlan/devthink/security";
45
+ import { buildtoolcatalog } from "@wenathlan/devthink/tools";
46
+ import type {
47
+ baseurlconfig,
48
+ gatewaychattoken,
49
+ localmodelconfig,
50
+ modelroute,
51
+ providerconfig,
52
+ } from "../types.js";
53
+ /* the mcp tooldef kind stays an os-owned devthink type imported through the
54
+ * published specifier — never copied into the gateway. */
55
+ import type { tooldef } from "@wenathlan/devthink/types";
56
+ import { startgatewayfixtureserver } from "./gatewayserver.ts";
57
+
58
+ const now = 1_800_000_000_000;
59
+ const instant = (): Promise<void> => Promise.resolve();
60
+
61
+ /** Builds one enabled and consented gateway config with every value user configured. */
62
+ function config(over: Partial<baseurlconfig> = {}): baseurlconfig {
63
+ return {
64
+ providerid: "prov1",
65
+ kind: "openaicompat",
66
+ baseurl: "https://gateway.example/v1",
67
+ enabled: true,
68
+ consented: true,
69
+ consentedat: now,
70
+ updatedat: now,
71
+ ...over,
72
+ };
73
+ }
74
+
75
+ /** Builds one stub transport that answers every request with the canned body and records what it saw. */
76
+ function stub(body: string, status = 200, seen: string[] = [], headers: Record<string, string> = {}): fetchtransport {
77
+ return async (url, init): Promise<transportresponse> => {
78
+ seen.push(
79
+ `${init.method} ${url} ${init.headers.authorization ?? init.headers["x-api-key"] ?? ""} ${init.body ?? ""}`,
80
+ );
81
+ return { status, headers: { "content-type": "application/json", ...headers }, body };
82
+ };
83
+ }
84
+
85
+ /** Reads one recorded fixture body of the gateway family by its original fixture file name from the provider wire fixture module. */
86
+ async function fixture(name: string): Promise<string> {
87
+ const text = (providerfixtures as Record<string, string>)[name];
88
+ if (text === undefined) throw new Error(`the provider wire fixture ${name} sits absent from the fixture module`);
89
+ return text;
90
+ }
91
+
92
+ /** The first tools of the real catalog for the capabilityad and request composition cases. */
93
+ function catalogtools(): tooldef[] {
94
+ return (buildtoolcatalog().domains[0]?.tools ?? []).slice(0, 2);
95
+ }
96
+
97
+ describe("gateway adapter request composition against the recorded fixtures", () => {
98
+ it("shapes every adapter request with its wire path, key placement and message envelope and parses its recorded answer", async () => {
99
+ const messages = [
100
+ { role: "system" as const, content: "be brief" },
101
+ { role: "user" as const, content: "draft one step" },
102
+ ];
103
+ const openai = openaicompatadapter.build({
104
+ config: config(),
105
+ model: "fixture-model-a",
106
+ messages,
107
+ apikey: "secret",
108
+ maxtokens: 64,
109
+ });
110
+ expect(openai.url).toBe("https://gateway.example/v1/chat/completions");
111
+ expect(openai.headers.authorization).toBe("Bearer secret");
112
+ const openaibody = JSON.parse(openai.body) as Record<string, unknown>;
113
+ expect(openaibody.model).toBe("fixture-model-a");
114
+ expect(openaibody["max_tokens"]).toBe(64);
115
+ expect(openaibody.messages).toEqual(messages);
116
+ const openaianswer = openaicompatadapter.parseanswer(await fixture("openaicompat-completion.json"));
117
+ expect(openaianswer.text).toContain("open the docs page");
118
+ expect(openaianswer.usage).toEqual({ prompttokens: 34, completiontokens: 21, totaltokens: 55 });
119
+
120
+ const anthropic = anthropicgatewayadapter.build({
121
+ config: config({ kind: "anthropicgateway", baseurl: "https://gateway.example" }),
122
+ model: "fixture-claude-shape",
123
+ messages,
124
+ apikey: "secret",
125
+ });
126
+ expect(anthropic.url).toBe("https://gateway.example/v1/messages");
127
+ expect(anthropic.headers["x-api-key"]).toBe("secret");
128
+ const anthropicbody = JSON.parse(anthropic.body) as Record<string, unknown>;
129
+ expect(anthropicbody.system).toBe("be brief");
130
+ expect(anthropicbody.messages).toEqual([{ role: "user", content: "draft one step" }]);
131
+ const anthropicanswer = anthropicgatewayadapter.parseanswer(await fixture("anthropic-completion.json"));
132
+ expect(anthropicanswer.text).toContain("summarize the page");
133
+ expect(anthropicanswer.usage).toEqual({ prompttokens: 47, completiontokens: 18, totaltokens: 65 });
134
+
135
+ const gemini = geminigatewayadapter.build({
136
+ config: config({ kind: "geminigateway", baseurl: "https://gateway.example" }),
137
+ model: "fixture-gemini-shape",
138
+ messages,
139
+ apikey: "secret",
140
+ });
141
+ expect(gemini.url).toBe("https://gateway.example/v1beta/models/fixture-gemini-shape:generateContent?key=secret");
142
+ const geminibody = JSON.parse(gemini.body) as Record<string, unknown>;
143
+ expect(geminibody.systemInstruction).toEqual({ parts: [{ text: "be brief" }] });
144
+ expect(geminibody.contents).toEqual([{ role: "user", parts: [{ text: "draft one step" }] }]);
145
+ const geminianswer = geminigatewayadapter.parseanswer(await fixture("gemini-completion.json"));
146
+ expect(geminianswer.text).toContain("answer the question");
147
+ expect(geminianswer.usage?.totaltokens).toBe(40);
148
+
149
+ const ollama = ollamalocaladapter.build({
150
+ config: config({ kind: "ollamalocal", baseurl: "http://localhost:11434" }),
151
+ model: "fixture-local:7b",
152
+ messages: [{ role: "user", content: "run locally" }],
153
+ });
154
+ expect(ollama.url).toBe("http://localhost:11434/api/chat");
155
+ expect(ollama.headers.authorization).toBeUndefined();
156
+ const ollamabody = JSON.parse(ollama.body) as Record<string, unknown>;
157
+ expect(ollamabody.model).toBe("fixture-local:7b");
158
+ expect(ollamabody.messages).toEqual([{ role: "user", content: "run locally" }]);
159
+ const ollamaanswer = ollamalocaladapter.parseanswer(await fixture("ollama-completion.json"));
160
+ expect(ollamaanswer.text).toContain("run locally");
161
+ expect(ollamaanswer.usage).toEqual({ prompttokens: 40, completiontokens: 17, totaltokens: 57 });
162
+ expect(adapterof("openaicompat").kind).toBe("openaicompat");
163
+ expect(Object.keys(gatewayadapters)).toEqual(["openaicompat", "anthropicgateway", "geminigateway", "ollamalocal"]);
164
+ });
165
+
166
+ it("joins the base url, the per provider path prefix and the wire path of every adapter", () => {
167
+ expect(gatewayurl({ baseurl: "https://gateway.example/v1/", pathprefix: "team" }, "/chat/completions")).toBe(
168
+ "https://gateway.example/v1/team/chat/completions",
169
+ );
170
+ expect(gatewayurl({ baseurl: "https://gateway.example" }, "/v1/messages")).toBe(
171
+ "https://gateway.example/v1/messages",
172
+ );
173
+ expect(gatewayurl({ baseurl: "http://localhost:11434/", pathprefix: "/ns/" }, "/api/chat")).toBe(
174
+ "http://localhost:11434/ns/api/chat",
175
+ );
176
+ });
177
+ });
178
+
179
+ describe("gateway streaming deltas, cancel contract and sidepanel rendering", () => {
180
+ it("parses the recorded stream bodies of every adapter into ordered tokens with the done marker", async () => {
181
+ const openai = openaicompatadapter.parsestream(await fixture("openaicompat-stream.txt"));
182
+ expect(openai.map((token) => token.text).join("")).toBe('{"goal":"streamed answer","steps":[]}');
183
+ expect(openai[openai.length - 1]?.done).toBe(true);
184
+ const anthropic = anthropicgatewayadapter.parsestream(await fixture("anthropic-stream.txt"));
185
+ expect(anthropic.map((token) => token.text).join("")).toBe("the messages content blocks stream");
186
+ const gemini = geminigatewayadapter.parsestream(await fixture("gemini-stream.txt"));
187
+ expect(gemini.map((token) => token.text).join("")).toBe("gemini candidate parts stream");
188
+ const ollama = ollamalocaladapter.parsestream(await fixture("ollama-stream.txt"));
189
+ expect(ollama.map((token) => token.text).join("")).toBe("the local runtime streams line by line");
190
+ expect(ollama[ollama.length - 1]?.done).toBe(true);
191
+ });
192
+
193
+ it("streams through the shared contract, fires the onevent seam per token and stops at the cancelled position", async () => {
194
+ const events: string[] = [];
195
+ const cancel = gatewaycancel();
196
+ const streambody = await fixture("openaicompat-stream.txt");
197
+ const transport = stub(streambody);
198
+ const streamed = await gatewaystream({
199
+ config: config(),
200
+ model: "fixture-model-a",
201
+ messages: [{ role: "user", content: "stream" }],
202
+ cancel,
203
+ transport,
204
+ sleep: instant,
205
+ onevent: (token) => {
206
+ events.push(token.text);
207
+ if (events.length === 2) cancel.cancel("The test cancelled mid stream.");
208
+ },
209
+ });
210
+ expect(events.length).toBe(2);
211
+ expect(streamed.tokens.length).toBe(2);
212
+ expect(streamed.text).toBe('{"goal":"streamed answer",');
213
+ const cancelled = gatewaycancel();
214
+ cancelled.cancel();
215
+ await expect(
216
+ gatewaycall({ config: config(), model: "m", messages: [], cancel: cancelled, transport, sleep: instant }),
217
+ ).rejects.toMatchObject({ code: "cancelled" });
218
+ });
219
+
220
+ it("renders the streamed tokens incrementally through the cursor batches of the sidepanel chat", () => {
221
+ const tokens: gatewaychattoken[] = [
222
+ { seq: 1, text: "hello ", at: now },
223
+ { seq: 2, text: "streamed ", at: now },
224
+ ];
225
+ const first = streamrender(tokens, 0, false);
226
+ expect(first.text).toBe("hello streamed ");
227
+ expect(first.nextcursor).toBe(2);
228
+ expect(first.done).toBe(false);
229
+ const grown: gatewaychattoken[] = [...tokens, { seq: 3, text: "world", at: now }];
230
+ const second = streamrender(grown, first.nextcursor, true);
231
+ expect(second.text).toBe("world");
232
+ expect(second.done).toBe(true);
233
+ const empty = streamrender(grown, 3, true);
234
+ expect(empty.text).toBe("");
235
+ expect(empty.done).toBe(true);
236
+ expect(streamrender([], 0, false).done).toBe(false);
237
+ const state = gatewaychatstateof({
238
+ requestid: "req1",
239
+ config: config(),
240
+ model: "m",
241
+ prompt: "p",
242
+ tokens,
243
+ done: true,
244
+ now,
245
+ });
246
+ expect(state.done).toBe(true);
247
+ expect(state.kind).toBe("openaicompat");
248
+ });
249
+ });
250
+
251
+ describe("gateway capabilityad advertisement and tool schema mapping", () => {
252
+ it("serializes the tool catalog into the provider specific schema of every adapter with the consent metadata and the plan review gate", () => {
253
+ const tools = catalogtools();
254
+ for (const kind of ["openaicompat", "anthropicgateway", "geminigateway", "ollamalocal"] as const) {
255
+ const ad = capabilityadvertisement({ kind, tools });
256
+ expect(ad.kind).toBe(kind);
257
+ if (kind === "geminigateway") {
258
+ expect(ad.tools).toHaveLength(1);
259
+ expect((ad.tools[0] as { functionDeclarations: unknown[] }).functionDeclarations).toHaveLength(tools.length);
260
+ } else {
261
+ expect(ad.tools).toHaveLength(tools.length);
262
+ }
263
+ expect(ad.consent).toHaveLength(tools.length);
264
+ expect(ad.consent[0]?.tool).toBe(tools[0]?.name);
265
+ expect(ad.requiredcapabilities).toContain("planreview");
266
+ }
267
+ const openai = capabilityadvertisement({ kind: "openaicompat", tools }).tools[0] as Record<string, unknown>;
268
+ expect(openai.type).toBe("function");
269
+ expect((openai.function as Record<string, unknown>).name).toBe(tools[0]?.name);
270
+ const anthropic = capabilityadvertisement({ kind: "anthropicgateway", tools }).tools[0] as Record<string, unknown>;
271
+ expect(anthropic["input_schema"]).toBeDefined();
272
+ const gemini = capabilityadvertisement({ kind: "geminigateway", tools }).tools[0] as Record<string, unknown>;
273
+ const declarations = gemini.functionDeclarations as Array<Record<string, unknown>>;
274
+ expect(declarations[0]?.name).toBe(tools[0]?.name);
275
+ const ollama = capabilityadvertisement({ kind: "ollamalocal", tools }).tools[0] as Record<string, unknown>;
276
+ expect(ollama.type).toBe("function");
277
+ const consenttool = tools.find((tool) => tool.consentmeta !== undefined);
278
+ if (consenttool !== undefined) {
279
+ const declared = capabilityadvertisement({ kind: "openaicompat", tools }).consent.find(
280
+ (entry) => entry.tool === consenttool.name,
281
+ );
282
+ expect(declared?.review).toBe(consenttool.consentmeta?.review);
283
+ }
284
+ const withtools = openaicompatadapter.build({
285
+ config: config(),
286
+ model: "m",
287
+ messages: [{ role: "user", content: "go" }],
288
+ tools,
289
+ });
290
+ const body = JSON.parse(withtools.body) as Record<string, unknown>;
291
+ expect(Array.isArray(body.tools)).toBe(true);
292
+ });
293
+ });
294
+
295
+ describe("gateway baseurlconfig validation and the empty default posture", () => {
296
+ it("validates the scheme, host and path shape before saving and keeps every remote default empty", () => {
297
+ expect(defaultbaseurl("openaicompat")).toBe("");
298
+ expect(defaultbaseurl("anthropicgateway")).toBe("");
299
+ expect(defaultbaseurl("geminigateway")).toBe("");
300
+ expect(defaultbaseurl("ollamalocal")).toBe("http://localhost:11434");
301
+ expect(gatewayislocal({ baseurl: defaultbaseurl("ollamalocal") })).toBe(true);
302
+ expect(gatewaybaseurlgate({ kind: "openaicompat", baseurl: "" }).allowed).toBe(false);
303
+ expect(gatewaybaseurlgate({ kind: "openaicompat", baseurl: "https://gateway.example/v1" }).allowed).toBe(true);
304
+ expect(gatewaybaseurlgate({ kind: "openaicompat", baseurl: "ftp://gateway.example" }).allowed).toBe(false);
305
+ expect(gatewaybaseurlgate({ kind: "openaicompat", baseurl: "https://gateway.example/v1?x=1" }).allowed).toBe(false);
306
+ expect(gatewaybaseurlgate({ kind: "openaicompat", baseurl: "https://gateway.example/v1#frag" }).allowed).toBe(
307
+ false,
308
+ );
309
+ expect(gatewaybaseurlgate({ kind: "openaicompat", baseurl: "https://gateway.example/../etc" }).allowed).toBe(false);
310
+ expect(gatewaybaseurlgate({ kind: "openaicompat", baseurl: "http://gateway.example/v1" }).allowed).toBe(false);
311
+ expect(gatewaybaseurlgate({ kind: "openaicompat", baseurl: "http://localhost:8080/v1" }).allowed).toBe(true);
312
+ expect(gatewaybaseurlgate({ kind: "ollamalocal", baseurl: "https://gateway.example" }).allowed).toBe(false);
313
+ expect(gatewaybaseurlgate({ kind: "ollamalocal", baseurl: "http://localhost:11434" }).allowed).toBe(true);
314
+ expect(gatewaybaseurlgate({ kind: "ollamalocal", baseurl: "http://127.0.0.1:11434" }).allowed).toBe(true);
315
+ const filled = validategatewayconfig({
316
+ providerid: "local1",
317
+ kind: "ollamalocal",
318
+ baseurl: "",
319
+ enabled: false,
320
+ updatedat: now,
321
+ });
322
+ expect(filled.ok).toBe(true);
323
+ expect(filled.config.baseurl).toBe("http://localhost:11434");
324
+ const refused = validategatewayconfig({
325
+ providerid: "r1",
326
+ kind: "openaicompat",
327
+ baseurl: "",
328
+ enabled: false,
329
+ updatedat: now,
330
+ });
331
+ expect(refused.ok).toBe(false);
332
+ });
333
+ });
334
+
335
+ describe("gateway key vault behind the seam", () => {
336
+ it("stores under the explicit consent, masks every log surface, revokes with one click and refuses the export leak", async () => {
337
+ const vault = inmemoryvault();
338
+ const provider = config({ kind: "anthropicgateway", baseurl: "https://gateway.example" });
339
+ await expect(
340
+ storeproviderkey({
341
+ seam: vault,
342
+ config: provider,
343
+ profileid: "p",
344
+ value: "secret-key-material",
345
+ consent: false,
346
+ now,
347
+ }),
348
+ ).rejects.toThrow(/explicit consent/i);
349
+ expect(gatewaykeyconsentgate({ consent: false, providerid: "prov1" }).allowed).toBe(false);
350
+ const entry = await storeproviderkey({
351
+ seam: vault,
352
+ config: provider,
353
+ profileid: "p",
354
+ value: "secret-key-material",
355
+ consent: true,
356
+ now,
357
+ });
358
+ expect(entry.scope).toBe("https://gateway.example");
359
+ expect(JSON.stringify(entry).includes("secret-key-material")).toBe(false);
360
+ const resolved = await vault.fetch(entry.vaultid);
361
+ expect(resolved).toBe("secret-key-material");
362
+ const mask = maskkey("secret-key-material");
363
+ expect(mask.includes("secret-key-material")).toBe(false);
364
+ expect(mask).toContain("19 chars");
365
+ const masked = maskrequest({
366
+ url: "https://gateway.example/v1/models?key=secret-key-material",
367
+ method: "POST",
368
+ headers: {
369
+ authorization: "Bearer secret-key-material",
370
+ "x-api-key": "secret-key-material",
371
+ "content-type": "application/json",
372
+ },
373
+ body: "{}",
374
+ });
375
+ expect(JSON.stringify(masked).includes("secret-key-material")).toBe(false);
376
+ expect(masked.headers.authorization).toContain("vault-key");
377
+ expect(masked.url).toContain("key=masked");
378
+ const revoked = await revokeproviderkey({ seam: vault, entry });
379
+ expect(revoked.dropped).toBe(true);
380
+ expect(await vault.fetch(entry.vaultid)).toBeUndefined();
381
+ const second = await storeproviderkey({
382
+ seam: vault,
383
+ config: provider,
384
+ profileid: "p",
385
+ value: "another-key-material",
386
+ consent: true,
387
+ now,
388
+ });
389
+ const leak = await keyexportcheck({ candidates: ["another-key-material", "plain text"], entries: [second] });
390
+ expect(leak.leaks).toEqual(["another-key-material"]);
391
+ });
392
+ });
393
+
394
+ describe("gateway modellist discovery, cache window and annotations", () => {
395
+ it("fetches through the adapter, annotates the context and modality hints and serves the cache inside the window", async () => {
396
+ const seen: string[] = [];
397
+ const transport = stub(await fixture("openaicompat-models.json"), 200, seen);
398
+ const fresh = await fetchmodellist({ config: config(), transport, now: () => now });
399
+ expect(fresh.cached).toBe(false);
400
+ expect(fresh.models[0]).toMatchObject({ id: "fixture-model-a", contextwindow: 8192, modalities: ["text"] });
401
+ expect(fresh.models[1]?.id).toBe("fixture-model-b");
402
+ expect(fresh.models[1]?.contextwindow).toBeUndefined();
403
+ const cached = await fetchmodellist({
404
+ config: config(),
405
+ transport,
406
+ cachewindow: 60_000,
407
+ cache: { providerid: "prov1", models: fresh.models, fetchedat: now },
408
+ now: () => now + 1000,
409
+ });
410
+ expect(cached.cached).toBe(true);
411
+ expect(cached.models).toHaveLength(2);
412
+ const stale = await fetchmodellist({
413
+ config: config(),
414
+ transport,
415
+ cachewindow: 60_000,
416
+ cache: { providerid: "prov1", models: [], fetchedat: now },
417
+ now: () => now + 61_000,
418
+ });
419
+ expect(stale.cached).toBe(false);
420
+ expect(stale.models).toHaveLength(2);
421
+ const failed = await fetchmodellist({ config: config(), transport: stub("nope", 500), now: () => now });
422
+ expect(failed.models).toEqual([]);
423
+ expect(failed.reason).toContain("500");
424
+ const gemini = await fetchmodellist({
425
+ config: config({ kind: "geminigateway", baseurl: "https://gateway.example" }),
426
+ transport: stub(await fixture("gemini-models.json")),
427
+ now: () => now,
428
+ });
429
+ expect(gemini.models[0]).toMatchObject({
430
+ id: "fixture-gemini-shape",
431
+ label: "Fixture Gemini Shape",
432
+ contextwindow: 32768,
433
+ });
434
+ const anthropic = await fetchmodellist({
435
+ config: config({ kind: "anthropicgateway", baseurl: "https://gateway.example" }),
436
+ transport: stub(await fixture("anthropic-models.json")),
437
+ now: () => now,
438
+ });
439
+ expect(anthropic.models[1]).toMatchObject({ id: "fixture-claude-wide", contextwindow: 200000 });
440
+ const ollama = await fetchmodellist({
441
+ config: config({ kind: "ollamalocal", baseurl: "http://localhost:11434" }),
442
+ transport: stub(await fixture("ollama-tags.json")),
443
+ now: () => now,
444
+ });
445
+ expect(ollama.models[0]).toMatchObject({ id: "fixture-local:7b" });
446
+ expect(ollama.models[0]?.modalities).toEqual(["llama"]);
447
+ void seen;
448
+ });
449
+ });
450
+
451
+ describe("gateway guardrails over the parsed answers", () => {
452
+ it("accepts the valid plan answer, retries the malformed one with the structured prompt and refuses after the capped attempts", () => {
453
+ const valid = gatewayguard({ attempts: ['{"goal":"g","steps":[],"openquestions":[]}"'] });
454
+ expect(valid.output.verdict).toBe("valid");
455
+ expect(valid.retryprompt).toBeUndefined();
456
+ expect(valid.cappedat).toBe(2);
457
+ const malformed = gatewayguard({ attempts: ["the model answered prose"] });
458
+ expect(malformed.output.verdict).toBe("invalid");
459
+ expect(malformed.retryprompt).toContain("failed its guard");
460
+ const exhausted = gatewayguard({ attempts: ["one", "two", "three"] });
461
+ expect(exhausted.output.verdict).toBe("invalid");
462
+ expect(exhausted.output.attempts).toBe(2);
463
+ expect(exhausted.retryprompt).toBeUndefined();
464
+ const refused = gatewayguard({ attempts: ["I cannot comply with that request"] });
465
+ expect(refused.output.verdict).toBe("refused");
466
+ expect(gatewayplanguard.schema.steps?.type).toBe("array");
467
+ expect(gatewayretrycapvalid(-1).allowed).toBe(false);
468
+ expect(gatewayretrycapvalid(3).allowed).toBe(true);
469
+ });
470
+ });
471
+
472
+ describe("gateway routing with the local fallback", () => {
473
+ it("maps the task kind through the user rules and falls back to the local provider when the remote gates refuse", () => {
474
+ const providers: providerconfig[] = [
475
+ {
476
+ id: "prov1",
477
+ name: "The remote gateway",
478
+ endpoint: "https://gateway.example/v1",
479
+ style: "chatcompletions",
480
+ models: ["model-a"],
481
+ status: "available",
482
+ createdat: now,
483
+ },
484
+ ];
485
+ const routes: modelroute[] = [
486
+ { id: "r1", kind: "chat", providerid: "prov1", model: "model-a", revision: 1, updatedat: now },
487
+ ];
488
+ const local: localmodelconfig = {
489
+ endpoint: "http://localhost:11434",
490
+ model: "fixture-local:7b",
491
+ style: "chatcompletions",
492
+ };
493
+ const routed = resolvegatewayroute({ kind: "chat", routes, providers, configs: [], local });
494
+ expect(routed.source).toBe("route");
495
+ expect(routed.provider?.id).toBe("prov1");
496
+ expect(routed.model).toBe("model-a");
497
+ const gated = resolvegatewayroute({
498
+ kind: "chat",
499
+ routes,
500
+ providers,
501
+ configs: [config({ providerid: "prov1", enabled: false, consented: false })],
502
+ local,
503
+ });
504
+ expect(gated.source).toBe("local");
505
+ expect(gated.local?.model).toBe("fixture-local:7b");
506
+ const notallowed = resolvegatewayroute({
507
+ kind: "chat",
508
+ routes,
509
+ providers,
510
+ configs: [config()],
511
+ local,
512
+ remoteallowed: false,
513
+ });
514
+ expect(notallowed.source).toBe("local");
515
+ const nolocal = resolvegatewayroute({
516
+ kind: "chat",
517
+ routes,
518
+ providers,
519
+ configs: [config({ providerid: "prov1", enabled: false, consented: false })],
520
+ });
521
+ expect(nolocal.reason).toBeDefined();
522
+ const fallbackpair: modelroute[] = [
523
+ {
524
+ id: "r2",
525
+ kind: "chat",
526
+ providerid: "prov1",
527
+ model: "model-a",
528
+ fallbackproviderid: "prov2",
529
+ fallbackmodel: "model-b",
530
+ revision: 1,
531
+ updatedat: now,
532
+ },
533
+ ];
534
+ const providers2: providerconfig[] = [
535
+ ...providers,
536
+ {
537
+ id: "prov2",
538
+ name: "The fallback gateway",
539
+ endpoint: "https://fallback.example/v1",
540
+ style: "chatcompletions" as const,
541
+ models: ["model-b"],
542
+ status: "available",
543
+ createdat: now,
544
+ },
545
+ ];
546
+ const fell = resolvegatewayroute({
547
+ kind: "chat",
548
+ routes: fallbackpair,
549
+ providers: providers2,
550
+ configs: [config({ providerid: "prov1", enabled: false, consented: false })],
551
+ });
552
+ expect(fell.source).toBe("fallback");
553
+ expect(fell.provider?.id).toBe("prov2");
554
+ });
555
+ });
556
+
557
+ describe("gateway token budget accounting and threshold warnings", () => {
558
+ it("records the usage with the request id and session, reports the per session and per run totals and warns at the configured ratio", () => {
559
+ const record = gatewayusagerecord({
560
+ providerid: "prov1",
561
+ endpoint: "https://gateway.example/v1/chat/completions",
562
+ model: "model-a",
563
+ usage: { prompttokens: 600, completiontokens: 400, totaltokens: 1000 },
564
+ costpermilliontokens: 3,
565
+ sessionid: "sess1",
566
+ runid: "run1",
567
+ requestid: "req1",
568
+ now,
569
+ });
570
+ expect(record.cost).toBeCloseTo(0.003, 6);
571
+ expect(record.requestid).toBe("req1");
572
+ expect(record.sessionid).toBe("sess1");
573
+ expect(record.local).toBeUndefined();
574
+ const localrecord = gatewayusagerecord({
575
+ providerid: "local",
576
+ endpoint: "http://localhost:11434/api/chat",
577
+ model: "fixture-local:7b",
578
+ usage: { prompttokens: 10, completiontokens: 5, totaltokens: 15 },
579
+ requestid: "req2",
580
+ local: true,
581
+ now,
582
+ });
583
+ expect(localrecord.local).toBe(true);
584
+ expect(localrecord.cost).toBe(0);
585
+ const totals = usagetotals([record, localrecord], { sessionid: "sess1" });
586
+ expect(totals.totaltokens).toBe(1000);
587
+ expect(usagetotals([record, localrecord], { runid: "run1" }).totaltokens).toBe(1000);
588
+ expect(usagetotals([record, localrecord]).totaltokens).toBe(1015);
589
+ const budget = { maxtokens: 2000, warnratio: 0.4, configuredat: now };
590
+ const quiet = gatewaybudgetwarning({ budget, totals: { totaltokens: 100, cost: 0 } });
591
+ expect(quiet.warned).toBe(false);
592
+ const warned = gatewaybudgetwarning({ budget, totals: { totaltokens: 900, cost: 0 } });
593
+ expect(warned.warned).toBe(true);
594
+ expect(warned.tokenratio).toBeCloseTo(0.45, 6);
595
+ const costwarned = gatewaybudgetwarning({
596
+ budget: { maxcost: 2, warnratio: 0.5, configuredat: now },
597
+ totals: { totaltokens: 0, cost: 1.2 },
598
+ });
599
+ expect(costwarned.warned).toBe(true);
600
+ const halted = gatewaybudgetcheck({
601
+ budget: { maxtokens: 100, configuredat: now },
602
+ totals: { totaltokens: 200, cost: 0 },
603
+ });
604
+ expect(halted.allowed).toBe(false);
605
+ expect(halted.asksuser).toBe(true);
606
+ const estimates = costestimates({
607
+ configs: [config({ costpermilliontokens: 2, currency: "usd" })],
608
+ providers,
609
+ records: [record],
610
+ });
611
+ expect(estimates[0]).toMatchObject({
612
+ providerid: "prov1",
613
+ model: "model-a",
614
+ permillion: 2,
615
+ currency: "usd",
616
+ recordedtokens: 1000,
617
+ });
618
+ });
619
+ const providers: providerconfig[] = [];
620
+ });
621
+
622
+ describe("gateway consent gate blocks the provider calls before approval", () => {
623
+ it("refuses the disabled, unconsented and unconfigured providers while the local runtime needs no remote consent", async () => {
624
+ const body = await fixture("openaicompat-completion.json");
625
+ await expect(
626
+ gatewaycall({
627
+ config: config({ enabled: false }),
628
+ model: "m",
629
+ messages: [],
630
+ transport: stub(body),
631
+ sleep: instant,
632
+ }),
633
+ ).rejects.toMatchObject({ code: "noconsent" });
634
+ await expect(
635
+ gatewaycall({
636
+ config: config({ consented: false }),
637
+ model: "m",
638
+ messages: [],
639
+ transport: stub(body),
640
+ sleep: instant,
641
+ }),
642
+ ).rejects.toMatchObject({ code: "noconsent" });
643
+ await expect(
644
+ gatewaycall({ config: config({ baseurl: "" }), model: "m", messages: [], transport: stub(body), sleep: instant }),
645
+ ).rejects.toMatchObject({ code: "notconfigured" });
646
+ const localanswer = await gatewaycall({
647
+ config: config({ kind: "ollamalocal", baseurl: "http://localhost:11434" }),
648
+ model: "fixture-local:7b",
649
+ messages: [{ role: "user", content: "hi" }],
650
+ transport: stub(await fixture("ollama-completion.json")),
651
+ sleep: instant,
652
+ });
653
+ expect(localanswer.text).toContain("run locally");
654
+ expect(
655
+ gatewayconsentgate({ config: { kind: "ollamalocal", baseurl: "http://localhost:11434", enabled: true } }).allowed,
656
+ ).toBe(true);
657
+ expect(
658
+ gatewayconsentgate({
659
+ config: { kind: "openaicompat", baseurl: "https://gateway.example", enabled: true, consented: true },
660
+ }).allowed,
661
+ ).toBe(true);
662
+ });
663
+ });
664
+
665
+ describe("gateway provenance, structured errors and audit reports", () => {
666
+ it("correlates every call through its request id and reports the provenance envelope", () => {
667
+ const report = gatewaycallreport({
668
+ requestid: "req1",
669
+ providerid: "prov1",
670
+ kind: "openaicompat",
671
+ model: "model-a",
672
+ tokens: { prompttokens: 10, completiontokens: 5, totaltokens: 15 },
673
+ cost: 0.001,
674
+ at: now,
675
+ });
676
+ expect(report.version).toBeDefined();
677
+ expect(report.requestid).toBe("req1");
678
+ expect(() =>
679
+ gatewaycallreport({
680
+ requestid: "",
681
+ providerid: "p",
682
+ kind: "openaicompat",
683
+ model: "m",
684
+ tokens: { prompttokens: 0, completiontokens: 0, totaltokens: 0 },
685
+ cost: 0,
686
+ at: now,
687
+ }),
688
+ ).toThrow(/request id/i);
689
+ const error = gatewayerrorof("ratelimited", "limited", "req2", "wait the window", 1500);
690
+ expect(error.retryafter).toBe(1500);
691
+ const normalized = gatewayerrorfrom(new Error("The request timed out after 10 milliseconds."), "req3");
692
+ expect(normalized.code).toBe("timeout");
693
+ expect(gatewayerrorfrom(error, "req4")).toBe(error);
694
+ });
695
+ });
696
+
697
+ describe("gateway timeout, transient retries and rate limit honoring", () => {
698
+ it("races the timeout, retries the transient failures with the jittered backoff and honors the retry-after header of the 429 answer", async () => {
699
+ const body = await fixture("openaicompat-completion.json");
700
+ const waits: number[] = [];
701
+ const sleep = async (milliseconds: number): Promise<void> => {
702
+ waits.push(milliseconds);
703
+ };
704
+ await expect(
705
+ gatewaycall({
706
+ config: config(),
707
+ model: "m",
708
+ messages: [],
709
+ options: { timeout: 50 },
710
+ transport: async () => {
711
+ await new Promise((resolve) => setTimeout(resolve, 120));
712
+ return { status: 200, headers: {}, body };
713
+ },
714
+ sleep,
715
+ now: () => now,
716
+ }),
717
+ ).rejects.toMatchObject({ code: "timeout" });
718
+ let calls = 0;
719
+ const flaky = async (): Promise<transportresponse> => {
720
+ calls += 1;
721
+ if (calls === 1) return { status: 503, headers: {}, body: '{"error":"transient"}' };
722
+ return { status: 200, headers: {}, body };
723
+ };
724
+ const retried = await gatewaycall({
725
+ config: config(),
726
+ model: "m",
727
+ messages: [],
728
+ options: { retries: 2, backoff: 10, jitter: 5 },
729
+ transport: flaky,
730
+ sleep,
731
+ jitter: () => 1,
732
+ now: () => now,
733
+ });
734
+ expect(retried.text).toContain("open the docs page");
735
+ expect(retried.retries).toBe(1);
736
+ expect(waits.some((wait) => wait >= 10)).toBe(true);
737
+ let limited = 0;
738
+ const ratelimited = async (): Promise<transportresponse> => {
739
+ limited += 1;
740
+ if (limited === 1) return { status: 429, headers: { "retry-after": "1" }, body: '{"error":"rate limited"}' };
741
+ return { status: 200, headers: {}, body };
742
+ };
743
+ const honored = await gatewaycall({
744
+ config: config(),
745
+ model: "m",
746
+ messages: [],
747
+ options: { retries: 1 },
748
+ transport: ratelimited,
749
+ sleep,
750
+ now: () => now,
751
+ });
752
+ expect(honored.retries).toBe(1);
753
+ expect(waits).toContain(1000);
754
+ let exhausted = 0;
755
+ const alwaysexhausted = async (): Promise<transportresponse> => {
756
+ exhausted += 1;
757
+ return { status: 429, headers: { "retry-after": "1" }, body: '{"error":"rate limited"}' };
758
+ };
759
+ await expect(
760
+ gatewaycall({ config: config(), model: "m", messages: [], transport: alwaysexhausted, sleep, now: () => now }),
761
+ ).rejects.toMatchObject({ code: "ratelimited", retryafter: 1000 });
762
+ await expect(
763
+ gatewaycall({ config: config(), model: "m", messages: [], transport: stub("no", 401), sleep, now: () => now }),
764
+ ).rejects.toMatchObject({ code: "unauthorized" });
765
+ await expect(
766
+ gatewaycall({
767
+ config: config(),
768
+ model: "m",
769
+ messages: [],
770
+ transport: stub("<html>broken</html>"),
771
+ sleep,
772
+ now: () => now,
773
+ }),
774
+ ).rejects.toMatchObject({ code: "parse" });
775
+ });
776
+ });
777
+
778
+ describe("gateway fixture server runs the full request cycle offline", () => {
779
+ it("serves the recorded shapes over localhost http for the call, the stream and the model list", async () => {
780
+ const server = await startgatewayfixtureserver();
781
+ try {
782
+ const transport: fetchtransport = async (url, init) => {
783
+ const response = await fetch(url, {
784
+ method: init.method,
785
+ headers: init.headers,
786
+ ...(init.body !== undefined ? { body: init.body } : {}),
787
+ });
788
+ return {
789
+ status: response.status,
790
+ headers: Object.fromEntries(response.headers.entries()),
791
+ body: await response.text(),
792
+ };
793
+ };
794
+ const outcome = await gatewaycall({
795
+ config: config({ baseurl: `http://127.0.0.1:${server.port}/openaicompat` }),
796
+ model: "fixture-model-a",
797
+ messages: [{ role: "user", content: "draft" }],
798
+ requestid: "cycle-1",
799
+ transport,
800
+ sleep: instant,
801
+ });
802
+ expect(outcome.text).toContain("open the docs page");
803
+ expect(outcome.status).toBe(200);
804
+ const streamed = await gatewaystream({
805
+ config: config({ kind: "ollamalocal", baseurl: `http://127.0.0.1:${server.port}/ollama` }),
806
+ model: "fixture-local:7b",
807
+ messages: [{ role: "user", content: "stream" }],
808
+ transport,
809
+ sleep: instant,
810
+ });
811
+ expect(streamed.text).toBe("the local runtime streams line by line");
812
+ const models = await fetchmodellist({
813
+ config: config({ kind: "geminigateway", baseurl: `http://127.0.0.1:${server.port}/gemini` }),
814
+ transport,
815
+ now: () => now,
816
+ });
817
+ expect(models.models.map((model) => model.id)).toContain("fixture-gemini-shape");
818
+ } finally {
819
+ await server.close();
820
+ }
821
+ });
822
+ });
823
+
824
+ describe("gateway prompt template library of the per task templates", () => {
825
+ it("ships the per task templates with their variable slots and composes through the shared prompt library", () => {
826
+ const templates = gatewaytemplates(now);
827
+ const names = templates.map((template) => template.name);
828
+ expect(names).toEqual([
829
+ "gateway.parsecommand",
830
+ "gateway.draftplan",
831
+ "gateway.replan",
832
+ "gateway.reflect",
833
+ "gateway.chat",
834
+ ]);
835
+ for (const template of templates) {
836
+ expect(template.version).toBe(1);
837
+ expect(template.variables.length).toBeGreaterThan(0);
838
+ for (const variable of template.variables) expect(template.body.includes(`{{${variable}}}`)).toBe(true);
839
+ }
840
+ const composed = composegatewayprompt({
841
+ templates,
842
+ name: "gateway.draftplan",
843
+ variables: { goal: "check the docs", tools: "none" },
844
+ });
845
+ expect(composed.text).toContain("check the docs");
846
+ expect(composed.text?.includes("{{goal}}")).toBe(false);
847
+ expect(composegatewayprompt({ templates, name: "missing", variables: {} }).reason).toBeDefined();
848
+ });
849
+ });
850
+
851
+ describe("hardcoded provider url scan of the source tree", () => {
852
+ it("asserts no provider endpoint literal and no default cloud url in the shipped sources", async () => {
853
+ const root = process.cwd();
854
+ /* the gateway lineage keeps every remote default empty: after the
855
+ * wave/ownership.getry split the scan covers the gateway family sources
856
+ * this app owns — the engine and the llm family it gates (the os-side
857
+ * gate sources the old list carried — http, mcp, server, crossbrowser,
858
+ * auth, bridge, memory, runtime — stayed devthink property and the os
859
+ * keeps its own copy of the gate there). the workbench provider catalog
860
+ * (providers.ts) and the antigravity provider lineages (the constants
861
+ * and the provider oauth family) talk to user configured cloud
862
+ * endpoints by design, and the shared types carry their documentation
863
+ * examples, so they sit outside this scan while the gateway family
864
+ * stays default empty */
865
+ const gatewaysources = ["engine.ts", "llm.ts"];
866
+ const files: string[] = gatewaysources.map((name) => join(root, name));
867
+ for (const path of files) await access(path);
868
+
869
+ /* the flattened tests village: the gate sources of the os moved from
870
+ * the repository-root tests folder in beside the modules they gate at
871
+ * the app root, and the suites with their example fixtures stay
872
+ * outside the scan the corpus law kept them in (the tests-village
873
+ * helpers ride in without their suites, and so does the reviewed
874
+ * origins catalog module — the typed data rows the sweep allowlist
875
+ * reads, the one module whose provider endpoint literals are the
876
+ * reviewed catalog itself, never a call target the gateway would
877
+ * dial), so the walk covers every root source and every
878
+ * tests-village helper outside the provider catalog exceptions — the
879
+ * workbench catalog (providers.ts, gatewayviewconfig.ts) and the
880
+ * shared types carry their documentation examples by design, while
881
+ * the gateway family stays default empty. the file floor rides the
882
+ * getry tree after the ownership split: the app root carries the
883
+ * gateway sources the wave moved in beside the theme lanes. */
884
+ const outsidescan = new Set([...gatewaysources, "providers.ts", "gatewayviewconfig.ts", "types.ts"]);
885
+ for (const entry of await readdir(root))
886
+ if (entry.endsWith(".ts") && !outsidescan.has(entry)) files.push(join(root, entry));
887
+ for (const entry of await readdir(join(root, "tests")))
888
+ if (entry.endsWith(".ts") && !entry.endsWith(".test.ts") && entry !== "reviewedorigins.ts")
889
+ files.push(join(root, "tests", entry));
890
+ expect(files.length).toBeGreaterThan(40);
891
+ const providerhosts = [
892
+ /api\.openai\.com/,
893
+ /api\.anthropic\.com/,
894
+ /generativelanguage\.googleapis\.com/,
895
+ /openrouter\.ai/,
896
+ /api\.groq\.com/,
897
+ /api\.mistral\.ai/,
898
+ /api\.cohere\.com/,
899
+ /api\.together\.xyz/,
900
+ /api\.deepseek\.com/,
901
+ /api\.x\.ai/,
902
+ /cloud\.ollama\.com/,
903
+ ];
904
+ for (const path of files) {
905
+ const content = await readFile(path, "utf8");
906
+ for (const host of providerhosts)
907
+ expect(host.test(content), `${path} carries the provider endpoint literal ${String(host)}`).toBe(false);
908
+ }
909
+ const shipped: string[] = gatewaysources.map((name) => join(root, name));
910
+
911
+ const deeplinkapps = [
912
+ "https://github.com",
913
+ "https://www.youtube.com",
914
+ "https://www.google.com",
915
+ "https://en.wikipedia.org",
916
+ "https://www.amazon.com",
917
+ "https://x.com",
918
+ "https://myaccount.google.com",
919
+ "https://opencode.ai",
920
+ ];
921
+ for (const path of shipped) {
922
+ const content = await readFile(path, "utf8");
923
+ const urls = content.match(/https?:\/\/[^\s"'`)<]+/g) ?? [];
924
+ for (const url of urls)
925
+ expect(
926
+ url.includes("${") ||
927
+ url.startsWith("http://localhost") ||
928
+ url.startsWith("https://localhost") ||
929
+ url.startsWith("http://127.0.0.1") ||
930
+ url.startsWith("https://127.0.0.1") ||
931
+ url.includes(".example") ||
932
+ /^https:\/\/(example\.(org|com|net|invalid|test))\b/.test(url) ||
933
+ /^https:\/\/(\*\.)?origin\b/.test(url) ||
934
+ deeplinkapps.some((app) => url.startsWith(app)),
935
+ `${path} carries the non example url literal ${url}`,
936
+ ).toBe(true);
937
+ }
938
+ const gateway = await readFile(join(root, "llm.ts"), "utf8");
939
+ expect(gateway.includes("http://localhost:11434")).toBe(true);
940
+ });
941
+ });
942
+
943
+ describe("api key literal scan of the built bundles", () => {
944
+ it("asserts no api key literal shape in any built dist bundle", async () => {
945
+ const root = process.cwd();
946
+ let distexists = true;
947
+ try {
948
+ await access(join(root, "build"));
949
+ } catch {
950
+ distexists = false;
951
+ }
952
+ if (!distexists)
953
+ return; /* the validate chain runs the tests before the build; the build gate scans every bundle itself and the next pass asserts the fresh dist */
954
+ const keyshapes = [/sk-[A-Za-z0-9]{20,}/, /Bearer\s+[A-Za-z0-9]{20,}/, /x-api-key[":\s]+[A-Za-z0-9-]{20,}/];
955
+ for (const entry of await readdir(join(root, "build"))) {
956
+ if (!entry.endsWith(".js") && !entry.endsWith(".cjs")) continue;
957
+ const content = await readFile(join(root, "build", entry), "utf8");
958
+ for (const shape of keyshapes)
959
+ expect(shape.test(content), `build/${entry} carries an api key literal shape`).toBe(false);
960
+ }
961
+ });
962
+ });