@hop-top/kit 0.5.0-alpha.12 → 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 +51 -0
- package/README.md +5 -5
- package/dist/bus-D2bAOPYz.d.ts +55 -0
- package/dist/bus.d.ts +1 -0
- package/dist/bus.js +13 -0
- package/dist/chunk-74E6RNOI.js +82 -0
- package/dist/chunk-B7XTFDBB.js +17 -0
- package/dist/chunk-CAONBSPO.js +497 -0
- package/dist/chunk-F7RSL4N4.js +88 -0
- package/dist/chunk-I6XDPSXQ.js +75 -0
- package/dist/chunk-IDM6YZXN.js +204 -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/chunk-VKQCOVKI.js +880 -0
- package/dist/cli.js +3 -3
- package/dist/index-BqZ7WGQf.d.ts +731 -0
- package/dist/index.d.ts +8 -5
- package/dist/index.js +32 -18
- 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/dist/upgrade/drivers/configfile.d.ts +45 -0
- package/dist/upgrade/drivers/configfile.js +78 -0
- package/dist/upgrade/drivers/fsdir.d.ts +61 -0
- package/dist/upgrade/drivers/fsdir.js +170 -0
- package/dist/upgrade/drivers/postgres.d.ts +121 -0
- package/dist/upgrade/drivers/postgres.js +195 -0
- package/dist/upgrade/drivers/sqlite.d.ts +101 -0
- package/dist/upgrade/drivers/sqlite.js +241 -0
- package/dist/upgrade/index.d.ts +2 -0
- package/dist/upgrade/index.js +73 -0
- package/dist/uri-IJ_AoY3d.d.ts +144 -0
- package/dist/uri.d.ts +1 -0
- package/dist/uri.js +37 -0
- package/dist/version-DEJ3pbiO.d.ts +10 -0
- package/dist/wizard-Bf_qHc31.d.ts +159 -0
- package/dist/wizard.d.ts +1 -0
- package/dist/wizard.js +39 -0
- package/package.json +76 -17
- package/skills/hop-top-kit-ts/.claude-plugin/plugin.json +19 -0
- package/skills/hop-top-kit-ts/SKILL.md +117 -0
- package/skills/hop-top-kit-ts/assets/snippets/mcp/mcp.expected +2 -0
- package/skills/hop-top-kit-ts/assets/snippets/mcp/mcp.ts +20 -0
- package/skills/hop-top-kit-ts/assets/snippets/quickstart/quickstart.expected +13 -0
- package/skills/hop-top-kit-ts/assets/snippets/quickstart/quickstart.ts +26 -0
- package/skills/hop-top-kit-ts/gym.json +5 -0
- package/skills/hop-top-kit-ts/references/ai-and-agents.md +45 -0
- package/skills/hop-top-kit-ts/references/cli-and-console.md +63 -0
- package/skills/hop-top-kit-ts/references/coverage.md +56 -0
- package/skills/hop-top-kit-ts/references/guardrails-and-trust.md +60 -0
- package/skills/hop-top-kit-ts/references/other-ports.md +31 -0
- package/skills/hop-top-kit-ts/references/serving-and-transports.md +49 -0
- package/skills/hop-top-kit-ts/scripts/detect-port.sh +168 -0
- package/src/index.test.ts +48 -2
- package/src/index.ts +6 -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/src/published-types.test.ts +8 -0
- package/src/serve.stopped-order.test.ts +156 -0
- package/src/upgrade/README.md +42 -0
- package/src/upgrade/backup.ts +174 -0
- package/src/upgrade/conformance.test.ts +310 -0
- package/src/upgrade/document.ts +229 -0
- package/src/upgrade/driver.ts +66 -0
- package/src/upgrade/drivers/README.md +47 -0
- package/src/upgrade/drivers/configfile.test.ts +112 -0
- package/src/upgrade/drivers/configfile.ts +107 -0
- package/src/upgrade/drivers/fsdir.test.ts +188 -0
- package/src/upgrade/drivers/fsdir.ts +216 -0
- package/src/upgrade/drivers/isolation.test.ts +18 -0
- package/src/upgrade/drivers/postgres.integration.test.ts +395 -0
- package/src/upgrade/drivers/postgres.test.ts +272 -0
- package/src/upgrade/drivers/postgres.ts +284 -0
- package/src/upgrade/drivers/sqlite.integration.test.ts +492 -0
- package/src/upgrade/drivers/sqlite.ts +300 -0
- package/src/upgrade/drivers/version.ts +21 -0
- package/src/upgrade/errors.ts +117 -0
- package/src/upgrade/events.ts +117 -0
- package/src/{upgrade.test.ts → upgrade/index.test.ts} +1 -1
- package/src/{upgrade.ts → upgrade/index.ts} +20 -0
- package/src/upgrade/migration.ts +89 -0
- package/src/upgrade/migrator.test.ts +391 -0
- package/src/upgrade/migrator.ts +527 -0
- package/src/upgrade/options.ts +59 -0
- package/src/upgrade/semver.ts +90 -0
- package/test/llm/conformance-helpers.ts +3 -0
- package/test/skill-snippets.test.ts +60 -0
- package/test/upgrade/conformance-migrator.ts +439 -0
- package/test/upgrade/conformance-support.ts +44 -0
- package/test/upgrade/driver-support.ts +44 -0
- package/test/upgrade/pg-container.ts +64 -0
- package/test/upgrade/pg-race-worker.ts +48 -0
- package/test/upgrade/race-helper.ts +36 -0
- package/test/upgrade/sqlite-support.ts +41 -0
- package/test/upgrade/testdata/go-fsdir-mydata.tar.gz +0 -0
- package/vitest.config.ts +26 -0
- package/dist/chunk-X4E5QGEB.js +0 -171
- package/dist/upgrade-BJ2z6Oqf.d.ts +0 -156
- package/dist/upgrade.d.ts +0 -1
- package/dist/upgrade.js +0 -9
- package/dist/{chunk-MFVUENZR.js → chunk-KV7FYEAF.js} +2 -2
package/src/llm-endpoint.ts
CHANGED
|
@@ -74,7 +74,8 @@ const CREDENTIAL_SUFFIXES = [
|
|
|
74
74
|
"_signature", "_credential", "_credentials",
|
|
75
75
|
];
|
|
76
76
|
|
|
77
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
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
|
-
/**
|
|
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) =>
|
|
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
|
|
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
|
|
160
|
-
// separator
|
|
161
|
-
|
|
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
|
}
|
package/src/llm-openai.test.ts
CHANGED
|
@@ -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
|
-
|
|
453
|
-
|
|
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
|
-
|
|
464
|
-
|
|
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: [
|
|
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
|
});
|
|
@@ -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
|
+
}
|