import type { Api, Model } from "@earendil-works/pi-ai"; import { getBuiltinModel } from "@earendil-works/pi-ai/providers/all"; import type { ExtensionAPI, ExtensionContext, ProviderModelConfig, } from "@earendil-works/pi-coding-agent"; import { QueryCoordinator } from "./src/coordinator.js"; import { dbg } from "./src/debug.js"; import { KLAUS_API, type KlausModelId, MODEL_SELECTORS, } from "./src/protocol.js"; const MODEL_IDS = Object.keys(MODEL_SELECTORS) as KlausModelId[]; dbg?.("index.module", { modelIds: MODEL_IDS }); function projectModel(model: Model): ProviderModelConfig { dbg?.("index.projectModel", { provider: model.provider, modelId: model.id }); return { id: model.id, name: model.name, reasoning: model.reasoning, thinkingLevelMap: model.thinkingLevelMap, input: [...model.input], cost: structuredClone(model.cost), compat: structuredClone(model.compat), contextWindow: model.contextWindow, maxTokens: model.maxTokens, }; } function builtinModels(): ProviderModelConfig[] { dbg?.("index.builtinModels.start"); const models = MODEL_IDS.flatMap((id) => { const model = getBuiltinModel("anthropic", id); dbg?.("index.builtinModels.lookup", { modelId: id, found: Boolean(model) }); return model ? [projectModel(model)] : []; }); dbg?.("index.builtinModels.end", { count: models.length }); return models; } export default function klaus(pi: ExtensionAPI): void { dbg?.("index.extension.start"); let context: ExtensionContext | undefined; let warnedFable = false; let warnedPromptDrift = false; const coordinator = new QueryCoordinator( async (modelId) => { dbg?.("index.oauth.start", { modelId, hasContext: Boolean(context) }); if (!context) throw new Error("Klaus has no active Pi session context."); const source = context.modelRegistry.find("anthropic", modelId); dbg?.("index.oauth.model", { modelId, found: Boolean(source) }); if (!source) throw new Error(`Anthropic model ${modelId} is unavailable in Pi.`); const usingOAuth = context.modelRegistry.isUsingOAuth(source); dbg?.("index.oauth.kind", { modelId, usingOAuth }); if (!usingOAuth) { throw new Error( "Klaus requires Anthropic OAuth. Use Pi /login for Anthropic first.", ); } const auth = await context.modelRegistry.getProviderAuth("anthropic"); const token = auth?.auth.apiKey; dbg?.("index.oauth.resolved", { modelId, hasAuth: Boolean(auth), hasToken: Boolean(token), tokenLength: token?.length, }); if (!token) throw new Error("Pi could not resolve Anthropic OAuth for Klaus."); if (modelId === "claude-fable-5" && !warnedFable) { dbg?.("index.oauth.fableWarning"); warnedFable = true; context.ui.notify( "Klaus Fable may consume Anthropic usage credits when subscription discovery omits it.", "warning", ); } dbg?.("index.oauth.end", { modelId }); return token; }, () => { const cwd = context?.cwd ?? process.cwd(); dbg?.("index.currentCwd", { cwd }); return cwd; }, () => { const scope = context ? { id: context.sessionManager.getSessionId(), persisted: context.sessionManager.getSessionFile() !== undefined, dir: context.sessionManager.getSessionDir(), } : undefined; dbg?.("index.currentSession", { hasScope: Boolean(scope), sessionId: scope?.id, persisted: scope?.persisted, dir: scope?.dir, }); return scope; }, (message) => { dbg?.("index.promptDriftWarning", { message, alreadyWarned: warnedPromptDrift, hasContext: Boolean(context), }); if (warnedPromptDrift || !context) return; warnedPromptDrift = true; context.ui.notify(message, "warning"); }, ); const register = (models: ProviderModelConfig[]): void => { dbg?.("index.register", { modelIds: models.map((model) => model.id) }); pi.registerProvider("klaus", { name: "Klaus", baseUrl: "https://klaus.invalid", apiKey: "klaus", authHeader: false, api: KLAUS_API, models, streamSimple: (model, requestContext, options) => { dbg?.("index.streamSimple", { modelId: model.id, messageCount: requestContext.messages.length, toolCount: requestContext.tools?.length ?? 0, sessionId: options?.sessionId, }); return coordinator.stream(model, requestContext, options); }, }); }; register(builtinModels()); pi.on("session_start", (_event, nextContext) => { dbg?.("index.session_start", { sessionId: nextContext.sessionManager.getSessionId(), persisted: nextContext.sessionManager.getSessionFile() !== undefined, cwd: nextContext.cwd, }); context = nextContext; warnedFable = false; warnedPromptDrift = false; void coordinator .preparePrimaryCache({ id: nextContext.sessionManager.getSessionId(), persisted: nextContext.sessionManager.getSessionFile() !== undefined, dir: nextContext.sessionManager.getSessionDir(), }) .catch((error) => nextContext.ui.notify( error instanceof Error ? error.message : String(error), "error", ), ); const models = MODEL_IDS.flatMap((id) => { const model = nextContext.modelRegistry.find("anthropic", id); dbg?.("index.sessionModel.lookup", { modelId: id, found: Boolean(model), }); return model ? [projectModel(model)] : []; }); register(models.length ? models : builtinModels()); }); pi.on("turn_end", async (_event, activeContext) => { const leafId = activeContext.sessionManager.getLeafId(); dbg?.("index.turn_end", { sessionId: activeContext.sessionManager.getSessionId(), leafId, }); if (leafId) { await coordinator.persistCheckpoint( activeContext.sessionManager.getSessionId(), leafId, ); } }); const flush = async (activeContext: ExtensionContext): Promise => { const leafId = activeContext.sessionManager.getLeafId(); dbg?.("index.flush", { sessionId: activeContext.sessionManager.getSessionId(), leafId, }); if (leafId) { await coordinator.persistCheckpoint( activeContext.sessionManager.getSessionId(), leafId, ); } }; const flushAndClose = async ( activeContext: ExtensionContext, reason: string, ): Promise => { try { await flush(activeContext); } finally { await coordinator.closeAll(reason); } }; pi.on("session_before_switch", async (_event, activeContext) => { dbg?.("index.session_before_switch"); await flushAndClose(activeContext, "Pi switched sessions."); }); pi.on("session_before_fork", async (_event, activeContext) => { dbg?.("index.session_before_fork"); await flushAndClose(activeContext, "Pi forked the session."); }); pi.on("session_before_compact", async (_event, activeContext) => { dbg?.("index.session_before_compact"); await flushAndClose(activeContext, "Pi compacted the session."); }); pi.on("session_shutdown", async (_event, activeContext) => { dbg?.("index.session_shutdown"); try { await flushAndClose(activeContext, "Pi shut down the session."); } finally { context = undefined; } }); }