import { resolveCliFamilyId, type CliFamilyId } from "../../../shared/cli-families.js"; /** * The supported CLI families and how each one is invoked headlessly. * * A family is one CLI binary that can answer a single prompt without a UI. The * plugin never speaks a provider API directly: Paseo already runs the provider * the user selected, so the same binary the agent runs on is the one PromptKit * shells out to. That is why `Current agent model` keeps working unchanged. * * A `process` family starts one process per rewrite. A `session` family (codex) answers * on a long-lived server process, see `codex-sessions.ts`. */ export interface CliInvocation { readonly command: string; readonly args: readonly string[]; /** Variables added to the daemon's environment for this run only. */ readonly env: Readonly>; } export interface CliRequest { /** The model id as the agent snapshot reports it, e.g. `openai/gpt-4.1-mini`. */ readonly model: string; readonly thinkingOptionId: string | null; /** Instruction text. Replaces the CLI's own default system prompt where supported. */ readonly systemPrompt: string; /** Absolute path of a file holding the user prompt. Set only for file delivery. */ readonly promptFilePath: string | null; } export interface ProcessCliFamily { readonly kind: "process"; readonly id: CliFamilyId; /** * How the user prompt reaches the process. `file` keeps the prompt out of * `argv`, so it never appears in `ps`; `stdin` is the same guarantee. */ readonly promptDelivery: "stdin" | "file"; buildInvocation(request: CliRequest): CliInvocation; /** Extracts the final answer from captured stdout, or null when there is none. */ parseOutput(stdout: string): string | null; /** The failure the CLI itself reports in stdout, or null when it reports none. */ parseError(stdout: string): string | null; } export interface SessionCliFamily { readonly kind: "session"; readonly id: CliFamilyId; } export type CliFamily = ProcessCliFamily | SessionCliFamily; /** The value `pick` finds in the last event of a JSONL stream that has one. */ function lastJsonlText( stdout: string, pick: (event: Record) => string | null, ): string | null { let found: string | null = null; for (const line of stdout.split("\n")) { const trimmed = line.trim(); if (trimmed === "" || !trimmed.startsWith("{")) continue; let event: unknown; try { event = JSON.parse(trimmed); } catch { continue; } if (event === null || typeof event !== "object") continue; const text = pick(event as Record); if (text !== null && text.trim() !== "") found = text; } return found; } /** Reported when a model stopped at its output limit; the partial text is never a rewrite. */ export const TRUNCATED_MESSAGE = "The model stopped at its output token limit before the rewrite was complete."; /** A provider error often arrives as JSON text; its innermost `message` is the readable part. */ export function innermostMessage(text: string): string { let current = text; for (let depth = 0; depth < 3; depth += 1) { let parsed: unknown; try { parsed = JSON.parse(current); } catch { return current; } const nested = at(parsed, "error", "message") ?? at(parsed, "message"); if (typeof nested !== "string" || nested.trim() === "") return current; current = nested; } return current; } function at(value: unknown, ...path: readonly string[]): unknown { let current = value; for (const step of path) { if (current === null || typeof current !== "object") return undefined; current = (current as Record)[step]; } return current; } /** Joins the text blocks of a pi message object, ignoring thinking blocks. */ function piMessageText(message: unknown): string | null { if (message === null || typeof message !== "object") return null; const content = (message as { content?: unknown }).content; if (!Array.isArray(content)) return null; const parts: string[] = []; for (const block of content) { if (block === null || typeof block !== "object") continue; const typed = block as { type?: unknown; text?: unknown }; if (typed.type === "text" && typeof typed.text === "string") parts.push(typed.text); } return parts.length === 0 ? null : parts.join("\n"); } export const piFamily: ProcessCliFamily = { kind: "process", id: "pi", promptDelivery: "file", buildInvocation: (request) => { const args = [ "--model", request.model, // A rewrite is a pure text transformation: no tools, no project context, // no session file. Each of these removes one way the answer could drift. "--no-tools", "--no-context-files", "--no-skills", "--no-extensions", "--no-prompt-templates", "--no-session", "--system-prompt", request.systemPrompt, "--mode", "json", "-p", ]; if (request.thinkingOptionId !== null) args.push("--thinking", request.thinkingOptionId); if (request.promptFilePath === null) { throw new Error("pi requires a prompt file"); } args.push(`@${request.promptFilePath}`); return { command: "pi", args, env: {} }; }, parseOutput: (stdout) => lastJsonlText(stdout, (event) => event.type === "turn_end" ? piMessageText(event.message) : null, ), // In json mode pi exits 0 after a failed request; the turn's stopReason is the only signal. parseError: (stdout) => lastJsonlText(stdout, (event) => { if (event.type !== "turn_end") return null; const reason = at(event, "message", "stopReason"); if (reason === "length") return TRUNCATED_MESSAGE; if (reason !== "error" && reason !== "aborted") return null; const message = at(event, "message", "errorMessage"); return typeof message === "string" && message.trim() !== "" ? innermostMessage(message) : `Request ${reason}.`; }), }; interface ClaudeResult { result?: unknown; is_error?: unknown; subtype?: unknown; stop_reason?: unknown; } /** The single JSON result object `claude -p --output-format json` prints, or null. */ function claudeResult(stdout: string): ClaudeResult | null { const start = stdout.indexOf("{"); if (start === -1) return null; try { const parsed: unknown = JSON.parse(stdout.slice(start)); return parsed !== null && typeof parsed === "object" ? (parsed as ClaudeResult) : null; } catch { return null; } } /** The failure a result object reports, or null for a finished answer. */ function claudeFailure(parsed: ClaudeResult): string | null { if (parsed.stop_reason === "max_tokens") return TRUNCATED_MESSAGE; const subtype = typeof parsed.subtype === "string" ? parsed.subtype : ""; if (parsed.is_error !== true && !subtype.startsWith("error")) return null; if (typeof parsed.result === "string" && parsed.result.trim() !== "") return parsed.result; return subtype === "" ? "Claude reported an error." : `Claude reported an error (${subtype}).`; } export const claudeFamily: ProcessCliFamily = { kind: "process", id: "claude", promptDelivery: "stdin", buildInvocation: (request) => { const args = [ "-p", "--model", request.model, // Replaces Claude Code's own coding-agent system prompt outright, so the // rewrite instruction is the only instruction in play. "--system-prompt", request.systemPrompt, // No tool use: a rewrite never needs one, and this closes the path where a // prompt could steer the model into running a command. "--tools", "", "--disallowedTools", "*", // The user's MCP servers, hooks and skills only slow a cold start toward the host's 30 s cap. "--strict-mcp-config", "--settings", JSON.stringify({ disableAllHooks: true }), "--disable-slash-commands", "--no-session-persistence", "--output-format", "json", ]; return { command: "claude", args, env: {} }; }, parseOutput: (stdout) => { const parsed = claudeResult(stdout); if (parsed === null || claudeFailure(parsed) !== null) return null; return typeof parsed.result === "string" ? parsed.result : null; }, // An auth or API failure still prints a result object, flagged `is_error` or an // `error_*` subtype, whose `result` is the error text rather than an answer. parseError: (stdout) => { const parsed = claudeResult(stdout); return parsed === null ? null : claudeFailure(parsed); }, }; /** codex answers on a warm `codex app-server`; see `codex-sessions.ts`. */ export const codexFamily: SessionCliFamily = { kind: "session", id: "codex" }; const OPENCODE_AGENT = "promptkit-rewrite"; /** * `opencode run` has no system-prompt flag, so the instruction becomes the prompt of an * inline agent with every tool off, layered onto the user's config for this run only. */ function opencodeAgentConfig(systemPrompt: string): string { return JSON.stringify({ agent: { [OPENCODE_AGENT]: { mode: "primary", prompt: systemPrompt, tools: { "*": false } } } }); } export const opencodeFamily: ProcessCliFamily = { kind: "process", id: "opencode", promptDelivery: "stdin", buildInvocation: (request) => { const args = ["run", "--model", request.model, "--agent", OPENCODE_AGENT, "--format", "json"]; if (request.thinkingOptionId !== null) args.push("--variant", request.thinkingOptionId); return { command: "opencode", args, env: { OPENCODE_CONFIG_CONTENT: opencodeAgentConfig(request.systemPrompt) } }; }, parseOutput: (stdout) => lastJsonlText(stdout, (event) => { if (event.type !== "text") return null; // opencode nests the payload under `part`, not at the event root. const part = event.part; if (part === null || typeof part !== "object") return null; const text = (part as { text?: unknown }).text; return typeof text === "string" ? text : null; }), // opencode exits 1 with an empty stderr; the failure is an `error` event in stdout. parseError: (stdout) => lastJsonlText(stdout, (event) => { if (event.type !== "error") return null; const message = at(event, "error", "data", "message") ?? at(event, "error", "message"); if (typeof message === "string" && message.trim() !== "") return innermostMessage(message); const name = at(event, "error", "name"); return typeof name === "string" ? name : "opencode reported an error."; }), }; const FAMILIES: readonly CliFamily[] = [piFamily, claudeFamily, codexFamily, opencodeFamily]; export function findFamily(familyId: string): CliFamily | null { return FAMILIES.find((family) => family.id === familyId) ?? null; } export function listFamilyIds(): readonly string[] { return FAMILIES.map((family) => family.id); } /** * The family that runs a Paseo provider. The id rule lives in * `shared/cli-families.ts` so the settings screen shows the same answer the * daemon acts on; this only attaches the invocation to it. */ export function resolveFamily( providerId: string, providerMap: Readonly> = {}, ): CliFamily | null { const id = resolveCliFamilyId(providerId, providerMap); return id === null ? null : findFamily(id); }