@stablekernel/pi-bifrost 0.8.0 → 0.9.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
@@ -34,36 +34,6 @@ provider's model list once, while the session starts, and neither can
34
34
  re-register one to a running session — so the report names the new models and
35
35
  says to restart, and nothing here fakes a reload.
36
36
 
37
- ## Datasheet supplement (off by default)
38
-
39
- Wildcard-provider models — e.g. a fresh Fireworks launch that the CLI's
40
- models.dev source has not cataloged yet — never reach `gateway-cli models`,
41
- so they cannot be listed here either. When configured, this extension also
42
- reads the datasheet feed Bifrost itself syncs from and appends the
43
- wildcard-provider ids the CLI list lacks; CLI-listed ids always win. Applies
44
- to the OpenAI-compatible surface only; the Anthropic surface stays
45
- Claude-only.
46
-
47
- Activation (first wins):
48
-
49
- 1. env `GATEWAY_DATASHEET_URL`
50
- 2. `~/.config/bifrost/datasheet.json` — `{"url": "..."}`
51
- 3. `<project>/.gateway/datasheet.json` — same shape
52
-
53
- The URL must be `https://`; a source with anything else is treated as absent.
54
-
55
- Behavior: the feed is fetched once per hour and cached under
56
- `~/.cache/gateway-bifrost/datasheet-cache.json` (or `$XDG_CACHE_HOME`), with
57
- a 3s hard timeout and a stale-cache fallback on failure. A failed first
58
- fetch also triggers a background cache fill, so a slow or cold feed costs
59
- one session rather than every start. Unconfigured or unreachable, the
60
- supplement is silently skipped — startup never blocks on it.
61
-
62
- Provenance: supplement-only models are tagged `limits_source: "datasheet"`
63
- and `cost_source: "datasheet"` in the `gateway-cli models` payload they ride
64
- in. The tags stop there — pi's provider config has no provenance field, so
65
- they are not forwarded into the registered shapes.
66
-
67
37
  ## Requirements
68
38
 
69
39
  - `gateway-cli` on `PATH` (or the `GATEWAY_CLI_BIN` env var pointing at it), connected once with `gateway-cli connect`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stablekernel/pi-bifrost",
3
- "version": "0.8.0",
3
+ "version": "0.9.0",
4
4
  "description": "Pi extension that registers the Bifrost gateway as a model provider, resolving per-project virtual keys via gateway-cli.",
5
5
  "type": "module",
