@hop-top/kit 0.5.0-alpha.13 → 0.5.0-alpha.14

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 (39) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist/{chunk-BXJ2J27B.js → chunk-IGKBRNEW.js} +10 -10
  3. package/dist/{chunk-VWGP4NVJ.js → chunk-MDVGMOZO.js} +45 -39
  4. package/dist/{chunk-4FMALWYB.js → chunk-MEF7W3MG.js} +45 -45
  5. package/dist/{chunk-VGOA5Y7S.js → chunk-Q547MHNB.js} +11 -11
  6. package/dist/{chunk-K7E34Q3A.js → chunk-TUU2BY5I.js} +136 -47
  7. package/dist/index.d.ts +4 -4
  8. package/dist/index.js +6 -6
  9. package/dist/{llm-DYuR7_uX.d.ts → llm-BazFKc_2.d.ts} +95 -9
  10. package/dist/{llm-anthropic-Cd_I2xXB.d.ts → llm-anthropic-BcAitoDV.d.ts} +1 -1
  11. package/dist/llm-anthropic.d.ts +2 -2
  12. package/dist/llm-anthropic.js +4 -4
  13. package/dist/{llm-openai-DyFrucmV.d.ts → llm-openai-CSDvuRH6.d.ts} +1 -1
  14. package/dist/llm-openai.d.ts +2 -2
  15. package/dist/llm-openai.js +4 -4
  16. package/dist/llm.d.ts +1 -1
  17. package/dist/llm.js +8 -2
  18. package/dist/{routellm-B0nv59mH.d.ts → routellm-B9UrONPr.d.ts} +1 -1
  19. package/dist/routellm.d.ts +2 -2
  20. package/dist/routellm.js +5 -5
  21. package/package.json +5 -5
  22. package/skills/hop-top-kit-ts/.claude-plugin/plugin.json +1 -1
  23. package/skills/hop-top-kit-ts/SKILL.md +2 -2
  24. package/skills/hop-top-kit-ts/references/other-ports.md +1 -1
  25. package/src/llm-anthropic.conformance.test.ts +7 -0
  26. package/src/llm-boundkey.test.ts +260 -0
  27. package/src/llm-choice-hermetic.test.ts +1 -1
  28. package/src/llm-config.test.ts +2 -4
  29. package/src/llm-config.ts +5 -1
  30. package/src/llm-endpoint.ts +25 -5
  31. package/src/llm-keys.ts +47 -15
  32. package/src/llm-openai.test.ts +10 -4
  33. package/src/llm-openai.ts +7 -1
  34. package/src/llm-spec.test.ts +347 -0
  35. package/src/llm-spec.ts +80 -0
  36. package/src/llm-uri.ts +96 -12
  37. package/src/llm.test.ts +2 -2
  38. package/src/llm.ts +10 -0
  39. package/test/llm/conformance-helpers.ts +3 -0
