177 lines
7.5 KiB
TypeScript
177 lines
7.5 KiB
TypeScript
import { writeFileSync } from "node:fs";
|
|
import { basename, dirname, join, resolve } from "node:path";
|
|
import { fileURLToPath } from "node:url";
|
|
import { NO_AUTOUPDATE_ENV, type Session } from "@peppa/core";
|
|
import { peppaRoot } from "@peppa/shared";
|
|
import { codexTrustRoots } from "./codex-trust.ts";
|
|
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).
|
|
* PEP-267: no CLI updates itself — versions change only through scripts/runner-image.sh.
|
|
*/
|
|
export function providerEnv(provider: Provider, c: Pick<LaunchContext, "sessionId" | "generation" | "sandbox">): Record<string, string> {
|
|
return {
|
|
...NO_AUTOUPDATE_ENV,
|
|
...(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 | undefined>): 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(" ");
|
|
}
|
|
|
|
/** Env names the peppa MCP server needs, locally (DB, state dir) and in a container (relay). */
|
|
const CODEX_MCP_ENV = ["PEPPA_SESSION_ID", "PEPPA_GENERATION", "PEPPA_PROJECT_DIR", "PEPPA_DB", "PEPPA_HOME", "PEPPA_ROOT", "PEPPA_AGENT_URL", "PEPPA_AGENT_TOKEN", "PEPPA_SECRET", "PEPPA_SECRET_PREVIOUS"];
|
|
|
|
export function codexMcpEnvNames(env: NodeJS.ProcessEnv = process.env): string[] {
|
|
return [...new Set([...CODEX_MCP_ENV, ...Object.keys(env).filter((k) => k.startsWith("PEPPA_"))])];
|
|
}
|
|
|
|
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.
|
|
// PEP-241: for a worktree it asks about the main repository's root — trust both.
|
|
...codexTrustRoots(c.cwd).flatMap((dir) => ["-c", `projects.${toml(dir)}.trust_level="trusted"`]),
|
|
// PEP-205: near the limit Codex asks «Switch to <model>?» and waits for a key — never show it.
|
|
"-c",
|
|
"notice.hide_rate_limit_model_nudge=true",
|
|
// PEP-267: the version is pinned — Codex must not offer (or run) an update at start.
|
|
"-c",
|
|
"check_for_update_on_startup=false",
|
|
...(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))}`,
|
|
// PEP-286: Codex starts MCP servers with a bare environment (HOME, PATH…) — without the
|
|
// session's PEPPA_* the server reaches neither the relay nor the DB and has no tools.
|
|
"-c",
|
|
`mcp_servers.peppa.env_vars=${toml(codexMcpEnvNames())}`,
|
|
// The runner's own tools need no approval (Codex asks for MCP calls otherwise).
|
|
"-c",
|
|
`mcp_servers.peppa.default_tools_approval_mode="approve"`,
|
|
// The ChatGPT account's connected apps can carry their own «peppa» (the remote MCP) that
|
|
// needs a fresh sign-in — the agent called it instead of the runner's server.
|
|
"-c",
|
|
"features.apps=false",
|
|
...(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",
|
|
// PEP-267: the version is pinned.
|
|
autoupdate: false,
|
|
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,
|
|
];
|
|
}
|