import { existsSync, writeSync } from "node:fs"; import { join } from "node:path"; import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; import { registerBillingHook } from "./billing-spoof.js"; import { GLOBAL_CONFIG_PATH, mergeConfigLayers, readRawConfig, type NormalizedPiPiConfig } from "./config.js"; import { AGENT_FLAG } from "./cli-model.js"; import { captureAvailableModels } from "./event-handlers.js"; import { initFlantSync, isClaudeSubInUse, refreshClaudeOAuthToken, refreshCodexOAuthToken, refreshCopilotOAuthToken, setModelRegistry } from "./flant-infra.js"; import { configureRouting, logicalProviderOf, pinnedRoleSpecs, resolveRef } from "./routing.js"; const SYSTEM_PROMPT = "You answer exactly one request, in one reply, with only the text it asks for: no preamble, no explanation, no quotes or formatting around it. You have no tools and cannot ask anything back."; /** * `pi -p --pp-agent quick`: one prompt answered on the configured quick model * and nothing else of pi-pi — no orchestrator prompt, tools, workers, menus, * logs or background work — so an outside caller with a deadline (bb's thread * titles) pays only for the model call. Every failure exits non-zero, since * running on pi's default model instead would be slow, costly and silent. */ export function registerQuickAgent(pi: ExtensionAPI, role: string, checkOnly = false): void { if (role !== "quick") fail(`--${AGENT_FLAG} supports only "quick"${role ? `, not "${role}"` : ""}`); const cwd = process.cwd(); let config: NormalizedPiPiConfig; try { // Read without creating the project's .pp directory, which loadConfig would. const project = join(cwd, ".pp", "config.json"); config = mergeConfigLayers(readRawConfig(GLOBAL_CONFIG_PATH), existsSync(project) ? readRawConfig(project) : null); } catch (error: any) { fail(`config error: ${error?.message ?? String(error)}`); } configureRouting(config); // From the cache, as the orchestrator does at load: pi picks its starting // model before session_start, and that model may be on a pi-pi provider. initFlantSync(pi, cwd, pinnedRoleSpecs(config)); registerBillingHook(pi); pi.on("session_start", async (_event, ctx: any) => { if (ctx.mode !== "print" && ctx.mode !== "json") fail(`--${AGENT_FLAG} runs only in print mode (-p) or --mode json`); let spec: string; try { spec = await useQuickModel(pi, ctx, config, cwd); } catch (error: any) { // pi logs a failed handler and goes on, which would send the prompt on its own model with every tool. fail(error?.message ?? String(error)); } if (checkOnly) { // Straight to the descriptor: in print mode pi sends process.stdout to stderr. writeSync(1, `${spec}\n`); process.exit(0); } }); // Exits before pi's own retries, which would outlast a caller's deadline, // and with a failure code in json mode too, where pi exits 0 regardless. pi.on("message_end", async (event: any) => { const message = event?.message; if (message?.role === "assistant" && message.stopReason === "error") fail(message.errorMessage || "the request failed", 1); }); pi.on("before_agent_start", async () => ({ systemPrompt: SYSTEM_PROMPT })); } async function useQuickModel(pi: ExtensionAPI, ctx: any, config: NormalizedPiPiConfig, cwd: string): Promise { setModelRegistry(ctx.modelRegistry); const pinned = pinnedRoleSpecs(config); // Registered again once the subscription's token is fresh and pi's model // registry is known; the network is touched only near the token's expiry. if (isClaudeSubInUse(config, pinned)) await refreshClaudeOAuthToken(); initFlantSync(pi, cwd, pinned); captureAvailableModels(ctx); const { model: ref, thinking } = config.agents.quick; const resolution = resolveRef(ref); if (!resolution.spec) throw new Error(`agents.quick: ${ref} has nothing to run on — ${resolution.steps.join("; ")}`); const spec = resolution.spec; const separator = spec.indexOf("/"); const provider = spec.slice(0, separator); const logical = logicalProviderOf(provider); if (logical === "codex") await refreshCodexOAuthToken(); if (logical === "copilot" && !process.env.COPILOT_GITHUB_TOKEN) await refreshCopilotOAuthToken(); const model = ctx.modelRegistry?.find?.(provider, spec.slice(separator + 1)); if (!model || !await pi.setModel(model)) throw new Error(`agents.quick: ${spec} is not usable (no model or no credentials)`); pi.setThinkingLevel(thinking as any); pi.setActiveTools([]); return spec; } function fail(message: string, code = 2): never { process.stderr.write(`pi-pi: ${message}\n`); process.exit(code); }