repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

feat(klaus): complete SDK integration

252fba0baba64c963766044495cbcd8d5afd1278

Oliver Jan Krylow <oliver@bugabinga.net> ·

SSH signature · not checked

Browse filesCompare with HEAD

Changed files (13)

extensions/klaus/__e2e__/provider-scenarios.test.ts

Modified
405 405 expect(result.metadata).toMatchObject({
406 406 "x-klaus-transport": "claude-agent-sdk",
407 - "x-klaus-sdk-version": "0.3.238",
408 - "x-klaus-claude-version": "2.1.238",
407 + "x-klaus-sdk-version": "0.3.261",
408 + "x-klaus-claude-version": "2.1.261",
410 410 }, 60_000);
822 - const { t, model } = await providerSession("claude-fable-5");
822 + const { t, model } = await providerSession("claude-fable-5-1");
823 823 const complete = (sessionId: string) =>
824 824 t.session.modelRuntime.completeSimple(
825 825 model,
842 842 expect(unknown.usage.cost).toEqual({
843 843 input: 10,
844 844 output: 50,
845 - cacheRead: 1,
845 + cacheRead: 0.25,
846 846 cacheWrite: 12.5,
847 - total: 73.5,
847 + total: 72.75,
849 849 }, 60_000);
962 962 expect(responseStatus).toBe(200);
963 963 expect(responseHeaders).toMatchObject({
964 964 "x-klaus-transport": "claude-agent-sdk",
965 - "x-klaus-sdk-version": "0.3.238",
966 - "x-klaus-claude-version": "2.1.238",
965 + "x-klaus-sdk-version": "0.3.261",
966 + "x-klaus-claude-version": "2.1.261",
968 968 const outbound = server.messageRequests()[0];
969 969 const body = JSON.stringify(outbound?.body);
1060 1060 expect(server.maxActiveMessages).toBeGreaterThanOrEqual(2);
1061 1061 }, 60_000);
1063 - it("warns once per Pi session before Fable requests", async () => {
1064 - await useServer((_request, index, response) =>
1063 + it("targets Fable 5.1 and warns once per Pi session", async () => {
1064 + const server = await useServer((_request, index, response) =>
1065 1065 sse(response, textFrames(index, "fable response")),
1067 - const { t, model } = await providerSession("claude-fable-5");
1067 + const { t, model } = await providerSession("claude-fable-5-1");
1068 1068 for (const prompt of ["first fable", "second fable"]) {
1069 1069 const result = await t.session.modelRuntime.completeSimple(
1074 1074 expect(result.stopReason).toBe("stop");
1077 + expect(server.messageRequests()[0]?.body).toMatchObject({
1078 + model: "claude-fable-5-1",
1079 + });
1077 1080 const warnings = t.events
1078 1081 .uiCallsFor("notify")
1079 1082 .filter((call) => String(call.args[0]).includes("Fable"));
1087 1090 .filter((call) =>
1088 1091 String(call.args[0]).includes("expected Pi system-prompt phrases"),
1090 - expect(promptWarnings).toHaveLength(1);
1091 - expect(promptWarnings[0]?.args[1]).toBe("warning");
1093 + expect(promptWarnings).toHaveLength(0);
1092 1094 }, 60_000);
1094 1096 it("sends exact Pi tool schemas while disabling every Claude built-in tool", async () => {

extensions/klaus/__tests__/cache.test.ts

Modified
207 207 expect(
208 208 JSON.parse(await readFile(join(root, "manifest.json"), "utf8")),
209 - ).toEqual({ schema: 1, sdk: "0.3.238" });
209 + ).toEqual({ schema: 1, sdk: "0.3.261" });
210 210 const transcript = await onlyFile(root, ".ndjson");
211 211 expect(await readFile(transcript, "utf8")).toBe(
212 212 '{"type":"assistant","uuid":"one","payload":"opaque"}\n',
311 311 it.each([
312 - { schema: 2, sdk: "0.3.238" },
313 - { schema: 1, sdk: "0.3.237" },
312 + { schema: 2, sdk: "0.3.261" },
313 + { schema: 1, sdk: "0.3.238" },
316 316 ] as const)("rejects incompatible manifest %j", async (manifest) => {

extensions/klaus/__tests__/debug.test.ts

Modified
33 33 expect(record.timestamp).toEqual(expect.any(String));
36 + it("does not write debug failures into Pi's terminal", async () => {
37 + root = await mkdtemp(join(tmpdir(), "klaus-debug-test-"));
38 + process.env.KLAUS_DEBUG_LOG = root;
39 + const stderr = vi.spyOn(process.stderr, "write");
40 + const { dbg } = await import("../src/debug.js");
42 + dbg?.("test.failure");
44 + expect(stderr).not.toHaveBeenCalled();
45 + stderr.mockRestore();
46 + });
36 48 it("skips argument evaluation when disabled at module load", async () => {
37 49 delete process.env.KLAUS_DEBUG_LOG;
38 50 const { dbg } = await import("../src/debug.js");

extensions/klaus/__tests__/harness.test.ts

Modified
54 54 expect(runtime.getModel("klaus", "default")).toBeUndefined();
57 - it("copies every advertised model capability and rate from Pi's Anthropic catalog", async () => {
57 + it("copies Anthropic model metadata and prices Fable safety fallbacks", async () => {
58 58 t = await createTestSession({ extensionFactories: [klaus] });
59 59 for (const id of Object.keys(MODEL_SELECTORS)) {
60 60 const source = getBuiltinModel("anthropic", id);
70 70 contextWindow: source?.contextWindow,
71 71 maxTokens: source?.maxTokens,
73 - expect(projected?.compat).toEqual(source?.compat);
73 + expect(projected?.compat).toEqual(
74 + id === "claude-fable-5-1"
75 + ? {
76 + ...source?.compat,
77 + allowedFallbackModels: [
78 + {
79 + provider: "anthropic",
80 + model: "claude-opus-4-8",
81 + cost: {
82 + input: 5,
83 + output: 25,
84 + cacheRead: 0.5,
85 + cacheWrite: 6.25,
86 + },
87 + },
88 + {
89 + provider: "anthropic",
90 + model: "claude-opus-5",
91 + cost: {
92 + input: 5,
93 + output: 25,
94 + cacheRead: 0.5,
95 + cacheWrite: 6.25,
96 + },
97 + },
98 + ],
99 + }
100 + : source?.compat,
101 + );

extensions/klaus/__tests__/subscription-prompt.test.ts

Modified
40 40 expect(warnings).toEqual([]);
43 - it("warns when expected phrases are absent", () => {
43 + it("does not warn for an intentional custom prompt", () => {
44 44 const custom = request();
45 45 custom.systemPrompt = "Custom system prompt.";
46 46 const warnings: string[] = [];
49 49 rewriteSubscriptionPrompt(custom, (message) => warnings.push(message))
50 50 .systemPrompt,
51 51 ).toBe(custom.systemPrompt);
52 + expect(warnings).toEqual([]);
53 + });
55 + it("warns when the recognizable Pi prompt loses both phrases", () => {
56 + const changed = request();
57 + changed.systemPrompt = "Pi documentation changed upstream.";
58 + const warnings: string[] = [];
60 + rewriteSubscriptionPrompt(changed, (message) => warnings.push(message));
52 62 expect(warnings).toEqual([
53 63 'Klaus did not find expected Pi system-prompt phrases: "asks about pi itself", "pi packages". Subscription routing may fail after upstream prompt changes.',

extensions/klaus/index.ts

Modified
1 -import type { Api, Model } from "@earendil-works/pi-ai";
1 +import type {
2 + AnthropicMessagesCompat,
3 + Api,
4 + Model,
5 +} from "@earendil-works/pi-ai";
2 6 import { getBuiltinModel } from "@earendil-works/pi-ai/providers/all";
3 7 import type {
4 8 ExtensionAPI,
14 18 } from "./src/protocol.js";
16 20 const MODEL_IDS = Object.keys(MODEL_SELECTORS) as KlausModelId[];
21 +const FABLE_FALLBACK_IDS = ["claude-opus-4-8", "claude-opus-5"] as const;
17 22 dbg?.("index.module", { modelIds: MODEL_IDS });
19 24 function projectModel(model: Model<Api>): ProviderModelConfig {
20 25 dbg?.("index.projectModel", { provider: model.provider, modelId: model.id });
26 + const compat =
27 + model.id === "claude-fable-5-1"
28 + ? ({
29 + ...(structuredClone(model.compat) as AnthropicMessagesCompat),
30 + allowedFallbackModels: FABLE_FALLBACK_IDS.flatMap((id) => {
31 + const fallback = getBuiltinModel("anthropic", id);
32 + return fallback
33 + ? [
34 + {
35 + provider: "anthropic",
36 + model: id,
37 + cost: structuredClone(fallback.cost),
38 + },
39 + ]
40 + : [];
41 + }),
42 + } satisfies AnthropicMessagesCompat)
43 + : structuredClone(model.compat);
21 44 return {
22 45 id: model.id,
23 46 name: model.name,
25 48 thinkingLevelMap: model.thinkingLevelMap,
26 49 input: [...model.input],
27 50 cost: structuredClone(model.cost),
28 - compat: structuredClone(model.compat),
51 + compat,
29 52 contextWindow: model.contextWindow,
30 53 maxTokens: model.maxTokens,
73 96 if (!token)
74 97 throw new Error("Pi could not resolve Anthropic OAuth for Klaus.");
75 - if (modelId === "claude-fable-5" && !warnedFable) {
98 + if (modelId === "claude-fable-5-1" && !warnedFable) {
76 99 dbg?.("index.oauth.fableWarning");
77 100 warnedFable = true;
78 101 context.ui.notify(

extensions/klaus/src/cache.ts

Modified
9 9 } from "node:fs/promises";
10 10 import { join } from "node:path";
11 11 import { dbg } from "./debug.js";
12 +import { SDK_VERSION } from "./protocol.js";
13 14 export interface StoreKey {
14 15 projectKey: string;
274 275 typeof value !== "object" ||
275 276 value === null ||
276 277 (value as { schema?: unknown }).schema !== 1 ||
277 - (value as { sdk?: unknown }).sdk !== "0.3.238"
278 + (value as { sdk?: unknown }).sdk !== SDK_VERSION
279 280 throw new Error("Klaus cache requires a tested migration.");
284 285 if (existing.length > 0) {
285 286 throw new Error("Klaus cache requires a tested migration.");
287 - await writeFile(path, JSON.stringify({ schema: 1, sdk: "0.3.238" }), {
288 + await writeFile(path, JSON.stringify({ schema: 1, sdk: SDK_VERSION }), {
288 289 mode: 0o600,

extensions/klaus/src/coordinator.ts

Modified
29 29 MODEL_SELECTORS,
30 30 modelFacingContent,
31 31 requiredConstrainedTool,
32 + SDK_VERSION,
32 33 toKlausTools,
33 34 } from "./protocol.js";
34 35 import { replayImages, replayPrompt } from "./replay.js";
364 365 this.cacheReady = Promise.resolve();
365 366 return this.cacheReady;
367 - const store = new FileSessionStore(join(scope.dir, ".klaus", "sessions"));
368 + const store = new FileSessionStore(
369 + join(scope.dir, ".klaus", SDK_VERSION, "sessions"),
370 + );
368 371 this.diskStores.set(scope.id, store);
369 372 this.cacheReady = store.prepare();
370 373 return this.cacheReady;
917 920 persisted: scope?.persisted,
919 922 return sessionId && scope?.id === sessionId && scope.persisted
920 - ? join(scope.dir, ".klaus", "checkpoints")
923 + ? join(scope.dir, ".klaus", SDK_VERSION, "checkpoints")
921 924 : undefined;
928 931 if (scope?.id === sessionId && scope.persisted) {
929 932 const existing = this.diskStores.get(sessionId);
930 933 if (existing) return existing;
931 - const store = new FileSessionStore(join(scope.dir, ".klaus", "sessions"));
934 + const store = new FileSessionStore(
935 + join(scope.dir, ".klaus", SDK_VERSION, "sessions"),
936 + );
932 937 this.diskStores.set(sessionId, store);
933 938 return store;

extensions/klaus/src/debug.ts

Modified
18 18 })}\n`,
19 19 { encoding: "utf8", mode: 0o600 },
21 - } catch (error) {
22 - process.stderr.write(
23 - `Klaus dbg failed: ${error instanceof Error ? error.message : String(error)}\n`,
24 - );
21 + } catch {
22 + // Debug logging must never write into Pi's terminal UI.
27 25 : undefined;

extensions/klaus/src/protocol.ts

Modified
13 13 import { dbg } from "./debug.js";
15 15 export const KLAUS_API = "klaus-agent-sdk";
16 -export const SDK_VERSION = "0.3.238";
17 -export const CLAUDE_VERSION = "2.1.238";
16 +export const SDK_VERSION = "0.3.261";
17 +export const CLAUDE_VERSION = "2.1.261";
19 19 export const MODEL_SELECTORS = {
20 - "claude-fable-5": "fable",
20 + "claude-fable-5-1": "fable",
21 21 "claude-haiku-4-5": "haiku",
22 22 "claude-opus-5": "opus",
23 23 "claude-sonnet-5": "sonnet",

extensions/klaus/src/runtime/android.ts

Modified
21 21 const execFileAsync = promisify(execFile);
22 22 const PACKAGE = "@anthropic-ai/claude-agent-sdk-linux-arm64";
23 23 const EXPECTED_SHA256 =
24 - "28d736120a6b14c5eae1ad1470e73371818c9c2fa41e0b3c7040207aa2d4edee";
24 + "7bbed5a9b0fc2e4ec67bad3490d06ca91b86d6b037d47520b7898951757d1b8a";
26 26 function stateRoot(): string {
27 27 const root = join(

extensions/klaus/src/runtime/standard.ts

Modified
14 14 const CHECKSUMS: Record<string, string> = {
15 15 "darwin-arm64":
16 - "1c196c456373b57818ae87df84aecee96cb659448c0d6a6bbb401ac5758431b2",
16 + "5efecaff231b798be3c66def9be54183623b328b80eaef17f93c43987024e82a",
17 17 "darwin-x64":
18 - "d10bc7bb1720435f8830aa3ee74085f09348d2b1a2a152bdee251b770d76cc73",
18 + "2cbc002b32778bd70aa2e668ada920c54d9aacd91b71dbd5619c01ca148ae533",
19 19 "linux-arm64":
20 - "28d736120a6b14c5eae1ad1470e73371818c9c2fa41e0b3c7040207aa2d4edee",
20 + "7bbed5a9b0fc2e4ec67bad3490d06ca91b86d6b037d47520b7898951757d1b8a",
21 21 "linux-arm64-musl":
22 - "a47d45149ea7c74e4474bce3c7628c4643b0541801b42053d6e26fd5e3203fdd",
22 + "53b58ffbeb3f9325f0ca5eb54fd03cd0346bd197328fa1e68a700ac8e097e6c1",
23 23 "linux-x64":
24 - "0933b286cf94e1b2504b35ac165ab76b8f822735d53371c56393988c23040d58",
24 + "4ae40dd1784e85753e742e09f267d29ecbb82890361ad3817d27560866d364a6",
25 25 "linux-x64-musl":
26 - "33546c2f7947bbfdb46a969123c5329e607c414045cd3645a29aa3cfe023c6ab",
26 + "df6502c5978420d71fb32fe41b4ca956a7eb3f6245fc11a03ca2cde7f03b8f93",
27 27 "win32-arm64":
28 - "645800d24201c93e5fd6f4308e0292bba9a75900693667401cdffb4361f8e616",
28 + "df26e336df846f4b68edda1021af5aecc1f8172d9f045ee33a480916385b35f9",
29 29 "win32-x64":
30 - "223bc058b5aef48138876e28de5d00387e4fd7362a18e733143bf00819c01aab",
30 + "f2f5d1a155167488aeb32cd263e15436253c7b1681ae147c9e73e4d6bbc3c852",
33 33 let resolution: Promise<string> | undefined;

extensions/klaus/src/subscription-prompt.ts

Modified
5 5 ["asks about pi itself", "asks about this harness"],
6 6 ["pi packages", "harness packages"],
7 7 ] as const;
8 +const PI_SYSTEM_PROMPT_MARKERS = [
9 + "You are an expert coding assistant operating inside pi",
10 + "Pi documentation",
11 +] as const;
9 13 export function rewriteSubscriptionPrompt(
10 14 request: KlausRequest,
11 15 warn: (message: string) => void = () => undefined,
12 16 ): KlausRequest {
13 17 let systemPrompt = request.systemPrompt;
18 + const isPiSystemPrompt = PI_SYSTEM_PROMPT_MARKERS.some((marker) =>
19 + systemPrompt.includes(marker),
20 + );
14 21 const substitutions: Array<(typeof SUBSTITUTIONS)[number]> = [];
15 22 const missing: string[] = [];
16 23 for (const substitution of SUBSTITUTIONS) {
26 33 missing.push(before);
29 - if (missing.length > 0) {
36 + if (missing.length > 0 && isPiSystemPrompt) {
30 37 warn(
31 38 `Klaus did not find expected Pi system-prompt phrase${missing.length === 1 ? "" : "s"}: ${missing.map((phrase) => JSON.stringify(phrase)).join(", ")}. Subscription routing may fail after upstream prompt changes.`,
34 - dbg?.("subscriptionPrompt.rewrite", { substitutions, missing });
41 + dbg?.("subscriptionPrompt.rewrite", {
42 + isPiSystemPrompt,
43 + substitutions,
44 + missing,
45 + });
35 46 return { ...request, systemPrompt };