@hop-top/kit 0.5.0-alpha.3 → 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.
Files changed (187) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/LICENSE +1 -1
  3. package/README.md +47 -575
  4. package/dist/{aim-CTp-kJW2.d.ts → aim-DZHwwiIc.d.ts} +1 -1
  5. package/dist/aim.d.ts +1 -1
  6. package/dist/aim.js +13 -414
  7. package/dist/{alias-dhhr08Ei.d.ts → alias-BOj0-VAr.d.ts} +1 -1
  8. package/dist/alias.d.ts +1 -1
  9. package/dist/alias.js +18 -206
  10. package/dist/{api-miiso81x.d.ts → api-DAexsu2H.d.ts} +1 -1
  11. package/dist/api.d.ts +1 -1
  12. package/dist/api.js +10 -164
  13. package/dist/auth.js +6 -40
  14. package/dist/chunk-3FIKGFKI.js +54 -0
  15. package/dist/chunk-4UE5TCMQ.js +104 -0
  16. package/dist/chunk-6HFAEZ52.js +29 -0
  17. package/dist/chunk-6SVOHNIC.js +17 -0
  18. package/dist/chunk-72XZWQX7.js +504 -0
  19. package/dist/chunk-ABQSE7AI.js +513 -0
  20. package/dist/chunk-BDNNPRX6.js +41 -0
  21. package/dist/chunk-BRNEKPWX.js +37 -0
  22. package/dist/chunk-CSJWB6D3.js +151 -0
  23. package/dist/chunk-GGWJRWWA.js +309 -0
  24. package/dist/chunk-IQXEISMC.js +142 -0
  25. package/dist/chunk-JTMPNXVQ.js +1491 -0
  26. package/dist/chunk-KVG7YCTS.js +115 -0
  27. package/dist/chunk-L23O2FFE.js +51 -0
  28. package/dist/chunk-MQXYDYRD.js +968 -0
  29. package/dist/chunk-MUIQVU6E.js +251 -0
  30. package/dist/chunk-POR5L2DG.js +247 -0
  31. package/dist/chunk-PSFYJGDG.js +1445 -0
  32. package/dist/chunk-QJVSKKRQ.js +369 -0
  33. package/dist/chunk-QPUCXQXT.js +67 -0
  34. package/dist/chunk-R5U7XKVJ.js +16 -0
  35. package/dist/chunk-S45UHXQF.js +182 -0
  36. package/dist/chunk-T46YPHKN.js +669 -0
  37. package/dist/chunk-UIOOOK6M.js +334 -0
  38. package/dist/chunk-UKZIAQA7.js +26 -0
  39. package/dist/chunk-WBVO43HU.js +355 -0
  40. package/dist/chunk-WTYDHXPW.js +574 -0
  41. package/dist/chunk-WUOAQVOA.js +86 -0
  42. package/dist/chunk-WWUKGJB5.js +90 -0
  43. package/dist/chunk-YGYQUFGY.js +219 -0
  44. package/dist/chunk-YOBAUCVN.js +583 -0
  45. package/dist/{cli-DLygZLi9.d.ts → cli-8rfITnv4.d.ts} +13 -4
  46. package/dist/cli.d.ts +4 -4
  47. package/dist/cli.js +50 -1057
  48. package/dist/{config-BUY7_W2n.d.ts → config-Bm9fBXch.d.ts} +35 -4
  49. package/dist/config.d.ts +1 -1
  50. package/dist/config.js +6 -78
  51. package/dist/errcorrect.js +8 -68
  52. package/dist/{error-DISJKeDu.d.ts → error-Do8Qji43.d.ts} +88 -1
  53. package/dist/id/index.d.ts +1 -1
  54. package/dist/id/index.js +14 -65
  55. package/dist/{index-MLrRDvEG.d.ts → index-B-pqGHhU.d.ts} +113 -19
  56. package/dist/{index-Bc5c7Ty5.d.ts → index-DEyjGoo2.d.ts} +1 -1
  57. package/dist/{index-QSffbLnj.d.ts → index-VLDcI5NF.d.ts} +3 -2
  58. package/dist/index.d.ts +18 -15
  59. package/dist/index.js +39 -6722
  60. package/dist/llm-DYuR7_uX.d.ts +1069 -0
  61. package/dist/llm-anthropic-Cd_I2xXB.d.ts +67 -0
  62. package/dist/llm-anthropic.d.ts +2 -0
  63. package/dist/llm-anthropic.js +13 -0
  64. package/dist/llm-openai-DyFrucmV.d.ts +87 -0
  65. package/dist/llm-openai.d.ts +2 -0
  66. package/dist/llm-openai.js +19 -0
  67. package/dist/llm.d.ts +1 -1
  68. package/dist/llm.js +101 -356
  69. package/dist/mcp/index.d.ts +2 -1
  70. package/dist/mcp/index.js +155 -1453
  71. package/dist/{netpolicy-asvCfwi8.d.ts → netpolicy-Brx5XZUB.d.ts} +16 -3
  72. package/dist/netpolicy.d.ts +1 -1
  73. package/dist/netpolicy.js +25 -118
  74. package/dist/{output-4aXs91GY.d.ts → output-CjZWmL8s.d.ts} +28 -4
  75. package/dist/output.d.ts +2 -2
  76. package/dist/output.js +137 -971
  77. package/dist/progress.js +6 -55
  78. package/dist/provenance.js +6 -31
  79. package/dist/routellm-B0nv59mH.d.ts +111 -0
  80. package/dist/routellm.d.ts +2 -2
  81. package/dist/routellm.js +13 -255
  82. package/dist/{rpc-D5xLEf8V.d.ts → rpc-D31Lg0Kc.d.ts} +1 -1
  83. package/dist/rpc.d.ts +2 -2
  84. package/dist/rpc.js +4 -98
  85. package/dist/safety.js +6 -43
  86. package/dist/scope.js +20 -377
  87. package/dist/{serve-DE-jscpb.d.ts → serve-D8yWMrTc.d.ts} +2 -2
  88. package/dist/serve.d.ts +2 -2
  89. package/dist/serve.js +75 -1019
  90. package/dist/sqlstore.js +6 -39
  91. package/dist/stream.js +8 -51
  92. package/dist/telemetry/index.js +24 -608
  93. package/dist/tui/index.d.ts +5 -5
  94. package/dist/tui/index.js +17 -374
  95. package/dist/upgrade.js +6 -114
  96. package/dist/xdg.js +14 -128
  97. package/package.json +130 -25
  98. package/src/README.md +15 -0
  99. package/src/cli.test.ts +56 -1
  100. package/src/cli.ts +24 -4
  101. package/src/completion-values.test.ts +10 -10
  102. package/src/compliance.test.ts +196 -2
  103. package/src/compliance.ts +440 -20
  104. package/src/config.test.ts +187 -1
  105. package/src/config.ts +173 -7
  106. package/src/gen/crud_pb.ts +7 -7
  107. package/src/id/README.md +38 -0
  108. package/src/id/contract.test.ts +1 -1
  109. package/src/id/index.test.ts +1 -1
  110. package/src/id/index.ts +3 -2
  111. package/src/index.test.ts +12 -0
  112. package/src/index.ts +2 -0
  113. package/src/llm-anthropic.conformance.test.ts +1135 -0
  114. package/src/llm-anthropic.test.ts +152 -0
  115. package/src/llm-anthropic.ts +940 -0
  116. package/src/llm-choice-hermetic.test.ts +335 -0
  117. package/src/llm-config.test.ts +232 -0
  118. package/src/llm-config.ts +106 -0
  119. package/src/llm-endpoint.ts +254 -0
  120. package/src/llm-error.ts +17 -0
  121. package/src/llm-errors.ts +152 -0
  122. package/src/llm-file.ts +126 -0
  123. package/src/llm-http.ts +317 -0
  124. package/src/llm-keys.ts +167 -0
  125. package/src/llm-media.conformance.test.ts +87 -0
  126. package/src/llm-media.test.ts +279 -0
  127. package/src/llm-media.ts +322 -0
  128. package/src/llm-openai.conformance.test.ts +407 -0
  129. package/src/llm-openai.test.ts +510 -0
  130. package/src/llm-openai.ts +708 -0
  131. package/src/llm-payload.ts +155 -0
  132. package/src/llm-quote.ts +46 -0
  133. package/src/llm-routellm.conformance.test.ts +44 -0
  134. package/src/llm-toolnames.conformance.test.ts +112 -0
  135. package/src/llm-toolnames.test.ts +132 -0
  136. package/src/llm-toolnames.ts +298 -0
  137. package/src/llm-uri.ts +99 -0
  138. package/src/llm.test.ts +43 -15
  139. package/src/llm.toolcall.test.ts +175 -0
  140. package/src/llm.ts +602 -190
  141. package/src/mcp/README.md +57 -0
  142. package/src/mcp/conformance.test.ts +24 -3
  143. package/src/mcp/dispatch.ts +4 -4
  144. package/src/mcp/identity.test.ts +166 -0
  145. package/src/mcp/identity.ts +72 -0
  146. package/src/mcp/index.ts +6 -0
  147. package/src/mcp/legacy.ts +21 -8
  148. package/src/mcp/mcp.test.ts +14 -4
  149. package/src/mcp/modern-confirm.ts +1 -1
  150. package/src/mcp/modern.ts +12 -11
  151. package/src/mcp/tasks.ts +1 -1
  152. package/src/mcp/types.ts +80 -8
  153. package/src/netpolicy.test.ts +78 -0
  154. package/src/netpolicy.ts +28 -3
  155. package/src/output/README.md +46 -0
  156. package/src/output/builtins.ts +5 -5
  157. package/src/output/error.ts +144 -1
  158. package/src/output/formatters/README.md +50 -0
  159. package/src/output.ts +24 -1
  160. package/src/published-types.test.ts +115 -0
  161. package/src/routellm.test.ts +209 -28
  162. package/src/routellm.toolcall.test.ts +521 -0
  163. package/src/routellm.ts +213 -177
  164. package/src/router/README.md +44 -0
  165. package/src/router/server.test.ts +41 -0
  166. package/src/router/server.ts +11 -0
  167. package/src/safety.test.ts +19 -9
  168. package/src/scope-defaults.json +29 -29
  169. package/src/serve.ts +1 -1
  170. package/src/telemetry/README.md +48 -0
  171. package/src/telemetry/client.ts +5 -5
  172. package/src/toolspec.test.ts +2 -2
  173. package/src/triton/README.md +34 -0
  174. package/src/tui/README.md +42 -0
  175. package/src/wizard.test.ts +7 -7
  176. package/test/llm/conformance-helpers.ts +100 -0
  177. package/test/output/dispatch.test.ts +1 -2
  178. package/test/output/error.test.ts +33 -2
  179. package/test/output/smoke-capture.ts +2 -2
  180. package/test/output/smoke.test.ts +2 -2
  181. package/test/output/taxonomy-contract.test.ts +148 -0
  182. package/test/setup-env.ts +16 -0
  183. package/tsconfig.json +3 -1
  184. package/tsconfig.test.json +10 -0
  185. package/vitest.config.ts +9 -0
  186. package/dist/llm-B5XUWH8T.d.ts +0 -231
  187. package/dist/routellm-PGSt2D1y.d.ts +0 -75
