@stablekernel/pi-bifrost 0.11.1 → 0.12.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
@@ -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`
package/package.json CHANGED
@@ -1,7 +1,12 @@
1
1
  {
2
2
  "name": "@stablekernel/pi-bifrost",
3
- "version": "0.11.1",
3
+ "version": "0.12.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
  /**
@@ -104,21 +104,30 @@ type Command = {
104
104
  };
105
105
 
106
106
  /** Everything the extension handed the harness while loading. */
107
- type Harness = { registered: Registered[]; commands: Command[] };
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[]> {
@@ -637,3 +646,168 @@ describe("bifrost-refresh command", () => {
637
646
  expect(printed).toEqual(["bifrost models: sync exploded"]);
638
647
  });
639
648
  });
649
+
650
+ describe("GPT-6.2 prompt-cache breakpoints", () => {
651
+ const MARK = { mode: "explicit" };
652
+ const SOL = "bedrock/openai.gpt-6.2-sol";
653
+ const sys = { role: "developer", content: "You are a coding agent." };
654
+ const user = (text: string) => ({
655
+ role: "user",
656
+ content: [{ type: "input_text", text }],
657
+ });
658
+ const call = (id: string) => ({
659
+ type: "function_call",
660
+ call_id: id,
661
+ name: "read",
662
+ arguments: "{}",
663
+ });
664
+ const result = (id: string, output: unknown) => ({
665
+ type: "function_call_output",
666
+ call_id: id,
667
+ output,
668
+ });
669
+ const reply = {
670
+ type: "message",
671
+ role: "assistant",
672
+ content: [{ type: "output_text", text: "done" }],
673
+ };
674
+
675
+ /** The payload after the extension's registered request hook. */
676
+ async function hooked(payload: unknown): Promise<unknown> {
677
+ mockCLI(OK_CLI);
678
+ const { requestHooks } = await runHarness();
679
+ expect(requestHooks).toHaveLength(1);
680
+ return requestHooks[0]({ payload });
681
+ }
682
+
683
+ test("first turn marks only the final input item", async () => {
684
+ const out = (await hooked({ model: SOL, input: [sys, user("hi")] })) as any;
685
+ expect(out.input[1].content[0].prompt_cache_breakpoint).toEqual(MARK);
686
+ expect(out.input[0]).toBe(sys); // nothing before the latest run
687
+ });
688
+
689
+ test("tool turn marks the new output and the previous request's end", async () => {
690
+ const input = [sys, user("hi"), call("a"), result("a", "file body")];
691
+ const out = (await hooked({ model: SOL, input })) as any;
692
+ expect(out.input[3].output).toEqual([
693
+ { type: "input_text", text: "file body", prompt_cache_breakpoint: MARK },
694
+ ]);
695
+ expect(out.input[1].content[0].prompt_cache_breakpoint).toEqual(MARK);
696
+ expect(out.input[0]).toBe(sys);
697
+ // The session's own transcript is not rewritten under it.
698
+ expect(input[3]).toEqual(result("a", "file body"));
699
+ expect((input[1] as any).content[0].prompt_cache_breakpoint).toBeUndefined();
700
+ });
701
+
702
+ test("parallel tool outputs: the boundary is before the model's calls", async () => {
703
+ const input = [
704
+ sys,
705
+ user("hi"),
706
+ call("a"),
707
+ call("b"),
708
+ result("a", "A"),
709
+ result("b", "B"),
710
+ ];
711
+ const out = (await hooked({ model: SOL, input })) as any;
712
+ expect(out.input[5].output[0].prompt_cache_breakpoint).toEqual(MARK);
713
+ expect(out.input[4]).toBe(input[4]); // same request's run: one marker only
714
+ expect(out.input[1].content[0].prompt_cache_breakpoint).toEqual(MARK);
715
+ });
716
+
717
+ test("a third turn rolls both markers forward", async () => {
718
+ const input = [
719
+ sys,
720
+ user("hi"),
721
+ call("a"),
722
+ result("a", "A"),
723
+ reply,
724
+ user("next"),
725
+ ];
726
+ const out = (await hooked({ model: SOL, input })) as any;
727
+ expect(out.input[5].content[0].prompt_cache_breakpoint).toEqual(MARK);
728
+ expect(out.input[3].output[0].prompt_cache_breakpoint).toEqual(MARK);
729
+ expect(out.input[1]).toBe(input[1]); // two turns back: unmarked again
730
+ });
731
+
732
+ test("marks the last cacheable block and keeps an existing marker's ttl", async () => {
733
+ const own = { mode: "explicit", ttl: "30m" };
734
+ const msg = {
735
+ role: "user",
736
+ content: [
737
+ { type: "input_text", text: "a", prompt_cache_breakpoint: own },
738
+ { type: "input_image", image_url: "data:x" },
739
+ { type: "output_text", text: "not cacheable" },
740
+ ],
741
+ };
742
+ const out = (await hooked({ model: SOL, input: [msg] })) as any;
743
+ expect(out.input[0].content[1].prompt_cache_breakpoint).toEqual(MARK);
744
+ expect(out.input[0].content[2]).toBe(msg.content[2]);
745
+
746
+ const first = {
747
+ role: "user",
748
+ content: [{ type: "input_text", text: "a", prompt_cache_breakpoint: own }],
749
+ };
750
+ const kept = (await hooked({ model: SOL, input: [first] })) as any;
751
+ expect(kept.input[0].content[0].prompt_cache_breakpoint).toBe(own);
752
+ });
753
+
754
+ test("covers gpt-6.2-astra too", async () => {
755
+ const out = (await hooked({
756
+ model: "bedrock/openai.gpt-6.2-astra",
757
+ input: [user("hi")],
758
+ })) as any;
759
+ expect(out.input[0].content[0].prompt_cache_breakpoint).toEqual(MARK);
760
+ });
761
+
762
+ test("leaves other models and non-Responses payloads untouched", async () => {
763
+ for (const payload of [
764
+ { model: "bedrock/openai.gpt-6.1-sol", input: [user("hi")] },
765
+ { model: "bedrock/openai.gpt-6.20-sol", input: [user("hi")] },
766
+ { model: "openai/gpt-6.2", input: [user("hi")] }, // not Bedrock's id form
767
+ { model: SOL, messages: [{ role: "user", content: "hi" }] },
768
+ { model: SOL, input: [reply] }, // nothing the client sent
769
+ { model: SOL, input: [{ role: "user", content: "" }] },
770
+ "not an object",
771
+ ]) {
772
+ expect(await hooked(payload)).toBeUndefined();
773
+ }
774
+ });
775
+ });
776
+
777
+ describe("Fireworks session affinity", () => {
778
+ const KIMI = "fireworks/kimi-k3.1";
779
+ const sys = { role: "system", content: "You are a coding agent." };
780
+ const msg = (role: string, content: string) => ({ role, content });
781
+
782
+ async function hooked(payload: unknown): Promise<any> {
783
+ mockCLI(OK_CLI);
784
+ const { requestHooks } = await runHarness();
785
+ return requestHooks[0]({ payload });
786
+ }
787
+
788
+ test("one conversation keeps one user key across turns; another gets its own", async () => {
789
+ const first = [sys, msg("user", "fix the bug")];
790
+ const payload: Record<string, unknown> = { model: KIMI, messages: first };
791
+ const turn1 = await hooked(payload);
792
+ const turn3 = await hooked({
793
+ model: KIMI,
794
+ messages: [...first, msg("assistant", "done"), msg("user", "now test it")],
795
+ });
796
+ const other = await hooked({ model: KIMI, messages: [sys, msg("user", "write docs")] });
797
+ expect(turn1.user).toMatch(/^bf-[0-9a-f]{32}$/); // inside Bifrost's 64-char cap
798
+ expect(turn3.user).toBe(turn1.user);
799
+ expect(other.user).not.toBe(turn1.user);
800
+ expect(payload.user).toBeUndefined(); // the session's payload is not mutated
801
+ });
802
+
803
+ test("keeps a caller's own user and leaves other payloads untouched", async () => {
804
+ for (const payload of [
805
+ { model: KIMI, user: "mine", messages: [msg("user", "hi")] },
806
+ { model: KIMI, messages: [sys] }, // no user message to key on
807
+ { model: KIMI, input: [msg("user", "hi")] },
808
+ { model: "bedrock/moonshotai.kimi-k2.5", messages: [msg("user", "hi")] },
809
+ ]) {
810
+ expect(await hooked(payload)).toBeUndefined();
811
+ }
812
+ });
813
+ });
@@ -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
+ }