@stablekernel/pi-bifrost 0.5.3 → 0.6.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 +27 -0
- package/package.json +1 -1
- package/src/index.ts +123 -1
- package/src/plugin.test.ts +153 -2
- package/src/refresh.test.ts +235 -0
- package/src/refresh.ts +294 -0
package/README.md
CHANGED
|
@@ -11,6 +11,29 @@ Pi extension that registers a [Bifrost](https://docs.getbifrost.ai) LLM gateway
|
|
|
11
11
|
- Seeds reasoning capability per model: catalog-flagged models register `reasoning: true`. On the OpenAI surface they also get a `thinkingLevelMap` translating pi's thinking levels to the model's effort values (unapplicable levels are hidden, never passed through by name) plus `supportsReasoningEffort`, so pi's per-request effort picker sends the provider's own values. On the Anthropic surface the capability is flagged and pi's Claude thinking handling applies. Toggle-only reasoning models get no effort map. The default effort itself is pi's own thinking-level default.
|
|
12
12
|
- Never holds the key: pi resolves it per request via the `!gateway-cli key print` command form, so the per-project key cascade (environment override → project → user default) applies on every turn.
|
|
13
13
|
|
|
14
|
+
## `/bifrost-refresh`
|
|
15
|
+
|
|
16
|
+
Reconciles the model list on demand, in pi and omp alike (one package, one
|
|
17
|
+
implementation, one command):
|
|
18
|
+
|
|
19
|
+
- **With `gateway-cli` on `PATH`** it runs `gateway-cli sync` — the same
|
|
20
|
+
reconcile as the background sync — and shows that command's own output. It
|
|
21
|
+
rewrites the saved selection and the harness configs on disk.
|
|
22
|
+
- **Without it** it asks the gateway directly: `$BIFROST_DISCOVERY_URL` (or
|
|
23
|
+
`$BIFROST_GATEWAY_URL`) with `$BIFROST_VK`, falling back to the key in
|
|
24
|
+
`~/.config/bifrost/keys/default.env`. It then reports how many models the
|
|
25
|
+
gateway offers and which are new or gone against the ids this session
|
|
26
|
+
registered. This mode reports only — it writes nothing, and the key is
|
|
27
|
+
never printed.
|
|
28
|
+
|
|
29
|
+
Either way the answer arrives as a notification, and any failure is one
|
|
30
|
+
readable line rather than an error thrown into the session.
|
|
31
|
+
|
|
32
|
+
**Restart the session to use a newly added model.** Pi and omp build a
|
|
33
|
+
provider's model list once, while the session starts, and neither can
|
|
34
|
+
re-register one to a running session — so the report names the new models and
|
|
35
|
+
says to restart, and nothing here fakes a reload.
|
|
36
|
+
|
|
14
37
|
## Datasheet supplement (off by default)
|
|
15
38
|
|
|
16
39
|
Wildcard-provider models — e.g. a fresh Fireworks launch that the CLI's
|
|
@@ -45,6 +68,10 @@ they are not forwarded into the registered shapes.
|
|
|
45
68
|
|
|
46
69
|
- `gateway-cli` on `PATH` (or the `GATEWAY_CLI_BIN` env var pointing at it), connected once with `gateway-cli connect`.
|
|
47
70
|
|
|
71
|
+
Without it nothing is registered — there is no credential to hand pi — but
|
|
72
|
+
`/bifrost-refresh` still reports the gateway's live list from the environment
|
|
73
|
+
(see above).
|
|
74
|
+
|
|
48
75
|
## Install
|
|
49
76
|
|
|
50
77
|
```sh
|
package/package.json
CHANGED
package/src/index.ts
CHANGED
|
@@ -1,6 +1,13 @@
|
|
|
1
|
-
import { execFileSync } from "node:child_process";
|
|
1
|
+
import { execFileSync, execFile, type ExecFileOptions } from "node:child_process";
|
|
2
|
+
import { readFileSync } from "node:fs";
|
|
2
3
|
import { homedir } from "node:os";
|
|
3
4
|
import { datasheetSupplement, mergeModels } from "./datasheet.js";
|
|
5
|
+
import {
|
|
6
|
+
REFRESH_COMMAND,
|
|
7
|
+
keyFileValue,
|
|
8
|
+
refresh,
|
|
9
|
+
refreshReport,
|
|
10
|
+
} from "./refresh.js";
|
|
4
11
|
|
|
5
12
|
/**
|
|
6
13
|
* Minimal structural type for the part of pi's ExtensionAPI this extension
|
|
@@ -14,6 +21,15 @@ import { datasheetSupplement, mergeModels } from "./datasheet.js";
|
|
|
14
21
|
* real object; only the call shape below needs to match.
|
|
15
22
|
*
|
|
16
23
|
* Shape per docs/custom-provider.md: pi.registerProvider(id, config).
|
|
24
|
+
*
|
|
25
|
+
* registerCommand is declared by both installed harnesses with the same call
|
|
26
|
+
* shape — pi `registerCommand(name, options: Omit<RegisteredCommand, "name" |
|
|
27
|
+
* "sourceInfo">)` (dist/core/extensions/types.d.ts:946) and omp
|
|
28
|
+
* `registerCommand(name, options)` (src/extensibility/extensions/types.ts:1363)
|
|
29
|
+
* — and both hand the handler a command context carrying `ui`
|
|
30
|
+
* (pi :254, omp :550), whose
|
|
31
|
+
* `notify(message: string, type?: "info" | "warning" | "error"): void`
|
|
32
|
+
* (pi :76, omp :279) is the only member this extension uses.
|
|
17
33
|
*/
|
|
18
34
|
type ProviderModelConfig = {
|
|
19
35
|
id: string;
|
|
@@ -56,6 +72,18 @@ type ProviderConfig = {
|
|
|
56
72
|
|
|
57
73
|
type ExtensionAPI = {
|
|
58
74
|
registerProvider(id: string, config: ProviderConfig): void;
|
|
75
|
+
registerCommand(name: string, options: CommandOptions): void;
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
/** What this extension passes to `registerCommand`; both harnesses accept it. */
|
|
79
|
+
type CommandOptions = {
|
|
80
|
+
description?: string;
|
|
81
|
+
handler: (args: string, ctx: CommandContext) => Promise<void>;
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
/** The part of the command context a handler gets: enough to say one thing. */
|
|
85
|
+
type CommandContext = {
|
|
86
|
+
ui: { notify(message: string, type?: "info" | "warning" | "error"): void };
|
|
59
87
|
};
|
|
60
88
|
|
|
61
89
|
/** Overridable so a non-PATH install still works. */
|
|
@@ -147,6 +175,20 @@ type WireSurface = {
|
|
|
147
175
|
* separately at request time via the `!command` apiKey form.
|
|
148
176
|
*/
|
|
149
177
|
export default async function (pi: ExtensionAPI): Promise<void> {
|
|
178
|
+
/** Ids this session registered; the live listing is diffed against them. */
|
|
179
|
+
const known: string[] = [];
|
|
180
|
+
|
|
181
|
+
// Registered before the provider check on purpose: the case this command
|
|
182
|
+
// exists for is the sandbox with no gateway-cli at all, where resolve()
|
|
183
|
+
// returns null and nothing else would be registered. That session has the
|
|
184
|
+
// fewest other ways to learn what the gateway offers.
|
|
185
|
+
pi.registerCommand(REFRESH_COMMAND, {
|
|
186
|
+
description:
|
|
187
|
+
"Reconcile the Bifrost model list (gateway-cli sync), or list the " +
|
|
188
|
+
"gateway directly when the CLI is missing",
|
|
189
|
+
handler: refreshHandler(known),
|
|
190
|
+
});
|
|
191
|
+
|
|
150
192
|
const info = resolve();
|
|
151
193
|
if (!info) {
|
|
152
194
|
// gateway-cli absent or project not configured: register nothing rather
|
|
@@ -174,6 +216,7 @@ export default async function (pi: ExtensionAPI): Promise<void> {
|
|
|
174
216
|
for (const surface of surfaces) {
|
|
175
217
|
const models = await listModels(surface, info.root);
|
|
176
218
|
if (models.length === 0) continue;
|
|
219
|
+
for (const model of models) known.push(model.id);
|
|
177
220
|
|
|
178
221
|
pi.registerProvider(surface.id, {
|
|
179
222
|
baseUrl: surface.baseUrl,
|
|
@@ -199,6 +242,46 @@ export default async function (pi: ExtensionAPI): Promise<void> {
|
|
|
199
242
|
}
|
|
200
243
|
}
|
|
201
244
|
|
|
245
|
+
/**
|
|
246
|
+
* The `/bifrost-refresh` handler: one `ui.notify` line, whatever happens.
|
|
247
|
+
*
|
|
248
|
+
* `known` is the live array the session filled while registering providers —
|
|
249
|
+
* read at command time, so a command run during a slow startup sees whatever
|
|
250
|
+
* had registered by then rather than a snapshot taken before it.
|
|
251
|
+
*
|
|
252
|
+
* `engine` is the test seam. `refresh()` already contains every failure it
|
|
253
|
+
* expects (no CLI, no key, no answer); the guard is for the one it does not,
|
|
254
|
+
* because a slash command must never be the thing that throws into a session.
|
|
255
|
+
*/
|
|
256
|
+
export function refreshHandler(
|
|
257
|
+
known: string[],
|
|
258
|
+
engine: typeof refresh = refresh,
|
|
259
|
+
): (args: string, ctx: CommandContext) => Promise<void> {
|
|
260
|
+
return async (_args, ctx) => {
|
|
261
|
+
let text: string;
|
|
262
|
+
try {
|
|
263
|
+
const result = await engine({
|
|
264
|
+
known,
|
|
265
|
+
// `gateway-cli sync` reconciles the saved selection and rewrites the
|
|
266
|
+
// launched harnesses; null (no binary, non-zero exit, timeout) hands
|
|
267
|
+
// the command to refresh()'s direct-fetch path. runAsync, not run: a
|
|
268
|
+
// slash command must not freeze the TUI while the gateway answers.
|
|
269
|
+
exec: async (args) => runAsync(args),
|
|
270
|
+
// The direct-fetch path's last credential resort, the same file
|
|
271
|
+
// `gateway-cli key print` reads.
|
|
272
|
+
readKeyFile: cliKeyFile,
|
|
273
|
+
env: process.env,
|
|
274
|
+
});
|
|
275
|
+
// Not `applied`: nothing here re-registers the provider list, so the
|
|
276
|
+
// report is the only thing telling the user to restart.
|
|
277
|
+
text = refreshReport(result);
|
|
278
|
+
} catch (err) {
|
|
279
|
+
text = `bifrost models: ${err instanceof Error ? err.message : String(err)}`;
|
|
280
|
+
}
|
|
281
|
+
ctx.ui.notify(text, "info");
|
|
282
|
+
};
|
|
283
|
+
}
|
|
284
|
+
|
|
202
285
|
/**
|
|
203
286
|
* Ask the CLI for one wire's models, already enriched.
|
|
204
287
|
*
|
|
@@ -356,6 +439,25 @@ export function isAllowedGatewayUrl(raw: string): boolean {
|
|
|
356
439
|
return url.protocol === "http:" && loopback;
|
|
357
440
|
}
|
|
358
441
|
|
|
442
|
+
/**
|
|
443
|
+
* The CLI's own user default key file, read by the refresh command only when
|
|
444
|
+
* the environment carries no `BIFROST_VK`. `~/.config/bifrost/keys/default.env`
|
|
445
|
+
* (XDG_CONFIG_HOME honored, as the CLI honors it) — the sandbox this command
|
|
446
|
+
* serves has no per-project key to resolve, and the file is read here rather
|
|
447
|
+
* than by shelling out to `key print`, which is exactly what is missing.
|
|
448
|
+
*/
|
|
449
|
+
function cliKeyFile(): string | null {
|
|
450
|
+
try {
|
|
451
|
+
const home = process.env.HOME || homedir();
|
|
452
|
+
const base = process.env.XDG_CONFIG_HOME ?? `${home}/.config`;
|
|
453
|
+
return keyFileValue(
|
|
454
|
+
readFileSync(`${base}/bifrost/keys/default.env`, "utf8"),
|
|
455
|
+
);
|
|
456
|
+
} catch {
|
|
457
|
+
return null; // absent or unreadable: the report says "no virtual key"
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
|
|
359
461
|
function run(args: string[]): string | null {
|
|
360
462
|
try {
|
|
361
463
|
return execFileSync(CLI, args, {
|
|
@@ -369,3 +471,23 @@ function run(args: string[]): string | null {
|
|
|
369
471
|
return null;
|
|
370
472
|
}
|
|
371
473
|
}
|
|
474
|
+
|
|
475
|
+
// runAsync is run() for the interactive /bifrost-refresh path: a sync on the
|
|
476
|
+
// event loop would freeze the TUI (input, rendering, notifications) for the
|
|
477
|
+
// duration of a gateway reconcile, which takes seconds. Same contract; the
|
|
478
|
+
// promise never rejects.
|
|
479
|
+
async function runAsync(args: string[]): Promise<string | null> {
|
|
480
|
+
const { promise, resolve } = Promise.withResolvers<string | null>();
|
|
481
|
+
execFile(
|
|
482
|
+
CLI,
|
|
483
|
+
args,
|
|
484
|
+
{
|
|
485
|
+
encoding: "utf8",
|
|
486
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
487
|
+
timeout: 30_000,
|
|
488
|
+
maxBuffer: 8 << 20,
|
|
489
|
+
} as ExecFileOptions,
|
|
490
|
+
(error, stdout) => resolve(error ? null : (stdout as string).trim()),
|
|
491
|
+
);
|
|
492
|
+
return promise;
|
|
493
|
+
}
|
package/src/plugin.test.ts
CHANGED
|
@@ -71,6 +71,20 @@ function mockCLI(responses: Record<string, string>) {
|
|
|
71
71
|
if (!(cmd in responses)) throw new Error(`command failed: ${cmd}`);
|
|
72
72
|
return responses[cmd];
|
|
73
73
|
},
|
|
74
|
+
execFile: (
|
|
75
|
+
_bin: string,
|
|
76
|
+
args: string[],
|
|
77
|
+
_opts: unknown,
|
|
78
|
+
callback: (error: Error | null, stdout: string, stderr: string) => void,
|
|
79
|
+
) => {
|
|
80
|
+
const cmd = args.join(" ");
|
|
81
|
+
calls.push(cmd);
|
|
82
|
+
if (!(cmd in responses)) {
|
|
83
|
+
callback(new Error(`command failed: ${cmd}`), "", "");
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
callback(null, responses[cmd], "");
|
|
87
|
+
},
|
|
74
88
|
}));
|
|
75
89
|
return calls;
|
|
76
90
|
}
|
|
@@ -83,21 +97,45 @@ const OK_CLI = {
|
|
|
83
97
|
|
|
84
98
|
type Registered = { id: string; config: any };
|
|
85
99
|
|
|
86
|
-
|
|
100
|
+
type Command = {
|
|
101
|
+
name: string;
|
|
102
|
+
description?: string;
|
|
103
|
+
handler: (args: string, ctx: unknown) => Promise<void>;
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
/** Everything the extension handed the harness while loading. */
|
|
107
|
+
type Harness = { registered: Registered[]; commands: Command[] };
|
|
108
|
+
|
|
109
|
+
async function runHarness(): Promise<Harness> {
|
|
87
110
|
const registered: Registered[] = [];
|
|
111
|
+
const commands: Command[] = [];
|
|
88
112
|
const pi = {
|
|
89
113
|
registerProvider: (id: string, config: any) =>
|
|
90
114
|
registered.push({ id, config }),
|
|
115
|
+
registerCommand: (name: string, options: Omit<Command, "name">) =>
|
|
116
|
+
commands.push({ name, ...options }),
|
|
91
117
|
};
|
|
92
118
|
// Fresh import each time so the mocked module is picked up.
|
|
93
119
|
const mod = await import(`./index.js?${Math.random()}`);
|
|
94
120
|
await mod.default(pi as never);
|
|
95
|
-
return registered;
|
|
121
|
+
return { registered, commands };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
async function runExtension(): Promise<Registered[]> {
|
|
125
|
+
return (await runHarness()).registered;
|
|
96
126
|
}
|
|
97
127
|
|
|
98
128
|
/** HOME as the suite found it, restored after each test. */
|
|
99
129
|
const ORIGINAL_HOME = process.env.HOME;
|
|
100
130
|
|
|
131
|
+
/** fetch as the suite found it, restored after each test. */
|
|
132
|
+
const ORIGINAL_FETCH = globalThis.fetch;
|
|
133
|
+
|
|
134
|
+
/** Env the refresh command reads; cleared so a developer's own cannot leak in. */
|
|
135
|
+
const REFRESH_ENV = ["BIFROST_GATEWAY_URL", "BIFROST_DISCOVERY_URL", "BIFROST_VK"];
|
|
136
|
+
const ORIGINAL_ENV: Record<string, string | undefined> = {};
|
|
137
|
+
for (const name of REFRESH_ENV) ORIGINAL_ENV[name] = process.env[name];
|
|
138
|
+
|
|
101
139
|
beforeEach(() => {
|
|
102
140
|
// Registration tests run the real datasheetSupplement. Keep it
|
|
103
141
|
// deterministic and machine-independent: drop the env override and point
|
|
@@ -105,10 +143,18 @@ beforeEach(() => {
|
|
|
105
143
|
// nor the real ~/.cache/gateway-bifrost cache is read or written.
|
|
106
144
|
delete process.env.GATEWAY_DATASHEET_URL;
|
|
107
145
|
process.env.HOME = mkdtempSync(join(tmpdir(), "gw-home-"));
|
|
146
|
+
// The CLI-less refresh path reads these; the tests that need them set them.
|
|
147
|
+
for (const name of REFRESH_ENV) delete process.env[name];
|
|
108
148
|
});
|
|
109
149
|
|
|
110
150
|
afterEach(() => {
|
|
111
151
|
mock.restore();
|
|
152
|
+
globalThis.fetch = ORIGINAL_FETCH;
|
|
153
|
+
for (const name of REFRESH_ENV) {
|
|
154
|
+
const value = ORIGINAL_ENV[name];
|
|
155
|
+
if (value === undefined) delete process.env[name];
|
|
156
|
+
else process.env[name] = value;
|
|
157
|
+
}
|
|
112
158
|
if (ORIGINAL_HOME === undefined) delete process.env.HOME;
|
|
113
159
|
else process.env.HOME = ORIGINAL_HOME;
|
|
114
160
|
});
|
|
@@ -352,6 +398,29 @@ describe("image input", () => {
|
|
|
352
398
|
const [model] = toPiModels({ models: [NOVA] }, "openai-completions");
|
|
353
399
|
expect(model?.input).toEqual(["text"]);
|
|
354
400
|
});
|
|
401
|
+
|
|
402
|
+
test("declares image input for the reported vision route from a gap-filled payload", async () => {
|
|
403
|
+
// Regression for #55: a selection served without image_input left pi
|
|
404
|
+
// text-only and it stripped images for a genuinely multimodal model. The
|
|
405
|
+
// CLI gap-fills the flag from the catalog; the mapping must honor it.
|
|
406
|
+
const { toPiModels } = await import("./index.js");
|
|
407
|
+
const [model] = toPiModels(
|
|
408
|
+
{
|
|
409
|
+
models: [
|
|
410
|
+
{
|
|
411
|
+
id: "fireworks/deepseek-v4.1-flash",
|
|
412
|
+
name: "DeepSeek V4.1 Flash",
|
|
413
|
+
context_window: 1048576,
|
|
414
|
+
max_output_tokens: 393216,
|
|
415
|
+
limits_source: "catalog",
|
|
416
|
+
image_input: true,
|
|
417
|
+
},
|
|
418
|
+
],
|
|
419
|
+
},
|
|
420
|
+
"openai-completions",
|
|
421
|
+
);
|
|
422
|
+
expect(model?.input).toEqual(["text", "image"]);
|
|
423
|
+
});
|
|
355
424
|
});
|
|
356
425
|
|
|
357
426
|
describe("reasoning", () => {
|
|
@@ -473,3 +542,85 @@ describe("gateway URL allowlist", () => {
|
|
|
473
542
|
expect(await runExtension()).toEqual([]);
|
|
474
543
|
});
|
|
475
544
|
});
|
|
545
|
+
|
|
546
|
+
describe("bifrost-refresh command", () => {
|
|
547
|
+
/** Collect what a command handler puts in front of the user. */
|
|
548
|
+
function recorder() {
|
|
549
|
+
const printed: string[] = [];
|
|
550
|
+
const ctx = {
|
|
551
|
+
ui: { notify: (message: string) => printed.push(message) },
|
|
552
|
+
};
|
|
553
|
+
return { printed, ctx };
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
const SYNC_OUTPUT =
|
|
557
|
+
"model selection updated (openai): added 1 new model(s): new-one\n";
|
|
558
|
+
|
|
559
|
+
test("registers once, with a description, even when no provider could be", async () => {
|
|
560
|
+
// No gateway-cli at all: the sandbox the command exists for. Nothing is
|
|
561
|
+
// registered to point at the gateway, so the command is the only way to
|
|
562
|
+
// learn what it offers.
|
|
563
|
+
mockCLI({});
|
|
564
|
+
const { registered, commands } = await runHarness();
|
|
565
|
+
expect(registered).toEqual([]);
|
|
566
|
+
expect(commands.length).toBe(1);
|
|
567
|
+
expect(commands[0].name).toBe("bifrost-refresh");
|
|
568
|
+
expect(commands[0].description).toBeTruthy();
|
|
569
|
+
});
|
|
570
|
+
|
|
571
|
+
test("prints the CLI's own sync output when the CLI answers", async () => {
|
|
572
|
+
mockCLI({ ...OK_CLI, sync: SYNC_OUTPUT });
|
|
573
|
+
const { commands } = await runHarness();
|
|
574
|
+
const { printed, ctx } = recorder();
|
|
575
|
+
await commands[0].handler("", ctx);
|
|
576
|
+
expect(printed).toEqual([
|
|
577
|
+
"model selection updated (openai): added 1 new model(s): new-one",
|
|
578
|
+
]);
|
|
579
|
+
});
|
|
580
|
+
|
|
581
|
+
test("without the CLI it asks the gateway and diffs this session", async () => {
|
|
582
|
+
// No `sync` key in the map: the call fails, as a missing binary would.
|
|
583
|
+
// The Anthropic wire only, so nothing here depends on the datasheet
|
|
584
|
+
// supplement (whose module mock an earlier test leaves registered).
|
|
585
|
+
mockCLI({
|
|
586
|
+
"resolve --json": JSON.stringify(RESOLUTION),
|
|
587
|
+
"models --wire=anthropic --all": cliPayload([HAIKU]),
|
|
588
|
+
});
|
|
589
|
+
process.env.BIFROST_GATEWAY_URL = "https://gw.example";
|
|
590
|
+
process.env.BIFROST_VK = "sk-bf-testkey";
|
|
591
|
+
const fetchCalls: string[] = [];
|
|
592
|
+
globalThis.fetch = (async (url: string | URL) => {
|
|
593
|
+
fetchCalls.push(String(url));
|
|
594
|
+
return {
|
|
595
|
+
ok: true,
|
|
596
|
+
status: 200,
|
|
597
|
+
json: async () => ({ data: [{ id: "brand-new" }] }),
|
|
598
|
+
};
|
|
599
|
+
}) as unknown as typeof fetch;
|
|
600
|
+
|
|
601
|
+
const { commands } = await runHarness();
|
|
602
|
+
const { printed, ctx } = recorder();
|
|
603
|
+
await commands[0].handler("", ctx);
|
|
604
|
+
|
|
605
|
+
expect(fetchCalls).toEqual(["https://gw.example/v1/models"]);
|
|
606
|
+
// HAIKU is what this session registered, so the diff can only be right
|
|
607
|
+
// if the handler handed refresh() the ids the provider loop collected.
|
|
608
|
+
expect(printed[0]).toBe(
|
|
609
|
+
[
|
|
610
|
+
"bifrost models: 1 offered by the gateway.",
|
|
611
|
+
"New since this session started: brand-new — restart to use them.",
|
|
612
|
+
`No longer offered: ${HAIKU.id}`,
|
|
613
|
+
].join("\n"),
|
|
614
|
+
);
|
|
615
|
+
});
|
|
616
|
+
|
|
617
|
+
test("a throwing path still prints one line and does not reject", async () => {
|
|
618
|
+
const { refreshHandler } = await import("./index.js");
|
|
619
|
+
const { printed, ctx } = recorder();
|
|
620
|
+
const handler = refreshHandler([], async () => {
|
|
621
|
+
throw new Error("sync exploded");
|
|
622
|
+
});
|
|
623
|
+
await handler("", ctx);
|
|
624
|
+
expect(printed).toEqual(["bifrost models: sync exploded"]);
|
|
625
|
+
});
|
|
626
|
+
});
|
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test";
|
|
2
|
+
import {
|
|
3
|
+
diffModels,
|
|
4
|
+
gatewayFromEnv,
|
|
5
|
+
keyFileValue,
|
|
6
|
+
liveModelIds,
|
|
7
|
+
refresh,
|
|
8
|
+
refreshReport,
|
|
9
|
+
type FetchLike,
|
|
10
|
+
} from "./refresh.js";
|
|
11
|
+
|
|
12
|
+
const KEY = "sk-bf-testkey";
|
|
13
|
+
|
|
14
|
+
/** A fetch stub that records calls and answers with the given body. */
|
|
15
|
+
function stubFetch(body: unknown, ok = true) {
|
|
16
|
+
const calls: { url: string; headers?: Record<string, string> }[] = [];
|
|
17
|
+
const fetchImpl: FetchLike = async (url, init) => {
|
|
18
|
+
calls.push({ url, headers: init?.headers });
|
|
19
|
+
return { ok, status: ok ? 200 : 403, json: async () => body };
|
|
20
|
+
};
|
|
21
|
+
return { fetchImpl, calls };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
describe("gatewayFromEnv", () => {
|
|
25
|
+
test("prefers the discovery host and takes only a virtual key", () => {
|
|
26
|
+
expect(
|
|
27
|
+
gatewayFromEnv({
|
|
28
|
+
BIFROST_DISCOVERY_URL: "https://discovery.example/",
|
|
29
|
+
BIFROST_GATEWAY_URL: "https://traffic.example",
|
|
30
|
+
BIFROST_VK: KEY,
|
|
31
|
+
}),
|
|
32
|
+
).toEqual({ baseUrl: "https://discovery.example", apiKey: KEY });
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
test("falls back to the traffic host and reports a missing key as null", () => {
|
|
36
|
+
expect(gatewayFromEnv({ BIFROST_GATEWAY_URL: "https://gw.example" })).toEqual({
|
|
37
|
+
baseUrl: "https://gw.example",
|
|
38
|
+
apiKey: null,
|
|
39
|
+
});
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
test("a non-key value never becomes an Authorization header", () => {
|
|
43
|
+
const target = gatewayFromEnv({ BIFROST_GATEWAY_URL: "https://gw.example", BIFROST_VK: "hunter2" });
|
|
44
|
+
expect(target?.apiKey).toBeNull();
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
test("plain HTTP is allowed for loopback only", () => {
|
|
48
|
+
expect(gatewayFromEnv({ BIFROST_GATEWAY_URL: "http://127.0.0.1:8080" })?.baseUrl).toBe(
|
|
49
|
+
"http://127.0.0.1:8080",
|
|
50
|
+
);
|
|
51
|
+
expect(gatewayFromEnv({ BIFROST_GATEWAY_URL: "http://gw.example" })).toBeNull();
|
|
52
|
+
expect(gatewayFromEnv({ BIFROST_GATEWAY_URL: "not a url" })).toBeNull();
|
|
53
|
+
expect(gatewayFromEnv({})).toBeNull();
|
|
54
|
+
});
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
describe("keyFileValue", () => {
|
|
58
|
+
test("reads the CLI's export line and nothing else", () => {
|
|
59
|
+
expect(keyFileValue(`# comment\nrequire_x=1\nexport BIFROST_VK=${KEY}\n`)).toBe(KEY);
|
|
60
|
+
expect(keyFileValue(`export BIFROST_VK="sk-bf-quoted"\n`)).toBe("sk-bf-quoted");
|
|
61
|
+
expect(keyFileValue("export OTHER_VK=sk-bf-nope\n")).toBeNull();
|
|
62
|
+
expect(keyFileValue("export BIFROST_VK=\n")).toBeNull();
|
|
63
|
+
expect(keyFileValue("export BIFROST_VK=not-a-vk\n")).toBeNull();
|
|
64
|
+
});
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
describe("liveModelIds and diffModels", () => {
|
|
68
|
+
test("ids come from a data array and junk is ignored", () => {
|
|
69
|
+
expect(liveModelIds({ data: [{ id: "a" }, { id: 7 }, {}, "x"] })).toEqual(["a"]);
|
|
70
|
+
expect(liveModelIds(null)).toEqual([]);
|
|
71
|
+
expect(liveModelIds({ data: "no" })).toEqual([]);
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
test("diff is membership, both directions, sorted", () => {
|
|
75
|
+
expect(diffModels(["a", "gone"], ["a", "new2", "new1"])).toEqual({
|
|
76
|
+
added: ["new1", "new2"],
|
|
77
|
+
removed: ["gone"],
|
|
78
|
+
});
|
|
79
|
+
});
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
describe("refresh", () => {
|
|
83
|
+
test("the CLI wins when it answers, and no request is made", async () => {
|
|
84
|
+
const { fetchImpl, calls } = stubFetch({});
|
|
85
|
+
const result = await refresh({
|
|
86
|
+
known: ["a"],
|
|
87
|
+
exec: async () => "model selection updated (openai): added 1 new model(s): b",
|
|
88
|
+
fetchImpl,
|
|
89
|
+
env: { BIFROST_GATEWAY_URL: "https://gw.example", BIFROST_VK: KEY },
|
|
90
|
+
});
|
|
91
|
+
expect(result.source).toBe("cli");
|
|
92
|
+
expect(result.cliOutput).toContain("added 1 new model(s)");
|
|
93
|
+
expect(calls).toHaveLength(0);
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
test("without the CLI it lists the gateway directly and diffs the session", async () => {
|
|
97
|
+
const { fetchImpl, calls } = stubFetch({ data: [{ id: "a" }, { id: "b" }] });
|
|
98
|
+
const result = await refresh({
|
|
99
|
+
known: ["a", "old"],
|
|
100
|
+
exec: async () => null,
|
|
101
|
+
fetchImpl,
|
|
102
|
+
env: { BIFROST_GATEWAY_URL: "https://gw.example", BIFROST_VK: KEY },
|
|
103
|
+
});
|
|
104
|
+
expect(result).toEqual({
|
|
105
|
+
source: "gateway",
|
|
106
|
+
live: ["a", "b"],
|
|
107
|
+
added: ["b"],
|
|
108
|
+
removed: ["old"],
|
|
109
|
+
knownCount: 2,
|
|
110
|
+
});
|
|
111
|
+
expect(calls[0]?.url).toBe("https://gw.example/v1/models");
|
|
112
|
+
expect(calls[0]?.headers?.Authorization).toBe(`Bearer ${KEY}`);
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
test("a key file stands in for the environment key", async () => {
|
|
116
|
+
const { fetchImpl } = stubFetch({ data: [{ id: "a" }] });
|
|
117
|
+
const result = await refresh({
|
|
118
|
+
known: ["a"],
|
|
119
|
+
exec: async () => null,
|
|
120
|
+
readKeyFile: () => KEY,
|
|
121
|
+
fetchImpl,
|
|
122
|
+
env: { BIFROST_GATEWAY_URL: "https://gw.example" },
|
|
123
|
+
});
|
|
124
|
+
expect(result.error).toBeUndefined();
|
|
125
|
+
expect(result.live).toEqual(["a"]);
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
test("says what is missing instead of failing silently", async () => {
|
|
129
|
+
const noUrl = await refresh({ known: [], exec: async () => null, env: {} });
|
|
130
|
+
expect(noUrl.error).toContain("BIFROST_GATEWAY_URL");
|
|
131
|
+
|
|
132
|
+
const noKey = await refresh({
|
|
133
|
+
known: [],
|
|
134
|
+
exec: async () => null,
|
|
135
|
+
env: { BIFROST_GATEWAY_URL: "https://gw.example" },
|
|
136
|
+
});
|
|
137
|
+
expect(noKey.error).toContain("BIFROST_VK");
|
|
138
|
+
|
|
139
|
+
const { fetchImpl } = stubFetch({}, false);
|
|
140
|
+
const rejected = await refresh({
|
|
141
|
+
known: [],
|
|
142
|
+
exec: async () => null,
|
|
143
|
+
fetchImpl,
|
|
144
|
+
env: { BIFROST_GATEWAY_URL: "https://gw.example", BIFROST_VK: KEY },
|
|
145
|
+
});
|
|
146
|
+
expect(rejected.error).toContain("could not list models");
|
|
147
|
+
});
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
describe("refreshReport", () => {
|
|
151
|
+
test("the CLI's own output is the report", () => {
|
|
152
|
+
expect(
|
|
153
|
+
refreshReport({
|
|
154
|
+
source: "cli",
|
|
155
|
+
live: [],
|
|
156
|
+
added: [],
|
|
157
|
+
removed: [],
|
|
158
|
+
knownCount: 1,
|
|
159
|
+
cliOutput: "done\n",
|
|
160
|
+
}),
|
|
161
|
+
).toBe("done");
|
|
162
|
+
expect(
|
|
163
|
+
refreshReport({
|
|
164
|
+
source: "cli",
|
|
165
|
+
live: [],
|
|
166
|
+
added: [],
|
|
167
|
+
removed: [],
|
|
168
|
+
knownCount: 1,
|
|
169
|
+
cliOutput: " ",
|
|
170
|
+
}),
|
|
171
|
+
).toContain("nothing to change");
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
test("errors and diffs read as one line each", () => {
|
|
175
|
+
expect(
|
|
176
|
+
refreshReport({
|
|
177
|
+
source: "gateway",
|
|
178
|
+
live: [],
|
|
179
|
+
added: [],
|
|
180
|
+
removed: [],
|
|
181
|
+
knownCount: 0,
|
|
182
|
+
error: "no virtual key",
|
|
183
|
+
}),
|
|
184
|
+
).toBe("bifrost models: no virtual key");
|
|
185
|
+
|
|
186
|
+
const added = refreshReport({
|
|
187
|
+
source: "gateway",
|
|
188
|
+
live: ["a", "b"],
|
|
189
|
+
added: ["b"],
|
|
190
|
+
removed: [],
|
|
191
|
+
knownCount: 1,
|
|
192
|
+
});
|
|
193
|
+
expect(added).toContain("2 offered by the gateway");
|
|
194
|
+
expect(added).toContain("restart to use them");
|
|
195
|
+
|
|
196
|
+
const applied = refreshReport(
|
|
197
|
+
{ source: "gateway", live: ["a", "b"], added: ["b"], removed: [], knownCount: 1 },
|
|
198
|
+
true,
|
|
199
|
+
);
|
|
200
|
+
expect(applied).toContain("Added this session: b");
|
|
201
|
+
expect(applied).not.toContain("restart");
|
|
202
|
+
|
|
203
|
+
expect(
|
|
204
|
+
refreshReport({ source: "gateway", live: ["a"], added: [], removed: [], knownCount: 1 }),
|
|
205
|
+
).toContain("current");
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
test("a session with nothing registered is not told every model is new", () => {
|
|
209
|
+
const report = refreshReport({
|
|
210
|
+
source: "gateway",
|
|
211
|
+
live: ["a", "b", "c"],
|
|
212
|
+
added: ["a", "b", "c"],
|
|
213
|
+
removed: [],
|
|
214
|
+
knownCount: 0,
|
|
215
|
+
});
|
|
216
|
+
expect(report).toContain("None registered in this session");
|
|
217
|
+
expect(report).not.toContain("New since this session started");
|
|
218
|
+
// The offered ids are the only listing a sandbox user gets.
|
|
219
|
+
expect(report).toContain("offered by the gateway: a, b, c");
|
|
220
|
+
});
|
|
221
|
+
|
|
222
|
+
test("a long list is capped so one notification stays readable", () => {
|
|
223
|
+
const ids = Array.from({ length: 11 }, (_, i) => `m${i}`);
|
|
224
|
+
const report = refreshReport({
|
|
225
|
+
source: "gateway",
|
|
226
|
+
live: ids,
|
|
227
|
+
added: ids,
|
|
228
|
+
removed: [],
|
|
229
|
+
knownCount: 1,
|
|
230
|
+
});
|
|
231
|
+
expect(report).toContain("(+3 more)");
|
|
232
|
+
expect(report).toContain("m7");
|
|
233
|
+
expect(report).not.toContain("m8");
|
|
234
|
+
});
|
|
235
|
+
});
|
package/src/refresh.ts
ADDED
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared engine for the `/bifrost-refresh` slash command: run the gateway CLI
|
|
3
|
+
* when it is installed, otherwise ask the gateway directly.
|
|
4
|
+
*
|
|
5
|
+
* The CLI stays the one implementation of model *enrichment* — limits,
|
|
6
|
+
* pricing, availability probes, the curated selection — and the one that
|
|
7
|
+
* persists anything. This module exists for the sandbox case the command was
|
|
8
|
+
* asked for: no binary on PATH, so the command lists what the gateway offers
|
|
9
|
+
* by reading `$BIFROST_GATEWAY_URL` / `$BIFROST_VK` (or the CLI's own key
|
|
10
|
+
* file) and reports the difference against the models this session
|
|
11
|
+
* registered. Nothing here writes config, and the key never leaves the
|
|
12
|
+
* request header.
|
|
13
|
+
*
|
|
14
|
+
* Byte-identical in packages/pi-bifrost and packages/opencode-bifrost;
|
|
15
|
+
* `make check-refresh-sync` fails the build if they drift.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
/** The subcommand name both harnesses register. */
|
|
19
|
+
export const REFRESH_COMMAND = "bifrost-refresh";
|
|
20
|
+
|
|
21
|
+
/** Which path answered: the CLI (it also reconciled), or a direct fetch. */
|
|
22
|
+
export type RefreshSource = "cli" | "gateway";
|
|
23
|
+
|
|
24
|
+
/** One refresh's outcome, ready to render. */
|
|
25
|
+
export type RefreshResult = {
|
|
26
|
+
source: RefreshSource;
|
|
27
|
+
/** Ids the gateway offers right now; empty when neither path answered. */
|
|
28
|
+
live: string[];
|
|
29
|
+
/** Live ids this session does not have — a restart or re-register shows them. */
|
|
30
|
+
added: string[];
|
|
31
|
+
/** Session ids the gateway no longer lists. */
|
|
32
|
+
removed: string[];
|
|
33
|
+
/** How many models this session had registered, to word the report. */
|
|
34
|
+
knownCount: number;
|
|
35
|
+
/** The CLI's own output, when it ran. */
|
|
36
|
+
cliOutput?: string;
|
|
37
|
+
/** Why nothing could be fetched; only set when live is empty. */
|
|
38
|
+
error?: string;
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
/** Runs `<cli> <args>` in the project directory; null when it is unavailable. */
|
|
42
|
+
export type Exec = (args: string[]) => Promise<string | null>;
|
|
43
|
+
|
|
44
|
+
/** Narrow fetch shape, injectable so tests need no network. */
|
|
45
|
+
export type FetchLike = (
|
|
46
|
+
url: string,
|
|
47
|
+
init?: { headers?: Record<string, string>; signal?: AbortSignal },
|
|
48
|
+
) => Promise<{ ok: boolean; status?: number; json(): Promise<unknown> }>;
|
|
49
|
+
|
|
50
|
+
/** The gateway coordinates a CLI-less refresh needs. */
|
|
51
|
+
export type GatewayTarget = { baseUrl: string; apiKey: string | null };
|
|
52
|
+
|
|
53
|
+
/** The virtual-key variable the CLI exports; both harnesses read it too. */
|
|
54
|
+
export const KEY_ENV = "BIFROST_VK";
|
|
55
|
+
|
|
56
|
+
/** Gateway host override, matching gateway-cli's own variable. */
|
|
57
|
+
export const URL_ENV = "BIFROST_GATEWAY_URL";
|
|
58
|
+
|
|
59
|
+
/** Discovery host override, for a proxy that does not serve /v1/models. */
|
|
60
|
+
export const DISCOVERY_ENV = "BIFROST_DISCOVERY_URL";
|
|
61
|
+
|
|
62
|
+
/** The `/v1/models` path, same surface `gateway-cli models` reads. */
|
|
63
|
+
const MODELS_PATH = "/v1/models";
|
|
64
|
+
|
|
65
|
+
/** Bounds the direct fetch so the command never hangs a session. */
|
|
66
|
+
const FETCH_TIMEOUT_MS = 5000;
|
|
67
|
+
|
|
68
|
+
/** Matches the CLI's own key-file line (`export BIFROST_VK=sk-bf-…`). */
|
|
69
|
+
const KEY_LINE = new RegExp(`^export\\s+${KEY_ENV}\\s*=\\s*(.+)$`);
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Pull the key out of a CLI key file (`export BIFROST_VK=sk-bf-…`). Anything
|
|
73
|
+
* unrecognized — another variable, a comment, a truncated line, a value that
|
|
74
|
+
* is not a virtual key — is null, so a stray file can never supply a
|
|
75
|
+
* non-key to a request header.
|
|
76
|
+
*/
|
|
77
|
+
export function keyFileValue(text: string): string | null {
|
|
78
|
+
for (const line of text.split("\n")) {
|
|
79
|
+
const match = KEY_LINE.exec(line.trim());
|
|
80
|
+
if (!match) continue;
|
|
81
|
+
const value = match[1].trim().replace(/^["']|["']$/g, "");
|
|
82
|
+
return value.startsWith("sk-bf-") ? value : null;
|
|
83
|
+
}
|
|
84
|
+
return null;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Resolve the gateway from environment alone: the discovery host (or the
|
|
89
|
+
* traffic host) plus the key. The URL is required — a harness package cannot
|
|
90
|
+
* know which deployment this project targets, and guessing a host would send
|
|
91
|
+
* a real key somewhere unintended. A missing key still returns a target, so
|
|
92
|
+
* the caller can report "no key" instead of "no gateway".
|
|
93
|
+
*/
|
|
94
|
+
export function gatewayFromEnv(
|
|
95
|
+
env: Record<string, string | undefined>,
|
|
96
|
+
): GatewayTarget | null {
|
|
97
|
+
const baseUrl = env[DISCOVERY_ENV] || env[URL_ENV];
|
|
98
|
+
if (!baseUrl) return null;
|
|
99
|
+
let url: URL;
|
|
100
|
+
try {
|
|
101
|
+
url = new URL(baseUrl);
|
|
102
|
+
} catch {
|
|
103
|
+
return null;
|
|
104
|
+
}
|
|
105
|
+
const loopback =
|
|
106
|
+
url.hostname === "localhost" ||
|
|
107
|
+
url.hostname === "127.0.0.1" ||
|
|
108
|
+
url.hostname === "::1";
|
|
109
|
+
if (url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) {
|
|
110
|
+
return null;
|
|
111
|
+
}
|
|
112
|
+
const apiKey = env[KEY_ENV]?.startsWith("sk-bf-") ? env[KEY_ENV]! : null;
|
|
113
|
+
return { baseUrl: baseUrl.replace(/\/+$/, ""), apiKey };
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Ids from a `/v1/models` body, tolerating anything unexpected. */
|
|
117
|
+
export function liveModelIds(payload: unknown): string[] {
|
|
118
|
+
const data = (payload as { data?: unknown } | null)?.data;
|
|
119
|
+
if (!Array.isArray(data)) return [];
|
|
120
|
+
const ids: string[] = [];
|
|
121
|
+
for (const entry of data) {
|
|
122
|
+
const id = (entry as { id?: unknown } | null)?.id;
|
|
123
|
+
if (typeof id === "string" && id.length > 0) ids.push(id);
|
|
124
|
+
}
|
|
125
|
+
return ids;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Diff the live listing against the ids this session registered. Membership
|
|
130
|
+
* is exact: an id prefix (BIFROST_MODEL_PREFIX) is the caller's business, so
|
|
131
|
+
* both sides must be compared in the same spelling.
|
|
132
|
+
*/
|
|
133
|
+
export function diffModels(
|
|
134
|
+
known: string[],
|
|
135
|
+
live: string[],
|
|
136
|
+
): { added: string[]; removed: string[] } {
|
|
137
|
+
const have = new Set(known);
|
|
138
|
+
const now = new Set(live);
|
|
139
|
+
return {
|
|
140
|
+
added: live.filter((id) => !have.has(id)).sort(),
|
|
141
|
+
removed: known.filter((id) => !now.has(id)).sort(),
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Fetch the live listing with the given key; null on any failure. */
|
|
146
|
+
async function fetchLive(
|
|
147
|
+
target: GatewayTarget,
|
|
148
|
+
apiKey: string,
|
|
149
|
+
fetchImpl: FetchLike,
|
|
150
|
+
): Promise<string[] | null> {
|
|
151
|
+
try {
|
|
152
|
+
const res = await fetchImpl(`${target.baseUrl}${MODELS_PATH}`, {
|
|
153
|
+
headers: { Authorization: `Bearer ${apiKey}` },
|
|
154
|
+
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
|
|
155
|
+
});
|
|
156
|
+
if (!res.ok) return null;
|
|
157
|
+
return liveModelIds(await res.json());
|
|
158
|
+
} catch {
|
|
159
|
+
return null;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Run one refresh.
|
|
165
|
+
*
|
|
166
|
+
* The CLI wins whenever it answers: `sync` reconciles the saved selection and
|
|
167
|
+
* rewrites launched harnesses, which a direct listing cannot do. Only when it
|
|
168
|
+
* is missing or fails does the gateway get asked directly, and then the
|
|
169
|
+
* result is a report — nothing is persisted.
|
|
170
|
+
*/
|
|
171
|
+
export async function refresh(opts: {
|
|
172
|
+
/** Ids this session registered (already in the client's spelling). */
|
|
173
|
+
known: string[];
|
|
174
|
+
/** Runs the CLI; null means "not installed here". */
|
|
175
|
+
exec: Exec;
|
|
176
|
+
/** Reads the CLI's key file, when the environment has no key. */
|
|
177
|
+
readKeyFile?: () => string | null;
|
|
178
|
+
/** A harness-stored credential (OpenCode's auth store); last resort. */
|
|
179
|
+
storedKey?: () => Promise<string | null>;
|
|
180
|
+
fetchImpl?: FetchLike;
|
|
181
|
+
env?: Record<string, string | undefined>;
|
|
182
|
+
}): Promise<RefreshResult> {
|
|
183
|
+
const knownCount = opts.known.length;
|
|
184
|
+
const cliOutput = await opts.exec(["sync"]);
|
|
185
|
+
if (cliOutput !== null) {
|
|
186
|
+
// The CLI reconciled on disk; what it printed is the whole story unless
|
|
187
|
+
// the caller wants to know what the session itself is missing.
|
|
188
|
+
return { source: "cli", live: [], added: [], removed: [], knownCount, cliOutput };
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const env = opts.env ?? {};
|
|
192
|
+
const target = gatewayFromEnv(env);
|
|
193
|
+
if (!target) {
|
|
194
|
+
return {
|
|
195
|
+
source: "gateway",
|
|
196
|
+
live: [],
|
|
197
|
+
added: [],
|
|
198
|
+
removed: [],
|
|
199
|
+
knownCount,
|
|
200
|
+
error: `no gateway to ask: set ${URL_ENV} (and ${KEY_ENV}) or install gateway-cli`,
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
const apiKey =
|
|
204
|
+
target.apiKey ??
|
|
205
|
+
opts.readKeyFile?.() ??
|
|
206
|
+
(await opts.storedKey?.().catch(() => null)) ??
|
|
207
|
+
null;
|
|
208
|
+
if (!apiKey) {
|
|
209
|
+
return {
|
|
210
|
+
source: "gateway",
|
|
211
|
+
live: [],
|
|
212
|
+
added: [],
|
|
213
|
+
removed: [],
|
|
214
|
+
knownCount,
|
|
215
|
+
error: `no virtual key: set ${KEY_ENV}, store one with gateway-cli, or install gateway-cli`,
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
const live = await fetchLive(target, apiKey, opts.fetchImpl ?? defaultFetch);
|
|
219
|
+
if (live === null) {
|
|
220
|
+
return {
|
|
221
|
+
source: "gateway",
|
|
222
|
+
live: [],
|
|
223
|
+
added: [],
|
|
224
|
+
removed: [],
|
|
225
|
+
knownCount,
|
|
226
|
+
error: `could not list models from ${target.baseUrl}${MODELS_PATH}`,
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
return { source: "gateway", live, knownCount, ...diffModels(opts.known, live) };
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* Default fetch adapter, narrowed to FetchLike so callers can inject one
|
|
234
|
+
* without touching the global fetch.
|
|
235
|
+
*/
|
|
236
|
+
const defaultFetch: FetchLike = async (url, init) => {
|
|
237
|
+
const res = await fetch(url, init);
|
|
238
|
+
return { ok: res.ok, status: res.status, json: () => res.json() };
|
|
239
|
+
};
|
|
240
|
+
|
|
241
|
+
/** How many ids a report line lists before it summarizes the rest. */
|
|
242
|
+
const IDS_PER_LINE = 8;
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* Render up to IDS_PER_LINE ids, then a count. A sandbox whose session
|
|
246
|
+
* registered nothing would otherwise print the gateway's whole lineup into a
|
|
247
|
+
* one-line notification.
|
|
248
|
+
*/
|
|
249
|
+
function idList(ids: string[]): string {
|
|
250
|
+
if (ids.length <= IDS_PER_LINE) return ids.join(", ");
|
|
251
|
+
return `${ids.slice(0, IDS_PER_LINE).join(", ")} (+${ids.length - IDS_PER_LINE} more)`;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* Render a result as the text the command puts in front of the user. `applied`
|
|
256
|
+
* says the harness re-registered the list already, so the text must not tell
|
|
257
|
+
* the user to restart for models that are already there.
|
|
258
|
+
*/
|
|
259
|
+
export function refreshReport(result: RefreshResult, applied = false): string {
|
|
260
|
+
if (result.source === "cli") {
|
|
261
|
+
const out = (result.cliOutput ?? "").trim();
|
|
262
|
+
return out.length > 0 ? out : "gateway-cli sync: nothing to change.";
|
|
263
|
+
}
|
|
264
|
+
if (result.error) return `bifrost models: ${result.error}`;
|
|
265
|
+
const heading = `bifrost models: ${result.live.length} offered by the gateway`;
|
|
266
|
+
// With nothing registered there is no diff to show, so the headline names
|
|
267
|
+
// what is on offer instead — the sandbox user has no other way to see it.
|
|
268
|
+
const lines =
|
|
269
|
+
result.knownCount === 0 && result.live.length > 0
|
|
270
|
+
? [`${heading}: ${idList(result.live)}`]
|
|
271
|
+
: [`${heading}.`];
|
|
272
|
+
if (result.added.length > 0) {
|
|
273
|
+
if (applied) {
|
|
274
|
+
lines.push(`Added this session: ${idList(result.added)}`);
|
|
275
|
+
} else if (result.knownCount === 0) {
|
|
276
|
+
// Nothing was registered here, so nothing is "new since startup": this
|
|
277
|
+
// session simply has no gateway models (the CLI-less sandbox case).
|
|
278
|
+
lines.push(
|
|
279
|
+
`None registered in this session — install gateway-cli (or point GATEWAY_CLI_BIN at it) and restart to use them.`,
|
|
280
|
+
);
|
|
281
|
+
} else {
|
|
282
|
+
lines.push(
|
|
283
|
+
`New since this session started: ${idList(result.added)} — restart to use them.`,
|
|
284
|
+
);
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
if (result.removed.length > 0) {
|
|
288
|
+
lines.push(`No longer offered: ${idList(result.removed)}`);
|
|
289
|
+
}
|
|
290
|
+
if (result.added.length === 0 && result.removed.length === 0) {
|
|
291
|
+
lines.push("This session's list is current.");
|
|
292
|
+
}
|
|
293
|
+
return lines.join("\n");
|
|
294
|
+
}
|