@stablekernel/pi-bifrost 0.2.2 → 0.2.3

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
@@ -11,6 +11,36 @@ 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
+ ## Datasheet supplement (off by default)
15
+
16
+ Wildcard-provider models — e.g. a fresh Fireworks launch that the CLI's
17
+ models.dev source has not cataloged yet — never reach `gateway-cli models`,
18
+ so they cannot be listed here either. When configured, this extension also
19
+ reads the datasheet feed Bifrost itself syncs from and appends the
20
+ wildcard-provider ids the CLI list lacks; CLI-listed ids always win. Applies
21
+ to the OpenAI-compatible surface only; the Anthropic surface stays
22
+ Claude-only.
23
+
24
+ Activation (first wins):
25
+
26
+ 1. env `GATEWAY_DATASHEET_URL`
27
+ 2. `~/.config/bifrost/datasheet.json` — `{"url": "..."}`
28
+ 3. `<project>/.gateway/datasheet.json` — same shape
29
+
30
+ The URL must be `https://`; a source with anything else is treated as absent.
31
+
32
+ Behavior: the feed is fetched once per hour and cached under
33
+ `~/.cache/gateway-bifrost/datasheet-cache.json` (or `$XDG_CACHE_HOME`), with
34
+ a 3s hard timeout and a stale-cache fallback on failure. A failed first
35
+ fetch also triggers a background cache fill, so a slow or cold feed costs
36
+ one session rather than every start. Unconfigured or unreachable, the
37
+ supplement is silently skipped — startup never blocks on it.
38
+
39
+ Provenance: supplement-only models are tagged `limits_source: "datasheet"`
40
+ and `cost_source: "datasheet"` in the `gateway-cli models` payload they ride
41
+ in. The tags stop there — pi's provider config has no provenance field, so
42
+ they are not forwarded into the registered shapes.
43
+
14
44
  ## Requirements
15
45
 