@@ -0,0 +1,1135 @@
1
+ // Runs contracts/llm-v1/vectors.json against this SDK: every
2
+ // anthropic_* section through AnthropicAdapter and loopback fake
3
+ // servers, credential_headers, key_endpoint, parse_uri, redact_uri,
4
+ // usage_cost, and the bus_* payloads through the pure builders (this
5
+ // client publishes no bus events). Go is canonical; a failure means
6
+ // this SDK drifted, not that a vector should change. tool_names runs
7
+ // in llm-toolnames.conformance.test.ts, media_fetch in
8
+ // llm-media.conformance.test.ts, openai_* in
9
+ // llm-openai.conformance.test.ts. A section in neither list fails the
10
+ // run, so none is skipped silently.
11
+
12
+ import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
13
+ import { tmpdir } from "node:os";
14
+ import { join } from "node:path";
15
+ import { afterEach, beforeEach, describe, expect, it } from "vitest";
16
+
17
+ import {
18
+ APIError,
19
+ AuthError,
20
+ LLMError,
21
+ HTTPStatusError,
22
+ KeyEndpointError,
23
+ ModelError,
24
+ PermissionDeniedError,
25
+ RateLimitError,
26
+ ResponseTooLargeError,
27
+ StreamTruncatedError,
28
+ ToolNameError,
29
+ inlineSource,
30
+ applyAPIKey,
31
+ isFallbackable,
32
+ loadConfig,
33
+ parseURI,
34
+ redactURI,
35
+ resolve,
36
+ requestStartedPayload,
37
+ responseReceivedPayload,
38
+ usageCost,
39
+ type CallOp,
40
+ type MediaSource,
41
+ type Message,
42
+ type Request,
43
+ type ResolvedConfig,
44
+ type Token,
45
+ type ToolCall,
46
+ type ToolChoiceMode,
47
+ type ToolDef,
48
+ type ToolStream,
49
+ type Usage,
50
+ } from "./llm";
51
+ import { AnthropicAdapter } from "./llm-anthropic";
52
+ import {
53
+ fakeServer,
54
+ isolateEnv,
55
+ loadVectors,
56
+ reply,
57
+ strictKeys,
58
+ type FakeServer,
59
+ } from "../test/llm/conformance-helpers";
60
+
61
+ // ─── Vector shapes ───────────────────────────────────────────────────────────
62
+
63
+ interface VMessage {
64
+ role: string;
65
+ content?: string;
66
+ parts?: { type: string; text?: string; mime_type?: string; data?: string; url?: string }[];
67
+ tool_calls?: { id?: string; name: string; arguments?: string }[];
68
+ tool_call_id?: string;
69
+ cache_control?: { ttl: string };
70
+ thinking?: { thinking?: string; signature?: string; redacted?: string }[];
71
+ }
72
+
73
+ interface VRequest {
74
+ model?: string;
75
+ temperature?: number;
76
+ max_tokens?: number;
77
+ stop_sequences?: string[];
78
+ messages: VMessage[];
79
+ thinking_budget?: number;
80
+ extensions?: Record<string, unknown>;
81
+ }
82
+
83
+ interface VTool {
84
+ name: string;
85
+ description?: string;
86
+ parameters?: string;
87
+ cache_control?: { ttl: string };
88
+ }
89
+
90
+ interface VResponse {
91
+ status: number;
92
+ headers: Record<string, string>;
93
+ body: string;
94
+ }
95
+
96
+ type Section = Record<string, unknown>[];
97
+
98
+ interface File {
99
+ version: string;
100
+ description: string;
101
+ [section: string]: unknown;
102
+ }
103
+
104
+ /** Sections run here and by sibling runners. */
105
+ const RUN = [
106
+ "redact_uri", "parse_uri", "usage_cost", "credential_headers", "key_endpoint",
107
+ "anthropic_request", "anthropic_request_error", "anthropic_headers",
108
+ "anthropic_stream", "anthropic_accumulate", "anthropic_error",
109
+ "anthropic_limits", "anthropic_response", "anthropic_tool_names",
110
+ "anthropic_tool_choice", "anthropic_hermetic", "anthropic_stream_events",
111
+ "bus_request_started", "bus_response_received",
112
+ ];
113
+ const SIBLING = [
114
+ "tool_names", "media_fetch", "gemini_stream_events",
115
+ // llm-openai.conformance.test.ts
116
+ "openai_request", "openai_stream", "openai_stream_events",
117
+ "openai_accumulate", "openai_error", "openai_limits",
118
+ // llm-routellm.conformance.test.ts
119
+ "routellm_base_url",
120
+ ];
121
+
122
+ const file = loadVectors<File>();
123
+ const section = (name: string): Section => file[name] as Section;
124
+ const CONF_KEY = "conf-key-must-not-leak";
125
+
126
+ describe("llm-v1 conformance file", () => {
127
+ it("is v1 and every section has a runner or a stated reason", () => {
128
+ expect(file.version).toBe("v1");
129
+ for (const k of Object.keys(file)) {
130
+ if (k === "version" || k === "description") continue;
131
+ expect(
132
+ RUN.includes(k) || SIBLING.includes(k),
133
+ `section ${k} has no runner`
134
+ ).toBe(true);
135
+ }
136
+ for (const s of RUN) expect(section(s)?.length, s).toBeGreaterThan(0);
137
+ });
138
+ });
139
+
140
+ // ─── Conversions ─────────────────────────────────────────────────────────────
141
+
142
+ /** A URL media source the adapter must send as a URL: reading it fails. */
143
+ function unfetchedURL(url: string): MediaSource {
144
+ return {
145
+ url: () => url,
146
+ mimeType: () => "",
147
+ read: async () => {
148
+ throw new Error(`url source ${url} was fetched; it must be sent as a url source`);
149
+ },
150
+ };
151
+ }
152
+
153
+ function toMessage(m: VMessage): Message {
154
+ strictKeys(m, [
155
+ "role", "content", "parts", "tool_calls", "tool_call_id", "cache_control", "thinking",
156
+ ], "message");
157
+ const out: Message = { role: m.role, content: m.content ?? "" };
158
+ if (m.parts) {
159
+ out.parts = m.parts.map((p) => {
160
+ strictKeys(p, ["type", "text", "mime_type", "data", "url"], "part");
161
+ return {
162
+ type: p.type as "text",
163
+ text: p.text,
164
+ mimeType: p.mime_type,
165
+ source: p.url
166
+ ? unfetchedURL(p.url)
167
+ : p.data
168
+ ? inlineSource(new Uint8Array(Buffer.from(p.data, "base64")), p.mime_type ?? "")
169
+ : undefined,
170
+ };
171
+ });
172
+ }
173
+ if (m.tool_calls) {
174
+ out.toolCalls = m.tool_calls.map(
175
+ (tc): ToolCall => ({ id: tc.id ?? "", name: tc.name, arguments: tc.arguments })
176
+ );
177
+ }
178
+ if (m.tool_call_id) out.toolCallId = m.tool_call_id;
179
+ if (m.cache_control) out.cacheControl = { ttl: m.cache_control.ttl };
180
+ if (m.thinking) {
181
+ out.thinking = m.thinking.map((t) => ({
182
+ thinking: t.thinking ?? "",
183
+ signature: t.signature ?? "",
184
+ redacted: t.redacted ?? "",
185
+ }));
186
+ }
187
+ return out;
188
+ }
189
+
190
+ function toRequest(r: VRequest): Request {
191
+ strictKeys(r, [
192
+ "model", "temperature", "max_tokens", "stop_sequences", "messages", "thinking_budget",
193
+ "extensions",
194
+ ], "request");
195
+ const out: Request = { messages: r.messages.map(toMessage) };
196
+ if (r.model) out.model = r.model;
197
+ if (r.temperature !== undefined) out.temperature = r.temperature;
198
+ if (r.max_tokens) out.maxTokens = r.max_tokens;
199
+ if (r.stop_sequences) out.stopSequences = r.stop_sequences;
200
+ if (r.thinking_budget) out.thinking = { budgetTokens: r.thinking_budget };
201
+ if (r.extensions) out.extensions = r.extensions;
202
+ return out;
203
+ }
204
+
205
+ function toTools(tools: VTool[]): ToolDef[] {
206
+ return tools.map((t) => {
207
+ strictKeys(t, ["name", "description", "parameters", "cache_control"], "tool");
208
+ const d: ToolDef = { name: t.name, description: t.description ?? "", parameters: t.parameters };
209
+ if (t.cache_control) d.cacheControl = { ttl: t.cache_control.ttl };
210
+ return d;
211
+ });
212
+ }
213
+
214
+ function adapter(
215
+ base: string,
216
+ opts: { model?: string; key?: string; params?: Record<string, string> } = {}
217
+ ): AnthropicAdapter {
218
+ const cfg: ResolvedConfig = {
219
+ uri: { scheme: "anthropic", model: opts.model ?? "m" },
220
+ provider: {
221
+ apiKey: opts.key ?? "k",
222
+ baseURL: base,
223
+ model: opts.model ?? "m",
224
+ params: opts.params,
225
+ },
226
+ fallbacks: [],
227
+ };
228
+ return new AnthropicAdapter(cfg);
229
+ }
230
+
231
+ const HI: Request = { messages: [{ role: "user", content: "Hi" }] };
232
+ const OK_MESSAGE = JSON.stringify({
233
+ id: "msg_1", type: "message", role: "assistant", model: "m",
234
+ content: [{ type: "text", text: "ok" }], stop_reason: "end_turn",
235
+ usage: { input_tokens: 1, output_tokens: 1 },
236
+ });
237
+
238
+ /** Reads a stream to its end: tokens, thinking deltas, and the error. */
239
+ async function drain(s: AsyncIterable<{ content: string; thinking?: string; done: boolean }>) {
240
+ const tokens: string[] = [];
241
+ const thinking: string[] = [];
242
+ let error: unknown;
243
+ let done = false;
244
+ try {
245
+ for await (const t of s) {
246
+ if (t.done) {
247
+ done = true;
248
+ break;
249
+ }
250
+ if (t.thinking) thinking.push(t.thinking);
251
+ else tokens.push(t.content);
252
+ }
253
+ } catch (e) {
254
+ error = e;
255
+ }
256
+ return { tokens, thinking, error, done };
257
+ }
258
+
259
+ function errorKind(err: unknown): [string, number] {
260
+ if (err === undefined || err === null) return ["", 0];
261
+ if (err instanceof StreamTruncatedError) return ["truncated", 0];
262
+ if (err instanceof ResponseTooLargeError) return ["too_large", 0];
263
+ if (err instanceof PermissionDeniedError) {
264
+ // A permission denial is an auth error too.
265
+ return [err instanceof AuthError ? "permission_denied" : "permission_denied without auth", 0];
266
+ }
267
+ if (err instanceof AuthError) return ["auth", 0];
268
+ if (err instanceof RateLimitError) return ["rate_limit", 0];
269
+ if (err instanceof ModelError) return ["model", 0];
270
+ if (err instanceof HTTPStatusError) return ["http_status", err.statusCode ?? 0];
271
+ if (err instanceof APIError) return ["api", err.statusCode ?? 0];
272
+ return ["other", 0];
273
+ }
274
+
275
+ let restoreEnv: () => void;
276
+ const servers: FakeServer[] = [];
277
+ beforeEach(() => {
278
+ restoreEnv = isolateEnv();
279
+ });
280
+ afterEach(async () => {
281
+ restoreEnv();
282
+ await Promise.all(servers.splice(0).map((s) => s.close()));
283
+ });
284
+
285
+ async function server(
286
+ handler: Parameters<typeof fakeServer>[0]
287
+ ): Promise<FakeServer> {
288
+ const s = await fakeServer(handler);
289
+ servers.push(s);
290
+ return s;
291
+ }
292
+
293
+ const sseServer = (body: string) =>
294
+ server((_h, res) => reply(res, "text/event-stream", body));
295
+
296
+ /**
297
+ * Points XDG_CONFIG_HOME at a fresh dir holding `yaml` as hop/llm.yaml
298
+ * (none when empty), where Go reads it. Restored after each test.
299
+ */
300
+ function useLLMYaml(yaml: string): void {
301
+ const xdg = mkdtempSync(join(tmpdir(), "kit-llm-conf-"));
302
+ const restore = isolateEnv(["XDG_CONFIG_HOME"]);
303
+ process.env["XDG_CONFIG_HOME"] = xdg;
304
+ if (yaml !== "") {
305
+ mkdirSync(join(xdg, "hop"), { recursive: true });
306
+ writeFileSync(join(xdg, "hop", "llm.yaml"), yaml);
307
+ }
308
+ cleanups.push(() => {
309
+ restore();
310
+ rmSync(xdg, { recursive: true, force: true });
311
+ });
312
+ }
313
+ const cleanups: (() => void)[] = [];
314
+ afterEach(() => {
315
+ for (const c of cleanups.splice(0).reverse()) c();
316
+ });
317
+
318
+ // ─── Provider-neutral sections ───────────────────────────────────────────────
319
+
320
+ describe("llm-v1 conformance: redact_uri", () => {
321
+ for (const v of section("redact_uri") as { name: string; in: string; want: string }[]) {
322
+ it(v.name, () => {
323
+ strictKeys(v, ["name", "in", "want"], v.name);
324
+ expect(redactURI(v.in)).toBe(v.want);
325
+ });
326
+ }
327
+ });
328
+
329
+ describe("llm-v1 conformance: parse_uri", () => {
330
+ type V = {
331
+ name: string;
332
+ uri: string;
333
+ scheme?: string;
334
+ model?: string;
335
+ host?: string;
336
+ params?: Record<string, string> | null;
337
+ error: string;
338
+ };
339
+ for (const v of section("parse_uri") as V[]) {
340
+ it(v.name, () => {
341
+ strictKeys(v, ["name", "uri", "scheme", "model", "host", "params", "error"], v.name);
342
+ if (v.error) {
343
+ let err: unknown;
344
+ try {
345
+ parseURI(v.uri);
346
+ } catch (e) {
347
+ err = e;
348
+ }
349
+ expect(err).toBeInstanceOf(LLMError);
350
+ expect((err as Error).message).toBe(v.error);
351
+ return;
352
+ }
353
+ const u = parseURI(v.uri);
354
+ expect(u.scheme).toBe(v.scheme);
355
+ expect(u.model).toBe(v.model);
356
+ expect(u.host ?? "").toBe(v.host);
357
+ expect(u.params ?? {}).toEqual(v.params ?? {});
358
+ });
359
+ }
360
+ });
361
+
362
+ describe("llm-v1 conformance: key_endpoint", () => {
363
+ type V = {
364
+ name: string;
365
+ op: string;
366
+ uri: string;
367
+ yaml: string;
368
+ env: Record<string, string>;
369
+ want_uri: string;
370
+ refused: boolean;
371
+ };
372
+ for (const v of section("key_endpoint") as V[]) {
373
+ it(v.name, () => {
374
+ strictKeys(v, ["name", "op", "uri", "yaml", "env", "want_uri", "refused"], v.name);
375
+ useLLMYaml(v.yaml);
376
+ Object.assign(process.env, v.env);
377
+ let got: string | undefined;
378
+ let err: unknown;
379
+ try {
380
+ switch (v.op) {
381
+ case "apply":
382
+ got = applyAPIKey(v.uri);
383
+ break;
384
+ case "load":
385
+ loadConfig(v.uri);
386
+ break;
387
+ case "resolve":
388
+ resolve(v.uri);
389
+ break;
390
+ default:
391
+ throw new Error(`unknown op ${JSON.stringify(v.op)}`);
392
+ }
393
+ } catch (e) {
394
+ err = e;
395
+ }
396
+ if (v.refused) {
397
+ expect(err).toBeInstanceOf(KeyEndpointError);
398
+ expect((err as Error).message).not.toContain("fake-env-key");
399
+ return;
400
+ }
401
+ expect(err).toBeUndefined();
402
+ if (v.op === "apply") expect(got).toBe(v.want_uri);
403
+ });
404
+ }
405
+ });
406
+
407
+ describe("llm-v1 conformance: usage_cost", () => {
408
+ type V = {
409
+ name: string;
410
+ usage: Record<string, number>;
411
+ price: Record<string, number>;
412
+ want: number;
413
+ };
414
+ for (const v of section("usage_cost") as V[]) {
415
+ it(v.name, () => {
416
+ strictKeys(v, ["name", "usage", "price", "want"], v.name);
417
+ const got = usageCost(
418
+ {
419
+ promptTokens: v.usage["prompt_tokens"]!,
420
+ completionTokens: v.usage["completion_tokens"]!,
421
+ cacheReadTokens: v.usage["cache_read_tokens"]!,
422
+ cacheCreationTokens: v.usage["cache_creation_tokens"]!,
423
+ totalTokens: 0,
424
+ },
425
+ {
426
+ input: v.price["input"]!,
427
+ output: v.price["output"]!,
428
+ cacheRead: v.price["cache_read"]!,
429
+ cacheWrite: v.price["cache_write"]!,
430
+ }
431
+ );
432
+ expect(got).toBeCloseTo(v.want, 9);
433
+ });
434
+ }
435
+ });
436
+
437
+ // ─── anthropic_* ─────────────────────────────────────────────────────────────
438
+
439
+ describe("llm-v1 conformance: anthropic_request", () => {
440
+ type V = {
441
+ name: string;
442
+ adapter_model: string;
443
+ request: VRequest;
444
+ tools?: VTool[];
445
+ want_body: unknown;
446
+ };
447
+ for (const v of section("anthropic_request") as V[]) {
448
+ it(v.name, async () => {
449
+ strictKeys(v, ["name", "adapter_model", "request", "tools", "want_body"], v.name);
450
+ const s = await server((_h, res) => reply(res, "application/json", OK_MESSAGE));
451
+ const a = adapter(s.url, { model: v.adapter_model });
452
+ const req = toRequest(v.request);
453
+ if (v.tools) await a.callWithTools(req, toTools(v.tools));
454
+ else await a.complete(req);
455
+ expect(s.hits).toHaveLength(1);
456
+ expect(JSON.parse(s.hits[0]!.body)).toEqual(v.want_body);
457
+ });
458
+ }
459
+ });
460
+
461
+ describe("llm-v1 conformance: anthropic_request_error", () => {
462
+ type V = { name: string; request: VRequest; error: string };
463
+ for (const v of section("anthropic_request_error") as V[]) {
464
+ it(v.name, async () => {
465
+ strictKeys(v, ["name", "request", "error"], v.name);
466
+ const s = await server((_h, res) => reply(res, "application/json", OK_MESSAGE));
467
+ const err = await adapter(s.url)
468
+ .complete(toRequest(v.request))
469
+ .then(() => undefined, (e: unknown) => e);
470
+ expect(err).toBeInstanceOf(Error);
471
+ expect((err as Error).message).toBe(v.error);
472
+ expect(s.hits, "a rejected request is never sent").toHaveLength(0);
473
+ });
474
+ }
475
+ });
476
+
477
+ describe("llm-v1 conformance: anthropic_headers", () => {
478
+ type V = {
479
+ name: string;
480
+ api_key: string;
481
+ env: Record<string, string>;
482
+ want: Record<string, string>;
483
+ absent: string[];
484
+ };
485
+ for (const v of section("anthropic_headers") as V[]) {
486
+ it(v.name, async () => {
487
+ strictKeys(v, ["name", "api_key", "env", "want", "absent"], v.name);
488
+ Object.assign(process.env, v.env);
489
+ const s = await server((_h, res) => reply(res, "application/json", OK_MESSAGE));
490
+ await adapter(s.url, { key: v.api_key }).complete(HI);
491
+ const got = s.hits[0]!.headers;
492
+ for (const [k, want] of Object.entries(v.want)) expect(got[k], k).toBe(want);
493
+ for (const k of v.absent) expect(got[k], k).toBeUndefined();
494
+ });
495
+ }
496
+ });
497
+
498
+ describe("llm-v1 conformance: credential_headers", () => {
499
+ type V = {
500
+ name: string;
501
+ base_url: string;
502
+ yaml: string;
503
+ env: Record<string, string>;
504
+ sent: string[];
505
+ withheld: string[];
506
+ refused: boolean;
507
+ };
508
+ for (const v of section("credential_headers") as V[]) {
509
+ it(v.name, async () => {
510
+ strictKeys(v, ["name", "base_url", "yaml", "env", "sent", "withheld", "refused"], v.name);
511
+ useLLMYaml(v.yaml);
512
+ Object.assign(process.env, v.env);
513
+ // Intercept fetch: the vectors name hosts no test may reach.
514
+ const sent: Headers[] = [];
515
+ const orig = globalThis.fetch;
516
+ globalThis.fetch = (async (_u: unknown, init?: RequestInit) => {
517
+ sent.push(new Headers(init?.headers));
518
+ return new globalThis.Response(OK_MESSAGE, {
519
+ status: 200,
520
+ headers: { "content-type": "application/json" },
521
+ });
522
+ }) as typeof fetch;
523
+ try {
524
+ let a: AnthropicAdapter;
525
+ try {
526
+ a = adapter(v.base_url, { key: "kit-key" });
527
+ } catch (e) {
528
+ expect(v.refused, String(e)).toBe(true);
529
+ expect(e).toBeInstanceOf(KeyEndpointError);
530
+ return;
531
+ }
532
+ expect(v.refused).toBe(false);
533
+ await a.complete(HI);
534
+ } finally {
535
+ globalThis.fetch = orig;
536
+ }
537
+ expect(sent).toHaveLength(1);
538
+ for (const h of v.sent) expect(sent[0]!.get(h), h).toBeTruthy();
539
+ for (const h of v.withheld) expect(sent[0]!.get(h), h).toBeNull();
540
+ });
541
+ }
542
+ });
543
+
544
+ describe("llm-v1 conformance: anthropic_stream", () => {
545
+ type V = {
546
+ name: string;
547
+ sse: string;
548
+ want_tokens: string[];
549
+ want_error: boolean;
550
+ error_kind: string;
551
+ thinking_budget: number;
552
+ want_thinking: string[];
553
+ };
554
+ for (const v of section("anthropic_stream") as V[]) {
555
+ it(v.name, async () => {
556
+ strictKeys(v, [
557
+ "name", "sse", "want_tokens", "want_error", "error_kind", "thinking_budget", "want_thinking",
558
+ ], v.name);
559
+ const s = await sseServer(v.sse);
560
+ const req: Request = { ...HI };
561
+ if (v.thinking_budget > 0) {
562
+ req.maxTokens = 4 * v.thinking_budget;
563
+ req.thinking = { budgetTokens: v.thinking_budget };
564
+ }
565
+ const st = adapter(s.url).stream(req);
566
+ const r = await drain(st);
567
+ expect(r.tokens).toEqual(v.want_tokens);
568
+ expect(r.thinking).toEqual(v.want_thinking);
569
+ expect(r.error !== undefined, String(r.error)).toBe(v.want_error);
570
+ expect(errorKind(r.error)[0], String(r.error)).toBe(v.error_kind);
571
+ if (r.done) {
572
+ // Nothing follows the final token.
573
+ expect((await st[Symbol.asyncIterator]().next()).done).toBe(true);
574
+ }
575
+ });
576
+ }
577
+ });
578
+
579
+ describe("llm-v1 conformance: anthropic_accumulate", () => {
580
+ type W = {
581
+ text?: string;
582
+ thinking?: string;
583
+ tool_calls?: { id: string; name: string; input: unknown }[];
584
+ stop_reason?: string;
585
+ usage?: Record<string, number>;
586
+ error: boolean;
587
+ thinking_blocks: { thinking: string; signature: string; redacted: string }[] | null;
588
+ };
589
+ type V = { name: string; sse?: string; sse_from?: string; want: W };
590
+ const streams = new Map(
591
+ (section("anthropic_stream") as { name: string; sse: string }[]).map((s) => [
592
+ `anthropic_stream/${s.name}`,
593
+ s.sse,
594
+ ])
595
+ );
596
+ for (const v of section("anthropic_accumulate") as V[]) {
597
+ it(v.name, async () => {
598
+ strictKeys(v, ["name", "sse", "sse_from", "want"], v.name);
599
+ strictKeys(v.want, [
600
+ "text", "thinking", "tool_calls", "stop_reason", "usage", "error", "thinking_blocks",
601
+ ], v.name);
602
+ const sse = v.sse_from ? streams.get(v.sse_from) : v.sse;
603
+ expect(sse, `sse_from ${v.sse_from}`).toBeDefined();
604
+ const s = await sseServer(sse!);
605
+ const st: ToolStream = adapter(s.url).streamWithTools(HI, [
606
+ { name: "get_weather", description: "", parameters: undefined },
607
+ ]);
608
+ const r = await drain(st);
609
+ expect(r.error !== undefined, String(r.error)).toBe(v.want.error);
610
+ if (v.want.error) {
611
+ expect(st.outcome(), "no outcome after an error").toBeUndefined();
612
+ return;
613
+ }
614
+ const out = st.outcome();
615
+ expect(out).toBeDefined();
616
+ expect(out!.content).toBe(v.want.text);
617
+ expect(out!.thinking.map((b) => b.thinking).join("")).toBe(v.want.thinking);
618
+ expect(out!.finishReason).toBe(v.want.stop_reason);
619
+ expect(out!.usage.promptTokens).toBe(v.want.usage!["input_tokens"]);
620
+ expect(out!.usage.completionTokens).toBe(v.want.usage!["output_tokens"]);
621
+ expect(out!.usage.cacheReadTokens).toBe(v.want.usage!["cache_read_tokens"]);
622
+ expect(out!.usage.cacheCreationTokens).toBe(v.want.usage!["cache_creation_tokens"]);
623
+ if (v.want.thinking_blocks !== null) {
624
+ expect(out!.thinking).toEqual(v.want.thinking_blocks);
625
+ }
626
+ expect(out!.toolCalls.map((c) => ({ id: c.id, name: c.name, input: c.arguments }))).toEqual(
627
+ v.want.tool_calls
628
+ );
629
+ });
630
+ }
631
+ });
632
+
633
+ describe("llm-v1 conformance: anthropic_error", () => {
634
+ type V = {
635
+ name: string;
636
+ responses: VResponse[];
637
+ want_kind: string;
638
+ want_status: number;
639
+ fallbackable: boolean;
640
+ attempts: number;
641
+ stream: boolean;
642
+ };
643
+ for (const v of section("anthropic_error") as V[]) {
644
+ it(v.name, { timeout: 10_000 }, async () => {
645
+ strictKeys(v, [
646
+ "name", "responses", "want_kind", "want_status", "fallbackable", "attempts", "stream",
647
+ ], v.name);
648
+ const s = await server((_h, res, n) => {
649
+ const r = v.responses[Math.min(n, v.responses.length - 1)]!;
650
+ const headers: Record<string, string> = { ...r.headers };
651
+ if (!Object.keys(headers).some((k) => k.toLowerCase() === "content-type")) {
652
+ headers["content-type"] = "application/json";
653
+ }
654
+ res.writeHead(r.status, headers);
655
+ res.end(r.body);
656
+ });
657
+ const a = adapter(s.url, { key: CONF_KEY });
658
+ let err: unknown;
659
+ if (v.stream) {
660
+ err = (await drain(a.stream(HI))).error;
661
+ } else {
662
+ err = await a.complete(HI).then(() => undefined, (e: unknown) => e);
663
+ }
664
+ if (err instanceof Error) {
665
+ expect(err.message).not.toContain(CONF_KEY);
666
+ expect(String(err.stack)).not.toContain(CONF_KEY);
667
+ expect(String((err as { cause?: Error }).cause?.message)).not.toContain(CONF_KEY);
668
+ }
669
+ const [kind, status] = errorKind(err);
670
+ expect(kind, String(err)).toBe(v.want_kind);
671
+ expect(status).toBe(v.want_status);
672
+ expect(err instanceof Error ? isFallbackable(err) : false).toBe(v.fallbackable);
673
+ expect(s.hits).toHaveLength(v.attempts);
674
+ });
675
+ }
676
+ });
677
+
678
+ describe("llm-v1 conformance: anthropic_limits", () => {
679
+ type V = {
680
+ name: string;
681
+ params: Record<string, string>;
682
+ stream: boolean;
683
+ content_type: string;
684
+ body: string;
685
+ too_large: boolean;
686
+ };
687
+ for (const v of section("anthropic_limits") as V[]) {
688
+ it(v.name, async () => {
689
+ strictKeys(v, ["name", "params", "stream", "content_type", "body", "too_large"], v.name);
690
+ const s = await server((_h, res) => reply(res, v.content_type, v.body));
691
+ const a = adapter(s.url, { params: v.params });
692
+ let err: unknown;
693
+ if (v.stream) err = (await drain(a.stream(HI))).error;
694
+ else err = await a.complete(HI).then(() => undefined, (e: unknown) => e);
695
+ if (v.too_large) {
696
+ expect(errorKind(err)[0], String(err)).toBe("too_large");
697
+ expect(s.hits, "an overrun is not retried").toHaveLength(1);
698
+ return;
699
+ }
700
+ expect(err).toBeUndefined();
701
+ });
702
+ }
703
+ });
704
+
705
+ describe("llm-v1 conformance: anthropic_response", () => {
706
+ type V = {
707
+ name: string;
708
+ tools: boolean;
709
+ body: string;
710
+ want: {
711
+ content: string;
712
+ thinking_blocks: { thinking: string; signature: string; redacted: string }[];
713
+ tool_calls: { id: string; name: string; input: unknown }[];
714
+ stop_reason: string;
715
+ usage: Record<string, number>;
716
+ };
717
+ };
718
+ for (const v of section("anthropic_response") as V[]) {
719
+ it(v.name, async () => {
720
+ strictKeys(v, ["name", "tools", "body", "want"], v.name);
721
+ const s = await server((_h, res) => reply(res, "application/json", v.body));
722
+ const a = adapter(s.url);
723
+ const got = v.tools
724
+ ? await a.callWithTools(HI, [{ name: "f", description: "", parameters: undefined }])
725
+ : { ...(await a.complete(HI)), toolCalls: [] as ToolCall[] };
726
+ expect(got.content).toBe(v.want.content);
727
+ expect(got.finishReason).toBe(v.want.stop_reason);
728
+ expect(got.thinking).toEqual(v.want.thinking_blocks);
729
+ expect(got.usage).toEqual({
730
+ promptTokens: v.want.usage["prompt_tokens"],
731
+ completionTokens: v.want.usage["completion_tokens"],
732
+ cacheReadTokens: v.want.usage["cache_read_tokens"],
733
+ cacheCreationTokens: v.want.usage["cache_creation_tokens"],
734
+ totalTokens: v.want.usage["total_tokens"],
735
+ });
736
+ expect(got.toolCalls.map((c) => ({ id: c.id, name: c.name, input: c.arguments }))).toEqual(
737
+ v.want.tool_calls
738
+ );
739
+ });
740
+ }
741
+ });
742
+
743
+ describe("llm-v1 conformance: anthropic_tool_names", () => {
744
+ type V = {
745
+ name: string;
746
+ call: "tools" | "stream_tools" | "complete" | "stream";
747
+ params?: Record<string, string>;
748
+ messages?: VMessage[];
749
+ tools?: string[];
750
+ body?: string;
751
+ want_tools?: string[];
752
+ want_history?: string[];
753
+ want_calls?: { id: string; name: string }[];
754
+ error?: { reason: string; name: string; other: string };
755
+ refused?: boolean;
756
+ };
757
+
758
+ function sentNames(body: string): { tools?: string[]; history?: string[] } {
759
+ const b = JSON.parse(body) as {
760
+ tools?: { name: string }[];
761
+ messages: { content: { type: string; name?: string }[] }[];
762
+ };
763
+ const history = b.messages.flatMap((m) =>
764
+ m.content.filter((c) => c.type === "tool_use").map((c) => c.name!)
765
+ );
766
+ return {
767
+ tools: b.tools?.map((t) => t.name),
768
+ history: history.length ? history : undefined,
769
+ };
770
+ }
771
+
772
+ for (const v of section("anthropic_tool_names") as V[]) {
773
+ it(v.name, async () => {
774
+ strictKeys(v, [
775
+ "name", "call", "params", "messages", "tools", "body", "want_tools",
776
+ "want_history", "want_calls", "error", "refused",
777
+ ], v.name);
778
+ const streaming = v.call === "stream" || v.call === "stream_tools";
779
+ const s = await server((_h, res) =>
780
+ reply(res, streaming ? "text/event-stream" : "application/json", v.body ?? "")
781
+ );
782
+ let a: AnthropicAdapter;
783
+ try {
784
+ a = adapter(s.url, { params: v.params });
785
+ } catch (e) {
786
+ expect(v.refused, String(e)).toBe(true);
787
+ return;
788
+ }
789
+ expect(v.refused ?? false).toBe(false);
790
+
791
+ const req: Request = v.messages ? toRequest({ messages: v.messages }) : HI;
792
+ const defs: ToolDef[] = (v.tools ?? []).map((name) => ({
793
+ name,
794
+ description: "",
795
+ parameters: undefined,
796
+ }));
797
+ let calls: ToolCall[] = [];
798
+ let err: unknown;
799
+ try {
800
+ switch (v.call) {
801
+ case "tools":
802
+ calls = (await a.callWithTools(req, defs)).toolCalls;
803
+ break;
804
+ case "stream_tools": {
805
+ const st = a.streamWithTools(req, defs);
806
+ const r = await drain(st);
807
+ if (r.error) throw r.error;
808
+ calls = st.outcome()!.toolCalls;
809
+ break;
810
+ }
811
+ case "complete":
812
+ await a.complete(req);
813
+ break;
814
+ case "stream": {
815
+ const r = await drain(a.stream(req));
816
+ if (r.error) throw r.error;
817
+ break;
818
+ }
819
+ }
820
+ } catch (e) {
821
+ err = e;
822
+ }
823
+
824
+ if (v.error) {
825
+ expect(err).toBeInstanceOf(ToolNameError);
826
+ const te = err as ToolNameError;
827
+ expect(te.reason).toBe(v.error.reason);
828
+ expect(te.toolName).toBe(v.error.name);
829
+ expect(te.other).toBe(v.error.other);
830
+ expect(isFallbackable(te)).toBe(false);
831
+ expect(s.hits, "a rejected request reaches no server").toHaveLength(0);
832
+ return;
833
+ }
834
+ expect(err).toBeUndefined();
835
+ const sent = sentNames(s.hits[0]!.body);
836
+ expect(sent.tools).toEqual(v.want_tools);
837
+ expect(sent.history).toEqual(v.want_history);
838
+ expect(calls.map((c) => ({ id: c.id, name: c.name }))).toEqual(v.want_calls ?? []);
839
+ });
840
+ }
841
+ });
842
+
843
+ // A complete, empty streamed turn.
844
+ const MINIMAL_SSE =
845
+ 'event: message_start\ndata: {"type":"message_start","message":{"id":"msg_1","type":"message","role":"assistant","content":[],"model":"m","stop_reason":null,"usage":{"input_tokens":1,"output_tokens":0}}}\n\n' +
846
+ 'event: message_stop\ndata: {"type":"message_stop"}\n\n';
847
+
848
+ const toolDefs = (names: string[]): ToolDef[] =>
849
+ names.map((name) => ({ name, description: "", parameters: undefined }));
850
+
851
+ describe("llm-v1 conformance: anthropic_tool_choice", () => {
852
+ type V = {
853
+ name: string;
854
+ call: "complete" | "stream" | "tools" | "stream_tools";
855
+ tools: string[];
856
+ tool_choice: { mode: string; name?: string } | null;
857
+ want_tool_choice?: unknown;
858
+ error?: string;
859
+ };
860
+ for (const v of section("anthropic_tool_choice") as V[]) {
861
+ it(v.name, async () => {
862
+ strictKeys(v, ["name", "call", "tools", "tool_choice", "want_tool_choice", "error"], v.name);
863
+ const streaming = v.call === "stream" || v.call === "stream_tools";
864
+ const s = await server((_h, res) =>
865
+ streaming ? reply(res, "text/event-stream", MINIMAL_SSE) : reply(res, "application/json", OK_MESSAGE)
866
+ );
867
+ const a = adapter(s.url);
868
+ const req: Request = { ...HI };
869
+ if (v.tool_choice) {
870
+ strictKeys(v.tool_choice, ["mode", "name"], v.name);
871
+ req.toolChoice = { mode: v.tool_choice.mode as ToolChoiceMode };
872
+ if (v.tool_choice.name !== undefined) req.toolChoice.name = v.tool_choice.name;
873
+ }
874
+ const tools = toolDefs(v.tools);
875
+ let err: unknown;
876
+ try {
877
+ switch (v.call) {
878
+ case "complete":
879
+ await a.complete(req);
880
+ break;
881
+ case "tools":
882
+ await a.callWithTools(req, tools);
883
+ break;
884
+ case "stream": {
885
+ const r = await drain(a.stream(req));
886
+ if (r.error) throw r.error;
887
+ break;
888
+ }
889
+ case "stream_tools": {
890
+ const r = await drain(a.streamWithTools(req, tools));
891
+ if (r.error) throw r.error;
892
+ break;
893
+ }
894
+ default:
895
+ throw new Error(`unknown call ${JSON.stringify(v.call)}`);
896
+ }
897
+ } catch (e) {
898
+ err = e;
899
+ }
900
+ if (v.error) {
901
+ expect(err).toBeInstanceOf(Error);
902
+ expect((err as Error).message).toBe(v.error);
903
+ expect(s.hits, "a rejected request is never sent").toHaveLength(0);
904
+ return;
905
+ }
906
+ expect(err).toBeUndefined();
907
+ const body = JSON.parse(s.hits[0]!.body) as { tool_choice?: unknown };
908
+ if (v.want_tool_choice === null || v.want_tool_choice === undefined) {
909
+ expect("tool_choice" in body, "no tool_choice sent").toBe(false);
910
+ return;
911
+ }
912
+ expect(body.tool_choice).toEqual(v.want_tool_choice);
913
+ });
914
+ }
915
+ });
916
+
917
+ describe("llm-v1 conformance: anthropic_hermetic", () => {
918
+ type V = {
919
+ name: string;
920
+ base_url: string;
921
+ yaml: string;
922
+ env: Record<string, string>;
923
+ want_host: string;
924
+ sent: string[];
925
+ withheld: string[];
926
+ };
927
+ for (const v of section("anthropic_hermetic") as V[]) {
928
+ it(v.name, async () => {
929
+ strictKeys(v, ["name", "base_url", "yaml", "env", "want_host", "sent", "withheld"], v.name);
930
+ // Written where llm.yaml is read; a hermetic adapter must not.
931
+ const xdg = mkdtempSync(join(tmpdir(), "kit-llm-hermetic-"));
932
+ const restore = isolateEnv(["XDG_CONFIG_HOME"]);
933
+ process.env["XDG_CONFIG_HOME"] = xdg;
934
+ if (v.yaml !== "") {
935
+ mkdirSync(join(xdg, "hop"), { recursive: true });
936
+ writeFileSync(join(xdg, "hop", "llm.yaml"), v.yaml);
937
+ }
938
+ Object.assign(process.env, v.env);
939
+ // Intercept fetch: the vectors name hosts no test may reach.
940
+ const sent: { url: string; headers: Headers }[] = [];
941
+ const orig = globalThis.fetch;
942
+ globalThis.fetch = (async (u: unknown, init?: RequestInit) => {
943
+ sent.push({ url: String(u), headers: new Headers(init?.headers) });
944
+ return new globalThis.Response(OK_MESSAGE, {
945
+ status: 200,
946
+ headers: { "content-type": "application/json" },
947
+ });
948
+ }) as typeof fetch;
949
+ try {
950
+ const a = new AnthropicAdapter({
951
+ uri: { scheme: "anthropic", model: "m" },
952
+ provider: { apiKey: "kit-key", baseURL: v.base_url || undefined, model: "m" },
953
+ fallbacks: [],
954
+ hermetic: true,
955
+ });
956
+ await a.complete(HI);
957
+ } finally {
958
+ globalThis.fetch = orig;
959
+ restore();
960
+ rmSync(xdg, { recursive: true, force: true });
961
+ }
962
+ expect(sent).toHaveLength(1);
963
+ expect(new URL(sent[0]!.url).host).toBe(v.want_host);
964
+ for (const h of v.sent) expect(sent[0]!.headers.get(h), h).toBeTruthy();
965
+ for (const h of v.withheld) expect(sent[0]!.headers.get(h), h).toBeNull();
966
+ });
967
+ }
968
+ });
969
+
970
+ function usageJSON(u: Usage): Record<string, number> {
971
+ return {
972
+ prompt_tokens: u.promptTokens,
973
+ completion_tokens: u.completionTokens,
974
+ cache_read_tokens: u.cacheReadTokens ?? 0,
975
+ cache_creation_tokens: u.cacheCreationTokens ?? 0,
976
+ total_tokens: u.totalTokens,
977
+ };
978
+ }
979
+
980
+ /** One streamed token as the vectors spell it. */
981
+ function eventJSON(t: Token): Record<string, unknown> {
982
+ if (t.done) return { type: "done" };
983
+ const ev = t.toolCall;
984
+ if (ev) {
985
+ const out: Record<string, unknown> = { type: "tool_call", kind: ev.kind, index: ev.index };
986
+ switch (ev.kind) {
987
+ case "start":
988
+ out["id"] = ev.id;
989
+ out["name"] = ev.name;
990
+ break;
991
+ case "delta":
992
+ out["arguments"] = ev.argumentsDelta;
993
+ break;
994
+ case "end":
995
+ expect(ev.call, "end carries the call").toBeDefined();
996
+ expect(ev.id, "end repeats the id").toBe(ev.call!.id);
997
+ expect(ev.name, "end repeats the name").toBe(ev.call!.name);
998
+ out["id"] = ev.call!.id;
999
+ out["name"] = ev.call!.name;
1000
+ out["arguments"] = ev.call!.arguments;
1001
+ break;
1002
+ }
1003
+ return out;
1004
+ }
1005
+ if (t.usage) return { type: "usage", usage: usageJSON(t.usage) };
1006
+ if (t.thinking) return { type: "thinking", thinking: t.thinking };
1007
+ return { type: "text", text: t.content };
1008
+ }
1009
+
1010
+ describe("llm-v1 conformance: anthropic_stream_events", () => {
1011
+ type V = {
1012
+ name: string;
1013
+ sse?: string;
1014
+ sse_from?: string;
1015
+ tools: string[];
1016
+ stream_events: boolean;
1017
+ want_events: unknown[];
1018
+ error_kind: string;
1019
+ };
1020
+ const streams = new Map(
1021
+ (section("anthropic_stream") as { name: string; sse: string }[]).map((s) => [
1022
+ `anthropic_stream/${s.name}`,
1023
+ s.sse,
1024
+ ])
1025
+ );
1026
+ for (const v of section("anthropic_stream_events") as V[]) {
1027
+ it(v.name, async () => {
1028
+ strictKeys(v, [
1029
+ "name", "sse", "sse_from", "tools", "stream_events", "want_events", "error_kind",
1030
+ ], v.name);
1031
+ const sse = v.sse_from ? streams.get(v.sse_from) : v.sse;
1032
+ expect(sse, `sse_from ${v.sse_from}`).toBeDefined();
1033
+ const s = await sseServer(sse!);
1034
+ const a = adapter(s.url);
1035
+ const req: Request = { ...HI, streamEvents: v.stream_events };
1036
+ const withTools = v.tools.length > 0;
1037
+ const st: ToolStream = withTools ? a.streamWithTools(req, toolDefs(v.tools)) : a.stream(req);
1038
+ const iter = st[Symbol.asyncIterator]();
1039
+ const got: unknown[] = [];
1040
+ const ends: { index: number; call: ToolCall }[] = [];
1041
+ let last: Usage | undefined;
1042
+ let err: unknown;
1043
+ try {
1044
+ for (;;) {
1045
+ const r = await iter.next();
1046
+ if (r.done) break;
1047
+ const t = r.value;
1048
+ got.push(eventJSON(t));
1049
+ if (t.toolCall?.kind === "end") ends.push({ index: t.toolCall.index, call: t.toolCall.call! });
1050
+ if (t.usage) last = t.usage;
1051
+ if (t.done) {
1052
+ expect((await iter.next()).done, "nothing follows done").toBe(true);
1053
+ break;
1054
+ }
1055
+ }
1056
+ } catch (e) {
1057
+ err = e;
1058
+ }
1059
+ expect(got).toEqual(v.want_events);
1060
+ expect(errorKind(err)[0], String(err)).toBe(v.error_kind);
1061
+ if (!withTools || err !== undefined) return;
1062
+ // The events and the outcome tell the same story.
1063
+ const out = st.outcome();
1064
+ expect(out).toBeDefined();
1065
+ if (v.stream_events) {
1066
+ expect(out!.toolCalls).toHaveLength(ends.length);
1067
+ for (const e of ends) expect(e.call, "end call is outcome.toolCalls[index]").toEqual(out!.toolCalls[e.index]);
1068
+ if (last) expect(out!.usage, "the last usage snapshot is the outcome's").toEqual(last);
1069
+ }
1070
+ });
1071
+ }
1072
+ });
1073
+
1074
+ describe("llm-v1 conformance: bus_request_started", () => {
1075
+ type V = {
1076
+ name: string;
1077
+ op: CallOp;
1078
+ tools: string[];
1079
+ request: VRequest;
1080
+ want_payload: unknown;
1081
+ };
1082
+ for (const v of section("bus_request_started") as V[]) {
1083
+ it(v.name, () => {
1084
+ strictKeys(v, ["name", "op", "tools", "request", "want_payload"], v.name);
1085
+ const got = requestStartedPayload(v.op, toRequest(v.request), v.tools.length);
1086
+ expect(JSON.parse(JSON.stringify(got))).toEqual(v.want_payload);
1087
+ });
1088
+ }
1089
+ });
1090
+
1091
+ describe("llm-v1 conformance: bus_response_received", () => {
1092
+ type V = {
1093
+ name: string;
1094
+ op: CallOp;
1095
+ response: {
1096
+ content: string;
1097
+ finish_reason: string;
1098
+ usage: Record<string, number>;
1099
+ thinking?: { thinking: string; signature: string }[];
1100
+ };
1101
+ tool_calls: { id: string; name: string; arguments: string }[];
1102
+ want_payload: Record<string, unknown>;
1103
+ };
1104
+ for (const v of section("bus_response_received") as V[]) {
1105
+ it(v.name, () => {
1106
+ strictKeys(v, ["name", "op", "response", "tool_calls", "want_payload"], v.name);
1107
+ const r = v.response;
1108
+ strictKeys(r, ["content", "finish_reason", "usage", "thinking"], v.name);
1109
+ const got = responseReceivedPayload(
1110
+ v.op,
1111
+ {
1112
+ content: r.content,
1113
+ role: "assistant",
1114
+ finishReason: r.finish_reason,
1115
+ usage: {
1116
+ promptTokens: r.usage["prompt_tokens"]!,
1117
+ completionTokens: r.usage["completion_tokens"]!,
1118
+ cacheReadTokens: r.usage["cache_read_tokens"]!,
1119
+ cacheCreationTokens: r.usage["cache_creation_tokens"]!,
1120
+ totalTokens: r.usage["total_tokens"]!,
1121
+ },
1122
+ thinking: (r.thinking ?? []).map((t) => ({ ...t, redacted: "" })),
1123
+ },
1124
+ v.tool_calls.map((c) => ({ id: c.id, name: c.name, arguments: c.arguments })),
1125
+ 12.7
1126
+ );
1127
+ const payload = JSON.parse(JSON.stringify(got)) as Record<string, unknown>;
1128
+ // duration_ms is a non-negative integer, not compared.
1129
+ expect(Number.isInteger(payload["duration_ms"])).toBe(true);
1130
+ expect(payload["duration_ms"] as number).toBeGreaterThanOrEqual(0);
1131
+ delete payload["duration_ms"];
1132
+ expect(payload).toEqual(v.want_payload);
1133
+ });
1134
+ }
1135
+ });