@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
package/src/llm.ts ADDED
@@ -0,0 +1,577 @@
1
+ /**
2
+ * @packageDocumentation
3
+ *
4
+ * LLM client facade — mirrors Go `llm` package interfaces as TS types.
5
+ *
6
+ * Provides URI parsing, config loading, provider registry, Client facade
7
+ * with fallback, and typed errors. Adapter implementations (OpenAI,
8
+ * Anthropic, Ollama) are deferred; register them via {@link register}.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * import { createLLM, register } from '@hop-top/kit/llm';
13
+ *
14
+ * register('mock', (cfg) => ({ complete: async (r) => ({ content: 'hi', role: 'assistant' }), close() {} }));
15
+ * const client = createLLM('mock://model-1');
16
+ * const resp = await client.complete({ messages: [{ role: 'user', content: 'hello' }] });
17
+ * ```
18
+ */
19
+
20
+ // ─── Data types ──────────────────────────────────────────────────────────────
21
+
22
+ export interface Message {
23
+ role: string;
24
+ content: string;
25
+ }
26
+
27
+ export interface Request {
28
+ messages: Message[];
29
+ model?: string;
30
+ temperature?: number;
31
+ maxTokens?: number;
32
+ stopSequences?: string[];
33
+ extensions?: Record<string, unknown>;
34
+ }
35
+
36
+ export interface Response {
37
+ content: string;
38
+ role: string;
39
+ usage?: Usage;
40
+ finishReason?: string;
41
+ }
42
+
43
+ export interface Usage {
44
+ promptTokens: number;
45
+ completionTokens: number;
46
+ totalTokens: number;
47
+ }
48
+
49
+ export interface Token {
50
+ content: string;
51
+ done: boolean;
52
+ }
53
+
54
+ export interface ToolDef {
55
+ name: string;
56
+ description: string;
57
+ parameters: unknown;
58
+ }
59
+
60
+ export interface ToolCall {
61
+ id: string;
62
+ name: string;
63
+ arguments: unknown;
64
+ }
65
+
66
+ export interface ToolResponse {
67
+ content: string;
68
+ toolCalls: ToolCall[];
69
+ }
70
+
71
+ // ─── Core interfaces ─────────────────────────────────────────────────────────
72
+
73
+ export interface Completer {
74
+ complete(req: Request): Promise<Response>;
75
+ }
76
+
77
+ export interface Streamer {
78
+ stream(req: Request): AsyncIterable<Token>;
79
+ }
80
+
81
+ export interface ToolCaller {
82
+ callWithTools(req: Request, tools: ToolDef[]): Promise<ToolResponse>;
83
+ }
84
+
85
+ export interface Provider
86
+ extends Partial<Completer & Streamer & ToolCaller> {
87
+ close(): void;
88
+ }
89
+
90
+ // ─── URI + Config ────────────────────────────────────────────────────────────
91
+
92
+ export interface URI {
93
+ scheme: string;
94
+ model: string;
95
+ host?: string;
96
+ params?: Record<string, string>;
97
+ }
98
+
99
+ export interface ProviderConfig {
100
+ apiKey?: string;
101
+ baseURL?: string;
102
+ model: string;
103
+ params?: Record<string, string>;
104
+ extras?: Record<string, unknown>;
105
+ }
106
+
107
+ export interface ResolvedConfig {
108
+ uri: URI;
109
+ provider: ProviderConfig;
110
+ fallbacks: string[];
111
+ }
112
+
113
+ // ─── Errors ──────────────────────────────────────────────────────────────────
114
+
115
+ export class LLMError extends Error {
116
+ statusCode?: number;
117
+ code?: string;
118
+
119
+ constructor(message: string) {
120
+ super(message);
121
+ this.name = "LLMError";
122
+ Object.setPrototypeOf(this, new.target.prototype);
123
+ }
124
+ }
125
+
126
+ export class ProviderNotFoundError extends LLMError {
127
+ scheme: string;
128
+
129
+ constructor(scheme: string) {
130
+ super(`provider not found: ${scheme}`);
131
+ this.name = "ProviderNotFoundError";
132
+ this.scheme = scheme;
133
+ }
134
+ }
135
+
136
+ export class CapabilityNotSupportedError extends LLMError {
137
+ capability: string;
138
+ provider: string;
139
+
140
+ constructor(capability: string, provider: string) {
141
+ super(
142
+ `capability "${capability}" not supported by provider "${provider}"`
143
+ );
144
+ this.name = "CapabilityNotSupportedError";
145
+ this.capability = capability;
146
+ this.provider = provider;
147
+ }
148
+ }
149
+
150
+ export class AuthError extends LLMError {
151
+ provider: string;
152
+
153
+ constructor(provider: string) {
154
+ super(`authentication failed for provider: ${provider}`);
155
+ this.name = "AuthError";
156
+ this.provider = provider;
157
+ }
158
+ }
159
+
160
+ export class RateLimitError extends LLMError {
161
+ provider: string;
162
+ retryAfter?: number;
163
+
164
+ constructor(provider: string, retryAfter?: number) {
165
+ super(`rate limit exceeded for provider: ${provider}`);
166
+ this.name = "RateLimitError";
167
+ this.provider = provider;
168
+ this.retryAfter = retryAfter;
169
+ this.statusCode = 429;
170
+ }
171
+ }
172
+
173
+ export class ModelError extends LLMError {
174
+ model: string;
175
+ provider: string;
176
+
177
+ constructor(model: string, provider: string) {
178
+ super(`model "${model}" not available on provider "${provider}"`);
179
+ this.name = "ModelError";
180
+ this.model = model;
181
+ this.provider = provider;
182
+ }
183
+ }
184
+
185
+ export class FallbackExhaustedError extends LLMError {
186
+ errors: Error[];
187
+
188
+ constructor(errors: Error[]) {
189
+ super(
190
+ `all providers exhausted (${errors.length} failures)`
191
+ );
192
+ this.name = "FallbackExhaustedError";
193
+ this.errors = errors;
194
+ }
195
+ }
196
+
197
+ /**
198
+ * Returns true when `err` should trigger a fallback attempt.
199
+ *
200
+ * Fallbackable conditions:
201
+ * - LLMError with statusCode >= 500
202
+ * - RateLimitError (429)
203
+ * - Connection/timeout errors (ECONNREFUSED, ETIMEDOUT, ECONNRESET)
204
+ */
205
+ export function isFallbackable(err: Error): boolean {
206
+ if (err instanceof RateLimitError) return true;
207
+ if (err instanceof LLMError) {
208
+ if (err.code && isConnectionError(err.code)) return true;
209
+ if (err.statusCode !== undefined && err.statusCode >= 500) return true;
210
+ return false;
211
+ }
212
+ // Handle NodeJS.ErrnoException (e.g. ECONNREFUSED, ETIMEDOUT)
213
+ const code = (err as { code?: string }).code;
214
+ if (code && isConnectionError(code)) return true;
215
+ return false;
216
+ }
217
+
218
+ const CONNECTION_CODES = new Set([
219
+ "ECONNREFUSED",
220
+ "ETIMEDOUT",
221
+ "ECONNRESET",
222
+ "ENETUNREACH",
223
+ "EHOSTUNREACH",
224
+ ]);
225
+
226
+ function isConnectionError(code: string): boolean {
227
+ return CONNECTION_CODES.has(code);
228
+ }
229
+
230
+ // ─── URI parsing ─────────────────────────────────────────────────────────────
231
+
232
+ /**
233
+ * Parses an LLM URI string into its components.
234
+ *
235
+ * Format: `scheme://[host[:port]/]model[?params]`
236
+ *
237
+ * When the path portion contains a host:port prefix (detected by the
238
+ * presence of a numeric port), the first segment is treated as host.
239
+ * Otherwise the entire path is the model name.
240
+ */
241
+ export function parseURI(raw: string): URI {
242
+ const sep = "://";
243
+ const idx = raw.indexOf(sep);
244
+ if (idx < 0) {
245
+ throw new LLMError(`invalid LLM URI (missing "://"): ${raw}`);
246
+ }
247
+
248
+ const scheme = raw.slice(0, idx);
249
+ if (!scheme) {
250
+ throw new LLMError(`invalid LLM URI (empty scheme): ${raw}`);
251
+ }
252
+
253
+ let rest = raw.slice(idx + sep.length);
254
+ if (!rest) {
255
+ throw new LLMError(`invalid LLM URI (empty model): ${raw}`);
256
+ }
257
+
258
+ // Extract query params
259
+ let params: Record<string, string> | undefined;
260
+ const qIdx = rest.indexOf("?");
261
+ if (qIdx >= 0) {
262
+ const qs = rest.slice(qIdx + 1);
263
+ rest = rest.slice(0, qIdx);
264
+ params = {};
265
+ for (const pair of qs.split("&")) {
266
+ const eqIdx = pair.indexOf("=");
267
+ if (eqIdx > 0) {
268
+ params[pair.slice(0, eqIdx)] = decodeURIComponent(
269
+ pair.slice(eqIdx + 1)
270
+ );
271
+ }
272
+ }
273
+ }
274
+
275
+ if (!rest) {
276
+ throw new LLMError(`invalid LLM URI (empty model): ${raw}`);
277
+ }
278
+
279
+ // Detect host:port pattern.
280
+ // If first segment matches `word:digits`, treat it as host.
281
+ let host: string | undefined;
282
+ let model: string;
283
+
284
+ const hostPortMatch = rest.match(/^([^/]+:\d+)\/(.+)$/);
285
+ if (hostPortMatch) {
286
+ host = hostPortMatch[1];
287
+ model = hostPortMatch[2];
288
+ } else {
289
+ model = rest;
290
+ }
291
+
292
+ const uri: URI = { scheme, model };
293
+ if (host) uri.host = host;
294
+ if (params && Object.keys(params).length > 0) uri.params = params;
295
+ return uri;
296
+ }
297
+
298
+ // ─── Config loading ──────────────────────────────────────────────────────────
299
+
300
+ /**
301
+ * Builds a {@link ResolvedConfig} from a URI string + env vars.
302
+ *
303
+ * When `uriStr` is empty/undefined, falls back to `LLM_PROVIDER`
304
+ * env var as a full default URI. If neither is provided, throws.
305
+ *
306
+ * URI query params `api_key` and `base_url` populate provider
307
+ * config. If `uri.host` is set, it derives a baseURL. Env vars
308
+ * `LLM_API_KEY` and `LLM_BASE_URL` override last.
309
+ *
310
+ * Env vars:
311
+ * - `LLM_PROVIDER` — full default URI when no arg provided
312
+ * - `LLM_API_KEY` — overrides provider API key
313
+ * - `LLM_BASE_URL` — overrides provider base URL
314
+ * - `LLM_FALLBACK` — comma-separated fallback URIs
315
+ */
316
+ export function loadConfig(uriStr?: string): ResolvedConfig {
317
+ const effective = uriStr || process.env["LLM_PROVIDER"];
318
+ if (!effective) {
319
+ throw new LLMError(
320
+ "no LLM URI provided and LLM_PROVIDER env var is not set"
321
+ );
322
+ }
323
+
324
+ const uri = parseURI(effective);
325
+
326
+ const fallbackEnv = process.env["LLM_FALLBACK"];
327
+ const fallbacks = fallbackEnv
328
+ ? fallbackEnv.split(",").map((s) => s.trim()).filter(Boolean)
329
+ : [];
330
+
331
+ const provider: ProviderConfig = {
332
+ model: uri.model,
333
+ };
334
+ if (uri.params) provider.params = { ...uri.params };
335
+
336
+ // Extract api_key and base_url from URI query params
337
+ if (uri.params?.api_key) {
338
+ provider.apiKey = uri.params.api_key;
339
+ }
340
+ if (uri.params?.base_url) {
341
+ provider.baseURL = uri.params.base_url;
342
+ }
343
+
344
+ // Derive baseURL from host if present
345
+ if (uri.host) {
346
+ provider.baseURL = `http://${uri.host}`;
347
+ }
348
+
349
+ // Env var overrides apply LAST
350
+ const envApiKey = process.env["LLM_API_KEY"] || undefined;
351
+ const envBaseURL = process.env["LLM_BASE_URL"] || undefined;
352
+ if (envApiKey) provider.apiKey = envApiKey;
353
+ if (envBaseURL) provider.baseURL = envBaseURL;
354
+
355
+ return { uri, provider, fallbacks };
356
+ }
357
+
358
+ // ─── Registry ────────────────────────────────────────────────────────────────
359
+
360
+ export type Factory = (cfg: ResolvedConfig) => Provider;
361
+
362
+ const registry = new Map<string, Factory>();
363
+
364
+ /** Register a provider factory for the given URI scheme. */
365
+ export function register(scheme: string, factory: Factory): void {
366
+ if (registry.has(scheme)) {
367
+ throw new LLMError(`provider already registered for scheme: ${scheme}`);
368
+ }
369
+ registry.set(scheme, factory);
370
+ }
371
+
372
+ /** Resolve a URI to a Provider instance via the registry. */
373
+ export function resolve(uriStr: string): Provider {
374
+ const cfg = loadConfig(uriStr);
375
+ const factory = registry.get(cfg.uri.scheme);
376
+ if (!factory) {
377
+ throw new ProviderNotFoundError(cfg.uri.scheme);
378
+ }
379
+ return factory(cfg);
380
+ }
381
+
382
+ /** Clear the registry (for tests). */
383
+ export function clearRegistry(): void {
384
+ registry.clear();
385
+ }
386
+
387
+ // ─── Client ──────────────────────────────────────────────────────────────────
388
+
389
+ export interface ClientOptions {
390
+ fallback?: string[];
391
+ onRequest?: (req: Request) => void;
392
+ onResponse?: (resp: Response, durationMs: number) => void;
393
+ onError?: (err: Error) => void;
394
+ onFallback?: (from: number, to: number, err: Error) => void;
395
+ }
396
+
397
+ export interface Client {
398
+ complete(req: Request): Promise<Response>;
399
+ stream(req: Request): AsyncIterable<Token>;
400
+ callWithTools(req: Request, tools: ToolDef[]): Promise<ToolResponse>;
401
+ capabilities(): string[];
402
+ provider(): Provider;
403
+ close(): void;
404
+ }
405
+
406
+ /**
407
+ * Create an LLM client with fallback support and event hooks.
408
+ *
409
+ * The returned Client delegates to the provider resolved from `uri`.
410
+ * On fallbackable errors, it tries each fallback URI in order.
411
+ */
412
+ export function createLLM(uri: string, opts?: ClientOptions): Client {
413
+ const cfg = loadConfig(uri);
414
+
415
+ // Merge fallbacks: opts > env > none
416
+ const fallbackURIs = opts?.fallback ?? cfg.fallbacks;
417
+
418
+ // Resolve primary; cache fallback providers for close()
419
+ const primary = resolve(uri);
420
+ const allURIs = [uri, ...fallbackURIs];
421
+ const resolvedProviders = new Map<number, Provider>();
422
+ resolvedProviders.set(0, primary);
423
+
424
+ function resolveAt(index: number): Provider {
425
+ let p = resolvedProviders.get(index);
426
+ if (!p) {
427
+ p = resolve(allURIs[index]);
428
+ resolvedProviders.set(index, p);
429
+ }
430
+ return p;
431
+ }
432
+
433
+ async function withFallback<T>(
434
+ op: string,
435
+ fn: (p: Provider) => Promise<T>
436
+ ): Promise<T> {
437
+ const errors: Error[] = [];
438
+ for (let i = 0; i < allURIs.length; i++) {
439
+ try {
440
+ const p = resolveAt(i);
441
+ if (
442
+ !(op in p) ||
443
+ typeof (p as unknown as Record<string, unknown>)[op] !== "function"
444
+ ) {
445
+ throw new CapabilityNotSupportedError(
446
+ op,
447
+ parseURI(allURIs[i]).scheme
448
+ );
449
+ }
450
+ return await fn(p);
451
+ } catch (err) {
452
+ const e = err instanceof Error ? err : new Error(String(err));
453
+ errors.push(e);
454
+ opts?.onError?.(e);
455
+
456
+ // CapabilityNotSupportedError: skip to next provider
457
+ const canContinue =
458
+ isFallbackable(e) || e instanceof CapabilityNotSupportedError;
459
+
460
+ if (!canContinue || i === allURIs.length - 1) {
461
+ if (errors.length > 1) {
462
+ throw new FallbackExhaustedError(errors);
463
+ }
464
+ throw e;
465
+ }
466
+ opts?.onFallback?.(i, i + 1, e);
467
+ }
468
+ }
469
+ throw new FallbackExhaustedError(errors);
470
+ }
471
+
472
+ return {
473
+ async complete(request: Request): Promise<Response> {
474
+ opts?.onRequest?.(request);
475
+ const start = Date.now();
476
+ const resp = await withFallback("complete", (p) =>
477
+ p.complete!(request)
478
+ );
479
+ opts?.onResponse?.(resp, Date.now() - start);
480
+ return resp;
481
+ },
482
+
483
+ stream(request: Request): AsyncIterable<Token> {
484
+ // Route stream through fallback. On creation or first-token
485
+ // failure with a fallbackable/capability error, try next provider.
486
+ return {
487
+ [Symbol.asyncIterator]() {
488
+ let inner: AsyncIterator<Token> | null = null;
489
+ let initialized = false;
490
+
491
+ return {
492
+ async next(): Promise<IteratorResult<Token>> {
493
+ if (!initialized) {
494
+ initialized = true;
495
+ opts?.onRequest?.(request);
496
+
497
+ const errors: Error[] = [];
498
+ for (let i = 0; i < allURIs.length; i++) {
499
+ try {
500
+ const p = resolveAt(i);
501
+ if (
502
+ !("stream" in p) ||
503
+ typeof p.stream !== "function"
504
+ ) {
505
+ throw new CapabilityNotSupportedError(
506
+ "stream",
507
+ parseURI(allURIs[i]).scheme
508
+ );
509
+ }
510
+ const iterable = p.stream(request);
511
+ const iter = iterable[Symbol.asyncIterator]();
512
+ // Attempt first read to detect immediate failures
513
+ const first = await iter.next();
514
+ inner = iter;
515
+ return first;
516
+ } catch (err) {
517
+ const e =
518
+ err instanceof Error
519
+ ? err
520
+ : new Error(String(err));
521
+ errors.push(e);
522
+ opts?.onError?.(e);
523
+ const canContinue =
524
+ isFallbackable(e) ||
525
+ e instanceof CapabilityNotSupportedError;
526
+ if (!canContinue || i === allURIs.length - 1) {
527
+ if (errors.length > 1)
528
+ throw new FallbackExhaustedError(errors);
529
+ throw e;
530
+ }
531
+ opts?.onFallback?.(i, i + 1, e);
532
+ }
533
+ }
534
+ throw new FallbackExhaustedError(errors);
535
+ }
536
+ return inner!.next();
537
+ },
538
+ };
539
+ },
540
+ };
541
+ },
542
+
543
+ async callWithTools(
544
+ request: Request,
545
+ tools: ToolDef[]
546
+ ): Promise<ToolResponse> {
547
+ opts?.onRequest?.(request);
548
+ const start = Date.now();
549
+ const resp = await withFallback("callWithTools", (p) =>
550
+ p.callWithTools!(request, tools)
551
+ );
552
+ opts?.onResponse?.(
553
+ { content: resp.content, role: "assistant" },
554
+ Date.now() - start
555
+ );
556
+ return resp;
557
+ },
558
+
559
+ capabilities(): string[] {
560
+ const caps: string[] = [];
561
+ if (primary.complete) caps.push("complete");
562
+ if (primary.stream) caps.push("stream");
563
+ if (primary.callWithTools) caps.push("callWithTools");
564
+ return caps;
565
+ },
566
+
567
+ provider(): Provider {
568
+ return primary;
569
+ },
570
+
571
+ close(): void {
572
+ for (const p of resolvedProviders.values()) {
573
+ p.close();
574
+ }
575
+ },
576
+ };
577
+ }
@@ -0,0 +1,145 @@
1
+ import { describe, it, expect, vi } from 'vitest';
2
+ import { createLogger } from './log';
3
+
4
+ function makeStderr(): { write: ReturnType<typeof vi.fn>; captured: () => string } {
5
+ const chunks: string[] = [];
6
+ const write = vi.fn((chunk: string) => { chunks.push(chunk); return true; });
7
+ return { write, captured: () => chunks.join('') };
8
+ }
9
+
10
+ // Patch process.stderr.write for tests
11
+ function withStderr(fn: (captured: () => string) => void) {
12
+ const orig = process.stderr.write;
13
+ const s = makeStderr();
14
+ process.stderr.write = s.write as unknown as typeof process.stderr.write;
15
+ try {
16
+ fn(s.captured);
17
+ } finally {
18
+ process.stderr.write = orig;
19
+ }
20
+ }
21
+
22
+ // ---------------------------------------------------------------------------
23
+ // Format
24
+ // ---------------------------------------------------------------------------
25
+
26
+ describe('log format', () => {
27
+ it('writes LEVEL msg to stderr', () => {
28
+ withStderr((captured) => {
29
+ const log = createLogger();
30
+ log.info('hello');
31
+ const out = captured();
32
+ expect(out).toContain('INFO');
33
+ expect(out).toContain('hello');
34
+ expect(out).toMatch(/\n$/);
35
+ });
36
+ });
37
+
38
+ it('formats key=val pairs', () => {
39
+ withStderr((captured) => {
40
+ const log = createLogger();
41
+ log.info('start', 'port', 8080, 'host', 'localhost');
42
+ const out = captured();
43
+ expect(out).toContain('port=8080');
44
+ expect(out).toContain('host=localhost');
45
+ });
46
+ });
47
+
48
+ it('uses correct level prefixes', () => {
49
+ withStderr((captured) => {
50
+ const log = createLogger();
51
+ log.error('e');
52
+ log.warn('w');
53
+ log.info('i');
54
+ log.debug('d');
55
+ const out = captured();
56
+ expect(out).toContain('ERRO');
57
+ expect(out).toContain('WARN');
58
+ expect(out).toContain('INFO');
59
+ expect(out).toContain('DEBU');
60
+ });
61
+ });
62
+ });
63
+
64
+ // ---------------------------------------------------------------------------
65
+ // Color
66
+ // ---------------------------------------------------------------------------
67
+
68
+ describe('log color', () => {
69
+ it('includes ANSI codes by default', () => {
70
+ withStderr((captured) => {
71
+ const log = createLogger();
72
+ log.error('fail');
73
+ expect(captured()).toContain('\x1b[');
74
+ });
75
+ });
76
+
77
+ it('strips ANSI when noColor=true', () => {
78
+ withStderr((captured) => {
79
+ const log = createLogger({ noColor: true });
80
+ log.error('fail');
81
+ expect(captured()).not.toContain('\x1b[');
82
+ });
83
+ });
84
+ });
85
+
86
+ // ---------------------------------------------------------------------------
87
+ // Quiet
88
+ // ---------------------------------------------------------------------------
89
+
90
+ describe('log quiet', () => {
91
+ it('suppresses info when quiet=true', () => {
92
+ withStderr((captured) => {
93
+ const log = createLogger({ quiet: true });
94
+ log.info('hidden');
95
+ expect(captured()).toBe('');
96
+ });
97
+ });
98
+
99
+ it('suppresses debug when quiet=true', () => {
100
+ withStderr((captured) => {
101
+ const log = createLogger({ quiet: true });
102
+ log.debug('hidden');
103
+ expect(captured()).toBe('');
104
+ });
105
+ });
106
+
107
+ it('still shows warn when quiet=true', () => {
108
+ withStderr((captured) => {
109
+ const log = createLogger({ quiet: true });
110
+ log.warn('visible');
111
+ expect(captured()).toContain('WARN');
112
+ });
113
+ });
114
+
115
+ it('still shows error when quiet=true', () => {
116
+ withStderr((captured) => {
117
+ const log = createLogger({ quiet: true });
118
+ log.error('visible');
119
+ expect(captured()).toContain('ERRO');
120
+ });
121
+ });
122
+ });
123
+
124
+ // ---------------------------------------------------------------------------
125
+ // Key-value edge cases
126
+ // ---------------------------------------------------------------------------
127
+
128
+ describe('log key-value edge cases', () => {
129
+ it('quotes values with spaces', () => {
130
+ withStderr((captured) => {
131
+ const log = createLogger({ noColor: true });
132
+ log.info('msg', 'path', '/my dir/file');
133
+ expect(captured()).toContain('path="/my dir/file"');
134
+ });
135
+ });
136
+
137
+ it('handles odd number of keyvals (trailing key)', () => {
138
+ withStderr((captured) => {
139
+ const log = createLogger({ noColor: true });
140
+ log.info('msg', 'orphan');
141
+ const out = captured();
142
+ expect(out).toContain('orphan');
143
+ });
144
+ });
145
+ });