@hop-top/kit 0.5.0-alpha.2 → 0.5.0-alpha.4
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 +60 -0
- package/LICENSE +1 -1
- package/README.md +48 -480
- package/dist/{aim-CTp-kJW2.d.ts → aim-DZHwwiIc.d.ts} +1 -1
- package/dist/aim.d.ts +1 -1
- package/dist/aim.js +13 -414
- package/dist/{alias-dhhr08Ei.d.ts → alias-BOj0-VAr.d.ts} +1 -1
- package/dist/alias.d.ts +1 -1
- package/dist/alias.js +18 -206
- package/dist/{api-miiso81x.d.ts → api-DAexsu2H.d.ts} +1 -1
- package/dist/api.d.ts +1 -1
- package/dist/api.js +10 -164
- package/dist/auth.js +6 -40
- package/dist/chunk-3FIKGFKI.js +54 -0
- package/dist/chunk-4UE5TCMQ.js +104 -0
- package/dist/chunk-6HFAEZ52.js +29 -0
- package/dist/chunk-6SVOHNIC.js +17 -0
- package/dist/chunk-72XZWQX7.js +504 -0
- package/dist/chunk-ABQSE7AI.js +513 -0
- package/dist/chunk-BDNNPRX6.js +41 -0
- package/dist/chunk-BRNEKPWX.js +37 -0
- package/dist/chunk-CSJWB6D3.js +151 -0
- package/dist/chunk-GGWJRWWA.js +309 -0
- package/dist/chunk-IQXEISMC.js +142 -0
- package/dist/chunk-JTMPNXVQ.js +1491 -0
- package/dist/chunk-KVG7YCTS.js +115 -0
- package/dist/chunk-L23O2FFE.js +51 -0
- package/dist/chunk-MQXYDYRD.js +968 -0
- package/dist/chunk-MUIQVU6E.js +251 -0
- package/dist/chunk-POR5L2DG.js +247 -0
- package/dist/chunk-PSFYJGDG.js +1445 -0
- package/dist/chunk-QJVSKKRQ.js +369 -0
- package/dist/chunk-QPUCXQXT.js +67 -0
- package/dist/chunk-R5U7XKVJ.js +16 -0
- package/dist/chunk-S45UHXQF.js +182 -0
- package/dist/chunk-T46YPHKN.js +669 -0
- package/dist/chunk-UIOOOK6M.js +334 -0
- package/dist/chunk-UKZIAQA7.js +26 -0
- package/dist/chunk-WBVO43HU.js +355 -0
- package/dist/chunk-WTYDHXPW.js +574 -0
- package/dist/chunk-WUOAQVOA.js +86 -0
- package/dist/chunk-WWUKGJB5.js +90 -0
- package/dist/chunk-YGYQUFGY.js +219 -0
- package/dist/chunk-YOBAUCVN.js +583 -0
- package/dist/{cli-DgOEOsPB.d.ts → cli-8rfITnv4.d.ts} +13 -4
- package/dist/cli.d.ts +4 -3
- package/dist/cli.js +50 -1056
- package/dist/{config-BUY7_W2n.d.ts → config-Bm9fBXch.d.ts} +35 -4
- package/dist/config.d.ts +1 -1
- package/dist/config.js +6 -78
- package/dist/errcorrect.js +8 -68
- package/dist/error-Do8Qji43.d.ts +231 -0
- package/dist/id/index.d.ts +1 -1
- package/dist/id/index.js +14 -65
- package/dist/{index-MLrRDvEG.d.ts → index-B-pqGHhU.d.ts} +113 -19
- package/dist/{index--C7Mtsmm.d.ts → index-DEyjGoo2.d.ts} +1 -1
- package/dist/{index-QSffbLnj.d.ts → index-VLDcI5NF.d.ts} +3 -2
- package/dist/index.d.ts +18 -13
- package/dist/index.js +40 -5792
- package/dist/llm-DYuR7_uX.d.ts +1069 -0
- package/dist/llm-anthropic-Cd_I2xXB.d.ts +67 -0
- package/dist/llm-anthropic.d.ts +2 -0
- package/dist/llm-anthropic.js +13 -0
- package/dist/llm-openai-DyFrucmV.d.ts +87 -0
- package/dist/llm-openai.d.ts +2 -0
- package/dist/llm-openai.js +19 -0
- package/dist/llm.d.ts +1 -1
- package/dist/llm.js +101 -356
- package/dist/mcp/index.d.ts +2 -1
- package/dist/mcp/index.js +155 -1453
- package/dist/{netpolicy-asvCfwi8.d.ts → netpolicy-Brx5XZUB.d.ts} +16 -3
- package/dist/netpolicy.d.ts +1 -1
- package/dist/netpolicy.js +25 -118
- package/dist/{output-VFFLqor9.d.ts → output-CjZWmL8s.d.ts} +29 -130
- package/dist/output.d.ts +2 -1
- package/dist/output.js +137 -958
- package/dist/progress.js +6 -55
- package/dist/provenance.js +6 -31
- package/dist/routellm-B0nv59mH.d.ts +111 -0
- package/dist/routellm.d.ts +2 -2
- package/dist/routellm.js +13 -255
- package/dist/{rpc-D5xLEf8V.d.ts → rpc-D31Lg0Kc.d.ts} +1 -1
- package/dist/rpc.d.ts +2 -2
- package/dist/rpc.js +4 -98
- package/dist/safety.js +6 -43
- package/dist/scope.js +20 -377
- package/dist/serve-D8yWMrTc.d.ts +646 -0
- package/dist/serve.d.ts +3 -0
- package/dist/serve.js +75 -0
- package/dist/sqlstore.js +6 -39
- package/dist/stream.js +8 -51
- package/dist/telemetry/index.js +24 -608
- package/dist/tui/index.d.ts +5 -4
- package/dist/tui/index.js +17 -373
- package/dist/upgrade.js +6 -114
- package/dist/xdg.js +14 -128
- package/package.json +135 -25
- package/src/README.md +15 -0
- package/src/cli.test.ts +56 -1
- package/src/cli.ts +24 -4
- package/src/completion-values.test.ts +10 -10
- package/src/compliance.test.ts +196 -2
- package/src/compliance.ts +440 -20
- package/src/config.test.ts +187 -1
- package/src/config.ts +173 -7
- package/src/gen/crud_pb.ts +7 -7
- package/src/id/README.md +38 -0
- package/src/id/contract.test.ts +1 -1
- package/src/id/index.test.ts +1 -1
- package/src/id/index.ts +3 -2
- package/src/index.test.ts +12 -0
- package/src/index.ts +3 -0
- package/src/llm-anthropic.conformance.test.ts +1135 -0
- package/src/llm-anthropic.test.ts +152 -0
- package/src/llm-anthropic.ts +940 -0
- package/src/llm-choice-hermetic.test.ts +335 -0
- package/src/llm-config.test.ts +232 -0
- package/src/llm-config.ts +106 -0
- package/src/llm-endpoint.ts +254 -0
- package/src/llm-error.ts +17 -0
- package/src/llm-errors.ts +152 -0
- package/src/llm-file.ts +126 -0
- package/src/llm-http.ts +317 -0
- package/src/llm-keys.ts +167 -0
- package/src/llm-media.conformance.test.ts +87 -0
- package/src/llm-media.test.ts +279 -0
- package/src/llm-media.ts +322 -0
- package/src/llm-openai.conformance.test.ts +407 -0
- package/src/llm-openai.test.ts +510 -0
- package/src/llm-openai.ts +708 -0
- package/src/llm-payload.ts +155 -0
- package/src/llm-quote.ts +46 -0
- package/src/llm-routellm.conformance.test.ts +44 -0
- package/src/llm-toolnames.conformance.test.ts +112 -0
- package/src/llm-toolnames.test.ts +132 -0
- package/src/llm-toolnames.ts +298 -0
- package/src/llm-uri.ts +99 -0
- package/src/llm.test.ts +43 -15
- package/src/llm.toolcall.test.ts +175 -0
- package/src/llm.ts +602 -190
- package/src/mcp/README.md +57 -0
- package/src/mcp/conformance.test.ts +24 -3
- package/src/mcp/dispatch.ts +4 -4
- package/src/mcp/identity.test.ts +166 -0
- package/src/mcp/identity.ts +72 -0
- package/src/mcp/index.ts +6 -0
- package/src/mcp/legacy.ts +21 -8
- package/src/mcp/mcp.test.ts +14 -4
- package/src/mcp/modern-confirm.ts +1 -1
- package/src/mcp/modern.ts +12 -11
- package/src/mcp/tasks.ts +1 -1
- package/src/mcp/types.ts +80 -8
- package/src/netpolicy.test.ts +78 -0
- package/src/netpolicy.ts +28 -3
- package/src/output/README.md +46 -0
- package/src/output/builtins.ts +5 -5
- package/src/output/error.ts +167 -1
- package/src/output/formatters/README.md +50 -0
- package/src/output.ts +26 -1
- package/src/published-types.test.ts +115 -0
- package/src/routellm.test.ts +209 -28
- package/src/routellm.toolcall.test.ts +521 -0
- package/src/routellm.ts +213 -177
- package/src/router/README.md +44 -0
- package/src/router/server.test.ts +41 -0
- package/src/router/server.ts +11 -0
- package/src/safety.test.ts +19 -9
- package/src/scope-defaults.json +29 -29
- package/src/serve.test.ts +1257 -0
- package/src/serve.ts +1665 -0
- package/src/telemetry/README.md +48 -0
- package/src/telemetry/client.ts +5 -5
- package/src/toolspec.test.ts +2 -2
- package/src/triton/README.md +34 -0
- package/src/tui/README.md +42 -0
- package/src/wizard.test.ts +7 -7
- package/test/llm/conformance-helpers.ts +100 -0
- package/test/output/dispatch.test.ts +1 -2
- package/test/output/error.test.ts +38 -2
- package/test/output/smoke-capture.ts +2 -2
- package/test/output/smoke.test.ts +2 -2
- package/test/output/taxonomy-contract.test.ts +148 -0
- package/test/setup-env.ts +16 -0
- package/tsconfig.json +3 -1
- package/tsconfig.test.json +10 -0
- package/vitest.config.ts +9 -0
- package/dist/llm-B5XUWH8T.d.ts +0 -231
- package/dist/routellm-PGSt2D1y.d.ts +0 -75
|
@@ -0,0 +1,335 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* tool_choice on the openai and routellm adapters, the 401/403 split,
|
|
3
|
+
* and hermetic resolution (no environment read by the config, the
|
|
4
|
+
* registry factories or the adapters). The anthropic side of each runs
|
|
5
|
+
* in the llm-v1 conformance runner.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { mkdirSync, rmSync, writeFileSync } from "node:fs";
|
|
9
|
+
import { join } from "node:path";
|
|
10
|
+
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
|
11
|
+
|
|
12
|
+
import "./llm-anthropic";
|
|
13
|
+
import {
|
|
14
|
+
AuthError,
|
|
15
|
+
LLMError,
|
|
16
|
+
PermissionDeniedError,
|
|
17
|
+
checkToolChoice,
|
|
18
|
+
createLLM,
|
|
19
|
+
isFallbackable,
|
|
20
|
+
loadConfig,
|
|
21
|
+
register,
|
|
22
|
+
resolve,
|
|
23
|
+
type Request,
|
|
24
|
+
type ResolvedConfig,
|
|
25
|
+
type ToolChoice,
|
|
26
|
+
type ToolDef,
|
|
27
|
+
} from "./llm";
|
|
28
|
+
import { OpenAIAdapter } from "./llm-openai";
|
|
29
|
+
import { RouteLLMAdapter, parseRouterConfig } from "./routellm";
|
|
30
|
+
import { fakeServer, isolateEnv, reply, type FakeServer } from "../test/llm/conformance-helpers";
|
|
31
|
+
|
|
32
|
+
const ENV = [
|
|
33
|
+
"ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_BASE_URL", "ANTHROPIC_WORKSPACE_ID",
|
|
34
|
+
"OPENAI_API_KEY", "LLM_API_KEY", "LLM_BASE_URL", "LLM_PROVIDER", "LLM_FALLBACK",
|
|
35
|
+
"ROUTELLM_BASE_URL", "ROUTELLM_STRONG_MODEL", "ROUTELLM_WEAK_MODEL", "ROUTELLM_ROUTERS",
|
|
36
|
+
"ROUTELLM_API_KEY", "LMSTUDIO_API_KEY",
|
|
37
|
+
];
|
|
38
|
+
|
|
39
|
+
let restoreEnv: () => void;
|
|
40
|
+
const servers: FakeServer[] = [];
|
|
41
|
+
beforeEach(() => {
|
|
42
|
+
restoreEnv = isolateEnv(ENV);
|
|
43
|
+
});
|
|
44
|
+
afterEach(async () => {
|
|
45
|
+
restoreEnv();
|
|
46
|
+
await Promise.all(servers.splice(0).map((s) => s.close()));
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
const COMPLETION = JSON.stringify({
|
|
50
|
+
id: "c1",
|
|
51
|
+
object: "chat.completion",
|
|
52
|
+
choices: [{ index: 0, message: { role: "assistant", content: "ok" }, finish_reason: "stop" }],
|
|
53
|
+
usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },
|
|
54
|
+
});
|
|
55
|
+
const ANTHROPIC_OK = JSON.stringify({
|
|
56
|
+
id: "msg_1", type: "message", role: "assistant", model: "m",
|
|
57
|
+
content: [{ type: "text", text: "ok" }], stop_reason: "end_turn",
|
|
58
|
+
usage: { input_tokens: 1, output_tokens: 1 },
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
async function server(handler: Parameters<typeof fakeServer>[0]): Promise<FakeServer> {
|
|
62
|
+
const s = await fakeServer(handler);
|
|
63
|
+
servers.push(s);
|
|
64
|
+
return s;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const okServer = (body = COMPLETION) => server((_h, res) => reply(res, "application/json", body));
|
|
68
|
+
|
|
69
|
+
function openaiCfg(base: string): ResolvedConfig {
|
|
70
|
+
return {
|
|
71
|
+
uri: { scheme: "openai", model: "gpt-test" },
|
|
72
|
+
provider: { apiKey: "k", baseURL: base, model: "gpt-test" },
|
|
73
|
+
fallbacks: [],
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const TOOLS: ToolDef[] = [
|
|
78
|
+
{ name: "get_weather", description: "", parameters: undefined },
|
|
79
|
+
{ name: "pane.open", description: "", parameters: undefined },
|
|
80
|
+
];
|
|
81
|
+
const hi = (toolChoice?: ToolChoice): Request => ({
|
|
82
|
+
messages: [{ role: "user", content: "Hi" }],
|
|
83
|
+
toolChoice,
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
/** Intercepts fetch; returns what was sent and a restore function. */
|
|
87
|
+
function captureFetch(body: string) {
|
|
88
|
+
const sent: { url: string; headers: Headers }[] = [];
|
|
89
|
+
const orig = globalThis.fetch;
|
|
90
|
+
globalThis.fetch = (async (u: unknown, init?: RequestInit) => {
|
|
91
|
+
sent.push({ url: String(u), headers: new Headers(init?.headers) });
|
|
92
|
+
return new globalThis.Response(body, {
|
|
93
|
+
status: 200,
|
|
94
|
+
headers: { "content-type": "application/json" },
|
|
95
|
+
});
|
|
96
|
+
}) as typeof fetch;
|
|
97
|
+
return { sent, restore: () => (globalThis.fetch = orig) };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
describe("checkToolChoice", () => {
|
|
101
|
+
it("accepts unset and each valid mode", () => {
|
|
102
|
+
expect(() => checkToolChoice(undefined, [])).not.toThrow();
|
|
103
|
+
for (const mode of ["auto", "any", "none"] as const) {
|
|
104
|
+
expect(() => checkToolChoice({ mode }, TOOLS)).not.toThrow();
|
|
105
|
+
}
|
|
106
|
+
expect(() => checkToolChoice({ mode: "tool", name: "pane.open" }, TOOLS)).not.toThrow();
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
it("rejects in Go's order with Go's messages", () => {
|
|
110
|
+
const bad = (c: ToolChoice, tools: ToolDef[] = TOOLS) => () => checkToolChoice(c, tools);
|
|
111
|
+
expect(bad({ mode: "required" as ToolChoice["mode"] }, [])).toThrow(
|
|
112
|
+
'unknown tool_choice mode "required"'
|
|
113
|
+
);
|
|
114
|
+
expect(bad({ mode: "auto" }, [])).toThrow('tool_choice "auto" needs tools');
|
|
115
|
+
expect(bad({ mode: "any", name: "get_weather" })).toThrow('tool_choice "any" takes no tool name');
|
|
116
|
+
expect(bad({ mode: "tool" })).toThrow('tool_choice "tool" needs a tool name');
|
|
117
|
+
expect(bad({ mode: "tool", name: "nope" })).toThrow('tool_choice names unknown tool "nope"');
|
|
118
|
+
expect(bad({ mode: "auto" }, [])).toThrow(LLMError);
|
|
119
|
+
});
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
describe("openai tool_choice", () => {
|
|
123
|
+
const cases: [string, ToolChoice | undefined, unknown][] = [
|
|
124
|
+
["unset sends none", undefined, undefined],
|
|
125
|
+
["auto", { mode: "auto" }, "auto"],
|
|
126
|
+
["any is required", { mode: "any" }, "required"],
|
|
127
|
+
["none", { mode: "none" }, "none"],
|
|
128
|
+
["named, by sent name", { mode: "tool", name: "pane.open" },
|
|
129
|
+
{ type: "function", function: { name: "pane_open" } }],
|
|
130
|
+
];
|
|
131
|
+
for (const [name, choice, want] of cases) {
|
|
132
|
+
it(name, async () => {
|
|
133
|
+
const s = await okServer();
|
|
134
|
+
await new OpenAIAdapter(openaiCfg(s.url)).callWithTools(hi(choice), TOOLS);
|
|
135
|
+
const body = JSON.parse(s.hits[0]!.body) as Record<string, unknown>;
|
|
136
|
+
if (want === undefined) expect("tool_choice" in body).toBe(false);
|
|
137
|
+
else expect(body["tool_choice"]).toEqual(want);
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
it("rejects before sending, on every call kind", async () => {
|
|
142
|
+
const s = await okServer();
|
|
143
|
+
const a = new OpenAIAdapter(openaiCfg(s.url));
|
|
144
|
+
await expect(a.complete(hi({ mode: "any" }))).rejects.toThrow(
|
|
145
|
+
'openai: tool_choice "any" needs tools'
|
|
146
|
+
);
|
|
147
|
+
const it1 = a.stream(hi({ mode: "any" }))[Symbol.asyncIterator]();
|
|
148
|
+
await expect(it1.next()).rejects.toThrow('openai: tool_choice "any" needs tools');
|
|
149
|
+
await expect(a.callWithTools(hi({ mode: "tool", name: "nope" }), TOOLS)).rejects.toThrow(
|
|
150
|
+
'openai: tool_choice names unknown tool "nope"'
|
|
151
|
+
);
|
|
152
|
+
const it2 = a.streamWithTools(hi({ mode: "tool" }), TOOLS)[Symbol.asyncIterator]();
|
|
153
|
+
await expect(it2.next()).rejects.toThrow('openai: tool_choice "tool" needs a tool name');
|
|
154
|
+
expect(s.hits).toHaveLength(0);
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
it("routellm passes it through, errors under its label", async () => {
|
|
158
|
+
const s = await okServer();
|
|
159
|
+
const r = new RouteLLMAdapter({
|
|
160
|
+
uri: { scheme: "routellm", model: "mf:0.7" },
|
|
161
|
+
provider: { model: "mf:0.7", baseURL: s.url },
|
|
162
|
+
fallbacks: [],
|
|
163
|
+
});
|
|
164
|
+
await r.callWithTools(hi({ mode: "any" }), TOOLS);
|
|
165
|
+
expect((JSON.parse(s.hits[0]!.body) as Record<string, unknown>)["tool_choice"]).toBe("required");
|
|
166
|
+
await expect(r.complete(hi({ mode: "auto" }))).rejects.toThrow(
|
|
167
|
+
'routellm: tool_choice "auto" needs tools'
|
|
168
|
+
);
|
|
169
|
+
expect(s.hits).toHaveLength(1);
|
|
170
|
+
});
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
describe("401/403 split", () => {
|
|
174
|
+
for (const [status, denied] of [[403, true], [401, false]] as const) {
|
|
175
|
+
it(`openai ${status}`, async () => {
|
|
176
|
+
const s = await server((_h, res) =>
|
|
177
|
+
reply(res, "application/json", '{"error":{"message":"no","type":"x"}}', status)
|
|
178
|
+
);
|
|
179
|
+
const err = await new OpenAIAdapter(openaiCfg(s.url))
|
|
180
|
+
.complete(hi())
|
|
181
|
+
.then(() => undefined, (e: unknown) => e);
|
|
182
|
+
expect(err instanceof PermissionDeniedError).toBe(denied);
|
|
183
|
+
expect(err, "every 401 and 403 is an auth error").toBeInstanceOf(AuthError);
|
|
184
|
+
expect(isFallbackable(err as Error)).toBe(false);
|
|
185
|
+
expect((err as AuthError).provider).toBe("openai");
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
it("a denial names itself and keeps the cause", () => {
|
|
190
|
+
const cause = new Error("no access");
|
|
191
|
+
const e = new PermissionDeniedError("anthropic", cause);
|
|
192
|
+
expect(e.message).toBe("permission denied for provider: anthropic: no access");
|
|
193
|
+
expect(e.name).toBe("PermissionDeniedError");
|
|
194
|
+
expect(e.cause).toBe(cause);
|
|
195
|
+
expect(e).toBeInstanceOf(AuthError);
|
|
196
|
+
expect(e).toBeInstanceOf(LLMError);
|
|
197
|
+
});
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
describe("local runtimes' keys", () => {
|
|
201
|
+
it("routellm takes ROUTELLM_API_KEY when set, never LLM_API_KEY", () => {
|
|
202
|
+
process.env["LLM_API_KEY"] = "env-key";
|
|
203
|
+
expect(loadConfig("routellm://m").provider.apiKey).toBeUndefined();
|
|
204
|
+
process.env["ROUTELLM_API_KEY"] = "router-key";
|
|
205
|
+
expect(loadConfig("routellm://m").provider.apiKey).toBe("router-key");
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
it("lmstudio takes no key from the environment", () => {
|
|
209
|
+
process.env["LLM_API_KEY"] = "env-key";
|
|
210
|
+
process.env["LMSTUDIO_API_KEY"] = "lms-key";
|
|
211
|
+
expect(loadConfig("lmstudio://m").provider.apiKey).toBeUndefined();
|
|
212
|
+
});
|
|
213
|
+
});
|
|
214
|
+
|
|
215
|
+
describe("hermetic", () => {
|
|
216
|
+
it("loadConfig reads no LLM_* variable", () => {
|
|
217
|
+
process.env["LLM_PROVIDER"] = "openai://ambient";
|
|
218
|
+
process.env["LLM_FALLBACK"] = "openai://fb";
|
|
219
|
+
process.env["LLM_API_KEY"] = "env-key";
|
|
220
|
+
process.env["LLM_BASE_URL"] = "https://gw.corp.test";
|
|
221
|
+
const cfg = loadConfig("anthropic://m", { hermetic: true });
|
|
222
|
+
expect(cfg.hermetic).toBe(true);
|
|
223
|
+
expect(cfg.fallbacks).toEqual([]);
|
|
224
|
+
expect(cfg.provider.apiKey).toBeUndefined();
|
|
225
|
+
expect(cfg.provider.baseURL).toBeUndefined();
|
|
226
|
+
expect(() => loadConfig("", { hermetic: true })).toThrow(/LLM_PROVIDER is not read/);
|
|
227
|
+
// Not hermetic, every one of them counts.
|
|
228
|
+
const amb = loadConfig("");
|
|
229
|
+
expect(amb.uri.model).toBe("ambient");
|
|
230
|
+
expect(amb.fallbacks).toEqual(["openai://fb"]);
|
|
231
|
+
expect(amb.provider.apiKey).toBe("env-key");
|
|
232
|
+
});
|
|
233
|
+
|
|
234
|
+
it("anthropic via resolve: only the URI's key, default host, no env header", async () => {
|
|
235
|
+
Object.assign(process.env, {
|
|
236
|
+
ANTHROPIC_API_KEY: "env-key",
|
|
237
|
+
ANTHROPIC_AUTH_TOKEN: "env-token",
|
|
238
|
+
ANTHROPIC_WORKSPACE_ID: "ws-1",
|
|
239
|
+
ANTHROPIC_BASE_URL: "https://gw.corp.test",
|
|
240
|
+
LLM_BASE_URL: "https://gw.corp.test",
|
|
241
|
+
});
|
|
242
|
+
const f = captureFetch(ANTHROPIC_OK);
|
|
243
|
+
try {
|
|
244
|
+
await resolve("anthropic://m?api_key=uri-key", { hermetic: true }).complete!(hi());
|
|
245
|
+
} finally {
|
|
246
|
+
f.restore();
|
|
247
|
+
}
|
|
248
|
+
expect(new URL(f.sent[0]!.url).host).toBe("api.anthropic.com");
|
|
249
|
+
expect(f.sent[0]!.headers.get("x-api-key")).toBe("uri-key");
|
|
250
|
+
expect(f.sent[0]!.headers.get("authorization")).toBeNull();
|
|
251
|
+
expect(f.sent[0]!.headers.get("anthropic-workspace-id")).toBeNull();
|
|
252
|
+
});
|
|
253
|
+
|
|
254
|
+
it("anthropic via resolve: no env key to fall back on", () => {
|
|
255
|
+
process.env["ANTHROPIC_API_KEY"] = "env-key";
|
|
256
|
+
process.env["LLM_API_KEY"] = "env-key";
|
|
257
|
+
expect(() => resolve("anthropic://m", { hermetic: true })).toThrow(
|
|
258
|
+
"anthropic: API key required"
|
|
259
|
+
);
|
|
260
|
+
expect(() => resolve("anthropic://m")).not.toThrow();
|
|
261
|
+
});
|
|
262
|
+
|
|
263
|
+
it("openai via createLLM: no <SCHEME>_API_KEY, no LLM_BASE_URL", async () => {
|
|
264
|
+
process.env["OPENAI_API_KEY"] = "env-key";
|
|
265
|
+
process.env["LLM_BASE_URL"] = "https://gw.corp.test";
|
|
266
|
+
const f = captureFetch(COMPLETION);
|
|
267
|
+
try {
|
|
268
|
+
await createLLM("openai://gpt-test", { hermetic: true }).complete(hi());
|
|
269
|
+
} finally {
|
|
270
|
+
f.restore();
|
|
271
|
+
}
|
|
272
|
+
expect(new URL(f.sent[0]!.url).host).toBe("api.openai.com");
|
|
273
|
+
expect(f.sent[0]!.headers.get("authorization")).toBeNull();
|
|
274
|
+
});
|
|
275
|
+
|
|
276
|
+
it("the key gate reads no LLM_BASE_URL and no llm.yaml", () => {
|
|
277
|
+
// An endpoint only the URI names, trusted through LLM_BASE_URL or
|
|
278
|
+
// llm.yaml: hermetic, the URI's key goes there, nothing else does.
|
|
279
|
+
process.env["LLM_BASE_URL"] = "https://gw.corp.test";
|
|
280
|
+
process.env["OPENAI_API_KEY"] = "env-key";
|
|
281
|
+
const dir = join(process.env["XDG_CONFIG_HOME"]!, "hop");
|
|
282
|
+
mkdirSync(dir, { recursive: true });
|
|
283
|
+
writeFileSync(join(dir, "llm.yaml"), "providers:\n openai:\n api_key: file-key\n");
|
|
284
|
+
try {
|
|
285
|
+
const uri = "openai://m?base_url=https://gw.corp.test";
|
|
286
|
+
expect(loadConfig(uri, { hermetic: true }).provider.apiKey).toBeUndefined();
|
|
287
|
+
expect(loadConfig(uri).provider.apiKey).toBe("file-key");
|
|
288
|
+
} finally {
|
|
289
|
+
rmSync(join(dir, "llm.yaml"));
|
|
290
|
+
}
|
|
291
|
+
});
|
|
292
|
+
|
|
293
|
+
it("routellm reads no ROUTELLM_* variable", () => {
|
|
294
|
+
Object.assign(process.env, {
|
|
295
|
+
ROUTELLM_BASE_URL: "http://env.test:9",
|
|
296
|
+
ROUTELLM_STRONG_MODEL: "s",
|
|
297
|
+
ROUTELLM_WEAK_MODEL: "w",
|
|
298
|
+
ROUTELLM_ROUTERS: "mf",
|
|
299
|
+
});
|
|
300
|
+
const extras = { routellm: { base_url: "http://cfg.test:7" } };
|
|
301
|
+
expect(parseRouterConfig(extras, { hermetic: true })).toMatchObject({
|
|
302
|
+
baseUrl: "http://cfg.test:7", strongModel: "", weakModel: "", routers: [],
|
|
303
|
+
});
|
|
304
|
+
expect(parseRouterConfig(extras).baseUrl).toBe("http://env.test:9");
|
|
305
|
+
const r = new RouteLLMAdapter({
|
|
306
|
+
uri: { scheme: "routellm", model: "mf:0.5" },
|
|
307
|
+
provider: { model: "mf:0.5", extras },
|
|
308
|
+
fallbacks: [],
|
|
309
|
+
hermetic: true,
|
|
310
|
+
});
|
|
311
|
+
expect(r.config.baseUrl).toBe("http://cfg.test:7");
|
|
312
|
+
});
|
|
313
|
+
});
|
|
314
|
+
|
|
315
|
+
describe("client onResponse after a tool call", () => {
|
|
316
|
+
it("gets the turn's usage, stop reason and thinking", async () => {
|
|
317
|
+
const usage = { promptTokens: 3, completionTokens: 4, totalTokens: 7 };
|
|
318
|
+
const thinking = [{ thinking: "hmm", signature: "sig", redacted: "" }];
|
|
319
|
+
register("mock-onresponse", () => ({
|
|
320
|
+
callWithTools: async () => ({
|
|
321
|
+
content: "c", toolCalls: [], usage, finishReason: "tool_use", thinking,
|
|
322
|
+
}),
|
|
323
|
+
close() {},
|
|
324
|
+
}));
|
|
325
|
+
let got: unknown;
|
|
326
|
+
await createLLM("mock-onresponse://m", {
|
|
327
|
+
onResponse: (r) => {
|
|
328
|
+
got = r;
|
|
329
|
+
},
|
|
330
|
+
}).callWithTools(hi(), TOOLS);
|
|
331
|
+
expect(got).toEqual({
|
|
332
|
+
content: "c", role: "assistant", usage, finishReason: "tool_use", thinking,
|
|
333
|
+
});
|
|
334
|
+
});
|
|
335
|
+
});
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* llm.yaml, key resolution order and the key-endpoint guard of the
|
|
3
|
+
* core: loadConfig, applyAPIKey, credentialsTrusted. Go `llm`
|
|
4
|
+
* (LoadConfig, ApplyAPIKey, CredentialsTrusted) is canonical; the
|
|
5
|
+
* llm-v1 vectors pin the endpoint rules, these the layering.
|
|
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
|
+
MissingKeyError,
|
|
16
|
+
applyAPIKey,
|
|
17
|
+
clearRegistry,
|
|
18
|
+
credentialsTrusted,
|
|
19
|
+
loadConfig,
|
|
20
|
+
register,
|
|
21
|
+
type Provider,
|
|
22
|
+
} from "./llm";
|
|
23
|
+
import { isolateEnv } from "../test/llm/conformance-helpers";
|
|
24
|
+
|
|
25
|
+
const ENV = [
|
|
26
|
+
"LLM_API_KEY", "LLM_BASE_URL", "LLM_PROVIDER", "LLM_FALLBACK",
|
|
27
|
+
"KITA_API_KEY", "KITA_ALT_KEY", "KITB_API_KEY", "KITC_API_KEY", "NOSUCH_API_KEY",
|
|
28
|
+
];
|
|
29
|
+
|
|
30
|
+
let restore: () => void;
|
|
31
|
+
beforeEach(() => {
|
|
32
|
+
restore = isolateEnv(ENV);
|
|
33
|
+
register("kita", stub, { endpoints: ["https://api.kita.test"] });
|
|
34
|
+
register("kitb", stub, { key: { envVars: [], optional: true } });
|
|
35
|
+
register("kitc", stub, { key: { envVars: ["KITC_API_KEY"], optional: true } });
|
|
36
|
+
});
|
|
37
|
+
afterEach(() => {
|
|
38
|
+
restore();
|
|
39
|
+
clearRegistry();
|
|
40
|
+
writeYaml("");
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
function stub(): Provider {
|
|
44
|
+
return { close: () => undefined };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Writes llm.yaml where the core reads it; "" removes its content. */
|
|
48
|
+
function writeYaml(yaml: string): void {
|
|
49
|
+
const dir = join(process.env["XDG_CONFIG_HOME"]!, "hop");
|
|
50
|
+
mkdirSync(dir, { recursive: true });
|
|
51
|
+
writeFileSync(join(dir, "llm.yaml"), yaml);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
describe("key resolution order", () => {
|
|
55
|
+
it("URI api_key, then llm.yaml api_key, api_key_env, <SCHEME>_API_KEY, LLM_API_KEY", () => {
|
|
56
|
+
process.env["LLM_API_KEY"] = "k-fallback";
|
|
57
|
+
expect(loadConfig("kita://m").provider.apiKey).toBe("k-fallback");
|
|
58
|
+
process.env["KITA_API_KEY"] = "k-scheme";
|
|
59
|
+
expect(loadConfig("kita://m").provider.apiKey).toBe("k-scheme");
|
|
60
|
+
process.env["KITA_ALT_KEY"] = "k-alt";
|
|
61
|
+
writeYaml("providers:\n kita:\n api_key_env: KITA_ALT_KEY\n");
|
|
62
|
+
expect(loadConfig("kita://m").provider.apiKey).toBe("k-alt");
|
|
63
|
+
writeYaml("providers:\n kita:\n api_key: k-file\n api_key_env: KITA_ALT_KEY\n");
|
|
64
|
+
expect(loadConfig("kita://m").provider.apiKey).toBe("k-file");
|
|
65
|
+
expect(loadConfig("kita://m?api_key=k-uri").provider.apiKey).toBe("k-uri");
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
it("treats a blank value as unset at every source", () => {
|
|
69
|
+
process.env["KITA_API_KEY"] = "k-scheme";
|
|
70
|
+
writeYaml("providers:\n kita:\n api_key: ' '\n");
|
|
71
|
+
const cfg = loadConfig("kita://m?api_key= ");
|
|
72
|
+
expect(cfg.provider.apiKey).toBe("k-scheme");
|
|
73
|
+
expect(cfg.uri.params).toBeUndefined();
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
it("lends LLM_API_KEY only to a scheme whose adapter requires a key", () => {
|
|
77
|
+
process.env["LLM_API_KEY"] = "k-fallback";
|
|
78
|
+
process.env["KITB_API_KEY"] = "k-b";
|
|
79
|
+
expect(loadConfig("kitb://m").provider.apiKey).toBeUndefined();
|
|
80
|
+
expect(loadConfig("kitc://m").provider.apiKey).toBeUndefined();
|
|
81
|
+
process.env["KITC_API_KEY"] = "k-c";
|
|
82
|
+
expect(loadConfig("kitc://m").provider.apiKey).toBe("k-c");
|
|
83
|
+
expect(loadConfig("nosuch://m").provider.apiKey).toBeUndefined();
|
|
84
|
+
process.env["NOSUCH_API_KEY"] = "k-nosuch";
|
|
85
|
+
expect(loadConfig("nosuch://m").provider.apiKey).toBeUndefined();
|
|
86
|
+
writeYaml("providers:\n nosuch:\n api_key_env: NOSUCH_KEY_VAR\n");
|
|
87
|
+
expect(loadConfig("nosuch://m").provider.apiKey).toBeUndefined();
|
|
88
|
+
// A scheme no adapter serves still takes its own llm.yaml key.
|
|
89
|
+
writeYaml("providers:\n nosuch:\n api_key: k-own\n");
|
|
90
|
+
expect(loadConfig("nosuch://m").provider.apiKey).toBe("k-own");
|
|
91
|
+
});
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
describe("llm.yaml", () => {
|
|
95
|
+
it("supplies default, fallback, model, base_url and extras", () => {
|
|
96
|
+
writeYaml(
|
|
97
|
+
[
|
|
98
|
+
"default: kita://",
|
|
99
|
+
"fallback: [kitb://x]",
|
|
100
|
+
"providers:",
|
|
101
|
+
" kita:",
|
|
102
|
+
" model: m-file",
|
|
103
|
+
" base_url: https://api.kita.test",
|
|
104
|
+
" tier: gold",
|
|
105
|
+
"",
|
|
106
|
+
].join("\n")
|
|
107
|
+
);
|
|
108
|
+
const cfg = loadConfig();
|
|
109
|
+
expect(cfg.uri.scheme).toBe("kita");
|
|
110
|
+
expect(cfg.provider.model).toBe("m-file");
|
|
111
|
+
expect(cfg.provider.baseURL).toBe("https://api.kita.test");
|
|
112
|
+
expect(cfg.provider.extras).toEqual({ tier: "gold" });
|
|
113
|
+
expect(cfg.fallbacks).toEqual(["kitb://x"]);
|
|
114
|
+
expect(loadConfig("kita://m-uri").provider.model).toBe("m-uri");
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
it("ranks the URI over LLM_BASE_URL over llm.yaml for the base URL", () => {
|
|
118
|
+
writeYaml("providers:\n kita:\n base_url: https://file.test\n");
|
|
119
|
+
expect(loadConfig("kita://m").provider.baseURL).toBe("https://file.test");
|
|
120
|
+
process.env["LLM_BASE_URL"] = "https://env.test";
|
|
121
|
+
expect(loadConfig("kita://m").provider.baseURL).toBe("https://env.test");
|
|
122
|
+
expect(loadConfig("kita://m?base_url=https://uri.test").provider.baseURL).toBe(
|
|
123
|
+
"https://uri.test"
|
|
124
|
+
);
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
it("LLM_PROVIDER and LLM_FALLBACK outrank llm.yaml", () => {
|
|
128
|
+
writeYaml("default: kita://file\nfallback: [kita://fb-file]\n");
|
|
129
|
+
process.env["LLM_PROVIDER"] = "kita://env";
|
|
130
|
+
process.env["LLM_FALLBACK"] = "kita://fb-env";
|
|
131
|
+
const cfg = loadConfig();
|
|
132
|
+
expect(cfg.uri.model).toBe("env");
|
|
133
|
+
expect(cfg.fallbacks).toEqual(["kita://fb-env"]);
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
it("is ignored when it does not parse", () => {
|
|
137
|
+
writeYaml("providers: [unclosed\n");
|
|
138
|
+
process.env["KITA_API_KEY"] = "k-scheme";
|
|
139
|
+
expect(loadConfig("kita://m").provider.apiKey).toBe("k-scheme");
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
it("is not read by a hermetic config", () => {
|
|
143
|
+
writeYaml(
|
|
144
|
+
"default: kita://file\nproviders:\n kita:\n api_key: k-file\n base_url: https://file.test\n"
|
|
145
|
+
);
|
|
146
|
+
expect(() => loadConfig("", { hermetic: true })).toThrow(LLMError);
|
|
147
|
+
const cfg = loadConfig("kita://m", { hermetic: true });
|
|
148
|
+
expect(cfg.provider.apiKey).toBeUndefined();
|
|
149
|
+
expect(cfg.provider.baseURL).toBeUndefined();
|
|
150
|
+
expect(cfg.provider.extras).toBeUndefined();
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
it("base_url makes an endpoint trusted for kit's own credentials", () => {
|
|
154
|
+
expect(credentialsTrusted("kita", "https://gw.corp.test/v1")).toBe(false);
|
|
155
|
+
writeYaml("providers:\n kita:\n base_url: https://gw.corp.test\n");
|
|
156
|
+
expect(credentialsTrusted("kita", "https://gw.corp.test/v1")).toBe(true);
|
|
157
|
+
expect(credentialsTrusted("kitb", "https://gw.corp.test/v1")).toBe(false);
|
|
158
|
+
});
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
describe("key-endpoint guard at load", () => {
|
|
162
|
+
it("keeps a key kit resolved off an endpoint only the URI names", () => {
|
|
163
|
+
process.env["KITA_API_KEY"] = "k-scheme";
|
|
164
|
+
expect(() => loadConfig("kita://m?base_url=https://evil.test")).toThrow(KeyEndpointError);
|
|
165
|
+
expect(() => loadConfig("kita://m?base_url=https://api.kita.test/v2")).not.toThrow();
|
|
166
|
+
expect(() => loadConfig("kita://m?api_key=k-uri&base_url=https://evil.test")).not.toThrow();
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
it("refuses any key over plain http to a remote host", () => {
|
|
170
|
+
expect(() => loadConfig("kita://m?api_key=k-uri&base_url=http://evil.test")).toThrow(
|
|
171
|
+
KeyEndpointError
|
|
172
|
+
);
|
|
173
|
+
process.env["KITA_API_KEY"] = "k-scheme";
|
|
174
|
+
process.env["LLM_BASE_URL"] = "http://gw.corp.test";
|
|
175
|
+
expect(() => loadConfig("kita://m")).toThrow(KeyEndpointError);
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
it("names llm.yaml base_url in the refusal", () => {
|
|
179
|
+
process.env["KITA_API_KEY"] = "k-scheme";
|
|
180
|
+
expect(() => loadConfig("kita://m?base_url=https://evil.test")).toThrow(
|
|
181
|
+
'llm: refusing to send the kita API key to "https://evil.test", which only the URI names; ' +
|
|
182
|
+
"set it as llm.yaml base_url or LLM_BASE_URL, or pass api_key in the URI"
|
|
183
|
+
);
|
|
184
|
+
});
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
describe("applyAPIKey", () => {
|
|
188
|
+
it("appends the resolved key", () => {
|
|
189
|
+
process.env["KITA_API_KEY"] = "k-scheme";
|
|
190
|
+
expect(applyAPIKey("kita://m")).toBe("kita://m?api_key=k-scheme");
|
|
191
|
+
expect(applyAPIKey("kita://m?t=1")).toBe("kita://m?t=1&api_key=k-scheme");
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
it("keeps the URI's own key and drops a blank one", () => {
|
|
195
|
+
process.env["KITA_API_KEY"] = "k-scheme";
|
|
196
|
+
expect(applyAPIKey("kita://m?api_key=k-uri")).toBe("kita://m?api_key=k-uri");
|
|
197
|
+
expect(applyAPIKey("kita://m?api_key=&t=1")).toBe("kita://m?t=1&api_key=k-scheme");
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
it("returns the URI unchanged when the scheme takes no key", () => {
|
|
201
|
+
process.env["LLM_API_KEY"] = "k-fallback";
|
|
202
|
+
expect(applyAPIKey("kitb://m")).toBe("kitb://m");
|
|
203
|
+
expect(applyAPIKey("nosuch://m")).toBe("nosuch://m");
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
it("throws MissingKeyError for a required key found nowhere", () => {
|
|
207
|
+
let err: unknown;
|
|
208
|
+
try {
|
|
209
|
+
applyAPIKey("kita://m");
|
|
210
|
+
} catch (e) {
|
|
211
|
+
err = e;
|
|
212
|
+
}
|
|
213
|
+
expect(err).toBeInstanceOf(MissingKeyError);
|
|
214
|
+
expect((err as MissingKeyError).envVars).toEqual(["KITA_API_KEY", "LLM_API_KEY"]);
|
|
215
|
+
expect((err as Error).message).toBe(
|
|
216
|
+
'llm: no API key for provider "kita" (model "m"): set KITA_API_KEY or LLM_API_KEY'
|
|
217
|
+
);
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
it("refuses a key a URI cannot carry", () => {
|
|
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
|
+
);
|
|
225
|
+
});
|
|
226
|
+
|
|
227
|
+
it("never quotes its input on a parse error", () => {
|
|
228
|
+
expect(() => applyAPIKey("kita/m?api_key=secret-value")).toThrow(
|
|
229
|
+
"llm: apply API key: provider URI must be scheme://model"
|
|
230
|
+
);
|
|
231
|
+
});
|
|
232
|
+
});
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Config loading: llm.yaml, the environment and the URI merged as Go
|
|
3
|
+
* `llm.LoadConfig` merges them. Re-exported from `@hop-top/kit/llm`.
|
|
4
|
+
*
|
|
5
|
+
* @internal
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import type { ProviderConfig, ResolvedConfig } from "./llm";
|
|
9
|
+
import { checkKeyEndpoint } from "./llm-endpoint";
|
|
10
|
+
import { LLMError } from "./llm-error";
|
|
11
|
+
import { providerBlock, readLLMFile } from "./llm-file";
|
|
12
|
+
import { dropBlankURIKey, guardKeyEndpoint, resolveKey, uriKey } from "./llm-keys";
|
|
13
|
+
import { parseURI } from "./llm-uri";
|
|
14
|
+
|
|
15
|
+
/** Options for {@link loadConfig}, `resolve` and `createLLM`. */
|
|
16
|
+
export interface LoadOptions {
|
|
17
|
+
/**
|
|
18
|
+
* Reads nothing ambient: the provider comes from the URI alone
|
|
19
|
+
* (`api_key`, `base_url`, host). No llm.yaml, no `LLM_PROVIDER`,
|
|
20
|
+
* `LLM_FALLBACK`, `LLM_API_KEY`, `LLM_BASE_URL` or `<SCHEME>_API_KEY`,
|
|
21
|
+
* and the adapter gets {@link ResolvedConfig.hermetic}, so it reads no
|
|
22
|
+
* environment variable either. For embedding kit in an app that owns
|
|
23
|
+
* its configuration.
|
|
24
|
+
*/
|
|
25
|
+
hermetic?: boolean;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Builds the {@link ResolvedConfig} for `uriStr` from llm.yaml
|
|
30
|
+
* (`{configDir("hop")}/llm.yaml`), the environment and the URI, the
|
|
31
|
+
* URI highest. Each field, highest precedence first:
|
|
32
|
+
*
|
|
33
|
+
* - URI: `uriStr`; `LLM_PROVIDER`; llm.yaml `default`. None throws.
|
|
34
|
+
* - apiKey: the URI's `api_key`; llm.yaml `providers.<scheme>.api_key`,
|
|
35
|
+
* then the variable its `api_key_env` names; the scheme's key
|
|
36
|
+
* variables (`<SCHEME>_API_KEY` unless its adapter declares others);
|
|
37
|
+
* `LLM_API_KEY` for a registered scheme that requires a key. Blank is
|
|
38
|
+
* unset everywhere; a blank `api_key` param is dropped. Found
|
|
39
|
+
* nowhere, it is left unset: the adapter reports it.
|
|
40
|
+
* - baseURL: the URI's `base_url`; its host (`http://host:port`);
|
|
41
|
+
* `LLM_BASE_URL`; llm.yaml `base_url`.
|
|
42
|
+
* - model: the URI's; llm.yaml `model`. extras: the block's other keys.
|
|
43
|
+
* - fallbacks: `LLM_FALLBACK` (comma-separated); llm.yaml `fallback`.
|
|
44
|
+
*
|
|
45
|
+
* Throws a {@link KeyEndpointError} when the key may not go where the
|
|
46
|
+
* config points: a key not from the URI to an endpoint only the URI
|
|
47
|
+
* names unless loopback or trusted (declared, llm.yaml `base_url`,
|
|
48
|
+
* `LLM_BASE_URL`); any key over plain http to a remote host.
|
|
49
|
+
*
|
|
50
|
+
* With `opts.hermetic` the config is the URI alone (see
|
|
51
|
+
* {@link LoadOptions}).
|
|
52
|
+
*/
|
|
53
|
+
export function loadConfig(uriStr?: string, opts: LoadOptions = {}): ResolvedConfig {
|
|
54
|
+
if (opts.hermetic === true) return hermeticConfig(uriStr);
|
|
55
|
+
const file = readLLMFile();
|
|
56
|
+
const effective = uriStr || process.env["LLM_PROVIDER"] || file.default;
|
|
57
|
+
if (!effective) {
|
|
58
|
+
throw new LLMError(
|
|
59
|
+
"no LLM URI provided: LLM_PROVIDER is not set and llm.yaml names no default"
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
const uri = parseURI(effective);
|
|
63
|
+
dropBlankURIKey(uri);
|
|
64
|
+
const block = providerBlock(file, uri.scheme);
|
|
65
|
+
|
|
66
|
+
const key = resolveKey(uri, file);
|
|
67
|
+
guardKeyEndpoint(uri, key.value, key.source);
|
|
68
|
+
|
|
69
|
+
const provider: ProviderConfig = { model: uri.model || block?.model || "" };
|
|
70
|
+
if (uri.params) provider.params = { ...uri.params };
|
|
71
|
+
if (block && Object.keys(block.extras).length > 0) provider.extras = block.extras;
|
|
72
|
+
if (key.value !== "") provider.apiKey = key.value;
|
|
73
|
+
|
|
74
|
+
// The URI's own choice outranks the environment, which outranks the
|
|
75
|
+
// file.
|
|
76
|
+
let base = process.env["LLM_BASE_URL"] || block?.baseURL || "";
|
|
77
|
+
if (uri.host) base = `http://${uri.host}`;
|
|
78
|
+
if (uri.params && "base_url" in uri.params) base = uri.params["base_url"]!;
|
|
79
|
+
if (base !== "") provider.baseURL = base;
|
|
80
|
+
checkKeyEndpoint(uri.scheme, key.value, base);
|
|
81
|
+
|
|
82
|
+
const fbEnv = process.env["LLM_FALLBACK"];
|
|
83
|
+
const fallbacks = fbEnv
|
|
84
|
+
? fbEnv.split(",").map((s) => s.trim()).filter(Boolean)
|
|
85
|
+
: [...file.fallback];
|
|
86
|
+
return { uri, provider, fallbacks };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** {@link loadConfig} from the URI alone. */
|
|
90
|
+
function hermeticConfig(uriStr: string | undefined): ResolvedConfig {
|
|
91
|
+
if (!uriStr) {
|
|
92
|
+
throw new LLMError("no LLM URI provided (hermetic: LLM_PROVIDER is not read)");
|
|
93
|
+
}
|
|
94
|
+
const uri = parseURI(uriStr);
|
|
95
|
+
dropBlankURIKey(uri);
|
|
96
|
+
const provider: ProviderConfig = { model: uri.model };
|
|
97
|
+
if (uri.params) provider.params = { ...uri.params };
|
|
98
|
+
const key = uriKey(uri) ?? "";
|
|
99
|
+
if (key !== "") provider.apiKey = key;
|
|
100
|
+
let base = uri.host ? `http://${uri.host}` : "";
|
|
101
|
+
if (uri.params && "base_url" in uri.params) base = uri.params["base_url"]!;
|
|
102
|
+
if (base !== "") provider.baseURL = base;
|
|
103
|
+
// A key never crosses the network in clear.
|
|
104
|
+
checkKeyEndpoint(uri.scheme, key, base);
|
|
105
|
+
return { uri, provider, fallbacks: [], hermetic: true };
|
|
106
|
+
}
|