@hop-top/kit 0.5.0-alpha.1 → 0.5.0-alpha.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (285) hide show
  1. package/CHANGELOG.md +251 -0
  2. package/LICENSE +1 -1
  3. package/LICENSE-cobra.txt +174 -0
  4. package/NOTICE +15 -0
  5. package/README.md +55 -259
  6. package/dist/aim-DZHwwiIc.d.ts +139 -0
  7. package/dist/aim.d.ts +1 -116
  8. package/dist/aim.js +13 -414
  9. package/dist/alias-D9_qFlyP.d.ts +174 -0
  10. package/dist/alias.d.ts +2 -73
  11. package/dist/alias.js +27 -207
  12. package/dist/api-DAexsu2H.d.ts +77 -0
  13. package/dist/api.d.ts +1 -62
  14. package/dist/api.js +10 -164
  15. package/dist/auth-2-jfgiHn.d.ts +34 -0
  16. package/dist/auth.d.ts +1 -26
  17. package/dist/auth.js +6 -40
  18. package/dist/chunk-2JV3A7OP.js +1894 -0
  19. package/dist/chunk-3FIKGFKI.js +54 -0
  20. package/dist/chunk-4UE5TCMQ.js +104 -0
  21. package/dist/chunk-6HFAEZ52.js +29 -0
  22. package/dist/chunk-6SVOHNIC.js +17 -0
  23. package/dist/chunk-72XZWQX7.js +504 -0
  24. package/dist/chunk-ABQSE7AI.js +513 -0
  25. package/dist/chunk-BDNNPRX6.js +41 -0
  26. package/dist/chunk-BLS2OBIQ.js +263 -0
  27. package/dist/chunk-BRNEKPWX.js +37 -0
  28. package/dist/chunk-CSJWB6D3.js +151 -0
  29. package/dist/chunk-GGWJRWWA.js +309 -0
  30. package/dist/chunk-GHPJJV5L.js +613 -0
  31. package/dist/chunk-IXVQ62NZ.js +334 -0
  32. package/dist/chunk-JKMQSAJP.js +174 -0
  33. package/dist/chunk-JZ22ZUFA.js +1131 -0
  34. package/dist/chunk-K7VCKJ27.js +814 -0
  35. package/dist/chunk-KVG7YCTS.js +115 -0
  36. package/dist/chunk-L23O2FFE.js +51 -0
  37. package/dist/chunk-MQXYDYRD.js +968 -0
  38. package/dist/chunk-MUIQVU6E.js +251 -0
  39. package/dist/chunk-NLMS7HGP.js +178 -0
  40. package/dist/chunk-POR5L2DG.js +247 -0
  41. package/dist/chunk-PSFYJGDG.js +1445 -0
  42. package/dist/chunk-QJVSKKRQ.js +369 -0
  43. package/dist/chunk-QPUCXQXT.js +67 -0
  44. package/dist/chunk-QQQYCWSC.js +240 -0
  45. package/dist/chunk-R5U7XKVJ.js +16 -0
  46. package/dist/chunk-SNVGDYX7.js +187 -0
  47. package/dist/chunk-T46YPHKN.js +669 -0
  48. package/dist/chunk-UKZIAQA7.js +26 -0
  49. package/dist/chunk-WBVO43HU.js +355 -0
  50. package/dist/chunk-WUOAQVOA.js +86 -0
  51. package/dist/chunk-WWUKGJB5.js +90 -0
  52. package/dist/chunk-XJTRY453.js +868 -0
  53. package/dist/chunk-YGYQUFGY.js +219 -0
  54. package/dist/chunk-YOBAUCVN.js +583 -0
  55. package/dist/cli-C5B5tnpA.d.ts +400 -0
  56. package/dist/cli.d.ts +7 -309
  57. package/dist/cli.js +70 -945
  58. package/dist/completion-csVun6SP.d.ts +112 -0
  59. package/dist/completion-values-By-mnjNt.d.ts +142 -0
  60. package/dist/completion-values.d.ts +1 -0
  61. package/dist/completion-values.js +29 -0
  62. package/dist/completion.d.ts +3 -0
  63. package/dist/completion.js +34 -0
  64. package/dist/compliance-AxFf-uMy.d.ts +60 -0
  65. package/dist/compliance.d.ts +1 -0
  66. package/dist/compliance.js +17 -0
  67. package/dist/config-CaK60ByQ.d.ts +241 -0
  68. package/dist/config.d.ts +1 -97
  69. package/dist/config.js +8 -78
  70. package/dist/errcorrect-BcX1Ft0K.d.ts +44 -0
  71. package/dist/errcorrect.d.ts +1 -37
  72. package/dist/errcorrect.js +8 -68
  73. package/dist/error-Do8Qji43.d.ts +231 -0
  74. package/dist/id/index.d.ts +2 -83
  75. package/dist/id/index.js +14 -65
  76. package/dist/index-BKJZClJx.d.ts +1486 -0
  77. package/dist/index-C3Zw4wDJ.d.ts +359 -0
  78. package/dist/index-DCe1boBz.d.ts +328 -0
  79. package/dist/index-VLDcI5NF.d.ts +95 -0
  80. package/dist/index.d.ts +37 -0
  81. package/dist/index.js +132 -0
  82. package/dist/llm-DYuR7_uX.d.ts +1069 -0
  83. package/dist/llm-anthropic-Cd_I2xXB.d.ts +67 -0
  84. package/dist/llm-anthropic.d.ts +2 -0
  85. package/dist/llm-anthropic.js +13 -0
  86. package/dist/llm-openai-DyFrucmV.d.ts +87 -0
  87. package/dist/llm-openai.d.ts +2 -0
  88. package/dist/llm-openai.js +19 -0
  89. package/dist/llm.d.ts +1 -188
  90. package/dist/llm.js +101 -356
  91. package/dist/log-CkaxMX3U.d.ts +115 -0
  92. package/dist/log.d.ts +2 -0
  93. package/dist/log.js +14 -0
  94. package/dist/mcp/index.d.ts +4 -0
  95. package/dist/mcp/index.js +184 -0
  96. package/dist/netpolicy-Brx5XZUB.d.ts +151 -0
  97. package/dist/netpolicy.d.ts +1 -0
  98. package/dist/netpolicy.js +25 -0
  99. package/dist/output-CjZWmL8s.d.ts +420 -0
  100. package/dist/output.d.ts +3 -213
  101. package/dist/output.js +137 -447
  102. package/dist/parity-CvMuYcVI.d.ts +61 -0
  103. package/dist/progress-CAzyxeWl.d.ts +38 -0
  104. package/dist/progress.d.ts +1 -30
  105. package/dist/progress.js +6 -55
  106. package/dist/provenance-SMFHm5gx.d.ts +30 -0
  107. package/dist/provenance.d.ts +1 -24
  108. package/dist/provenance.js +6 -31
  109. package/dist/routellm-B0nv59mH.d.ts +111 -0
  110. package/dist/routellm.d.ts +2 -64
  111. package/dist/routellm.js +13 -255
  112. package/dist/rpc-D31Lg0Kc.d.ts +32 -0
  113. package/dist/rpc.d.ts +2 -25
  114. package/dist/rpc.js +4 -98
  115. package/dist/safety-CUaYEjZc.d.ts +30 -0
  116. package/dist/safety.d.ts +1 -24
  117. package/dist/safety.js +6 -43
  118. package/dist/scope-BrhYB4ij.d.ts +141 -0
  119. package/dist/scope.d.ts +1 -121
  120. package/dist/scope.js +20 -377
  121. package/dist/serve-D8yWMrTc.d.ts +646 -0
  122. package/dist/serve.d.ts +3 -0
  123. package/dist/serve.js +75 -0
  124. package/dist/sqlstore.js +6 -39
  125. package/dist/stream-CrjeCp0M.d.ts +44 -0
  126. package/dist/stream.d.ts +1 -35
  127. package/dist/stream.js +8 -51
  128. package/dist/telemetry/index.d.ts +1 -315
  129. package/dist/telemetry/index.js +26 -599
  130. package/dist/toolspec-DcPwwoAZ.d.ts +368 -0
  131. package/dist/toolspec.d.ts +2 -0
  132. package/dist/toolspec.js +37 -0
  133. package/dist/tui/index.d.ts +6 -298
  134. package/dist/tui/index.js +17 -381
  135. package/dist/upgrade-p_zh3pvV.d.ts +102 -0
  136. package/dist/upgrade.d.ts +1 -95
  137. package/dist/upgrade.js +6 -114
  138. package/dist/xdg-DB7Shoib.d.ts +179 -0
  139. package/dist/xdg.d.ts +1 -169
  140. package/dist/xdg.js +14 -128
  141. package/package.json +192 -24
  142. package/src/README.md +15 -0
  143. package/src/alias.conformance.test.ts +250 -0
  144. package/src/alias.test.ts +206 -2
  145. package/src/alias.ts +196 -21
  146. package/src/cli.help-command.test.ts +105 -0
  147. package/src/cli.offline.test.ts +93 -0
  148. package/src/cli.parity.test.ts +192 -0
  149. package/src/cli.test.ts +95 -1
  150. package/src/cli.ts +195 -25
  151. package/src/completion-scripts.ts +16 -0
  152. package/src/completion-values.test.ts +76 -16
  153. package/src/completion-values.ts +170 -66
  154. package/src/completion.conformance.test.ts +297 -0
  155. package/src/completion.test.ts +256 -145
  156. package/src/completion.ts +767 -121
  157. package/src/compliance.test.ts +196 -2
  158. package/src/compliance.ts +440 -20
  159. package/src/config-merge.test.ts +425 -0
  160. package/src/config.test.ts +228 -1
  161. package/src/config.ts +429 -16
  162. package/src/gen/crud_pb.ts +7 -7
  163. package/src/id/README.md +38 -0
  164. package/src/id/contract.test.ts +1 -1
  165. package/src/id/index.test.ts +1 -1
  166. package/src/id/index.ts +3 -2
  167. package/src/index.test.ts +71 -0
  168. package/src/index.ts +46 -0
  169. package/src/llm-anthropic.conformance.test.ts +1135 -0
  170. package/src/llm-anthropic.test.ts +152 -0
  171. package/src/llm-anthropic.ts +940 -0
  172. package/src/llm-choice-hermetic.test.ts +335 -0
  173. package/src/llm-config.test.ts +232 -0
  174. package/src/llm-config.ts +106 -0
  175. package/src/llm-endpoint.ts +254 -0
  176. package/src/llm-error.ts +17 -0
  177. package/src/llm-errors.ts +152 -0
  178. package/src/llm-file.ts +126 -0
  179. package/src/llm-http.ts +317 -0
  180. package/src/llm-keys.ts +167 -0
  181. package/src/llm-media.conformance.test.ts +87 -0
  182. package/src/llm-media.test.ts +279 -0
  183. package/src/llm-media.ts +322 -0
  184. package/src/llm-openai.conformance.test.ts +407 -0
  185. package/src/llm-openai.test.ts +510 -0
  186. package/src/llm-openai.ts +708 -0
  187. package/src/llm-payload.ts +155 -0
  188. package/src/llm-quote.ts +46 -0
  189. package/src/llm-routellm.conformance.test.ts +44 -0
  190. package/src/llm-toolnames.conformance.test.ts +112 -0
  191. package/src/llm-toolnames.test.ts +132 -0
  192. package/src/llm-toolnames.ts +298 -0
  193. package/src/llm-uri.ts +99 -0
  194. package/src/llm.test.ts +43 -15
  195. package/src/llm.toolcall.test.ts +175 -0
  196. package/src/llm.ts +602 -190
  197. package/src/log.parity.test.ts +105 -0
  198. package/src/log.test.ts +270 -1
  199. package/src/log.ts +228 -49
  200. package/src/mcp/README.md +63 -0
  201. package/src/mcp/args-separator.test.ts +164 -0
  202. package/src/mcp/args.test.ts +223 -0
  203. package/src/mcp/args.ts +160 -0
  204. package/src/mcp/audit.test.ts +520 -0
  205. package/src/mcp/audit.ts +70 -0
  206. package/src/mcp/bridge.test.ts +222 -0
  207. package/src/mcp/bridge.ts +291 -0
  208. package/src/mcp/conformance.test.ts +357 -0
  209. package/src/mcp/dispatch.ts +359 -0
  210. package/src/mcp/identity.test.ts +166 -0
  211. package/src/mcp/identity.ts +72 -0
  212. package/src/mcp/index.ts +176 -0
  213. package/src/mcp/legacy-notify.test.ts +59 -0
  214. package/src/mcp/legacy.ts +367 -0
  215. package/src/mcp/mcp.test.ts +707 -0
  216. package/src/mcp/modern-confirm.test.ts +520 -0
  217. package/src/mcp/modern-confirm.ts +484 -0
  218. package/src/mcp/modern.ts +788 -0
  219. package/src/mcp/stdio.test.ts +313 -0
  220. package/src/mcp/stdio.ts +254 -0
  221. package/src/mcp/tasks.ts +82 -0
  222. package/src/mcp/testtree.ts +250 -0
  223. package/src/mcp/toolname.test.ts +147 -0
  224. package/src/mcp/types.ts +689 -0
  225. package/src/netpolicy.test.ts +280 -0
  226. package/src/netpolicy.ts +256 -0
  227. package/src/output/README.md +46 -0
  228. package/src/output/builtins.ts +5 -5
  229. package/src/output/dispatch.ts +10 -2
  230. package/src/output/error.ts +459 -0
  231. package/src/output/formatter.ts +29 -5
  232. package/src/output/formatters/README.md +50 -0
  233. package/src/output/formatters/csv.ts +48 -12
  234. package/src/output/formatters/json.ts +4 -25
  235. package/src/output/formatters/project.ts +34 -0
  236. package/src/output/formatters/table.ts +8 -6
  237. package/src/output/formatters/text.ts +7 -3
  238. package/src/output/formatters/yaml.ts +5 -22
  239. package/src/output/projection.test.ts +298 -0
  240. package/src/output/projection.ts +33 -59
  241. package/src/output/template.ts +11 -21
  242. package/src/output.surface.test.ts +41 -0
  243. package/src/output.ts +64 -3
  244. package/src/published-types.test.ts +133 -0
  245. package/src/routellm.test.ts +209 -28
  246. package/src/routellm.toolcall.test.ts +521 -0
  247. package/src/routellm.ts +213 -177
  248. package/src/router/README.md +44 -0
  249. package/src/router/server.test.ts +41 -0
  250. package/src/router/server.ts +11 -0
  251. package/src/safety.test.ts +19 -9
  252. package/src/scope-defaults.json +29 -29
  253. package/src/serve.test.ts +1257 -0
  254. package/src/serve.ts +1665 -0
  255. package/src/telemetry/README.md +48 -0
  256. package/src/telemetry/client.test.ts +31 -0
  257. package/src/telemetry/client.ts +12 -6
  258. package/src/telemetry/offline.test.ts +64 -0
  259. package/src/toolspec-internal.ts +279 -0
  260. package/src/toolspec-manifest.test.ts +167 -0
  261. package/src/toolspec-manifest.ts +410 -0
  262. package/src/toolspec-spec-schemas.ts +12 -0
  263. package/src/toolspec-spec.test.ts +273 -0
  264. package/src/toolspec-spec.ts +458 -0
  265. package/src/toolspec.from-command.test.ts +350 -0
  266. package/src/toolspec.test.ts +2 -2
  267. package/src/toolspec.ts +222 -0
  268. package/src/triton/README.md +34 -0
  269. package/src/tui/README.md +42 -0
  270. package/src/tui/parity.test.ts +120 -31
  271. package/src/tui/parity.ts +58 -7
  272. package/src/wizard.test.ts +7 -7
  273. package/test/llm/conformance-helpers.ts +100 -0
  274. package/test/output/csv.test.ts +164 -0
  275. package/test/output/dispatch.test.ts +1 -2
  276. package/test/output/error.test.ts +277 -0
  277. package/test/output/smoke-capture.ts +2 -2
  278. package/test/output/smoke.test.ts +2 -2
  279. package/test/output/taxonomy-contract.test.ts +148 -0
  280. package/test/setup-env.ts +16 -0
  281. package/test/toolspec/fixture.ts +79 -0
  282. package/tsconfig.json +3 -1
  283. package/tsconfig.test.json +10 -0
  284. package/vitest.config.ts +9 -0
  285. package/src/tui/parity.json +0 -74
@@ -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
+ }