@@ -0,0 +1,260 @@
1
+ /**
2
+ * A scheme declaring keyBoundToDefault keeps its ambient key (provider
3
+ * variable, LLM_API_KEY) for its default endpoint; a custom endpoint,
4
+ * loopback included, gets only a key set for it. Go `llm`
5
+ * (boundkey_test.go) is canonical; the llm-v1 key_endpoint vectors pin
6
+ * the shared cases.
7
+ */
8
+
9
+ import { mkdirSync, writeFileSync } from "node:fs";
10
+ import { join } from "node:path";
11
+ import { afterEach, beforeEach, describe, expect, it } from "vitest";
12
+
13
+ import {
14
+ KeyEndpointError,
15
+ applyAPIKey,
16
+ createLLM,
17
+ loadConfig,
18
+ register,
19
+ type Provider,
20
+ } from "./llm";
21
+ import { OPENAI_SCHEMES } from "./llm-openai";
22
+ import { declarationOf } from "./llm-endpoint";
23
+ import { fakeServer, isolateEnv, type FakeServer } from "../test/llm/conformance-helpers";
24
+
25
+ const HOSTED = "fake-bound-hosted-key-must-not-leak";
26
+ const OWN = "fake-bound-endpoint-key";
27
+ const ENV = [
28
+ "LLM_API_KEY", "LLM_BASE_URL", "LLM_PROVIDER", "LLM_FALLBACK",
29
+ "BOUNDKEY_API_KEY", "PLAINKEY_API_KEY", "MY_COMPAT_KEY",
30
+ "OPENAI_API_KEY", "OPENROUTER_API_KEY", "LMSTUDIO_API_KEY",
31
+ ];
32
+
33
+ let restoreEnv: () => void;
34
+ const servers: FakeServer[] = [];
35
+
36
+ function stub(): Provider {
37
+ return { close: () => undefined };
38
+ }
39
+
40
+ // Registered once: the openai schemes register on import and must stay.
41
+ // boundkey keeps its hosted key (BOUNDKEY_API_KEY, LLM_API_KEY) for its
42
+ // default endpoint; plainkey, declared alike but not bound, does not.
43
+ register("boundkey", stub, {
44
+ baseURL: "https://api.boundkey.test/v1",
45
+ keyBoundToDefault: true,
46
+ });
47
+ register("plainkey", stub, { baseURL: "https://api.plainkey.test/v1" });
48
+ register("unbound", stub);
49
+
50
+ beforeEach(() => {
51
+ restoreEnv = isolateEnv(ENV);
52
+ });
53
+ afterEach(async () => {
54
+ restoreEnv();
55
+ writeYaml("");
56
+ await Promise.all(servers.splice(0).map((s) => s.close()));
57
+ });
58
+
59
+ function writeYaml(yaml: string): void {
60
+ const dir = join(process.env["XDG_CONFIG_HOME"]!, "hop");
61
+ mkdirSync(dir, { recursive: true });
62
+ writeFileSync(join(dir, "llm.yaml"), yaml);
63
+ }
64
+
65
+ function setup(yaml: string): void {
66
+ writeYaml(yaml);
67
+ process.env["BOUNDKEY_API_KEY"] = HOSTED;
68
+ process.env["PLAINKEY_API_KEY"] = HOSTED;
69
+ process.env["MY_COMPAT_KEY"] = OWN;
70
+ process.env["LLM_API_KEY"] = HOSTED;
71
+ }
72
+
73
+ describe("hosted key only on the default endpoint", () => {
74
+ const cases: { name: string; yaml?: string; envBase?: string; uri: string; want?: string }[] = [
75
+ { name: "no endpoint", uri: "boundkey://m", want: HOSTED },
76
+ { name: "default as base_url", uri: "boundkey://m?base_url=https://api.boundkey.test/v1", want: HOSTED },
77
+ { name: "same origin, other path", uri: "boundkey://m?base_url=https://API.boundkey.test:443/other", want: HOSTED },
78
+ { name: "LLM_BASE_URL same origin", envBase: "https://api.boundkey.test", uri: "boundkey://m", want: HOSTED },
79
+ {
80
+ name: "llm.yaml base_url same origin",
81
+ yaml: "providers:\n boundkey:\n base_url: https://api.boundkey.test/v1\n",
82
+ uri: "boundkey://m",
83
+ want: HOSTED,
84
+ },
85
+
86
+ { name: "URI base_url loopback", uri: "boundkey://m?base_url=http://127.0.0.1:9/v1" },
87
+ { name: "URI host loopback", uri: "boundkey://localhost:8000/m" },
88
+ { name: "LLM_BASE_URL loopback", envBase: "http://127.0.0.1:9/v1", uri: "boundkey://m" },
89
+ {
90
+ name: "llm.yaml base_url loopback",
91
+ yaml: "providers:\n boundkey:\n base_url: http://127.0.0.1:9/v1\n",
92
+ uri: "boundkey://m",
93
+ },
94
+ {
95
+ name: "llm.yaml base_url remote",
96
+ yaml: "providers:\n boundkey:\n base_url: https://llm.corp.test/v1\n",
97
+ uri: "boundkey://m",
98
+ },
99
+ { name: "URI base_url remote https", uri: "boundkey://m?base_url=https://llm.corp.test/v1" },
100
+ { name: "unparseable base_url is custom", uri: "boundkey://m?base_url=nonsense" },
101
+
102
+ {
103
+ name: "api_key_env on custom endpoint",
104
+ yaml: "providers:\n boundkey:\n api_key_env: MY_COMPAT_KEY\n",
105
+ uri: "boundkey://m?base_url=http://127.0.0.1:9/v1",
106
+ want: OWN,
107
+ },
108
+ {
109
+ name: "llm.yaml api_key on custom endpoint",
110
+ yaml: `providers:\n boundkey:\n api_key: ${OWN}\n`,
111
+ uri: "boundkey://m?base_url=http://127.0.0.1:9/v1",
112
+ want: OWN,
113
+ },
114
+
115
+ { name: "non-bound scheme, loopback base_url", uri: "plainkey://m?base_url=http://127.0.0.1:9/v1", want: HOSTED },
116
+ { name: "non-bound scheme, LLM_BASE_URL", envBase: "http://127.0.0.1:9/v1", uri: "plainkey://m", want: HOSTED },
117
+ ];
118
+ for (const tc of cases) {
119
+ it(tc.name, () => {
120
+ setup(tc.yaml ?? "");
121
+ if (tc.envBase) process.env["LLM_BASE_URL"] = tc.envBase;
122
+ // "nonsense" is no endpoint a key may go to; it never carries one.
123
+ const cfg = loadConfig(tc.uri);
124
+ expect(cfg.provider.apiKey, "no key for a custom endpoint is no error").toBe(tc.want);
125
+
126
+ const got = applyAPIKey(tc.uri);
127
+ if (tc.want === undefined) expect(got).toBe(tc.uri);
128
+ else expect(got).toContain(`api_key=${tc.want}`);
129
+ expect(got).not.toContain(`${HOSTED}&`);
130
+ });
131
+ }
132
+
133
+ it("a key in the URI outranks everything on a custom endpoint", () => {
134
+ setup("");
135
+ const uri = `boundkey://m?api_key=${OWN}&base_url=http://127.0.0.1:9/v1`;
136
+ expect(applyAPIKey(uri)).toBe(uri);
137
+ expect(loadConfig(uri).provider.apiKey).toBe(OWN);
138
+ });
139
+
140
+ it("a key set for a custom endpoint still obeys the endpoint guard", () => {
141
+ setup(`providers:\n boundkey:\n api_key: ${OWN}\n`);
142
+ expect(() => loadConfig("boundkey://m?base_url=https://llm.corp.test/v1")).toThrow(
143
+ KeyEndpointError
144
+ );
145
+ });
146
+
147
+ it("a scheme with no declaration is never bound", () => {
148
+ setup("");
149
+ expect(loadConfig("unbound://m?base_url=http://127.0.0.1:9/v1").provider.apiKey).toBe(HOSTED);
150
+ });
151
+ });
152
+
153
+ describe("the openai-family schemes are bound to their default endpoints", () => {
154
+ const DEFAULTS: Record<string, string> = {
155
+ openai: "https://api.openai.com/v1",
156
+ openrouter: "https://openrouter.ai/api/v1",
157
+ xai: "https://api.x.ai/v1",
158
+ lmstudio: "http://localhost:1234/v1",
159
+ groq: "https://api.groq.com/openai/v1",
160
+ together: "https://api.together.xyz/v1",
161
+ fireworks: "https://api.fireworks.ai/inference/v1",
162
+ deepseek: "https://api.deepseek.com",
163
+ mistral: "https://api.mistral.ai/v1",
164
+ };
165
+
166
+ it("declares each scheme bound, with Go's default endpoint", () => {
167
+ expect([...OPENAI_SCHEMES].sort()).toEqual(Object.keys(DEFAULTS).sort());
168
+ for (const s of OPENAI_SCHEMES) {
169
+ // The module registered them on import; clearRegistry has not run.
170
+ const d = declarationOf(s);
171
+ expect(d?.keyBoundToDefault, s).toBe(true);
172
+ expect(d?.baseURL, s).toBe(DEFAULTS[s]);
173
+ }
174
+ });
175
+
176
+ it("OPENAI_API_KEY stays off a self-hosted server and on api.openai.com", () => {
177
+ process.env["OPENAI_API_KEY"] = HOSTED;
178
+ process.env["LLM_API_KEY"] = HOSTED;
179
+ expect(loadConfig("openai://m?base_url=http://127.0.0.1:9/v1").provider.apiKey).toBeUndefined();
180
+ expect(loadConfig("openai://localhost:8000/m").provider.apiKey).toBeUndefined();
181
+ expect(loadConfig("openai://m").provider.apiKey).toBe(HOSTED);
182
+ expect(loadConfig("openai://m?base_url=https://api.openai.com/v1").provider.apiKey).toBe(HOSTED);
183
+ process.env["LLM_BASE_URL"] = "http://127.0.0.1:9/v1";
184
+ expect(loadConfig("openai://m").provider.apiKey).toBeUndefined();
185
+ });
186
+
187
+ it("openrouter's own key goes only to openrouter.ai", () => {
188
+ process.env["OPENROUTER_API_KEY"] = HOSTED;
189
+ expect(loadConfig("openrouter://a/b").provider.apiKey).toBe(HOSTED);
190
+ expect(loadConfig("openrouter://a/b?base_url=http://127.0.0.1:9").provider.apiKey).toBeUndefined();
191
+ });
192
+
193
+ it("lmstudio takes no key", () => {
194
+ process.env["LMSTUDIO_API_KEY"] = HOSTED;
195
+ process.env["LLM_API_KEY"] = HOSTED;
196
+ expect(loadConfig("lmstudio://m").provider.apiKey).toBeUndefined();
197
+ });
198
+ });
199
+
200
+ describe("on the wire", () => {
201
+ async function recorder(): Promise<FakeServer> {
202
+ const s = await fakeServer((_h, res) => {
203
+ res.setHeader("content-type", "application/json");
204
+ res.end(JSON.stringify({ choices: [{ message: { role: "assistant", content: "ok" }, finish_reason: "stop" }] }));
205
+ });
206
+ servers.push(s);
207
+ return s;
208
+ }
209
+
210
+ async function call(uri: string): Promise<void> {
211
+ const c = createLLM(uri);
212
+ try {
213
+ await c.complete({ messages: [{ role: "user", content: "hi" }] });
214
+ } finally {
215
+ c.close();
216
+ }
217
+ }
218
+
219
+ it("a self-hosted server gets no Authorization from the hosted key", async () => {
220
+ const srv = await recorder();
221
+ process.env["OPENAI_API_KEY"] = HOSTED;
222
+ process.env["LLM_API_KEY"] = HOSTED;
223
+ await call(`openai://m?base_url=${srv.url}/v1`);
224
+ expect(srv.hits).toHaveLength(1);
225
+ expect(srv.hits[0]!.headers["authorization"]).toBeUndefined();
226
+ });
227
+
228
+ it("LLM_BASE_URL does not redirect the hosted key either", async () => {
229
+ const srv = await recorder();
230
+ process.env["OPENAI_API_KEY"] = HOSTED;
231
+ process.env["LLM_BASE_URL"] = `${srv.url}/v1`;
232
+ await call("openai://m");
233
+ expect(srv.hits).toHaveLength(1);
234
+ expect(srv.hits[0]!.headers["authorization"]).toBeUndefined();
235
+ });
236
+
237
+ it("the URI's own key reaches it", async () => {
238
+ const srv = await recorder();
239
+ process.env["OPENAI_API_KEY"] = HOSTED;
240
+ await call(`openai://m?api_key=${OWN}&base_url=${srv.url}/v1`);
241
+ expect(srv.hits[0]!.headers["authorization"]).toBe(`Bearer ${OWN}`);
242
+ });
243
+
244
+ it("llm.yaml api_key_env reaches it", async () => {
245
+ const srv = await recorder();
246
+ process.env["OPENAI_API_KEY"] = HOSTED;
247
+ process.env["MY_COMPAT_KEY"] = OWN;
248
+ writeYaml("providers:\n openai:\n api_key_env: MY_COMPAT_KEY\n");
249
+ await call(`openai://m?base_url=${srv.url}/v1`);
250
+ expect(srv.hits[0]!.headers["authorization"]).toBe(`Bearer ${OWN}`);
251
+ });
252
+
253
+ it("llm.yaml api_key reaches it", async () => {
254
+ const srv = await recorder();
255
+ process.env["OPENAI_API_KEY"] = HOSTED;
256
+ writeYaml(`providers:\n openai:\n api_key: ${OWN}\n`);
257
+ await call(`openai://m?base_url=${srv.url}/v1`);
258
+ expect(srv.hits[0]!.headers["authorization"]).toBe(`Bearer ${OWN}`);
259
+ });
260
+ });
@@ -214,7 +214,7 @@ describe("local runtimes' keys", () => {
214
214
 
215
215
  describe("hermetic", () => {
216
216
  it("loadConfig reads no LLM_* variable", () => {
217
- process.env["LLM_PROVIDER"] = "openai://ambient";
217
+ process.env["LLM_PROVIDER"] = "anthropic://ambient";
218
218
  process.env["LLM_FALLBACK"] = "openai://fb";
219
219
  process.env["LLM_API_KEY"] = "env-key";
220
220
  process.env["LLM_BASE_URL"] = "https://gw.corp.test";
@@ -217,11 +217,9 @@ describe("applyAPIKey", () => {
217
217
  );
218
218
  });
219
219
 
220
- it("refuses a key a URI cannot carry", () => {
220
+ it("carries a key holding separators escaped", () => {
221
221
  process.env["KITA_API_KEY"] = "k&x";
222
- expect(() => applyAPIKey("kita://m")).toThrow(
223
- "llm: kita API key contains a character a provider URI cannot carry (& ? #)"
224
- );
222
+ expect(applyAPIKey("kita://m")).toBe("kita://m?api_key=k%26x");
225
223
  });
226
224
 
227
225
  it("never quotes its input on a parse error", () => {
package/src/llm-config.ts CHANGED
@@ -36,7 +36,11 @@ export interface LoadOptions {
36
36
  * variables (`<SCHEME>_API_KEY` unless its adapter declares others);
37
37
  * `LLM_API_KEY` for a registered scheme that requires a key. Blank is
38
38
  * unset everywhere; a blank `api_key` param is dropped. Found
39
- * nowhere, it is left unset: the adapter reports it.
39
+ * nowhere, it is left unset: the adapter reports it. A scheme
40
+ * declaring `keyBoundToDefault` (the openai family) lends the last
41
+ * two only on its default endpoint: on any other, only the URI's
42
+ * `api_key`, llm.yaml `api_key` and `api_key_env` apply, and no key
43
+ * is no error.
40
44
  * - baseURL: the URI's `base_url`; its host (`http://host:port`);
41
45
  * `LLM_BASE_URL`; llm.yaml `base_url`.
42
46
  * - model: the URI's; llm.yaml `model`. extras: the block's other keys.
@@ -74,7 +74,8 @@ const CREDENTIAL_SUFFIXES = [
74
74
  "_signature", "_credential", "_credentials",
75
75
  ];
76
76
 
77
- function credentialParam(name: string): boolean {
77
+ /** @internal Whether a param named `name` carries a credential. */
78
+ export function credentialParam(name: string): boolean {
78
79
  try {
79
80
  name = decodeURIComponent(name.replace(/\+/g, " "));
80
81
  } catch {
@@ -98,7 +99,8 @@ export function scrubSecrets(msg: string, secrets: readonly string[]): string {
98
99
 
99
100
  // ─── Endpoints ───────────────────────────────────────────────────────────────
100
101
 
101
- interface Endpoint {
102
+ /** @internal */
103
+ export interface Endpoint {
102
104
  scheme: string;
103
105
  host: string;
104
106
  port: string;
@@ -111,7 +113,7 @@ interface Endpoint {
111
113
  * percent-escape, whitespace or a control character: forms where
112
114
  * parsers disagree on the host.
113
115
  */
114
- function parseEndpoint(raw: string): Endpoint | undefined {
116
+ export function parseEndpoint(raw: string): Endpoint | undefined {
115
117
  if (/[\\%]/.test(raw) || /[\u0000- \u007f\s]/.test(raw)) {
116
118
  return undefined;
117
119
  }
@@ -134,7 +136,8 @@ function parseEndpoint(raw: string): Endpoint | undefined {
134
136
  return { scheme, host: u.hostname.toLowerCase(), port };
135
137
  }
136
138
 
137
- function origin(e: Endpoint): string {
139
+ /** @internal */
140
+ export function origin(e: Endpoint): string {
138
141
  return `${e.scheme}://${e.host}:${e.port}`;
139
142
  }
140
143
 
@@ -184,6 +187,22 @@ export interface ProviderKey {
184
187
  export interface Declaration {
185
188
  endpoints?: string[];
186
189
  key?: ProviderKey;
190
+ /** The scheme's default endpoint; see {@link keyBoundToDefault}. */
191
+ baseURL?: string;
192
+ /**
193
+ * Makes the scheme's ambient credentials (its provider variables and
194
+ * `LLM_API_KEY`) belong to {@link baseURL} alone. When the URI names
195
+ * another endpoint (a host or `base_url` param), or `LLM_BASE_URL` or
196
+ * the llm.yaml block's `base_url` does, none of them is lent: only a
197
+ * key the caller set for that endpoint resolves, namely the URI's
198
+ * `api_key`, llm.yaml `api_key`, or the variable llm.yaml
199
+ * `api_key_env` names. No key then is no error: a compatible server
200
+ * may take none. An endpoint sharing `baseURL`'s origin counts as the
201
+ * default; one that does not parse counts as custom. Needs
202
+ * `baseURL`; set it for adapters whose hosted key must not reach a
203
+ * self-hosted compatible server.
204
+ */
205
+ keyBoundToDefault?: boolean;
187
206
  }
188
207
 
189
208
  const declarations = new Map<string, Declaration>();
@@ -240,7 +259,8 @@ export function trustedOrigin(
240
259
  const e = parseEndpoint(baseURL);
241
260
  if (!e) return false;
242
261
  if (isLoopback(e.host)) return true;
243
- const trusted = [...(declarations.get(scheme)?.endpoints ?? []), ...extra];
262
+ const decl = declarations.get(scheme);
263
+ const trusted = [...(decl?.baseURL ? [decl.baseURL] : []), ...(decl?.endpoints ?? []), ...extra];
244
264
  if (ambient) {
245
265
  const file = providerBlock(readLLMFile(), scheme)?.baseURL;
246
266
  if (file) trusted.push(file);
package/src/llm-keys.ts CHANGED
@@ -13,13 +13,15 @@ import {
13
13
  checkKeyEndpoint,
14
14
  declarationOf,
15
15
  isRegistered,
16
+ origin,
17
+ parseEndpoint,
16
18
  redactURI,
17
19
  trustedOrigin,
18
20
  } from "./llm-endpoint";
19
21
  import { LLMError } from "./llm-error";
20
22
  import { KeyEndpointError, MissingKeyError } from "./llm-errors";
21
- import { providerBlock, readLLMFile, type LLMFile } from "./llm-file";
22
- import { parseURI } from "./llm-uri";
23
+ import { providerBlock, readLLMFile, type LLMFile, type LLMFileProvider } from "./llm-file";
24
+ import { escapeParam, parseURI, percentDecode } from "./llm-uri";
23
25
 
24
26
  /** The universal key variable, lent to a scheme that requires a key. */
25
27
  export const FALLBACK_ENV_KEY = "LLM_API_KEY";
@@ -53,7 +55,10 @@ export function uriKey(u: URI): string | undefined {
53
55
  * {@link ProviderKey} or `<SCHEME>_API_KEY`); `LLM_API_KEY` for a
54
56
  * registered scheme that requires a key. A scheme no adapter serves
55
57
  * takes only what its own llm.yaml block names. Blank counts as unset
56
- * everywhere.
58
+ * everywhere. For a scheme declaring `keyBoundToDefault`, an endpoint
59
+ * other than its default leaves just the URI's `api_key`, llm.yaml
60
+ * `api_key` and the variable `api_key_env` names: no provider
61
+ * variable, no `LLM_API_KEY`, and no key is no error.
57
62
  */
58
63
  export function resolveKey(u: URI, file: LLMFile): ResolvedKey {
59
64
  const own = uriKey(u);
@@ -66,12 +71,19 @@ export function resolveKey(u: URI, file: LLMFile): ResolvedKey {
66
71
  if (block && !blankKey(block.apiKeyEnv)) {
67
72
  names = [block.apiKeyEnv, ...names.filter((n) => n !== block.apiKeyEnv)];
68
73
  }
74
+ let required = known && decl?.optional !== true;
75
+ if (customEndpoint(u, block)) {
76
+ // The ambient key is the default endpoint's: only the variable
77
+ // llm.yaml api_key_env names is the user's for this one, and a
78
+ // compatible server may take no key.
79
+ names = block && !blankKey(block.apiKeyEnv) ? [block.apiKeyEnv] : [];
80
+ required = false;
81
+ }
69
82
  if (names.length === 0) return { value: "", source: "" };
70
83
  for (const n of names) {
71
84
  const v = process.env[n];
72
85
  if (v !== undefined && !blankKey(v)) return { value: v, source: "env" };
73
86
  }
74
- const required = known && decl?.optional !== true;
75
87
  if (!required) return { value: "", source: "" };
76
88
  const fb = process.env[FALLBACK_ENV_KEY];
77
89
  if (fb !== undefined && !blankKey(fb)) return { value: fb, source: "fallback" };
@@ -82,6 +94,24 @@ export function resolveKey(u: URI, file: LLMFile): ResolvedKey {
82
94
  };
83
95
  }
84
96
 
97
+ /**
98
+ * Whether a request for `u` goes to an endpoint other than the default
99
+ * of a scheme declaring `keyBoundToDefault`: the one the URI names
100
+ * (`base_url` param, else host), else `LLM_BASE_URL`, else the llm.yaml
101
+ * block's `base_url`, in the order {@link loadConfig} applies them.
102
+ * Origins are compared; an endpoint that does not parse is custom.
103
+ */
104
+ function customEndpoint(u: URI, block: LLMFileProvider | undefined): boolean {
105
+ const decl = declarationOf(u.scheme);
106
+ if (!decl?.keyBoundToDefault || !decl.baseURL) return false;
107
+ const cand = uriEndpoint(u) || process.env["LLM_BASE_URL"] || block?.baseURL || "";
108
+ if (cand === "") return false;
109
+ const c = parseEndpoint(cand);
110
+ if (!c) return true;
111
+ const d = parseEndpoint(decl.baseURL);
112
+ return !d || origin(c) !== origin(d);
113
+ }
114
+
85
115
  /** The endpoint a URI itself names: its `base_url`, else its host. */
86
116
  export function uriEndpoint(u: URI): string {
87
117
  const b = u.params?.["base_url"];
@@ -115,7 +145,10 @@ export function dropBlankURIKey(u: URI): void {
115
145
  if (Object.keys(u.params!).length === 0) delete u.params;
116
146
  }
117
147
 
118
- /** `raw` without any `name` param; the `?` goes too when none is left. */
148
+ /**
149
+ * `raw` without any `name` param, names compared decoded; the `?` goes
150
+ * too when none is left.
151
+ */
119
152
  function stripURIParam(raw: string, name: string): string {
120
153
  const s = raw.indexOf("://");
121
154
  if (s < 0) return raw;
@@ -124,7 +157,10 @@ function stripURIParam(raw: string, name: string): string {
124
157
  const kept = raw
125
158
  .slice(q + 1)
126
159
  .split("&")
127
- .filter((p) => p.split("=", 1)[0] !== name);
160
+ .filter((p) => {
161
+ const k = p.split("=", 1)[0]!;
162
+ return (percentDecode(k) ?? k) !== name;
163
+ });
128
164
  return kept.length === 0 ? raw.slice(0, q) : `${raw.slice(0, q + 1)}${kept.join("&")}`;
129
165
  }
130
166
 
@@ -137,7 +173,8 @@ function stripURIParam(raw: string, name: string): string {
137
173
  * names none. A required key found nowhere throws a
138
174
  * {@link MissingKeyError}. Go `ApplyAPIKey` without a secret store.
139
175
  *
140
- * The result holds the key: never log it. Errors never carry it.
176
+ * The key is added escaped, as {@link parseURI} decodes it. The result
177
+ * holds the key: never log it. Errors never carry it.
141
178
  */
142
179
  export function applyAPIKey(uri: string): string {
143
180
  let parsed: URI;
@@ -156,12 +193,7 @@ export function applyAPIKey(uri: string): string {
156
193
  if (key.missing) throw key.missing;
157
194
  guardKeyEndpoint(parsed, key.value, key.source);
158
195
  if (key.source === "uri" || key.value === "") return uri;
159
- // The query splits on & and is not unescaped: a key holding a
160
- // separator cannot travel as a param intact.
161
- if (/[&?#]/.test(key.value)) {
162
- throw new LLMError(
163
- `llm: ${parsed.scheme} API key contains a character a provider URI cannot carry (& ? #)`
164
- );
165
- }
166
- return `${uri}${uri.includes("?") ? "&" : "?"}api_key=${key.value}`;
196
+ // The value travels escaped: parseURI decodes it, so a key holding a
197
+ // separator or a "%" arrives intact.
198
+ return `${uri}${uri.includes("?") ? "&" : "?"}api_key=${escapeParam(key.value)}`;
167
199
  }
@@ -19,6 +19,7 @@ import {
19
19
  ToolNameError,
20
20
  createLLM,
21
21
  isFallbackable,
22
+ loadConfig,
22
23
  resolve,
23
24
  type Message,
24
25
  type ResolvedConfig,
@@ -449,8 +450,12 @@ describe("openai registry", () => {
449
450
  it("resolves every scheme and reads <SCHEME>_API_KEY", async () => {
450
451
  const s = await server((_h, res) => reply(res, "application/json", completion({ content: "ok" })));
451
452
  process.env["OPENROUTER_API_KEY"] = "or-key";
452
- process.env["LLM_BASE_URL"] = s.url;
453
- await resolve("openrouter://openai/gpt-4.1-nano").complete!({ messages: HI });
453
+ expect(loadConfig("openrouter://openai/gpt-4.1-nano").provider.apiKey).toBe("or-key");
454
+ // The env key is openrouter.ai's: a server of our own gets the
455
+ // URI's key.
456
+ await resolve(`openrouter://openai/gpt-4.1-nano?base_url=${s.url}&api_key=or-key`).complete!({
457
+ messages: HI,
458
+ });
454
459
  expect(s.hits[0]!.headers["authorization"]).toBe("Bearer or-key");
455
460
  expect(JSON.parse(s.hits[0]!.body).model).toBe("openai/gpt-4.1-nano");
456
461
  for (const scheme of ["openai", "xai", "groq", "together", "fireworks", "deepseek", "mistral"]) {
@@ -460,8 +465,9 @@ describe("openai registry", () => {
460
465
 
461
466
  it("keeps an env key off an endpoint only the URI names", () => {
462
467
  process.env["OPENAI_API_KEY"] = "env-key";
463
- expect(() => resolve("openai://m?base_url=https://evil.example.test/v1")).toThrow(
464
- KeyEndpointError
468
+ // The hosted key is lent to no other endpoint: none goes there.
469
+ expect(loadConfig("openai://m?base_url=https://evil.example.test/v1").provider.apiKey).toBe(
470
+ undefined
465
471
  );
466
472
  // The URI's own key is the caller's choice for an https host.
467
473
  expect(() =>
package/src/llm-openai.ts CHANGED
@@ -700,8 +700,14 @@ function openaiFactory(cfg: ResolvedConfig): Provider {
700
700
  }
701
701
 
702
702
  for (const s of OPENAI_SCHEMES) {
703
+ const base = OPENAI_BASE_URLS[s] ?? OPENAI_DEFAULT_BASE_URL;
703
704
  register(s, openaiFactory, {
704
- endpoints: [OPENAI_BASE_URLS[s] ?? OPENAI_DEFAULT_BASE_URL],
705
+ endpoints: [base],
706
+ // The hosted key belongs to the hosted endpoint: a server named by
707
+ // another base URL (vLLM, llama.cpp, LiteLLM) gets only a key set
708
+ // for it.
709
+ baseURL: base,
710
+ keyBoundToDefault: true,
705
711
  // LM Studio's local server takes no key: none is resolved for it.
706
712
  ...(s === "lmstudio" ? { key: { envVars: [], optional: true } } : {}),
707
713
  });