@hop-top/kit 0.4.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (174) hide show
  1. package/CHANGELOG.md +86 -0
  2. package/LICENSE +25 -0
  3. package/README.md +189 -0
  4. package/dist/aim.d.ts +116 -0
  5. package/dist/aim.js +417 -0
  6. package/dist/alias.d.ts +73 -0
  7. package/dist/alias.js +207 -0
  8. package/dist/api.d.ts +62 -0
  9. package/dist/api.js +165 -0
  10. package/dist/auth.d.ts +26 -0
  11. package/dist/auth.js +41 -0
  12. package/dist/cli.d.ts +309 -0
  13. package/dist/cli.js +885 -0
  14. package/dist/config.d.ts +97 -0
  15. package/dist/config.js +79 -0
  16. package/dist/errcorrect.d.ts +37 -0
  17. package/dist/errcorrect.js +69 -0
  18. package/dist/llm.d.ts +188 -0
  19. package/dist/llm.js +356 -0
  20. package/dist/output.d.ts +213 -0
  21. package/dist/output.js +447 -0
  22. package/dist/progress.d.ts +30 -0
  23. package/dist/progress.js +56 -0
  24. package/dist/provenance.d.ts +24 -0
  25. package/dist/provenance.js +32 -0
  26. package/dist/routellm.d.ts +64 -0
  27. package/dist/routellm.js +258 -0
  28. package/dist/rpc.d.ts +25 -0
  29. package/dist/rpc.js +101 -0
  30. package/dist/safety.d.ts +24 -0
  31. package/dist/safety.js +44 -0
  32. package/dist/scope.d.ts +121 -0
  33. package/dist/scope.js +380 -0
  34. package/dist/sqlstore.d.ts +84 -0
  35. package/dist/sqlstore.js +85 -0
  36. package/dist/stream.d.ts +35 -0
  37. package/dist/stream.js +52 -0
  38. package/dist/tui/index.d.ts +300 -0
  39. package/dist/tui/index.js +332 -0
  40. package/dist/upgrade.d.ts +95 -0
  41. package/dist/upgrade.js +115 -0
  42. package/dist/xdg.d.ts +169 -0
  43. package/dist/xdg.js +129 -0
  44. package/eslint.config.mjs +17 -0
  45. package/package.json +133 -0
  46. package/src/README.md +3 -0
  47. package/src/aim.test.ts +331 -0
  48. package/src/aim.ts +388 -0
  49. package/src/alias.test.ts +423 -0
  50. package/src/alias.ts +256 -0
  51. package/src/api.test.ts +190 -0
  52. package/src/api.ts +214 -0
  53. package/src/auth.test.ts +24 -0
  54. package/src/auth.ts +37 -0
  55. package/src/bus.test.ts +178 -0
  56. package/src/bus.ts +114 -0
  57. package/src/cli.test.ts +690 -0
  58. package/src/cli.ts +741 -0
  59. package/src/completion-values.test.ts +202 -0
  60. package/src/completion-values.ts +173 -0
  61. package/src/completion.test.ts +212 -0
  62. package/src/completion.ts +158 -0
  63. package/src/compliance.test.ts +134 -0
  64. package/src/compliance.ts +669 -0
  65. package/src/config.test.ts +110 -0
  66. package/src/config.ts +164 -0
  67. package/src/errcorrect.test.ts +134 -0
  68. package/src/errcorrect.ts +84 -0
  69. package/src/flagregister.test.ts +103 -0
  70. package/src/flagregister.ts +78 -0
  71. package/src/gen/crud_connect.ts +76 -0
  72. package/src/gen/crud_pb.ts +269 -0
  73. package/src/hint.test.ts +315 -0
  74. package/src/hint.ts +178 -0
  75. package/src/llm.test.ts +612 -0
  76. package/src/llm.ts +577 -0
  77. package/src/log.test.ts +145 -0
  78. package/src/log.ts +155 -0
  79. package/src/output/builtins.ts +34 -0
  80. package/src/output/dispatch.ts +195 -0
  81. package/src/output/flags.ts +151 -0
  82. package/src/output/format_help.ts +80 -0
  83. package/src/output/formatter.ts +167 -0
  84. package/src/output/formatters/csv.ts +72 -0
  85. package/src/output/formatters/json.ts +44 -0
  86. package/src/output/formatters/table.ts +44 -0
  87. package/src/output/formatters/text.ts +109 -0
  88. package/src/output/formatters/yaml.ts +47 -0
  89. package/src/output/projection.ts +126 -0
  90. package/src/output/registry.ts +88 -0
  91. package/src/output/template.ts +63 -0
  92. package/src/output.test.ts +117 -0
  93. package/src/output.ts +90 -0
  94. package/src/progress.test.ts +93 -0
  95. package/src/progress.ts +58 -0
  96. package/src/provenance.test.ts +59 -0
  97. package/src/provenance.ts +26 -0
  98. package/src/routellm.test.ts +179 -0
  99. package/src/routellm.ts +365 -0
  100. package/src/router/bert.test.ts +180 -0
  101. package/src/router/bert.ts +145 -0
  102. package/src/router/controller.test.ts +183 -0
  103. package/src/router/controller.ts +165 -0
  104. package/src/router/integration.test.ts +309 -0
  105. package/src/router/intent.test.ts +187 -0
  106. package/src/router/intent.ts +208 -0
  107. package/src/router/mf.test.ts +66 -0
  108. package/src/router/mf.ts +52 -0
  109. package/src/router/random.test.ts +23 -0
  110. package/src/router/random.ts +13 -0
  111. package/src/router/router.test.ts +31 -0
  112. package/src/router/router.ts +62 -0
  113. package/src/router/server.test.ts +193 -0
  114. package/src/router/server.ts +134 -0
  115. package/src/router/sw.test.ts +199 -0
  116. package/src/router/sw.ts +232 -0
  117. package/src/rpc.test.ts +47 -0
  118. package/src/rpc.ts +91 -0
  119. package/src/safety.test.ts +53 -0
  120. package/src/safety.ts +42 -0
  121. package/src/scope-defaults.json +72 -0
  122. package/src/scope.test.ts +177 -0
  123. package/src/scope.ts +382 -0
  124. package/src/setflag.test.ts +110 -0
  125. package/src/setflag.ts +102 -0
  126. package/src/sqlstore.test.ts +110 -0
  127. package/src/sqlstore.ts +144 -0
  128. package/src/stream.test.ts +69 -0
  129. package/src/stream.ts +47 -0
  130. package/src/textflag.test.ts +105 -0
  131. package/src/textflag.ts +68 -0
  132. package/src/toolspec.test.ts +187 -0
  133. package/src/toolspec.ts +279 -0
  134. package/src/triton/client.test.ts +205 -0
  135. package/src/triton/client.ts +261 -0
  136. package/src/tui/anim.test.ts +146 -0
  137. package/src/tui/anim.ts +134 -0
  138. package/src/tui/badge.test.ts +41 -0
  139. package/src/tui/badge.ts +55 -0
  140. package/src/tui/confirm.test.ts +68 -0
  141. package/src/tui/confirm.ts +49 -0
  142. package/src/tui/index.ts +29 -0
  143. package/src/tui/list.test.ts +84 -0
  144. package/src/tui/list.ts +72 -0
  145. package/src/tui/parity.ts +41 -0
  146. package/src/tui/pills.test.ts +40 -0
  147. package/src/tui/pills.ts +43 -0
  148. package/src/tui/progress.test.ts +164 -0
  149. package/src/tui/progress.ts +120 -0
  150. package/src/tui/spinner.test.ts +111 -0
  151. package/src/tui/spinner.ts +96 -0
  152. package/src/tui/status.test.ts +68 -0
  153. package/src/tui/status.ts +66 -0
  154. package/src/upgrade.test.ts +298 -0
  155. package/src/upgrade.ts +205 -0
  156. package/src/uri.ts +199 -0
  157. package/src/wizard.test.ts +441 -0
  158. package/src/wizard.ts +662 -0
  159. package/src/xdg.test.ts +202 -0
  160. package/src/xdg.ts +280 -0
  161. package/test/output/cols.test.ts +148 -0
  162. package/test/output/csv.test.ts +129 -0
  163. package/test/output/dispatch.test.ts +194 -0
  164. package/test/output/format_help.test.ts +131 -0
  165. package/test/output/formatter.test.ts +137 -0
  166. package/test/output/output_flag.test.ts +124 -0
  167. package/test/output/registry.test.ts +127 -0
  168. package/test/output/smoke-capture.ts +83 -0
  169. package/test/output/smoke.test.ts +142 -0
  170. package/test/output/template.test.ts +95 -0
  171. package/test/output/text.test.ts +75 -0
  172. package/test/testdata/api-fixture.json +115 -0
  173. package/test/testdata/query-vectors.json +187 -0
  174. package/tsconfig.json +12 -0
