@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/README.md CHANGED
@@ -6,8 +6,8 @@ OpenCode plugin that routes model traffic through a [Bifrost](https://docs.getbi
6
6
 
7
7
  - Registers a `bifrost` provider on OpenCode's OpenAI-compatible surface.
8
8
  - Fetches the model list at startup through `gateway-cli models --wire=openai`, with per-model context/output limits and pricing already applied — no catalog is checked in, so a model added to the gateway appears without a local edit.
9
- - Seeds reasoning capability per model: catalog-flagged models are registered `reasoning: true` with one variant per effort value they accept, and the config cascade's default `reasoning_effort` is seeded as the model's `options.reasoningEffort` when the model accepts it. The static `gateway-cli emit opencode` block mirrors this.
10
- - Resolves the virtual key per project directory (`gateway-cli resolve` / `gateway-cli key print`), so two projects on different keys never collide in OpenCode's global auth store. Falls back to a credential stored via `opencode auth login` on machines without `gateway-cli`.
9
+ - Seeds reasoning capability per model: catalog-flagged models are registered `reasoning: true` with one variant per effort value they accept. The config cascade's default `reasoning_effort` is seeded as the model's default when the model accepts it — on OpenCode 1.x as `options.reasoningEffort`, on OpenCode 2 as model-level `settings.reasoningEffort` — and a variant picked in the model picker overrides it. The static `gateway-cli emit opencode` block mirrors this (`--v2` for the 2.x form).
10
+ - Resolves the virtual key per project directory (`gateway-cli resolve` / `gateway-cli key print`), so two projects on different keys never collide in OpenCode's global auth store. On OpenCode 1.x it falls back to a credential stored via `opencode auth login` on machines without `gateway-cli`; OpenCode 2 removed that hook, so there discovery requires the CLI.
11
11
 
12
12
  No secret is held by the plugin; the key is read at runtime.
13
13
 
@@ -20,10 +20,13 @@ want it, without restarting OpenCode. Two modes, chosen by what is available at
20
20
  the moment you run it:
21
21
 
22
22
  - **`gateway-cli` present** — runs `gateway-cli sync`, which reconciles the
23
- saved selection on disk, and prints its output. Once that turn ends, the
24
- plugin disposes the instance so the TUI re-bootstraps and the model picker
25
- re-reads the reconciled list (disposing mid-turn would cut the turn short).
26
- Since the list was re-registered, the report does not tell you to restart.
23
+ saved selection on disk, and prints its output. On OpenCode 1.x, once that
24
+ turn ends, the plugin disposes the instance so the TUI re-bootstraps and the
25
+ model picker re-reads the reconciled list (disposing mid-turn would cut the
26
+ turn short); OpenCode 2 exposes no dispose hook, so restart the service
27
+ (`opencode service stop`) to pick up a reconciled list. On 1.x the list
28
+ was re-registered, so the report does not tell you to restart; on
29
+ OpenCode 2 the report is `gateway-cli sync`'s own output.
27
30
  - **`gateway-cli` gone** (sandboxed machine) — asks
28
31
  `$BIFROST_DISCOVERY_URL` (or `$BIFROST_GATEWAY_URL`) `/v1/models` directly and
29
32
  reports what the gateway offers versus what this session registered: new ids,
@@ -31,8 +34,8 @@ the moment you run it:
31
34
  nothing is written**, here or anywhere else, and no instance is disposed; the
32
35
  text says to restart because this mode cannot re-register anything. The key
33
36
  comes from `$BIFROST_VK`, else the CLI's own
34
- `~/.config/bifrost/keys/default.env`, else the credential stored by
35
- `opencode auth login`.
37
+ `~/.config/bifrost/keys/default.env` (on OpenCode 1.x, else the credential
38
+ stored by `opencode auth login`).
36
39
 
37
40
  Either way the result arrives as a message part, never as an error: a failure
38
41
  prints one line. The virtual key is never printed or logged.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@stablekernel/opencode-bifrost",
3
- "version": "0.7.0",
4
- "description": "OpenCode plugin that routes models through the Bifrost gateway, resolving per-project virtual keys via gateway-cli.",
3
+ "version": "0.8.0",
4
+ "description": "OpenCode plugin that routes models through the Bifrost gateway, resolving per-project virtual keys via gateway-cli. Supports OpenCode 1.x and 2.x.",
5
5
  "type": "module",
6
6
  "main": "src/index.ts",
7
7
  "exports": {
@@ -0,0 +1,133 @@
1
+ import { expect, test } from "bun:test";
2
+ import { mkdtempSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { BifrostGateway } from "./index.js";
6
+
7
+ // Exercises the REAL ./datasheet.js (no mock.module): the supplement is
8
+ // env + fetch driven, so the test points GATEWAY_DATASHEET_URL at a stubbed
9
+ // fetch and HOME at a temp dir. This keeps the whole supplement path —
10
+ // datasheet.js through shared.ts's listCliModels — honest without
11
+ // rewriting module bindings, which leak across test files in one process.
12
+
13
+ const ORIGINAL_FETCH = globalThis.fetch;
14
+ const ORIGINAL_HOME = process.env.HOME;
15
+ const ORIGINAL_XDG_CACHE_HOME = process.env.XDG_CACHE_HOME;
16
+ const ORIGINAL_DATASHEET_URL = process.env.GATEWAY_DATASHEET_URL;
17
+
18
+ const EXTRA_FLASH = "glm-5p3-flash";
19
+
20
+ const RESOLUTION = {
21
+ env: "prod",
22
+ root: "/repo",
23
+ anthropic_base_url: "https://gw.example.com/anthropic",
24
+ openai_base_url: "https://gw.example.com/openai/v1",
25
+ has_key: true,
26
+ };
27
+
28
+ const SHELL: Record<string, string> = {
29
+ "resolve --json": JSON.stringify(RESOLUTION),
30
+ "key print": "sk-bf-projectkey\n",
31
+ "models --wire=openai": JSON.stringify({
32
+ wire: "openai-completions",
33
+ env: "prod",
34
+ models: [
35
+ {
36
+ id: "anthropic/claude-haiku-4-5-20251001",
37
+ name: "Claude Haiku 4.5",
38
+ context_window: 200000,
39
+ max_output_tokens: 64000,
40
+ cost: { input: 1, output: 5, cache_read: 0.1, cache_write: 1.25 },
41
+ limits_source: "gateway",
42
+ cost_source: "catalog",
43
+ },
44
+ {
45
+ id: "bedrock/amazon.nova-lite-v1:0",
46
+ name: "Nova Lite",
47
+ context_window: 300000,
48
+ max_output_tokens: 8192,
49
+ cost: { input: 0.06, output: 0.24, cache_read: 0.015, cache_write: 0 },
50
+ limits_source: "catalog",
51
+ cost_source: "catalog",
52
+ },
53
+ ],
54
+ }),
55
+ };
56
+
57
+ function fakeShell(responses: Record<string, string>) {
58
+ return (_strings: TemplateStringsArray, ...values: unknown[]) => {
59
+ const argv = (values[1] as string[]) ?? [];
60
+ const cmd = argv.join(" ");
61
+ const chain = {
62
+ cwd: () => chain,
63
+ quiet: () => chain,
64
+ text: async () => {
65
+ if (!(cmd in responses)) throw new Error(`command failed: ${cmd}`);
66
+ return responses[cmd];
67
+ },
68
+ };
69
+ return chain;
70
+ };
71
+ }
72
+
73
+ test("appends datasheet supplement ids to the bifrost provider's models map", async () => {
74
+ // Home holds no ~/.config/bifrost/datasheet.json, so the env override is
75
+ // the only activation; the cache dir under it is otherwise empty.
76
+ const home = mkdtempSync(join(tmpdir(), "gw-oc-ds-"));
77
+ process.env.HOME = home;
78
+ // datasheetCacheDir() checks XDG_CACHE_HOME before HOME, so pin it under
79
+ // the temp home too — otherwise CI/Linux reads and dirties the real cache.
80
+ process.env.XDG_CACHE_HOME = join(home, ".cache");
81
+ process.env.GATEWAY_DATASHEET_URL = "https://feed.example/datasheet";
82
+ // The stubbed feed answers immediately, so the supplement is active this run.
83
+ globalThis.fetch = (async () => ({
84
+ ok: true,
85
+ status: 200,
86
+ json: async () => ({
87
+ "fireworks_ai/glm-5p3-flash": {
88
+ mode: "chat",
89
+ base_model: "glm-5p3-flash",
90
+ max_input_tokens: 1048576,
91
+ max_output_tokens: 131072,
92
+ },
93
+ }),
94
+ })) as never;
95
+ try {
96
+ const hooks = await BifrostGateway({
97
+ directory: "/repo",
98
+ $: fakeShell(SHELL),
99
+ client: {
100
+ app: { log: async () => undefined },
101
+ instance: { dispose: async () => {} },
102
+ },
103
+ } as never);
104
+ const cfg = {
105
+ command: {},
106
+ provider: {},
107
+ } as unknown as {
108
+ command: Record<string, unknown>;
109
+ provider: Record<
110
+ string,
111
+ { models: Record<string, { limit: { context: number; output: number } }> }
112
+ >;
113
+ };
114
+ await hooks.config!(cfg as never);
115
+ const ids = Object.keys(cfg.provider.bifrost.models);
116
+ // The CLI's list survives; the supplemented id is appended alongside.
117
+ expect(ids).toContain("anthropic/claude-haiku-4-5-20251001");
118
+ expect(ids).toContain("bedrock/amazon.nova-lite-v1:0");
119
+ expect(ids).toContain(EXTRA_FLASH);
120
+ expect(cfg.provider.bifrost.models[EXTRA_FLASH]!.limit).toEqual({
121
+ context: 1048576,
122
+ output: 131072,
123
+ });
124
+ } finally {
125
+ globalThis.fetch = ORIGINAL_FETCH;
126
+ if (ORIGINAL_HOME === undefined) delete process.env.HOME;
127
+ else process.env.HOME = ORIGINAL_HOME;
128
+ if (ORIGINAL_XDG_CACHE_HOME === undefined) delete process.env.XDG_CACHE_HOME;
129
+ else process.env.XDG_CACHE_HOME = ORIGINAL_XDG_CACHE_HOME;
130
+ if (ORIGINAL_DATASHEET_URL === undefined) delete process.env.GATEWAY_DATASHEET_URL;
131
+ else process.env.GATEWAY_DATASHEET_URL = ORIGINAL_DATASHEET_URL;
132
+ }
133
+ });
package/src/index.test.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test";
1
+ import { afterEach, beforeEach, describe, expect, test } from "bun:test";
2
2
  import type { Hooks } from "@opencode-ai/plugin";
3
3
  import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
4
4
  import { tmpdir } from "node:os";
@@ -309,58 +309,6 @@ describe("config hook", () => {
309
309
  });
310
310
  });
311
311
 
312
- describe("datasheet supplement gate", () => {
313
- const EXTRA_FLASH = {
314
- id: "accounts/fireworks/models/glm-5p3-flash",
315
- name: "glm-5p3-flash",
316
- context_window: 1048576,
317
- max_output_tokens: 131072,
318
- limits_source: "datasheet",
319
- };
320
-
321
- test("appends supplement ids to the bifrost provider's models map", async () => {
322
- // The module under test is statically imported at the top of this file,
323
- // so register the ./datasheet.js mock and then re-import index.js fresh
324
- // (cache-busted) — the plugin's datasheetSupplement/mergeModels bindings
325
- // resolve to the mocks only in that new instance. mock.restore() in
326
- // finally keeps every other test on the real module.
327
- mock.module("./datasheet.js", () => ({
328
- datasheetSupplement: async () => [EXTRA_FLASH],
329
- // Same CLI-wins dedup as the real mergeModels, inlined to avoid a
330
- // circular import of the module under mock.
331
- mergeModels: (
332
- cli: Array<{ id: string }>,
333
- extra: Array<{ id: string }>,
334
- ) => {
335
- const seen = new Set(cli.map((m) => m.id));
336
- return [...cli, ...extra.filter((m) => !seen.has(m.id))];
337
- },
338
- }));
339
- try {
340
- const mod = (await import(
341
- `./index.js?${Math.random()}`
342
- )) as typeof import("./index.js");
343
- const hooks = await mod.BifrostGateway({
344
- directory: "/repo",
345
- $: fakeShell(OK_SHELL),
346
- } as never);
347
- const cfg = {} as TestConfig;
348
- await hooks.config!(cfg as never);
349
- const ids = Object.keys(cfg.provider.bifrost.models);
350
- // The CLI's list survives; the supplemented id is appended alongside.
351
- expect(ids).toContain("anthropic/claude-haiku-4-5-20251001");
352
- expect(ids).toContain("bedrock/amazon.nova-lite-v1:0");
353
- expect(ids).toContain(EXTRA_FLASH.id);
354
- expect(cfg.provider.bifrost.models[EXTRA_FLASH.id].limit).toEqual({
355
- context: 1048576,
356
- output: 131072,
357
- });
358
- } finally {
359
- mock.restore();
360
- }
361
- });
362
- });
363
-
364
312
  describe("image input", () => {
365
313
  test("declares image modalities + attachment when the CLI advertises it", () => {
366
314
  // OpenCode computes input.image and attachment from the config model and
package/src/index.ts CHANGED
@@ -1,46 +1,24 @@
1
1
  import type { Plugin } from "@opencode-ai/plugin";
2
- import { readFileSync } from "node:fs";
3
- import { homedir } from "node:os";
4
- import { datasheetSupplement, mergeModels } from "./datasheet.js";
2
+ import { REFRESH_COMMAND, refresh, refreshReport } from "./refresh.js";
5
3
  import {
6
- REFRESH_COMMAND,
7
- keyFileValue,
8
- refresh,
9
- refreshReport,
10
- } from "./refresh.js";
11
-
12
- /** Provider id registered with OpenCode. */
13
- const PROVIDER_ID = "bifrost";
14
-
15
- /** Overridable so a non-PATH install still works. */
16
- const CLI = process.env.GATEWAY_CLI_BIN ?? "gateway-cli";
17
-
18
- /**
19
- * Suffix for models nothing could price.
20
- *
21
- * The gateway reports no pricing, and the public catalog does not cover every
22
- * model it serves. Declaring a zero rate would render as "free", so the rate
23
- * card is omitted entirely and the name carries the caveat instead.
24
- */
25
- const UNPRICED_SUFFIX = " (pricing unknown)";
26
-
27
- /**
28
- * Non-secret wiring emitted by `gateway-cli resolve --json`. The virtual key
29
- * is deliberately absent: it is read separately via `gateway-cli key print`
30
- * so this payload can be logged.
31
- */
32
- type Resolution = {
33
- env: string;
34
- root: string;
35
- anthropic_base_url: string;
36
- openai_base_url: string;
37
- has_key: boolean;
38
- key_name?: string;
39
- key_source?: string;
40
- headers?: Record<string, string>;
41
- /** Resolved default reasoning effort (project over user), empty unset. */
42
- reasoning_effort?: string;
43
- };
4
+ CLI,
5
+ PROVIDER_ID,
6
+ UNPRICED_SUFFIX,
7
+ announceIfStale,
8
+ listCliModels,
9
+ readCliKey,
10
+ readKeyFile,
11
+ REFRESH_DESCRIPTION,
12
+ REFRESH_TEMPLATE,
13
+ resolveInfo,
14
+ type CliModels,
15
+ } from "./shared.js";
16
+ import { setupV2 } from "./v2.js";
17
+
18
+ // Re-exported: these moved to ./shared.js when the v2 plugin began sharing
19
+ // them, and this module stays the package's public surface.
20
+ export { isAllowedGatewayUrl, isStale } from "./shared.js";
21
+ export type { CliModel, CliModels } from "./shared.js";
44
22
 
45
23
  /** One entry in OpenCode's `provider` config map, as this plugin writes it. */
46
24
  type ProviderEntry = {
@@ -77,35 +55,6 @@ type ConfigModel = {
77
55
  options?: Record<string, unknown>;
78
56
  };
79
57
 
80
- /** One model as reported by `gateway-cli models`. */
81
- export type CliModel = {
82
- id: string;
83
- name: string;
84
- context_window: number;
85
- max_output_tokens: number;
86
- cost?: {
87
- input: number;
88
- output: number;
89
- cache_read: number;
90
- cache_write: number;
91
- };
92
- limits_source: string;
93
- cost_source?: string;
94
- /** True when the gateway lists the model but it rejects completion on
95
- * this key (not entitled, needs provisioned throughput, retired). */
96
- disabled?: boolean;
97
- /** Reasoning capability and applicable efforts, from the catalog. */
98
- reasoning?: boolean;
99
- reasoning_efforts?: string[];
100
- reasoning_budget_min?: number;
101
- /** True when the model accepts image content blocks (from the catalog's
102
- * modalities.input). Absent means text-only, so a harness never guesses a
103
- * capability from silence. */
104
- image_input?: boolean;
105
- };
106
-
107
- export type CliModels = { models?: CliModel[] };
108
-
109
58
  /**
110
59
  * Bifrost gateway provider for OpenCode.
111
60
  *
@@ -119,156 +68,12 @@ export type CliModels = { models?: CliModel[] };
119
68
  * the gateway live and fills in what the gateway does not report. Nothing is
120
69
  * written into the project and no catalog goes stale. Verified against
121
70
  * OpenCode 1.18.18: `provider.<id>.models` in config is the list that reaches
122
- * the picker. The v2 `provider.models` hook is not used because the v2
123
- * catalog is not active in this version.
124
- */
125
- /**
126
- * How long a "plugin is current" answer is trusted before the registry is
127
- * asked again. Kept on disk so the once-daily check costs nothing on the
128
- * frequent path (every opencode startup constructs this plugin).
129
- */
130
- const VERSION_CHECK_TTL_MS = 24 * 60 * 60 * 1000;
131
-
132
- /** npm registry endpoint for the published package's latest version. */
133
- const REGISTRY_URL =
134
- "https://registry.npmjs.org/@stablekernel/opencode-bifrost/latest";
135
-
136
- /** The version of this build, read from the package's own package.json. */
137
- function ownVersion(): string | null {
138
- try {
139
- const pkg = require("../package.json") as { version?: string };
140
- return pkg.version ?? null;
141
- } catch {
142
- return null;
143
- }
144
- }
145
-
146
- type VersionCheckCache = { checkedAt: number; latest: string };
147
-
148
- /** opencode's plugin cache root; matches where the host itself caches. */
149
- function versionCheckPath(): string | null {
150
- const home = process.env.HOME;
151
- if (!home) return null;
152
- const base = process.env.XDG_CACHE_HOME ?? `${home}/.cache`;
153
- return `${base}/opencode/bifrost-version-check.json`;
154
- }
155
-
156
- /** Where the datasheet feed cache lives; same base as the version check. */
157
- function datasheetCacheDir(): string | null {
158
- const home = process.env.HOME || homedir() || null;
159
- const base = process.env.XDG_CACHE_HOME ?? (home ? `${home}/.cache` : null);
160
- return base ? `${base}/opencode` : null;
161
- }
162
-
163
- /**
164
- * The virtual key from the CLI's own default key file. Only the CLI-less
165
- * refresh path reads it: normal provider registration never needs the key,
166
- * and the value stays in memory for the one request header that uses it.
167
- */
168
- function readKeyFile(): string | null {
169
- const home = process.env.HOME || homedir();
170
- const base =
171
- process.env.XDG_CONFIG_HOME ?? (home ? `${home}/.config` : null);
172
- if (!base) return null;
173
- try {
174
- const path = `${base}/bifrost/keys/default.env`;
175
- return keyFileValue(readFileSync(path, "utf8"));
176
- } catch {
177
- return null; // absent, unreadable, or not a key file
178
- }
179
- }
180
-
181
- /**
182
- * The latest published version, from a fresh-enough cache file when present
183
- * and the npm registry otherwise. Null means unknown — offline, timeout, or
184
- * an unreadable cache — and never warns.
185
- */
186
- async function latestPublishedVersion(): Promise<string | null> {
187
- const path = versionCheckPath();
188
- if (path) {
189
- try {
190
- const cached = JSON.parse(
191
- await Bun.file(path).text(),
192
- ) as VersionCheckCache;
193
- if (
194
- typeof cached.latest === "string" &&
195
- Date.now() - cached.checkedAt < VERSION_CHECK_TTL_MS
196
- ) {
197
- return cached.latest;
198
- }
199
- } catch {
200
- // Missing or corrupt cache: fall through to the registry.
201
- }
202
- }
203
- let latest: string | null = null;
204
- try {
205
- const res = await fetch(REGISTRY_URL, {
206
- signal: AbortSignal.timeout(1500),
207
- });
208
- if (res.ok) {
209
- const body = (await res.json()) as { version?: string };
210
- latest = typeof body.version === "string" ? body.version : null;
211
- }
212
- } catch {
213
- return null; // offline or slow registry: stay silent
214
- }
215
- if (latest && path) {
216
- try {
217
- const { mkdirSync, writeFileSync } = await import("node:fs");
218
- const { dirname } = await import("node:path");
219
- mkdirSync(dirname(path), { recursive: true });
220
- writeFileSync(
221
- path,
222
- JSON.stringify({
223
- checkedAt: Date.now(),
224
- latest,
225
- } satisfies VersionCheckCache),
226
- );
227
- } catch {
228
- // A failed cache write just means the next start asks again.
229
- }
230
- }
231
- return latest;
232
- }
233
-
234
- /**
235
- * Whether the installed build should warn about a newer release. Dev builds
236
- * ahead of the registry (installed > latest) are not stale.
237
- */
238
- export function isStale(installed: string, latest: string): boolean {
239
- if (installed === latest) return false;
240
- // Strict semver core only: parseInt would silently accept "0.3.0-dev" as
241
- // 0.3.0 and misjudge the comparison. Odd shapes (prereleases, two-part
242
- // versions) fall back to "warn on any difference" rather than a guess.
243
- const SEMVER = /^(\d+)\.(\d+)\.(\d+)$/;
244
- const a = SEMVER.exec(installed);
245
- const b = SEMVER.exec(latest);
246
- if (!a || !b) return true;
247
- for (let i = 1; i <= 3; i++) {
248
- const av = Number(a[i]);
249
- const bv = Number(b[i]);
250
- if (bv > av) return true;
251
- if (bv < av) return false;
252
- }
253
- return false;
254
- }
255
-
256
- /**
257
- * Report a newer published plugin exactly once per version via the host's
258
- * log. Fire-and-forget from the config hook: version drift must never block
259
- * or fail provider registration.
71
+ * the picker.
72
+ *
73
+ * This is the OpenCode 1.x path. OpenCode 2 removed the config and auth hooks
74
+ * this returns, so it registers through ./v2.ts instead; see the note on the
75
+ * default export below for how one package serves both.
260
76
  */
261
- async function announceIfStale(log: (message: string) => void): Promise<void> {
262
- const installed = ownVersion();
263
- if (!installed) return;
264
- const latest = await latestPublishedVersion();
265
- if (!latest || !isStale(installed, latest)) return;
266
- log(
267
- `opencode-bifrost ${latest} is available (installed ${installed}). ` +
268
- "Run `gateway-cli update` to refresh.",
269
- );
270
- }
271
-
272
77
  export const BifrostGateway: Plugin = async ({ client, directory, $ }) => {
273
78
  /** Ids the config hook registered; the known side of a refresh diff. */
274
79
  let registered: string[] = [];
@@ -292,44 +97,6 @@ export const BifrostGateway: Plugin = async ({ client, directory, $ }) => {
292
97
  }
293
98
  }
294
99
 
295
- async function resolve(): Promise<Resolution | null> {
296
- const raw = await cli(["resolve", "--json"]);
297
- if (!raw) return null;
298
- try {
299
- const parsed = JSON.parse(raw) as Resolution;
300
- // Allowlist the outbound origin before any derived URL is fetched.
301
- return isAllowedGatewayUrl(parsed.openai_base_url) ? parsed : null;
302
- } catch {
303
- return null;
304
- }
305
- }
306
-
307
- async function readKey(): Promise<string | null> {
308
- const key = await cli(["key", "print"]);
309
- return key && key.startsWith("sk-bf-") ? key : null;
310
- }
311
-
312
- // Model discovery goes through the CLI, so the key is never needed here —
313
- // only auth.loader below, which must hand it to the SDK, sees it.
314
- // The datasheet supplement adds wildcard-provider ids the CLI cannot list
315
- // yet (feed Bifrost itself syncs from); CLI-listed ids always win.
316
- // `directory` is the plugin's closure variable, not a parameter.
317
- async function listModels(): Promise<CliModels | null> {
318
- const raw = await cli(["models", "--wire=openai"]);
319
- if (!raw) return null;
320
- try {
321
- const payload = JSON.parse(raw) as CliModels;
322
- const cacheDir = datasheetCacheDir();
323
- if (cacheDir) {
324
- const extra = await datasheetSupplement(directory, cacheDir);
325
- payload.models = mergeModels(payload.models ?? [], extra);
326
- }
327
- return payload;
328
- } catch {
329
- return null;
330
- }
331
- }
332
-
333
100
  return {
334
101
  /**
335
102
  * Register the provider and its live model list. Runs at startup and
@@ -356,23 +123,21 @@ export const BifrostGateway: Plugin = async ({ client, directory, $ }) => {
356
123
  // The template only reaches the model if the command hook below cannot
357
124
  // inject its report.
358
125
  (cfg.command ??= {})[REFRESH_COMMAND] = {
359
- description:
360
- "Reconcile the Bifrost model list (gateway-cli sync), or list " +
361
- "the gateway directly when the CLI is missing",
362
- template:
363
- "Refresh the Bifrost model list: run `gateway-cli sync` if it is " +
364
- "installed, otherwise list the gateway's /v1/models directly, " +
365
- "and report what changed.",
126
+ description: REFRESH_DESCRIPTION,
127
+ template: REFRESH_TEMPLATE,
366
128
  };
367
129
 
368
- const info = await resolve();
130
+ const info = await resolveInfo(cli);
369
131
  if (!info) return;
370
132
 
371
133
  const providers = ((
372
134
  cfg as { provider?: Record<string, ProviderEntry> }
373
135
  ).provider ??= {});
374
136
  const existing: ProviderEntry = providers[PROVIDER_ID] ?? {};
375
- const models = toConfigModels(await listModels(), info.reasoning_effort);
137
+ const models = toConfigModels(
138
+ await listCliModels(cli, directory),
139
+ info.reasoning_effort,
140
+ );
376
141
  const merged = { ...models, ...(existing.models ?? {}) };
377
142
  // What this session is about to register; /bifrost-refresh diffs the
378
143
  // gateway's live listing against exactly this.
@@ -403,8 +168,8 @@ export const BifrostGateway: Plugin = async ({ client, directory, $ }) => {
403
168
  * `opencode auth login` for machines without gateway-cli.
404
169
  */
405
170
  loader: async (getAuth) => {
406
- const info = await resolve();
407
- let apiKey = await readKey();
171
+ const info = await resolveInfo(cli);
172
+ let apiKey = await readCliKey(cli);
408
173
  if (!apiKey) {
409
174
  const stored = await getAuth().catch(() => undefined);
410
175
  // OpenCode stores whatever was typed at the connect prompt with no
@@ -547,19 +312,23 @@ export function toConfigModels(
547
312
  * gateway development. Keeps a malformed or hostile config from redirecting
548
313
  * model discovery and the credential that goes with it.
549
314
  */
550
- export function isAllowedGatewayUrl(raw: string): boolean {
551
- let url: URL;
552
- try {
553
- url = new URL(raw);
554
- } catch {
555
- return false;
556
- }
557
- if (url.protocol === "https:") return true;
558
- const loopback =
559
- url.hostname === "localhost" ||
560
- url.hostname === "127.0.0.1" ||
561
- url.hostname === "::1";
562
- return url.protocol === "http:" && loopback;
563
- }
564
315
 
565
- export default BifrostGateway;
316
+ /**
317
+ * One default export serves both OpenCode majors, and neither side minds the
318
+ * other's key:
319
+ *
320
+ * - OpenCode 1.18+ reads `default` first. An object with `id` must carry a
321
+ * `server()` function, or the load throws; a bare function default would
322
+ * instead send it scanning every export as a plugin.
323
+ * - OpenCode 2 validates `default` as `{id, setup}` and drops unknown keys.
324
+ * A function is rejected even with `id` and `setup` attached.
325
+ *
326
+ * A `./server` subpath export does not separate them: both majors resolve it
327
+ * ahead of the package root. Verified against the 1.18.0, 1.18.18 and 2.0.14
328
+ * loaders, so do not "simplify" this to a single-shape export.
329
+ */
330
+ export default {
331
+ id: "bifrost-gateway",
332
+ server: BifrostGateway,
333
+ setup: setupV2,
334
+ };