@hop-top/kit 0.5.0-alpha.3 → 0.5.0-alpha.5

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 (188) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/LICENSE +1 -1
  3. package/README.md +47 -575
  4. package/dist/{aim-CTp-kJW2.d.ts → aim-DZHwwiIc.d.ts} +1 -1
  5. package/dist/aim.d.ts +1 -1
  6. package/dist/aim.js +13 -414
  7. package/dist/{alias-dhhr08Ei.d.ts → alias-BOj0-VAr.d.ts} +1 -1
  8. package/dist/alias.d.ts +1 -1
  9. package/dist/alias.js +18 -206
  10. package/dist/{api-miiso81x.d.ts → api-DAexsu2H.d.ts} +1 -1
  11. package/dist/api.d.ts +1 -1
  12. package/dist/api.js +10 -164
  13. package/dist/auth.js +6 -40
  14. package/dist/chunk-3FIKGFKI.js +54 -0
  15. package/dist/chunk-4UE5TCMQ.js +104 -0
  16. package/dist/chunk-6HFAEZ52.js +29 -0
  17. package/dist/chunk-6SVOHNIC.js +17 -0
  18. package/dist/chunk-72XZWQX7.js +504 -0
  19. package/dist/chunk-ABQSE7AI.js +513 -0
  20. package/dist/chunk-BDNNPRX6.js +41 -0
  21. package/dist/chunk-BRNEKPWX.js +37 -0
  22. package/dist/chunk-CSJWB6D3.js +151 -0
  23. package/dist/chunk-GGWJRWWA.js +309 -0
  24. package/dist/chunk-IQXEISMC.js +142 -0
  25. package/dist/chunk-IXVQ62NZ.js +334 -0
  26. package/dist/chunk-JTMPNXVQ.js +1491 -0
  27. package/dist/chunk-KVG7YCTS.js +115 -0
  28. package/dist/chunk-L23O2FFE.js +51 -0
  29. package/dist/chunk-MQXYDYRD.js +968 -0
  30. package/dist/chunk-MUIQVU6E.js +251 -0
  31. package/dist/chunk-POR5L2DG.js +247 -0
  32. package/dist/chunk-PSFYJGDG.js +1445 -0
  33. package/dist/chunk-QJVSKKRQ.js +369 -0
  34. package/dist/chunk-QPUCXQXT.js +67 -0
  35. package/dist/chunk-R5U7XKVJ.js +16 -0
  36. package/dist/chunk-S45UHXQF.js +182 -0
  37. package/dist/chunk-T46YPHKN.js +669 -0
  38. package/dist/chunk-UKZIAQA7.js +26 -0
  39. package/dist/chunk-WBVO43HU.js +355 -0
  40. package/dist/chunk-WUOAQVOA.js +86 -0
  41. package/dist/chunk-WWUKGJB5.js +90 -0
  42. package/dist/chunk-YGYQUFGY.js +219 -0
  43. package/dist/chunk-YOBAUCVN.js +583 -0
  44. package/dist/chunk-ZC5TZYZJ.js +609 -0
  45. package/dist/{cli-DLygZLi9.d.ts → cli-8rfITnv4.d.ts} +13 -4
  46. package/dist/cli.d.ts +4 -4
  47. package/dist/cli.js +51 -1057
  48. package/dist/{config-BUY7_W2n.d.ts → config-Bm9fBXch.d.ts} +35 -4
  49. package/dist/config.d.ts +1 -1
  50. package/dist/config.js +6 -78
  51. package/dist/errcorrect.js +8 -68
  52. package/dist/{error-DISJKeDu.d.ts → error-Do8Qji43.d.ts} +88 -1
  53. package/dist/id/index.d.ts +1 -1
  54. package/dist/id/index.js +14 -65
  55. package/dist/{index-MLrRDvEG.d.ts → index-B-pqGHhU.d.ts} +113 -19
  56. package/dist/{index-Bc5c7Ty5.d.ts → index-DEyjGoo2.d.ts} +1 -1
  57. package/dist/{index-QSffbLnj.d.ts → index-VLDcI5NF.d.ts} +3 -2
  58. package/dist/index.d.ts +18 -15
  59. package/dist/index.js +39 -6722
  60. package/dist/llm-DYuR7_uX.d.ts +1069 -0
  61. package/dist/llm-anthropic-Cd_I2xXB.d.ts +67 -0
  62. package/dist/llm-anthropic.d.ts +2 -0
  63. package/dist/llm-anthropic.js +13 -0
  64. package/dist/llm-openai-DyFrucmV.d.ts +87 -0
  65. package/dist/llm-openai.d.ts +2 -0
  66. package/dist/llm-openai.js +19 -0
  67. package/dist/llm.d.ts +1 -1
  68. package/dist/llm.js +101 -356
  69. package/dist/mcp/index.d.ts +2 -1
  70. package/dist/mcp/index.js +155 -1453
  71. package/dist/{netpolicy-asvCfwi8.d.ts → netpolicy-Brx5XZUB.d.ts} +16 -3
  72. package/dist/netpolicy.d.ts +1 -1
  73. package/dist/netpolicy.js +25 -118
  74. package/dist/{output-4aXs91GY.d.ts → output-CjZWmL8s.d.ts} +28 -4
  75. package/dist/output.d.ts +2 -2
  76. package/dist/output.js +137 -971
  77. package/dist/progress.js +6 -55
  78. package/dist/provenance.js +6 -31
  79. package/dist/routellm-B0nv59mH.d.ts +111 -0
  80. package/dist/routellm.d.ts +2 -2
  81. package/dist/routellm.js +13 -255
  82. package/dist/{rpc-D5xLEf8V.d.ts → rpc-D31Lg0Kc.d.ts} +1 -1
  83. package/dist/rpc.d.ts +2 -2
  84. package/dist/rpc.js +4 -98
  85. package/dist/safety.js +6 -43
  86. package/dist/scope.js +20 -377
  87. package/dist/{serve-DE-jscpb.d.ts → serve-D8yWMrTc.d.ts} +2 -2
  88. package/dist/serve.d.ts +2 -2
  89. package/dist/serve.js +75 -1019
  90. package/dist/sqlstore.js +6 -39
  91. package/dist/stream.js +8 -51
  92. package/dist/telemetry/index.js +24 -608
  93. package/dist/tui/index.d.ts +5 -5
  94. package/dist/tui/index.js +17 -374
  95. package/dist/upgrade.js +6 -114
  96. package/dist/xdg.js +14 -128
  97. package/package.json +130 -25
  98. package/src/README.md +15 -0
  99. package/src/cli.help-command.test.ts +105 -0
  100. package/src/cli.test.ts +95 -1
  101. package/src/cli.ts +78 -13
  102. package/src/completion-values.test.ts +10 -10
  103. package/src/compliance.test.ts +196 -2
  104. package/src/compliance.ts +440 -20
  105. package/src/config.test.ts +187 -1
  106. package/src/config.ts +173 -7
  107. package/src/gen/crud_pb.ts +7 -7
  108. package/src/id/README.md +38 -0
  109. package/src/id/contract.test.ts +1 -1
  110. package/src/id/index.test.ts +1 -1
  111. package/src/id/index.ts +3 -2
  112. package/src/index.test.ts +12 -0
  113. package/src/index.ts +2 -0
  114. package/src/llm-anthropic.conformance.test.ts +1135 -0
  115. package/src/llm-anthropic.test.ts +152 -0
  116. package/src/llm-anthropic.ts +940 -0
  117. package/src/llm-choice-hermetic.test.ts +335 -0
  118. package/src/llm-config.test.ts +232 -0
  119. package/src/llm-config.ts +106 -0
  120. package/src/llm-endpoint.ts +254 -0
  121. package/src/llm-error.ts +17 -0
  122. package/src/llm-errors.ts +152 -0
  123. package/src/llm-file.ts +126 -0
  124. package/src/llm-http.ts +317 -0
  125. package/src/llm-keys.ts +167 -0
  126. package/src/llm-media.conformance.test.ts +87 -0
  127. package/src/llm-media.test.ts +279 -0
  128. package/src/llm-media.ts +322 -0
  129. package/src/llm-openai.conformance.test.ts +407 -0
  130. package/src/llm-openai.test.ts +510 -0
  131. package/src/llm-openai.ts +708 -0
  132. package/src/llm-payload.ts +155 -0
  133. package/src/llm-quote.ts +46 -0
  134. package/src/llm-routellm.conformance.test.ts +44 -0
  135. package/src/llm-toolnames.conformance.test.ts +112 -0
  136. package/src/llm-toolnames.test.ts +132 -0
  137. package/src/llm-toolnames.ts +298 -0
  138. package/src/llm-uri.ts +99 -0
  139. package/src/llm.test.ts +43 -15
  140. package/src/llm.toolcall.test.ts +175 -0
  141. package/src/llm.ts +602 -190
  142. package/src/mcp/README.md +57 -0
  143. package/src/mcp/conformance.test.ts +24 -3
  144. package/src/mcp/dispatch.ts +4 -4
  145. package/src/mcp/identity.test.ts +166 -0
  146. package/src/mcp/identity.ts +72 -0
  147. package/src/mcp/index.ts +6 -0
  148. package/src/mcp/legacy.ts +21 -8
  149. package/src/mcp/mcp.test.ts +14 -4
  150. package/src/mcp/modern-confirm.ts +1 -1
  151. package/src/mcp/modern.ts +12 -11
  152. package/src/mcp/tasks.ts +1 -1
  153. package/src/mcp/types.ts +80 -8
  154. package/src/netpolicy.test.ts +78 -0
  155. package/src/netpolicy.ts +28 -3
  156. package/src/output/README.md +46 -0
  157. package/src/output/builtins.ts +5 -5
  158. package/src/output/error.ts +144 -1
  159. package/src/output/formatters/README.md +50 -0
  160. package/src/output.ts +24 -1
  161. package/src/published-types.test.ts +115 -0
  162. package/src/routellm.test.ts +209 -28
  163. package/src/routellm.toolcall.test.ts +521 -0
  164. package/src/routellm.ts +213 -177
  165. package/src/router/README.md +44 -0
  166. package/src/router/server.test.ts +41 -0
  167. package/src/router/server.ts +11 -0
  168. package/src/safety.test.ts +19 -9
  169. package/src/scope-defaults.json +29 -29
  170. package/src/serve.ts +1 -1
  171. package/src/telemetry/README.md +48 -0
  172. package/src/telemetry/client.ts +5 -5
  173. package/src/toolspec.test.ts +2 -2
  174. package/src/triton/README.md +34 -0
  175. package/src/tui/README.md +42 -0
  176. package/src/wizard.test.ts +7 -7
  177. package/test/llm/conformance-helpers.ts +100 -0
  178. package/test/output/dispatch.test.ts +1 -2
  179. package/test/output/error.test.ts +33 -2
  180. package/test/output/smoke-capture.ts +2 -2
  181. package/test/output/smoke.test.ts +2 -2
  182. package/test/output/taxonomy-contract.test.ts +148 -0
  183. package/test/setup-env.ts +16 -0
  184. package/tsconfig.json +3 -1
  185. package/tsconfig.test.json +10 -0
  186. package/vitest.config.ts +9 -0
  187. package/dist/llm-B5XUWH8T.d.ts +0 -231
  188. package/dist/routellm-PGSt2D1y.d.ts +0 -75
