@stablekernel/opencode-bifrost 0.7.0 → 0.8.0

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/src/v2.test.ts ADDED
@@ -0,0 +1,394 @@
1
+ import { afterEach, beforeEach, describe, expect, test } from "bun:test";
2
+ import plugin from "./index.js";
3
+ import { mkdtempSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { setupV2, toV2Models, type V2Model } from "./v2.js";
7
+ import { REFRESH_DESCRIPTION, type CliModel } from "./shared.js";
8
+
9
+ /** HOME as the suite found it, restored after each test. */
10
+ const ORIGINAL_HOME = process.env.HOME;
11
+
12
+ /** XDG_CACHE_HOME as the suite found it, restored after each test. */
13
+ const ORIGINAL_XDG_CACHE_HOME = process.env.XDG_CACHE_HOME;
14
+
15
+ /** GATEWAY_DATASHEET_URL as the suite found it, restored after each test. */
16
+ const ORIGINAL_DATASHEET_URL = process.env.GATEWAY_DATASHEET_URL;
17
+
18
+ /** BIFROST_GATEWAY_URL as the suite found it, restored after each test. */
19
+ const ORIGINAL_GATEWAY_URL = process.env.BIFROST_GATEWAY_URL;
20
+
21
+ /** BIFROST_DISCOVERY_URL as the suite found it, restored after each test. */
22
+ const ORIGINAL_DISCOVERY_URL = process.env.BIFROST_DISCOVERY_URL;
23
+
24
+ /** BIFROST_VK as the suite found it, restored after each test. */
25
+ const ORIGINAL_VK = process.env.BIFROST_VK;
26
+
27
+ /** XDG_CONFIG_HOME as the suite found it, restored after each test. */
28
+ const ORIGINAL_XDG_CONFIG_HOME = process.env.XDG_CONFIG_HOME;
29
+
30
+ beforeEach(() => {
31
+ // The setupV2 tests run the real listCliModels, which consults the real
32
+ // datasheet supplement. Keep it deterministic and machine-independent:
33
+ // point HOME and the cache root at an empty temp dir, so neither
34
+ // ~/.config/bifrost/datasheet.json nor a warm ~/.cache/opencode cache
35
+ // is read, and drop any feed override from the developer's shell.
36
+ delete process.env.GATEWAY_DATASHEET_URL;
37
+ delete process.env.XDG_CACHE_HOME;
38
+ // /bifrost-refresh reads its gateway and key from the environment; a real
39
+ // BIFROST_GATEWAY_URL in the developer's shell must not reach these tests.
40
+ delete process.env.BIFROST_GATEWAY_URL;
41
+ delete process.env.BIFROST_DISCOVERY_URL;
42
+ delete process.env.BIFROST_VK;
43
+ // The key-file lookup prefers XDG_CONFIG_HOME; CI sets it, a developer
44
+ // shell may too, and either would point those tests away from the temp
45
+ // HOME they just wrote a key into.
46
+ delete process.env.XDG_CONFIG_HOME;
47
+ process.env.HOME = mkdtempSync(join(tmpdir(), "gw-oc-home-"));
48
+ });
49
+
50
+ afterEach(() => {
51
+ if (ORIGINAL_HOME === undefined) delete process.env.HOME;
52
+ else process.env.HOME = ORIGINAL_HOME;
53
+ if (ORIGINAL_XDG_CACHE_HOME === undefined) delete process.env.XDG_CACHE_HOME;
54
+ else process.env.XDG_CACHE_HOME = ORIGINAL_XDG_CACHE_HOME;
55
+ if (ORIGINAL_DATASHEET_URL === undefined) delete process.env.GATEWAY_DATASHEET_URL;
56
+ else process.env.GATEWAY_DATASHEET_URL = ORIGINAL_DATASHEET_URL;
57
+ if (ORIGINAL_GATEWAY_URL === undefined) delete process.env.BIFROST_GATEWAY_URL;
58
+ else process.env.BIFROST_GATEWAY_URL = ORIGINAL_GATEWAY_URL;
59
+ if (ORIGINAL_DISCOVERY_URL === undefined) delete process.env.BIFROST_DISCOVERY_URL;
60
+ else process.env.BIFROST_DISCOVERY_URL = ORIGINAL_DISCOVERY_URL;
61
+ if (ORIGINAL_VK === undefined) delete process.env.BIFROST_VK;
62
+ else process.env.BIFROST_VK = ORIGINAL_VK;
63
+ if (ORIGINAL_XDG_CONFIG_HOME === undefined) delete process.env.XDG_CONFIG_HOME;
64
+ else process.env.XDG_CONFIG_HOME = ORIGINAL_XDG_CONFIG_HOME;
65
+ });
66
+
67
+ const NOVA: CliModel = {
68
+ id: "bedrock/amazon.nova-lite-v1:0",
69
+ name: "Nova Lite",
70
+ context_window: 300000,
71
+ max_output_tokens: 8192,
72
+ cost: { input: 0.06, output: 0.24, cache_read: 0.015, cache_write: 0 },
73
+ limits_source: "catalog",
74
+ cost_source: "catalog",
75
+ };
76
+
77
+ const UNPRICED: CliModel = {
78
+ id: "bedrock/deepseek.v3.1",
79
+ name: "deepseek.v3.1 (bedrock)",
80
+ context_window: 200000,
81
+ max_output_tokens: 4096,
82
+ limits_source: "floor",
83
+ };
84
+
85
+ const REASONING: CliModel = {
86
+ ...NOVA,
87
+ id: "anthropic/claude-opus-5",
88
+ name: "Claude Opus 5",
89
+ reasoning: true,
90
+ reasoning_efforts: ["low", "medium", "high"],
91
+ };
92
+
93
+ const byId = (models: ReturnType<typeof toV2Models>, id: string) =>
94
+ models.find((m) => m.id === id);
95
+
96
+ describe("the package default export", () => {
97
+ // OpenCode 2 rejects a function default and requires {id, setup}; OpenCode
98
+ // 1.18 requires an object default to carry server(). Losing either field
99
+ // silently unloads the plugin on that major.
100
+ test("is an object carrying id, server and setup", () => {
101
+ expect(typeof plugin).toBe("object");
102
+ expect(plugin.id).toBe("bifrost-gateway");
103
+ expect(typeof plugin.server).toBe("function");
104
+ expect(typeof plugin.setup).toBe("function");
105
+ });
106
+ });
107
+
108
+ describe("toV2Models", () => {
109
+ test("maps limits and ids onto the catalog shape", () => {
110
+ const m = byId(toV2Models({ models: [NOVA] }), NOVA.id)!;
111
+ expect(m.modelID).toBe(NOVA.id);
112
+ expect(m.providerID).toBe("bifrost");
113
+ expect(m.limit).toEqual({ context: 300000, output: 8192 });
114
+ expect(m.enabled).toBe(true);
115
+ expect(m.status).toBe("active");
116
+ });
117
+
118
+ test("carries pricing as a list, with cache rates nested", () => {
119
+ const m = byId(toV2Models({ models: [NOVA] }), NOVA.id)!;
120
+ expect(m.cost).toEqual([
121
+ { input: 0.06, output: 0.24, cache: { read: 0.015, write: 0 } },
122
+ ]);
123
+ });
124
+
125
+ test("omits the rate card for an unpriced model rather than zeroing it", () => {
126
+ const m = byId(toV2Models({ models: [UNPRICED] }), UNPRICED.id)!;
127
+ expect(m.cost).toEqual([]);
128
+ expect(m.name).toContain("pricing unknown");
129
+ });
130
+
131
+ test("leaves a priced model's name alone", () => {
132
+ expect(byId(toV2Models({ models: [NOVA] }), NOVA.id)!.name).toBe(
133
+ "Nova Lite",
134
+ );
135
+ });
136
+
137
+ test("omits models the CLI marks disabled", () => {
138
+ expect(toV2Models({ models: [{ ...NOVA, disabled: true }] })).toEqual([]);
139
+ });
140
+
141
+ test("tolerates an empty or absent model list", () => {
142
+ expect(toV2Models(null)).toEqual([]);
143
+ expect(toV2Models({})).toEqual([]);
144
+ expect(toV2Models({ models: [] })).toEqual([]);
145
+ });
146
+
147
+ test("declares image input only when the CLI reports it", () => {
148
+ const withImage = byId(
149
+ toV2Models({ models: [{ ...NOVA, image_input: true }] }),
150
+ NOVA.id,
151
+ )!;
152
+ expect(withImage.capabilities.input).toEqual(["text", "image"]);
153
+ const textOnly = byId(toV2Models({ models: [NOVA] }), NOVA.id)!;
154
+ expect(textOnly.capabilities.input).toEqual(["text"]);
155
+ });
156
+
157
+ test("turns reasoning efforts into a variant list", () => {
158
+ const m = byId(toV2Models({ models: [REASONING] }), REASONING.id)!;
159
+ expect(m.variants).toEqual([
160
+ { id: "low", settings: { reasoningEffort: "low" } },
161
+ { id: "medium", settings: { reasoningEffort: "medium" } },
162
+ { id: "high", settings: { reasoningEffort: "high" } },
163
+ ]);
164
+ });
165
+
166
+ test("offers no variants for a non-reasoning model", () => {
167
+ // The efforts field alone must not create variants: the CLI reports it
168
+ // from the catalog even where the model cannot reason.
169
+ const m = byId(
170
+ toV2Models({ models: [{ ...NOVA, reasoning_efforts: ["high"] }] }),
171
+ NOVA.id,
172
+ )!;
173
+ expect(m.variants).toEqual([]);
174
+ });
175
+
176
+ test("seeds the default effort as model settings when the model accepts it", () => {
177
+ const m = byId(toV2Models({ models: [REASONING] }, "medium"), REASONING.id)!;
178
+ expect(m.settings).toEqual({ reasoningEffort: "medium" });
179
+ });
180
+
181
+ test("seeds nothing when the default effort is unset or not accepted", () => {
182
+ expect(byId(toV2Models({ models: [REASONING] }), REASONING.id)!.settings).toBeUndefined();
183
+ expect(
184
+ byId(toV2Models({ models: [REASONING] }, "max"), REASONING.id)!.settings,
185
+ ).toBeUndefined();
186
+ // A non-reasoning model has no accepted efforts, so it never seeds.
187
+ expect(
188
+ byId(toV2Models({ models: [NOVA] }, "high"), NOVA.id)!.settings,
189
+ ).toBeUndefined();
190
+ });
191
+
192
+ test("reports an unknown release date as epoch instead of inventing one", () => {
193
+ expect(byId(toV2Models({ models: [NOVA] }), NOVA.id)!.time.released).toBe(0);
194
+ });
195
+
196
+ test("skips an entry with no id", () => {
197
+ expect(toV2Models({ models: [{ ...NOVA, id: "" }] })).toEqual([]);
198
+ });
199
+ });
200
+
201
+ /**
202
+ * Derived from setupV2's own signature so the test doubles can't drift from
203
+ * the structural types declared inside v2.ts.
204
+ */
205
+ type TestCtx = Parameters<typeof setupV2>[0];
206
+
207
+ /** One CLI call the fake exec recorded, split like the real argv. */
208
+ type CliCall = { argv: string[] };
209
+
210
+ function fakeCtx(cwd = "/repo") {
211
+ // Matches the published @opencode/plugin 2.x CommandDomain: a command is
212
+ // {name, description?, execute(input)} and the domain offers only
213
+ // list/transform/reload — there is no command hook.
214
+ const commands: Array<{
215
+ name: string;
216
+ description?: string;
217
+ execute: (input: {
218
+ sessionID: string;
219
+ prompt: { text: string };
220
+ delivery: string;
221
+ }) => Promise<void>;
222
+ }> = [];
223
+ const providers: Array<{
224
+ info: {
225
+ id: string;
226
+ name: string;
227
+ activation: string;
228
+ package: string;
229
+ headers?: Record<string, string>;
230
+ settings: { baseURL: string; apiKey: string };
231
+ };
232
+ models: V2Model[];
233
+ }> = [];
234
+ const synthetics: Array<{
235
+ sessionID: string;
236
+ text: string;
237
+ description?: string;
238
+ delivery?: string;
239
+ resume?: boolean;
240
+ }> = [];
241
+ const ctx: TestCtx = {
242
+ location: { directory: cwd },
243
+ command: {
244
+ transform: async (fn) =>
245
+ fn({
246
+ add: (entry) => {
247
+ commands.push(entry);
248
+ },
249
+ }),
250
+ },
251
+ provider: {
252
+ transform: async (fn) =>
253
+ fn({
254
+ add: (entry) => {
255
+ providers.push(entry);
256
+ },
257
+ }),
258
+ },
259
+ session: {
260
+ synthetic: async (input) => {
261
+ synthetics.push(input);
262
+ },
263
+ },
264
+ };
265
+ return { ctx, commands, providers, synthetics };
266
+ }
267
+
268
+ /**
269
+ * Fake `Exec`: answers the plugin's known subcommands and records every call
270
+ * in order, so tests can assert the CLI was invoked exactly once per query.
271
+ */
272
+ function fakeExec(responses: Record<string, string>, calls: CliCall[]) {
273
+ return async (args: string[]): Promise<string | null> => {
274
+ calls.push({ argv: args });
275
+ const cmd = args.join(" ");
276
+ if (!(cmd in responses)) return null;
277
+ return responses[cmd];
278
+ };
279
+ }
280
+
281
+ const V2_SHELL = {
282
+ "resolve --json": JSON.stringify({
283
+ env: "prod",
284
+ root: "/srv/bifrost",
285
+ anthropic_base_url: "https://gw.example.com/anthropic",
286
+ openai_base_url: "https://gw.example.com/openai/v1",
287
+ has_key: true,
288
+ reasoning_effort: "high",
289
+ }),
290
+ "key print": "sk-bf-v2key\n",
291
+ "models --wire=openai": JSON.stringify({
292
+ wire: "openai-completions",
293
+ env: "prod",
294
+ models: [NOVA, REASONING],
295
+ }),
296
+ sync: "reconciled 2 models",
297
+ };
298
+
299
+ describe("setupV2", () => {
300
+ test("registers the provider with the CLI-resolved id, key and models", async () => {
301
+ const { ctx, providers } = fakeCtx();
302
+ const calls: CliCall[] = [];
303
+ await setupV2(ctx, fakeExec(V2_SHELL, calls));
304
+ expect(providers).toHaveLength(1);
305
+ const added = providers[0]!;
306
+ expect(added.info.id).toBe("bifrost");
307
+ expect(added.info.name).toBe("Bifrost Gateway (prod)");
308
+ expect(added.info.settings.baseURL).toBe("https://gw.example.com/openai/v1");
309
+ expect(added.info.settings.apiKey).toBe("sk-bf-v2key");
310
+ expect(added.models.map((m) => m.id)).toEqual([NOVA.id, REASONING.id]);
311
+ // One exec per discovery query: resolve, key print, models.
312
+ expect(calls.map((c) => c.argv.join(" "))).toEqual([
313
+ "resolve --json",
314
+ "key print",
315
+ "models --wire=openai",
316
+ ]);
317
+ });
318
+
319
+ test("seeds the default effort on catalog models that accept it", async () => {
320
+ const { ctx, providers } = fakeCtx();
321
+ await setupV2(ctx, fakeExec(V2_SHELL, []));
322
+ const m = providers[0]!.models.find((m) => m.id === REASONING.id)!;
323
+ expect(m.settings).toEqual({ reasoningEffort: "high" });
324
+ // A variant's own settings still override the seeded default.
325
+ expect(m.variants).toContainEqual({ id: "low", settings: { reasoningEffort: "low" } });
326
+ // A model without reasoning capability seeds nothing.
327
+ const plain = providers[0]!.models.find((m) => m.id === NOVA.id)!;
328
+ expect(plain.settings).toBeUndefined();
329
+ });
330
+
331
+ test("puts the org routing headers at the provider's top level", async () => {
332
+ const { ctx, providers } = fakeCtx();
333
+ const shell = {
334
+ ...V2_SHELL,
335
+ "resolve --json": JSON.stringify({
336
+ ...JSON.parse(V2_SHELL["resolve --json"]),
337
+ headers: { "x-org-id": "acme" },
338
+ }),
339
+ };
340
+ await setupV2(ctx, fakeExec(shell, []));
341
+ const added = providers[0]!;
342
+ // 2.x reads request headers from Provider.Info.headers; anything under
343
+ // settings.headers is dropped before the request is built.
344
+ expect(added.info.headers).toEqual({ "x-org-id": "acme" });
345
+ expect(added.info.settings).not.toHaveProperty("headers");
346
+ });
347
+
348
+ test("registers the refresh command with an execute that delivers the report", async () => {
349
+ const { ctx, commands, synthetics } = fakeCtx();
350
+ await setupV2(ctx, fakeExec(V2_SHELL, []));
351
+ expect(commands).toHaveLength(1);
352
+ const command = commands[0]!;
353
+ expect(command.name).toBe("bifrost-refresh");
354
+ expect(command.description).toBe(REFRESH_DESCRIPTION);
355
+ expect(typeof command.execute).toBe("function");
356
+ await command.execute({
357
+ sessionID: "ses_test",
358
+ prompt: { text: "" },
359
+ delivery: "steer",
360
+ });
361
+ expect(synthetics).toHaveLength(1);
362
+ expect(synthetics[0]!.sessionID).toBe("ses_test");
363
+ // The CLI answered `sync`, so the report is the CLI's own output.
364
+ expect(synthetics[0]!.text).toContain("reconciled");
365
+ // The 2.x TUI and web timeline render only a synthetic's description, so
366
+ // the report must ride there, not the fixed command blurb.
367
+ expect(synthetics[0]!.description).toContain("reconciled");
368
+ // A report must not kick off a model turn.
369
+ expect(synthetics[0]!.resume).toBe(false);
370
+ });
371
+
372
+ test("reports a failed refresh as a synthetic message instead of throwing", async () => {
373
+ const { ctx, commands, synthetics } = fakeCtx();
374
+ await setupV2(ctx, async () => null);
375
+ const command = commands[0]!;
376
+ await command.execute({
377
+ sessionID: "ses_test",
378
+ prompt: { text: "" },
379
+ delivery: "steer",
380
+ });
381
+ expect(synthetics).toHaveLength(1);
382
+ // No CLI and no gateway env: the refresh itself reports the no-target
383
+ // state; the execute path must deliver it, not throw.
384
+ expect(synthetics[0]!.text).toContain("no gateway to ask");
385
+ });
386
+
387
+ test("registers nothing but the refresh command when the CLI is missing", async () => {
388
+ const { ctx, providers, commands } = fakeCtx();
389
+ await setupV2(ctx, async () => null);
390
+ expect(providers).toEqual([]);
391
+ // The refresh command is the no-CLI case's whole lifeline: it must exist.
392
+ expect(commands.map((c) => c.name)).toEqual(["bifrost-refresh"]);
393
+ });
394
+ });