import { writeFileSync } from "node:fs"; import { basename, dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import type { Session } from "@peppa/core"; import { peppaRoot } from "@peppa/shared"; import { runDir, writeRunRules, writeRunSettings } from "./run-settings.ts"; /** PEP-17: inside the runner container the launch dir is mounted here (see sandbox.ts). */ const RUN_MOUNT = "/peppa/run"; export type Provider = Session["provider"]; export const PROVIDERS: Provider[] = ["claude", "codex", "opencode"]; // PEPPA_ROOT first: inside a Next.js build import.meta.url points into .next/. const ROOT = () => peppaRoot(resolve(dirname(fileURLToPath(import.meta.url)), "../../..")); export const HOOK_BIN = () => `${ROOT()}/packages/runner/bin/peppa-hook`; const MCP_BIN = () => `${ROOT()}/packages/mcp/bin/peppa-mcp`; export interface LaunchContext { sessionId: number; generation: number; cwd: string; prompt: string; rules: string; resume?: string; permissionMode?: string; model?: string; /** PEP-41: Claude --effort, Codex model_reasoning_effort (OpenCode has none). */ effort?: string; /** PEP-17: the agent runs in the runner container — bins from the image, files under /peppa/run. */ sandbox?: boolean; } const hookBin = (c: { sandbox?: boolean }) => (c.sandbox ? "peppa-hook" : HOOK_BIN()); const mcpBin = (c: { sandbox?: boolean }) => (c.sandbox ? "peppa-mcp" : MCP_BIN()); /** A file of the launch dir as the agent sees it. */ const runFile = (c: { sandbox?: boolean }, path: string) => (c.sandbox ? `${RUN_MOUNT}/${basename(path)}` : path); const bin = (c: { sandbox?: boolean }, name: string, env: string) => (c.sandbox ? name : (process.env[env] ?? name)); /** argv for one run of the agent CLI (executable first). */ export function buildCommand(provider: Provider, c: LaunchContext): string[] { return provider === "codex" ? codexCommand(c) : provider === "opencode" ? opencodeCommand(c) : claudeCommand(c); } /** Extra environment the provider's CLI needs for this run (OpenCode reads its config from a file). */ export function providerEnv(provider: Provider, c: Pick): Record { return provider === "opencode" ? { OPENCODE_CONFIG: runFile(c, join(runDir(c.sessionId, c.generation), "opencode.json")) } : {}; } function claudeCommand(c: LaunchContext): string[] { return [ bin(c, "claude", "PEPPA_CLAUDE_BIN"), "--settings", runFile(c, writeRunSettings(c.sessionId, c.generation, hookBin(c))), "--append-system-prompt-file", runFile(c, writeRunRules(c.sessionId, c.generation, c.rules)), "--permission-mode", c.permissionMode ?? process.env.PEPPA_PERMISSION_MODE ?? "acceptEdits", ...(c.model ? ["--model", c.model] : []), ...(c.effort ? ["--effort", c.effort] : []), ...(c.resume ? ["--resume", c.resume] : []), "--", c.prompt, ]; } /** * Codex has no Claude-style hooks: Peppa only learns about completed turns through the * `notify` callback, and about crashes, stalls and limits through the watchdog. * Permission prompts can't be routed to the PM: like Claude's bypassPermissions (PEP-171 — Codex * 0.169 removed --full-auto) it runs with no approvals and no sandbox, unless PEPPA_CODEX_MODE says otherwise. */ export const CODEX_DEFAULT_MODE = "--dangerously-bypass-approvals-and-sandbox"; /** * PEP-188: the mode string as separate argv items. A .env value may arrive with its quotes * (`"--sandbox x"`), and Claude's values (`bypassPermissions`) are not Codex flags — those fall back. */ export function codexModeArgs(...candidates: Array): string[] { for (const raw of candidates) { const args = (raw ?? "") .split(/\s+/) .map((a) => a.replace(/^["']+|["']+$/g, "")) .filter(Boolean); if (args.length && args.every((a) => a.startsWith("-") || args[0]!.startsWith("-"))) return args; } return CODEX_DEFAULT_MODE.split(" "); } function codexCommand(c: LaunchContext): string[] { const toml = (v: unknown) => JSON.stringify(v); return [ bin(c, "codex", "PEPPA_CODEX_BIN"), "--no-alt-screen", "--cd", c.cwd, ...codexModeArgs(c.permissionMode, process.env.PEPPA_CODEX_MODE), // PEP-188: Codex 0.169 asks «Trust this folder?» on a first run and waits for a key. "-c", `projects.${toml(c.cwd)}.trust_level="trusted"`, // PEP-205: near the limit Codex asks «Switch to ?» and waits for a key — never show it. "-c", "notice.hide_rate_limit_model_nudge=true", ...(c.model ? ["--model", c.model] : []), // Codex knows low/medium/high (xhigh/max → high). ...(c.effort ? ["-c", `model_reasoning_effort=${toml(["xhigh", "max"].includes(c.effort) ? "high" : c.effort)}`] : []), "-c", `notify=${toml([hookBin(c), "codex-notify"])}`, "-c", `developer_instructions=${toml(c.rules)}`, "-c", `mcp_servers.peppa.command=${toml(mcpBin(c))}`, ...(c.resume ? ["resume", c.resume] : []), "--", c.prompt, ]; } /** * OpenCode (PEP-67): TUI in tmux; rules and the peppa MCP server come from a generated * opencode.json (OPENCODE_CONFIG, see providerEnv). It has no Claude-style hooks — the * watchdog follows the process (alive, dead, stalled); hooks via an OpenCode plugin later. */ function opencodeCommand(c: LaunchContext): string[] { const dir = runDir(c.sessionId, c.generation); writeFileSync( join(dir, "opencode.json"), JSON.stringify( { $schema: "https://opencode.ai/config.json", instructions: [runFile(c, writeRunRules(c.sessionId, c.generation, c.rules))], mcp: { peppa: { type: "local", command: [mcpBin(c)], enabled: true } }, }, null, 2, ), ); return [ bin(c, "opencode", "PEPPA_OPENCODE_BIN"), c.cwd, ...(c.model ? ["--model", c.model] : []), ...(c.resume ? ["--session", c.resume] : []), "--prompt", c.prompt, ]; }