@@ -0,0 +1,612 @@
1
+ /**
2
+ * Tests for LLM module (llm.ts).
3
+ * Covers: parseURI, loadConfig, registry, Client, fallback, hooks, errors.
4
+ */
5
+
6
+ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
7
+ import {
8
+ parseURI,
9
+ loadConfig,
10
+ register,
11
+ resolve,
12
+ clearRegistry,
13
+ createLLM,
14
+ LLMError,
15
+ ProviderNotFoundError,
16
+ CapabilityNotSupportedError,
17
+ AuthError,
18
+ RateLimitError,
19
+ ModelError,
20
+ FallbackExhaustedError,
21
+ isFallbackable,
22
+ type Request,
23
+ type Response,
24
+ type Provider,
25
+ type Token,
26
+ type Factory,
27
+ } from "./llm";
28
+
29
+ // ---------------------------------------------------------------------------
30
+ // Helpers
31
+ // ---------------------------------------------------------------------------
32
+
33
+ function mockProvider(overrides: Partial<Provider> = {}): Provider {
34
+ return {
35
+ close: vi.fn(),
36
+ ...overrides,
37
+ };
38
+ }
39
+
40
+ function mockCompleteProvider(
41
+ response: Response
42
+ ): Provider {
43
+ return {
44
+ complete: vi.fn().mockResolvedValue(response),
45
+ close: vi.fn(),
46
+ };
47
+ }
48
+
49
+ function req(content = "hello"): Request {
50
+ return { messages: [{ role: "user", content }] };
51
+ }
52
+
53
+ // ---------------------------------------------------------------------------
54
+ // parseURI
55
+ // ---------------------------------------------------------------------------
56
+
57
+ describe("parseURI", () => {
58
+ it("parses basic scheme://model", () => {
59
+ const uri = parseURI("openai://gpt-4");
60
+ expect(uri.scheme).toBe("openai");
61
+ expect(uri.model).toBe("gpt-4");
62
+ expect(uri.host).toBeUndefined();
63
+ expect(uri.params).toBeUndefined();
64
+ });
65
+
66
+ it("parses scheme with params", () => {
67
+ const uri = parseURI("openai://gpt-4?temperature=0.7&max_tokens=100");
68
+ expect(uri.scheme).toBe("openai");
69
+ expect(uri.model).toBe("gpt-4");
70
+ expect(uri.params).toEqual({ temperature: "0.7", max_tokens: "100" });
71
+ });
72
+
73
+ it("parses with host:port", () => {
74
+ const uri = parseURI("ollama://localhost:11434/llama3");
75
+ expect(uri.scheme).toBe("ollama");
76
+ expect(uri.host).toBe("localhost:11434");
77
+ expect(uri.model).toBe("llama3");
78
+ });
79
+
80
+ it("handles slashes in model name", () => {
81
+ const uri = parseURI("openai://org/model-name");
82
+ expect(uri.scheme).toBe("openai");
83
+ expect(uri.model).toBe("org/model-name");
84
+ });
85
+
86
+ it("handles host + slashes in model", () => {
87
+ const uri = parseURI("ollama://myhost:8080/ns/model-v2");
88
+ expect(uri.scheme).toBe("ollama");
89
+ expect(uri.host).toBe("myhost:8080");
90
+ expect(uri.model).toBe("ns/model-v2");
91
+ });
92
+
93
+ it("throws on missing scheme", () => {
94
+ expect(() => parseURI("gpt-4")).toThrow();
95
+ });
96
+
97
+ it("throws on empty model", () => {
98
+ expect(() => parseURI("openai://")).toThrow();
99
+ });
100
+
101
+ it("throws on empty string", () => {
102
+ expect(() => parseURI("")).toThrow();
103
+ });
104
+ });
105
+
106
+ // ---------------------------------------------------------------------------
107
+ // loadConfig
108
+ // ---------------------------------------------------------------------------
109
+
110
+ describe("loadConfig", () => {
111
+ const saved: Record<string, string | undefined> = {};
112
+ const envKeys = [
113
+ "LLM_PROVIDER",
114
+ "LLM_API_KEY",
115
+ "LLM_BASE_URL",
116
+ "LLM_FALLBACK",
117
+ ];
118
+
119
+ beforeEach(() => {
120
+ for (const k of envKeys) {
121
+ saved[k] = process.env[k];
122
+ delete process.env[k];
123
+ }
124
+ });
125
+
126
+ afterEach(() => {
127
+ for (const k of envKeys) {
128
+ if (saved[k] === undefined) delete process.env[k];
129
+ else process.env[k] = saved[k];
130
+ }
131
+ });
132
+
133
+ it("loads from URI string", () => {
134
+ const cfg = loadConfig("openai://gpt-4");
135
+ expect(cfg.uri.scheme).toBe("openai");
136
+ expect(cfg.uri.model).toBe("gpt-4");
137
+ expect(cfg.provider.model).toBe("gpt-4");
138
+ });
139
+
140
+ it("applies env var overrides", () => {
141
+ process.env["LLM_API_KEY"] = "sk-test";
142
+ process.env["LLM_BASE_URL"] = "https://custom.api.com";
143
+ process.env["LLM_FALLBACK"] = "anthropic://claude-3,ollama://llama3";
144
+
145
+ const cfg = loadConfig("openai://gpt-4");
146
+ expect(cfg.provider.apiKey).toBe("sk-test");
147
+ expect(cfg.provider.baseURL).toBe("https://custom.api.com");
148
+ expect(cfg.fallbacks).toEqual([
149
+ "anthropic://claude-3",
150
+ "ollama://llama3",
151
+ ]);
152
+ });
153
+
154
+ it("LLM_PROVIDER env is used as full default URI when no arg", () => {
155
+ process.env["LLM_PROVIDER"] = "anthropic://claude-3";
156
+ const cfg = loadConfig();
157
+ expect(cfg.uri.scheme).toBe("anthropic");
158
+ expect(cfg.uri.model).toBe("claude-3");
159
+ });
160
+
161
+ it("LLM_PROVIDER env is ignored when URI arg is provided", () => {
162
+ process.env["LLM_PROVIDER"] = "anthropic://claude-3";
163
+ const cfg = loadConfig("openai://gpt-4");
164
+ expect(cfg.uri.scheme).toBe("openai");
165
+ expect(cfg.uri.model).toBe("gpt-4");
166
+ });
167
+
168
+ it("throws when no URI and no LLM_PROVIDER env", () => {
169
+ expect(() => loadConfig()).toThrow(/no LLM URI provided/);
170
+ });
171
+
172
+ it("passes URI params to provider params", () => {
173
+ const cfg = loadConfig("openai://gpt-4?temperature=0.5");
174
+ expect(cfg.provider.params).toEqual({ temperature: "0.5" });
175
+ });
176
+
177
+ it("extracts api_key from URI params", () => {
178
+ const cfg = loadConfig("openai://gpt-4?api_key=sk-test123");
179
+ expect(cfg.provider.apiKey).toBe("sk-test123");
180
+ });
181
+
182
+ it("extracts base_url from URI params", () => {
183
+ const cfg = loadConfig(
184
+ "openai://gpt-4?base_url=https%3A%2F%2Fcustom.api.com"
185
+ );
186
+ expect(cfg.provider.baseURL).toBe("https://custom.api.com");
187
+ });
188
+
189
+ it("derives baseURL from uri.host", () => {
190
+ const cfg = loadConfig("ollama://localhost:11434/llama3");
191
+ expect(cfg.provider.baseURL).toBe("http://localhost:11434");
192
+ });
193
+
194
+ it("env LLM_API_KEY overrides URI api_key param", () => {
195
+ process.env["LLM_API_KEY"] = "env-key";
196
+ const cfg = loadConfig("openai://gpt-4?api_key=uri-key");
197
+ expect(cfg.provider.apiKey).toBe("env-key");
198
+ });
199
+
200
+ it("env LLM_BASE_URL overrides host-derived baseURL", () => {
201
+ process.env["LLM_BASE_URL"] = "https://override.com";
202
+ const cfg = loadConfig("ollama://localhost:11434/llama3");
203
+ expect(cfg.provider.baseURL).toBe("https://override.com");
204
+ });
205
+ });
206
+
207
+ // ---------------------------------------------------------------------------
208
+ // Registry
209
+ // ---------------------------------------------------------------------------
210
+
211
+ describe("registry", () => {
212
+ beforeEach(() => clearRegistry());
213
+
214
+ it("register + resolve returns a provider", () => {
215
+ const factory: Factory = (_cfg) =>
216
+ mockCompleteProvider({ content: "ok", role: "assistant" });
217
+ register("test", factory);
218
+ const provider = resolve("test://model-1");
219
+ expect(provider).toBeDefined();
220
+ expect(provider.complete).toBeDefined();
221
+ });
222
+
223
+ it("resolve throws ProviderNotFoundError for unknown scheme", () => {
224
+ expect(() => resolve("unknown://model")).toThrow(ProviderNotFoundError);
225
+ });
226
+
227
+ it("duplicate register throws", () => {
228
+ const factory: Factory = () => mockProvider();
229
+ register("dup", factory);
230
+ expect(() => register("dup", factory)).toThrow();
231
+ });
232
+ });
233
+
234
+ // ---------------------------------------------------------------------------
235
+ // Client
236
+ // ---------------------------------------------------------------------------
237
+
238
+ describe("Client", () => {
239
+ beforeEach(() => clearRegistry());
240
+
241
+ it("complete delegates to provider", async () => {
242
+ const resp: Response = {
243
+ content: "world",
244
+ role: "assistant",
245
+ usage: { promptTokens: 5, completionTokens: 3, totalTokens: 8 },
246
+ };
247
+ register("mock", () => mockCompleteProvider(resp));
248
+
249
+ const client = createLLM("mock://test-model");
250
+ const result = await client.complete(req());
251
+ expect(result.content).toBe("world");
252
+ expect(result.role).toBe("assistant");
253
+ });
254
+
255
+ it("stream throws CapabilityNotSupportedError when unsupported", async () => {
256
+ register("mock", () => mockProvider());
257
+ const client = createLLM("mock://m");
258
+ await expect(async () => {
259
+
260
+ for await (const _t of client.stream(req())) {
261
+ /* noop */
262
+ }
263
+ }).rejects.toThrow(CapabilityNotSupportedError);
264
+ });
265
+
266
+ it("capabilities reflects provider methods", () => {
267
+ register("mock", () =>
268
+ mockProvider({
269
+ complete: vi.fn(),
270
+ stream: vi.fn() as unknown as Provider["stream"],
271
+ })
272
+ );
273
+ const client = createLLM("mock://m");
274
+ const caps = client.capabilities();
275
+ expect(caps).toContain("complete");
276
+ expect(caps).toContain("stream");
277
+ expect(caps).not.toContain("callWithTools");
278
+ });
279
+
280
+ it("provider accessor returns the underlying provider", () => {
281
+ const p = mockProvider();
282
+ register("mock", () => p);
283
+ const client = createLLM("mock://m");
284
+ expect(client.provider()).toBe(p);
285
+ });
286
+
287
+ it("close delegates to provider", () => {
288
+ const p = mockProvider();
289
+ register("mock", () => p);
290
+ const client = createLLM("mock://m");
291
+ client.close();
292
+ expect(p.close).toHaveBeenCalled();
293
+ });
294
+
295
+ it("close also closes fallback providers used during operation", async () => {
296
+ const err5xx = new LLMError("down");
297
+ err5xx.statusCode = 500;
298
+ const primaryP = mockProvider({
299
+ complete: vi.fn().mockRejectedValue(err5xx),
300
+ });
301
+ const backupP = mockCompleteProvider({
302
+ content: "ok",
303
+ role: "assistant",
304
+ });
305
+
306
+ register("pri", () => primaryP);
307
+ register("bak", () => backupP);
308
+
309
+ const client = createLLM("pri://m", { fallback: ["bak://m2"] });
310
+ await client.complete(req());
311
+ client.close();
312
+ expect(primaryP.close).toHaveBeenCalled();
313
+ expect(backupP.close).toHaveBeenCalled();
314
+ });
315
+ });
316
+
317
+ // ---------------------------------------------------------------------------
318
+ // Fallback
319
+ // ---------------------------------------------------------------------------
320
+
321
+ describe("fallback", () => {
322
+ beforeEach(() => clearRegistry());
323
+
324
+ it("5xx triggers fallback to next provider", async () => {
325
+ const err5xx = new LLMError("server error");
326
+ err5xx.statusCode = 500;
327
+
328
+ register("primary", () =>
329
+ mockProvider({
330
+ complete: vi.fn().mockRejectedValue(err5xx),
331
+ })
332
+ );
333
+ register("backup", () =>
334
+ mockCompleteProvider({ content: "backup-ok", role: "assistant" })
335
+ );
336
+
337
+ const client = createLLM("primary://m", {
338
+ fallback: ["backup://fallback-model"],
339
+ });
340
+ const result = await client.complete(req());
341
+ expect(result.content).toBe("backup-ok");
342
+ });
343
+
344
+ it("4xx does NOT trigger fallback", async () => {
345
+ const err4xx = new LLMError("bad request");
346
+ err4xx.statusCode = 400;
347
+
348
+ register("primary", () =>
349
+ mockProvider({ complete: vi.fn().mockRejectedValue(err4xx) })
350
+ );
351
+ register("backup", () =>
352
+ mockCompleteProvider({ content: "should-not-reach", role: "assistant" })
353
+ );
354
+
355
+ const client = createLLM("primary://m", {
356
+ fallback: ["backup://fb"],
357
+ });
358
+ await expect(client.complete(req())).rejects.toThrow("bad request");
359
+ });
360
+
361
+ it("capability mismatch skips to next provider", async () => {
362
+ // Primary has no complete; backup does
363
+ register("nocap", () => mockProvider());
364
+ register("capable", () =>
365
+ mockCompleteProvider({ content: "from-capable", role: "assistant" })
366
+ );
367
+
368
+ const client = createLLM("nocap://m", {
369
+ fallback: ["capable://m2"],
370
+ });
371
+ const result = await client.complete(req());
372
+ expect(result.content).toBe("from-capable");
373
+ });
374
+
375
+ it("stream falls back on provider failure", async () => {
376
+ const err5xx = new LLMError("down");
377
+ err5xx.statusCode = 500;
378
+
379
+ async function* failStream(): AsyncIterable<Token> {
380
+ throw err5xx;
381
+ }
382
+ async function* okStream(): AsyncIterable<Token> {
383
+ yield { content: "streamed", done: true };
384
+ }
385
+
386
+ register("brokens", () =>
387
+ mockProvider({ stream: () => failStream() as any })
388
+ );
389
+ register("goods", () =>
390
+ mockProvider({ stream: () => okStream() as any })
391
+ );
392
+
393
+ const client = createLLM("brokens://m", {
394
+ fallback: ["goods://m2"],
395
+ });
396
+ const tokens: Token[] = [];
397
+ for await (const t of client.stream(req())) {
398
+ tokens.push(t);
399
+ }
400
+ expect(tokens).toHaveLength(1);
401
+ expect(tokens[0].content).toBe("streamed");
402
+ });
403
+
404
+ it("stream falls back when provider lacks stream capability", async () => {
405
+ async function* okStream(): AsyncIterable<Token> {
406
+ yield { content: "ok", done: true };
407
+ }
408
+
409
+ register("nostream", () => mockProvider());
410
+ register("hasstream", () =>
411
+ mockProvider({ stream: () => okStream() as any })
412
+ );
413
+
414
+ const client = createLLM("nostream://m", {
415
+ fallback: ["hasstream://m2"],
416
+ });
417
+ const tokens: Token[] = [];
418
+ for await (const t of client.stream(req())) {
419
+ tokens.push(t);
420
+ }
421
+ expect(tokens[0].content).toBe("ok");
422
+ });
423
+
424
+ it("all providers exhausted throws FallbackExhaustedError", async () => {
425
+ const err = new LLMError("down");
426
+ err.statusCode = 503;
427
+
428
+ register("a", () =>
429
+ mockProvider({ complete: vi.fn().mockRejectedValue(err) })
430
+ );
431
+ register("b", () =>
432
+ mockProvider({ complete: vi.fn().mockRejectedValue(err) })
433
+ );
434
+
435
+ const client = createLLM("a://m1", { fallback: ["b://m2"] });
436
+ await expect(client.complete(req())).rejects.toThrow(
437
+ FallbackExhaustedError
438
+ );
439
+ });
440
+ });
441
+
442
+ // ---------------------------------------------------------------------------
443
+ // Event hooks
444
+ // ---------------------------------------------------------------------------
445
+
446
+ describe("event hooks", () => {
447
+ beforeEach(() => clearRegistry());
448
+
449
+ it("onRequest fires before call", async () => {
450
+ const onRequest = vi.fn();
451
+ register("mock", () =>
452
+ mockCompleteProvider({ content: "ok", role: "assistant" })
453
+ );
454
+ const client = createLLM("mock://m", { onRequest });
455
+ await client.complete(req("ping"));
456
+ expect(onRequest).toHaveBeenCalledTimes(1);
457
+ expect(onRequest.mock.calls[0][0].messages[0].content).toBe("ping");
458
+ });
459
+
460
+ it("onResponse fires after call with duration", async () => {
461
+ const onResponse = vi.fn();
462
+ register("mock", () =>
463
+ mockCompleteProvider({ content: "ok", role: "assistant" })
464
+ );
465
+ const client = createLLM("mock://m", { onResponse });
466
+ await client.complete(req());
467
+ expect(onResponse).toHaveBeenCalledTimes(1);
468
+ expect(typeof onResponse.mock.calls[0][1]).toBe("number");
469
+ });
470
+
471
+ it("onError fires on failure", async () => {
472
+ const onError = vi.fn();
473
+ const err = new LLMError("boom");
474
+ err.statusCode = 400;
475
+ register("mock", () =>
476
+ mockProvider({ complete: vi.fn().mockRejectedValue(err) })
477
+ );
478
+ const client = createLLM("mock://m", { onError });
479
+ await expect(client.complete(req())).rejects.toThrow();
480
+ expect(onError).toHaveBeenCalledTimes(1);
481
+ });
482
+
483
+ it("onResponse fires for callWithTools", async () => {
484
+ const onResponse = vi.fn();
485
+ register("mock", () =>
486
+ mockProvider({
487
+ callWithTools: vi
488
+ .fn()
489
+ .mockResolvedValue({ content: "ok", toolCalls: [] }),
490
+ })
491
+ );
492
+ const client = createLLM("mock://m", { onResponse });
493
+ await client.callWithTools(req(), []);
494
+ expect(onResponse).toHaveBeenCalledTimes(1);
495
+ expect(typeof onResponse.mock.calls[0][1]).toBe("number");
496
+ });
497
+
498
+ it("onFallback fires when switching providers", async () => {
499
+ const onFallback = vi.fn();
500
+ const err = new LLMError("down");
501
+ err.statusCode = 502;
502
+
503
+ register("a", () =>
504
+ mockProvider({ complete: vi.fn().mockRejectedValue(err) })
505
+ );
506
+ register("b", () =>
507
+ mockCompleteProvider({ content: "ok", role: "assistant" })
508
+ );
509
+
510
+ const client = createLLM("a://m", {
511
+ fallback: ["b://m2"],
512
+ onFallback,
513
+ });
514
+ await client.complete(req());
515
+ expect(onFallback).toHaveBeenCalledWith(0, 1, err);
516
+ });
517
+ });
518
+
519
+ // ---------------------------------------------------------------------------
520
+ // Error types + isFallbackable
521
+ // ---------------------------------------------------------------------------
522
+
523
+ describe("error types", () => {
524
+ it("LLMError is instanceof Error", () => {
525
+ const e = new LLMError("test");
526
+ expect(e).toBeInstanceOf(Error);
527
+ expect(e).toBeInstanceOf(LLMError);
528
+ expect(e.message).toBe("test");
529
+ });
530
+
531
+ it("ProviderNotFoundError has scheme", () => {
532
+ const e = new ProviderNotFoundError("openai");
533
+ expect(e.scheme).toBe("openai");
534
+ expect(e).toBeInstanceOf(LLMError);
535
+ });
536
+
537
+ it("CapabilityNotSupportedError has capability + provider", () => {
538
+ const e = new CapabilityNotSupportedError("stream", "ollama");
539
+ expect(e.capability).toBe("stream");
540
+ expect(e.provider).toBe("ollama");
541
+ });
542
+
543
+ it("AuthError has provider", () => {
544
+ const e = new AuthError("openai");
545
+ expect(e.provider).toBe("openai");
546
+ });
547
+
548
+ it("RateLimitError has provider + optional retryAfter", () => {
549
+ const e = new RateLimitError("openai", 30);
550
+ expect(e.provider).toBe("openai");
551
+ expect(e.retryAfter).toBe(30);
552
+ });
553
+
554
+ it("ModelError has model + provider", () => {
555
+ const e = new ModelError("gpt-5", "openai");
556
+ expect(e.model).toBe("gpt-5");
557
+ expect(e.provider).toBe("openai");
558
+ });
559
+
560
+ it("FallbackExhaustedError has errors array", () => {
561
+ const errs = [new Error("a"), new Error("b")];
562
+ const e = new FallbackExhaustedError(errs);
563
+ expect(e.errors).toHaveLength(2);
564
+ });
565
+ });
566
+
567
+ describe("isFallbackable", () => {
568
+ it("returns true for 5xx LLMError", () => {
569
+ const e = new LLMError("server error");
570
+ e.statusCode = 500;
571
+ expect(isFallbackable(e)).toBe(true);
572
+ });
573
+
574
+ it("returns true for 502", () => {
575
+ const e = new LLMError("bad gateway");
576
+ e.statusCode = 502;
577
+ expect(isFallbackable(e)).toBe(true);
578
+ });
579
+
580
+ it("returns false for 4xx", () => {
581
+ const e = new LLMError("not found");
582
+ e.statusCode = 404;
583
+ expect(isFallbackable(e)).toBe(false);
584
+ });
585
+
586
+ it("returns false for plain Error", () => {
587
+ expect(isFallbackable(new Error("plain"))).toBe(false);
588
+ });
589
+
590
+ it("returns true for RateLimitError (429)", () => {
591
+ const e = new RateLimitError("openai");
592
+ expect(isFallbackable(e)).toBe(true);
593
+ });
594
+
595
+ it("returns true for connection/timeout errors (LLMError)", () => {
596
+ const e = new LLMError("ECONNREFUSED");
597
+ e.code = "ECONNREFUSED";
598
+ expect(isFallbackable(e)).toBe(true);
599
+ });
600
+
601
+ it("returns true for NodeJS.ErrnoException with ECONNREFUSED", () => {
602
+ const e = new Error("connect ECONNREFUSED") as Error & { code: string };
603
+ e.code = "ECONNREFUSED";
604
+ expect(isFallbackable(e)).toBe(true);
605
+ });
606
+
607
+ it("returns true for NodeJS.ErrnoException with ETIMEDOUT", () => {
608
+ const e = new Error("connect ETIMEDOUT") as Error & { code: string };
609
+ e.code = "ETIMEDOUT";
610
+ expect(isFallbackable(e)).toBe(true);
611
+ });
612
+ });