@@ -0,0 +1,254 @@
1
+ /**
2
+ * Where credentials may go: URI redaction, endpoint parsing, the
3
+ * plain-http and trusted-origin gates, and adapter declarations.
4
+ * Re-exported from `@hop-top/kit/llm`; mirrors Go `llm` (`RedactURI`,
5
+ * `CheckKeyEndpoint`, `CredentialsTrusted`).
6
+ *
7
+ * @internal
8
+ */
9
+
10
+ import { KeyEndpointError } from "./llm-errors";
11
+ import { providerBlock, readLLMFile } from "./llm-file";
12
+ import { isLoopback } from "./netpolicy";
13
+
14
+ // ─── Redaction ───────────────────────────────────────────────────────────────
15
+
16
+ const REDACTED = "REDACTED";
17
+
18
+ /**
19
+ * Masks the credentials in a provider URI or URL: the value of every
20
+ * credential-named query param (`api_key`, `key`, `*_token`, ...) and
21
+ * userinfo before an `@`. Tolerates malformed input; a `name@version`
22
+ * model id is kept.
23
+ */
24
+ export function redactURI(raw: string): string {
25
+ let out = "";
26
+ for (;;) {
27
+ const m = /[?&]/.exec(raw);
28
+ if (!m) return out + redactSegment(raw);
29
+ out += redactSegment(raw.slice(0, m.index)) + m[0];
30
+ raw = raw.slice(m.index + 1);
31
+ }
32
+ }
33
+
34
+ function redactSegment(seg: string): string {
35
+ const eq = seg.indexOf("=");
36
+ if (eq < 0) return redactUserinfo(seg, false);
37
+ const k = seg.slice(0, eq);
38
+ const v = seg.slice(eq + 1);
39
+ if (k.includes("://")) return redactUserinfo(seg, false);
40
+ if (credentialParam(k)) return v === "" ? seg : `${k}=${REDACTED}`;
41
+ return `${k}=${redactUserinfo(v, true)}`;
42
+ }
43
+
44
+ function redactUserinfo(s: string, strict: boolean): string {
45
+ let start = 0;
46
+ let scheme = "";
47
+ const i = s.indexOf("://");
48
+ if (i >= 0) {
49
+ start = i + 3;
50
+ scheme = s.slice(0, i).toLowerCase();
51
+ }
52
+ const rest = s.slice(start);
53
+ let end = rest.indexOf("/");
54
+ const hasPath = end >= 0;
55
+ if (!hasPath) end = rest.length;
56
+ const at = rest.slice(0, end).lastIndexOf("@");
57
+ if (at <= 0) return s;
58
+ const credential =
59
+ strict ||
60
+ scheme === "http" ||
61
+ scheme === "https" ||
62
+ (hasPath && start > 0) ||
63
+ rest.slice(0, at).includes(":");
64
+ if (!credential) return s; // a "name@version" model id
65
+ return s.slice(0, start) + REDACTED + rest.slice(at);
66
+ }
67
+
68
+ const CREDENTIAL_NAMES = new Set([
69
+ "key", "apikey", "token", "secret", "password", "passwd", "pwd",
70
+ "auth", "authorization", "signature", "sig", "credential", "credentials",
71
+ ]);
72
+ const CREDENTIAL_SUFFIXES = [
73
+ "_key", "apikey", "_token", "_secret", "_password",
74
+ "_signature", "_credential", "_credentials",
75
+ ];
76
+
77
+ function credentialParam(name: string): boolean {
78
+ try {
79
+ name = decodeURIComponent(name.replace(/\+/g, " "));
80
+ } catch {
81
+ // keep the raw name
82
+ }
83
+ name = name.trim().toLowerCase().replace(/-/g, "_");
84
+ if (CREDENTIAL_NAMES.has(name)) return true;
85
+ return CREDENTIAL_SUFFIXES.some((s) => name.endsWith(s));
86
+ }
87
+
88
+ /**
89
+ * Returns `msg` with every secret replaced by `REDACTED`. Blank secrets
90
+ * are ignored.
91
+ */
92
+ export function scrubSecrets(msg: string, secrets: readonly string[]): string {
93
+ for (const s of secrets) {
94
+ if (s.trim() !== "") msg = msg.split(s).join(REDACTED);
95
+ }
96
+ return msg;
97
+ }
98
+
99
+ // ─── Endpoints ───────────────────────────────────────────────────────────────
100
+
101
+ interface Endpoint {
102
+ scheme: string;
103
+ host: string;
104
+ port: string;
105
+ }
106
+
107
+ /**
108
+ * Parses `raw` for a credential check with the WHATWG URL parser fetch
109
+ * uses. Undefined, and no credential may go to `raw`, when it does not
110
+ * parse, has no host, or carries userinfo, a backslash, a
111
+ * percent-escape, whitespace or a control character: forms where
112
+ * parsers disagree on the host.
113
+ */
114
+ function parseEndpoint(raw: string): Endpoint | undefined {
115
+ if (/[\\%]/.test(raw) || /[\u0000- \u007f\s]/.test(raw)) {
116
+ return undefined;
117
+ }
118
+ let u: URL;
119
+ try {
120
+ u = new URL(raw);
121
+ } catch {
122
+ return undefined;
123
+ }
124
+ const authority = raw.slice(raw.indexOf("//") + 2).split(/[/?#]/)[0] ?? "";
125
+ if (!u.host || !u.hostname || u.username || u.password || authority.includes("@")) {
126
+ return undefined;
127
+ }
128
+ const scheme = u.protocol.replace(/:$/, "").toLowerCase();
129
+ let port = u.port;
130
+ if (port === "") {
131
+ if (scheme === "https") port = "443";
132
+ else if (scheme === "http") port = "80";
133
+ }
134
+ return { scheme, host: u.hostname.toLowerCase(), port };
135
+ }
136
+
137
+ function origin(e: Endpoint): string {
138
+ return `${e.scheme}://${e.host}:${e.port}`;
139
+ }
140
+
141
+ /** @internal A key that is empty or only whitespace: no key. */
142
+ export function blankKey(key: string | undefined): boolean {
143
+ return (key ?? "").trim() === "";
144
+ }
145
+
146
+ /**
147
+ * Throws a {@link KeyEndpointError} for a non-blank `key` bound for a
148
+ * malformed endpoint, or over plain http to a host other than loopback.
149
+ * Adapters call it on the base URL they settle on.
150
+ */
151
+ export function checkKeyEndpoint(
152
+ scheme: string,
153
+ key: string | undefined,
154
+ baseURL: string
155
+ ): void {
156
+ if (blankKey(key) || baseURL === "") return;
157
+ const e = parseEndpoint(baseURL);
158
+ if (!e) {
159
+ throw new KeyEndpointError(scheme, redactURI(baseURL), { malformed: true });
160
+ }
161
+ if (e.scheme === "http" && !isLoopback(e.host)) {
162
+ throw new KeyEndpointError(scheme, redactURI(baseURL), { insecure: true });
163
+ }
164
+ }
165
+
166
+ // ─── Declarations ────────────────────────────────────────────────────────────
167
+
168
+ /**
169
+ * A scheme's credential: the variables holding its key, highest
170
+ * precedence first. `optional` marks a key a provider runs without
171
+ * (a local runtime): `LLM_API_KEY` is then not lent to it. No
172
+ * `envVars` and `optional` is a scheme that takes no key at all.
173
+ */
174
+ export interface ProviderKey {
175
+ envVars: string[];
176
+ optional?: boolean;
177
+ }
178
+
179
+ /**
180
+ * What an adapter states about its scheme: the endpoints credentials
181
+ * kit resolved itself may go to (see {@link credentialsTrusted}), and
182
+ * its credential when the `<SCHEME>_API_KEY` convention does not fit.
183
+ */
184
+ export interface Declaration {
185
+ endpoints?: string[];
186
+ key?: ProviderKey;
187
+ }
188
+
189
+ const declarations = new Map<string, Declaration>();
190
+ const registered = new Set<string>();
191
+
192
+ /** @internal Records that `scheme` has an adapter; `register` calls it. */
193
+ export function setDeclaration(scheme: string, decl?: Declaration): void {
194
+ registered.add(scheme);
195
+ if (decl) declarations.set(scheme, decl);
196
+ }
197
+
198
+ /** @internal */
199
+ export function clearDeclarations(): void {
200
+ declarations.clear();
201
+ registered.clear();
202
+ }
203
+
204
+ /** The declaration `scheme` registered with, if any. */
205
+ export function declarationOf(scheme: string): Declaration | undefined {
206
+ return declarations.get(scheme);
207
+ }
208
+
209
+ /** @internal Whether an adapter is registered for `scheme`. */
210
+ export function isRegistered(scheme: string): boolean {
211
+ return registered.has(scheme);
212
+ }
213
+
214
+ /**
215
+ * Reports whether credentials kit resolved itself, not taken from the
216
+ * URI (an env or llm.yaml key, a bearer token, a workspace header), may
217
+ * go to `baseURL` for `scheme`: it is loopback, or shares an origin
218
+ * with the scheme's declared endpoints, its llm.yaml `base_url`,
219
+ * `LLM_BASE_URL` or one of `extra` (the adapter's default endpoint and
220
+ * its own base URL variable). Every credential path decides here.
221
+ */
222
+ export function credentialsTrusted(
223
+ scheme: string,
224
+ baseURL: string,
225
+ ...extra: string[]
226
+ ): boolean {
227
+ return trustedOrigin(scheme, baseURL, extra, true);
228
+ }
229
+
230
+ /**
231
+ * @internal {@link credentialsTrusted}; `ambient` false (hermetic)
232
+ * consults neither `LLM_BASE_URL` nor llm.yaml.
233
+ */
234
+ export function trustedOrigin(
235
+ scheme: string,
236
+ baseURL: string,
237
+ extra: readonly string[],
238
+ ambient: boolean
239
+ ): boolean {
240
+ const e = parseEndpoint(baseURL);
241
+ if (!e) return false;
242
+ if (isLoopback(e.host)) return true;
243
+ const trusted = [...(declarations.get(scheme)?.endpoints ?? []), ...extra];
244
+ if (ambient) {
245
+ const file = providerBlock(readLLMFile(), scheme)?.baseURL;
246
+ if (file) trusted.push(file);
247
+ const env = process.env["LLM_BASE_URL"];
248
+ if (env) trusted.push(env);
249
+ }
250
+ return trusted.some((t) => {
251
+ const te = t ? parseEndpoint(t) : undefined;
252
+ return te !== undefined && origin(te) === origin(e);
253
+ });
254
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Base error of the llm layer. Lives apart from `llm.ts` so modules
3
+ * that `llm.ts` re-exports can extend it without an import cycle.
4
+ * Import it from `@hop-top/kit/llm`.
5
+ *
6
+ * @internal
7
+ */
8
+ export class LLMError extends Error {
9
+ statusCode?: number;
10
+ code?: string;
11
+
12
+ constructor(message: string) {
13
+ super(message);
14
+ this.name = "LLMError";
15
+ Object.setPrototypeOf(this, new.target.prototype);
16
+ }
17
+ }
@@ -0,0 +1,152 @@
1
+ /**
2
+ * Typed errors the HTTP adapters return, re-exported from
3
+ * `@hop-top/kit/llm`. Apart from `llm.ts` so the adapters' transport
4
+ * can raise them without an import cycle.
5
+ *
6
+ * @internal
7
+ */
8
+
9
+ import { LLMError } from "./llm-error";
10
+ import { goQuote } from "./llm-quote";
11
+
12
+ /**
13
+ * An HTTP error response kit classifies by status: a 5xx (fallbackable)
14
+ * or a redirect, which is never followed.
15
+ */
16
+ export class HTTPStatusError extends LLMError {
17
+ readonly status: string;
18
+
19
+ constructor(statusCode: number, status: string) {
20
+ super(`http ${statusCode}: ${status}`);
21
+ this.name = "HTTPStatusError";
22
+ this.statusCode = statusCode;
23
+ this.status = status;
24
+ }
25
+ }
26
+
27
+ /**
28
+ * A provider error response no other class covers (a 4xx such as an
29
+ * invalid request). `type` is the provider's error type, when it gave
30
+ * one. Not fallbackable.
31
+ */
32
+ export class APIError extends LLMError {
33
+ readonly provider: string;
34
+ readonly type: string;
35
+
36
+ constructor(provider: string, statusCode: number, type: string, message: string) {
37
+ super(message);
38
+ this.name = "APIError";
39
+ this.provider = provider;
40
+ this.statusCode = statusCode;
41
+ this.type = type;
42
+ }
43
+ }
44
+
45
+ /**
46
+ * A stream ended before the provider's terminal event: the response is
47
+ * incomplete, never a success. Not fallbackable: tokens may already
48
+ * have been consumed.
49
+ */
50
+ export class StreamTruncatedError extends LLMError {
51
+ readonly provider: string;
52
+
53
+ constructor(provider: string) {
54
+ super(
55
+ `stream truncated (provider ${JSON.stringify(provider)}): ended before its final event`
56
+ );
57
+ this.name = "StreamTruncatedError";
58
+ this.provider = provider;
59
+ }
60
+ }
61
+
62
+ /**
63
+ * A response body, or one streamed event, exceeded its size limit
64
+ * (`max_body_bytes`, `max_event_bytes`). Not fallbackable.
65
+ */
66
+ export class ResponseTooLargeError extends LLMError {
67
+ readonly provider: string;
68
+ /** The part that overran: `"body"` or `"event"`. */
69
+ readonly what: "body" | "event";
70
+ readonly limit: number;
71
+
72
+ constructor(provider: string, what: "body" | "event", limit: number) {
73
+ super(
74
+ `response ${what} exceeds ${limit} bytes (provider ${JSON.stringify(provider)})`
75
+ );
76
+ this.name = "ResponseTooLargeError";
77
+ this.provider = provider;
78
+ this.what = what;
79
+ this.limit = limit;
80
+ }
81
+ }
82
+
83
+ /**
84
+ * A provider key kit will not send to an endpoint. `endpoint` is masked
85
+ * by `redactURI`; the key never appears.
86
+ */
87
+ export class KeyEndpointError extends LLMError {
88
+ readonly scheme: string;
89
+ readonly endpoint: string;
90
+ /** Set when the refusal is plain http to a remote host. */
91
+ readonly insecure: boolean;
92
+ /**
93
+ * Set when the endpoint carries userinfo, a backslash, a
94
+ * percent-escape, whitespace or a control character, or does not
95
+ * parse: no credential goes to it.
96
+ */
97
+ readonly malformed: boolean;
98
+
99
+ constructor(
100
+ scheme: string,
101
+ endpoint: string,
102
+ opts: { insecure?: boolean; malformed?: boolean } = {}
103
+ ) {
104
+ super(keyEndpointMessage(scheme, endpoint, opts));
105
+ this.name = "KeyEndpointError";
106
+ this.scheme = scheme;
107
+ this.endpoint = endpoint;
108
+ this.insecure = opts.insecure ?? false;
109
+ this.malformed = opts.malformed ?? false;
110
+ }
111
+ }
112
+
113
+ function keyEndpointMessage(
114
+ scheme: string,
115
+ endpoint: string,
116
+ opts: { insecure?: boolean; malformed?: boolean }
117
+ ): string {
118
+ const q = goQuote(endpoint);
119
+ if (opts.malformed) {
120
+ return (
121
+ `llm: refusing to send the ${scheme} API key to ${q}: an endpoint must parse and carry ` +
122
+ "no userinfo, backslash, percent-escape, whitespace or control character"
123
+ );
124
+ }
125
+ if (opts.insecure) {
126
+ return `llm: refusing to send the ${scheme} API key over plain http to ${q}; use https or a loopback host`;
127
+ }
128
+ return (
129
+ `llm: refusing to send the ${scheme} API key to ${q}, which only the URI names; ` +
130
+ "set it as llm.yaml base_url or LLM_BASE_URL, or pass api_key in the URI"
131
+ );
132
+ }
133
+
134
+ /**
135
+ * No key was found for a scheme whose adapter requires one. Carries
136
+ * names only, never a value: `envVars` lists every variable consulted,
137
+ * highest precedence first, ending with `LLM_API_KEY`.
138
+ */
139
+ export class MissingKeyError extends LLMError {
140
+ readonly scheme: string;
141
+ readonly model: string;
142
+ readonly envVars: string[];
143
+
144
+ constructor(scheme: string, model: string, envVars: string[]) {
145
+ const m = model !== "" ? ` (model ${goQuote(model)})` : "";
146
+ super(`llm: no API key for provider ${goQuote(scheme)}${m}: set ${envVars.join(" or ")}`);
147
+ this.name = "MissingKeyError";
148
+ this.scheme = scheme;
149
+ this.model = model;
150
+ this.envVars = envVars;
151
+ }
152
+ }
@@ -0,0 +1,126 @@
1
+ /**
2
+ * llm.yaml: `{configDir("hop")}/llm.yaml`, read as Go `llm` reads it.
3
+ * Best-effort: a missing, unreadable or malformed file is an empty
4
+ * config. Read on each call, never cached. A hermetic config does not
5
+ * call it.
6
+ *
7
+ * ```yaml
8
+ * default: anthropic://claude-sonnet-4-5
9
+ * fallback: [openai://gpt-4.1]
10
+ * providers:
11
+ * anthropic:
12
+ * api_key: ... # or api_key_env: MY_ANTHROPIC_KEY
13
+ * base_url: https://gw.corp.example
14
+ * model: claude-sonnet-4-5
15
+ * routellm: {...} # any other key: ProviderConfig.extras
16
+ * ```
17
+ *
18
+ * @internal
19
+ */
20
+
21
+ import { readFileSync } from "node:fs";
22
+ import { join } from "node:path";
23
+ import * as yaml from "js-yaml";
24
+
25
+ import { configDir } from "./xdg";
26
+
27
+ /** One `providers.<name>` block. */
28
+ export interface LLMFileProvider {
29
+ apiKey: string;
30
+ apiKeyEnv: string;
31
+ baseURL: string;
32
+ model: string;
33
+ /** The block's other keys, typed as YAML types them. */
34
+ extras: Record<string, unknown>;
35
+ }
36
+
37
+ /** The parts of llm.yaml the llm core reads. */
38
+ export interface LLMFile {
39
+ default: string;
40
+ fallback: string[];
41
+ providers: Map<string, LLMFileProvider>;
42
+ }
43
+
44
+ const EMPTY: LLMFile = { default: "", fallback: [], providers: new Map() };
45
+
46
+ const FIELDS = new Set(["api_key", "api_key_env", "base_url", "model"]);
47
+
48
+ /** Reads llm.yaml; an empty config when there is none to read. */
49
+ export function readLLMFile(): LLMFile {
50
+ let text: string;
51
+ try {
52
+ text = readFileSync(join(configDir("hop"), "llm.yaml"), "utf8");
53
+ } catch {
54
+ return emptyFile();
55
+ }
56
+ try {
57
+ // Fields decode as Go decodes them into strings: every scalar as
58
+ // written (FAILSAFE). Extras keep their YAML types (CORE).
59
+ return decode(
60
+ yaml.load(text, { schema: yaml.FAILSAFE_SCHEMA }),
61
+ yaml.load(text, { schema: yaml.CORE_SCHEMA })
62
+ );
63
+ } catch {
64
+ return emptyFile();
65
+ }
66
+ }
67
+
68
+ /** The block configuring `scheme`, if llm.yaml has one. */
69
+ export function providerBlock(file: LLMFile, scheme: string): LLMFileProvider | undefined {
70
+ return file.providers.get(scheme);
71
+ }
72
+
73
+ function emptyFile(): LLMFile {
74
+ return { ...EMPTY, fallback: [], providers: new Map() };
75
+ }
76
+
77
+ class Shape extends Error {}
78
+
79
+ function isMap(v: unknown): v is Record<string, unknown> {
80
+ return typeof v === "object" && v !== null && !Array.isArray(v);
81
+ }
82
+
83
+ /** A string field: absent or null is "", a scalar is its text. */
84
+ function str(v: unknown): string {
85
+ if (v === undefined || v === null) return "";
86
+ if (typeof v !== "string") throw new Shape();
87
+ return v;
88
+ }
89
+
90
+ /**
91
+ * Builds the config from the file parsed twice; a field of the wrong
92
+ * shape empties the whole file, as a failed Go decode does.
93
+ */
94
+ function decode(raw: unknown, typed: unknown): LLMFile {
95
+ if (raw === undefined || raw === null) return emptyFile();
96
+ if (!isMap(raw)) throw new Shape();
97
+ const t = isMap(typed) ? typed : {};
98
+ const out = emptyFile();
99
+ out.default = str(raw["default"]);
100
+ const fb = raw["fallback"];
101
+ if (fb !== undefined && fb !== null) {
102
+ if (!Array.isArray(fb)) throw new Shape();
103
+ out.fallback = fb.map(str);
104
+ }
105
+ const ps = raw["providers"];
106
+ if (ps === undefined || ps === null) return out;
107
+ if (!isMap(ps)) throw new Shape();
108
+ const tps = isMap(t["providers"]) ? t["providers"] : {};
109
+ for (const [name, block] of Object.entries(ps)) {
110
+ const b = block === null ? {} : block;
111
+ if (!isMap(b)) throw new Shape();
112
+ const tb = isMap(tps[name]) ? (tps[name] as Record<string, unknown>) : {};
113
+ const extras: Record<string, unknown> = {};
114
+ for (const k of Object.keys(b)) {
115
+ if (!FIELDS.has(k) && k !== "__proto__") extras[k] = tb[k];
116
+ }
117
+ out.providers.set(name, {
118
+ apiKey: str(b["api_key"]),
119
+ apiKeyEnv: str(b["api_key_env"]),
120
+ baseURL: str(b["base_url"]),
121
+ model: str(b["model"]),
122
+ extras,
123
+ });
124
+ }
125
+ return out;
126
+ }