repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

feat(klaus): inherit Pi's Anthropic model settings with SDK-safe bounds

055d55e8483203a9d8c4eda2afb9e5295df00248

Oliver Krylow <o.krylow@isp-insoft.de> ·

SSH signature · not checked

Browse filesCompare with HEAD

Klaus already copied Pi's Anthropic catalog entries, but it copied an overridden context window or output maximum verbatim, and it re-projected the catalog only at session start.

Project models in one tested module: inherit human overrides, keep transport-owned fields out, clamp inherited limits to the builtin catalog value the Claude Agent SDK path can deliver, re-project at each turn boundary, and register only when the projection changed.

Changed files (5)

CHANGELOG.md

Modified
3 3 # Changelog
5 5 ## Unreleased
7 7 - Recover Decay from partial classification with up to two gap-fill rounds over only the missing chunks, tolerate exact duplicate chunk records, and salvage a deterministic summary from ranked atoms when the summarizer fails instead of discarding the whole run to default compaction
8 +- Keep Klaus models in sync with Pi's Anthropic catalog: inherit the human's model overrides, never inherit transport-owned fields, clamp an inherited context window or output maximum to the builtin catalog value the Agent SDK path can actually deliver, re-project the catalog at each turn boundary, and re-register the provider only when the projection changed
8 9 - Expose Klaus tools to Claude under their Pi names instead of the `mcp__klaus__` prefix, while still accepting prefixed names from resumed sessions and older runtimes
9 10 - Stop Klaus from replacing large Pi tool results with a `<persisted-output>` pointer into a deleted temp directory, and isolate the Klaus child from ambient Claude Code context, deferred tool loading, tool backgrounding, and non-streaming retries
10 11 - Capture Klaus tool identities from Claude's `PreToolUse` hook so tool calls keep working when a permission rule answers them without asking Klaus, and truncate tool results at Claude's result-size ceiling instead of losing them to a persisted file

docs/super/specs/2026-08-21-klaus-plan-spec.md

Modified
226 226 - Output metadata.
227 227 - Cost rates and tiers.
229 +The Pi catalog entry includes the human's own model overrides, and Klaus inherits them.
230 +Transport-owned fields are never inherited, because the Claude Agent SDK owns the request: API kind, base URL, request headers, and sampling parameters.
231 +An inherited context window or output-token maximum above the builtin catalog value for the same model is clamped to that value, because header-gated Anthropic API capacity is unreachable through the Agent SDK path.
229 233 A row absent from Pi's catalog is not advertised.
230 -Provider registration is refreshed when Pi replaces or reloads the active session context.
234 +Provider registration is refreshed when Pi replaces or reloads the active session context, and re-evaluated at each turn boundary so a reloaded catalog takes effect within the session.
235 +Registration is repeated only when the projected catalog changed.
232 237 Authenticated SDK discovery is advisory, not the product table.
233 238 It may verify selector resolution and produce warnings, but it must not hide Fable or auto-expose unknown models.

extensions/klaus/__tests__/models.test.ts

