// PEP-17: the agent of a runner in its own docker container. tmux stays outside (watchdog, // web terminal, input work unchanged); the container sees only the runner's working copy, // its launch dir (read-only) and its own home — no Peppa files, .env, ~/.ssh or database. // Hooks, MCP and git reach Peppa through the agent relay (agent-relay.ts) with the run's token. import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { agentRelayToken } from "@peppa/core"; import { loadEnv, peppaHome } from "@peppa/shared"; import { runOn, shq, type Target } from "./exec.ts"; import { markClaudeTrusted } from "./claude-config.ts"; /** Inside the container: launch dir (settings, rules, opencode.json) and the agent's HOME. */ export const RUN_MOUNT = "/peppa/run"; export const CONTAINER_HOME = "/peppa/home"; export const runnerImage = () => process.env.PEPPA_RUNNER_IMAGE ?? "peppa/runner:latest"; export const dockerBin = (target: Target) => (target ? "docker" : (process.env.PEPPA_DOCKER_BIN ?? "docker")); export const containerName = (sessionId: number) => `peppa-s${sessionId}`; /** Where the relay is reached from the container: a host's setting, else PEPPA_AGENT_URL, else the local web. */ export function relayUrl(host?: { peppaUrl: string | null } | null): string { const env = loadEnv() as Record; if (host) return (host.peppaUrl || env.PEPPA_WEB_URL || "https://peppa.telecom.quest").replace(/\/$/, ""); return (process.env.PEPPA_AGENT_URL ?? `http://host.docker.internal:${process.env.PEPPA_WEB_PORT ?? 3100}`).replace(/\/$/, ""); } /** The agent's own HOME on this machine (conversation history for --resume, claude config). */ export const localAgentHome = (sessionId: number) => join(peppaHome(), "sandboxes", `s${sessionId}`, "home"); /** Claude config for the container: onboarding done, the workspace trusted, the peppa MCP server enabled. */ export function claudeConfigFor(existing: string | null, cwd: string): string { const cfg = existing ? (JSON.parse(existing) as Record) : {}; cfg.hasCompletedOnboarding = true; // PEP-230: a fresh HOME shows the "Bypass Permissions mode" notice and waits for a key — nobody is there to press it. cfg.bypassPermissionsModeAccepted = true; // PEP-263: the worktree and its main repository's root (Claude looks a worktree's trust up there). markClaudeTrusted(cfg, cwd); return JSON.stringify(cfg, null, 2); } export function prepareLocalHome(sessionId: number, cwd: string): string { const home = localAgentHome(sessionId); mkdirSync(home, { recursive: true, mode: 0o700 }); const f = join(home, ".claude.json"); writeFileSync(f, claudeConfigFor(existsSync(f) ? readFileSync(f, "utf8") : null, cwd)); return home; } /** * Git inside the container goes through the relay's proxy (only the project's repo; the Gitea * token never enters the container): GIT_CONFIG_* rewrites the Gitea URL and adds the run's token. */ export function gitRelayEnv(relay: string, token: string): Record { const env = loadEnv() as Record; const gitea = env.GITEA_URL?.replace(/\/$/, ""); if (!gitea) return {}; const base = `${relay}/api/agent/git/`; // PEP-230: on the Mac the author came from the host's global git config; in a container on the // server there is none and `git commit` fails — commits of agents are signed by the bot. const login = env.GITEA_BOT_LOGIN || "peppa-bot"; return { GIT_AUTHOR_NAME: login, GIT_AUTHOR_EMAIL: env.PEPPA_GIT_EMAIL || `${login}@telecom.quest`, GIT_COMMITTER_NAME: login, GIT_COMMITTER_EMAIL: env.PEPPA_GIT_EMAIL || `${login}@telecom.quest`, GIT_CONFIG_COUNT: "3", GIT_CONFIG_KEY_0: `url.${base}.insteadOf`, GIT_CONFIG_VALUE_0: `${gitea}/`, GIT_CONFIG_KEY_1: `http.${base}.extraHeader`, GIT_CONFIG_VALUE_1: `Authorization: Bearer ${token}`, GIT_CONFIG_KEY_2: "safe.directory", GIT_CONFIG_VALUE_2: "*", }; } export interface Mount { src: string; dst: string; ro?: boolean; } export interface ContainerSpec { sessionId: number; generation: number; target: Target; cwd: string; /** Launch dir on the host where docker runs (mounted read-only at RUN_MOUNT). */ runDir: string; /** The agent's home on that host (mounted at CONTAINER_HOME). */ home: string; /** Extra mounts: the project's .git for a worktree, CODEX_HOME of the subscription. */ mounts?: Mount[]; relay: string; /** Agent argv inside the container (executable first). */ argv: string[]; /** Environment of the agent: values go to tmux, the script passes only names to docker. */ env: Record; /** More names for docker `-e` whose values the script sets itself (PEP-54 project secrets). */ passEnv?: string[]; /** Shell lines before `docker run` (sourcing the secrets file). */ preamble?: string; } /** The run's environment: session, relay, git through the relay, plus the subscription/provider env. */ export function containerEnv(spec: Pick, extra: Record): Record { const token = agentRelayToken(spec.sessionId, spec.generation); return { PEPPA_SESSION_ID: String(spec.sessionId), PEPPA_GENERATION: String(spec.generation), PEPPA_AGENT_URL: spec.relay, PEPPA_AGENT_TOKEN: token, ...gitRelayEnv(spec.relay, token), ...extra, }; } /** * launch.sh for tmux: `docker run` of the runner image. Values of the environment stay out of * the script (it is mounted into the container and kept on disk): `-e NAME` takes them from * the docker client's environment, which tmux sets. */ export function dockerRunScript(spec: ContainerSpec): string { const name = containerName(spec.sessionId); const mounts: Mount[] = [ { src: spec.cwd, dst: spec.cwd }, { src: spec.runDir, dst: RUN_MOUNT, ro: true }, { src: spec.home, dst: CONTAINER_HOME }, ...(spec.mounts ?? []), ]; const args = [ dockerBin(spec.target), "run", "--rm", "-it", "--init", "--name", name, "--label", `peppa.session=${spec.sessionId}`, "--add-host", "host.docker.internal:host-gateway", "-w", spec.cwd, ...mounts.flatMap((m) => ["-v", `${m.src}:${m.dst}${m.ro ? ":ro" : ""}`]), "-e", `HOME=${CONTAINER_HOME}`, ...[...new Set([...Object.keys(spec.env), ...(spec.passEnv ?? [])])].sort().flatMap((k) => ["-e", k]), ...(process.env.PEPPA_SANDBOX_DOCKER_ARGS ?? "").split(" ").filter(Boolean), ]; // Files written by the agent belong to the host user, not root (Linux hosts). return [ "#!/bin/bash", `# PEP-17: agent of session ${spec.sessionId} (generation ${spec.generation}) in its container`, `${dockerBin(spec.target)} rm -f ${name} >/dev/null 2>&1`, ...(spec.preamble ? [spec.preamble.trimEnd()] : []), `exec ${args.map(shq).join(" ")} --user "$(id -u):$(id -g)" ${shq(runnerImage())} ${spec.argv.map(shq).join(" ")}`, "", ].join("\n"); } /** Removes the runner's container (its docker client under tmux may die first). */ export async function removeContainer(target: Target, name: string): Promise { await runOn(target, [dockerBin(target), "rm", "-f", name]).catch(() => {}); }