@stablekernel/pi-bifrost 0.11.1 → 0.13.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 +7 -1
- package/package.json +6 -1
- package/src/index.ts +17 -0
- package/src/plugin.test.ts +184 -7
- package/src/prompt-cache.ts +153 -0
- package/src/refresh-project.test.ts +349 -0
- package/src/refresh.test.ts +13 -2
- package/src/refresh.ts +74 -0
package/README.md
CHANGED
|
@@ -9,6 +9,8 @@ Pi extension that registers a [Bifrost](https://docs.getbifrost.ai) LLM gateway
|
|
|
9
9
|
- `bifrost-anthropic` — the Anthropic Messages surface, Claude models only. The Anthropic wire carries prompt-cache control blocks that only Claude accepts, so non-Claude models are registered on the OpenAI surface instead of being listed twice with one copy broken.
|
|
10
10
|
- Fetches each surface's model list, limits and pricing through `gateway-cli models --wire=…` at startup — no catalog is checked in.
|
|
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. Models with effort levels also set `supportsPerMessageEffort` (omp only) so thinking-level changes keep the prompt cache. Cache-keeping has been verified live only on `claude-opus-5-5` through Bifrost; other models remain unverified ([G-012](../../KNOWN-GAPS.md)). Toggle-only reasoning models get no effort map. The default effort itself is pi's own thinking-level default.
|
|
12
|
+
- Adds rolling prompt-cache breakpoints for GPT-6.2 on Bedrock (`bedrock/openai.gpt-6.2-*`). Those models reuse a cached prefix only up to a content block marked `prompt_cache_breakpoint: {mode: "explicit"}`, so without markers every agent turn was a full cache write. A `before_provider_request` hook marks the last input item of each request and the item that ended the previous request; string content on a marked item is sent as a one-block `input_text` list. Other models, 6.0/6.1 included, cache implicitly and are left untouched. Verified live 2026-11-24 on `gpt-6.2-sol` through omp: cache reads per turn went from 0, 0, 0, 0 to 44.5K, 46.0K, 47.6K, 49.0K (about 97% of the prompt).
|
|
13
|
+
- Sets `user` on chat-completions requests to Fireworks models (`fireworks/*`) to a hash of the conversation's first messages, Fireworks' documented session-affinity key (Bifrost forwards it), so a session's turns tend to reach the replica that holds its cached prefix. It is a hint, not a pin: measured live 2026-11-24 on `kimi-k3.1`, follow-up turns that missed the previous prefix fell from 26% to 18% (200 turns each). The rest is Fireworks routing ([G-020](../../KNOWN-GAPS.md)). A `user` the harness already set is kept.
|
|
12
14
|
- 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
15
|
|
|
14
16
|
## `/bifrost-refresh`
|
|
@@ -24,7 +26,11 @@ implementation, one command):
|
|
|
24
26
|
`~/.config/bifrost/keys/default.env`. It then reports how many models the
|
|
25
27
|
gateway offers and which are new or gone against the ids this session
|
|
26
28
|
registered. This mode reports only — it writes nothing, and the key is
|
|
27
|
-
never printed.
|
|
29
|
+
never printed. Project lookup also honors committed `.gateway/shared.json`,
|
|
30
|
+
with personal > shared > user precedence per deployment. A saved project
|
|
31
|
+
selection is the exception: refresh refuses before making a request and
|
|
32
|
+
tells you to install `gateway-cli`, because direct discovery cannot apply
|
|
33
|
+
the project context.
|
|
28
34
|
|
|
29
35
|
Either way the answer arrives as a notification, and any failure is one
|
|
30
36
|
readable line rather than an error thrown into the session.
|
package/package.json
CHANGED
|
@@ -1,7 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@stablekernel/pi-bifrost",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.13.0",
|
|
4
4
|
"description": "Pi extension that registers the Bifrost gateway as a model provider, resolving per-project virtual keys via gateway-cli.",
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "git+https://github.com/stablekernel/gateway.git",
|
|
8
|
+
"directory": "packages/pi-bifrost"
|
|
9
|
+
},
|
|
5
10
|
"type": "module",
|
|
6
11
|
"files": [
|
|
7
12
|
"src",
|
package/src/index.ts
CHANGED
|
@@ -7,6 +7,7 @@ import {
|
|
|
7
7
|
refresh,
|
|
8
8
|
refreshReport,
|
|
9
9
|
} from "./refresh.js";
|
|
10
|
+
import { withCacheBreakpoints, withSessionAffinity } from "./prompt-cache.js";
|
|
10
11
|
|
|
11
12
|
/**
|
|
12
13
|
* Minimal structural type for the part of pi's ExtensionAPI this extension
|
|
@@ -78,6 +79,13 @@ type ProviderConfig = {
|
|
|
78
79
|
type ExtensionAPI = {
|
|
79
80
|
registerProvider(id: string, config: ProviderConfig): void;
|
|
80
81
|
registerCommand(name: string, options: CommandOptions): void;
|
|
82
|
+
/** Same shape in pi (dist/core/extensions/types.d.ts:1203) and omp
|
|
83
|
+
* (src/extensibility/extensions/types.ts:1259): a non-undefined return
|
|
84
|
+
* replaces the provider request payload. */
|
|
85
|
+
on(
|
|
86
|
+
event: "before_provider_request",
|
|
87
|
+
handler: (event: { payload: unknown }) => unknown,
|
|
88
|
+
): void;
|
|
81
89
|
};
|
|
82
90
|
|
|
83
91
|
/** What this extension passes to `registerCommand`; both harnesses accept it. */
|
|
@@ -236,6 +244,15 @@ export default async function (pi: ExtensionAPI): Promise<void> {
|
|
|
236
244
|
: {}),
|
|
237
245
|
});
|
|
238
246
|
}
|
|
247
|
+
|
|
248
|
+
// GPT-6.2 on Bedrock reuses the prompt cache only at explicit markers;
|
|
249
|
+
// Fireworks needs a session key to keep a conversation on one cache
|
|
250
|
+
// replica. See ./prompt-cache.ts. Every other payload comes back as the
|
|
251
|
+
// same reference.
|
|
252
|
+
pi.on("before_provider_request", (event) => {
|
|
253
|
+
const next = withSessionAffinity(withCacheBreakpoints(event.payload));
|
|
254
|
+
return next === event.payload ? undefined : next;
|
|
255
|
+
});
|
|
239
256
|
}
|
|
240
257
|
|
|
241
258
|
/**
|
package/src/plugin.test.ts
CHANGED
|
@@ -104,47 +104,59 @@ type Command = {
|
|
|
104
104
|
};
|
|
105
105
|
|
|
106
106
|
/** Everything the extension handed the harness while loading. */
|
|
107
|
-
type Harness = {
|
|
107
|
+
type Harness = {
|
|
108
|
+
registered: Registered[];
|
|
109
|
+
commands: Command[];
|
|
110
|
+
/** before_provider_request handlers, in registration order. */
|
|
111
|
+
requestHooks: Array<(event: { payload: unknown }) => unknown>;
|
|
112
|
+
};
|
|
108
113
|
|
|
109
114
|
async function runHarness(): Promise<Harness> {
|
|
110
115
|
const registered: Registered[] = [];
|
|
111
116
|
const commands: Command[] = [];
|
|
117
|
+
const requestHooks: Harness["requestHooks"] = [];
|
|
112
118
|
const pi = {
|
|
113
119
|
registerProvider: (id: string, config: any) =>
|
|
114
120
|
registered.push({ id, config }),
|
|
115
121
|
registerCommand: (name: string, options: Omit<Command, "name">) =>
|
|
116
122
|
commands.push({ name, ...options }),
|
|
123
|
+
on: (event: string, handler: Harness["requestHooks"][number]) => {
|
|
124
|
+
if (event === "before_provider_request") requestHooks.push(handler);
|
|
125
|
+
},
|
|
117
126
|
};
|
|
118
127
|
// Fresh import each time so the mocked module is picked up.
|
|
119
128
|
const mod = await import(`./index.js?${Math.random()}`);
|
|
120
129
|
await mod.default(pi as never);
|
|
121
|
-
return { registered, commands };
|
|
130
|
+
return { registered, commands, requestHooks };
|
|
122
131
|
}
|
|
123
132
|
|
|
124
133
|
async function runExtension(): Promise<Registered[]> {
|
|
125
134
|
return (await runHarness()).registered;
|
|
126
135
|
}
|
|
127
136
|
|
|
128
|
-
/**
|
|
137
|
+
/** Process state as the suite found it, restored after each test. */
|
|
129
138
|
const ORIGINAL_HOME = process.env.HOME;
|
|
139
|
+
const ORIGINAL_CWD = process.cwd();
|
|
130
140
|
|
|
131
141
|
/** fetch as the suite found it, restored after each test. */
|
|
132
142
|
const ORIGINAL_FETCH = globalThis.fetch;
|
|
133
143
|
|
|
134
144
|
/** 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"];
|
|
145
|
+
const REFRESH_ENV = ["BIFROST_GATEWAY_URL", "BIFROST_DISCOVERY_URL", "BIFROST_VK", "XDG_CONFIG_HOME"];
|
|
136
146
|
const ORIGINAL_ENV: Record<string, string | undefined> = {};
|
|
137
147
|
for (const name of REFRESH_ENV) ORIGINAL_ENV[name] = process.env[name];
|
|
138
148
|
|
|
139
149
|
beforeEach(() => {
|
|
140
|
-
//
|
|
141
|
-
|
|
142
|
-
process.env.HOME =
|
|
150
|
+
// An empty temp HOME and cwd keep real user and repo config out of tests.
|
|
151
|
+
const home = mkdtempSync(join(tmpdir(), "gw-home-"));
|
|
152
|
+
process.env.HOME = home;
|
|
153
|
+
process.chdir(home);
|
|
143
154
|
// The CLI-less refresh path reads these; the tests that need them set them.
|
|
144
155
|
for (const name of REFRESH_ENV) delete process.env[name];
|
|
145
156
|
});
|
|
146
157
|
|
|
147
158
|
afterEach(() => {
|
|
159
|
+
process.chdir(ORIGINAL_CWD);
|
|
148
160
|
mock.restore();
|
|
149
161
|
globalThis.fetch = ORIGINAL_FETCH;
|
|
150
162
|
for (const name of REFRESH_ENV) {
|
|
@@ -637,3 +649,168 @@ describe("bifrost-refresh command", () => {
|
|
|
637
649
|
expect(printed).toEqual(["bifrost models: sync exploded"]);
|
|
638
650
|
});
|
|
639
651
|
});
|
|
652
|
+
|
|
653
|
+
describe("GPT-6.2 prompt-cache breakpoints", () => {
|
|
654
|
+
const MARK = { mode: "explicit" };
|
|
655
|
+
const SOL = "bedrock/openai.gpt-6.2-sol";
|
|
656
|
+
const sys = { role: "developer", content: "You are a coding agent." };
|
|
657
|
+
const user = (text: string) => ({
|
|
658
|
+
role: "user",
|
|
659
|
+
content: [{ type: "input_text", text }],
|
|
660
|
+
});
|
|
661
|
+
const call = (id: string) => ({
|
|
662
|
+
type: "function_call",
|
|
663
|
+
call_id: id,
|
|
664
|
+
name: "read",
|
|
665
|
+
arguments: "{}",
|
|
666
|
+
});
|
|
667
|
+
const result = (id: string, output: unknown) => ({
|
|
668
|
+
type: "function_call_output",
|
|
669
|
+
call_id: id,
|
|
670
|
+
output,
|
|
671
|
+
});
|
|
672
|
+
const reply = {
|
|
673
|
+
type: "message",
|
|
674
|
+
role: "assistant",
|
|
675
|
+
content: [{ type: "output_text", text: "done" }],
|
|
676
|
+
};
|
|
677
|
+
|
|
678
|
+
/** The payload after the extension's registered request hook. */
|
|
679
|
+
async function hooked(payload: unknown): Promise<unknown> {
|
|
680
|
+
mockCLI(OK_CLI);
|
|
681
|
+
const { requestHooks } = await runHarness();
|
|
682
|
+
expect(requestHooks).toHaveLength(1);
|
|
683
|
+
return requestHooks[0]({ payload });
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
test("first turn marks only the final input item", async () => {
|
|
687
|
+
const out = (await hooked({ model: SOL, input: [sys, user("hi")] })) as any;
|
|
688
|
+
expect(out.input[1].content[0].prompt_cache_breakpoint).toEqual(MARK);
|
|
689
|
+
expect(out.input[0]).toBe(sys); // nothing before the latest run
|
|
690
|
+
});
|
|
691
|
+
|
|
692
|
+
test("tool turn marks the new output and the previous request's end", async () => {
|
|
693
|
+
const input = [sys, user("hi"), call("a"), result("a", "file body")];
|
|
694
|
+
const out = (await hooked({ model: SOL, input })) as any;
|
|
695
|
+
expect(out.input[3].output).toEqual([
|
|
696
|
+
{ type: "input_text", text: "file body", prompt_cache_breakpoint: MARK },
|
|
697
|
+
]);
|
|
698
|
+
expect(out.input[1].content[0].prompt_cache_breakpoint).toEqual(MARK);
|
|
699
|
+
expect(out.input[0]).toBe(sys);
|
|
700
|
+
// The session's own transcript is not rewritten under it.
|
|
701
|
+
expect(input[3]).toEqual(result("a", "file body"));
|
|
702
|
+
expect((input[1] as any).content[0].prompt_cache_breakpoint).toBeUndefined();
|
|
703
|
+
});
|
|
704
|
+
|
|
705
|
+
test("parallel tool outputs: the boundary is before the model's calls", async () => {
|
|
706
|
+
const input = [
|
|
707
|
+
sys,
|
|
708
|
+
user("hi"),
|
|
709
|
+
call("a"),
|
|
710
|
+
call("b"),
|
|
711
|
+
result("a", "A"),
|
|
712
|
+
result("b", "B"),
|
|
713
|
+
];
|
|
714
|
+
const out = (await hooked({ model: SOL, input })) as any;
|
|
715
|
+
expect(out.input[5].output[0].prompt_cache_breakpoint).toEqual(MARK);
|
|
716
|
+
expect(out.input[4]).toBe(input[4]); // same request's run: one marker only
|
|
717
|
+
expect(out.input[1].content[0].prompt_cache_breakpoint).toEqual(MARK);
|
|
718
|
+
});
|
|
719
|
+
|
|
720
|
+
test("a third turn rolls both markers forward", async () => {
|
|
721
|
+
const input = [
|
|
722
|
+
sys,
|
|
723
|
+
user("hi"),
|
|
724
|
+
call("a"),
|
|
725
|
+
result("a", "A"),
|
|
726
|
+
reply,
|
|
727
|
+
user("next"),
|
|
728
|
+
];
|
|
729
|
+
const out = (await hooked({ model: SOL, input })) as any;
|
|
730
|
+
expect(out.input[5].content[0].prompt_cache_breakpoint).toEqual(MARK);
|
|
731
|
+
expect(out.input[3].output[0].prompt_cache_breakpoint).toEqual(MARK);
|
|
732
|
+
expect(out.input[1]).toBe(input[1]); // two turns back: unmarked again
|
|
733
|
+
});
|
|
734
|
+
|
|
735
|
+
test("marks the last cacheable block and keeps an existing marker's ttl", async () => {
|
|
736
|
+
const own = { mode: "explicit", ttl: "30m" };
|
|
737
|
+
const msg = {
|
|
738
|
+
role: "user",
|
|
739
|
+
content: [
|
|
740
|
+
{ type: "input_text", text: "a", prompt_cache_breakpoint: own },
|
|
741
|
+
{ type: "input_image", image_url: "data:x" },
|
|
742
|
+
{ type: "output_text", text: "not cacheable" },
|
|
743
|
+
],
|
|
744
|
+
};
|
|
745
|
+
const out = (await hooked({ model: SOL, input: [msg] })) as any;
|
|
746
|
+
expect(out.input[0].content[1].prompt_cache_breakpoint).toEqual(MARK);
|
|
747
|
+
expect(out.input[0].content[2]).toBe(msg.content[2]);
|
|
748
|
+
|
|
749
|
+
const first = {
|
|
750
|
+
role: "user",
|
|
751
|
+
content: [{ type: "input_text", text: "a", prompt_cache_breakpoint: own }],
|
|
752
|
+
};
|
|
753
|
+
const kept = (await hooked({ model: SOL, input: [first] })) as any;
|
|
754
|
+
expect(kept.input[0].content[0].prompt_cache_breakpoint).toBe(own);
|
|
755
|
+
});
|
|
756
|
+
|
|
757
|
+
test("covers gpt-6.2-astra too", async () => {
|
|
758
|
+
const out = (await hooked({
|
|
759
|
+
model: "bedrock/openai.gpt-6.2-astra",
|
|
760
|
+
input: [user("hi")],
|
|
761
|
+
})) as any;
|
|
762
|
+
expect(out.input[0].content[0].prompt_cache_breakpoint).toEqual(MARK);
|
|
763
|
+
});
|
|
764
|
+
|
|
765
|
+
test("leaves other models and non-Responses payloads untouched", async () => {
|
|
766
|
+
for (const payload of [
|
|
767
|
+
{ model: "bedrock/openai.gpt-6.1-sol", input: [user("hi")] },
|
|
768
|
+
{ model: "bedrock/openai.gpt-6.20-sol", input: [user("hi")] },
|
|
769
|
+
{ model: "openai/gpt-6.2", input: [user("hi")] }, // not Bedrock's id form
|
|
770
|
+
{ model: SOL, messages: [{ role: "user", content: "hi" }] },
|
|
771
|
+
{ model: SOL, input: [reply] }, // nothing the client sent
|
|
772
|
+
{ model: SOL, input: [{ role: "user", content: "" }] },
|
|
773
|
+
"not an object",
|
|
774
|
+
]) {
|
|
775
|
+
expect(await hooked(payload)).toBeUndefined();
|
|
776
|
+
}
|
|
777
|
+
});
|
|
778
|
+
});
|
|
779
|
+
|
|
780
|
+
describe("Fireworks session affinity", () => {
|
|
781
|
+
const KIMI = "fireworks/kimi-k3.1";
|
|
782
|
+
const sys = { role: "system", content: "You are a coding agent." };
|
|
783
|
+
const msg = (role: string, content: string) => ({ role, content });
|
|
784
|
+
|
|
785
|
+
async function hooked(payload: unknown): Promise<any> {
|
|
786
|
+
mockCLI(OK_CLI);
|
|
787
|
+
const { requestHooks } = await runHarness();
|
|
788
|
+
return requestHooks[0]({ payload });
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
test("one conversation keeps one user key across turns; another gets its own", async () => {
|
|
792
|
+
const first = [sys, msg("user", "fix the bug")];
|
|
793
|
+
const payload: Record<string, unknown> = { model: KIMI, messages: first };
|
|
794
|
+
const turn1 = await hooked(payload);
|
|
795
|
+
const turn3 = await hooked({
|
|
796
|
+
model: KIMI,
|
|
797
|
+
messages: [...first, msg("assistant", "done"), msg("user", "now test it")],
|
|
798
|
+
});
|
|
799
|
+
const other = await hooked({ model: KIMI, messages: [sys, msg("user", "write docs")] });
|
|
800
|
+
expect(turn1.user).toMatch(/^bf-[0-9a-f]{32}$/); // inside Bifrost's 64-char cap
|
|
801
|
+
expect(turn3.user).toBe(turn1.user);
|
|
802
|
+
expect(other.user).not.toBe(turn1.user);
|
|
803
|
+
expect(payload.user).toBeUndefined(); // the session's payload is not mutated
|
|
804
|
+
});
|
|
805
|
+
|
|
806
|
+
test("keeps a caller's own user and leaves other payloads untouched", async () => {
|
|
807
|
+
for (const payload of [
|
|
808
|
+
{ model: KIMI, user: "mine", messages: [msg("user", "hi")] },
|
|
809
|
+
{ model: KIMI, messages: [sys] }, // no user message to key on
|
|
810
|
+
{ model: KIMI, input: [msg("user", "hi")] },
|
|
811
|
+
{ model: "bedrock/moonshotai.kimi-k2.5", messages: [msg("user", "hi")] },
|
|
812
|
+
]) {
|
|
813
|
+
expect(await hooked(payload)).toBeUndefined();
|
|
814
|
+
}
|
|
815
|
+
});
|
|
816
|
+
});
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rolling prompt-cache breakpoints for GPT-6.2 on Bedrock.
|
|
3
|
+
*
|
|
4
|
+
* Bedrock's OpenAI Responses endpoint reuses a cached prefix for GPT-6.2 only
|
|
5
|
+
* up to a content block marked `prompt_cache_breakpoint: {mode: "explicit"}`;
|
|
6
|
+
* an unmarked request that extends an earlier one reads nothing back and is
|
|
7
|
+
* billed as a full cache write. GPT-6.0/6.1 on the same route cache
|
|
8
|
+
* implicitly, so they are left alone. Measured live 2026-11-24: with no
|
|
9
|
+
* markers an agent loop read 0 tokens per turn; with one marker on the last
|
|
10
|
+
* input item of this request and one on the item that ended the previous
|
|
11
|
+
* request, reads rose turn over turn at about 95% of the prompt.
|
|
12
|
+
*
|
|
13
|
+
* The previous request's end is found without state: in a replayed
|
|
14
|
+
* transcript it is the last input item before the model's latest output
|
|
15
|
+
* (assistant message, function call, reasoning). Marking it again means the
|
|
16
|
+
* cache entry the previous request wrote is read back; marking the end of
|
|
17
|
+
* this request writes the entry the next request will read.
|
|
18
|
+
*
|
|
19
|
+
* Also: Fireworks session affinity (`withSessionAffinity`, at the end).
|
|
20
|
+
*
|
|
21
|
+
* Kept byte-identical between packages/pi-bifrost and packages/opencode-bifrost
|
|
22
|
+
* (`make vet` fails on drift), like refresh.ts.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
import { createHash } from "node:crypto";
|
|
26
|
+
|
|
27
|
+
/** Bedrock GPT-6.2 ids ("bedrock/openai.gpt-6.2-sol"), not 6.0/6.1 and not
|
|
28
|
+
* the slash form other routers use for OpenAI's own endpoint. */
|
|
29
|
+
const BEDROCK_GPT_62 = /(?:^|\/)openai\.gpt-6\.2(?!\d)/;
|
|
30
|
+
|
|
31
|
+
// Sets, not Records: these test wire strings, and a Record lookup would
|
|
32
|
+
// accept prototype keys such as "constructor".
|
|
33
|
+
const CACHEABLE_BLOCK = new Set(["input_text", "input_image", "input_file"]);
|
|
34
|
+
const INPUT_ROLE = new Set(["user", "developer", "system"]);
|
|
35
|
+
const TOOL_OUTPUT = new Set(["function_call_output", "custom_tool_call_output"]);
|
|
36
|
+
|
|
37
|
+
type Item = Record<string, unknown>;
|
|
38
|
+
|
|
39
|
+
function isRecord(value: unknown): value is Item {
|
|
40
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Items the client sends, as opposed to items the model produced. */
|
|
44
|
+
function isInputItem(item: unknown): item is Item {
|
|
45
|
+
if (!isRecord(item)) return false;
|
|
46
|
+
if (typeof item.type === "string" && TOOL_OUTPUT.has(item.type)) return true;
|
|
47
|
+
return (
|
|
48
|
+
(item.type === undefined || item.type === "message") &&
|
|
49
|
+
typeof item.role === "string" &&
|
|
50
|
+
INPUT_ROLE.has(item.role)
|
|
51
|
+
);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* The content value with its last cacheable block marked, or null when it has
|
|
56
|
+
* none. A string becomes a one-block `input_text` list, the only form a
|
|
57
|
+
* marker can ride on; an existing marker (with its own ttl) is kept.
|
|
58
|
+
*/
|
|
59
|
+
function markContent(content: unknown): unknown[] | null {
|
|
60
|
+
if (typeof content === "string") {
|
|
61
|
+
if (content === "") return null;
|
|
62
|
+
return [
|
|
63
|
+
{
|
|
64
|
+
type: "input_text",
|
|
65
|
+
text: content,
|
|
66
|
+
prompt_cache_breakpoint: { mode: "explicit" },
|
|
67
|
+
},
|
|
68
|
+
];
|
|
69
|
+
}
|
|
70
|
+
if (!Array.isArray(content)) return null;
|
|
71
|
+
for (let i = content.length - 1; i >= 0; i--) {
|
|
72
|
+
const block = content[i];
|
|
73
|
+
if (!isRecord(block) || !CACHEABLE_BLOCK.has(block.type as string)) continue;
|
|
74
|
+
const marked = content.slice();
|
|
75
|
+
marked[i] = {
|
|
76
|
+
...block,
|
|
77
|
+
prompt_cache_breakpoint: block.prompt_cache_breakpoint ?? {
|
|
78
|
+
mode: "explicit",
|
|
79
|
+
},
|
|
80
|
+
};
|
|
81
|
+
return marked;
|
|
82
|
+
}
|
|
83
|
+
return null;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** A copy of an input item with a marker on it, or null if it cannot carry one. */
|
|
87
|
+
function markItem(item: Item): Item | null {
|
|
88
|
+
const field = TOOL_OUTPUT.has(item.type as string) ? "output" : "content";
|
|
89
|
+
const marked = markContent(item[field]);
|
|
90
|
+
return marked ? { ...item, [field]: marked } : null;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* A Responses request body with rolling breakpoints added, for Bedrock GPT-6.2
|
|
95
|
+
* models. Any other body is returned as the same reference, untouched; the
|
|
96
|
+
* input body is never mutated.
|
|
97
|
+
*/
|
|
98
|
+
export function withCacheBreakpoints<T>(body: T): T {
|
|
99
|
+
if (!isRecord(body)) return body;
|
|
100
|
+
if (typeof body.model !== "string" || !BEDROCK_GPT_62.test(body.model)) {
|
|
101
|
+
return body;
|
|
102
|
+
}
|
|
103
|
+
if (!Array.isArray(body.input)) return body;
|
|
104
|
+
|
|
105
|
+
const input: unknown[] = body.input;
|
|
106
|
+
const out = input.slice();
|
|
107
|
+
let changed = false;
|
|
108
|
+
let end = input.length - 1;
|
|
109
|
+
// Run 0 is this request's trailing input items; run 1 the previous request's.
|
|
110
|
+
for (let run = 0; run < 2 && end >= 0; run++) {
|
|
111
|
+
while (end >= 0 && !isInputItem(input[end])) end--;
|
|
112
|
+
for (let i = end; i >= 0 && isInputItem(input[i]); i--) {
|
|
113
|
+
const marked = markItem(input[i] as Item);
|
|
114
|
+
if (marked) {
|
|
115
|
+
out[i] = marked;
|
|
116
|
+
changed = true;
|
|
117
|
+
break;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
while (end >= 0 && isInputItem(input[end])) end--;
|
|
121
|
+
}
|
|
122
|
+
return changed ? ({ ...body, input: out } as T) : body;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Fireworks ids as the gateway lists them ("fireworks/kimi-k3.1"). */
|
|
126
|
+
const FIREWORKS = /^fireworks\//;
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* A chat-completions body for a Fireworks model with `user` set to a key
|
|
130
|
+
* stable for the whole conversation. Fireworks caches prompts per replica
|
|
131
|
+
* and uses `user` or the `x-session-affinity` header to send one session's
|
|
132
|
+
* requests to the same replica (docs.fireworks.ai/guides/prompt-caching).
|
|
133
|
+
* Bifrost forwards `user`; the header passes only as `x-bf-eh-…`, which
|
|
134
|
+
* measured no better than nothing. It is a hint, not a pin: measured live
|
|
135
|
+
* 2026-11-24 on kimi-k3.1 over 200 follow-up turns each, 26% landed on a
|
|
136
|
+
* replica without the previous prefix with no key and 18% with it.
|
|
137
|
+
*
|
|
138
|
+
* The key is a hash of every message up to and including the first user
|
|
139
|
+
* message, so it needs no session state and changes only when the prefix it
|
|
140
|
+
* names does. A caller's own `user` is kept. Any other body is returned as
|
|
141
|
+
* the same reference; the input body is never mutated.
|
|
142
|
+
*/
|
|
143
|
+
export function withSessionAffinity<T>(body: T): T {
|
|
144
|
+
if (!isRecord(body) || body.user !== undefined) return body;
|
|
145
|
+
if (typeof body.model !== "string" || !FIREWORKS.test(body.model)) return body;
|
|
146
|
+
if (!Array.isArray(body.messages)) return body;
|
|
147
|
+
const firstUser = body.messages.findIndex((m) => isRecord(m) && m.role === "user");
|
|
148
|
+
if (firstUser < 0) return body;
|
|
149
|
+
const head = JSON.stringify(body.messages.slice(0, firstUser + 1));
|
|
150
|
+
// 32 hex chars: well inside the 64-character cap Bifrost drops longer values at.
|
|
151
|
+
const user = `bf-${createHash("sha256").update(head).digest("hex").slice(0, 32)}`;
|
|
152
|
+
return { ...body, user } as T;
|
|
153
|
+
}
|
|
@@ -0,0 +1,349 @@
|
|
|
1
|
+
import { expect, test } from "bun:test";
|
|
2
|
+
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { refresh, type FetchLike } from "./refresh.js";
|
|
6
|
+
|
|
7
|
+
const INSTALL_MESSAGE =
|
|
8
|
+
"Bifrost project context requires gateway-cli; install gateway-cli and put it on PATH";
|
|
9
|
+
|
|
10
|
+
function fixture() {
|
|
11
|
+
const home = mkdtempSync(join(tmpdir(), "gateway-project-refresh-"));
|
|
12
|
+
const root = join(home, "repo");
|
|
13
|
+
const cwd = join(root, "nested");
|
|
14
|
+
const configHome = join(home, "config");
|
|
15
|
+
mkdirSync(cwd, { recursive: true });
|
|
16
|
+
mkdirSync(join(root, ".gateway"), { recursive: true });
|
|
17
|
+
mkdirSync(join(configHome, "bifrost"), { recursive: true });
|
|
18
|
+
const env: Record<string, string | undefined> = {
|
|
19
|
+
HOME: home,
|
|
20
|
+
XDG_CONFIG_HOME: configHome,
|
|
21
|
+
BIFROST_GATEWAY_URL: "https://gateway.example",
|
|
22
|
+
BIFROST_VK: "sk-bf-fixture",
|
|
23
|
+
};
|
|
24
|
+
const save = (scope: "user" | "repo" | "shared", contents: unknown) => {
|
|
25
|
+
const path =
|
|
26
|
+
scope === "user"
|
|
27
|
+
? join(configHome, "bifrost", "config.json")
|
|
28
|
+
: join(root, ".gateway", scope === "repo" ? "config.json" : "shared.json");
|
|
29
|
+
writeFileSync(
|
|
30
|
+
path,
|
|
31
|
+
typeof contents === "string" ? contents : JSON.stringify(contents),
|
|
32
|
+
);
|
|
33
|
+
};
|
|
34
|
+
const requests: { url: string; headers?: Record<string, string> }[] = [];
|
|
35
|
+
const commands: string[][] = [];
|
|
36
|
+
const fetchImpl: FetchLike = async (url, init) => {
|
|
37
|
+
requests.push({ url, headers: init?.headers });
|
|
38
|
+
return { ok: true, json: async () => ({ data: [{ id: "one" }] }) };
|
|
39
|
+
};
|
|
40
|
+
const exec = async (args: string[]) => {
|
|
41
|
+
commands.push(args);
|
|
42
|
+
return null;
|
|
43
|
+
};
|
|
44
|
+
return {
|
|
45
|
+
home,
|
|
46
|
+
root,
|
|
47
|
+
cwd,
|
|
48
|
+
env,
|
|
49
|
+
save,
|
|
50
|
+
requests,
|
|
51
|
+
commands,
|
|
52
|
+
fetchImpl,
|
|
53
|
+
exec,
|
|
54
|
+
clean: () => rmSync(home, { recursive: true, force: true }),
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
test("repo project selection refuses fallback before any request", async () => {
|
|
59
|
+
const f = fixture();
|
|
60
|
+
try {
|
|
61
|
+
f.save("repo", { bifrost_projects: { prod: { id: "project-1" } } });
|
|
62
|
+
const result = await refresh({
|
|
63
|
+
known: ["old"],
|
|
64
|
+
cwd: f.cwd,
|
|
65
|
+
env: f.env,
|
|
66
|
+
fetchImpl: f.fetchImpl,
|
|
67
|
+
exec: f.exec,
|
|
68
|
+
});
|
|
69
|
+
expect(result.error).toBe(INSTALL_MESSAGE);
|
|
70
|
+
expect(result.live).toEqual([]);
|
|
71
|
+
expect(f.requests).toHaveLength(0);
|
|
72
|
+
} finally {
|
|
73
|
+
f.clean();
|
|
74
|
+
}
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
test("user project selection refuses fallback through either config home", async () => {
|
|
78
|
+
for (const useXdg of [true, false]) {
|
|
79
|
+
const f = fixture();
|
|
80
|
+
try {
|
|
81
|
+
if (useXdg) {
|
|
82
|
+
f.save("user", { bifrost_projects: { prod: { id: "project-1" } } });
|
|
83
|
+
} else {
|
|
84
|
+
f.env.XDG_CONFIG_HOME = undefined;
|
|
85
|
+
const config = join(f.home, ".config", "bifrost");
|
|
86
|
+
mkdirSync(config, { recursive: true });
|
|
87
|
+
writeFileSync(
|
|
88
|
+
join(config, "config.json"),
|
|
89
|
+
JSON.stringify({ bifrost_projects: { prod: { id: "project-1" } } }),
|
|
90
|
+
);
|
|
91
|
+
}
|
|
92
|
+
const result = await refresh({
|
|
93
|
+
known: [],
|
|
94
|
+
cwd: f.cwd,
|
|
95
|
+
env: f.env,
|
|
96
|
+
fetchImpl: f.fetchImpl,
|
|
97
|
+
exec: f.exec,
|
|
98
|
+
});
|
|
99
|
+
expect(result.error).toBe(INSTALL_MESSAGE);
|
|
100
|
+
expect(f.requests).toHaveLength(0);
|
|
101
|
+
} finally {
|
|
102
|
+
f.clean();
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
test("an empty repo record masks a user project selection", async () => {
|
|
108
|
+
const f = fixture();
|
|
109
|
+
try {
|
|
110
|
+
f.save("user", { bifrost_projects: { prod: { id: "user-project" } } });
|
|
111
|
+
f.save("repo", { bifrost_projects: { prod: {} } });
|
|
112
|
+
const result = await refresh({
|
|
113
|
+
known: [],
|
|
114
|
+
cwd: f.cwd,
|
|
115
|
+
env: f.env,
|
|
116
|
+
fetchImpl: f.fetchImpl,
|
|
117
|
+
exec: f.exec,
|
|
118
|
+
});
|
|
119
|
+
expect(result.error).toBeUndefined();
|
|
120
|
+
expect(result.live).toEqual(["one"]);
|
|
121
|
+
expect(f.requests).toHaveLength(1);
|
|
122
|
+
} finally {
|
|
123
|
+
f.clean();
|
|
124
|
+
}
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
test("shared project selection refuses fallback before any request", async () => {
|
|
128
|
+
const f = fixture();
|
|
129
|
+
try {
|
|
130
|
+
f.save("shared", { bifrost_projects: { prod: { id: "shared-project" } } });
|
|
131
|
+
const result = await refresh({
|
|
132
|
+
known: [],
|
|
133
|
+
cwd: f.cwd,
|
|
134
|
+
env: f.env,
|
|
135
|
+
fetchImpl: f.fetchImpl,
|
|
136
|
+
exec: f.exec,
|
|
137
|
+
});
|
|
138
|
+
expect(result.error).toBe(INSTALL_MESSAGE);
|
|
139
|
+
expect(result.live).toEqual([]);
|
|
140
|
+
expect(f.requests).toHaveLength(0);
|
|
141
|
+
} finally {
|
|
142
|
+
f.clean();
|
|
143
|
+
}
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
test("an empty personal record masks a shared project selection", async () => {
|
|
147
|
+
const f = fixture();
|
|
148
|
+
try {
|
|
149
|
+
f.save("user", { bifrost_projects: { prod: { id: "user-project" } } });
|
|
150
|
+
f.save("shared", {
|
|
151
|
+
env: "staging",
|
|
152
|
+
bifrost_projects: { staging: { id: "shared-project" } },
|
|
153
|
+
});
|
|
154
|
+
f.save("repo", { bifrost_projects: { staging: {} } });
|
|
155
|
+
const result = await refresh({
|
|
156
|
+
known: [],
|
|
157
|
+
cwd: f.cwd,
|
|
158
|
+
env: f.env,
|
|
159
|
+
fetchImpl: f.fetchImpl,
|
|
160
|
+
exec: f.exec,
|
|
161
|
+
});
|
|
162
|
+
expect(result.error).toBeUndefined();
|
|
163
|
+
expect(result.live).toEqual(["one"]);
|
|
164
|
+
expect(f.requests).toHaveLength(1);
|
|
165
|
+
} finally {
|
|
166
|
+
f.clean();
|
|
167
|
+
}
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
test("shared config with an unknown field fails closed", async () => {
|
|
171
|
+
const f = fixture();
|
|
172
|
+
try {
|
|
173
|
+
f.save("shared", { key: "not-allowed", bifrost_projects: { prod: {} } });
|
|
174
|
+
const result = await refresh({
|
|
175
|
+
known: [],
|
|
176
|
+
cwd: f.cwd,
|
|
177
|
+
env: f.env,
|
|
178
|
+
fetchImpl: f.fetchImpl,
|
|
179
|
+
exec: f.exec,
|
|
180
|
+
});
|
|
181
|
+
expect(result.error).toBe(INSTALL_MESSAGE);
|
|
182
|
+
expect(result.live).toEqual([]);
|
|
183
|
+
expect(f.requests).toHaveLength(0);
|
|
184
|
+
} finally {
|
|
185
|
+
f.clean();
|
|
186
|
+
}
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
test("a staging-only selection does not block a prod fallback", async () => {
|
|
190
|
+
for (const scope of ["user", "repo"] as const) {
|
|
191
|
+
const f = fixture();
|
|
192
|
+
try {
|
|
193
|
+
f.save(scope, { bifrost_projects: { staging: { id: "stage-project" } } });
|
|
194
|
+
const result = await refresh({
|
|
195
|
+
known: [],
|
|
196
|
+
cwd: f.cwd,
|
|
197
|
+
env: f.env,
|
|
198
|
+
fetchImpl: f.fetchImpl,
|
|
199
|
+
exec: f.exec,
|
|
200
|
+
});
|
|
201
|
+
expect(result.error).toBeUndefined();
|
|
202
|
+
expect(result.live).toEqual(["one"]);
|
|
203
|
+
expect(f.requests).toHaveLength(1);
|
|
204
|
+
} finally {
|
|
205
|
+
f.clean();
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
});
|
|
209
|
+
|
|
210
|
+
test("repo deployment selects the staging project for refusal", async () => {
|
|
211
|
+
const f = fixture();
|
|
212
|
+
try {
|
|
213
|
+
f.save("repo", {
|
|
214
|
+
env: "staging",
|
|
215
|
+
bifrost_projects: { staging: { id: "stage-project" } },
|
|
216
|
+
});
|
|
217
|
+
const result = await refresh({
|
|
218
|
+
known: [],
|
|
219
|
+
cwd: f.cwd,
|
|
220
|
+
env: f.env,
|
|
221
|
+
fetchImpl: f.fetchImpl,
|
|
222
|
+
exec: f.exec,
|
|
223
|
+
});
|
|
224
|
+
expect(result.error).toBe(INSTALL_MESSAGE);
|
|
225
|
+
expect(f.requests).toHaveLength(0);
|
|
226
|
+
} finally {
|
|
227
|
+
f.clean();
|
|
228
|
+
}
|
|
229
|
+
});
|
|
230
|
+
|
|
231
|
+
test("personal deployment overrides shared deployment", async () => {
|
|
232
|
+
const f = fixture();
|
|
233
|
+
try {
|
|
234
|
+
f.save("shared", {
|
|
235
|
+
env: "prod",
|
|
236
|
+
bifrost_projects: { prod: { id: "shared-project" } },
|
|
237
|
+
});
|
|
238
|
+
f.save("repo", { env: "staging", bifrost_projects: { staging: {} } });
|
|
239
|
+
const result = await refresh({
|
|
240
|
+
known: [],
|
|
241
|
+
cwd: f.cwd,
|
|
242
|
+
env: f.env,
|
|
243
|
+
fetchImpl: f.fetchImpl,
|
|
244
|
+
exec: f.exec,
|
|
245
|
+
});
|
|
246
|
+
expect(result.error).toBeUndefined();
|
|
247
|
+
expect(result.live).toEqual(["one"]);
|
|
248
|
+
expect(f.requests).toHaveLength(1);
|
|
249
|
+
} finally {
|
|
250
|
+
f.clean();
|
|
251
|
+
}
|
|
252
|
+
});
|
|
253
|
+
|
|
254
|
+
test("no selection preserves the main-branch request and ignores outer repo configs", async () => {
|
|
255
|
+
const f = fixture();
|
|
256
|
+
try {
|
|
257
|
+
for (const configure of [
|
|
258
|
+
() => {},
|
|
259
|
+
() => f.save("user", { bifrost_projects: { prod: {} } }),
|
|
260
|
+
() => {
|
|
261
|
+
f.save("repo", { bifrost_projects: { prod: { id: "outer" } } });
|
|
262
|
+
f.save("shared", { bifrost_projects: { prod: { id: "outer-shared" } } });
|
|
263
|
+
const nearest = join(f.cwd, ".gateway");
|
|
264
|
+
mkdirSync(nearest);
|
|
265
|
+
writeFileSync(
|
|
266
|
+
join(nearest, "config.json"),
|
|
267
|
+
JSON.stringify({
|
|
268
|
+
headers: { "x-bf-project-id": "legacy", "X-Org": "team" },
|
|
269
|
+
bifrost_projects: { prod: { id: "" }, staging: {} },
|
|
270
|
+
}),
|
|
271
|
+
);
|
|
272
|
+
},
|
|
273
|
+
]) {
|
|
274
|
+
configure();
|
|
275
|
+
const result = await refresh({
|
|
276
|
+
known: ["old"],
|
|
277
|
+
cwd: f.cwd,
|
|
278
|
+
env: f.env,
|
|
279
|
+
fetchImpl: f.fetchImpl,
|
|
280
|
+
exec: f.exec,
|
|
281
|
+
});
|
|
282
|
+
expect(result).toEqual({
|
|
283
|
+
source: "gateway",
|
|
284
|
+
live: ["one"],
|
|
285
|
+
added: ["one"],
|
|
286
|
+
removed: ["old"],
|
|
287
|
+
knownCount: 1,
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
expect(f.commands).toEqual([["sync"], ["sync"], ["sync"]]);
|
|
291
|
+
expect(f.requests).toHaveLength(3);
|
|
292
|
+
for (const request of f.requests) {
|
|
293
|
+
expect(request.url).toBe("https://gateway.example/v1/models");
|
|
294
|
+
expect(request.headers).toEqual({ Authorization: "Bearer sk-bf-fixture" });
|
|
295
|
+
}
|
|
296
|
+
} finally {
|
|
297
|
+
f.clean();
|
|
298
|
+
}
|
|
299
|
+
});
|
|
300
|
+
|
|
301
|
+
test("malformed JSON in any config fails closed with the install message", async () => {
|
|
302
|
+
for (const scope of ["user", "repo", "shared"] as const) {
|
|
303
|
+
const f = fixture();
|
|
304
|
+
try {
|
|
305
|
+
f.save(scope, "{");
|
|
306
|
+
const result = await refresh({
|
|
307
|
+
known: [],
|
|
308
|
+
cwd: f.cwd,
|
|
309
|
+
env: f.env,
|
|
310
|
+
fetchImpl: f.fetchImpl,
|
|
311
|
+
exec: f.exec,
|
|
312
|
+
});
|
|
313
|
+
expect(result.error).toBe(INSTALL_MESSAGE);
|
|
314
|
+
expect(f.requests).toHaveLength(0);
|
|
315
|
+
} finally {
|
|
316
|
+
f.clean();
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
});
|
|
320
|
+
|
|
321
|
+
test("a working CLI still handles a selected project without discovery", async () => {
|
|
322
|
+
const f = fixture();
|
|
323
|
+
try {
|
|
324
|
+
f.save("repo", { bifrost_projects: { prod: { id: "project-1" } } });
|
|
325
|
+
const commands: string[][] = [];
|
|
326
|
+
const result = await refresh({
|
|
327
|
+
known: [],
|
|
328
|
+
cwd: f.cwd,
|
|
329
|
+
env: f.env,
|
|
330
|
+
fetchImpl: f.fetchImpl,
|
|
331
|
+
exec: async (args) => {
|
|
332
|
+
commands.push(args);
|
|
333
|
+
return args[0] === "sync" ? "synced" : null;
|
|
334
|
+
},
|
|
335
|
+
});
|
|
336
|
+
expect(result).toEqual({
|
|
337
|
+
source: "cli",
|
|
338
|
+
live: [],
|
|
339
|
+
added: [],
|
|
340
|
+
removed: [],
|
|
341
|
+
knownCount: 0,
|
|
342
|
+
cliOutput: "synced",
|
|
343
|
+
});
|
|
344
|
+
expect(commands).toEqual([["sync"]]);
|
|
345
|
+
expect(f.requests).toHaveLength(0);
|
|
346
|
+
} finally {
|
|
347
|
+
f.clean();
|
|
348
|
+
}
|
|
349
|
+
});
|
package/src/refresh.test.ts
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
|
-
import { describe, expect, test } from "bun:test";
|
|
1
|
+
import { afterAll, describe, expect, test } from "bun:test";
|
|
2
|
+
import { mkdtempSync, rmSync } from "node:fs";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
2
5
|
import {
|
|
3
6
|
diffModels,
|
|
4
7
|
gatewayFromEnv,
|
|
@@ -80,9 +83,13 @@ describe("liveModelIds and diffModels", () => {
|
|
|
80
83
|
});
|
|
81
84
|
|
|
82
85
|
describe("refresh", () => {
|
|
86
|
+
const cwd = mkdtempSync(join(tmpdir(), "gateway-refresh-test-"));
|
|
87
|
+
afterAll(() => rmSync(cwd, { recursive: true, force: true }));
|
|
88
|
+
|
|
83
89
|
test("the CLI wins when it answers, and no request is made", async () => {
|
|
84
90
|
const { fetchImpl, calls } = stubFetch({});
|
|
85
91
|
const result = await refresh({
|
|
92
|
+
cwd,
|
|
86
93
|
known: ["a"],
|
|
87
94
|
exec: async () => "model selection updated (openai): added 1 new model(s): b",
|
|
88
95
|
fetchImpl,
|
|
@@ -96,6 +103,7 @@ describe("refresh", () => {
|
|
|
96
103
|
test("without the CLI it lists the gateway directly and diffs the session", async () => {
|
|
97
104
|
const { fetchImpl, calls } = stubFetch({ data: [{ id: "a" }, { id: "b" }] });
|
|
98
105
|
const result = await refresh({
|
|
106
|
+
cwd,
|
|
99
107
|
known: ["a", "old"],
|
|
100
108
|
exec: async () => null,
|
|
101
109
|
fetchImpl,
|
|
@@ -115,6 +123,7 @@ describe("refresh", () => {
|
|
|
115
123
|
test("a key file stands in for the environment key", async () => {
|
|
116
124
|
const { fetchImpl } = stubFetch({ data: [{ id: "a" }] });
|
|
117
125
|
const result = await refresh({
|
|
126
|
+
cwd,
|
|
118
127
|
known: ["a"],
|
|
119
128
|
exec: async () => null,
|
|
120
129
|
readKeyFile: () => KEY,
|
|
@@ -126,10 +135,11 @@ describe("refresh", () => {
|
|
|
126
135
|
});
|
|
127
136
|
|
|
128
137
|
test("says what is missing instead of failing silently", async () => {
|
|
129
|
-
const noUrl = await refresh({ known: [], exec: async () => null, env: {} });
|
|
138
|
+
const noUrl = await refresh({ cwd, known: [], exec: async () => null, env: {} });
|
|
130
139
|
expect(noUrl.error).toContain("BIFROST_GATEWAY_URL");
|
|
131
140
|
|
|
132
141
|
const noKey = await refresh({
|
|
142
|
+
cwd,
|
|
133
143
|
known: [],
|
|
134
144
|
exec: async () => null,
|
|
135
145
|
env: { BIFROST_GATEWAY_URL: "https://gw.example" },
|
|
@@ -138,6 +148,7 @@ describe("refresh", () => {
|
|
|
138
148
|
|
|
139
149
|
const { fetchImpl } = stubFetch({}, false);
|
|
140
150
|
const rejected = await refresh({
|
|
151
|
+
cwd,
|
|
141
152
|
known: [],
|
|
142
153
|
exec: async () => null,
|
|
143
154
|
fetchImpl,
|
package/src/refresh.ts
CHANGED
|
@@ -14,6 +14,68 @@
|
|
|
14
14
|
* Byte-identical in packages/pi-bifrost and packages/opencode-bifrost;
|
|
15
15
|
* `make check-refresh-sync` fails the build if they drift.
|
|
16
16
|
*/
|
|
17
|
+
import { readFileSync } from "node:fs";
|
|
18
|
+
import { dirname, join, resolve } from "node:path";
|
|
19
|
+
|
|
20
|
+
type ProjectConfig = {
|
|
21
|
+
env?: string;
|
|
22
|
+
bifrost_projects?: Record<string, { id?: unknown }>;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
const PROJECT_CLI_REQUIRED =
|
|
26
|
+
"Bifrost project context requires gateway-cli; install gateway-cli and put it on PATH";
|
|
27
|
+
|
|
28
|
+
function readProjectConfig(path: string): ProjectConfig | null | undefined {
|
|
29
|
+
try {
|
|
30
|
+
return JSON.parse(readFileSync(path, "utf8")) as ProjectConfig | null;
|
|
31
|
+
} catch (error) {
|
|
32
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
|
|
33
|
+
throw error;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function hasProject(
|
|
38
|
+
config: ProjectConfig | null | undefined,
|
|
39
|
+
deployment: string,
|
|
40
|
+
): boolean {
|
|
41
|
+
const project = config?.bifrost_projects?.[deployment];
|
|
42
|
+
return typeof project?.id === "string" && project.id.length > 0;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function projectSelected(
|
|
46
|
+
cwd: string,
|
|
47
|
+
env: Record<string, string | undefined>,
|
|
48
|
+
): boolean {
|
|
49
|
+
try {
|
|
50
|
+
const base =
|
|
51
|
+
env.XDG_CONFIG_HOME || (env.HOME ? join(env.HOME, ".config") : null);
|
|
52
|
+
const user = base
|
|
53
|
+
? readProjectConfig(join(base, "bifrost", "config.json"))
|
|
54
|
+
: undefined;
|
|
55
|
+
let repo: ProjectConfig | null | undefined;
|
|
56
|
+
let shared: ProjectConfig | null | undefined;
|
|
57
|
+
for (let dir = resolve(cwd); ; dir = dirname(dir)) {
|
|
58
|
+
repo = readProjectConfig(join(dir, ".gateway", "config.json"));
|
|
59
|
+
shared = readProjectConfig(join(dir, ".gateway", "shared.json"));
|
|
60
|
+
if (repo !== undefined || shared !== undefined || dirname(dir) === dir) break;
|
|
61
|
+
}
|
|
62
|
+
if (
|
|
63
|
+
shared &&
|
|
64
|
+
Object.keys(shared).some((field) => field !== "env" && field !== "bifrost_projects")
|
|
65
|
+
) {
|
|
66
|
+
throw new Error("shared config may only contain env and bifrost_projects");
|
|
67
|
+
}
|
|
68
|
+
const deployment = repo?.env || shared?.env || user?.env || "prod";
|
|
69
|
+
for (const config of [repo, shared, user]) {
|
|
70
|
+
if (config?.bifrost_projects && deployment in config.bifrost_projects) {
|
|
71
|
+
return hasProject(config, deployment);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return false;
|
|
75
|
+
} catch {
|
|
76
|
+
return true; // malformed or unreadable config fails closed
|
|
77
|
+
}
|
|
78
|
+
}
|
|
17
79
|
|
|
18
80
|
/** The subcommand name both harnesses register. */
|
|
19
81
|
export const REFRESH_COMMAND = "bifrost-refresh";
|
|
@@ -179,6 +241,8 @@ export async function refresh(opts: {
|
|
|
179
241
|
storedKey?: () => Promise<string | null>;
|
|
180
242
|
fetchImpl?: FetchLike;
|
|
181
243
|
env?: Record<string, string | undefined>;
|
|
244
|
+
/** Same working directory as the normal CLI-backed harness path. */
|
|
245
|
+
cwd?: string;
|
|
182
246
|
}): Promise<RefreshResult> {
|
|
183
247
|
const knownCount = opts.known.length;
|
|
184
248
|
const cliOutput = await opts.exec(["sync"]);
|
|
@@ -189,6 +253,16 @@ export async function refresh(opts: {
|
|
|
189
253
|
}
|
|
190
254
|
|
|
191
255
|
const env = opts.env ?? {};
|
|
256
|
+
if (projectSelected(opts.cwd ?? process.cwd(), env)) {
|
|
257
|
+
return {
|
|
258
|
+
source: "gateway",
|
|
259
|
+
live: [],
|
|
260
|
+
added: [],
|
|
261
|
+
removed: [],
|
|
262
|
+
knownCount,
|
|
263
|
+
error: PROJECT_CLI_REQUIRED,
|
|
264
|
+
};
|
|
265
|
+
}
|
|
192
266
|
const target = gatewayFromEnv(env);
|
|
193
267
|
if (!target) {
|
|
194
268
|
return {
|