16
46
  - `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.2.2",
3
+ "version": "0.2.3",
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": [
@@ -0,0 +1,305 @@
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("drops non-chat entries, unknown providers, and rows without limits", () => {
58
+ const out = parseDatasheet({
59
+ "fireworks_ai/accounts/fireworks/models/qwen3-embedding-8b": {
60
+ ...glmFlash,
61
+ mode: "embedding",
62
+ },
63
+ "other_provider/some/model": glmFlash,
64
+ "fireworks_ai/accounts/fireworks/models/no-limits": {
65
+ ...glmFlash,
66
+ context_length: undefined,
67
+ },
68
+ "fireworks_ai/accounts/fireworks/models/no-max-out": {
69
+ ...glmFlash,
70
+ max_output_tokens: undefined,
71
+ },
72
+ });
73
+ expect(out).toEqual([]);
74
+ });
75
+
76
+ test("unpriced entry omits cost entirely and falls back to slug name", () => {
77
+ const out = parseDatasheet({
78
+ "fireworks_ai/accounts/fireworks/models/glm-5p3-flash": {
79
+ mode: "chat",
80
+ context_length: 1000,
81
+ max_output_tokens: 100,
82
+ },
83
+ });
84
+ expect(out[0]?.name).toBe("glm-5p3-flash");
85
+ expect(out[0]?.cost).toBeUndefined();
86
+ expect(out[0]?.cost_source).toBeUndefined();
87
+ });
88
+ });
89
+
90
+ describe("mergeModels", () => {
91
+ test("appends ids the CLI list lacks; CLI entry wins on collision", () => {
92
+ // mergeModels is generic over {id: string}: dedup is by id only, so the
93
+ // test uses plain {id, name} literals rather than full model shapes.
94
+ const cli = [
95
+ { id: "a", name: "A" },
96
+ { id: "b", name: "B" },
97
+ ];
98
+ const extra = [
99
+ { id: "b", name: "B-datasheet" },
100
+ { id: "c", name: "C" },
101
+ ];
102
+ expect(mergeModels(cli, extra)).toEqual([
103
+ { id: "a", name: "A" },
104
+ { id: "b", name: "B" },
105
+ { id: "c", name: "C" },
106
+ ]);
107
+ });
108
+ });
109
+
110
+ describe("datasheetUrl", () => {
111
+ const tmp = mkdtempSync(join(tmpdir(), "gw-ds-"));
112
+ const proj = join(tmp, "proj");
113
+ const home = join(tmp, "home");
114
+ mkdirSync(join(proj, ".gateway"), { recursive: true });
115
+ mkdirSync(join(home, ".config", "bifrost"), { recursive: true });
116
+
117
+ test("env var wins over files", () => {
118
+ expect(datasheetUrl("https://env/datasheet", home, proj)).toBe(
119
+ "https://env/datasheet",
120
+ );
121
+ });
122
+
123
+ test("user file beats project file", () => {
124
+ writeFileSync(
125
+ join(home, ".config", "bifrost", "datasheet.json"),
126
+ `{"url": "https://user/datasheet"}`,
127
+ );
128
+ writeFileSync(
129
+ join(proj, ".gateway", "datasheet.json"),
130
+ `{"url": "https://proj/datasheet"}`,
131
+ );
132
+ expect(datasheetUrl(undefined, home, proj)).toBe("https://user/datasheet");
133
+ });
134
+
135
+ test("project file used when user-level absent; null when neither", () => {
136
+ // Self-seeded: does not depend on files written by earlier tests.
137
+ writeFileSync(
138
+ join(proj, ".gateway", "datasheet.json"),
139
+ `{"url": "https://proj/datasheet"}`,
140
+ );
141
+ // a home with no datasheet.json falls through to the project file
142
+ const homeEmpty = join(tmp, "home-empty");
143
+ mkdirSync(homeEmpty, { recursive: true });
144
+ expect(datasheetUrl(undefined, homeEmpty, proj)).toBe(
145
+ "https://proj/datasheet",
146
+ );
147
+ expect(datasheetUrl(undefined, homeEmpty, join(tmp, "other"))).toBeNull();
148
+ });
149
+
150
+ test("non-https URLs are treated as absent and fall through", () => {
151
+ // Feeds steer local model listings, so every source must be TLS: an
152
+ // http:// project file is skipped, and with nothing else yielding a
153
+ // URL the result is null.
154
+ const projHttp = join(tmp, "proj-http");
155
+ mkdirSync(join(projHttp, ".gateway"), { recursive: true });
156
+ writeFileSync(
157
+ join(projHttp, ".gateway", "datasheet.json"),
158
+ `{"url": "http://insecure/datasheet"}`,
159
+ );
160
+ const homeEmpty = join(tmp, "home-empty-http");
161
+ mkdirSync(homeEmpty, { recursive: true });
162
+ expect(datasheetUrl(undefined, homeEmpty, projHttp)).toBeNull();
163
+ // A non-TLS env override likewise falls through to an https file.
164
+ writeFileSync(
165
+ join(projHttp, ".gateway", "datasheet.json"),
166
+ `{"url": "https://proj/datasheet"}`,
167
+ );
168
+ expect(
169
+ datasheetUrl("http://insecure-env/datasheet", homeEmpty, projHttp),
170
+ ).toBe("https://proj/datasheet");
171
+ });
172
+ });
173
+
174
+ describe("fetchDatasheet", () => {
175
+ const tmp = mkdtempSync(join(tmpdir(), "gw-ds-cache-"));
176
+ // Each test gets its own cache file so results never depend on run order.
177
+ const cachePath = (name: string) => join(tmp, `${name}.json`);
178
+ const ok: FetchLike = async () => ({
179
+ ok: true,
180
+ json: async () => ({
181
+ "fireworks_ai/accounts/fireworks/models/glm-5p3-flash": glmFlash,
182
+ }),
183
+ });
184
+ const fail: FetchLike = async () => ({ ok: false, json: async () => ({}) });
185
+
186
+ test("fetches, returns parsed body, writes cache", async () => {
187
+ const body = await fetchDatasheet(
188
+ "https://feed/datasheet",
189
+ cachePath("t1"),
190
+ ok,
191
+ 1000,
192
+ );
193
+ expect(
194
+ body?.["fireworks_ai/accounts/fireworks/models/glm-5p3-flash"],
195
+ ).toBeDefined();
196
+ const cached = JSON.parse(readFileSync(cachePath("t1"), "utf8"));
197
+ expect(cached.fetchedAt).toBe(1000);
198
+ });
199
+
200
+ test("fresh cache short-circuits the fetch", async () => {
201
+ // Seed a cache first so the counting call below has something to hit.
202
+ await fetchDatasheet("https://feed/datasheet", cachePath("t2"), ok, 1000);
203
+ let called = 0;
204
+ const counting: FetchLike = async () => {
205
+ called++;
206
+ return ok("u");
207
+ };
208
+ await fetchDatasheet(
209
+ "https://feed/datasheet",
210
+ cachePath("t2"),
211
+ counting,
212
+ 1000 + 1000,
213
+ );
214
+ expect(called).toBe(0);
215
+ });
216
+
217
+ test("expired cache refetches; fetch failure falls back to stale cache", async () => {
218
+ await fetchDatasheet("https://feed/datasheet", cachePath("t3"), ok, 1000);
219
+ const body = await fetchDatasheet(
220
+ "https://feed/datasheet",
221
+ cachePath("t3"),
222
+ fail,
223
+ 1000 + 3_600_000 + 1,
224
+ );
225
+ expect(
226
+ body?.["fireworks_ai/accounts/fireworks/models/glm-5p3-flash"],
227
+ ).toBeDefined();
228
+ });
229
+
230
+ test("fetch failure with no cache returns null", async () => {
231
+ expect(
232
+ await fetchDatasheet(
233
+ "https://feed/datasheet",
234
+ cachePath("absent"),
235
+ fail,
236
+ 1000,
237
+ ),
238
+ ).toBeNull();
239
+ });
240
+
241
+ test("failed fetch with no cache backfills the cache in the background", async () => {
242
+ const path = cachePath("backfill");
243
+ let calls = 0;
244
+ const flaky: FetchLike = async () => {
245
+ calls++;
246
+ if (calls === 1) throw new Error("cold start");
247
+ return {
248
+ ok: true,
249
+ json: async () => ({
250
+ "fireworks_ai/accounts/fireworks/models/glm-5p3-flash": glmFlash,
251
+ }),
252
+ };
253
+ };
254
+ const first = await fetchDatasheet(
255
+ "https://feed/datasheet",
256
+ path,
257
+ flaky,
258
+ 1000,
259
+ );
260
+ expect(first).toBeNull(); // this session skips the supplement
261
+ // the detached backfill (call 2) lands the cache for the next session
262
+ const deadline = Date.now() + 2000;
263
+ while (Date.now() < deadline) {
264
+ if (existsSync(path)) break;
265
+ await new Promise((r) => setTimeout(r, 25));
266
+ }
267
+ expect(calls).toBe(2);
268
+ const doc = JSON.parse(readFileSync(path, "utf8")) as {
269
+ fetchedAt: number;
270
+ };
271
+ expect(doc.fetchedAt).toBeGreaterThan(1000);
272
+ });
273
+ });
274
+
275
+ describe("end-to-end: CLI payload + datasheet extra -> pi provider models", () => {
276
+ test("supplemented id reaches the provider list with datasheet limits", () => {
277
+ const cliPayload: CliModels = {
278
+ models: [
279
+ {
280
+ id: "accounts/fireworks/models/glm-5p2",
281
+ name: "GLM 5.2",
282
+ context_window: 200000,
283
+ max_output_tokens: 32768,
284
+ limits_source: "gateway",
285
+ },
286
+ ],
287
+ };
288
+ const extra = parseDatasheet({
289
+ "fireworks_ai/accounts/fireworks/models/glm-5p3-flash": glmFlash,
290
+ });
291
+ const merged = mergeModels(cliPayload.models ?? [], extra);
292
+ const piModels = toPiModels({ models: merged }, "openai-completions");
293
+ const flash = piModels.find(
294
+ (m) => m.id === "accounts/fireworks/models/glm-5p3-flash",
295
+ );
296
+ expect(flash).toBeDefined();
297
+ expect(flash?.contextWindow).toBe(1048576);
298
+ expect(flash?.maxTokens).toBe(131072);
299
+ expect(flash?.cost?.input).toBe(0.15);
300
+ // CLI-listed model survives the merge untouched
301
+ expect(
302
+ piModels.find((m) => m.id === "accounts/fireworks/models/glm-5p2"),
303
+ ).toBeDefined();
304
+ });
305
+ });
@@ -0,0 +1,280 @@
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
+ cache_write_input_token_cost?: number;
37
+ supports_reasoning?: boolean;
38
+ };
39
+
40
+ /** A model in the same shape `gateway-cli models` emits (structural subset). */
41
+ export type SupplementalModel = {
42
+ id: string;
43
+ name: string;
44
+ context_window: number;
45
+ max_output_tokens: number;
46
+ limits_source: string;
47
+ cost_source?: string;
48
+ cost?: {
49
+ input: number;
50
+ output: number;
51
+ cache_read: number;
52
+ cache_write: number;
53
+ };
54
+ reasoning?: boolean;
55
+ };
56
+
57
+ /** Datasheet provider prefixes whose entries this module understands. */
58
+ const PROVIDER_PREFIXES = ["fireworks_ai/"];
59
+
60
+ /** How long a fetched feed is reused before refetching. */
61
+ const DATASHEET_TTL_MS = 60 * 60 * 1000;
62
+
63
+ /** Fetch hard timeout: the supplement must never block plugin init long. */
64
+ const FETCH_TIMEOUT_MS = 3000;
65
+
66
+ /** Budget for the background cache fill after a failed fetch: init is never
67
+ * blocked by it, so it can afford to outlast a cold feed start. */
68
+ const BACKFILL_TIMEOUT_MS = 15_000;
69
+
70
+ export type FetchLike = (
71
+ url: string,
72
+ init?: { signal?: AbortSignal },
73
+ ) => Promise<{ ok: boolean; status?: number; json(): Promise<unknown> }>;
74
+
75
+ type CacheDoc = { fetchedAt: number; body: Record<string, DatasheetEntry> };
76
+
77
+ /**
78
+ * Discover the feed URL: env, then user file, then project file. Only
79
+ * https:// URLs are honored; a source with anything else (including a
80
+ * non-TLS env override) falls through to the next candidate.
81
+ */
82
+ export function datasheetUrl(
83
+ env: string | undefined,
84
+ home: string | undefined,
85
+ root: string,
86
+ ): string | null {
87
+ if (env && env.startsWith("https://")) return env;
88
+ const candidates = [
89
+ home ? join(home, ".config", "bifrost", "datasheet.json") : null,
90
+ join(root, ".gateway", "datasheet.json"),
91
+ ];
92
+ for (const p of candidates) {
93
+ if (!p) continue;
94
+ try {
95
+ const parsed = JSON.parse(readFileSync(p, "utf8")) as { url?: unknown };
96
+ if (
97
+ typeof parsed.url === "string" &&
98
+ parsed.url.startsWith("https://")
99
+ ) {
100
+ return parsed.url;
101
+ }
102
+ } catch {
103
+ // absent or malformed: try the next candidate
104
+ }
105
+ }
106
+ return null;
107
+ }
108
+
109
+ function readCache(path: string): CacheDoc | null {
110
+ try {
111
+ const doc = JSON.parse(readFileSync(path, "utf8")) as CacheDoc;
112
+ if (
113
+ typeof doc.fetchedAt === "number" &&
114
+ doc.body &&
115
+ typeof doc.body === "object"
116
+ ) {
117
+ return doc;
118
+ }
119
+ } catch {
120
+ // absent or malformed: treat as no cache
121
+ }
122
+ return null;
123
+ }
124
+
125
+ function writeCache(path: string, doc: CacheDoc): void {
126
+ try {
127
+ mkdirSync(dirname(path), { recursive: true });
128
+ writeFileSync(path, JSON.stringify(doc));
129
+ } catch {
130
+ // cache write failure is non-fatal: refetch next init
131
+ }
132
+ }
133
+
134
+ /**
135
+ * Default fetch adapter: narrows the platform Response to FetchLike's
136
+ * subset so callers can inject a mock without touching the global fetch.
137
+ */
138
+ const defaultFetch: FetchLike = async (u, i) => {
139
+ const resp = await fetch(u, i);
140
+ return { ok: resp.ok, status: resp.status, json: () => resp.json() };
141
+ };
142
+
143
+ /**
144
+ * Fetch the feed, honoring a fresh cache. On fetch failure a stale cache is
145
+ * served; with no cache at all the result is null and the caller skips the
146
+ * supplement. Garbage responses (non-object JSON, HTTP error) are treated
147
+ * as fetch failures so they never poison the cache. A fetch failure with no
148
+ * cache also triggers an unawaited backfill fetch (15s budget) that only
149
+ * writes the cache, so a cold feed costs one session, not one per start.
150
+ */
151
+ export async function fetchDatasheet(
152
+ url: string,
153
+ cachePath: string,
154
+ fetchImpl: FetchLike = defaultFetch,
155
+ now: number = Date.now(),
156
+ ): Promise<Record<string, DatasheetEntry> | null> {
157
+ const cached = readCache(cachePath);
158
+ if (cached && now - cached.fetchedAt < DATASHEET_TTL_MS) return cached.body;
159
+ try {
160
+ const resp = await fetchImpl(url, {
161
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
162
+ });
163
+ if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
164
+ const body = (await resp.json()) as Record<string, DatasheetEntry>;
165
+ if (!body || typeof body !== "object" || Array.isArray(body)) {
166
+ throw new Error("unexpected feed shape");
167
+ }
168
+ writeCache(cachePath, { fetchedAt: now, body });
169
+ return body;
170
+ } catch {
171
+ if (!cached) {
172
+ // Fire-and-forget warm fill: a slow feed (cold start) must not block
173
+ // plugin init, but the next session should find a warm cache. Never
174
+ // awaited; every failure path is swallowed (writeCache guards, and
175
+ // the .catch below covers the rest).
176
+ void fetchImpl(url, {
177
+ signal: AbortSignal.timeout(BACKFILL_TIMEOUT_MS),
178
+ })
179
+ .then(async (resp) => {
180
+ if (!resp.ok) return;
181
+ const body = (await resp.json()) as Record<string, DatasheetEntry>;
182
+ if (body && typeof body === "object" && !Array.isArray(body)) {
183
+ writeCache(cachePath, { fetchedAt: Date.now(), body });
184
+ }
185
+ })
186
+ .catch(() => {});
187
+ }
188
+ return cached?.body ?? null;
189
+ }
190
+ }
191
+
192
+ function perMillion(rate: number | undefined): number {
193
+ return typeof rate === "number" ? Math.round(rate * 1_000_000 * 1e8) / 1e8 : 0;
194
+ }
195
+
196
+ /**
197
+ * Turn feed rows into model entries. Keeps only chat-mode rows under a known
198
+ * provider prefix, requires usable limits, converts per-token rates to
199
+ * per-million (mirroring the CLI's perTokenToPerMTok).
200
+ */
201
+ export function parseDatasheet(
202
+ body: Record<string, DatasheetEntry>,
203
+ ): SupplementalModel[] {
204
+ const out: SupplementalModel[] = [];
205
+ for (const [key, e] of Object.entries(body)) {
206
+ if (!e || typeof e !== "object" || e.mode !== "chat") continue;
207
+ const prefix = PROVIDER_PREFIXES.find((p) => key.startsWith(p));
208
+ if (!prefix) continue;
209
+ const id = key.slice(prefix.length);
210
+ if (!id) continue;
211
+ if (
212
+ typeof e.context_length !== "number" ||
213
+ typeof e.max_output_tokens !== "number"
214
+ ) {
215
+ continue;
216
+ }
217
+ const slug = id.split("/").pop() as string;
218
+ const priced =
219
+ typeof e.input_cost_per_token === "number" ||
220
+ typeof e.output_cost_per_token === "number";
221
+ out.push({
222
+ id,
223
+ name:
224
+ typeof e.base_model === "string" && e.base_model ? e.base_model : slug,
225
+ context_window: e.context_length,
226
+ max_output_tokens: e.max_output_tokens,
227
+ limits_source: "datasheet",
228
+ ...(priced
229
+ ? {
230
+ cost_source: "datasheet",
231
+ cost: {
232
+ input: perMillion(e.input_cost_per_token),
233
+ output: perMillion(e.output_cost_per_token),
234
+ cache_read: perMillion(e.cache_read_input_token_cost),
235
+ cache_write: perMillion(e.cache_write_input_token_cost),
236
+ },
237
+ }
238
+ : {}),
239
+ ...(e.supports_reasoning === true ? { reasoning: true } : {}),
240
+ });
241
+ }
242
+ return out;
243
+ }
244
+
245
+ /** Merge supplemented ids into the CLI list. The CLI entry wins on collision. */
246
+ export function mergeModels<A extends { id: string }>(
247
+ cli: A[],
248
+ extra: A[],
249
+ ): A[] {
250
+ const seen = new Set(cli.map((m) => m.id));
251
+ return [...cli, ...extra.filter((m) => !seen.has(m.id))];
252
+ }
253
+
254
+ /**
255
+ * Entry point for the plugin: resolve the feed URL for this project, fetch
256
+ * (cached), and return supplementable models. Empty when the feature is off
257
+ * or the feed is unreachable and uncached — never throws, never blocks init
258
+ * beyond FETCH_TIMEOUT_MS.
259
+ *
260
+ * cacheDir may be any writable directory; the cache file is named
261
+ * datasheet-cache.json so it can never collide with a discovery config file.
262
+ */
263
+ export async function datasheetSupplement(
264
+ root: string,
265
+ cacheDir: string,
266
+ fetchImpl?: FetchLike,
267
+ ): Promise<SupplementalModel[]> {
268
+ const url = datasheetUrl(
269
+ process.env.GATEWAY_DATASHEET_URL,
270
+ process.env.HOME,
271
+ root,
272
+ );
273
+ if (!url) return [];
274
+ const body = await fetchDatasheet(
275
+ url,
276
+ join(cacheDir, "datasheet-cache.json"),
277
+ fetchImpl,
278
+ );
279
+ return body ? parseDatasheet(body) : [];
280
+ }
package/src/index.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  import { execFileSync } from "node:child_process";
2
+ import { homedir } from "node:os";
3
+ import { datasheetSupplement, mergeModels } from "./datasheet.js";
2
4
 
3
5
  /**
4
6
  * Minimal structural type for the part of pi's ExtensionAPI this extension
@@ -59,6 +61,15 @@ type ExtensionAPI = {
59
61
  /** Overridable so a non-PATH install still works. */
60
62
  const CLI = process.env.GATEWAY_CLI_BIN ?? "gateway-cli";
61
63
 
64
+ /** Where the datasheet feed cache lives for this plugin. */
65
+ function datasheetCacheDir(): string {
66
+ // HOME can be unset or empty in minimal environments; fall back to
67
+ // os.homedir() so the path never degrades to "undefined/.cache".
68
+ const home = process.env.HOME || homedir();
69
+ const base = process.env.XDG_CACHE_HOME ?? `${home}/.cache`;
70
+ return `${base}/gateway-bifrost`;
71
+ }
72
+
62
73
  /**
63
74
  * Suffix for models nothing could price.
64
75
  *
@@ -88,7 +99,7 @@ type Resolution = {
88
99
  * `reasoning_efforts` come from the catalog; absent means nothing advertised
89
100
  * the capability.
90
101
  */
91
- type CliModel = {
102
+ export type CliModel = {
92
103
  id: string;
93
104
  name: string;
94
105
  context_window: number;
@@ -109,7 +120,7 @@ type CliModel = {
109
120
  reasoning_budget_min?: number;
110
121
  };
111
122
 
112
- type CliModels = { models?: CliModel[] };
123
+ export type CliModels = { models?: CliModel[] };
113
124
 
114
125
  type WireSurface = {
115
126
  id: string;
@@ -157,7 +168,7 @@ export default async function (pi: ExtensionAPI): Promise<void> {
157
168
  ];
158
169
 
159
170
  for (const surface of surfaces) {
160
- const models = listModels(surface.wire, surface.api);
171
+ const models = await listModels(surface, info.root);
161
172
  if (models.length === 0) continue;
162
173
 
163
174
  pi.registerProvider(surface.id, {
@@ -280,14 +291,21 @@ function thinkingLevelMap(
280
291
  return map;
281
292
  }
282
293
 
283
- function listModels(
284
- wire: "anthropic" | "openai",
285
- api: "anthropic-messages" | "openai-completions",
286
- ): ProviderModelConfig[] {
287
- const raw = run(["models", `--wire=${wire}`, "--all"]);
294
+ async function listModels(
295
+ surface: WireSurface,
296
+ root: string,
297
+ ): Promise<ProviderModelConfig[]> {
298
+ const raw = run(["models", `--wire=${surface.wire}`, "--all"]);
288
299
  if (!raw) return [];
289
300
  try {
290
- return toPiModels(JSON.parse(raw) as CliModels, api);
301
+ const payload = JSON.parse(raw) as CliModels;
302
+ if (surface.wire === "openai") {
303
+ // Wildcard-provider ids the CLI cannot list yet, from the datasheet
304
+ // feed Bifrost itself syncs from. CLI-listed ids always win.
305
+ const extra = await datasheetSupplement(root, datasheetCacheDir());
306
+ payload.models = mergeModels(payload.models ?? [], extra);
307
+ }
308
+ return toPiModels(payload, surface.api);
291
309
  } catch {
292
310
  return [];
293
311
  }
@@ -1,4 +1,15 @@
1
- import { afterEach, describe, expect, mock, test } from "bun:test";
1
+ import {
2
+ afterEach,
3
+ beforeEach,
4
+ describe,
5
+ expect,
6
+ mock,
7
+ test,
8
+ } from "bun:test";
9
+ import { mkdtempSync } from "node:fs";
10
+ import { tmpdir } from "node:os";
11
+ import { join } from "node:path";
12
+ import type { CliModel } from "./index.js";
2
13
 
3
14
  const RESOLUTION = {
4
15
  env: "prod",
@@ -9,29 +20,6 @@ const RESOLUTION = {
9
20
  headers: { "X-Org-Route": "prod" },
10
21
  };
11
22
 
12
- /** Shape of one model as `gateway-cli models` reports it. */
13
- type CliModel = {
14
- id: string;
15
- name: string;
16
- context_window: number;
17
- max_output_tokens: number;
18
- cost?: {
19
- input: number;
20
- output: number;
21
- cache_read: number;
22
- cache_write: number;
23
- };
24
- limits_source: string;
25
- cost_source?: string;
26
- /** True when the gateway lists the model but it rejects completion on
27
- * this key (not entitled, needs provisioned throughput, retired). */
28
- disabled?: boolean;
29
- /** Reasoning capability and applicable efforts, from the catalog. */
30
- reasoning?: boolean;
31
- reasoning_efforts?: string[];
32
- reasoning_budget_min?: number;
33
- };
34
-
35
23
  function cliPayload(models: CliModel[]): string {
36
24
  return JSON.stringify({
37
25
  wire: "openai-completions",
@@ -107,8 +95,22 @@ async function runExtension(): Promise<Registered[]> {
107
95
  return registered;
108
96
  }
109
97
 
98
+ /** HOME as the suite found it, restored after each test. */
99
+ const ORIGINAL_HOME = process.env.HOME;
100
+
101
+ beforeEach(() => {
102
+ // Registration tests run the real datasheetSupplement. Keep it
103
+ // deterministic and machine-independent: drop the env override and point
104
+ // HOME at an empty temp dir, so neither ~/.config/bifrost/datasheet.json
105
+ // nor the real ~/.cache/gateway-bifrost cache is read or written.
106
+ delete process.env.GATEWAY_DATASHEET_URL;
107
+ process.env.HOME = mkdtempSync(join(tmpdir(), "gw-home-"));
108
+ });
109
+
110
110
  afterEach(() => {
111
111
  mock.restore();
112
+ if (ORIGINAL_HOME === undefined) delete process.env.HOME;
113
+ else process.env.HOME = ORIGINAL_HOME;
112
114
  });
113
115
 
114
116
  describe("provider registration", () => {
@@ -244,6 +246,47 @@ describe("provider registration", () => {
244
246
  });
245
247
  });
246
248
 
249
+ describe("datasheet supplement gate", () => {
250
+ const EXTRA_FLASH = {
251
+ id: "accounts/fireworks/models/glm-5p3-flash",
252
+ name: "glm-5p3-flash",
253
+ context_window: 1048576,
254
+ max_output_tokens: 131072,
255
+ limits_source: "datasheet",
256
+ };
257
+
258
+ test("appends supplement ids on the openai wire only", async () => {
259
+ // Mock the datasheet module the same way child_process is mocked above:
260
+ // registered before the fresh extension import, undone by mock.restore()
261
+ // in afterEach, so the other tests still see the real module.
262
+ mock.module("./datasheet.js", () => ({
263
+ datasheetSupplement: async () => [EXTRA_FLASH],
264
+ // Same CLI-wins dedup as the real mergeModels, inlined to avoid a
265
+ // circular import of the module under mock.
266
+ mergeModels: (
267
+ cli: Array<{ id: string }>,
268
+ extra: Array<{ id: string }>,
269
+ ) => {
270
+ const seen = new Set(cli.map((m) => m.id));
271
+ return [...cli, ...extra.filter((m) => !seen.has(m.id))];
272
+ },
273
+ }));
274
+ mockCLI(OK_CLI);
275
+ const registered = await runExtension();
276
+
277
+ const openai = registered.find((r) => r.id === "bifrost-openai")!;
278
+ const openaiIds = openai.config.models.map((m: { id: string }) => m.id);
279
+ expect(openaiIds).toContain("bedrock/amazon.nova-lite-v1:0");
280
+ expect(openaiIds).toContain(EXTRA_FLASH.id);
281
+
282
+ const anthropic = registered.find((r) => r.id === "bifrost-anthropic")!;
283
+ const anthropicIds = anthropic.config.models.map(
284
+ (m: { id: string }) => m.id,
285
+ );
286
+ expect(anthropicIds).not.toContain(EXTRA_FLASH.id);
287
+ });
288
+ });
289
+
247
290
  describe("unpriced models", () => {
248
291
  test("marks the name rather than advertising a zero rate as free", async () => {
249
292
  // Pi's model shape requires `cost` and defaults it to zeros, which renders