Added
new file mode 100644
1 +import type { Api, Model } from "@earendil-works/pi-ai";
2 +import { getBuiltinModel } from "@earendil-works/pi-ai/providers/all";
3 +import { describe, expect, it } from "vitest";
4 +import {
5 + builtinSource,
6 + MODEL_IDS,
7 + modelsSignature,
8 + projectModel,
9 + projectModels,
10 +} from "../src/models";
12 +function anthropic(modelId: string): Model<Api> {
13 + const model = getBuiltinModel("anthropic", modelId);
14 + if (!model) throw new Error(`missing builtin anthropic model ${modelId}`);
15 + return model;
18 +describe("Klaus model projection", () => {
19 + it("advertises every Klaus model from Pi's builtin catalog", () => {
20 + const models = projectModels(builtinSource);
21 + expect(models.map((model) => model.id)).toEqual(MODEL_IDS);
22 + });
24 + it("copies Pi catalog metadata without transport fields", () => {
25 + const source = anthropic("claude-sonnet-5");
26 + const projected = projectModel(source);
27 + expect(projected).toEqual({
28 + id: source.id,
29 + name: source.name,
30 + reasoning: source.reasoning,
31 + thinkingLevelMap: source.thinkingLevelMap,
32 + input: [...source.input],
33 + cost: source.cost,
34 + compat: source.compat,
35 + contextWindow: source.contextWindow,
36 + maxTokens: source.maxTokens,
37 + });
38 + expect(projected).not.toHaveProperty("api");
39 + expect(projected).not.toHaveProperty("baseUrl");
40 + expect(projected).not.toHaveProperty("headers");
41 + expect(projected).not.toHaveProperty("samplingParams");
42 + });
44 + it("inherits user overrides that stay within the builtin baseline", () => {
45 + const baseline = anthropic("claude-opus-5");
46 + const projected = projectModel({
47 + ...baseline,
48 + name: "Opus (work account)",
49 + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
50 + contextWindow: baseline.contextWindow - 1000,
51 + maxTokens: baseline.maxTokens - 1000,
52 + });
53 + expect(projected.name).toBe("Opus (work account)");
54 + expect(projected.cost).toEqual({
55 + input: 0,
56 + output: 0,
57 + cacheRead: 0,
58 + cacheWrite: 0,
59 + });
60 + expect(projected.contextWindow).toBe(baseline.contextWindow - 1000);
61 + expect(projected.maxTokens).toBe(baseline.maxTokens - 1000);
62 + });
64 + it("clamps overrides that exceed what the Agent SDK path can deliver", () => {
65 + const baseline = anthropic("claude-haiku-4-5");
66 + const projected = projectModel({
67 + ...baseline,
68 + contextWindow: 1_000_000,
69 + maxTokens: baseline.maxTokens * 4,
70 + });
71 + expect(projected.contextWindow).toBe(baseline.contextWindow);
72 + expect(projected.maxTokens).toBe(baseline.maxTokens);
73 + });
75 + it("keeps Fable fallback models priced from the builtin catalog", () => {
76 + const projected = projectModel(anthropic("claude-fable-5-1"));
77 + expect(projected.compat).toMatchObject({
78 + allowedFallbackModels: [
79 + {
80 + provider: "anthropic",
81 + model: "claude-opus-4-8",
82 + cost: anthropic("claude-opus-4-8").cost,
83 + },
84 + {
85 + provider: "anthropic",
86 + model: "claude-opus-5",
87 + cost: anthropic("claude-opus-5").cost,
88 + },
89 + ],
90 + });
91 + });
93 + it("does not mutate the Pi catalog entry it projects", () => {
94 + const source = anthropic("claude-fable-5-1");
95 + const before = structuredClone(source);
96 + const projected = projectModel(source);
97 + projected.cost.input = 999;
98 + projected.input.push("image");
99 + expect(source).toEqual(before);
100 + });
102 + it("skips models that Pi's catalog no longer knows", () => {
103 + const models = projectModels((id) =>
104 + id === "claude-haiku-4-5" ? undefined : builtinSource(id),
105 + );
106 + expect(models.map((model) => model.id)).not.toContain("claude-haiku-4-5");
107 + expect(models).toHaveLength(MODEL_IDS.length - 1);
108 + });
110 + it("signs identical projections identically", () => {
111 + expect(modelsSignature(projectModels(builtinSource))).toBe(
112 + modelsSignature(projectModels(builtinSource)),
113 + );
114 + expect(modelsSignature(projectModels(builtinSource))).not.toBe(
115 + modelsSignature(
116 + projectModels((id) =>
117 + id === "claude-opus-5"
118 + ? { ...anthropic(id), name: "renamed" }
119 + : builtinSource(id),
120 + ),
121 + ),
122 + );
123 + });
124 +});

extensions/klaus/index.ts

Modified
1 -import type {
2 - AnthropicMessagesCompat,
3 - Api,
4 - Model,
5 -} from "@earendil-works/pi-ai";
6 -import { getBuiltinModel } from "@earendil-works/pi-ai/providers/all";
7 1 import type {
8 2 ExtensionAPI,
9 3 ExtensionContext,
12 6 import { QueryCoordinator } from "./src/coordinator.js";
13 7 import { dbg } from "./src/debug.js";
14 8 import {
15 - KLAUS_API,
16 - type KlausModelId,
17 - MODEL_SELECTORS,
18 -} from "./src/protocol.js";
9 + builtinSource,
10 + MODEL_IDS,
11 + modelsSignature,
12 + projectModels,
13 +} from "./src/models.js";
14 +import { KLAUS_API } from "./src/protocol.js";
19 15 import { runSetupTokenCommand } from "./src/setup-token.js";
21 -const MODEL_IDS = Object.keys(MODEL_SELECTORS) as KlausModelId[];
22 -const FABLE_FALLBACK_IDS = ["claude-opus-4-8", "claude-opus-5"] as const;
23 17 dbg?.("index.module", { modelIds: MODEL_IDS });
25 -function projectModel(model: Model<Api>): ProviderModelConfig {
26 - dbg?.("index.projectModel", { provider: model.provider, modelId: model.id });
27 - const compat =
28 - model.id === "claude-fable-5-1"
29 - ? ({
30 - ...(structuredClone(model.compat) as AnthropicMessagesCompat),
31 - allowedFallbackModels: FABLE_FALLBACK_IDS.flatMap((id) => {
32 - const fallback = getBuiltinModel("anthropic", id);
33 - return fallback
34 - ? [
35 - {
36 - provider: "anthropic",
37 - model: id,
38 - cost: structuredClone(fallback.cost),
39 - },
40 - ]
41 - : [];
42 - }),
43 - } satisfies AnthropicMessagesCompat)
44 - : structuredClone(model.compat);
45 - return {
46 - id: model.id,
47 - name: model.name,
48 - reasoning: model.reasoning,
49 - thinkingLevelMap: model.thinkingLevelMap,
50 - input: [...model.input],
51 - cost: structuredClone(model.cost),
52 - compat,
53 - contextWindow: model.contextWindow,
54 - maxTokens: model.maxTokens,
55 - };
58 -function builtinModels(): ProviderModelConfig[] {
59 - dbg?.("index.builtinModels.start");
60 - const models = MODEL_IDS.flatMap((id) => {
61 - const model = getBuiltinModel("anthropic", id);
62 - dbg?.("index.builtinModels.lookup", { modelId: id, found: Boolean(model) });
63 - return model ? [projectModel(model)] : [];
64 - });
65 - dbg?.("index.builtinModels.end", { count: models.length });
66 - return models;
19 +/** Pi's catalog carries user overrides, so the session registry outranks the
20 + * builtin catalog whenever it still knows the model. */
21 +function sessionModels(activeContext: ExtensionContext): ProviderModelConfig[] {
22 + const models = projectModels((id) =>
23 + activeContext.modelRegistry.find("anthropic", id),
24 + );
25 + return models.length ? models : projectModels(builtinSource);
69 28 export default function klaus(pi: ExtensionAPI): void | Promise<void> {
108 + let registeredSignature: string | undefined;
149 109 const register = (models: ProviderModelConfig[]): void => {
110 + const signature = modelsSignature(models);
111 + if (signature === registeredSignature) {
112 + dbg?.("index.register.unchanged", { count: models.length });
113 + return;
115 + registeredSignature = signature;
150 116 dbg?.("index.register", { modelIds: models.map((model) => model.id) });
151 117 pi.registerProvider("klaus", {
152 118 name: "Klaus",
170 - register(builtinModels());
136 + register(projectModels(builtinSource));
172 138 pi.on("session_start", (_event, nextContext) => {
173 139 dbg?.("index.session_start", {
190 156 "error",
193 - const models = MODEL_IDS.flatMap((id) => {
194 - const model = nextContext.modelRegistry.find("anthropic", id);
195 - dbg?.("index.sessionModel.lookup", {
196 - modelId: id,
197 - found: Boolean(model),
198 - });
199 - return model ? [projectModel(model)] : [];
200 - });
201 - register(models.length ? models : builtinModels());
159 + register(sessionModels(nextContext));
160 + });
161 + pi.on("turn_start", (_event, activeContext) => {
162 + // Pi has no catalog-reload event, so a turn boundary is the cheapest
163 + // place to notice a refreshed models.json. Registration is skipped when
164 + // the projection is unchanged.
165 + register(sessionModels(activeContext));
203 167 pi.on("turn_end", async (_event, activeContext) => {
204 168 const leafId = activeContext.sessionManager.getLeafId();

extensions/klaus/src/models.ts

Added
new file mode 100644
1 +import type {
2 + AnthropicMessagesCompat,
3 + Api,
4 + Model,
5 +} from "@earendil-works/pi-ai";
6 +import { getBuiltinModel } from "@earendil-works/pi-ai/providers/all";
7 +import type { ProviderModelConfig } from "@earendil-works/pi-coding-agent";
8 +import { dbg } from "./debug.js";
9 +import {
10 + isKlausModelId,
11 + type KlausModelId,
12 + MODEL_SELECTORS,
13 +} from "./protocol.js";
15 +export const MODEL_IDS = Object.keys(MODEL_SELECTORS) as KlausModelId[];
17 +const FABLE_FALLBACK_IDS = ["claude-opus-4-8", "claude-opus-5"] as const;
19 +/** Pi model lookup, satisfied by `ModelRegistry.find` or the builtin catalog. */
20 +export type AnthropicModelSource = (
21 + modelId: KlausModelId,
22 +) => Model<Api> | undefined;
24 +export const builtinSource: AnthropicModelSource = (modelId) =>
25 + getBuiltinModel("anthropic", modelId);
27 +/** Pi catalog entries may be tuned for the direct Anthropic API, where request
28 + * headers unlock capacity that the Claude Agent SDK path does not provide.
29 + * Klaus drops those headers, so it must not advertise more than the builtin
30 + * catalog promises for the same model. */
31 +function clampToBaseline(
32 + modelId: string,
33 + field: "contextWindow" | "maxTokens",
34 + value: number,
35 + baseline: Model<Api> | undefined,
36 +): number {
37 + const ceiling = baseline?.[field];
38 + if (ceiling === undefined || value <= ceiling) return value;
39 + dbg?.("models.clamp", { modelId, field, value, ceiling });
40 + return ceiling;
43 +function fableCompat(model: Model<Api>): Model<Api>["compat"] {
44 + return {
45 + ...(structuredClone(model.compat) as AnthropicMessagesCompat),
46 + allowedFallbackModels: FABLE_FALLBACK_IDS.flatMap((id) => {
47 + const fallback = getBuiltinModel("anthropic", id);
48 + return fallback
49 + ? [
50 + {
51 + provider: "anthropic",
52 + model: id,
53 + cost: structuredClone(fallback.cost),
54 + },
55 + ]
56 + : [];
57 + }),
58 + } satisfies AnthropicMessagesCompat;
61 +/** Project one Pi Anthropic model onto the Klaus provider. Transport-owned
62 + * fields (`api`, `baseUrl`, `headers`, sampling parameters) are never
63 + * inherited, because the Claude Agent SDK owns the request. */
64 +export function projectModel(model: Model<Api>): ProviderModelConfig {
65 + dbg?.("models.projectModel", { provider: model.provider, modelId: model.id });
66 + const baseline = isKlausModelId(model.id)
67 + ? getBuiltinModel("anthropic", model.id)
68 + : undefined;
69 + return {
70 + id: model.id,
71 + name: model.name,
72 + reasoning: model.reasoning,
73 + thinkingLevelMap: model.thinkingLevelMap,
74 + input: [...model.input],
75 + cost: structuredClone(model.cost),
76 + compat:
77 + model.id === "claude-fable-5-1"
78 + ? fableCompat(model)
79 + : structuredClone(model.compat),
80 + contextWindow: clampToBaseline(
81 + model.id,
82 + "contextWindow",
83 + model.contextWindow,
84 + baseline,
85 + ),
86 + maxTokens: clampToBaseline(
87 + model.id,
88 + "maxTokens",
89 + model.maxTokens,
90 + baseline,
91 + ),
92 + };
95 +/** Project every advertised Klaus model that the source still knows. */
96 +export function projectModels(
97 + source: AnthropicModelSource,
98 +): ProviderModelConfig[] {
99 + const models = MODEL_IDS.flatMap((id) => {
100 + const model = source(id);
101 + dbg?.("models.lookup", { modelId: id, found: Boolean(model) });
102 + return model ? [projectModel(model)] : [];
103 + });
104 + dbg?.("models.projectModels", { count: models.length });
105 + return models;
108 +/** Stable identity of a projected catalog, used to skip redundant provider
109 + * registrations. */
110 +export function modelsSignature(models: ProviderModelConfig[]): string {
111 + return JSON.stringify(models);