@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.
- package/CHANGELOG.md +22 -0
- package/dist/{chunk-BXJ2J27B.js → chunk-IGKBRNEW.js} +10 -10
- package/dist/{chunk-VWGP4NVJ.js → chunk-MDVGMOZO.js} +45 -39
- package/dist/{chunk-4FMALWYB.js → chunk-MEF7W3MG.js} +45 -45
- package/dist/{chunk-VGOA5Y7S.js → chunk-Q547MHNB.js} +11 -11
- package/dist/{chunk-K7E34Q3A.js → chunk-TUU2BY5I.js} +136 -47
- package/dist/index.d.ts +4 -4
- package/dist/index.js +6 -6
- package/dist/{llm-DYuR7_uX.d.ts → llm-BazFKc_2.d.ts} +95 -9
- package/dist/{llm-anthropic-Cd_I2xXB.d.ts → llm-anthropic-BcAitoDV.d.ts} +1 -1
- package/dist/llm-anthropic.d.ts +2 -2
- package/dist/llm-anthropic.js +4 -4
- package/dist/{llm-openai-DyFrucmV.d.ts → llm-openai-CSDvuRH6.d.ts} +1 -1
- package/dist/llm-openai.d.ts +2 -2
- package/dist/llm-openai.js +4 -4
- package/dist/llm.d.ts +1 -1
- package/dist/llm.js +8 -2
- package/dist/{routellm-B0nv59mH.d.ts → routellm-B9UrONPr.d.ts} +1 -1
- package/dist/routellm.d.ts +2 -2
- package/dist/routellm.js +5 -5
- package/package.json +5 -5
- package/skills/hop-top-kit-ts/.claude-plugin/plugin.json +1 -1
- package/skills/hop-top-kit-ts/SKILL.md +2 -2
- package/skills/hop-top-kit-ts/references/other-ports.md +1 -1
- package/src/llm-anthropic.conformance.test.ts +7 -0
- package/src/llm-boundkey.test.ts +260 -0
- package/src/llm-choice-hermetic.test.ts +1 -1
- package/src/llm-config.test.ts +2 -4
- package/src/llm-config.ts +5 -1
- package/src/llm-endpoint.ts +25 -5
- package/src/llm-keys.ts +47 -15
- package/src/llm-openai.test.ts +10 -4
- package/src/llm-openai.ts +7 -1
- package/src/llm-spec.test.ts +347 -0
- package/src/llm-spec.ts +80 -0
- package/src/llm-uri.ts +96 -12
- package/src/llm.test.ts +2 -2
- package/src/llm.ts +10 -0
- package/test/llm/conformance-helpers.ts +3 -0
|
@@ -0,0 +1,347 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* parseURI decoding, applyAPIKey escaping and the typed Spec. Go `llm`
|
|
3
|
+
* (spec_test.go) is canonical; the llm-v1 parse_uri and key_endpoint
|
|
4
|
+
* vectors pin the shared cases, these the rest: the model-name
|
|
5
|
+
* injection a Spec closes, round trips and the Spec guards.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { mkdirSync, writeFileSync } from "node:fs";
|
|
9
|
+
import { join } from "node:path";
|
|
10
|
+
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
|
11
|
+
|
|
12
|
+
import {
|
|
13
|
+
KeyEndpointError,
|
|
14
|
+
LLMError,
|
|
15
|
+
applyAPIKey,
|
|
16
|
+
clearRegistry,
|
|
17
|
+
loadConfig,
|
|
18
|
+
loadConfigSpec,
|
|
19
|
+
parseURI,
|
|
20
|
+
register,
|
|
21
|
+
resolve,
|
|
22
|
+
resolveSpec,
|
|
23
|
+
specURI,
|
|
24
|
+
type Provider,
|
|
25
|
+
type ResolvedConfig,
|
|
26
|
+
type Spec,
|
|
27
|
+
} from "./llm";
|
|
28
|
+
import {
|
|
29
|
+
fakeServer,
|
|
30
|
+
isolateEnv,
|
|
31
|
+
type FakeServer,
|
|
32
|
+
} from "../test/llm/conformance-helpers";
|
|
33
|
+
|
|
34
|
+
const KEY = "fake-spec-key-must-stay-home";
|
|
35
|
+
const ENV = [
|
|
36
|
+
"LLM_API_KEY", "LLM_BASE_URL", "LLM_PROVIDER", "LLM_FALLBACK",
|
|
37
|
+
"SPECKEY_API_KEY",
|
|
38
|
+
];
|
|
39
|
+
|
|
40
|
+
let restoreEnv: () => void;
|
|
41
|
+
const servers: FakeServer[] = [];
|
|
42
|
+
const built: ResolvedConfig[] = [];
|
|
43
|
+
const sent: Promise<unknown>[] = [];
|
|
44
|
+
|
|
45
|
+
beforeEach(() => {
|
|
46
|
+
restoreEnv = isolateEnv(ENV);
|
|
47
|
+
built.length = 0;
|
|
48
|
+
// specprobe records each config it is built from and, as an adapter
|
|
49
|
+
// would, sends its key to the base URL it settled on.
|
|
50
|
+
register(
|
|
51
|
+
"specprobe",
|
|
52
|
+
(cfg): Provider => {
|
|
53
|
+
built.push(cfg);
|
|
54
|
+
const base = cfg.provider.baseURL ?? "";
|
|
55
|
+
if (base.startsWith("http://127.0.0.1")) {
|
|
56
|
+
const headers: Record<string, string> = {};
|
|
57
|
+
if (cfg.provider.apiKey) headers["authorization"] = `Bearer ${cfg.provider.apiKey}`;
|
|
58
|
+
sent.push(fetch(base, { method: "POST", headers }).catch(() => undefined));
|
|
59
|
+
}
|
|
60
|
+
return { close: () => undefined };
|
|
61
|
+
},
|
|
62
|
+
{ endpoints: ["https://api.specprobe.test/v1"] }
|
|
63
|
+
);
|
|
64
|
+
register("speckey", () => ({ close: () => undefined }), {
|
|
65
|
+
baseURL: "https://api.speckey.test/v1",
|
|
66
|
+
keyBoundToDefault: true,
|
|
67
|
+
});
|
|
68
|
+
});
|
|
69
|
+
afterEach(async () => {
|
|
70
|
+
restoreEnv();
|
|
71
|
+
clearRegistry();
|
|
72
|
+
writeYaml("");
|
|
73
|
+
await Promise.all(sent.splice(0));
|
|
74
|
+
await Promise.all(servers.splice(0).map((s) => s.close()));
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
async function recorder(): Promise<FakeServer> {
|
|
78
|
+
const s = await fakeServer((_h, res) => {
|
|
79
|
+
res.statusCode = 200;
|
|
80
|
+
res.end();
|
|
81
|
+
});
|
|
82
|
+
servers.push(s);
|
|
83
|
+
return s;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const auths = (s: FakeServer): (string | undefined)[] => s.hits.map((h) => h.headers["authorization"]);
|
|
87
|
+
|
|
88
|
+
function writeYaml(yaml: string): void {
|
|
89
|
+
const dir = join(process.env["XDG_CONFIG_HOME"]!, "hop");
|
|
90
|
+
mkdirSync(dir, { recursive: true });
|
|
91
|
+
writeFileSync(join(dir, "llm.yaml"), yaml);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function lastProbe(): ResolvedConfig {
|
|
95
|
+
expect(built.length).toBeGreaterThan(0);
|
|
96
|
+
return built[built.length - 1]!;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
describe("Spec: a model name is data", () => {
|
|
100
|
+
it("concatenation is the hazard; a Spec keeps the model a model", async () => {
|
|
101
|
+
const good = await recorder();
|
|
102
|
+
const evil = await recorder();
|
|
103
|
+
const model = `x?base_url=${evil.url}&z=`;
|
|
104
|
+
|
|
105
|
+
// The hazard a Spec removes: the key follows the injected base_url.
|
|
106
|
+
resolve(`specprobe://${model}?base_url=${good.url}&api_key=${KEY}`);
|
|
107
|
+
await Promise.all(sent.splice(0));
|
|
108
|
+
expect(auths(evil)).toEqual([`Bearer ${KEY}`]);
|
|
109
|
+
|
|
110
|
+
const before = evil.hits.length;
|
|
111
|
+
resolveSpec({ scheme: "specprobe", model, baseURL: good.url, apiKey: KEY });
|
|
112
|
+
await Promise.all(sent.splice(0));
|
|
113
|
+
const cfg = lastProbe();
|
|
114
|
+
expect(cfg.provider.model).toBe(model);
|
|
115
|
+
expect(cfg.provider.baseURL).toBe(good.url);
|
|
116
|
+
expect(auths(good)).toEqual([`Bearer ${KEY}`]);
|
|
117
|
+
expect(evil.hits.length, "no request, no Authorization to the attacker").toBe(before);
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
it("a model with a param separator and no baseURL injects nothing", () => {
|
|
121
|
+
const model = "x?base_url=http://127.0.0.1:1&z=";
|
|
122
|
+
const cfg = loadConfigSpec({ scheme: "specprobe", model, apiKey: KEY });
|
|
123
|
+
expect(cfg.provider.model).toBe(model);
|
|
124
|
+
expect(cfg.provider.baseURL).toBeUndefined();
|
|
125
|
+
expect(cfg.provider.params).not.toHaveProperty("base_url");
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
it("an escaped-by-hand URI round-trips", () => {
|
|
129
|
+
const evil = "http://127.0.0.1:1";
|
|
130
|
+
const uri =
|
|
131
|
+
"specprobe://x%3Fbase_url%3D" +
|
|
132
|
+
evil.replace(/:/g, "%3A").replace(/\//g, "%2F") +
|
|
133
|
+
`?api_key=${KEY}`;
|
|
134
|
+
const p = parseURI(uri);
|
|
135
|
+
expect(p.model).toBe(`x?base_url=${evil}`);
|
|
136
|
+
expect(p.params).not.toHaveProperty("base_url");
|
|
137
|
+
});
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
describe("parseURI decoding", () => {
|
|
141
|
+
const cases: [string, string, string, Record<string, string> | undefined][] = [
|
|
142
|
+
["model", "s://a%2Fb%3Fc%26d%23e%25f", "a/b?c&d#e%f", undefined],
|
|
143
|
+
["param value", "s://m?k=a%26b%3Dc%25", "m", { k: "a&b=c%" }],
|
|
144
|
+
["param name", "s://m?a%26b=1", "m", { "a&b": "1" }],
|
|
145
|
+
["plus stays plus", "s://m+x?k=a+b", "m+x", { k: "a+b" }],
|
|
146
|
+
["unescaped unchanged", "s://org/m:1?k=https://h/p?q=1", "org/m:1", { k: "https://h/p?q=1" }],
|
|
147
|
+
["escaped colon is no host", "s://h%3A80/m", "h:80/m", undefined],
|
|
148
|
+
["multi-byte", "s://m%C3%A9?k=%E2%82%AC", "mé", { k: "€" }],
|
|
149
|
+
];
|
|
150
|
+
for (const [name, uri, model, params] of cases) {
|
|
151
|
+
it(name, () => {
|
|
152
|
+
const u = parseURI(uri);
|
|
153
|
+
expect(u.model).toBe(model);
|
|
154
|
+
expect(u.host).toBeUndefined();
|
|
155
|
+
expect(u.params).toEqual(params);
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
it("detects host:port on the raw text, then decodes the model", () => {
|
|
160
|
+
const u = parseURI("s://localhost:80/a%2Fb");
|
|
161
|
+
expect(u.host).toBe("localhost:80");
|
|
162
|
+
expect(u.model).toBe("a/b");
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
it("rejects a malformed escape, invalid UTF-8 and repeated security params", () => {
|
|
166
|
+
const bad: [string, string][] = [
|
|
167
|
+
["s://a%zz", "malformed percent-escape"],
|
|
168
|
+
["s://a%2", "malformed percent-escape"],
|
|
169
|
+
["s://a%", "malformed percent-escape"],
|
|
170
|
+
["s://m?k=%G1", "malformed percent-escape"],
|
|
171
|
+
["s://m?%G1=v", "malformed percent-escape"],
|
|
172
|
+
["s://m%FF", "malformed percent-escape"],
|
|
173
|
+
["s://m?k=%C3", "malformed percent-escape"],
|
|
174
|
+
["s://m?base_url=https://a&base_url=https://b", "duplicate"],
|
|
175
|
+
["s://m?api_key=a&api_key=b", "duplicate"],
|
|
176
|
+
["s://m?api_key=&api_key=", "duplicate"],
|
|
177
|
+
["s://m?api_key=a&api%5Fkey=b", "duplicate"],
|
|
178
|
+
["s://m?token=a&token=b", "duplicate"],
|
|
179
|
+
];
|
|
180
|
+
for (const [uri, want] of bad) {
|
|
181
|
+
let err: unknown;
|
|
182
|
+
try {
|
|
183
|
+
parseURI(uri);
|
|
184
|
+
} catch (e) {
|
|
185
|
+
err = e;
|
|
186
|
+
}
|
|
187
|
+
expect(err, uri).toBeInstanceOf(LLMError);
|
|
188
|
+
expect((err as Error).message, uri).toContain(want);
|
|
189
|
+
expect((err as Error).message, uri).not.toContain("=a&");
|
|
190
|
+
}
|
|
191
|
+
expect(parseURI("s://m?temperature=1&temperature=2").params).toEqual({ temperature: "2" });
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
it("masks the key in a malformed-escape error", () => {
|
|
195
|
+
expect(() => parseURI(`s://m%zz?api_key=${KEY}`)).toThrow(
|
|
196
|
+
'malformed percent-escape in URI "s://m%zz?api_key=REDACTED"'
|
|
197
|
+
);
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
it("keeps __proto__ an own param", () => {
|
|
201
|
+
const u = parseURI("s://m?__proto__=x");
|
|
202
|
+
expect(Object.keys(u.params!)).toEqual(["__proto__"]);
|
|
203
|
+
expect(({} as Record<string, unknown>)["x"]).toBeUndefined();
|
|
204
|
+
});
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
describe("specURI", () => {
|
|
208
|
+
const specs: Spec[] = [
|
|
209
|
+
{ scheme: "openai", model: "gpt-4o" },
|
|
210
|
+
{ scheme: "openrouter", model: "meta-llama/llama-3-70b" },
|
|
211
|
+
{ scheme: "ollama", model: "llama3:8b" },
|
|
212
|
+
{ scheme: "x", model: "h:80/m" },
|
|
213
|
+
{ scheme: "x", model: "a?b&c#d%e f+g=h" },
|
|
214
|
+
{ scheme: "x", model: "claude@2024", baseURL: "https://h.test/v1?a=1&b=2", apiKey: "k&?#%+= z" },
|
|
215
|
+
{ scheme: "x", params: { temperature: "0.2", "a&b": "c=d" } },
|
|
216
|
+
{ scheme: "x" },
|
|
217
|
+
{ scheme: "x", model: "é€" },
|
|
218
|
+
];
|
|
219
|
+
for (const s of specs) {
|
|
220
|
+
it(`round-trips ${JSON.stringify(s)}`, () => {
|
|
221
|
+
const uri = specURI(s);
|
|
222
|
+
const u = parseURI(uri);
|
|
223
|
+
expect(u.scheme).toBe(s.scheme);
|
|
224
|
+
expect(u.model).toBe(s.model ?? "");
|
|
225
|
+
expect(u.host, uri).toBeUndefined();
|
|
226
|
+
const want: Record<string, string> = { ...(s.params ?? {}) };
|
|
227
|
+
if (s.baseURL) want["base_url"] = s.baseURL;
|
|
228
|
+
if (s.apiKey) want["api_key"] = s.apiKey;
|
|
229
|
+
expect(u.params ?? {}, uri).toEqual(want);
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
it("sorts params by name, then base_url, then api_key", () => {
|
|
234
|
+
expect(
|
|
235
|
+
specURI({ scheme: "x", model: "m", params: { b: "2", a: "1" }, baseURL: "https://h", apiKey: "k" })
|
|
236
|
+
).toBe("x://m?a=1&b=2&base_url=https://h&api_key=k");
|
|
237
|
+
});
|
|
238
|
+
|
|
239
|
+
it("rejects what a URI cannot hold, without echoing the key", () => {
|
|
240
|
+
const bad: Record<string, Spec> = {
|
|
241
|
+
"empty scheme": { scheme: "", model: "m" },
|
|
242
|
+
"scheme injection": { scheme: "x://y?z=", model: "m" },
|
|
243
|
+
"scheme space": { scheme: "x y" },
|
|
244
|
+
"base_url param": { scheme: "x", params: { base_url: "https://a" } },
|
|
245
|
+
"api_key param": { scheme: "x", params: { api_key: KEY } },
|
|
246
|
+
"empty param name": { scheme: "x", params: { "": "v" } },
|
|
247
|
+
};
|
|
248
|
+
for (const [name, s] of Object.entries(bad)) {
|
|
249
|
+
expect(() => specURI(s), name).toThrow(LLMError);
|
|
250
|
+
expect(() => loadConfigSpec(s), name).toThrow(LLMError);
|
|
251
|
+
expect(() => resolveSpec(s), name).toThrow(LLMError);
|
|
252
|
+
try {
|
|
253
|
+
specURI(s);
|
|
254
|
+
} catch (e) {
|
|
255
|
+
expect((e as Error).message, name).not.toContain(KEY);
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
});
|
|
259
|
+
});
|
|
260
|
+
|
|
261
|
+
describe("a Spec resolves as the equivalent URI", () => {
|
|
262
|
+
const cases: { name: string; spec: Spec; uri: string; env?: Record<string, string>; refused?: boolean }[] = [
|
|
263
|
+
{ name: "scheme+model", spec: { scheme: "specprobe", model: "m" }, uri: "specprobe://m" },
|
|
264
|
+
{ name: "model with slash", spec: { scheme: "specprobe", model: "org/m" }, uri: "specprobe://org/m" },
|
|
265
|
+
{
|
|
266
|
+
name: "params",
|
|
267
|
+
spec: { scheme: "specprobe", model: "m", params: { temperature: "0.2", top_p: "0.9" } },
|
|
268
|
+
uri: "specprobe://m?temperature=0.2&top_p=0.9",
|
|
269
|
+
},
|
|
270
|
+
{
|
|
271
|
+
name: "base_url loopback + key",
|
|
272
|
+
spec: { scheme: "specprobe", model: "m", baseURL: "http://127.0.0.1:9/v1", apiKey: KEY },
|
|
273
|
+
uri: `specprobe://m?base_url=http://127.0.0.1:9/v1&api_key=${KEY}`,
|
|
274
|
+
},
|
|
275
|
+
{
|
|
276
|
+
name: "key https",
|
|
277
|
+
spec: { scheme: "specprobe", model: "m", baseURL: "https://llm.corp.test/v1", apiKey: KEY },
|
|
278
|
+
uri: `specprobe://m?base_url=https://llm.corp.test/v1&api_key=${KEY}`,
|
|
279
|
+
},
|
|
280
|
+
{
|
|
281
|
+
name: "env key refused off-origin",
|
|
282
|
+
spec: { scheme: "specprobe", model: "m", baseURL: "https://evil.test/v1" },
|
|
283
|
+
uri: "specprobe://m?base_url=https://evil.test/v1",
|
|
284
|
+
env: { LLM_API_KEY: KEY },
|
|
285
|
+
refused: true,
|
|
286
|
+
},
|
|
287
|
+
{
|
|
288
|
+
name: "key over plain http refused",
|
|
289
|
+
spec: { scheme: "specprobe", model: "m", baseURL: "http://remote.test/v1", apiKey: KEY },
|
|
290
|
+
uri: `specprobe://m?base_url=http://remote.test/v1&api_key=${KEY}`,
|
|
291
|
+
refused: true,
|
|
292
|
+
},
|
|
293
|
+
{
|
|
294
|
+
name: "bound hosted key off default",
|
|
295
|
+
spec: { scheme: "speckey", model: "m", baseURL: "http://127.0.0.1:9/v1" },
|
|
296
|
+
uri: "speckey://m?base_url=http://127.0.0.1:9/v1",
|
|
297
|
+
env: { SPECKEY_API_KEY: KEY },
|
|
298
|
+
},
|
|
299
|
+
{
|
|
300
|
+
name: "bound hosted key on default",
|
|
301
|
+
spec: { scheme: "speckey", model: "m" },
|
|
302
|
+
uri: "speckey://m",
|
|
303
|
+
env: { SPECKEY_API_KEY: KEY },
|
|
304
|
+
},
|
|
305
|
+
];
|
|
306
|
+
for (const tc of cases) {
|
|
307
|
+
it(tc.name, () => {
|
|
308
|
+
Object.assign(process.env, tc.env);
|
|
309
|
+
if (tc.refused) {
|
|
310
|
+
expect(() => loadConfig(tc.uri)).toThrow(KeyEndpointError);
|
|
311
|
+
let err: unknown;
|
|
312
|
+
try {
|
|
313
|
+
loadConfigSpec(tc.spec);
|
|
314
|
+
} catch (e) {
|
|
315
|
+
err = e;
|
|
316
|
+
}
|
|
317
|
+
expect(err).toBeInstanceOf(KeyEndpointError);
|
|
318
|
+
expect((err as Error).message).not.toContain(KEY);
|
|
319
|
+
return;
|
|
320
|
+
}
|
|
321
|
+
expect(loadConfigSpec(tc.spec)).toEqual(loadConfig(tc.uri));
|
|
322
|
+
});
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
it("a bound scheme's hosted key stays off a custom endpoint", () => {
|
|
326
|
+
process.env["SPECKEY_API_KEY"] = KEY;
|
|
327
|
+
const cfg = loadConfigSpec({ scheme: "speckey", model: "m", baseURL: "http://127.0.0.1:9/v1" });
|
|
328
|
+
expect(cfg.provider.apiKey).toBeUndefined();
|
|
329
|
+
});
|
|
330
|
+
});
|
|
331
|
+
|
|
332
|
+
describe("applyAPIKey escapes the key", () => {
|
|
333
|
+
it("a key holding separators reaches parseURI intact", () => {
|
|
334
|
+
const odd = "k&?#%+=z 1";
|
|
335
|
+
process.env["SPECKEY_API_KEY"] = odd;
|
|
336
|
+
const uri = applyAPIKey("speckey://m?temperature=1");
|
|
337
|
+
expect(uri).toBe("speckey://m?temperature=1&api_key=k%26%3F%23%25%2B%3Dz%201");
|
|
338
|
+
const u = parseURI(uri);
|
|
339
|
+
expect(u.params!["api_key"]).toBe(odd);
|
|
340
|
+
expect(u.params!["temperature"]).toBe("1");
|
|
341
|
+
});
|
|
342
|
+
|
|
343
|
+
it("drops a blank api_key named through an escape", () => {
|
|
344
|
+
process.env["SPECKEY_API_KEY"] = "k";
|
|
345
|
+
expect(applyAPIKey("speckey://m?api%5Fkey=&t=1")).toBe("speckey://m?t=1&api_key=k");
|
|
346
|
+
});
|
|
347
|
+
});
|
package/src/llm-spec.ts
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A provider named by its parts, not by a URI string: Go `llm.Spec`.
|
|
3
|
+
* Re-exported from `@hop-top/kit/llm`.
|
|
4
|
+
*
|
|
5
|
+
* @internal
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import type { ResolvedConfig } from "./llm";
|
|
9
|
+
import { loadConfig, type LoadOptions } from "./llm-config";
|
|
10
|
+
import { LLMError } from "./llm-error";
|
|
11
|
+
import { escapeModel, escapeParam } from "./llm-uri";
|
|
12
|
+
import { goQuote } from "./llm-quote";
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* A provider named by its parts. Building `"scheme://" + model +
|
|
16
|
+
* "?base_url=" + u` by hand lets a model name holding `?` or `&` add
|
|
17
|
+
* params of its own, among them a `base_url` that takes the API key to
|
|
18
|
+
* another host. A Spec keeps each part where it is: {@link specURI}
|
|
19
|
+
* escapes them, and `resolveSpec` and {@link loadConfigSpec} then run
|
|
20
|
+
* the same pipeline, with the same guards (key endpoint, hosted key
|
|
21
|
+
* bound to its default endpoint, base URL checks), as the URI they
|
|
22
|
+
* stand for.
|
|
23
|
+
*/
|
|
24
|
+
export interface Spec {
|
|
25
|
+
scheme: string;
|
|
26
|
+
/** The model; absent or empty for none. */
|
|
27
|
+
model?: string;
|
|
28
|
+
/** The `base_url` param; absent or empty for the provider's own. */
|
|
29
|
+
baseURL?: string;
|
|
30
|
+
/** The `api_key` param; absent or empty to resolve it as `applyAPIKey` does. */
|
|
31
|
+
apiKey?: string;
|
|
32
|
+
/**
|
|
33
|
+
* The other params. `base_url` and `api_key` belong in `baseURL` and
|
|
34
|
+
* `apiKey`: naming either here is an error.
|
|
35
|
+
*/
|
|
36
|
+
params?: Record<string, string>;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const SCHEME = /^[A-Za-z0-9\-._+]+$/;
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Renders `s` as an escaped provider URI that `parseURI` reads back as
|
|
43
|
+
* the same parts. It holds the key when `apiKey` is set: never log it
|
|
44
|
+
* (see `redactURI`). Throws an {@link LLMError} for an empty or invalid
|
|
45
|
+
* scheme and for an empty, `base_url` or `api_key` param name; the
|
|
46
|
+
* error never carries the key.
|
|
47
|
+
*/
|
|
48
|
+
export function specURI(s: Spec): string {
|
|
49
|
+
if (!s.scheme) throw new LLMError("llm: spec: empty scheme");
|
|
50
|
+
if (!SCHEME.test(s.scheme)) {
|
|
51
|
+
throw new LLMError(`llm: spec: invalid scheme ${goQuote(s.scheme)}`);
|
|
52
|
+
}
|
|
53
|
+
const names = Object.keys(s.params ?? {});
|
|
54
|
+
for (const k of names) {
|
|
55
|
+
if (k === "") throw new LLMError("llm: spec: empty param name");
|
|
56
|
+
if (k === "base_url") throw new LLMError("llm: spec: set base_url in baseURL, not params");
|
|
57
|
+
if (k === "api_key") throw new LLMError("llm: spec: set api_key in apiKey, not params");
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const q: string[] = [];
|
|
61
|
+
const add = (k: string, v: string): void => {
|
|
62
|
+
q.push(`${escapeParam(k)}=${escapeParam(v)}`);
|
|
63
|
+
};
|
|
64
|
+
// Byte order, as Go sorts.
|
|
65
|
+
names.sort((a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b)));
|
|
66
|
+
for (const k of names) add(k, s.params![k]!);
|
|
67
|
+
if (s.baseURL) add("base_url", s.baseURL);
|
|
68
|
+
if (s.apiKey) add("api_key", s.apiKey);
|
|
69
|
+
|
|
70
|
+
const uri = `${s.scheme}://${escapeModel(s.model ?? "")}`;
|
|
71
|
+
return q.length > 0 ? `${uri}?${q.join("&")}` : uri;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* {@link loadConfig} for a {@link Spec}. A Spec with no scheme is not
|
|
76
|
+
* the default provider: it is an error.
|
|
77
|
+
*/
|
|
78
|
+
export function loadConfigSpec(s: Spec, opts: LoadOptions = {}): ResolvedConfig {
|
|
79
|
+
return loadConfig(specURI(s), opts);
|
|
80
|
+
}
|
package/src/llm-uri.ts
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
8
|
import type { URI } from "./llm";
|
|
9
|
-
import { redactURI } from "./llm-endpoint";
|
|
9
|
+
import { credentialParam, redactURI } from "./llm-endpoint";
|
|
10
10
|
import { LLMError } from "./llm-error";
|
|
11
11
|
import { goQuote } from "./llm-quote";
|
|
12
12
|
|
|
@@ -18,13 +18,24 @@ import { goQuote } from "./llm-quote";
|
|
|
18
18
|
* `ollama://[::1]:11434/llama3`) when it splits as `host:port` with a
|
|
19
19
|
* non-empty port; otherwise the whole path is the model
|
|
20
20
|
* (`openrouter://openai/gpt-4.1-nano`). The query splits on `&`, each
|
|
21
|
-
* pair on its first
|
|
22
|
-
*
|
|
23
|
-
*
|
|
21
|
+
* pair on its first `=`; a param without `=` is `""`, one with an
|
|
22
|
+
* empty name is dropped. `params` is absent when none is left.
|
|
23
|
+
*
|
|
24
|
+
* The model and each param name and value are percent-decoded after
|
|
25
|
+
* the URI is split, so an escaped `?`, `&` or `#` is part of the text,
|
|
26
|
+
* never a separator: `x%3Fbase_url%3Dhttps%3A%2F%2Fevil` is a model of
|
|
27
|
+
* that literal text and sets no `base_url`. Only `%XX` is decoded; `+`
|
|
28
|
+
* stays `+`, so a key holding one survives. A malformed escape (or one
|
|
29
|
+
* that does not decode to UTF-8) is an error, as is a `base_url` or
|
|
30
|
+
* credential param (`api_key`, `token`, ...) named twice, whichever
|
|
31
|
+
* value would win; other params are last-wins. Build a URI from parts
|
|
32
|
+
* with {@link specURI}, never by concatenation: a raw `?` or `&` in a
|
|
33
|
+
* part still splits.
|
|
24
34
|
*
|
|
25
35
|
* Throws an {@link LLMError} (`empty URI`, `missing scheme in URI
|
|
26
|
-
* "..."`, `empty scheme in URI "..."
|
|
27
|
-
*
|
|
36
|
+
* "..."`, `empty scheme in URI "..."`, `malformed percent-escape in
|
|
37
|
+
* URI "..."`, `duplicate "name" param in URI "..."`) quoting `raw` with
|
|
38
|
+
* its credentials masked by {@link redactURI}.
|
|
28
39
|
*/
|
|
29
40
|
export function parseURI(raw: string): URI {
|
|
30
41
|
if (raw === "") throw new LLMError("empty URI");
|
|
@@ -37,7 +48,7 @@ export function parseURI(raw: string): URI {
|
|
|
37
48
|
let params: Record<string, string> | undefined;
|
|
38
49
|
const q = rest.indexOf("?");
|
|
39
50
|
if (q >= 0) {
|
|
40
|
-
params = parseQuery(rest.slice(q + 1));
|
|
51
|
+
params = parseQuery(rest.slice(q + 1), raw);
|
|
41
52
|
rest = rest.slice(0, q);
|
|
42
53
|
}
|
|
43
54
|
|
|
@@ -52,26 +63,99 @@ export function parseURI(raw: string): URI {
|
|
|
52
63
|
}
|
|
53
64
|
}
|
|
54
65
|
|
|
55
|
-
|
|
66
|
+
// Split first, decode after: an escaped separator stays text.
|
|
67
|
+
const decoded = percentDecode(model);
|
|
68
|
+
if (decoded === undefined) throw malformed(raw);
|
|
69
|
+
const uri: URI = { scheme, model: decoded };
|
|
56
70
|
if (host !== "") uri.host = host;
|
|
57
71
|
if (params && Object.keys(params).length > 0) uri.params = params;
|
|
58
72
|
return uri;
|
|
59
73
|
}
|
|
60
74
|
|
|
61
|
-
function parseQuery(qs: string): Record<string, string> | undefined {
|
|
75
|
+
function parseQuery(qs: string, raw: string): Record<string, string> | undefined {
|
|
62
76
|
if (qs === "") return undefined;
|
|
63
77
|
const m: Record<string, string> = {};
|
|
64
78
|
for (const pair of qs.split("&")) {
|
|
65
79
|
const eq = pair.indexOf("=");
|
|
66
|
-
const
|
|
67
|
-
const
|
|
68
|
-
if (
|
|
80
|
+
const rk = eq < 0 ? pair : pair.slice(0, eq);
|
|
81
|
+
const rv = eq < 0 ? "" : pair.slice(eq + 1);
|
|
82
|
+
if (rk === "") continue;
|
|
83
|
+
const k = percentDecode(rk);
|
|
84
|
+
const v = percentDecode(rv);
|
|
85
|
+
if (k === undefined || v === undefined) throw malformed(raw);
|
|
86
|
+
// Which of two security params wins must never depend on what a
|
|
87
|
+
// caller appended.
|
|
88
|
+
if (Object.prototype.hasOwnProperty.call(m, k) && (k === "base_url" || credentialParam(k))) {
|
|
89
|
+
throw new LLMError(`duplicate ${goQuote(k)} param in URI ${goQuote(redactURI(raw))}`);
|
|
90
|
+
}
|
|
69
91
|
// An own property even for "__proto__": never the prototype.
|
|
70
92
|
Object.defineProperty(m, k, { value: v, enumerable: true, writable: true, configurable: true });
|
|
71
93
|
}
|
|
72
94
|
return m;
|
|
73
95
|
}
|
|
74
96
|
|
|
97
|
+
function malformed(raw: string): LLMError {
|
|
98
|
+
return new LLMError(`malformed percent-escape in URI ${goQuote(redactURI(raw))}`);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Percent-decodes `s`: `%XX` only, `+` stays `+`. Undefined for an
|
|
103
|
+
* escape that is not two hex digits or whose bytes are not UTF-8.
|
|
104
|
+
*
|
|
105
|
+
* @internal
|
|
106
|
+
*/
|
|
107
|
+
export function percentDecode(s: string): string | undefined {
|
|
108
|
+
if (!s.includes("%")) return s;
|
|
109
|
+
if (/%(?![0-9A-Fa-f]{2})/.test(s)) return undefined;
|
|
110
|
+
try {
|
|
111
|
+
return s.replace(/(?:%[0-9A-Fa-f]{2})+/g, (run) => decodeURIComponent(run));
|
|
112
|
+
} catch {
|
|
113
|
+
return undefined;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const UNRESERVED = /[A-Za-z0-9\-._~]/;
|
|
118
|
+
const enc = new TextEncoder();
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Percent-escapes everything but unreserved characters and those in
|
|
122
|
+
* `keep`, as UTF-8.
|
|
123
|
+
*
|
|
124
|
+
* @internal
|
|
125
|
+
*/
|
|
126
|
+
export function escapeExcept(s: string, keep: string): string {
|
|
127
|
+
let out = "";
|
|
128
|
+
for (const ch of s) {
|
|
129
|
+
if (UNRESERVED.test(ch) || (ch.length === 1 && keep.includes(ch))) {
|
|
130
|
+
out += ch;
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
for (const b of enc.encode(ch)) out += `%${b.toString(16).toUpperCase().padStart(2, "0")}`;
|
|
134
|
+
}
|
|
135
|
+
return out;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Escapes a param name or value as {@link parseURI} decodes it: `&`,
|
|
140
|
+
* `#`, `%`, `+` and `=` are escaped, `:` `/` `@` kept for readability.
|
|
141
|
+
*
|
|
142
|
+
* @internal
|
|
143
|
+
*/
|
|
144
|
+
export function escapeParam(s: string): string {
|
|
145
|
+
return escapeExcept(s, ":/@");
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Escapes a model: everything but unreserved characters, `/` and `@`,
|
|
150
|
+
* so `:` cannot pass for a host:port and `?`, `&`, `#` and `%` stay
|
|
151
|
+
* text.
|
|
152
|
+
*
|
|
153
|
+
* @internal
|
|
154
|
+
*/
|
|
155
|
+
export function escapeModel(s: string): string {
|
|
156
|
+
return escapeExcept(s, "/@");
|
|
157
|
+
}
|
|
158
|
+
|
|
75
159
|
/** Go `net.SplitHostPort`: undefined where Go returns an error. */
|
|
76
160
|
function splitHostPort(hp: string): [string, string] | undefined {
|
|
77
161
|
const i = hp.lastIndexOf(":");
|
package/src/llm.test.ts
CHANGED
|
@@ -110,9 +110,9 @@ describe("parseURI", () => {
|
|
|
110
110
|
expect(() => parseURI("")).toThrow("empty URI");
|
|
111
111
|
});
|
|
112
112
|
|
|
113
|
-
it("
|
|
113
|
+
it("percent-decodes param values", () => {
|
|
114
114
|
const uri = parseURI("openai://gpt-4?base_url=https%3A%2F%2Fx.test&flag");
|
|
115
|
-
expect(uri.params).toEqual({ base_url: "https
|
|
115
|
+
expect(uri.params).toEqual({ base_url: "https://x.test", flag: "" });
|
|
116
116
|
});
|
|
117
117
|
|
|
118
118
|
it("takes an IPv6 host form", () => {
|
package/src/llm.ts
CHANGED
|
@@ -57,6 +57,7 @@ import {
|
|
|
57
57
|
} from "./llm-endpoint";
|
|
58
58
|
import { loadConfig, type LoadOptions } from "./llm-config";
|
|
59
59
|
import { parseURI } from "./llm-uri";
|
|
60
|
+
import { specURI, type Spec } from "./llm-spec";
|
|
60
61
|
export {
|
|
61
62
|
checkKeyEndpoint,
|
|
62
63
|
credentialsTrusted,
|
|
@@ -65,6 +66,7 @@ export {
|
|
|
65
66
|
} from "./llm-endpoint";
|
|
66
67
|
export { loadConfig, parseURI, type LoadOptions };
|
|
67
68
|
export { applyAPIKey } from "./llm-keys";
|
|
69
|
+
export { loadConfigSpec, specURI, type Spec } from "./llm-spec";
|
|
68
70
|
export {
|
|
69
71
|
requestStartedPayload,
|
|
70
72
|
responseReceivedPayload,
|
|
@@ -757,6 +759,14 @@ export function resolve(uriStr: string, opts: LoadOptions = {}): Provider {
|
|
|
757
759
|
return factory(cfg);
|
|
758
760
|
}
|
|
759
761
|
|
|
762
|
+
/**
|
|
763
|
+
* {@link resolve} for a {@link Spec}: the Spec's parts are escaped
|
|
764
|
+
* into the URI, so no part can add a param of its own.
|
|
765
|
+
*/
|
|
766
|
+
export function resolveSpec(s: Spec, opts: LoadOptions = {}): Provider {
|
|
767
|
+
return resolve(specURI(s), opts);
|
|
768
|
+
}
|
|
769
|
+
|
|
760
770
|
/** Clear the registry (for tests). */
|
|
761
771
|
export function clearRegistry(): void {
|
|
762
772
|
registry.clear();
|
|
@@ -78,6 +78,9 @@ export const LLM_ENV = [
|
|
|
78
78
|
"ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_BASE_URL",
|
|
79
79
|
"ANTHROPIC_WORKSPACE_ID", "LLM_BASE_URL", "LLM_API_KEY", "LLM_PROVIDER",
|
|
80
80
|
"LLM_FALLBACK", "OPENAI_API_KEY", "ROUTELLM_BASE_URL",
|
|
81
|
+
// The other openai-family schemes' key variables.
|
|
82
|
+
"OPENROUTER_API_KEY", "XAI_API_KEY", "LMSTUDIO_API_KEY", "GROQ_API_KEY",
|
|
83
|
+
"TOGETHER_API_KEY", "FIREWORKS_API_KEY", "DEEPSEEK_API_KEY", "MISTRAL_API_KEY",
|
|
81
84
|
];
|
|
82
85
|
|
|
83
86
|
/** Snapshots `keys`, clears them, and returns a restore function. */
|