6
6
  "files": [
package/src/index.ts CHANGED
@@ -1,7 +1,6 @@
1
1
  import { execFileSync, execFile, type ExecFileOptions } from "node:child_process";
2
2
  import { readFileSync } from "node:fs";
3
3
  import { homedir } from "node:os";
4
- import { datasheetSupplement, mergeModels } from "./datasheet.js";
5
4
  import {
6
5
  REFRESH_COMMAND,
7
6
  keyFileValue,
@@ -89,15 +88,6 @@ type CommandContext = {
89
88
  /** Overridable so a non-PATH install still works. */
90
89
  const CLI = process.env.GATEWAY_CLI_BIN ?? "gateway-cli";
91
90
 
92
- /** Where the datasheet feed cache lives for this plugin. */
93
- function datasheetCacheDir(): string {
94
- // HOME can be unset or empty in minimal environments; fall back to
95
- // os.homedir() so the path never degrades to "undefined/.cache".
96
- const home = process.env.HOME || homedir();
97
- const base = process.env.XDG_CACHE_HOME ?? `${home}/.cache`;
98
- return `${base}/gateway-bifrost`;
99
- }
100
-
101
91
  /**
102
92
  * Suffix for models nothing could price.
103
93
  *
@@ -214,7 +204,7 @@ export default async function (pi: ExtensionAPI): Promise<void> {
214
204
  ];
215
205
 
216
206
  for (const surface of surfaces) {
217
- const models = await listModels(surface, info.root);
207
+ const models = listModels(surface);
218
208
  if (models.length === 0) continue;
219
209
  for (const model of models) known.push(model.id);
220
210
 
@@ -381,21 +371,16 @@ function thinkingLevelMap(
381
371
  return map;
382
372
  }
383
373
 
384
- async function listModels(
385
- surface: WireSurface,
386
- root: string,
387
- ): Promise<ProviderModelConfig[]> {
388
- const raw = run(["models", `--wire=${surface.wire}`, "--all"]);
374
+ function listModels(surface: WireSurface): ProviderModelConfig[] {
375
+ // openai needs wildcard-discovered providers a frozen selection would hide; anthropic honors the launch picker's selection.
376
+ const raw = run([
377
+ "models",
378
+ `--wire=${surface.wire}`,
379
+ ...(surface.wire === "openai" ? ["--all"] : []),
380
+ ]);
389
381
  if (!raw) return [];
390
382
  try {
391
- const payload = JSON.parse(raw) as CliModels;
392
- if (surface.wire === "openai") {
393
- // Wildcard-provider ids the CLI cannot list yet, from the datasheet
394
- // feed Bifrost itself syncs from. CLI-listed ids always win.
395
- const extra = await datasheetSupplement(root, datasheetCacheDir());
396
- payload.models = mergeModels(payload.models ?? [], extra);
397
- }
398
- return toPiModels(payload, surface.api);
383
+ return toPiModels(JSON.parse(raw) as CliModels, surface.api);
399
384
  } catch {
400
385
  return [];
401
386
  }
@@ -91,7 +91,7 @@ function mockCLI(responses: Record<string, string>) {
91
91
 
92
92
  const OK_CLI = {
93
93
  "resolve --json": JSON.stringify(RESOLUTION),
94
- "models --wire=anthropic --all": cliPayload([HAIKU]),
94
+ "models --wire=anthropic": cliPayload([HAIKU]),
95
95
  "models --wire=openai --all": cliPayload([NOVA]),
96
96
  };
97
97
 
@@ -137,11 +137,8 @@ const ORIGINAL_ENV: Record<string, string | undefined> = {};
137
137
  for (const name of REFRESH_ENV) ORIGINAL_ENV[name] = process.env[name];
138
138
 
139
139
  beforeEach(() => {
140
- // Registration tests run the real datasheetSupplement. Keep it
141
- // deterministic and machine-independent: drop the env override and point
142
- // HOME at an empty temp dir, so neither ~/.config/bifrost/datasheet.json
143
- // nor the real ~/.cache/gateway-bifrost cache is read or written.
144
- delete process.env.GATEWAY_DATASHEET_URL;
140
+ // Point HOME at an empty temp dir so the real ~/.config/bifrost key file
141
+ // is never read.
145
142
  process.env.HOME = mkdtempSync(join(tmpdir(), "gw-home-"));
146
143
  // The CLI-less refresh path reads these; the tests that need them set them.
147
144
  for (const name of REFRESH_ENV) delete process.env[name];
@@ -181,7 +178,9 @@ describe("provider registration", () => {
181
178
  test("asks the CLI per wire, so each surface gets its own id spelling", async () => {
182
179
  const calls = mockCLI(OK_CLI);
183
180
  await runExtension();
184
- expect(calls).toContain("models --wire=anthropic --all");
181
+ expect(calls).toContain("models --wire=anthropic");
182
+ // The saved anthropic selection must be honored, so --all stays off this wire.
183
+ expect(calls).not.toContain("models --wire=anthropic --all");
185
184
  expect(calls).toContain("models --wire=openai --all");
186
185
  });
187
186
 
@@ -200,7 +199,7 @@ describe("provider registration", () => {
200
199
  // behavior anyway so a future CLI change cannot quietly flip it.
201
200
  mockCLI({
202
201
  "resolve --json": JSON.stringify({ ...RESOLUTION, headers: {} }),
203
- "models --wire=anthropic --all": cliPayload([HAIKU]),
202
+ "models --wire=anthropic": cliPayload([HAIKU]),
204
203
  "models --wire=openai --all": cliPayload([NOVA]),
205
204
  });
206
205
  const registered = await runExtension();
@@ -215,7 +214,7 @@ describe("provider registration", () => {
215
214
  delete noHeaders.headers;
216
215
  mockCLI({
217
216
  "resolve --json": JSON.stringify(noHeaders),
218
- "models --wire=anthropic --all": cliPayload([HAIKU]),
217
+ "models --wire=anthropic": cliPayload([HAIKU]),
219
218
  "models --wire=openai --all": cliPayload([NOVA]),
220
219
  });
221
220
  const registered = await runExtension();
@@ -275,7 +274,7 @@ describe("provider registration", () => {
275
274
  test("skips a surface the CLI cannot list", async () => {
276
275
  mockCLI({
277
276
  "resolve --json": JSON.stringify(RESOLUTION),
278
- "models --wire=anthropic --all": cliPayload([HAIKU]),
277
+ "models --wire=anthropic": cliPayload([HAIKU]),
279
278
  // openai wire omitted: the command fails
280
279
  });
281
280
  const registered = await runExtension();
@@ -285,54 +284,13 @@ describe("provider registration", () => {
285
284
  test("registers nothing when the CLI emits unparseable output", async () => {
286
285
  mockCLI({
287
286
  "resolve --json": JSON.stringify(RESOLUTION),
288
- "models --wire=anthropic --all": "not json",
287
+ "models --wire=anthropic": "not json",
289
288
  "models --wire=openai --all": "not json",
290
289
  });
291
290
  expect(await runExtension()).toEqual([]);
292
291
  });
293
292
  });
294
293
 
295
- describe("datasheet supplement gate", () => {
296
- const EXTRA_FLASH = {
297
- id: "accounts/fireworks/models/glm-5p3-flash",
298
- name: "glm-5p3-flash",
299
- context_window: 1048576,
300
- max_output_tokens: 131072,
301
- limits_source: "datasheet",
302
- };
303
-
304
- test("appends supplement ids on the openai wire only", async () => {
305
- // Mock the datasheet module the same way child_process is mocked above:
306
- // registered before the fresh extension import, undone by mock.restore()
307
- // in afterEach, so the other tests still see the real module.
308
- mock.module("./datasheet.js", () => ({
309
- datasheetSupplement: async () => [EXTRA_FLASH],
310
- // Same CLI-wins dedup as the real mergeModels, inlined to avoid a
311
- // circular import of the module under mock.
312
- mergeModels: (
313
- cli: Array<{ id: string }>,
314
- extra: Array<{ id: string }>,
315
- ) => {
316
- const seen = new Set(cli.map((m) => m.id));
317
- return [...cli, ...extra.filter((m) => !seen.has(m.id))];
318
- },
319
- }));
320
- mockCLI(OK_CLI);
321
- const registered = await runExtension();
322
-
323
- const openai = registered.find((r) => r.id === "bifrost-openai")!;
324
- const openaiIds = openai.config.models.map((m: { id: string }) => m.id);
325
- expect(openaiIds).toContain("bedrock/amazon.nova-lite-v1:0");
326
- expect(openaiIds).toContain(EXTRA_FLASH.id);
327
-
328
- const anthropic = registered.find((r) => r.id === "bifrost-anthropic")!;
329
- const anthropicIds = anthropic.config.models.map(
330
- (m: { id: string }) => m.id,
331
- );
332
- expect(anthropicIds).not.toContain(EXTRA_FLASH.id);
333
- });
334
- });
335
-
336
294
  describe("unpriced models", () => {
337
295
  test("marks the name rather than advertising a zero rate as free", async () => {
338
296
  // Pi's model shape requires `cost` and defaults it to zeros, which renders
@@ -580,11 +538,9 @@ describe("bifrost-refresh command", () => {
580
538
 
581
539
  test("without the CLI it asks the gateway and diffs this session", async () => {
582
540
  // 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
541
  mockCLI({
586
542
  "resolve --json": JSON.stringify(RESOLUTION),
587
- "models --wire=anthropic --all": cliPayload([HAIKU]),
543
+ "models --wire=anthropic": cliPayload([HAIKU]),
588
544
  });
589
545
  process.env.BIFROST_GATEWAY_URL = "https://gw.example";
590
546
  process.env.BIFROST_VK = "sk-bf-testkey";
@@ -1,360 +0,0 @@
1
- import { describe, expect, test } from "bun:test";
2
- import {
3
- existsSync,
4
- mkdirSync,
5
- mkdtempSync,
6
- readFileSync,
7
- writeFileSync,
8
- } from "node:fs";
9
- import { tmpdir } from "node:os";
10
- import { join } from "node:path";
11
- import {
12
- type FetchLike,
13
- type SupplementalModel,
14
- datasheetUrl,
15
- fetchDatasheet,
16
- mergeModels,
17
- parseDatasheet,
18
- } from "./datasheet.js";
19
- import { toPiModels, type CliModels } from "./index.js";
20
-
21
- const glmFlash = {
22
- provider: "fireworks_ai",
23
- mode: "chat",
24
- base_model: "glm-5.3-flash",
25
- context_length: 1048576,
26
- max_input_tokens: 1048576,
27
- max_output_tokens: 131072,
28
- input_cost_per_token: 0.00000015,
29
- cache_read_input_token_cost: 0.000000029,
30
- output_cost_per_token: 0.0000005,
31
- supports_reasoning: true,
32
- };
33
-
34
- describe("parseDatasheet", () => {
35
- test("maps a fireworks_ai chat entry, converting per-token to per-million", () => {
36
- const out = parseDatasheet({
37
- "fireworks_ai/accounts/fireworks/models/glm-5p3-flash": glmFlash,
38
- });
39
- expect(out).toHaveLength(1);
40
- expect(out[0]).toEqual({
41
- id: "accounts/fireworks/models/glm-5p3-flash",
42
- name: "glm-5.3-flash",
43
- context_window: 1048576,
44
- max_output_tokens: 131072,
45
- limits_source: "datasheet",
46
- cost_source: "datasheet",
47
- cost: {
48
- input: 0.15,
49
- output: 0.5,
50
- cache_read: 0.029,
51
- cache_write: 0,
52
- },
53
- reasoning: true,
54
- } satisfies SupplementalModel);
55
- });
56
-
57
- test("maps supports_image_input to image_input only when true", () => {
58
- const out = parseDatasheet({
59
- "fireworks_ai/accounts/fireworks/models/glm-5p3-flash": {
60
- ...glmFlash,
61
- supports_image_input: true,
62
- },
63
- "fireworks_ai/accounts/fireworks/models/glm-5p2": {
64
- ...glmFlash,
65
- supports_image_input: false,
66
- },
67
- });
68
- expect(out).toHaveLength(2);
69
- const byId = new Map(out.map((m) => [m.id, m]));
70
- expect(byId.get("accounts/fireworks/models/glm-5p3-flash")?.image_input).toBe(true);
71
- expect(byId.get("accounts/fireworks/models/glm-5p2")?.image_input).toBeUndefined();
72
- });
73
-
74
- test("maps supports_vision to image_input — the upstream field name (1570 rows vs 8 for supports_image_input)", () => {
75
- const out = parseDatasheet({
76
- "fireworks_ai/accounts/fireworks/models/deepseek-v4-flash-vision-exp": {
77
- ...glmFlash,
78
- supports_vision: true,
79
- },
80
- "fireworks_ai/accounts/fireworks/models/deepseek-v4-flash": {
81
- ...glmFlash,
82
- supports_vision: false,
83
- },
84
- });
85
- expect(out).toHaveLength(2);
86
- const byId = new Map(out.map((m) => [m.id, m]));
87
- expect(byId.get("accounts/fireworks/models/deepseek-v4-flash-vision-exp")?.image_input).toBe(true);
88
- expect(byId.get("accounts/fireworks/models/deepseek-v4-flash")?.image_input).toBeUndefined();
89
- });
90
-
91
- test("falls back to max_input_tokens when context_length is absent — upstream rows never carry context_length", () => {
92
- const { context_length, ...upstreamShape } = glmFlash;
93
- const out = parseDatasheet({
94
- "fireworks_ai/accounts/fireworks/models/glm-5p3-flash": upstreamShape,
95
- });
96
- expect(out).toHaveLength(1);
97
- expect(out[0].context_window).toBe(upstreamShape.max_input_tokens);
98
- });
99
-
100
- test("reads cache_write from cache_creation_input_token_cost — the upstream field name (503 rows vs 0)", () => {
101
- const out = parseDatasheet({
102
- "fireworks_ai/accounts/fireworks/models/glm-5p3-flash": {
103
- ...glmFlash,
104
- cache_creation_input_token_cost: 0.00000015,
105
- },
106
- });
107
- expect(out).toHaveLength(1);
108
- expect(out[0].cost?.cache_write).toBe(0.15);
109
- });
110
-
111
- test("drops non-chat entries, unknown providers, and rows without limits", () => {
112
- const out = parseDatasheet({
113
- "fireworks_ai/accounts/fireworks/models/qwen3-embedding-8b": {
114
- ...glmFlash,
115
- mode: "embedding",
116
- },
117
- "other_provider/some/model": glmFlash,
118
- "fireworks_ai/accounts/fireworks/models/no-limits": {
119
- ...glmFlash,
120
- context_length: undefined,
121
- max_input_tokens: undefined,
122
- },
123
- "fireworks_ai/accounts/fireworks/models/no-max-out": {
124
- ...glmFlash,
125
- max_output_tokens: undefined,
126
- },
127
- });
128
- expect(out).toEqual([]);
129
- });
130
-
131
- test("unpriced entry omits cost entirely and falls back to slug name", () => {
132
- const out = parseDatasheet({
133
- "fireworks_ai/accounts/fireworks/models/glm-5p3-flash": {
134
- mode: "chat",
135
- context_length: 1000,
136
- max_output_tokens: 100,
137
- },
138
- });
139
- expect(out[0]?.name).toBe("glm-5p3-flash");
140
- expect(out[0]?.cost).toBeUndefined();
141
- expect(out[0]?.cost_source).toBeUndefined();
142
- });
143
- });
144
-
145
- describe("mergeModels", () => {
146
- test("appends ids the CLI list lacks; CLI entry wins on collision", () => {
147
- // mergeModels is generic over {id: string}: dedup is by id only, so the
148
- // test uses plain {id, name} literals rather than full model shapes.
149
- const cli = [
150
- { id: "a", name: "A" },
151
- { id: "b", name: "B" },
152
- ];
153
- const extra = [
154
- { id: "b", name: "B-datasheet" },
155
- { id: "c", name: "C" },
156
- ];
157
- expect(mergeModels(cli, extra)).toEqual([
158
- { id: "a", name: "A" },
159
- { id: "b", name: "B" },
160
- { id: "c", name: "C" },
161
- ]);
162
- });
163
- });
164
-
165
- describe("datasheetUrl", () => {
166
- const tmp = mkdtempSync(join(tmpdir(), "gw-ds-"));
167
- const proj = join(tmp, "proj");
168
- const home = join(tmp, "home");
169
- mkdirSync(join(proj, ".gateway"), { recursive: true });
170
- mkdirSync(join(home, ".config", "bifrost"), { recursive: true });
171
-
172
- test("env var wins over files", () => {
173
- expect(datasheetUrl("https://env/datasheet", home, proj)).toBe(
174
- "https://env/datasheet",
175
- );
176
- });
177
-
178
- test("user file beats project file", () => {
179
- writeFileSync(
180
- join(home, ".config", "bifrost", "datasheet.json"),
181
- `{"url": "https://user/datasheet"}`,
182
- );
183
- writeFileSync(
184
- join(proj, ".gateway", "datasheet.json"),
185
- `{"url": "https://proj/datasheet"}`,
186
- );
187
- expect(datasheetUrl(undefined, home, proj)).toBe("https://user/datasheet");
188
- });
189
-
190
- test("project file used when user-level absent; null when neither", () => {
191
- // Self-seeded: does not depend on files written by earlier tests.
192
- writeFileSync(
193
- join(proj, ".gateway", "datasheet.json"),
194
- `{"url": "https://proj/datasheet"}`,
195
- );
196
- // a home with no datasheet.json falls through to the project file
197
- const homeEmpty = join(tmp, "home-empty");
198
- mkdirSync(homeEmpty, { recursive: true });
199
- expect(datasheetUrl(undefined, homeEmpty, proj)).toBe(
200
- "https://proj/datasheet",
201
- );
202
- expect(datasheetUrl(undefined, homeEmpty, join(tmp, "other"))).toBeNull();
203
- });
204
-
205
- test("non-https URLs are treated as absent and fall through", () => {
206
- // Feeds steer local model listings, so every source must be TLS: an
207
- // http:// project file is skipped, and with nothing else yielding a
208
- // URL the result is null.
209
- const projHttp = join(tmp, "proj-http");
210
- mkdirSync(join(projHttp, ".gateway"), { recursive: true });
211
- writeFileSync(
212
- join(projHttp, ".gateway", "datasheet.json"),
213
- `{"url": "http://insecure/datasheet"}`,
214
- );
215
- const homeEmpty = join(tmp, "home-empty-http");
216
- mkdirSync(homeEmpty, { recursive: true });
217
- expect(datasheetUrl(undefined, homeEmpty, projHttp)).toBeNull();
218
- // A non-TLS env override likewise falls through to an https file.
219
- writeFileSync(
220
- join(projHttp, ".gateway", "datasheet.json"),
221
- `{"url": "https://proj/datasheet"}`,
222
- );
223
- expect(
224
- datasheetUrl("http://insecure-env/datasheet", homeEmpty, projHttp),
225
- ).toBe("https://proj/datasheet");
226
- });
227
- });
228
-
229
- describe("fetchDatasheet", () => {
230
- const tmp = mkdtempSync(join(tmpdir(), "gw-ds-cache-"));
231
- // Each test gets its own cache file so results never depend on run order.
232
- const cachePath = (name: string) => join(tmp, `${name}.json`);
233
- const ok: FetchLike = async () => ({
234
- ok: true,
235
- json: async () => ({
236
- "fireworks_ai/accounts/fireworks/models/glm-5p3-flash": glmFlash,
237
- }),
238
- });
239
- const fail: FetchLike = async () => ({ ok: false, json: async () => ({}) });
240
-
241
- test("fetches, returns parsed body, writes cache", async () => {
242
- const body = await fetchDatasheet(
243
- "https://feed/datasheet",
244
- cachePath("t1"),
245
- ok,
246
- 1000,
247
- );
248
- expect(
249
- body?.["fireworks_ai/accounts/fireworks/models/glm-5p3-flash"],
250
- ).toBeDefined();
251
- const cached = JSON.parse(readFileSync(cachePath("t1"), "utf8"));
252
- expect(cached.fetchedAt).toBe(1000);
253
- });
254
-
255
- test("fresh cache short-circuits the fetch", async () => {
256
- // Seed a cache first so the counting call below has something to hit.
257
- await fetchDatasheet("https://feed/datasheet", cachePath("t2"), ok, 1000);
258
- let called = 0;
259
- const counting: FetchLike = async () => {
260
- called++;
261
- return ok("u");
262
- };
263
- await fetchDatasheet(
264
- "https://feed/datasheet",
265
- cachePath("t2"),
266
- counting,
267
- 1000 + 1000,
268
- );
269
- expect(called).toBe(0);
270
- });
271
-
272
- test("expired cache refetches; fetch failure falls back to stale cache", async () => {
273
- await fetchDatasheet("https://feed/datasheet", cachePath("t3"), ok, 1000);
274
- const body = await fetchDatasheet(
275
- "https://feed/datasheet",
276
- cachePath("t3"),
277
- fail,
278
- 1000 + 3_600_000 + 1,
279
- );
280
- expect(
281
- body?.["fireworks_ai/accounts/fireworks/models/glm-5p3-flash"],
282
- ).toBeDefined();
283
- });
284
-
285
- test("fetch failure with no cache returns null", async () => {
286
- expect(
287
- await fetchDatasheet(
288
- "https://feed/datasheet",
289
- cachePath("absent"),
290
- fail,
291
- 1000,
292
- ),
293
- ).toBeNull();
294
- });
295
-
296
- test("failed fetch with no cache backfills the cache in the background", async () => {
297
- const path = cachePath("backfill");
298
- let calls = 0;
299
- const flaky: FetchLike = async () => {
300
- calls++;
301
- if (calls === 1) throw new Error("cold start");
302
- return {
303
- ok: true,
304
- json: async () => ({
305
- "fireworks_ai/accounts/fireworks/models/glm-5p3-flash": glmFlash,
306
- }),
307
- };
308
- };
309
- const first = await fetchDatasheet(
310
- "https://feed/datasheet",
311
- path,
312
- flaky,
313
- 1000,
314
- );
315
- expect(first).toBeNull(); // this session skips the supplement
316
- // the detached backfill (call 2) lands the cache for the next session
317
- const deadline = Date.now() + 2000;
318
- while (Date.now() < deadline) {
319
- if (existsSync(path)) break;
320
- await new Promise((r) => setTimeout(r, 25));
321
- }
322
- expect(calls).toBe(2);
323
- const doc = JSON.parse(readFileSync(path, "utf8")) as {
324
- fetchedAt: number;
325
- };
326
- expect(doc.fetchedAt).toBeGreaterThan(1000);
327
- });
328
- });
329
-
330
- describe("end-to-end: CLI payload + datasheet extra -> pi provider models", () => {
331
- test("supplemented id reaches the provider list with datasheet limits", () => {
332
- const cliPayload: CliModels = {
333
- models: [
334
- {
335
- id: "accounts/fireworks/models/glm-5p2",
336
- name: "GLM 5.2",
337
- context_window: 200000,
338
- max_output_tokens: 32768,
339
- limits_source: "gateway",
340
- },
341
- ],
342
- };
343
- const extra = parseDatasheet({
344
- "fireworks_ai/accounts/fireworks/models/glm-5p3-flash": glmFlash,
345
- });
346
- const merged = mergeModels(cliPayload.models ?? [], extra);
347
- const piModels = toPiModels({ models: merged }, "openai-completions");
348
- const flash = piModels.find(
349
- (m) => m.id === "accounts/fireworks/models/glm-5p3-flash",
350
- );
351
- expect(flash).toBeDefined();
352
- expect(flash?.contextWindow).toBe(1048576);
353
- expect(flash?.maxTokens).toBe(131072);
354
- expect(flash?.cost?.input).toBe(0.15);
355
- // CLI-listed model survives the merge untouched
356
- expect(
357
- piModels.find((m) => m.id === "accounts/fireworks/models/glm-5p2"),
358
- ).toBeDefined();
359
- });
360
- });
package/src/datasheet.ts DELETED
@@ -1,303 +0,0 @@
1
- /**
2
- * Datasheet supplement: a second, faster id source for wildcard-provider
3
- * models the CLI cannot list yet.
4
- *
5
- * The CLI sources Fireworks (wildcard-provider) ids from models.dev, which
6
- * lags provider launches by days and is cached 24h. Bifrost itself syncs
7
- * from the datasheet-proxy feed hourly, so a model merged there is routable —
8
- * this module reads the same feed and merges the ids the CLI list lacks.
9
- * The virtual key never passes through here: the feed is public.
10
- *
11
- * Off by default. Activated by (first wins; the URL must be https — any
12
- * source yielding something else is treated as absent):
13
- * 1. env GATEWAY_DATASHEET_URL
14
- * 2. ~/.config/bifrost/datasheet.json {"url": "<function-url>/datasheet"}
15
- * 3. <project-root>/.gateway/datasheet.json
16
- *
17
- * Security note: entries only produce local picker listings and metadata;
18
- * requests still go to the CLI-resolved (allowlisted) gateway origin. A
19
- * hostile feed cannot redirect traffic or exfiltrate the key.
20
- */
21
- import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
22
- import { dirname, join } from "node:path";
23
-
24
- /** One row of the datasheet feed (flat map keyed by "<provider>/<model-id>"). */
25
- export type DatasheetEntry = {
26
- provider?: string;
27
- mode?: string;
28
- base_model?: string;
29
- context_length?: number;
30
- max_input_tokens?: number;
31
- max_output_tokens?: number;
32
- max_tokens?: number;
33
- input_cost_per_token?: number;
34
- output_cost_per_token?: number;
35
- cache_read_input_token_cost?: number;
36
- // Upstream rows name the cache-write rate `cache_creation_input_token_cost`
37
- // (503 rows); the `cache_write_…` spelling appears on zero rows and is
38
- // kept for symmetry with Bifrost's own pricing-card vocabulary.
39
- cache_write_input_token_cost?: number;
40
- cache_creation_input_token_cost?: number;
41
- supports_reasoning?: boolean;
42
- // Upstream rows express image capability as `supports_vision` (1,570
43
- // rows); `supports_image_input` appears on only 8. Either true counts.
44
- supports_vision?: boolean;
45
- supports_image_input?: boolean;
46
- };
47
-
48
- /** A model in the same shape `gateway-cli models` emits (structural subset). */
49
- export type SupplementalModel = {
50
- id: string;
51
- name: string;
52
- context_window: number;
53
- max_output_tokens: number;
54
- limits_source: string;
55
- cost_source?: string;
56
- cost?: {
57
- input: number;
58
- output: number;
59
- cache_read: number;
60
- cache_write: number;
61
- };
62
- reasoning?: boolean;
63
- image_input?: boolean;
64
- };
65
-
66
- /** Datasheet provider prefixes whose entries this module understands. */
67
- const PROVIDER_PREFIXES = ["fireworks_ai/"];
68
-
69
- /** How long a fetched feed is reused before refetching. */
70
- const DATASHEET_TTL_MS = 60 * 60 * 1000;
71
-
72
- /** Fetch hard timeout: the supplement must never block plugin init long. */
73
- const FETCH_TIMEOUT_MS = 3000;
74
-
75
- /** Budget for the background cache fill after a failed fetch: init is never
76
- * blocked by it, so it can afford to outlast a cold feed start. */
77
- const BACKFILL_TIMEOUT_MS = 15_000;
78
-
79
- export type FetchLike = (
80
- url: string,
81
- init?: { signal?: AbortSignal },
82
- ) => Promise<{ ok: boolean; status?: number; json(): Promise<unknown> }>;
83
-
84
- type CacheDoc = { fetchedAt: number; body: Record<string, DatasheetEntry> };
85
-
86
- /**
87
- * Discover the feed URL: env, then user file, then project file. Only
88
- * https:// URLs are honored; a source with anything else (including a
89
- * non-TLS env override) falls through to the next candidate.
90
- */
91
- export function datasheetUrl(
92
- env: string | undefined,
93
- home: string | undefined,
94
- root: string,
95
- ): string | null {
96
- if (env && env.startsWith("https://")) return env;
97
- const candidates = [
98
- home ? join(home, ".config", "bifrost", "datasheet.json") : null,
99
- join(root, ".gateway", "datasheet.json"),
100
- ];
101
- for (const p of candidates) {
102
- if (!p) continue;
103
- try {
104
- const parsed = JSON.parse(readFileSync(p, "utf8")) as { url?: unknown };
105
- if (
106
- typeof parsed.url === "string" &&
107
- parsed.url.startsWith("https://")
108
- ) {
109
- return parsed.url;
110
- }
111
- } catch {
112
- // absent or malformed: try the next candidate
113
- }
114
- }
115
- return null;
116
- }
117
-
118
- function readCache(path: string): CacheDoc | null {
119
- try {
120
- const doc = JSON.parse(readFileSync(path, "utf8")) as CacheDoc;
121
- if (
122
- typeof doc.fetchedAt === "number" &&
123
- doc.body &&
124
- typeof doc.body === "object"
125
- ) {
126
- return doc;
127
- }
128
- } catch {
129
- // absent or malformed: treat as no cache
130
- }
131
- return null;
132
- }
133
-
134
- function writeCache(path: string, doc: CacheDoc): void {
135
- try {
136
- mkdirSync(dirname(path), { recursive: true });
137
- writeFileSync(path, JSON.stringify(doc));
138
- } catch {
139
- // cache write failure is non-fatal: refetch next init
140
- }
141
- }
142
-
143
- /**
144
- * Default fetch adapter: narrows the platform Response to FetchLike's
145
- * subset so callers can inject a mock without touching the global fetch.
146
- */
147
- const defaultFetch: FetchLike = async (u, i) => {
148
- const resp = await fetch(u, i);
149
- return { ok: resp.ok, status: resp.status, json: () => resp.json() };
150
- };
151
-
152
- /**
153
- * Fetch the feed, honoring a fresh cache. On fetch failure a stale cache is
154
- * served; with no cache at all the result is null and the caller skips the
155
- * supplement. Garbage responses (non-object JSON, HTTP error) are treated
156
- * as fetch failures so they never poison the cache. A fetch failure with no
157
- * cache also triggers an unawaited backfill fetch (15s budget) that only
158
- * writes the cache, so a cold feed costs one session, not one per start.
159
- */
160
- export async function fetchDatasheet(
161
- url: string,
162
- cachePath: string,
163
- fetchImpl: FetchLike = defaultFetch,
164
- now: number = Date.now(),
165
- ): Promise<Record<string, DatasheetEntry> | null> {
166
- const cached = readCache(cachePath);
167
- if (cached && now - cached.fetchedAt < DATASHEET_TTL_MS) return cached.body;
168
- try {
169
- const resp = await fetchImpl(url, {
170
- signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
171
- });
172
- if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
173
- const body = (await resp.json()) as Record<string, DatasheetEntry>;
174
- if (!body || typeof body !== "object" || Array.isArray(body)) {
175
- throw new Error("unexpected feed shape");
176
- }
177
- writeCache(cachePath, { fetchedAt: now, body });
178
- return body;
179
- } catch {
180
- if (!cached) {
181
- // Fire-and-forget warm fill: a slow feed (cold start) must not block
182
- // plugin init, but the next session should find a warm cache. Never
183
- // awaited; every failure path is swallowed (writeCache guards, and
184
- // the .catch below covers the rest).
185
- void fetchImpl(url, {
186
- signal: AbortSignal.timeout(BACKFILL_TIMEOUT_MS),
187
- })
188
- .then(async (resp) => {
189
- if (!resp.ok) return;
190
- const body = (await resp.json()) as Record<string, DatasheetEntry>;
191
- if (body && typeof body === "object" && !Array.isArray(body)) {
192
- writeCache(cachePath, { fetchedAt: Date.now(), body });
193
- }
194
- })
195
- .catch(() => {});
196
- }
197
- return cached?.body ?? null;
198
- }
199
- }
200
-
201
- function perMillion(rate: number | undefined): number {
202
- return typeof rate === "number" ? Math.round(rate * 1_000_000 * 1e8) / 1e8 : 0;
203
- }
204
-
205
- /**
206
- * Turn feed rows into model entries. Keeps only chat-mode rows under a known
207
- * provider prefix, requires usable limits, converts per-token rates to
208
- * per-million (mirroring the CLI's perTokenToPerMTok).
209
- */
210
- export function parseDatasheet(
211
- body: Record<string, DatasheetEntry>,
212
- ): SupplementalModel[] {
213
- const out: SupplementalModel[] = [];
214
- for (const [key, e] of Object.entries(body)) {
215
- if (!e || typeof e !== "object" || e.mode !== "chat") continue;
216
- const prefix = PROVIDER_PREFIXES.find((p) => key.startsWith(p));
217
- if (!prefix) continue;
218
- const id = key.slice(prefix.length);
219
- if (!id) continue;
220
- // Upstream rows never carry `context_length` (0 of 4,336); they state
221
- // `max_input_tokens` instead. Either sets the context window.
222
- const contextLength =
223
- typeof e.context_length === "number"
224
- ? e.context_length
225
- : typeof e.max_input_tokens === "number"
226
- ? e.max_input_tokens
227
- : undefined;
228
- if (
229
- typeof contextLength !== "number" ||
230
- typeof e.max_output_tokens !== "number"
231
- ) {
232
- continue;
233
- }
234
- const slug = id.split("/").pop() as string;
235
- const priced =
236
- typeof e.input_cost_per_token === "number" ||
237
- typeof e.output_cost_per_token === "number";
238
- out.push({
239
- id,
240
- name:
241
- typeof e.base_model === "string" && e.base_model ? e.base_model : slug,
242
- context_window: contextLength,
243
- max_output_tokens: e.max_output_tokens,
244
- limits_source: "datasheet",
245
- ...(priced
246
- ? {
247
- cost_source: "datasheet",
248
- cost: {
249
- input: perMillion(e.input_cost_per_token),
250
- output: perMillion(e.output_cost_per_token),
251
- cache_read: perMillion(e.cache_read_input_token_cost),
252
- cache_write: perMillion(
253
- e.cache_write_input_token_cost ??
254
- e.cache_creation_input_token_cost,
255
- ),
256
- },
257
- }
258
- : {}),
259
- ...(e.supports_reasoning === true ? { reasoning: true } : {}),
260
- ...(e.supports_image_input === true || e.supports_vision === true
261
- ? { image_input: true }
262
- : {}),
263
- });
264
- }
265
- return out;
266
- }
267
-
268
- /** Merge supplemented ids into the CLI list. The CLI entry wins on collision. */
269
- export function mergeModels<A extends { id: string }>(
270
- cli: A[],
271
- extra: A[],
272
- ): A[] {
273
- const seen = new Set(cli.map((m) => m.id));
274
- return [...cli, ...extra.filter((m) => !seen.has(m.id))];
275
- }
276
-
277
- /**
278
- * Entry point for the plugin: resolve the feed URL for this project, fetch
279
- * (cached), and return supplementable models. Empty when the feature is off
280
- * or the feed is unreachable and uncached — never throws, never blocks init
281
- * beyond FETCH_TIMEOUT_MS.
282
- *
283
- * cacheDir may be any writable directory; the cache file is named
284
- * datasheet-cache.json so it can never collide with a discovery config file.
285
- */
286
- export async function datasheetSupplement(
287
- root: string,
288
- cacheDir: string,
289
- fetchImpl?: FetchLike,
290
- ): Promise<SupplementalModel[]> {
291
- const url = datasheetUrl(
292
- process.env.GATEWAY_DATASHEET_URL,
293
- process.env.HOME,
294
- root,
295
- );
296
- if (!url) return [];
297
- const body = await fetchDatasheet(
298
- url,
299
- join(cacheDir, "datasheet-cache.json"),
300
- fetchImpl,
301
- );
302
- return body ? parseDatasheet(body) : [];
303
- }