PEP-17/40: agent sandbox per runner (docker + agent relay) and runner hosts over SSH

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Асель 2026-11-14 07:48:02 +05:00
parent 4094e846c6
commit ca57f9543b
59 changed files with 6482 additions and 443 deletions

View File

@ -21,6 +21,7 @@
- **Раннеры (PEP-10/27/53)**: настройки `core/runners.ts` с наследованием `platform.runner` → `project.runner:<id>` → `task.runner:<taskId>` (строки `settings`): `mode` story (по умолчанию, один раннер на стори) / queue, `context` fresh / continue, `workspace` shared / worktree, `maxRunners`. История и очередь — таблица `runner_tasks`, имя — `sessions.name`. `moveTask` → `startTaskOnRunner` (runner/runners.ts); переход к следующей стори и переезд очереди упавшего раннера — `runnerTick` в вачдоге; queue: «Готово» освобождает раннер (`releaseRunner`), fresh = `relaunchFresh` (тот же tmux, новое поколение без resume). Worktree — runner/worktree.ts (`$PEPPA_HOME/worktrees/<slug>/s<id>`, `sessions.workspace_path`, ветка `task/<key>`, уборка когда чисто и всё запушено). Свободный раннер — `startFreeRunner` (без стори; хук не пингует), `promoteRunner` («Оформить стори»), `renameRunner`; CLI `peppa runner new|rename|promote|queue|show|settings`
- **Раннер-сервис (PEP-21)**: процессы агентов запускает только вачдог (`peppa watchdog` = раннер-сервис, `serveRunnerCommands` в runner/runner-service.ts). Веб (`instrumentation.ts`) и бот (`apps/bot/src/index.ts`) — клиенты (`setRunnerClient`, флаг в `globalThis`): функции жизненного цикла (`startSession`, `startFreeRunner`, `startTaskOnRunner`, `resumeSession`, `stopSession`, `sendToSession`, `moveTask`, `archiveTask`, `acceptTask`, `acceptStory`, `answerAndDeliver`, `queueTaskOnRunner`, `promoteRunner`) первой строкой уходят в `runnerCall` (runner/runner-client.ts): строка в `runner_commands` (payload — id, автор PEP-48 → `runAsActor` в сервисе) + пинок в `$PEPPA_HOME/runner.sock`, ожидание результата; изменяющие tmux-операции (`newSession`/`killSession`/`sendText`/`sendKeys`/`sendHex`) из прочих путей — командой `tmux` (payload стирается после выполнения). Ключ `task:<id>`/`session:<id>` — одна стори по очереди. Нет сокета → сразу ошибка «Раннер-сервис не запущен», не взял за 15 с (`PEPPA_RUNNER_PICKUP_SEC`) → `expired` и ошибка, поздно не выполняется; рестарт сервиса → `running` → `failed`. Тесты по умолчанию «на месте» (флаг ставят только бинари); `runAsRunnerService` — контекст сервиса в одном процессе с клиентом. `PEPPA_RUNNER_MODE=inline` — аварийный откат. CLI `session start|send|resume|stop`, `runner new|promote|queue`, `q answer` — через сервис, если он жив; `peppa runner commands`, `peppa status`
- **Вачдог 2.0 (PEP-28, runner/recovery.ts)**: пороги `platform.watchdog` ← env `PEPPA_WATCHDOG_*` ← умолчания (`peppa platform watchdog key=value|reset`: restartMax 3, restartWindowMin 1440, restartDelaysMin 1,5,15, stallRestartMin 60, remindMin 30, escalateMin 120, idleStopHours 24; 0 = выкл). Упал/пропал раннер стори в `proposing`/`in_progress` (не лимит, не пауза бюджета) → `failed` + `watch_state.restartAt` вместо вопроса, `restartTick` делает `resumeSession` (`auto_restarted`); предел исчерпан — вопрос PM с причиной. Зависший без ответа `stallRestartMin` после алерта — kill + перезапуск. `remindTick`: вопросы question/permission/approval моложе суток — напоминания аудитории (`questions.reminders` 1,2; событие `questions`), затем `alertAdmins` (3); claim атомарный. `idleStopTick`: `waiting_input` без открытых вопросов дольше `idleStopHours` → `stopSession` + сообщение. Память вачдога (хэш экрана, `limitGen`, `thresholdGen`, перезапуски, `stallAlertAt`) — `sessions.watch_state`, переживает рестарт
- **Песочница и хосты (PEP-17/40)**: настройки раннеров `isolation` none (по умолчанию, как раньше) / container и `hosts` (id хостов; пусто — Mac Пеппы; хост → всегда контейнер). Все вызовы tmux — по адресу pane `{name, host}` (`tmux.sessionPane(s)`, `runner/exec.ts`: локально или `ssh` ключом `$PEPPA_HOME/ssh/id_ed25519`, ControlMaster; код 255 → `HostUnreachable`, `hasSession` его не глотает — вачдог не объявит раннер пропавшим). Контейнер (`runner/sandbox.ts`): tmux снаружи, `docker run --rm -it --init --name peppa-s<id>` образа `PEPPA_RUNNER_IMAGE` (`infra/runner/Dockerfile`, `scripts/runner-image.sh`), монтируются только рабочая копия (+ `.git` проекта для worktree, `CODEX_HOME` подписки), каталог запуска → `/peppa/run:ro`, свой HOME → `/peppa/home`; env — только сессии/релея/подписки (значения в tmux, в launch.sh только имена); без подписки не стартует; остановка — `killRunner` (tmux + `docker rm -f`). Релей агента (`runner/agent-relay.ts`, веб `/api/agent/[...path]`, токен `agentRelayToken` = HMAC сессии+поколения): `hook` (настоящий `peppa-hook` в Пеппе; ответ ≤25 с, дальше `{wait, rid}`; транскрипт прикладывает шим), `mcp` (`@peppa/mcp/relay`: сервер агента с `lockProject`), `git/…` (прокси в Gitea с токеном бота, только `owner/repo` проекта; в контейнере `GIT_CONFIG_*` insteadOf). Шимы в образе — `infra/runner/peppa-agent.mjs` (`peppa-hook`, `peppa-mcp`). Хосты: таблица `runner_hosts`, `sessions.host_id`/`container` (миграция 0013), `runner/hosts.ts` (`checkHost`, `hostTick` в вачдоге раз в минуту, клон `<workdir>/ws/<slug>/s<id>` одноразовым контейнером через релей, каталог запуска tar по SSH), выбор — `pickHost` (наименее занятый онлайн). Веб `/hosts` (суперадмин), «⋯ Настройки проекта → Раннеры»; CLI `peppa host list|key|add|set|check|disable|enable|rm|push-image`. Моки: `mock-docker run` (исполняет команду образа локально, env только из `-e`, `runs.jsonl`), `mock-ssh` (`MOCK_SSH_ROOT/<host>`, свой tmux, `MOCK_SSH_DOWN`)
- хуки не в репо проекта, а в генерируемом `~/.peppa/runs/s<id>-g<gen>/settings.json` (`claude --settings`)
- `PEPPA_SESSION_ID` + `PEPPA_GENERATION`: хук из старого поколения (до resume) игнорируется
- PermissionRequest и AskUserQuestion блокируют и ждут ответ PM из БД (`PEPPA_HOOK_WAIT_SEC`, 540с), потом откат на диалог в терминале; `questions.awaiting_hook` не даёт ответу уйти ещё и в tmux

View File

@ -261,7 +261,10 @@ export async function setRunnerSettingsAction(f: FormData) {
mode: pick("mode"),
context: pick("context"),
workspace: pick("workspace"),
isolation: pick("isolation"),
...(max === "" ? {} : { maxRunners: max === "0" ? null : Number(max) }),
// PEP-40: "" inherit, local — Peppa's machine, list — the ticked hosts.
...(str(f, "hostsMode") === "local" ? { hosts: [] } : str(f, "hostsMode") === "list" ? { hosts: f.getAll("hosts").map(Number).filter((n) => n > 0) } : {}),
});
});
}

View File

@ -74,6 +74,7 @@ export default async function Help() {
<li><b>Раннер</b> — агент, запущенный по стори в tmux на машине Пеппы. Все раннеры твоих и общих проектов — в разделе <Link href="/runners">Раннеры</Link>: статус, стори, команда <code>tmux attach</code>, сообщение, остановка и resume; фильтры-счётчики «ждут тебя / работают / упали / готово» и поиск; строки, где нужен ты, подсвечены, у раннера на лимите — «остановлена · продолжит в HH:MM». Выбери раннер — справа его детали, вопросы, действия и <b>живой терминал</b>: экран агента в реальном времени с историей (прокрутка), размер шрифта A−/A+ и режим во весь экран. Кнопка «Ввод» позволяет печатать агенту прямо в терминал (вставка многострочного текста уходит одной вставкой, для телефона есть Esc, Tab, стрелки, Enter, Ctrl-C); ввод сбрасывает счётчик автопродолжений и отмечается в событиях раннера. Тот же терминал — на странице стори у работающего раннера. Терминал доступен владельцу и участникам проекта.</li>
<li><b>Новый терминал</b> — раннер без стори: в «Раннерах» или на вкладке «Сессии» проекта выбери проект, имя, агента и напиши промпт (можно голосом — кнопка «Голосом» в браузерах с распознаванием речи). После ходов такой раннер не пингует — им управляешь ты в терминале. Получилась работа — «Оформить стори» в карточке раннера: стори создаётся в работе, раннер ведёт её дальше. Раннер можно переименовать.</li>
<li><b>Раннеры и стори</b> — «⋯ Настройки проекта → Раннеры» (и на странице стори — для неё одной): «один раннер на стори» (по умолчанию) или «раннер ведёт очередь стори» — стори достаётся свободному раннеру, при лимите раннеров проекта ждёт в его очереди, а «Принять» не останавливает раннер, а даёт ему следующую стори; переход — «свежий контекст» (тот же терминал, новый разговор) или «один разговор». «Свой git worktree на раннер» — у каждого раннера своя копия и ветка <code>task/…</code>, параллельные стори не мешают друг другу; копия убирается, когда всё запушено. В карточке раннера — история его стори и очередь.</li>
<li><b>Изоляция и хосты</b> — там же: «Контейнер на раннер» запускает агента в docker-образе раннера — он видит только свою рабочую копию, работает на подписке из пула проекта и не видит токенов Пеппы и чужих проектов; хуки, MCP и git идут в Пеппу через релей и только к репозиторию проекта (PR агент открывает инструментом <code>open_pull_request</code>). «Где запускать раннеры» — Mac Пеппы или отмеченные хосты: раннер уходит на наименее занятый онлайн-хост, там клонируется рабочая копия, а терминал, ввод и ответы работают как обычно. Хосты подключает суперадмин в разделе «Хосты» (SSH-ключ Пеппы на хосте, tmux и docker); недоступный хост помечается «офлайн», его раннеры не считаются упавшими.</li>
<li><b>Главная</b> — вопросы агентов (только архитектурные стопперы) и «готово к ревью», активные раннеры и проекты. Отвечать можно в вебе, Telegram или через MCP. Список проектов и «Новый проект» — в разделе <Link href="/projects">Проекты</Link>.</li>
</ul>
</Section>

View File

@ -0,0 +1,73 @@
"use server";
// «Хосты» (PEP-40): every action is superadmin-only (others get "not found").
import { createHost, deleteHost, getHost, PeppaError, requireSuperadmin, setHostDisabled, updateHost } from "@peppa/core";
import { checkHost, ensureSshKey } from "@peppa/runner";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { asWebActor, requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
const str = (f: FormData, k: string) => String(f.get(k) ?? "").trim();
const BASE = "/hosts";
async function attempt(f: FormData, fn: () => Promise<string | void>): Promise<never> {
const user = asWebActor(await requireUser());
let target = BASE;
try {
await requireSuperadmin(db, user);
target = (await fn()) || target;
} catch (e) {
const msg = e instanceof PeppaError ? e.message : `Ошибка: ${(e as Error).message}`;
target = `${BASE}?error=${encodeURIComponent(msg.slice(0, 300))}`;
}
revalidatePath("/", "layout");
redirect(target);
}
const fields = (f: FormData) => ({
sshTarget: str(f, "sshTarget"),
sshPort: str(f, "sshPort") ? Number(str(f, "sshPort")) : undefined,
workdir: str(f, "workdir") || undefined,
peppaUrl: str(f, "peppaUrl") || null,
});
export async function addHostAction(f: FormData) {
await attempt(f, async () => {
await ensureSshKey();
const h = await createHost(db, { name: str(f, "name"), ...fields(f) });
await checkHost(db, h);
return `${BASE}#h-${h.id}`;
});
}
export async function updateHostAction(f: FormData) {
await attempt(f, async () => {
const id = Number(str(f, "id"));
const h = await updateHost(db, id, fields(f));
await checkHost(db, h);
return `${BASE}#h-${id}`;
});
}
export async function checkHostAction(f: FormData) {
await attempt(f, async () => {
const id = Number(str(f, "id"));
await checkHost(db, await getHost(db, id));
return `${BASE}#h-${id}`;
});
}
export async function toggleHostAction(f: FormData) {
await attempt(f, async () => {
const id = Number(str(f, "id"));
await setHostDisabled(db, id, str(f, "disable") === "1");
return `${BASE}#h-${id}`;
});
}
export async function deleteHostAction(f: FormData) {
await attempt(f, async () => {
await deleteHost(db, Number(str(f, "id")));
});
}

View File

@ -0,0 +1,133 @@
import { notFound } from "next/navigation";
import { Plus, RefreshCw, Server, Trash2 } from "lucide-react";
import { HOST_STATUS_RU, isSuperadmin, listHosts, type RunnerHostView } from "@peppa/core";
import { ensureSshKey, runnerImage } from "@peppa/runner";
import { Hidden } from "@/components/cards";
import { ago, Disclosure, Empty, Flash, PageHeader, Section } from "@/components/common";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Input, Label } from "@/components/ui/input";
import { Workspace } from "@/components/Workspace";
import { requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
import { addHostAction, checkHostAction, deleteHostAction, toggleHostAction, updateHostAction } from "./actions";
export const metadata = { title: "Хосты — Пеппа" };
function StatusOf({ h }: { h: RunnerHostView }) {
if (h.disabledAt) return <Badge variant="secondary">отключён</Badge>;
return <Badge variant={h.status === "online" ? "ok" : h.status === "offline" ? "danger" : "info"}>{HOST_STATUS_RU[h.status]}</Badge>;
}
function HostFields({ h }: { h?: RunnerHostView }) {
return (
<div className="grid gap-2 sm:grid-cols-2">
<Label>
SSH-адрес
<Input name="sshTarget" required placeholder="peppa@build1.example.com" defaultValue={h?.sshTarget} className="h-8 font-mono" />
</Label>
<Label>
Порт SSH
<Input name="sshPort" type="number" min={1} max={65535} placeholder="22" defaultValue={h?.sshPort} className="h-8" />
</Label>
<Label>
Каталог на хосте (от домашнего)
<Input name="workdir" placeholder="peppa" defaultValue={h?.workdir} className="h-8 font-mono" />
</Label>
<Label>
Адрес Пеппы для хоста (релей агента)
<Input name="peppaUrl" placeholder="как PEPPA_WEB_URL" defaultValue={h?.peppaUrl ?? ""} className="h-8 font-mono" />
</Label>
</div>
);
}
function HostCard({ h }: { h: RunnerHostView }) {
const i = h.info ?? {};
return (
<Card id={`h-${h.id}`} className="gap-2">
<div className="flex flex-wrap items-center gap-2">
<span className="font-semibold">{h.name}</span>
<span className="font-mono text-xs text-muted-foreground">{h.sshTarget}{h.sshPort !== 22 ? `:${h.sshPort}` : ""}</span>
<StatusOf h={h} />
<span className="ml-auto text-xs text-muted-foreground">раннеров: {h.runners}</span>
</div>
<div className="flex flex-wrap gap-x-4 gap-y-1 text-xs text-muted-foreground">
{i.load != null && <span>загрузка {i.load}{i.cpus ? ` / ${i.cpus} CPU` : ""}</span>}
{i.docker && <span>docker {i.docker}</span>}
{i.tmux && <span>{i.tmux}</span>}
{i.os && <span>{i.os}</span>}
<span>образ раннера: {i.image ? <span className="font-mono">{i.image}</span> : "не загружен"}</span>
<span>проверен {ago(h.lastSeenAt)}</span>
</div>
{h.lastError && <p className="m-0 text-xs text-destructive">{h.lastError}</p>}
<div className="flex flex-wrap gap-2">
<form action={checkHostAction}>
<Hidden fields={{ id: h.id }} />
<Button size="sm" variant="outline"><RefreshCw />Проверить</Button>
</form>
<form action={toggleHostAction}>
<Hidden fields={{ id: h.id, disable: h.disabledAt ? "0" : "1" }} />
<Button size="sm" variant="outline">{h.disabledAt ? "Включить" : "Отключить"}</Button>
</form>
<form action={deleteHostAction}>
<Hidden fields={{ id: h.id }} />
<Button size="sm" variant="ghost" disabled={h.runners > 0} title={h.runners > 0 ? "На хосте работают раннеры" : undefined}><Trash2 />Удалить</Button>
</form>
</div>
<Disclosure summary="Изменить">
<form action={updateHostAction} className="flex flex-col gap-2">
<Hidden fields={{ id: h.id }} />
<HostFields h={h} />
<Button size="sm" variant="default" className="self-start">Сохранить и проверить</Button>
</form>
</Disclosure>
</Card>
);
}
export default async function Hosts({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
const user = await requireUser();
if (!(await isSuperadmin(db, user))) notFound();
const { error } = await searchParams;
const [hosts, pub] = await Promise.all([listHosts(db), ensureSshKey().catch((e: Error) => `(ключ не создан: ${e.message})`)]);
return (
<Workspace>
<div className="max-w-3xl">
<Flash error={error} />
<PageHeader title={<><Server className="mr-1 inline size-5 text-primary" />Хосты</>}>
Серверы, на которых работают раннеры. Пеппа заходит на хост по SSH своим ключом и запускает там tmux с агентом в контейнере образа раннера; агент ходит в Пеппу только через релей. Демона на хосте нет — нужны sshd, tmux и docker. Проект выбирает хосты в «⋯ Настройки проекта → Раннеры». Раздел видят только суперадмины.
</PageHeader>
<Section title="Хосты" count={hosts.length}>
{hosts.length === 0 ? <Empty>Хостов нет — раннеры работают на Mac Пеппы.</Empty> : hosts.map((h) => <HostCard key={h.id} h={h} />)}
<Disclosure summary={<span className="flex items-center gap-1.5"><Plus className="size-4" />Подключить хост</span>}>
<form action={addHostAction} className="flex flex-col gap-2">
<Label>
Имя
<Input name="name" required placeholder="build1" className="h-8" />
</Label>
<HostFields />
<Button size="sm" variant="default" className="self-start">Подключить и проверить</Button>
</form>
</Disclosure>
</Section>
<Section title="Как подготовить хост">
<ol className="m-0 flex list-decimal flex-col gap-2 pl-5 text-sm">
<li>
Добавьте ключ Пеппы в <code>~/.ssh/authorized_keys</code> пользователя на хосте:
<pre className="mt-1 overflow-x-auto rounded-md bg-muted p-2 text-xs"><code>{pub}</code></pre>
</li>
<li>Установите tmux и docker; пользователь должен иметь доступ к docker.</li>
<li>
Загрузите образ раннера <code>{runnerImage()}</code>: <code>scripts/runner-image.sh --push &lt;имя хоста&gt;</code> (или <code>peppa host push-image &lt;имя&gt;</code>).
</li>
<li>Адрес Пеппы для хоста должен открываться с хоста (по умолчанию — адрес веба); через него идут хуки, MCP и git агента.</li>
</ol>
</Section>
</div>
</Workspace>
);
}

View File

@ -1,7 +1,7 @@
import { notFound } from "next/navigation";
import { ExternalLink, Plus, Rocket, SquareTerminal } from "lucide-react";
import { columnOf, currentReleases, describeRepo, isPlatform, listReleases, bugsinkWebhookBase, openPulls, platformReleaseCandidate, platformReleaseOffers, repoOverview, type Release } from "@peppa/runner";
import { DEFAULT_RUNNER_SETTINGS, DEFAULT_AGENT_SETTINGS, getProjectAgentSettings, getSystemAgentSettings, getProjectRunnerSettings, getSystemRunnerSettings, blockedLabel, blockersMap, epicProgress, progressLabel, taskProgress, getProjectBudget, listJournal, listProjectSecrets, projectMetrics, type ActorChannel, type ActorKind, getAutonomy, getIncidentSettings, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, projectAgentWarning, memoryStats, readMemory, projectPool, repoAudience, repoVisibilityLabel } from "@peppa/core";
import { listHosts, DEFAULT_RUNNER_SETTINGS, DEFAULT_AGENT_SETTINGS, getProjectAgentSettings, getSystemAgentSettings, getProjectRunnerSettings, getSystemRunnerSettings, blockedLabel, blockersMap, epicProgress, progressLabel, taskProgress, getProjectBudget, listJournal, listProjectSecrets, projectMetrics, type ActorChannel, type ActorKind, getAutonomy, getIncidentSettings, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, projectAgentWarning, memoryStats, readMemory, projectPool, repoAudience, repoVisibilityLabel } from "@peppa/core";
import { LiveRefresh } from "@/components/LiveRefresh";
import { PanelSection } from "@/components/ActivityAside";
import { Board, type Card } from "@/components/Board";
@ -101,7 +101,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
const superadmin = await isSuperadmin(db, user);
const [pool, pools, autonomy] = await Promise.all([projectPool(db, p.id), superadmin ? listPools(db) : Promise.resolve([]), getAutonomy(db, p.id)]);
// PEP-10/27: runner settings of the project over the system ones.
const [runnerOwn, runnerSystem, secrets] = await Promise.all([getProjectRunnerSettings(db, p.id), getSystemRunnerSettings(db), listProjectSecrets(db, p.id)]);
const [runnerOwn, runnerSystem, secrets, runnerHosts] = await Promise.all([getProjectRunnerSettings(db, p.id), getSystemRunnerSettings(db), listProjectSecrets(db, p.id), listHosts(db, { enabled: true })]);
// PEP-41: agent provider/model of the project over the platform's.
const [agentOwn, agentSystem] = await Promise.all([getProjectAgentSettings(db, p.id), getSystemAgentSettings(db)]);
// PEP-31: the project's pool has no working subscription — agents won't start.
@ -180,7 +180,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
</PanelSection>
<PanelSection title="Раннеры">
<RunnerSettingsPanel projectId={p.id} own={runnerOwn} inherited={{ ...DEFAULT_RUNNER_SETTINGS, ...runnerSystem }} back={back} />
<RunnerSettingsPanel projectId={p.id} own={runnerOwn} inherited={{ ...DEFAULT_RUNNER_SETTINGS, ...runnerSystem }} back={back} hosts={runnerHosts} />
</PanelSection>
<PanelSection title="Модель агента">

View File

@ -89,6 +89,9 @@ export default async function Settings({ searchParams }: { searchParams: Promise
<Button asChild size="sm">
<a href="/secrets">Секреты</a>
</Button>
<Button asChild size="sm">
<a href="/hosts">Хосты</a>
</Button>
<Button asChild size="sm">
<a href="/journal">Журнал</a>
</Button>

View File

@ -0,0 +1,18 @@
import { agentRelayMcp } from "@peppa/mcp/relay";
import { handleAgentRelay } from "@peppa/runner";
import { db } from "@/lib/db";
export const dynamic = "force-dynamic";
// A blocking hook (question to the PM) is answered in ≤25 s chunks (`wait` + `rid`).
export const maxDuration = 60;
/**
* PEP-17: the agent relay — hooks, MCP and git of agents in runner containers (here or on
* runner hosts, PEP-40). No web login: Bearer = the run's own token.
*/
async function handle(req: Request, { params }: { params: Promise<{ path: string[] }> }) {
const { path } = await params;
return handleAgentRelay(db, req, `/${path.join("/")}`, { mcp: agentRelayMcp });
}
export const GET = handle;
export const POST = handle;

View File

@ -146,6 +146,11 @@ export function RunnerDetails({ s, questions, events, steps, stories, back, clos
{s.subscriptionName ?? (s.subscriptionId ? `#${s.subscriptionId}` : "вход машины")}
{s.subscriptionSwitches > 0 && <span className="text-muted-foreground"> · переключений {s.subscriptionSwitches}</span>}
</dd>
<dt className="text-muted-foreground">Где</dt>
<dd className="m-0">
{s.host ? `хост ${s.host.name}` : "Mac Пеппы"}
{s.container ? <span className="text-muted-foreground"> · контейнер {s.container}</span> : <span className="text-muted-foreground"> · без изоляции</span>}
</dd>
<dt className="text-muted-foreground">Запущен</dt>
<dd className="m-0">{ago(s.startedAt)}</dd>
<dt className="text-muted-foreground">Активность</dt>

View File

@ -7,6 +7,10 @@ import {
RUNNER_MODES,
RUNNER_WORKSPACE_RU,
RUNNER_WORKSPACES,
RUNNER_ISOLATION_RU,
RUNNER_ISOLATIONS,
HOST_STATUS_RU,
type RunnerHost,
type RunnerSettings,
type RunnerSettingsPatch,
type RunnerTaskView,
@ -69,7 +73,8 @@ export function NewRunnerForm({ projects, projectId, back }: { projects?: Array<
const inherit = (label: string) => `Как выше: ${label}`;
/** «⋯ Настройки проекта → Раннеры»: overrides of the project; empty = system. */
export function RunnerSettingsPanel({ projectId, own, inherited, back }: { projectId: number; own: RunnerSettingsPatch; inherited: RunnerSettings; back: string }) {
export function RunnerSettingsPanel({ projectId, own, inherited, back, hosts = [] }: { projectId: number; own: RunnerSettingsPatch; inherited: RunnerSettings; back: string; hosts?: Pick<RunnerHost, "id" | "name" | "status">[] }) {
const hostNames = (ids: number[]) => (ids.length ? ids.map((id) => hosts.find((h) => h.id === id)?.name ?? `#${id}`).join(", ") : "Mac Пеппы");
return (
<form action={setRunnerSettingsAction} className="flex flex-col gap-3">
<Hidden fields={{ projectId, back }} />
@ -104,6 +109,36 @@ export function RunnerSettingsPanel({ projectId, own, inherited, back }: { proje
Лимит раннеров проекта (пусто — {inherited.maxRunners ? `как выше: ${inherited.maxRunners}` : "без лимита"}, 0 — без лимита)
<Input name="maxRunners" type="number" min={0} max={50} defaultValue={own.maxRunners === undefined ? "" : (own.maxRunners ?? 0)} className="h-8" />
</Label>
<Label>
Изоляция агента
<NativeSelect name="isolation" defaultValue={own.isolation ?? ""} className="h-8">
<option value="">{inherit(RUNNER_ISOLATION_RU[inherited.isolation])}</option>
{RUNNER_ISOLATIONS.map((m) => (
<option key={m} value={m}>{RUNNER_ISOLATION_RU[m]}</option>
))}
</NativeSelect>
</Label>
<Label>
Где запускать раннеры
<NativeSelect name="hostsMode" defaultValue={own.hosts === undefined ? "" : own.hosts.length ? "list" : "local"} className="h-8">
<option value="">{inherit(hostNames(inherited.hosts))}</option>
<option value="local">Mac Пеппы</option>
<option value="list" disabled={!hosts.length}>Хосты, отмеченные ниже (наименее занятый онлайн)</option>
</NativeSelect>
</Label>
{hosts.length > 0 && (
<div className="flex flex-wrap gap-x-4 gap-y-1 text-sm">
{hosts.map((h) => (
<label key={h.id} className="flex items-center gap-1.5">
<input type="checkbox" name="hosts" value={h.id} defaultChecked={(own.hosts ?? []).includes(h.id)} /> {h.name}
<span className="text-xs text-muted-foreground">({HOST_STATUS_RU[h.status]})</span>
</label>
))}
</div>
)}
<p className="m-0 text-xs text-muted-foreground">
Контейнер: агент работает в docker-образе раннера и видит только свою рабочую копию; токены Пеппы и чужие проекты ему недоступны, нужна подписка в пуле проекта. На хосте агент всегда в контейнере.
</p>
<p className="m-0 text-xs text-muted-foreground">
Очередь: стори достаётся свободному раннеру, при лимите ждёт в очереди; «Принять» не останавливает раннер, а даёт ему следующую стори. Свой worktree: у каждого раннера своя копия и ветка <code>task/…</code>, параллельные стори не мешают друг другу.
</p>

View File

@ -2,7 +2,7 @@
import Link from "next/link";
import { usePathname } from "next/navigation";
import { Bot, FolderKanban, House, KeyRound, ScrollText, LifeBuoy, LogOut, Search, Settings, ShieldCheck, Users, type LucideIcon } from "lucide-react";
import { Bot, FolderKanban, House, KeyRound, ScrollText, LifeBuoy, LogOut, Search, Server, Settings, ShieldCheck, Users, type LucideIcon } from "lucide-react";
import { Brand } from "@/components/Brand";
import { ThemeToggle } from "@/components/ThemeToggle";
import { Button } from "@/components/ui/button";
@ -25,6 +25,7 @@ const ITEMS: Item[] = [
{ href: "/help", label: "Помощь", icon: LifeBuoy, match: (p) => p.startsWith("/help") },
{ href: "/subscriptions", label: "Подписки", icon: KeyRound, match: (p) => p.startsWith("/subscriptions"), admin: true },
{ href: "/secrets", label: "Секреты", icon: ShieldCheck, match: (p) => p.startsWith("/secrets"), admin: true },
{ href: "/hosts", label: "Хосты", icon: Server, match: (p) => p.startsWith("/hosts"), admin: true },
{ href: "/journal", label: "Журнал", icon: ScrollText, match: (p) => p.startsWith("/journal"), admin: true },
{ href: "/users", label: "Пользователи", icon: Users, match: (p) => p.startsWith("/users"), admin: true },
{ href: "/settings", label: "Настройки", icon: Settings, match: (p) => p.startsWith("/settings") },

View File

@ -130,6 +130,8 @@ export function SessionCard({ s, back, showTitle = false, terminal = false, step
<span className="ml-auto font-mono text-xs text-muted-foreground">
<Link href={`/runners?id=${s.id}`} className="text-muted-foreground hover:text-foreground">#{s.id}</Link> · {s.provider}
{s.subscriptionName && <> · {s.subscriptionName}</>}
{s.host && <> · {s.host.name}</>}
{s.container && <> · в контейнере</>}
{s.subscriptionSwitches > 0 && <> · переключений {s.subscriptionSwitches}</>} · пок. {s.generation} · {ago(s.lastActivityAt)}
</span>
</header>

34
infra/runner/Dockerfile Normal file
View File

@ -0,0 +1,34 @@
# PEP-17/40: the runner image — the agent of one runner (Claude Code, Codex, OpenCode) with
# git and common build tools, and Peppa's shims (peppa-hook, peppa-mcp) that reach Peppa only
# through the agent relay. Same image on Peppa's machine and on runner hosts.
# Build: scripts/runner-image.sh (tag: $PEPPA_RUNNER_IMAGE, default peppa/runner:latest)
FROM node:22-bookworm-slim
ARG CLAUDE_CODE_VERSION=latest
ARG CODEX_VERSION=latest
ARG OPENCODE_VERSION=latest
ARG PNPM_VERSION=10
RUN apt-get update \
&& apt-get install -y --no-install-recommends git ca-certificates curl ripgrep jq less procps python3 make g++ unzip \
&& rm -rf /var/lib/apt/lists/*
RUN npm install -g --no-fund --no-audit \
"@anthropic-ai/claude-code@${CLAUDE_CODE_VERSION}" \
"@openai/codex@${CODEX_VERSION}" \
"opencode-ai@${OPENCODE_VERSION}" \
"pnpm@${PNPM_VERSION}" \
&& npm cache clean --force
COPY peppa-agent.mjs bin/peppa-hook bin/peppa-mcp /usr/local/bin/
RUN chmod 755 /usr/local/bin/peppa-hook /usr/local/bin/peppa-mcp \
# The runner runs as the host user (--user uid:gid): repos are owned by someone "else".
&& git config --system safe.directory '*' \
&& git config --system init.defaultBranch main \
&& mkdir -p /peppa/home /peppa/run && chmod 1777 /peppa/home
ENV HOME=/peppa/home \
DISABLE_AUTOUPDATER=1 \
CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1
WORKDIR /peppa/home
LABEL org.opencontainers.image.title="peppa-runner" quest.telecom.peppa.component="runner"

View File

@ -0,0 +1 @@
../peppa-agent.mjs

3
infra/runner/bin/peppa-hook Executable file
View File

@ -0,0 +1,3 @@
#!/bin/sh
# PEP-17: Claude/Codex hooks inside the runner container → the agent relay.
exec node "$(dirname "$0")/peppa-agent.mjs" hook "$@"

3
infra/runner/bin/peppa-mcp Executable file
View File

@ -0,0 +1,3 @@
#!/bin/sh
# PEP-17: the peppa MCP server inside the runner container (stdio ↔ the agent relay).
exec node "$(dirname "$0")/peppa-agent.mjs" mcp "$@"

View File

@ -0,0 +1,122 @@
// PEP-17: Peppa's side inside the runner container — hooks and the peppa MCP server of the agent
// talk to Peppa only through the agent relay (PEPPA_AGENT_URL, Bearer PEPPA_AGENT_TOKEN).
// No dependencies (node ≥ 18). Usage: peppa-agent hook <event> [args…] | peppa-agent mcp
// (wrappers peppa-hook / peppa-mcp). A hook never breaks the agent: always exits 0.
import { readFileSync, statSync, openSync, readSync, closeSync } from "node:fs";
import { createInterface } from "node:readline";
const URL_BASE = (process.env.PEPPA_AGENT_URL || "").replace(/\/$/, "");
const TOKEN = process.env.PEPPA_AGENT_TOKEN || "";
const TRANSCRIPT_EVENTS = new Set(["stop", "stop-failure", "session-end"]);
const TRANSCRIPT_MAX = 8 * 1024 * 1024;
const HOOK_DEADLINE_MS = 15 * 60_000;
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const headers = (extra = {}) => ({ Authorization: `Bearer ${TOKEN}`, ...extra });
function readStdin() {
try {
return readFileSync(0, "utf8");
} catch {
return "";
}
}
/** Last TRANSCRIPT_MAX bytes of the transcript, from the first full line. */
function transcriptTail(path) {
try {
const size = statSync(path).size;
const len = Math.min(size, TRANSCRIPT_MAX);
const buf = Buffer.alloc(len);
const fd = openSync(path, "r");
readSync(fd, buf, 0, len, size - len);
closeSync(fd);
let text = buf.toString("utf8");
if (len < size) text = text.slice(text.indexOf("\n") + 1);
return text;
} catch {
return undefined;
}
}
async function post(path, body, extraHeaders) {
return fetch(`${URL_BASE}${path}`, { method: "POST", headers: headers({ "Content-Type": "application/json", ...extraHeaders }), body: JSON.stringify(body) });
}
async function hook(event, args) {
const stdin = readStdin();
if (!URL_BASE || !TOKEN || !event) return "";
let transcript;
if (TRANSCRIPT_EVENTS.has(event)) {
try {
const p = JSON.parse(stdin).transcript_path;
if (p) transcript = transcriptTail(p);
} catch {}
}
const deadline = Date.now() + HOOK_DEADLINE_MS;
let body = { event, args, stdin, transcript };
let failures = 0;
while (Date.now() < deadline) {
try {
const res = await post("/api/agent/hook", body);
if (res.status === 401 || res.status === 404 || res.status === 400) return "";
if (!res.ok) throw new Error(`relay ${res.status}`);
const r = await res.json();
if (r.wait && r.rid) {
body = { rid: r.rid };
failures = 0;
continue;
}
return typeof r.stdout === "string" ? r.stdout : "";
} catch {
if (++failures > 5) return "";
await sleep(1000 * failures);
}
}
return "";
}
/** stdio MCP ↔ the relay's Streamable HTTP endpoint (stateless, JSON responses). */
async function mcp() {
const out = (msg) => process.stdout.write(`${JSON.stringify(msg)}\n`);
let chain = Promise.resolve();
const rl = createInterface({ input: process.stdin });
rl.on("line", (line) => {
if (!line.trim()) return;
chain = chain.then(async () => {
let msg;
try {
msg = JSON.parse(line);
} catch {
return;
}
const id = Array.isArray(msg) ? undefined : msg.id;
try {
const res = await post("/api/agent/mcp", msg, { Accept: "application/json, text/event-stream" });
const text = await res.text();
if (res.status === 202 || !text.trim()) return;
if ((res.headers.get("content-type") || "").includes("text/event-stream")) {
for (const l of text.split("\n")) if (l.startsWith("data:")) out(JSON.parse(l.slice(5)));
return;
}
const r = JSON.parse(text);
if (!res.ok && id !== undefined && !r.jsonrpc) throw new Error(r.error || `relay ${res.status}`);
for (const m of Array.isArray(r) ? r : [r]) out(m);
} catch (e) {
if (id !== undefined) out({ jsonrpc: "2.0", id, error: { code: -32603, message: `Peppa relay: ${e.message}` } });
}
});
});
rl.on("close", () => chain.then(() => process.exit(0)));
}
const [mode, ...rest] = process.argv.slice(2);
if (mode === "hook") {
const stdout = await hook(rest[0], rest.slice(1));
process.stdout.write(stdout, () => process.exit(0));
} else if (mode === "mcp") {
await mcp();
} else {
process.stderr.write("usage: peppa-agent hook <event> [args…] | peppa-agent mcp\n");
process.exit(2);
}

View File

@ -0,0 +1,90 @@
# Design: PEP-17 + PEP-40
## Где что выполняется
```
Пеппа (Mac) хост (Mac Пеппы или SSH-сервер)
runner ── exec(local | ssh host) ──▶ tmux peppa-<key>-s<id>
└─ docker run peppa/runner (isolation=container)
agent CLI ── hooks/MCP/git ──┐
web /api/agent/* ◀────────────── HTTP (Bearer токен сессии) ───────────────┘
```
- tmux всегда снаружи контейнера: вачдог, терминал в вебе (PEP-9) и ввод работают как
раньше, только команда tmux идёт через `exec` (локально или `ssh`).
- `isolation=none` и пустые `hosts` — ровно прежний путь (локальный tmux, агент на Mac).
- Удалённый хост всегда запускает агента в контейнере: на хосте нужны только sshd, tmux и
docker (+ образ). Codex на удалённом хосте пока не поддерживается (его вход — каталог
`CODEX_HOME` на Mac Пеппы); локальный контейнер монтирует `CODEX_HOME` подписки.
## Контейнер
`docker run --rm -it --init --name peppa-s<id> --user <uid:gid хоста>`:
- `-v <рабочая копия>:<тот же путь>` (+ `-v <проект>/.git:<тот же путь>` для worktree, чтобы
`.git`-файл worktree указывал в смонтированное),
- `-v <runs/s<id>-g<gen>>:/peppa/run:ro` — settings.json, rules.md, opencode.json; argv
агента ссылается на `/peppa/run/…`, хуки — голые `peppa-hook <event>` из образа,
- `-v <sandboxes/s<id>/home>:/peppa/home` — свой `HOME` агента (история разговоров для
`--resume`, `.claude.json` с доверием каталогу и пройденным онбордингом),
- `-e` только: `PEPPA_SESSION_ID`, `PEPPA_GENERATION`, `PEPPA_AGENT_URL`,
`PEPPA_AGENT_TOKEN`, `HOME`, переменные подписки (`CLAUDE_CODE_OAUTH_TOKEN`, ключ
OpenCode, `CODEX_HOME`), `OPENCODE_CONFIG`.
- Без подписки контейнер не стартует: у агента в контейнере нет входа машины — «нужна подписка».
- Остановка: `tmux kill-session` + `docker rm -f peppa-s<id>` (клиент docker под tmux может
умереть раньше контейнера); перед запуском — тоже `rm -f` (остаток прошлого поколения).
- Сеть — обычная bridge (нужны API провайдера и Gitea). Файлы Пеппы, `.env`, `~/.ssh`, база и
чужие рабочие копии в контейнер не смонтированы — это и есть граница PEP-17.
## Релей агента
Токен сессии: `base64url(sessionId.generation.hmac)`, HMAC-SHA256 ключом `key("agent")`
(core/crypto.ts, из секрета Пеппы). Принимается, пока поколение текущее и сессия не завершена.
- `POST /api/agent/hook {event, args, stdin, transcript?}` → Пеппа запускает настоящий
`peppa-hook` с env сессии, отдаёт stdout. Блокирующие хуки (вопрос PM до 540 с) не
держат HTTP дольше 25 с: ответ `{wait, rid}`, шим повторяет с `rid` — переживает лимит
Cloudflare в 100 с для удалённых хостов. Транскрипт (для учёта токенов и последней реплики)
шим прикладывает к stop/stop-failure/session-end (хвост ≤ 8 МБ), Пеппа кладёт его во
временный файл и подменяет `transcript_path`.
- `POST /api/agent/mcp` — Streamable HTTP (stateless) MCP-сервер агента для проекта сессии;
стори других проектов отклоняются. Шим `peppa-mcp` — stdio ↔ HTTP.
- `/api/agent/git/<owner>/<repo>.git/…` и `/api/agent/git/api/v1/repos/<owner>/<repo>/…` —
прокси в Gitea с токеном peppa-bot, только к репозиторию проекта сессии. В контейнере git
направлен туда через `GIT_CONFIG_*` (`url.<relay>.insteadOf <gitea>` + заголовок
авторизации), так что `git push` работает как раньше, а токен бота в контейнер не попадает.
- Обработчики — в `runner/agent-relay.ts` (чистые функции Request→Response); веб — тонкие
маршруты; тесты поднимают тот же обработчик на `node:http`.
- Адрес релея: локальный контейнер — `PEPPA_AGENT_URL` (по умолчанию
`http://host.docker.internal:<порт веба>`), хост — `runner_hosts.peppa_url`
(по умолчанию `PEPPA_WEB_URL`).
## Хосты (SSH)
- Ключ Пеппы: `$PEPPA_HOME/ssh/id_ed25519` (создаётся `ssh-keygen` при первом обращении),
публичный — в «Хостах» для `authorized_keys`. `ssh -o BatchMode=yes -o ControlMaster=auto
-o ControlPersist=10m -o ControlPath=$PEPPA_HOME/ssh/cm-%C -o StrictHostKeyChecking=accept-new`.
Бинарь — `PEPPA_SSH_BIN` (в тестах `mock-ssh`).
- Ошибка соединения (код 255) → `HostUnreachable`: `hasSession` его не глотает, вачдог
пропускает сессию (лог), а не объявляет её пропавшей; `hostTick` ставит хосту `offline`.
- Каталог хоста `workdir` (по умолчанию `~/peppa`): `<workdir>/ws/<slug>/s<id>` — клон
репозитория на ветке `task/<KEY>` (через одноразовый контейнер с релеем: на хосте нет
токена), `<workdir>/runs/s<id>-g<gen>` — каталог запуска (tar по SSH),
`<workdir>/home/s<id>`.
- Выбор хоста: `hosts` из настроек раннеров → онлайн и не отключённые → наименьшее число
живых раннеров. Нет доступного → ошибка запуска «нет доступного хоста».
- Терминал PEP-9 на удалённом раннере — те же `capture-pane`/`send-keys` через SSH; один
цикл опроса на раннер, ControlMaster держит одно соединение.
## Модель данных
- `runner_hosts`: id, name (уникальное), ssh_target, ssh_port, workdir, peppa_url,
status (`unknown|online|offline`), info (JSON: os, docker, tmux, load, cpus, image),
last_seen_at, last_error, disabled_at, created_at.
- `sessions.host_id` (null = Mac Пеппы), `sessions.container` (имя контейнера или null).
- Настройки раннеров (JSON в `settings`, без миграции): `isolation`, `hosts`.
## Что на моках
- docker — `mock-docker run` исполняет команду образа локально с env только из `-e`,
`PATH` образа = `infra/runner/bin` (+ `MOCK_DOCKER_PATH`), `-w`; пишет вызовы и монтирования.
- SSH — `mock-ssh`: тот же синтаксис, выполняет команду через `sh -c` в «хосте»
(`MOCK_SSH_ROOT/<host>`: свой `HOME`, свой `TMUX_TMPDIR` → свой tmux-сервер),
`MOCK_SSH_DOWN=<host>` — код 255.
## Альтернативы
- Отдельный системный пользователь macOS вместо docker — не переносится на хосты, PM выбрал контейнер.
- Монтировать базу в контейнер ради хуков — ломает изоляцию; релей по HTTP проще и общий для хостов.
- Deploy-ключи Gitea на проект — честнее прокси, но требует SSH-доступа к Gitea из контейнеров;
прокси даёт ту же границу (только свой репозиторий) без новых портов.

View File

@ -0,0 +1,44 @@
# PEP-17 + PEP-40: песочница агента и хосты раннеров
## Why
Агент работает под тем же пользователем macOS, что и Пеппа: видит `.env` с токенами,
`~/.ssh`, базу `~/.peppa/peppa.db` и рабочие копии чужих проектов. И раннеры живут только
на Mac Пеппы — нельзя добавить мощностей, подключив ещё один сервер.
Решения PM (2026-11-13): контейнер на раннер — tmux снаружи, агент в docker с примонтированной
только своей рабочей копией и своим токеном; тот же образ — на хостах. На хост Пеппа ходит по
SSH своим ключом; агента-демона на хосте нет; терминал в вебе — поток через SSH.
## What Changes
- **Песочница (PEP-17)**: настройка раннеров `isolation` = `none` (по умолчанию, как сейчас) |
`container`. В контейнере tmux запускает `docker run` образа `peppa/runner` (`infra/runner/`):
смонтированы только рабочая копия раннера (и `.git` проекта для worktree), каталог запуска
(настройки/правила, только чтение) и свой домашний каталог агента; переменные — только
сессии (`PEPPA_SESSION_ID`, поколение, адрес и токен релея) и логин подписки.
- **Релей агента**: хуки, MCP `peppa` и git внутри контейнера не видят базу и токены — их
шимы (`peppa-agent` в образе: `peppa-hook`, `peppa-mcp`, `git-credential-peppa`) ходят в
Пеппу по HTTP (`/api/agent/*`) с токеном сессии (HMAC от секрета Пеппы, сессии и поколения).
Пеппа выполняет настоящий хук, MCP-сервер агента (только проект сессии) и проксирует git и
API Gitea только к репозиторию проекта. Токен Gitea в контейнер не попадает.
- **Хосты раннеров (PEP-40)**: таблица `runner_hosts` (имя, `user@host`, порт, каталог, адрес
Пеппы для релея, статус, сведения). Пеппа ходит на хост по SSH ключом
`$PEPPA_HOME/ssh/id_ed25519` (ControlMaster), запускает там tmux + тот же контейнер;
рабочая копия раннера клонируется на хосте через релей. Настройка раннеров `hosts`
(список id; пусто — Mac Пеппы) — выбирается наименее занятый онлайн-хост.
- Все операции tmux (вачдог, терминал PEP-9, ввод, ответы PM) идут через адрес pane
(`{name, host}`): локально или `ssh host tmux …`. Недоступный хост не «убивает» сессии.
- Вачдог раз в минуту проверяет хосты (`hostTick`): онлайн/офлайн, загрузка, версии.
- Веб: раздел «Хосты» (суперадмин: добавить, проверить, отключить, публичный ключ Пеппы),
«⋯ Настройки проекта → Раннеры»: изоляция и хосты; в карточке раннера — хост и контейнер.
CLI `peppa host …`, `peppa runner settings … isolation= hosts=`. MCP агента:
`open_pull_request`.
## Impact
- Миграция: `runner_hosts`, `sessions.host_id`, `sessions.container`.
- `packages/runner`: `exec.ts` (локально/SSH), `tmux.ts` (адрес pane), `sandbox.ts`,
`hosts.ts`, `agent-relay.ts`; `sessions.ts`, вачдог, терминал.
- `packages/mcp`: фабрика сервера агента (`agent.ts`) для stdio и релея.
- `apps/web`: `/api/agent/{hook,mcp,git}`, `/hosts`, настройки раннеров.
- `infra/runner/Dockerfile` + `peppa-agent.mjs`, `scripts/runner-image.sh`.
- Моки: `mock-docker run/rm/ps`, `mock-ssh`.
- По умолчанию поведение не меняется (`isolation=none`, без хостов).

View File

@ -0,0 +1,55 @@
## ADDED Requirements
### Requirement: Агент в контейнере
Настройка раннеров `isolation` SHALL выбирать, где работает агент: `none` (по умолчанию —
процесс на машине, как раньше) или `container`. В режиме `container` tmux раннера запускает
агента в docker-образе раннера, в который смонтированы только рабочая копия раннера (и `.git`
проекта для worktree), каталог запуска (только чтение) и свой домашний каталог агента, а
переменные окружения — только сессии, релея и подписки.
#### Scenario: Запуск в контейнере
- **GIVEN** у проекта PAY `isolation=container` и подписка Claude в пуле проекта
- **WHEN** PM переносит PAY-3 в «В работе»
- **THEN** в tmux раннера запущен `docker run` с монтированием рабочей копии PAY
- **AND** в окружении контейнера есть `CLAUDE_CODE_OAUTH_TOKEN` подписки, но нет `PEPPA_DB` и `GITEA_TOKEN`
#### Scenario: Без настройки — как раньше
- **GIVEN** у проекта нет настройки `isolation`
- **WHEN** запускается раннер
- **THEN** агент запускается в tmux без docker, как до PEP-17
#### Scenario: Нет подписки
- **GIVEN** у проекта `isolation=container` и нет ни одной подписки
- **WHEN** запускается раннер
- **THEN** запуск отклоняется с сообщением «для контейнера нужна подписка»
#### Scenario: Остановка убирает контейнер
- **GIVEN** раннер PAY-3 работает в контейнере `peppa-s12`
- **WHEN** PM останавливает раннер
- **THEN** tmux-сессия закрыта и выполнен `docker rm -f peppa-s12`
### Requirement: Релей агента
Хуки, MCP-сервер `peppa` и git агента в контейнере SHALL обращаться к Пеппе только через
релей `/api/agent/*` с токеном своей сессии. Токен действителен для текущего поколения
незавершённой сессии; MCP через релей работает только со стори проекта сессии; git и API Gitea
проксируются только к репозиторию проекта.
#### Scenario: Хук через релей
- **GIVEN** агент PAY-3 в контейнере заканчивает ход
- **WHEN** срабатывает Stop-хук
- **THEN** Пеппа получает его через релей и отмечает ход сессии так же, как у локального агента
#### Scenario: Чужой или старый токен
- **GIVEN** сессия #12 перезапущена (поколение 2)
- **WHEN** приходит запрос релея с токеном поколения 1 или с испорченной подписью
- **THEN** ответ 401, хук не выполняется
#### Scenario: Чужой проект через MCP
- **GIVEN** агент PAY-3 работает через релей
- **WHEN** он вызывает `get_task` для стори SHOP-1 другого проекта
- **THEN** инструмент возвращает ошибку доступа, данные SHOP-1 не отдаются
#### Scenario: Git только к своему репозиторию
- **GIVEN** агент PAY-3 работает через релей
- **WHEN** он запрашивает через прокси репозиторий другого проекта
- **THEN** ответ 403, к Gitea запрос не уходит

View File

@ -0,0 +1,39 @@
## ADDED Requirements
### Requirement: Хосты раннеров по SSH
Суперадмин SHALL подключать серверы для раннеров: имя, `user@host`, порт, каталог, адрес
Пеппы для релея. Пеппа ходит на хост по SSH своим ключом (публичный показан в «Хостах»),
раз в минуту проверяет его (онлайн/офлайн, загрузка, версии docker и tmux) и запускает там
tmux с агентом в том же контейнере, что и локально. Агента-демона на хосте нет.
#### Scenario: Подключить хост
- **GIVEN** на сервере `build1` ключ Пеппы в `authorized_keys`, есть tmux и docker
- **WHEN** суперадмин добавляет хост «build1» `peppa@build1` и нажимает «Проверить»
- **THEN** хост в статусе «онлайн», видны версии docker и tmux и загрузка
#### Scenario: Хост недоступен
- **GIVEN** хост «build1» онлайн и на нём работает раннер PAY-3
- **WHEN** SSH к хосту перестаёт отвечать
- **THEN** хост становится «офлайн», а раннер PAY-3 не объявляется пропавшим
#### Scenario: Не суперадмин
- **GIVEN** пользователь не в `platform.admins`
- **WHEN** он открывает `/hosts`
- **THEN** ответ 404
### Requirement: Раннеры на хостах
Настройка раннеров `hosts` (список хостов; пусто — Mac Пеппы) SHALL направлять новые раннеры
проекта на наименее занятый онлайн-хост из списка. Рабочая копия раннера клонируется на хосте,
агент работает в контейнере, хуки и MCP идут через релей, терминал в вебе и ввод работают
через SSH.
#### Scenario: Раннер на хосте
- **GIVEN** у проекта PAY `hosts=[build1]`, хост онлайн, подписка Claude в пуле
- **WHEN** PM переносит PAY-3 в «В работе»
- **THEN** на build1 появляется клон PAY на ветке `task/PAY-3` и tmux-сессия раннера
- **AND** терминал раннера в вебе показывает экран агента с build1
#### Scenario: Нет доступного хоста
- **GIVEN** у проекта PAY `hosts=[build1]`, хост офлайн
- **WHEN** запускается раннер
- **THEN** запуск отклоняется с сообщением «нет доступного хоста»

View File

@ -0,0 +1,26 @@
# Tasks: PEP-17 + PEP-40
## 1. Основа
- [x] 1.1 Схема и миграция: `runner_hosts`, `sessions.host_id`, `sessions.container`; core `hosts.ts`, `SessionView.host`
- [x] 1.2 Настройки раннеров: `isolation`, `hosts`
- [x] 1.3 `runner/exec.ts` (локально / SSH, ключ Пеппы, `HostUnreachable`), `tmux.ts` по адресу pane, перевод вызовов
## 2. Песочница
- [x] 2.1 `runner/sandbox.ts`: команда `docker run`, монтирования, env, домашний каталог агента, `docker rm -f`
- [x] 2.2 `sessions.ts`: запуск/resume/fresh/stop с контейнером; пути в argv агента
- [x] 2.3 Образ `infra/runner/` (Dockerfile, `peppa-agent.mjs`), `scripts/runner-image.sh`
## 3. Релей
- [x] 3.1 Токен сессии (core), `runner/agent-relay.ts`: hook (wait/rid, транскрипт), mcp, git-прокси
- [x] 3.2 MCP: фабрика сервера агента `packages/mcp/src/agent.ts`, ограничение проектом, `open_pull_request`
- [x] 3.3 Веб-маршруты `/api/agent/*`
## 4. Хосты
- [x] 4.1 `runner/hosts.ts`: проверка, `hostTick`, выбор хоста, клон и каталог запуска на хосте
- [x] 4.2 CLI `peppa host …`, `peppa runner settings isolation= hosts=`
- [x] 4.3 Веб: «Хосты» (суперадмин), настройки раннеров проекта, хост/контейнер в карточке, «Помощь»
## 5. Проверка
- [x] 5.1 `mock-docker run/rm`, `mock-ssh`
- [x] 5.2 e2e: контейнер (env, монтирования, хук и MCP через релей, остановка), релей (токены, чужой проект, git-прокси), хост (запуск, терминал, недоступность, выбор)
- [x] 5.3 AGENTS.md, RULES.md, typecheck, `pnpm run ci`

View File

@ -0,0 +1,60 @@
# agent-sandbox Specification
## Purpose
Агент раннера в своём docker-контейнере: видит только свою рабочую копию, ходит в Пеппу только через релей с токеном своей сессии (PEP-17).
## Requirements
### Requirement: Агент в контейнере
Настройка раннеров `isolation` SHALL выбирать, где работает агент: `none` (по умолчанию —
процесс на машине, как раньше) или `container`. В режиме `container` tmux раннера запускает
агента в docker-образе раннера, в который смонтированы только рабочая копия раннера (и `.git`
проекта для worktree), каталог запуска (только чтение) и свой домашний каталог агента, а
переменные окружения — только сессии, релея и подписки.
#### Scenario: Запуск в контейнере
- **GIVEN** у проекта PAY `isolation=container` и подписка Claude в пуле проекта
- **WHEN** PM переносит PAY-3 в «В работе»
- **THEN** в tmux раннера запущен `docker run` с монтированием рабочей копии PAY
- **AND** в окружении контейнера есть `CLAUDE_CODE_OAUTH_TOKEN` подписки, но нет `PEPPA_DB` и `GITEA_TOKEN`
#### Scenario: Без настройки — как раньше
- **GIVEN** у проекта нет настройки `isolation`
- **WHEN** запускается раннер
- **THEN** агент запускается в tmux без docker, как до PEP-17
#### Scenario: Нет подписки
- **GIVEN** у проекта `isolation=container` и нет ни одной подписки
- **WHEN** запускается раннер
- **THEN** запуск отклоняется с сообщением «для контейнера нужна подписка»
#### Scenario: Остановка убирает контейнер
- **GIVEN** раннер PAY-3 работает в контейнере `peppa-s12`
- **WHEN** PM останавливает раннер
- **THEN** tmux-сессия закрыта и выполнен `docker rm -f peppa-s12`
### Requirement: Релей агента
Хуки, MCP-сервер `peppa` и git агента в контейнере SHALL обращаться к Пеппе только через
релей `/api/agent/*` с токеном своей сессии. Токен действителен для текущего поколения
незавершённой сессии; MCP через релей работает только со стори проекта сессии; git и API Gitea
проксируются только к репозиторию проекта.
#### Scenario: Хук через релей
- **GIVEN** агент PAY-3 в контейнере заканчивает ход
- **WHEN** срабатывает Stop-хук
- **THEN** Пеппа получает его через релей и отмечает ход сессии так же, как у локального агента
#### Scenario: Чужой или старый токен
- **GIVEN** сессия #12 перезапущена (поколение 2)
- **WHEN** приходит запрос релея с токеном поколения 1 или с испорченной подписью
- **THEN** ответ 401, хук не выполняется
#### Scenario: Чужой проект через MCP
- **GIVEN** агент PAY-3 работает через релей
- **WHEN** он вызывает `get_task` для стори SHOP-1 другого проекта
- **THEN** инструмент возвращает ошибку доступа, данные SHOP-1 не отдаются
#### Scenario: Git только к своему репозиторию
- **GIVEN** агент PAY-3 работает через релей
- **WHEN** он запрашивает через прокси репозиторий другого проекта
- **THEN** ответ 403, к Gitea запрос не уходит

View File

@ -0,0 +1,44 @@
# runner-hosts Specification
## Purpose
Серверы для раннеров: Пеппа ходит на них по SSH своим ключом и запускает там tmux с агентом в контейнере, без демона на хосте (PEP-40).
## Requirements
### Requirement: Хосты раннеров по SSH
Суперадмин SHALL подключать серверы для раннеров: имя, `user@host`, порт, каталог, адрес
Пеппы для релея. Пеппа ходит на хост по SSH своим ключом (публичный показан в «Хостах»),
раз в минуту проверяет его (онлайн/офлайн, загрузка, версии docker и tmux) и запускает там
tmux с агентом в том же контейнере, что и локально. Агента-демона на хосте нет.
#### Scenario: Подключить хост
- **GIVEN** на сервере `build1` ключ Пеппы в `authorized_keys`, есть tmux и docker
- **WHEN** суперадмин добавляет хост «build1» `peppa@build1` и нажимает «Проверить»
- **THEN** хост в статусе «онлайн», видны версии docker и tmux и загрузка
#### Scenario: Хост недоступен
- **GIVEN** хост «build1» онлайн и на нём работает раннер PAY-3
- **WHEN** SSH к хосту перестаёт отвечать
- **THEN** хост становится «офлайн», а раннер PAY-3 не объявляется пропавшим
#### Scenario: Не суперадмин
- **GIVEN** пользователь не в `platform.admins`
- **WHEN** он открывает `/hosts`
- **THEN** ответ 404
### Requirement: Раннеры на хостах
Настройка раннеров `hosts` (список хостов; пусто — Mac Пеппы) SHALL направлять новые раннеры
проекта на наименее занятый онлайн-хост из списка. Рабочая копия раннера клонируется на хосте,
агент работает в контейнере, хуки и MCP идут через релей, терминал в вебе и ввод работают
через SSH.
#### Scenario: Раннер на хосте
- **GIVEN** у проекта PAY `hosts=[build1]`, хост онлайн, подписка Claude в пуле
- **WHEN** PM переносит PAY-3 в «В работе»
- **THEN** на build1 появляется клон PAY на ветке `task/PAY-3` и tmux-сессия раннера
- **AND** терминал раннера в вебе показывает экран агента с build1
#### Scenario: Нет доступного хоста
- **GIVEN** у проекта PAY `hosts=[build1]`, хост офлайн
- **WHEN** запускается раннер
- **THEN** запуск отклоняется с сообщением «нет доступного хоста»

View File

@ -69,7 +69,9 @@ import {
setDefaultActor,
} from "@peppa/core";
import { createDb, migrateDb } from "@peppa/db";
import { checkHost, ensureSshKey, pushImage, sshArgs } from "@peppa/runner";
import { promoteRunner, queueTaskOnRunner, renameRunner, startFreeRunner, runnerServiceAlive, setRunnerClient, recentRunnerCommands, getWatchdogSettings, setWatchdogSettings } from "@peppa/runner";
import { createHost, deleteHost, findHost, HOST_STATUS_RU, listHosts, setHostDisabled, updateHost } from "@peppa/core";
import { getProjectRunnerSettings, getSystemRunnerSettings, getTaskRunnerSettings, resolveRunnerSettings, runnerStories, setProjectRunnerSettings, setSystemRunnerSettings, setTaskRunnerSettings, type RunnerSettingsPatch } from "@peppa/core";
import { answerAndDeliver, connectCi, importIssues, deployProd, listReleases, platformReleaseOffers, setPlatformReleaseOffers, recordRelease, type ReleaseStatus, provisionProject, setProjectVisibility, PROVIDERS, type Provider, resumeSession, runWatchdog, sendToSession, startSession, stopSession, tick } from "@peppa/runner";
import { spawnSync } from "node:child_process";
@ -111,7 +113,11 @@ const USAGE = `peppa — Peppa software factory CLI
peppa runner queue <id> <PEP-42> [-p <промпт>] (story into the runner's queue, PEP-10)
peppa runner show <id> (history and queue of the runner)
peppa runner commands [N] (PEP-21: last commands of the runner service)
peppa runner settings [system|KEY|PEP-42] [mode=story|queue context=fresh|continue workspace=shared|worktree max=N|- | reset]
peppa runner settings [system|KEY|PEP-42] [mode=story|queue context=fresh|continue workspace=shared|worktree max=N|- isolation=none|container hosts=1,2|- | reset]
peppa host list | key (PEP-40: runner hosts; key = Peppa's public SSH key for authorized_keys)
peppa host add <name> <user@host> [port=22] [workdir=peppa] [url=https://…] (url — where the host reaches the agent relay)
peppa host set <name> [port=… workdir=… url=…|url=-]
peppa host check|disable|enable|rm|push-image <name>
(PEP-10/27: system → project → story; a story overrides mode/context only)
peppa platform allowlist | allow <login> | deny <login> (who may log into Peppa)
peppa platform release-offers [on|off] ("deploy to prod?" after a green main of Peppa; off before launch)
@ -468,7 +474,9 @@ async function main(): Promise<void> {
case "session attach": {
const s = await getSession(db, Number(args[0]));
const socket = process.env.PEPPA_TMUX_SOCKET ? ["-L", process.env.PEPPA_TMUX_SOCKET] : [];
spawnSync("tmux", [...socket, "attach", "-t", s.tmuxName], { stdio: "inherit" });
// PEP-40: a runner on a host — attach there over SSH with Peppa's key.
if (s.host) spawnSync(process.env.PEPPA_SSH_BIN ?? "ssh", ["-t", ...sshArgs(s.host), s.host.sshTarget, ["tmux", ...socket, "attach", "-t", s.tmuxName].join(" ")], { stdio: "inherit" });
else spawnSync("tmux", [...socket, "attach", "-t", s.tmuxName], { stdio: "inherit" });
break;
}
case "session resume": {
@ -537,7 +545,8 @@ async function main(): Promise<void> {
for (const arg of rest.filter((a) => a !== "reset")) {
const [k, v = ""] = arg.split("=");
if (k === "max") patch.maxRunners = v === "-" || v === "" ? null : Number(v);
else if (k === "mode" || k === "context" || k === "workspace") (patch as Record<string, string>)[k] = v;
else if (k === "mode" || k === "context" || k === "workspace" || k === "isolation") (patch as Record<string, string>)[k] = v;
else if (k === "hosts") patch.hosts = v === "-" || v === "" ? [] : await Promise.all(v.split(",").map(async (h) => (await findHost(db, h.trim())).id));
else throw new PeppaError(`unknown setting: ${k}`);
}
if (level === "system") await setSystemRunnerSettings(db, patch);
@ -546,9 +555,56 @@ async function main(): Promise<void> {
}
const eff = await resolveRunnerSettings(db, project?.id ?? ref?.project.id ?? 0, ref?.task.id);
console.log(`${level === "system" ? "system" : project?.key ?? ref!.key}: overrides ${JSON.stringify(await read())}`);
if (level !== "system") console.log(`effective: mode=${eff.mode} context=${eff.context} workspace=${eff.workspace} max=${eff.maxRunners ?? "-"}`);
if (level !== "system") console.log(`effective: mode=${eff.mode} context=${eff.context} workspace=${eff.workspace} max=${eff.maxRunners ?? "-"} isolation=${eff.isolation} hosts=${eff.hosts.join(",") || "-"}`);
break;
}
case "host list": {
for (const h of await listHosts(db)) {
const i = h.info ?? {};
console.log(`#${h.id} ${h.name.padEnd(12)} ${h.sshTarget}:${h.sshPort} ${h.disabledAt ? "отключён" : HOST_STATUS_RU[h.status]} раннеров ${h.runners}` +
`${i.load != null ? ` load ${i.load}/${i.cpus ?? "?"}` : ""}${i.docker ? ` docker ${i.docker}` : ""}${i.tmux ? ` ${i.tmux}` : ""} образ ${i.image ?? "нет"}${h.lastError ? `\n ${h.lastError}` : ""}`);
}
break;
}
case "host key":
console.log(await ensureSshKey());
break;
case "host add":
case "host set": {
const kv = Object.fromEntries(args.slice(cmd === "add" ? 2 : 1).map((a) => [a.slice(0, a.indexOf("=")), a.slice(a.indexOf("=") + 1)]));
for (const k of Object.keys(kv)) if (!["port", "workdir", "url"].includes(k)) throw new PeppaError(`unknown option: ${k}`);
const patch = {
...(kv.port ? { sshPort: Number(kv.port) } : {}),
...(kv.workdir ? { workdir: kv.workdir } : {}),
...(kv.url !== undefined ? { peppaUrl: kv.url === "-" ? null : kv.url } : {}),
};
const h = cmd === "add"
? await createHost(db, { name: args[0] ?? "", sshTarget: args[1] ?? "", ...patch })
: await updateHost(db, (await findHost(db, args[0] ?? "")).id, patch);
await ensureSshKey();
const r = await checkHost(db, h);
console.log(`#${r.id} ${r.name}: ${HOST_STATUS_RU[r.status]}${r.lastError ? ` — ${r.lastError}` : ""}`);
if (r.status !== "online") console.log(`Добавьте ключ Пеппы в ~/.ssh/authorized_keys на хосте:\n${await ensureSshKey()}`);
break;
}
case "host check": {
const r = await checkHost(db, await findHost(db, args[0] ?? ""));
console.log(`${r.name}: ${HOST_STATUS_RU[r.status]}${r.lastError ? ` — ${r.lastError}` : ""} ${JSON.stringify(r.info ?? {})}`);
break;
}
case "host disable":
case "host enable":
await setHostDisabled(db, (await findHost(db, args[0] ?? "")).id, cmd === "disable");
console.log(`${args[0]}: ${cmd === "disable" ? "отключён (новые раннеры не идут)" : "включён"}`);
break;
case "host rm":
await deleteHost(db, (await findHost(db, args[0] ?? "")).id);
console.log(`${args[0]} удалён`);
break;
case "host push-image":
await pushImage(await findHost(db, args[0] ?? ""));
console.log(`образ загружен на ${args[0]}`);
break;
case "web login-link": {
const u = await getUserByLogin(db, args[0] ?? "");
if (!u) throw new PeppaError(`User "${args[0]}" has never logged into the web`);

View File

@ -108,3 +108,21 @@ export function verifyHookSignature(projectId: number, body: string, signature:
return given.length === expected.length && timingSafeEqual(given, expected);
});
}
/**
* PEP-17: token of one agent run for the agent relay (/api/agent/*): `s<id>.<generation>.<hmac>`.
* Only checks the signature — the caller also checks the generation is current and the session alive.
*/
export function agentRelayToken(sessionId: number, generation: number): string {
const body = `s${sessionId}.${generation}`;
return `${body}.${createHmac("sha256", key("agent")).update(body).digest("base64url")}`;
}
export function parseAgentRelayToken(token: string | null | undefined): { sessionId: number; generation: number } | null {
const m = token?.trim().match(/^s(\d+)\.(\d+)\.([A-Za-z0-9_-]+)$/);
if (!m) return null;
const expected = createHmac("sha256", key("agent")).update(`s${m[1]}.${m[2]}`).digest();
const given = Buffer.from(m[3]!, "base64url");
if (given.length !== expected.length || !timingSafeEqual(given, expected)) return null;
return { sessionId: Number(m[1]), generation: Number(m[2]) };
}

115
packages/core/src/hosts.ts Normal file
View File

@ -0,0 +1,115 @@
// PEP-40: servers runners run on (SSH, no daemon). Reaching them — runner/exec.ts, checks — runner/hosts.ts.
import { runnerHosts, sessions, type Db, type RunnerHostInfo } from "@peppa/db";
import { and, asc, eq, inArray, isNull, notInArray, sql } from "drizzle-orm";
import { PeppaError } from "./errors.ts";
import { FINISHED_SESSION_STATUSES } from "./sessions.ts";
export type RunnerHost = typeof runnerHosts.$inferSelect;
export interface RunnerHostView extends RunnerHost {
/** Live runners on the host. */
runners: number;
}
const NAME_RE = /^[a-z0-9][a-z0-9._-]{0,39}$/i;
// user@host or host; host: name, IPv4 or [IPv6]. No options smuggled in (a leading "-").
const TARGET_RE = /^(?:[a-z_][a-z0-9._-]{0,31}@)?(?:[a-z0-9][a-z0-9.-]{0,252}|\[[0-9a-f:]+\])$/i;
const WORKDIR_RE = /^[A-Za-z0-9._/~-]{1,200}$/;
export interface HostInput {
name: string;
sshTarget: string;
sshPort?: number;
workdir?: string;
peppaUrl?: string | null;
}
function check(h: Partial<HostInput>) {
if (h.name !== undefined && !NAME_RE.test(h.name)) throw new PeppaError("Имя хоста — латиница, цифры, «.-_», до 40 символов");
if (h.sshTarget !== undefined && !TARGET_RE.test(h.sshTarget)) throw new PeppaError("SSH-адрес — user@host или host");
if (h.sshPort !== undefined && !(Number.isInteger(h.sshPort) && h.sshPort > 0 && h.sshPort < 65536)) throw new PeppaError("Порт SSH — от 1 до 65535");
if (h.workdir !== undefined && (!WORKDIR_RE.test(h.workdir) || h.workdir.split("/").includes(".."))) throw new PeppaError("Каталог на хосте — путь без пробелов и «..»");
if (h.peppaUrl) {
try {
const u = new URL(h.peppaUrl);
if (u.protocol !== "http:" && u.protocol !== "https:") throw new Error();
} catch {
throw new PeppaError("Адрес Пеппы — http(s)://…");
}
}
}
export async function createHost(db: Db, h: HostInput): Promise<RunnerHost> {
const v = { ...h, name: h.name.trim(), sshTarget: h.sshTarget.trim(), workdir: h.workdir?.trim() || undefined, peppaUrl: h.peppaUrl?.trim() || null };
check(v);
const [dup] = await db.select({ id: runnerHosts.id }).from(runnerHosts).where(eq(runnerHosts.name, v.name));
if (dup) throw new PeppaError(`Хост «${v.name}» уже есть`);
const [row] = await db.insert(runnerHosts).values(v).returning();
return row!;
}
export async function updateHost(db: Db, id: number, patch: Partial<HostInput>): Promise<RunnerHost> {
check(patch);
await getHost(db, id);
const [row] = await db.update(runnerHosts).set(patch).where(eq(runnerHosts.id, id)).returning();
return row!;
}
export async function getHost(db: Db, id: number): Promise<RunnerHost> {
const [row] = await db.select().from(runnerHosts).where(eq(runnerHosts.id, id));
if (!row) throw new PeppaError(`Хост #${id} не найден`);
return row;
}
/** By id or name. */
export async function findHost(db: Db, ref: string | number): Promise<RunnerHost> {
if (typeof ref === "number" || /^\d+$/.test(ref)) return getHost(db, Number(ref));
const [row] = await db.select().from(runnerHosts).where(eq(runnerHosts.name, ref));
if (!row) throw new PeppaError(`Хост «${ref}» не найден`);
return row;
}
const liveRunners = sql<number>`(select count(*) from sessions s where s.host_id = "runner_hosts"."id" and s.status not in ('done','failed'))`;
export async function listHosts(db: Db, opts: { ids?: number[]; enabled?: boolean } = {}): Promise<RunnerHostView[]> {
if (opts.ids && !opts.ids.length) return [];
const rows = await db
.select({ host: runnerHosts, runners: liveRunners })
.from(runnerHosts)
.where(and(opts.ids ? inArray(runnerHosts.id, opts.ids) : undefined, opts.enabled ? isNull(runnerHosts.disabledAt) : undefined))
.orderBy(asc(runnerHosts.name));
return rows.map((r) => ({ ...r.host, runners: Number(r.runners) }));
}
export async function setHostDisabled(db: Db, id: number, disabled: boolean): Promise<void> {
await getHost(db, id);
await db.update(runnerHosts).set({ disabledAt: disabled ? new Date() : null }).where(eq(runnerHosts.id, id));
}
/** Removes a host with no live runners (finished sessions keep their history, host_id → null). */
export async function deleteHost(db: Db, id: number): Promise<void> {
const [live] = await db
.select({ n: sql<number>`count(*)` })
.from(sessions)
.where(and(eq(sessions.hostId, id), notInArray(sessions.status, FINISHED_SESSION_STATUSES)));
if (Number(live?.n ?? 0) > 0) throw new PeppaError("На хосте работают раннеры — остановите их или отключите хост");
await db.delete(runnerHosts).where(eq(runnerHosts.id, id));
}
/** Result of a check (runner/hosts.ts): online with fresh info, or offline with the error. */
export async function recordHostCheck(db: Db, id: number, r: { ok: true; info: RunnerHostInfo } | { ok: false; error: string }, now = new Date()): Promise<RunnerHost> {
const [row] = await db
.update(runnerHosts)
.set(r.ok ? { status: "online", info: r.info, lastSeenAt: now, lastError: null } : { status: "offline", lastError: r.error.slice(0, 500) })
.where(eq(runnerHosts.id, id))
.returning();
return row!;
}
/** PEP-40: the least busy online, enabled host among `ids`; null when none is available. */
export async function pickHost(db: Db, ids: number[]): Promise<RunnerHostView | null> {
const hosts = (await listHosts(db, { ids, enabled: true })).filter((h) => h.status === "online");
hosts.sort((a, b) => a.runners - b.runners || a.id - b.id);
return hosts[0] ?? null;
}
export const HOST_STATUS_RU: Record<RunnerHost["status"], string> = { unknown: "не проверен", online: "онлайн", offline: "офлайн" };

View File

@ -7,6 +7,7 @@ export * from "./sessions.ts";
export * from "./rules.ts";
export * from "./settings.ts";
export * from "./runners.ts";
export * from "./hosts.ts";
export * from "./telegram.ts";
export * from "./crypto.ts";
export * from "./gitea.ts";

View File

@ -9,6 +9,8 @@ import { projects } from "@peppa/db";
export const RUNNER_MODES = ["story", "queue"] as const;
export const RUNNER_CONTEXTS = ["fresh", "continue"] as const;
export const RUNNER_WORKSPACES = ["shared", "worktree"] as const;
export const RUNNER_ISOLATIONS = ["none", "container"] as const;
export type RunnerIsolation = (typeof RUNNER_ISOLATIONS)[number];
export type RunnerMode = (typeof RUNNER_MODES)[number];
export type RunnerContext = (typeof RUNNER_CONTEXTS)[number];
export type RunnerWorkspace = (typeof RUNNER_WORKSPACES)[number];
@ -22,16 +24,23 @@ export interface RunnerSettings {
workspace: RunnerWorkspace;
/** Live runners per project; null = no limit. */
maxRunners: number | null;
/** PEP-17: none — the agent runs directly in tmux (default); container — in the runner image. */
isolation: RunnerIsolation;
/** PEP-40: hosts runners go to (least busy online one); empty — Peppa's own machine. */
hosts: number[];
}
export type RunnerSettingsPatch = Partial<RunnerSettings>;
/** Which settings a story may override. */
export type TaskRunnerPatch = Partial<Pick<RunnerSettings, "mode" | "context">>;
export const DEFAULT_RUNNER_SETTINGS: RunnerSettings = { mode: "story", context: "fresh", workspace: "shared", maxRunners: null };
export const DEFAULT_RUNNER_SETTINGS: RunnerSettings = { mode: "story", context: "fresh", workspace: "shared", maxRunners: null, isolation: "none", hosts: [] };
export const RUNNER_MODE_RU: Record<RunnerMode, string> = { story: "Один раннер на стори", queue: "Раннер ведёт очередь стори" };
export const RUNNER_CONTEXT_RU: Record<RunnerContext, string> = { fresh: "Свежий контекст на стори", continue: "Один разговор на все стори" };
export const RUNNER_WORKSPACE_RU: Record<RunnerWorkspace, string> = { shared: "Общая рабочая копия", worktree: "Свой git worktree на раннер" };
export const RUNNER_ISOLATION_RU: Record<RunnerIsolation, string> = { none: "Без изоляции (агент на машине)", container: "Контейнер на раннер (docker)" };
const validHosts = (v: unknown): v is number[] => Array.isArray(v) && v.length <= 50 && v.every((n) => Number.isInteger(n) && n > 0);
const SYSTEM_KEY = "platform.runner";
const projectKey = (projectId: number) => `project.runner:${projectId}`;
@ -44,6 +53,8 @@ function clean(p: Record<string, unknown> | null, allow: Array<keyof RunnerSetti
if (allow.includes("mode") && RUNNER_MODES.includes(p.mode as RunnerMode)) out.mode = p.mode as RunnerMode;
if (allow.includes("context") && RUNNER_CONTEXTS.includes(p.context as RunnerContext)) out.context = p.context as RunnerContext;
if (allow.includes("workspace") && RUNNER_WORKSPACES.includes(p.workspace as RunnerWorkspace)) out.workspace = p.workspace as RunnerWorkspace;
if (allow.includes("isolation") && RUNNER_ISOLATIONS.includes(p.isolation as RunnerIsolation)) out.isolation = p.isolation as RunnerIsolation;
if (allow.includes("hosts") && validHosts(p.hosts)) out.hosts = [...new Set(p.hosts)];
if (allow.includes("maxRunners") && "maxRunners" in p) {
const n = p.maxRunners;
if (n === null) out.maxRunners = null;
@ -51,7 +62,7 @@ function clean(p: Record<string, unknown> | null, allow: Array<keyof RunnerSetti
}
return out;
}
const ALL: Array<keyof RunnerSettings> = ["mode", "context", "workspace", "maxRunners"];
const ALL: Array<keyof RunnerSettings> = ["mode", "context", "workspace", "maxRunners", "isolation", "hosts"];
const TASK: Array<keyof RunnerSettings> = ["mode", "context"];
export async function getSystemRunnerSettings(db: Db): Promise<RunnerSettingsPatch> {
@ -80,7 +91,8 @@ async function store(db: Db, key: string, patch: Record<string, unknown>, allow:
if (v === undefined) continue;
if (!allow.includes(k as keyof RunnerSettings)) throw new PeppaError(`Неизвестная настройка раннеров: ${k}`);
if (k === "maxRunners" && v !== null && !(Number.isInteger(v) && (v as number) >= 1 && (v as number) <= 50)) throw new PeppaError("Лимит раннеров — от 1 до 50 или без лимита");
if (k !== "maxRunners" && !clean({ [k]: v }, allow)[k as keyof RunnerSettings]) throw new PeppaError(`Недопустимое значение ${k}: ${String(v)}`);
if (k === "hosts" && !validHosts(v)) throw new PeppaError("Хосты — список номеров хостов");
if (k !== "maxRunners" && k !== "hosts" && !clean({ [k]: v }, allow)[k as keyof RunnerSettings]) throw new PeppaError(`Недопустимое значение ${k}: ${String(v)}`);
}
const value = clean(patch, allow);
if (Object.keys(value).length) await setSetting(db, key, value);

View File

@ -1,4 +1,4 @@
import { events, projects, questions, sessions, sessionStatus, subscriptions, tasks, type Db } from "@peppa/db";
import { events, projects, questions, runnerHosts, sessions, sessionStatus, subscriptions, tasks, type Db } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared";
import { and, desc, eq, inArray, isNull, lte, notInArray, sql } from "drizzle-orm";
import { PeppaError } from "./errors.ts";
@ -21,6 +21,18 @@ export interface SessionView extends Session {
subscriptionName: string | null;
/** PEP-39: how many times the session moved to another subscription (events). */
subscriptionSwitches: number;
/** PEP-40: where the runner's tmux lives (null = Peppa's own machine). */
host: SessionHost | null;
}
/** PEP-40: how to reach a runner's host (see runner/exec.ts). */
export interface SessionHost {
id: number;
name: string;
sshTarget: string;
sshPort: number;
workdir: string;
peppaUrl: string | null;
}
export async function createSession(
@ -77,7 +89,7 @@ export async function listUserSessions(db: Db, userId: number, opts: { filter?:
export async function updateSession(
db: Db,
id: number,
patch: Partial<Pick<Session, "status" | "tmuxName" | "conversationId" | "generation" | "autoNudges" | "lastActivityAt" | "endedAt" | "resumeAt" | "limitProbeMin" | "limitResumes" | "limitResumesDay" | "limitResumedAt" | "subscriptionId" | "rotateReason" | "name" | "workspacePath" | "taskId" | "watchState">>,
patch: Partial<Pick<Session, "status" | "tmuxName" | "conversationId" | "generation" | "autoNudges" | "lastActivityAt" | "endedAt" | "resumeAt" | "limitProbeMin" | "limitResumes" | "limitResumesDay" | "limitResumedAt" | "subscriptionId" | "rotateReason" | "name" | "workspacePath" | "taskId" | "watchState" | "hostId" | "container">>,
): Promise<Session> {
const [row] = await db.update(sessions).set(patch).where(eq(sessions.id, id)).returning();
if (!row) throw new PeppaError(`Session #${id} not found`);
@ -170,14 +182,16 @@ function sessionQuery(db: Db) {
return db
.select({ session: sessions, projectKey: projects.key, taskNumber: tasks.number, taskTitle: tasks.title, taskStatus: tasks.status, subscriptionName: subscriptions.name,
switches: sql<number>`(select count(*) from events e where e.session_id = ${sessions.id} and e.type = 'subscription_switched')`,
host: { id: runnerHosts.id, name: runnerHosts.name, sshTarget: runnerHosts.sshTarget, sshPort: runnerHosts.sshPort, workdir: runnerHosts.workdir, peppaUrl: runnerHosts.peppaUrl },
})
.from(sessions)
.innerJoin(projects, eq(sessions.projectId, projects.id))
.leftJoin(tasks, eq(sessions.taskId, tasks.id))
.leftJoin(subscriptions, eq(sessions.subscriptionId, subscriptions.id));
.leftJoin(subscriptions, eq(sessions.subscriptionId, subscriptions.id))
.leftJoin(runnerHosts, eq(sessions.hostId, runnerHosts.id));
}
function toView(r: { session: Session; projectKey: string; taskNumber: number | null; taskTitle: string | null; taskStatus: string | null; subscriptionName: string | null; switches: number }): SessionView {
function toView(r: { session: Session; projectKey: string; taskNumber: number | null; taskTitle: string | null; taskStatus: string | null; subscriptionName: string | null; switches: number; host: SessionHost | { id: null } | null }): SessionView {
return {
...r.session,
projectKey: r.projectKey,
@ -186,6 +200,7 @@ function toView(r: { session: Session; projectKey: string; taskNumber: number |
taskStatus: r.taskStatus,
subscriptionName: r.subscriptionName,
subscriptionSwitches: Number(r.switches ?? 0),
host: r.host && r.host.id != null ? (r.host as SessionHost) : null,
};
}

View File

@ -0,0 +1,18 @@
CREATE TABLE `runner_hosts` (
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
`name` text NOT NULL,
`ssh_target` text NOT NULL,
`ssh_port` integer DEFAULT 22 NOT NULL,
`workdir` text DEFAULT 'peppa' NOT NULL,
`peppa_url` text,
`status` text DEFAULT 'unknown' NOT NULL,
`info` text,
`last_seen_at` integer,
`last_error` text,
`disabled_at` integer,
`created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL
);
--> statement-breakpoint
CREATE UNIQUE INDEX `runner_hosts_name_unique` ON `runner_hosts` (`name`);--> statement-breakpoint
ALTER TABLE `sessions` ADD `host_id` integer REFERENCES runner_hosts(id);--> statement-breakpoint
ALTER TABLE `sessions` ADD `container` text;

File diff suppressed because it is too large Load Diff

View File

@ -92,6 +92,13 @@
"when": 1794623649272,
"tag": "0012_runner_service",
"breakpoints": true
},
{
"idx": 13,
"version": "6",
"when": 1794624555440,
"tag": "0013_runner_hosts",
"breakpoints": true
}
]
}

View File

@ -252,6 +252,37 @@ export const subscriptionPoolMembers = sqliteTable(
);
/** An agent CLI session (Claude Code, Codex or OpenCode) running in tmux on this machine. */
/**
* PEP-40: a server runners run on. Peppa reaches it over SSH with its own key; tmux and the
* agent's container live there (PEP-17). No daemon on the host.
*/
export const runnerHosts = sqliteTable("runner_hosts", {
id: integer("id").primaryKey({ autoIncrement: true }),
name: text("name").notNull().unique(),
sshTarget: text("ssh_target").notNull(),
sshPort: integer("ssh_port").notNull().default(22),
// Base directory on the host: ws/ (clones), runs/ (launch dirs), home/ (agent homes).
workdir: text("workdir").notNull().default("peppa"),
// Where the agent relay (/api/agent/*) is reached from the host; null = PEPPA_WEB_URL.
peppaUrl: text("peppa_url"),
status: text("status", { enum: ["unknown", "online", "offline"] }).notNull().default("unknown"),
info: text("info", { mode: "json" }).$type<RunnerHostInfo>(),
lastSeenAt: integer("last_seen_at", { mode: "timestamp_ms" }),
lastError: text("last_error"),
disabledAt: integer("disabled_at", { mode: "timestamp_ms" }),
createdAt: createdAt(),
});
export interface RunnerHostInfo {
os?: string;
docker?: string;
tmux?: string;
cpus?: number;
load?: number;
image?: string | null;
checkedAt?: number;
}
export const sessions = sqliteTable("sessions", {
id: integer("id").primaryKey({ autoIncrement: true }),
projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
@ -279,6 +310,10 @@ export const sessions = sqliteTable("sessions", {
name: text("name"),
// PEP-27: the runner's own git worktree (null = the project's working copy).
workspacePath: text("workspace_path"),
// PEP-40: the host the runner lives on (null = Peppa's own machine).
hostId: integer("host_id").references(() => runnerHosts.id, { onDelete: "set null" }),
// PEP-17: the agent's docker container (null = the agent runs directly in tmux).
container: text("container"),
// PEP-5: tokens (per conversation, from the transcript), cost (per generation, from the
// statusLine), context window — see core/usage.ts.
usage: text("usage", { mode: "json" }).$type<SessionUsage>(),

View File

@ -20,6 +20,8 @@
"drizzle-orm": "0.45.4"
},
"exports": {
"./manager": "./src/manager.ts"
"./manager": "./src/manager.ts",
"./agent": "./src/agent.ts",
"./relay": "./src/relay.ts"
}
}

332
packages/mcp/src/agent.ts Normal file
View File

@ -0,0 +1,332 @@
// Peppa MCP server of an agent: gives sessions inside a project access to its epics, stories
// (tasks in the tool names) and the PM. Served over stdio (index.ts) or, for agents in a runner
// container, over the agent relay (PEP-17) — then locked to the session's project.
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import {
askPm,
createTask,
giteaForBot,
getIncident,
getAutonomy,
getProject,
getTaskDetails,
incidentStatuses,
listIncidents,
listEpics,
listTasks,
blockedLabel,
blockersMap,
epicProgress,
progressLabel,
setDependencies,
loadSharedRules,
PeppaError,
reportProgress,
resolveTask,
TASK_STATUSES,
updateTask,
getSession,
listProjectSecrets,
MEMORY_FILE,
MEMORY_SECTIONS,
memoryContext,
rememberFact,
replaceMemory,
} from "@peppa/core";
import type { Db } from "@peppa/db";
import { requestReview, reviewGate, storyBranch } from "@peppa/runner";
import { z } from "zod";
import { formatIncident, formatTask } from "./format.ts";
export interface AgentServerOptions {
/** The project of the agent's repo (.peppa/project.json) — default for bare story numbers. */
defaultKey?: string;
/** Set for sessions Peppa started; absent for a manual `claude`. */
sessionId?: number;
/** PEP-17: refuse stories and projects other than `defaultKey` (agents behind the relay). */
lockProject?: boolean;
/**
* PEP-30: the repo root of the agent's working copy (where .peppa/project.json lives) — the
* project memory is there. null: not reachable from Peppa (a runner on a host, PEP-40).
*/
repoDir?: string | null;
}
export function createAgentServer(db: Db, opts: AgentServerOptions = {}): McpServer {
const server = new McpServer({ name: "peppa", version: "0.1.0" });
const { defaultKey, sessionId } = opts;
type Result = { content: Array<{ type: "text"; text: string }>; isError?: boolean };
function tool<S extends z.ZodRawShape>(
name: string,
description: string,
inputSchema: S,
run: (args: z.infer<z.ZodObject<S>>) => Promise<string>,
) {
server.registerTool(name, { description, inputSchema }, (async (args: z.infer<z.ZodObject<S>>): Promise<Result> => {
try {
return { content: [{ type: "text", text: await run(args) }] };
} catch (e) {
const msg = e instanceof PeppaError ? e.message : `Internal error: ${(e as Error).message}`;
return { content: [{ type: "text", text: msg }], isError: true };
}
}) as never);
}
const taskArg = z
.string()
.describe(`Story key like ${defaultKey ?? "PEP"}-42, or just the number for the current project`);
const projectArg = z
.string()
.optional()
.describe(`Project key or slug; defaults to the current repo's project${defaultKey ? ` (${defaultKey})` : ""}`);
async function projectOrDefault(p?: string) {
const k = p ?? defaultKey;
if (!k) throw new PeppaError("No project given and no .peppa/project.json found in this repo");
const project = await getProject(db, k);
if (opts.lockProject && project.key !== defaultKey) throw new PeppaError(`Access denied: this agent works only in project ${defaultKey}`);
return project;
}
/** A story of this project (PEP-17: an agent behind the relay can't reach other projects). */
async function resolve(task: string) {
const ref = await resolveTask(db, task, defaultKey);
if (opts.lockProject && ref.project.key !== defaultKey) throw new PeppaError(`Access denied: ${ref.key} is not in project ${defaultKey}`);
return ref;
}
tool(
"get_rules",
"Get Peppa's shared agent rules (story workflow on OpenSpec, PM approval, when to ask the PM). Sessions started by Peppa already have them in the system prompt; call this in a manually started session.",
{},
async () => (await loadSharedRules()).text,
);
tool("get_task", "Get a Peppa story (one business story = one OpenSpec change): description, epic, status, OpenSpec change, PM Q&A and the next step to take. Call this first when the user names a story number.", { task: taskArg }, async ({ task }) =>
formatTask(await getTaskDetails(db, await resolve(task))),
);
tool(
"list_tasks",
"List stories in a project in board order (top = highest priority), optionally filtered by status or epic; \"waits for\" marks stories blocked by unfinished predecessors.",
{ project: projectArg, status: z.enum(TASK_STATUSES).optional(), epic_id: z.number().int().optional(), goal_id: z.number().int().optional().describe("Alias of epic_id") },
async ({ project, status, epic_id, goal_id }) => {
const p = await projectOrDefault(project);
const rows = await listTasks(db, { projectId: p.id, goalId: epic_id ?? goal_id, statuses: status ? [status] : undefined });
if (!rows.length) return "No stories.";
const deps = await blockersMap(db, p.id);
return rows.map((t) => {
const b = blockedLabel(deps.get(t.id))?.replace("ждёт", "waits for");
return `- ${t.key} [${t.status}]${t.goalId ? ` (epic #${t.goalId})` : ""} ${t.title}${b ? ` — ${b}` : ""}`;
}).join("\n");
},
);
const listEpicsText = async ({ project }: { project?: string }) => {
const p = await projectOrDefault(project);
const rows = await listEpics(db, p.id);
if (!rows.length) return "No open epics.";
const progress = await epicProgress(db, p.id);
return rows.map((g) => `- #${g.id} ${g.title} (done ${progressLabel(progress.get(g.id))})${g.description ? ` — ${g.description.split("\n")[0]}` : ""}`).join("\n");
};
tool("list_epics", "List the open epics of a project (labels that group stories).", { project: projectArg }, listEpicsText);
tool("list_goals", "Alias of list_epics (goals were renamed to epics).", { project: projectArg }, listEpicsText);
tool(
"create_task",
"Create a new story (e.g. follow-up work discovered outside the current change's scope). Label it with an epic when one fits.",
{
title: z.string().min(3),
description: z.string().optional(),
epic_id: z.number().int().optional(),
goal_id: z.number().int().optional().describe("Alias of epic_id"),
blocked_by: z.array(z.string()).optional().describe("Stories this one waits for (keys); it won't be started automatically until they are in review/done"),
project: projectArg,
},
async ({ title, description, epic_id, goal_id, blocked_by, project }) => {
const p = await projectOrDefault(project);
const ref = await createTask(db, { projectId: p.id, goalId: epic_id ?? goal_id, title, description });
const deps = blocked_by?.length ? await setDependencies(db, ref, blocked_by).catch((e: Error) => { throw new PeppaError(`Created ${ref.key}, but dependencies were not set: ${e.message}`); }) : [];
return `Created ${ref.key}: ${title}${deps.length ? ` (waits for ${deps.map((d) => d.key).join(", ")})` : ""}`;
},
);
tool(
"update_task",
"Update a story's status, OpenSpec change name, PR URL, title or description.",
{
task: taskArg,
status: z.enum(TASK_STATUSES).optional(),
openspec_change: z.string().optional().describe("Change id under openspec/changes/, e.g. pep-42-add-auth"),
pr_url: z.string().url().optional(),
title: z.string().optional(),
description: z.string().optional(),
},
async ({ task, status, openspec_change, pr_url, title, description }) => {
const ref = await resolve(task);
// Acceptance stays with the PM: agents can't mark work done or approve themselves.
if (status === "done") throw new PeppaError("Only the PM marks a story done. Open a PR and set status: review.");
if (status === "in_progress" && ref.task.status === "awaiting_approval") {
throw new PeppaError("The proposal is awaiting the PM's approval; only the PM can move it to in_progress.");
}
// PEP-23: a project where the PM approves every proposal — Apply only after the approval
// (the PM's answer moves the story to in_progress itself).
if (status === "in_progress" && (ref.task.status === "backlog" || ref.task.status === "proposing") && (await getAutonomy(db, ref.project.id)).proposal === "pm") {
throw new PeppaError("In this project the PM approves every proposal: call request_approval with the proposal summary and end your turn.");
}
if (status === "review" && ref.task.status !== "review") {
// PEP-57: review only with green checks of the PR head (the PR given now counts).
const reason = await reviewGate({ ...ref, task: { ...ref.task, prUrl: pr_url ?? ref.task.prUrl } });
if (reason) {
throw new PeppaError(`Not moved to review: ${reason}. Wait for the CI checks of the PR's last commit to pass (red ones come back to you with the log), then set status: review again.`);
}
}
if (status === "review" && ref.task.status !== "review") {
// PEP-26: the project's reviewer agent reads the diff before the PM (when turned on).
const withPr = { ...ref, task: { ...ref.task, prUrl: pr_url ?? ref.task.prUrl } };
const r = await requestReview(db, withPr).catch(() => ({ action: "review" as const }));
if (r.action === "queued") {
await updateTask(db, ref, { openspecChange: openspec_change, prUrl: pr_url, title, description }, sessionId);
return `${ref.key}: the reviewer agent is checking PR commit ${r.review.sha.slice(0, 7)} (review #${r.review.id}); the story stays in_progress. End your turn now — findings come back to you as a message; if the review is fine the story goes to the PM's review by itself.`;
}
}
const t = await updateTask(db, ref, { status, openspecChange: openspec_change, prUrl: pr_url, title, description }, sessionId);
return `${ref.key} updated: status=${t.status}${t.openspecChange ? `, change=${t.openspecChange}` : ""}${t.prUrl ? `, pr=${t.prUrl}` : ""}`;
},
);
tool(
"request_approval",
"Ask the PM to approve an ARCHITECTURAL decision in a story's proposal (new service/dependency, data model, security/access, money, irreversible actions, scope change). Routine proposals need no approval — go straight to apply. Sets awaiting_approval and notifies the PM; end your turn afterwards.",
{ task: taskArg, summary: z.string().min(10).describe("What, why, risks, open questions — readable on a phone") },
async ({ task, summary }) => {
const ref = await resolve(task);
const q = await askPm(db, ref, { kind: "approval", text: summary, sessionId });
return `Approval requested (#${q.id}); ${ref.key} is awaiting_approval. End your turn now and wait for the PM's reply.`;
},
);
tool(
"ask_pm",
"Ask the PM about a STOPPER only (scope, architecture, data, money, access/secrets, or a costly-to-undo fork). Decide everything else yourself and record it in design.md. Delivered to Telegram; end your turn afterwards — the answer arrives as the next user message.",
{
task: taskArg,
question: z.string().min(5).describe("One question, 1–2 sentences of context"),
options: z.array(z.string()).max(6).optional().describe("Suggested answers, shown as buttons"),
},
async ({ task, question, options }) => {
const ref = await resolve(task);
const q = await askPm(db, ref, { kind: "question", text: question, options, sessionId });
return `Question #${q.id} sent to the PM. End your turn now and wait for the answer.`;
},
);
tool(
"report_progress",
"Log a short progress note on a story (visible to the PM in the web UI / Telegram digest).",
{ task: taskArg, text: z.string().min(3) },
async ({ task, text }) => {
const ref = await resolve(task);
await reportProgress(db, ref, text, sessionId);
return `Progress noted on ${ref.key}.`;
},
);
tool(
"list_incidents",
"List production errors (Bugsink incidents) of a project: id, status, title, where, release, event count, linked story.",
{ project: projectArg, status: z.enum(incidentStatuses).optional() },
async ({ project, status }) => {
const p = await projectOrDefault(project);
const rows = await listIncidents(db, p.id, status ? [status] : undefined);
if (!rows.length) return "No incidents.";
return rows.map((i) => `- #${i.id} [${i.status}] ${i.title}${i.culprit ? ` (${i.culprit})` : ""} · ${i.environment ?? "?"} · release ${i.lastRelease ?? "?"} · ${i.events} events${i.taskId ? ` · story #${i.taskId}` : ""}`).join("\n");
},
);
tool(
"get_incident",
"Get a production error (Bugsink incident): stack top, where, release, environment, frequency, Bugsink link. Use it when fixing a bug story made from an incident: first write a test reproducing this stack.",
{ id: z.number().int() },
async ({ id }) => {
const i = await getIncident(db, id);
if (defaultKey && i.projectId !== (await getProject(db, defaultKey)).id) throw new PeppaError(`Incident #${id} is not in this project`);
return formatIncident(i);
},
);
tool(
"open_pull_request",
"Open a pull request in the project's Gitea repo from the story branch (default task/<key>) to the default branch; returns the PR URL (pass it to update_task as pr_url). Use it when you have no Gitea token (e.g. in a runner container); an already open PR of the branch is returned as is.",
{ task: taskArg, title: z.string().min(3), body: z.string().optional(), head: z.string().optional().describe("Source branch; default task/<key in lower case>") },
async ({ task, title, body, head }) => {
const ref = await resolve(task);
const branch = head ?? storyBranch(ref.key);
const bot = giteaForBot();
const open = await bot.openPullForBranch(ref.project.giteaOwner, ref.project.giteaRepo, branch);
const pr = open ?? (await bot.createPullRequest(ref.project.giteaOwner, ref.project.giteaRepo, { head: branch, base: ref.project.defaultBranch, title, body: body ?? `Story ${ref.key}` }));
return `${open ? "Already open" : "Opened"}: ${pr.html_url}`;
},
);
tool(
"list_secrets",
"List the names of this project's secrets (API keys and accesses the PM stored in Peppa). They are already in your environment as variables of the same name — use them as $NAME, never print, log or commit their values. Values are not available here. Missing a secret? ask_pm to add it in «⋯ Настройки проекта → Секреты» (the next session start gets it).",
{},
async () => {
// PEP-54: only the project of this session (or this repo), names only.
const p = sessionId ? await getProject(db, (await getSession(db, sessionId)).projectKey) : await projectOrDefault();
const rows = await listProjectSecrets(db, p.id);
if (!rows.length) return `${p.key} has no secrets.`;
return [`Secrets of ${p.key} (in your env):`, ...rows.map((r) => `- ${r.name}`)].join("\n");
},
);
// ── PEP-30: project memory (.peppa/memory.md in the repo) ─────────────────────
const memoryDir = () => {
if (!opts.repoDir) {
throw new PeppaError(
opts.lockProject
? `Project memory is not reachable from Peppa for this runner: edit ${MEMORY_FILE} in your working copy directly and commit it in your story branch`
: "No .peppa/project.json found — project memory lives next to it",
);
}
return opts.repoDir;
};
tool(
"get_memory",
`Read the project memory (${MEMORY_FILE}: commands, conventions, pitfalls, decisions written by earlier agents) and a digest of the last finished stories. Runner sessions already get it in the system prompt.`,
{},
async () => {
const dir = memoryDir();
const project = await projectOrDefault();
return memoryContext(db, project.id, dir);
},
);
tool(
"remember",
`Add one durable fact to the project memory (${MEMORY_FILE}) for the next agents: a build/test command, a convention, a pitfall you hit, a decision. One short line; duplicates are skipped. With replace: true, \`text\` becomes the whole memory (use it to compact when the size limit is near). Commit the file in your story branch.`,
{
section: z.string().optional().describe(`One of: ${MEMORY_SECTIONS.join(", ")} (or commands, conventions, pitfalls, decisions). Not needed with replace.`),
text: z.string().describe("The fact (one line), or the whole memory with replace: true"),
replace: z.boolean().optional(),
},
async ({ section, text, replace }) => {
const dir = memoryDir();
if (replace) {
const st = replaceMemory(dir, text);
return `Память переписана: ${st.chars} из ${st.max} символов. Закоммить ${MEMORY_FILE} в ветке стори.`;
}
const r = rememberFact(dir, section ?? "", text);
if (r.result === "exists") return "Такой пункт уже есть — ничего не изменил.";
return `Запомнил. Память: ${r.stats.chars} из ${r.stats.max} символов${r.stats.nearLimit ? " — почти предел, ужми (remember с replace: true)" : ""}. Закоммить ${MEMORY_FILE} в ветке стори.`;
},
);
return server;
}

View File

@ -1,296 +1,19 @@
// Peppa MCP server: gives Claude sessions inside a project access to its epics, stories
// (tasks in the tool names) and the PM. Runs over stdio; the project defaults to the repo's .peppa/project.json.
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
askPm,
createTask,
findProjectFile,
getIncident,
getAutonomy,
getProject,
getTaskDetails,
incidentStatuses,
listIncidents,
listEpics,
listTasks,
blockedLabel,
blockersMap,
epicProgress,
progressLabel,
setDependencies,
loadSharedRules,
PeppaError,
reportProgress,
resolveTask,
TASK_STATUSES,
updateTask,
setDefaultActor,
getSession,
listProjectSecrets,
MEMORY_FILE,
MEMORY_SECTIONS,
memoryContext,
rememberFact,
replaceMemory,
} from "@peppa/core";
// Peppa MCP server for agent sessions over stdio; the project defaults to the repo's .peppa/project.json.
import { dirname } from "node:path";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { findProjectFile, setDefaultActor } from "@peppa/core";
import { createDb } from "@peppa/db";
import { requestReview, reviewGate } from "@peppa/runner";
import { z } from "zod";
import { formatIncident, formatTask } from "./format.ts";
import { createAgentServer } from "./agent.ts";
const db = createDb();
const projectFile = findProjectFile(process.env.PEPPA_PROJECT_DIR ?? process.cwd());
const defaultKey = projectFile?.data.key;
// Set by the runner for sessions it starts; absent for a manual `claude`.
const sessionId = process.env.PEPPA_SESSION_ID ? Number(process.env.PEPPA_SESSION_ID) : undefined;
// PEP-48: this server acts for the agent (its tool calls are the agent's actions).
setDefaultActor({ kind: "agent", channel: "mcp" });
const server = new McpServer({ name: "peppa", version: "0.1.0" });
type Result = { content: Array<{ type: "text"; text: string }>; isError?: boolean };
function tool<S extends z.ZodRawShape>(
name: string,
description: string,
inputSchema: S,
run: (args: z.infer<z.ZodObject<S>>) => Promise<string>,
) {
server.registerTool(name, { description, inputSchema }, (async (args: z.infer<z.ZodObject<S>>): Promise<Result> => {
try {
return { content: [{ type: "text", text: await run(args) }] };
} catch (e) {
const msg = e instanceof PeppaError ? e.message : `Internal error: ${(e as Error).message}`;
return { content: [{ type: "text", text: msg }], isError: true };
}
}) as never);
}
const taskArg = z
.string()
.describe(`Story key like ${defaultKey ?? "PEP"}-42, or just the number for the current project`);
const projectArg = z
.string()
.optional()
.describe(`Project key or slug; defaults to the current repo's project${defaultKey ? ` (${defaultKey})` : ""}`);
async function projectOrDefault(p?: string) {
const k = p ?? defaultKey;
if (!k) throw new PeppaError("No project given and no .peppa/project.json found in this repo");
return getProject(db, k);
}
tool(
"get_rules",
"Get Peppa's shared agent rules (story workflow on OpenSpec, PM approval, when to ask the PM). Sessions started by Peppa already have them in the system prompt; call this in a manually started session.",
{},
async () => (await loadSharedRules()).text,
);
tool("get_task", "Get a Peppa story (one business story = one OpenSpec change): description, epic, status, OpenSpec change, PM Q&A and the next step to take. Call this first when the user names a story number.", { task: taskArg }, async ({ task }) =>
formatTask(await getTaskDetails(db, await resolveTask(db, task, defaultKey))),
);
tool(
"list_tasks",
"List stories in a project in board order (top = highest priority), optionally filtered by status or epic; \"waits for\" marks stories blocked by unfinished predecessors.",
{ project: projectArg, status: z.enum(TASK_STATUSES).optional(), epic_id: z.number().int().optional(), goal_id: z.number().int().optional().describe("Alias of epic_id") },
async ({ project, status, epic_id, goal_id }) => {
const p = await projectOrDefault(project);
const rows = await listTasks(db, { projectId: p.id, goalId: epic_id ?? goal_id, statuses: status ? [status] : undefined });
if (!rows.length) return "No stories.";
const deps = await blockersMap(db, p.id);
return rows.map((t) => {
const b = blockedLabel(deps.get(t.id))?.replace("ждёт", "waits for");
return `- ${t.key} [${t.status}]${t.goalId ? ` (epic #${t.goalId})` : ""} ${t.title}${b ? ` — ${b}` : ""}`;
}).join("\n");
},
);
const listEpicsText = async ({ project }: { project?: string }) => {
const p = await projectOrDefault(project);
const rows = await listEpics(db, p.id);
if (!rows.length) return "No open epics.";
const progress = await epicProgress(db, p.id);
return rows.map((g) => `- #${g.id} ${g.title} (done ${progressLabel(progress.get(g.id))})${g.description ? ` — ${g.description.split("\n")[0]}` : ""}`).join("\n");
};
tool("list_epics", "List the open epics of a project (labels that group stories).", { project: projectArg }, listEpicsText);
tool("list_goals", "Alias of list_epics (goals were renamed to epics).", { project: projectArg }, listEpicsText);
tool(
"create_task",
"Create a new story (e.g. follow-up work discovered outside the current change's scope). Label it with an epic when one fits.",
{
title: z.string().min(3),
description: z.string().optional(),
epic_id: z.number().int().optional(),
goal_id: z.number().int().optional().describe("Alias of epic_id"),
blocked_by: z.array(z.string()).optional().describe("Stories this one waits for (keys); it won't be started automatically until they are in review/done"),
project: projectArg,
},
async ({ title, description, epic_id, goal_id, blocked_by, project }) => {
const p = await projectOrDefault(project);
const ref = await createTask(db, { projectId: p.id, goalId: epic_id ?? goal_id, title, description });
const deps = blocked_by?.length ? await setDependencies(db, ref, blocked_by).catch((e: Error) => { throw new PeppaError(`Created ${ref.key}, but dependencies were not set: ${e.message}`); }) : [];
return `Created ${ref.key}: ${title}${deps.length ? ` (waits for ${deps.map((d) => d.key).join(", ")})` : ""}`;
},
);
tool(
"update_task",
"Update a story's status, OpenSpec change name, PR URL, title or description.",
{
task: taskArg,
status: z.enum(TASK_STATUSES).optional(),
openspec_change: z.string().optional().describe("Change id under openspec/changes/, e.g. pep-42-add-auth"),
pr_url: z.string().url().optional(),
title: z.string().optional(),
description: z.string().optional(),
},
async ({ task, status, openspec_change, pr_url, title, description }) => {
const ref = await resolveTask(db, task, defaultKey);
// Acceptance stays with the PM: agents can't mark work done or approve themselves.
if (status === "done") throw new PeppaError("Only the PM marks a story done. Open a PR and set status: review.");
if (status === "in_progress" && ref.task.status === "awaiting_approval") {
throw new PeppaError("The proposal is awaiting the PM's approval; only the PM can move it to in_progress.");
}
// PEP-23: a project where the PM approves every proposal — Apply only after the approval
// (the PM's answer moves the story to in_progress itself).
if (status === "in_progress" && (ref.task.status === "backlog" || ref.task.status === "proposing") && (await getAutonomy(db, ref.project.id)).proposal === "pm") {
throw new PeppaError("In this project the PM approves every proposal: call request_approval with the proposal summary and end your turn.");
}
if (status === "review" && ref.task.status !== "review") {
// PEP-57: review only with green checks of the PR head (the PR given now counts).
const reason = await reviewGate({ ...ref, task: { ...ref.task, prUrl: pr_url ?? ref.task.prUrl } });
if (reason) {
throw new PeppaError(`Not moved to review: ${reason}. Wait for the CI checks of the PR's last commit to pass (red ones come back to you with the log), then set status: review again.`);
}
}
if (status === "review" && ref.task.status !== "review") {
// PEP-26: the project's reviewer agent reads the diff before the PM (when turned on).
const withPr = { ...ref, task: { ...ref.task, prUrl: pr_url ?? ref.task.prUrl } };
const r = await requestReview(db, withPr).catch(() => ({ action: "review" as const }));
if (r.action === "queued") {
await updateTask(db, ref, { openspecChange: openspec_change, prUrl: pr_url, title, description }, sessionId);
return `${ref.key}: the reviewer agent is checking PR commit ${r.review.sha.slice(0, 7)} (review #${r.review.id}); the story stays in_progress. End your turn now — findings come back to you as a message; if the review is fine the story goes to the PM's review by itself.`;
}
}
const t = await updateTask(db, ref, { status, openspecChange: openspec_change, prUrl: pr_url, title, description }, sessionId);
return `${ref.key} updated: status=${t.status}${t.openspecChange ? `, change=${t.openspecChange}` : ""}${t.prUrl ? `, pr=${t.prUrl}` : ""}`;
},
);
tool(
"request_approval",
"Ask the PM to approve an ARCHITECTURAL decision in a story's proposal (new service/dependency, data model, security/access, money, irreversible actions, scope change). Routine proposals need no approval — go straight to apply. Sets awaiting_approval and notifies the PM; end your turn afterwards.",
{ task: taskArg, summary: z.string().min(10).describe("What, why, risks, open questions — readable on a phone") },
async ({ task, summary }) => {
const ref = await resolveTask(db, task, defaultKey);
const q = await askPm(db, ref, { kind: "approval", text: summary, sessionId });
return `Approval requested (#${q.id}); ${ref.key} is awaiting_approval. End your turn now and wait for the PM's reply.`;
},
);
tool(
"ask_pm",
"Ask the PM about a STOPPER only (scope, architecture, data, money, access/secrets, or a costly-to-undo fork). Decide everything else yourself and record it in design.md. Delivered to Telegram; end your turn afterwards — the answer arrives as the next user message.",
{
task: taskArg,
question: z.string().min(5).describe("One question, 1–2 sentences of context"),
options: z.array(z.string()).max(6).optional().describe("Suggested answers, shown as buttons"),
},
async ({ task, question, options }) => {
const ref = await resolveTask(db, task, defaultKey);
const q = await askPm(db, ref, { kind: "question", text: question, options, sessionId });
return `Question #${q.id} sent to the PM. End your turn now and wait for the answer.`;
},
);
tool(
"report_progress",
"Log a short progress note on a story (visible to the PM in the web UI / Telegram digest).",
{ task: taskArg, text: z.string().min(3) },
async ({ task, text }) => {
const ref = await resolveTask(db, task, defaultKey);
await reportProgress(db, ref, text, sessionId);
return `Progress noted on ${ref.key}.`;
},
);
tool(
"list_incidents",
"List production errors (Bugsink incidents) of a project: id, status, title, where, release, event count, linked story.",
{ project: projectArg, status: z.enum(incidentStatuses).optional() },
async ({ project, status }) => {
const p = await projectOrDefault(project);
const rows = await listIncidents(db, p.id, status ? [status] : undefined);
if (!rows.length) return "No incidents.";
return rows.map((i) => `- #${i.id} [${i.status}] ${i.title}${i.culprit ? ` (${i.culprit})` : ""} · ${i.environment ?? "?"} · release ${i.lastRelease ?? "?"} · ${i.events} events${i.taskId ? ` · story #${i.taskId}` : ""}`).join("\n");
},
);
tool(
"get_incident",
"Get a production error (Bugsink incident): stack top, where, release, environment, frequency, Bugsink link. Use it when fixing a bug story made from an incident: first write a test reproducing this stack.",
{ id: z.number().int() },
async ({ id }) => {
const i = await getIncident(db, id);
if (defaultKey && i.projectId !== (await getProject(db, defaultKey)).id) throw new PeppaError(`Incident #${id} is not in this project`);
return formatIncident(i);
},
);
tool(
"list_secrets",
"List the names of this project's secrets (API keys and accesses the PM stored in Peppa). They are already in your environment as variables of the same name — use them as $NAME, never print, log or commit their values. Values are not available here. Missing a secret? ask_pm to add it in «⋯ Настройки проекта → Секреты» (the next session start gets it).",
{},
async () => {
// PEP-54: only the project of this session (or this repo), names only.
const p = sessionId ? await getProject(db, (await getSession(db, sessionId)).projectKey) : await projectOrDefault();
const rows = await listProjectSecrets(db, p.id);
if (!rows.length) return `${p.key} has no secrets.`;
return [`Secrets of ${p.key} (in your env):`, ...rows.map((r) => `- ${r.name}`)].join("\n");
},
);
// ── PEP-30: project memory (.peppa/memory.md in the repo) ─────────────────────
// The repo root: where .peppa/project.json lives (the runner's working copy or worktree).
const memoryDir = () => {
if (!projectFile) throw new PeppaError("No .peppa/project.json found — project memory lives next to it");
return dirname(dirname(projectFile.path));
};
tool(
"get_memory",
`Read the project memory (${MEMORY_FILE}: commands, conventions, pitfalls, decisions written by earlier agents) and a digest of the last finished stories. Runner sessions already get it in the system prompt.`,
{},
async () => {
const dir = memoryDir();
const project = await projectOrDefault();
return memoryContext(db, project.id, dir);
},
);
tool(
"remember",
`Add one durable fact to the project memory (${MEMORY_FILE}) for the next agents: a build/test command, a convention, a pitfall you hit, a decision. One short line; duplicates are skipped. With replace: true, \`text\` becomes the whole memory (use it to compact when the size limit is near). Commit the file in your story branch.`,
{
section: z.string().optional().describe(`One of: ${MEMORY_SECTIONS.join(", ")} (or commands, conventions, pitfalls, decisions). Not needed with replace.`),
text: z.string().describe("The fact (one line), or the whole memory with replace: true"),
replace: z.boolean().optional(),
},
async ({ section, text, replace }) => {
const dir = memoryDir();
if (replace) {
const st = replaceMemory(dir, text);
return `Память переписана: ${st.chars} из ${st.max} символов. Закоммить ${MEMORY_FILE} в ветке стори.`;
}
const r = rememberFact(dir, section ?? "", text);
if (r.result === "exists") return "Такой пункт уже есть — ничего не изменил.";
return `Запомнил. Память: ${r.stats.chars} из ${r.stats.max} символов${r.stats.nearLimit ? " — почти предел, ужми (remember с replace: true)" : ""}. Закоммить ${MEMORY_FILE} в ветке стори.`;
},
);
const server = createAgentServer(db, {
defaultKey: projectFile?.data.key,
// Set by the runner for sessions it starts; absent for a manual `claude`.
sessionId: process.env.PEPPA_SESSION_ID ? Number(process.env.PEPPA_SESSION_ID) : undefined,
// PEP-30: the repo root (the runner's working copy or worktree) — where the memory file lives.
repoDir: projectFile ? dirname(dirname(projectFile.path)) : null,
});
await server.connect(new StdioServerTransport());

18
packages/mcp/src/relay.ts Normal file
View File

@ -0,0 +1,18 @@
// PEP-17: the agent MCP server behind the agent relay (/api/agent/mcp): Streamable HTTP,
// stateless, one server per request, locked to the session's project.
import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
import { runAsActor } from "@peppa/core";
import type { Db } from "@peppa/db";
import type { RelayContext } from "@peppa/runner";
import { createAgentServer } from "./agent.ts";
export async function agentRelayMcp(db: Db, ctx: RelayContext, req: Request): Promise<Response> {
return runAsActor({ kind: "agent", channel: "mcp" }, async () => {
// PEP-30: the memory file is in the runner's working copy — reachable here unless it is on a host.
const repoDir = ctx.session.host ? null : (ctx.session.workspacePath ?? ctx.project.workspacePath);
const server = createAgentServer(db, { defaultKey: ctx.project.key, sessionId: ctx.session.id, lockProject: true, repoDir });
const transport = new WebStandardStreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
await server.connect(transport);
return transport.handleRequest(req);
});
}

View File

@ -0,0 +1,204 @@
// PEP-17: the agent relay — the only way an agent in a runner container (here or on a host,
// PEP-40) reaches Peppa. Bearer = the run's token (core agentRelayToken). Hooks run here as the
// real peppa-hook; MCP is the agent server of the session's project (injected by the caller);
// git and the Gitea API are proxied only to the project's repo with the bot token, which never
// leaves Peppa. Request → Response handlers: Next routes and the test server share them.
import { spawn } from "node:child_process";
import { mkdirSync, writeFileSync } from "node:fs";
import { createServer, type Server } from "node:http";
import { join } from "node:path";
import { Readable } from "node:stream";
import { FINISHED_SESSION_STATUSES, getSession, parseAgentRelayToken, type Project, type SessionView } from "@peppa/core";
import { projects, type Db } from "@peppa/db";
import { loadEnv, peppaHome } from "@peppa/shared";
import { eq } from "drizzle-orm";
import { HOOK_BIN } from "./providers.ts";
/** Hook requests are answered within this time; a longer wait (a blocking question) is resumed by `rid`. */
const RELAY_WAIT_MS = () => Number(process.env.PEPPA_RELAY_WAIT_MS ?? 25_000);
const MAX_BODY = 12 * 1024 * 1024;
export interface RelayContext {
session: SessionView;
project: Project;
}
export type RelayMcpHandler = (db: Db, ctx: RelayContext, req: Request) => Promise<Response>;
const jsonRes = (body: unknown, status = 200) => Response.json(body, { status, headers: { "Cache-Control": "no-store" } });
/** The run behind the Bearer token: current generation; `alive` — the session is not finished. */
export async function relayAuth(db: Db, req: Request, opts: { alive: boolean }): Promise<RelayContext | null> {
const token = req.headers.get("authorization")?.match(/^Bearer\s+(\S+)$/i)?.[1];
const t = parseAgentRelayToken(token);
if (!t) return null;
const session = await getSession(db, t.sessionId).catch(() => null);
if (!session || session.generation !== t.generation) return null;
if (opts.alive && FINISHED_SESSION_STATUSES.includes(session.status)) return null;
const [project] = await db.select().from(projects).where(eq(projects.id, session.projectId));
return project ? { session, project } : null;
}
// ── hooks ──────────────────────────────────────────────────────────────────────
interface HookCall {
sessionId: number;
done: Promise<{ stdout: string }>;
result?: { stdout: string };
expires: number;
}
type Pending = Map<string, HookCall>;
const pending: Pending = ((globalThis as { __peppaRelayHooks?: Pending }).__peppaRelayHooks ??= new Map());
function runHook(ctx: RelayContext, event: string, args: string[], stdin: string): Promise<{ stdout: string }> {
const env = loadEnv();
return new Promise((resolve) => {
const p = spawn(HOOK_BIN(), [event, ...args], {
stdio: ["pipe", "pipe", "ignore"],
env: {
...process.env,
PEPPA_SESSION_ID: String(ctx.session.id),
PEPPA_GENERATION: String(ctx.session.generation),
PEPPA_DB: env.PEPPA_DB,
PEPPA_RELAYED: "1",
},
});
let out = "";
p.stdout.setEncoding("utf8").on("data", (d) => (out += d));
// A hook never breaks the agent: whatever happens, an answer (maybe empty) goes back.
p.on("error", () => resolve({ stdout: "" }));
p.on("close", () => resolve({ stdout: out }));
p.stdin.on("error", () => {});
p.stdin.end(stdin);
});
}
/** The transcript lives in the container: the shim sends its tail, the hook reads this copy. */
function withTranscript(ctx: RelayContext, stdin: string, transcript: unknown): string {
if (typeof transcript !== "string" || !transcript) return stdin;
try {
const input = JSON.parse(stdin) as Record<string, unknown>;
const dir = join(peppaHome(), "relay", `s${ctx.session.id}`);
mkdirSync(dir, { recursive: true, mode: 0o700 });
const file = join(dir, "transcript.jsonl");
writeFileSync(file, transcript.slice(-8 * 1024 * 1024));
return JSON.stringify({ ...input, transcript_path: file });
} catch {
return stdin;
}
}
async function waitFor(call: HookCall, ms: number): Promise<{ stdout: string } | null> {
if (call.result) return call.result;
let timer: NodeJS.Timeout | undefined;
const r = await Promise.race([call.done, new Promise<null>((res) => (timer = setTimeout(() => res(null), ms)))]);
clearTimeout(timer);
return r;
}
async function hookRequest(db: Db, req: Request): Promise<Response> {
const ctx = await relayAuth(db, req, { alive: true });
if (!ctx) return jsonRes({ error: "invalid agent token" }, 401);
const body = (await req.json().catch(() => null)) as { event?: string; args?: unknown; stdin?: unknown; transcript?: unknown; rid?: string } | null;
if (!body) return jsonRes({ error: "bad request" }, 400);
const now = Date.now();
for (const [k, c] of pending) if (c.expires < now) pending.delete(k);
let rid = body.rid;
let call = rid ? pending.get(rid) : undefined;
if (rid && (!call || call.sessionId !== ctx.session.id)) return jsonRes({ error: "unknown rid" }, 404);
if (!call) {
if (!body.event || !/^[a-z-]{1,40}$/.test(body.event)) return jsonRes({ error: "bad event" }, 400);
const args = Array.isArray(body.args) ? body.args.filter((a): a is string => typeof a === "string").slice(0, 4) : [];
const stdin = withTranscript(ctx, typeof body.stdin === "string" ? body.stdin : "", body.transcript);
rid = crypto.randomUUID();
const c: HookCall = { sessionId: ctx.session.id, done: runHook(ctx, body.event, args, stdin), expires: now + 20 * 60_000 };
void c.done.then((r) => (c.result = r));
call = c;
pending.set(rid, call);
}
const r = await waitFor(call, RELAY_WAIT_MS());
if (!r) return jsonRes({ wait: true, rid });
pending.delete(rid!);
return jsonRes({ stdout: r.stdout });
}
// ── git / Gitea proxy ──────────────────────────────────────────────────────────
/** Only the session project's repo: git over HTTP (`owner/repo[.git]/…`) and its API (`api/v1/repos/owner/repo…`). */
export function allowedGitPath(project: Pick<Project, "giteaOwner" | "giteaRepo">, path: string): boolean {
const p = path.replace(/^\/+/, "");
if (p.split("/").some((seg) => seg === ".." || seg === ".")) return false;
const repo = `${project.giteaOwner}/${project.giteaRepo}`.toLowerCase();
const lower = p.toLowerCase();
return lower.startsWith(`${repo}.git/`) || lower.startsWith(`${repo}/`) || lower === `api/v1/repos/${repo}` || lower.startsWith(`api/v1/repos/${repo}/`);
}
const FORWARD_HEADERS = ["content-type", "content-encoding", "accept", "git-protocol", "content-length"];
const BACK_HEADERS = ["content-type", "cache-control", "expires", "pragma", "link", "x-total-count"];
async function gitRequest(db: Db, req: Request, rest: string): Promise<Response> {
// The generation is enough here: a resumed runner's clone is made again before it is alive.
const ctx = await relayAuth(db, req, { alive: false });
if (!ctx) return new Response("invalid agent token\n", { status: 401, headers: { "WWW-Authenticate": 'Bearer realm="peppa-agent"' } });
if (!allowedGitPath(ctx.project, rest)) return new Response("forbidden: only this project's repository\n", { status: 403 });
const env = loadEnv();
const token = (env as Record<string, string | undefined>).GITEA_TOKEN;
const url = `${env.GITEA_URL.replace(/\/$/, "")}/${rest.replace(/^\/+/, "")}${new URL(req.url).search}`;
const headers = new Headers();
for (const h of FORWARD_HEADERS) {
const v = req.headers.get(h);
if (v) headers.set(h, v);
}
// Undecoded bytes both ways (fetch would gunzip a response but keep its header).
headers.set("accept-encoding", "identity");
if (token) headers.set("authorization", `token ${token}`);
const hasBody = req.method !== "GET" && req.method !== "HEAD";
const up = await fetch(url, { method: req.method, headers, body: hasBody ? req.body : undefined, duplex: "half", redirect: "manual" } as RequestInit);
const back = new Headers();
for (const h of BACK_HEADERS) {
const v = up.headers.get(h);
if (v) back.set(h, v);
}
return new Response(up.body, { status: up.status, headers: back });
}
// ── entry ──────────────────────────────────────────────────────────────────────
/** `path` — after /api/agent (e.g. "/hook", "/mcp", "/git/owner/repo.git/info/refs"). */
export async function handleAgentRelay(db: Db, req: Request, path: string, opts: { mcp?: RelayMcpHandler } = {}): Promise<Response> {
try {
if (Number(req.headers.get("content-length") ?? 0) > MAX_BODY) return jsonRes({ error: "too large" }, 413);
if (path === "/hook" && req.method === "POST") return await hookRequest(db, req);
if (path === "/mcp") {
if (req.method !== "POST") return new Response("Method Not Allowed (stateless server: POST only)", { status: 405, headers: { Allow: "POST" } });
const ctx = await relayAuth(db, req, { alive: true });
if (!ctx) return jsonRes({ error: "invalid agent token" }, 401);
if (!opts.mcp) return jsonRes({ error: "mcp not served here" }, 501);
return await opts.mcp(db, ctx, req);
}
if (path.startsWith("/git/")) return await gitRequest(db, req, path.slice(5));
return jsonRes({ error: "not found" }, 404);
} catch (e) {
return jsonRes({ error: (e as Error).message }, 500);
}
}
/** The relay on node:http (tests; a standalone relay if the web is not reachable from hosts). */
export function serveAgentRelay(db: Db, port: number, opts: { mcp?: RelayMcpHandler; host?: string } = {}): Promise<Server> {
const server = createServer(async (req, res) => {
const url = new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`);
const path = url.pathname.replace(/^\/api\/agent/, "");
const hasBody = req.method !== "GET" && req.method !== "HEAD";
const request = new Request(url, {
method: req.method,
headers: Object.entries(req.headers).flatMap(([k, v]) => (v === undefined ? [] : (Array.isArray(v) ? v : [v]).map((x) => [k, x] as [string, string]))),
body: hasBody ? (Readable.toWeb(req) as ReadableStream) : undefined,
duplex: "half",
} as RequestInit);
const r = await handleAgentRelay(db, request, path, opts);
res.writeHead(r.status, Object.fromEntries(r.headers));
if (r.body) for await (const chunk of r.body as unknown as AsyncIterable<Uint8Array>) res.write(chunk);
res.end();
});
return new Promise((resolve) => server.listen(port, opts.host ?? "127.0.0.1", () => resolve(server)));
}

View File

@ -58,7 +58,7 @@ async function pauseStory(db: Db, taskId: number, ss: SessionView[], over: strin
await setBudgetState(db, taskId, { pausedAt: now, over: over as never, questionId: null });
for (const s of ss) {
// Escape interrupts the agent's turn; the process and the conversation stay for «extend».
if (s.status === "running" || s.status === "starting" || s.status === "stalled") await tmux.sendKeys(s.tmuxName, "Escape").catch(() => {});
if (s.status === "running" || s.status === "starting" || s.status === "stalled") await tmux.sendKeys(tmux.sessionPane(s), "Escape").catch(() => {});
await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: new Date(now) });
await logSessionEvent(db, s, "budget_paused", { over, summary });
}
@ -75,7 +75,7 @@ async function pauseStory(db: Db, taskId: number, ss: SessionView[], over: strin
/** Resumes paused live runners of the story with a message. */
async function continueStory(db: Db, taskId: number, text: string) {
for (const s of await listSessions(db, { active: true, taskId })) {
if (!(await tmux.hasSession(s.tmuxName))) continue;
if (!(await tmux.hasSession(tmux.sessionPane(s)))) continue;
await sendToSession(db, s.id, text).catch(() => {});
}
}

128
packages/runner/src/exec.ts Normal file
View File

@ -0,0 +1,128 @@
// PEP-40: run a command on Peppa's machine or on a runner host over SSH (Peppa's own key,
// one multiplexed connection per host). No daemon on the host: tmux, docker and git only.
import { spawn } from "node:child_process";
import { createHash } from "node:crypto";
import { existsSync, mkdirSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { peppaHome } from "@peppa/shared";
/** How to reach a host (a `runner_hosts` row or `SessionView.host`); null = this machine. */
export interface HostTarget {
name: string;
sshTarget: string;
sshPort: number;
}
export type Target = HostTarget | null | undefined;
/** The host did not answer over SSH (ssh exit 255): state unknown, not "gone". */
export class HostUnreachable extends Error {
host: string;
constructor(host: string, detail: string) {
super(`Хост ${host} недоступен по SSH: ${detail.trim().split("\n").slice(-1)[0] || "нет соединения"}`);
this.host = host;
}
}
export class ExecError extends Error {
code: number | null;
stderr: string;
stdout: string;
constructor(cmd: string, code: number | null, stdout: string, stderr: string) {
super(`${cmd} failed (${code}): ${stderr.trim().slice(-500)}`);
this.code = code;
this.stdout = stdout;
this.stderr = stderr;
}
}
/** Quotes one word for a POSIX shell. */
export const shq = (s: string) => (/^[A-Za-z0-9_@%+=:,./-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`);
export const sshDir = () => join(peppaHome(), "ssh");
export const sshKeyPath = () => join(sshDir(), "id_ed25519");
/** Peppa's SSH key (created on first use); returns the public key for hosts' authorized_keys. */
export async function ensureSshKey(): Promise<string> {
const key = sshKeyPath();
if (!existsSync(key)) {
mkdirSync(sshDir(), { recursive: true, mode: 0o700 });
await runOn(null, [process.env.PEPPA_SSH_KEYGEN_BIN ?? "ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-C", "peppa-runner", "-f", key]);
}
return readFileSync(`${key}.pub`, "utf8").trim();
}
/**
* Directory of the multiplexing sockets: a unix socket path is limited to 104 bytes (macOS), and
* ssh appends a 40-char hash — a deep PEPPA_HOME falls back to a short private dir in /tmp.
*/
function controlDir(): string {
const dir = sshDir();
if (dir.length + 45 < 100) return dir;
const short = `/tmp/peppa-ssh-${process.getuid?.() ?? 0}-${createHash("sha1").update(dir).digest("hex").slice(0, 8)}`;
mkdirSync(short, { recursive: true, mode: 0o700 });
return short;
}
export function sshArgs(h: HostTarget): string[] {
const dir = sshDir();
mkdirSync(dir, { recursive: true, mode: 0o700 });
return [
"-i", sshKeyPath(),
"-p", String(h.sshPort),
"-o", "BatchMode=yes",
"-o", "ConnectTimeout=10",
"-o", "ServerAliveInterval=15",
"-o", "StrictHostKeyChecking=accept-new",
"-o", `UserKnownHostsFile=${join(dir, "known_hosts")}`,
// One connection per host: the web terminal polls tmux every 250 ms (PEP-9).
"-o", "ControlMaster=auto",
"-o", `ControlPath=${join(controlDir(), "cm-%C")}`,
"-o", "ControlPersist=600",
];
}
export interface RunOptions {
input?: string | Buffer;
/** Working directory (remote: `cd` first). */
cwd?: string;
/** Extra environment (remote: `env K=V`). */
env?: Record<string, string>;
timeoutMs?: number;
}
/** argv → the command line ssh hands to the host's shell. */
export function remoteCommand(argv: string[], opts: Pick<RunOptions, "cwd" | "env"> = {}): string {
const env = Object.entries(opts.env ?? {}).map(([k, v]) => shq(`${k}=${v}`));
const cmd = [...(env.length ? ["env", ...env] : []), ...argv.map(shq)].join(" ");
return opts.cwd ? `cd ${shq(opts.cwd)} && ${cmd}` : cmd;
}
/** Runs argv locally, or on the host through ssh. Rejects with ExecError / HostUnreachable. */
export function runOn(target: Target, argv: string[], opts: RunOptions = {}): Promise<{ stdout: string; stderr: string }> {
const [bin, args, spawnOpts] = target
? [process.env.PEPPA_SSH_BIN ?? "ssh", [...sshArgs(target), target.sshTarget, remoteCommand(argv, opts)], {}]
: [argv[0]!, argv.slice(1), { cwd: opts.cwd, env: opts.env ? { ...process.env, ...opts.env } : process.env }];
return new Promise((resolve, reject) => {
const p = spawn(bin, args, { ...spawnOpts, stdio: ["pipe", "pipe", "pipe"] });
let out = "";
let err = "";
p.stdout.setEncoding("utf8").on("data", (d) => (out += d));
p.stderr.setEncoding("utf8").on("data", (d) => (err += d));
const timer = opts.timeoutMs ? setTimeout(() => p.kill("SIGKILL"), opts.timeoutMs) : null;
p.on("error", (e) => {
if (timer) clearTimeout(timer);
reject(target ? new HostUnreachable(target.name, e.message) : e);
});
p.on("close", (code) => {
if (timer) clearTimeout(timer);
if (code === 0) return resolve({ stdout: out, stderr: err });
if (target && (code === 255 || code === null)) return reject(new HostUnreachable(target.name, err || "timeout"));
reject(new ExecError(target ? `${target.name}: ${argv[0]}` : argv[0]!, code, out, err));
});
p.stdin.on("error", () => {});
p.stdin.end(opts.input ?? "");
});
}
/** Shell script on the host (`sh -c`), for pipelines like mkdir + tar. */
export const shOn = (target: Target, script: string, opts: RunOptions = {}) => runOn(target, ["sh", "-c", script], opts);

View File

@ -0,0 +1,153 @@
// PEP-40: runner hosts over SSH — checks (hostTick), the runner's clone and launch dir on the
// host. On the host: sshd, tmux, docker and the runner image (PEP-17); nothing of Peppa's.
import { execFileSync } from "node:child_process";
import { existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
import {
agentRelayToken,
listHosts,
recordHostCheck,
type Project,
type RunnerHost,
type SessionHost,
type SessionView,
} from "@peppa/core";
import type { Db, RunnerHostInfo } from "@peppa/db";
import { loadEnv } from "@peppa/shared";
import { HostUnreachable, runOn, shOn, shq, type HostTarget } from "./exec.ts";
import { claudeConfigFor, gitRelayEnv, relayUrl, runnerImage } from "./sandbox.ts";
import { storyBranch } from "./worktree.ts";
type Host = HostTarget & Pick<SessionHost, "id" | "workdir" | "peppaUrl">;
// Absolute workdir per host (the configured one may be relative to the SSH user's home).
const workdirs = new Map<string, string>();
/** `<workdir>` on the host as an absolute path; creates ws/, runs/, home/. */
export async function hostWorkdir(h: Host): Promise<string> {
const key = `${h.id}:${h.workdir}`;
const known = workdirs.get(key);
if (known) return known;
const w = h.workdir.replace(/^~\//, "");
const { stdout } = await shOn(h, `mkdir -p ${shq(w)}/ws ${shq(w)}/runs ${shq(w)}/home && cd ${shq(w)} && pwd`);
const abs = stdout.trim().split("\n").pop()!;
if (!abs.startsWith("/")) throw new Error(`не удалось определить каталог ${h.workdir} на хосте`);
workdirs.set(key, abs);
return abs;
}
export const hostRunDir = async (h: Host, sessionId: number, generation: number) => `${await hostWorkdir(h)}/runs/s${sessionId}-g${generation}`;
/** Copies a launch dir (settings, rules, launch.sh) to the host. */
export async function pushRunDir(h: Host, localDir: string, remoteDir: string): Promise<void> {
const tar = execFileSync("tar", ["-c", "-C", localDir, "."], { env: { ...process.env, COPYFILE_DISABLE: "1" } });
await shOn(h, `mkdir -p ${shq(remoteDir)} && tar -x -C ${shq(remoteDir)} 2>/dev/null`, { input: tar });
}
/** The agent's HOME on the host, with the claude config trusting its working copy. */
export async function hostAgentHome(h: Host, sessionId: number, cwd: string): Promise<string> {
const home = `${await hostWorkdir(h)}/home/s${sessionId}`;
const f = `${home}/.claude.json`;
const { stdout } = await shOn(h, `mkdir -p ${shq(home)} && chmod 700 ${shq(home)} && cat ${shq(f)} 2>/dev/null || true`);
let existing: string | null = stdout.trim() || null;
try {
if (existing) JSON.parse(existing);
} catch {
existing = null;
}
await shOn(h, `cat > ${shq(f)}`, { input: claudeConfigFor(existing, cwd) });
return home;
}
/**
* The runner's clone on the host (`<workdir>/ws/<slug>/s<id>`) on the story's branch. Cloned by a
* one-off container of the runner image through the relay's git proxy — no token on the host.
* Untracked Peppa files (.peppa/project.json, .mcp.json) come from the project's copy.
*/
export async function ensureHostWorkspace(db: Db, s: SessionView, project: Project): Promise<{ path: string; branch: string | null }> {
const h = s.host;
if (!h) throw new Error("runner has no host");
void db;
const abs = await hostWorkdir(h);
const parent = `${abs}/ws/${project.slug}`;
const path = `${parent}/s${s.id}`;
const branch = s.taskKey ? storyBranch(s.taskKey) : null;
const { stdout } = await shOn(h, `test -d ${shq(path)}/.git && echo yes || echo no`);
if (stdout.trim() !== "yes") {
const relay = relayUrl(h);
const env = gitRelayEnv(relay, agentRelayToken(s.id, s.generation));
const url = `${loadEnv().GITEA_URL.replace(/\/$/, "")}/${project.giteaOwner}/${project.giteaRepo}.git`;
const inner = [
`git clone --quiet ${shq(url)} ${shq(path)}`,
`cd ${shq(path)}`,
...(branch ? [`(git checkout --quiet ${shq(branch)} 2>/dev/null || git checkout --quiet -b ${shq(branch)})`] : []),
].join(" && ");
const docker = [
"docker", "run", "--rm",
"--add-host", "host.docker.internal:host-gateway",
"-v", `${parent}:${parent}`,
"-e", `HOME=/tmp`,
...Object.entries(env).flatMap(([k, v]) => ["-e", `${k}=${v}`]),
];
await shOn(h, `mkdir -p ${shq(parent)} && ${docker.map(shq).join(" ")} --user "$(id -u):$(id -g)" ${shq(runnerImage())} sh -c ${shq(inner)}`, { timeoutMs: 10 * 60_000 });
}
for (const f of [".peppa/project.json", ".mcp.json"]) {
const src = join(project.workspacePath, f);
if (!existsSync(src)) continue;
const dst = `${path}/${f}`;
await shOn(h, `test -e ${shq(dst)} || { mkdir -p "$(dirname ${shq(dst)})" && cat > ${shq(dst)}; }`, { input: readFileSync(src) });
}
return { path, branch };
}
/** One look at the host: OS, docker, tmux, CPUs, load, whether the runner image is there. */
export async function checkHost(db: Db, host: RunnerHost, now = new Date()): Promise<RunnerHost> {
const image = runnerImage();
const script = [
`echo "os=$(uname -sm)"`,
`echo "docker=$(docker version --format '{{.Server.Version}}' 2>/dev/null)"`,
`echo "tmux=$(tmux -V 2>/dev/null)"`,
`echo "cpus=$(nproc 2>/dev/null || sysctl -n hw.ncpu 2>/dev/null)"`,
`echo "load=$(cut -d' ' -f1 /proc/loadavg 2>/dev/null || sysctl -n vm.loadavg 2>/dev/null | awk '{print $2}')"`,
`echo "image=$(docker image inspect -f '{{.Id}}' ${shq(image)} 2>/dev/null | cut -c8-19)"`,
].join("; ");
try {
const { stdout } = await shOn(host, script, { timeoutMs: 30_000 });
const kv = Object.fromEntries(stdout.split("\n").map((l) => [l.slice(0, l.indexOf("=")), l.slice(l.indexOf("=") + 1).trim()]));
const info: RunnerHostInfo = {
os: kv.os || undefined,
docker: kv.docker || undefined,
tmux: kv.tmux || undefined,
cpus: kv.cpus ? Number(kv.cpus) : undefined,
load: kv.load ? Number(kv.load) : undefined,
image: kv.image || null,
checkedAt: now.getTime(),
};
const missing = [!info.docker && "docker", !info.tmux && "tmux"].filter(Boolean);
if (missing.length) return recordHostCheck(db, host.id, { ok: false, error: `на хосте нет ${missing.join(" и ")}` }, now);
return recordHostCheck(db, host.id, { ok: true, info }, now);
} catch (e) {
return recordHostCheck(db, host.id, { ok: false, error: e instanceof HostUnreachable ? e.message : (e as Error).message }, now);
}
}
const HOST_CHECK_MS = 60_000;
const lastCheck = new Map<number, number>();
/** Watchdog: each enabled host once a minute; logs going offline / back online. */
export async function hostTick(db: Db, opts: { now?: Date; log?: (m: string) => void; force?: boolean } = {}): Promise<void> {
const now = opts.now ?? new Date();
for (const h of await listHosts(db, { enabled: true })) {
if (!opts.force && now.getTime() - (lastCheck.get(h.id) ?? 0) < HOST_CHECK_MS) continue;
lastCheck.set(h.id, now.getTime());
const r = await checkHost(db, h, now);
if (r.status !== h.status) opts.log?.(`host ${h.name}: ${h.status} → ${r.status}${r.lastError ? ` (${r.lastError})` : ""}`);
}
}
/** Puts the runner image on a host: `docker save` here | `docker load` there. */
export async function pushImage(host: RunnerHost): Promise<void> {
const image = runnerImage();
const tar = execFileSync(process.env.PEPPA_DOCKER_BIN ?? "docker", ["save", image], { maxBuffer: 4 * 1024 ** 3 });
await runOn(host, ["docker", "load"], { input: tar, timeoutMs: 30 * 60_000 });
}

View File

@ -34,3 +34,7 @@ export * from "./runner-client.ts";
export * from "./runner-service.ts";
export * from "./recovery.ts";
export * from "./escalation.ts";
export * from "./exec.ts";
export * from "./sandbox.ts";
export * from "./hosts.ts";
export * from "./agent-relay.ts";

View File

@ -1,16 +1,19 @@
import { writeFileSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
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)), "../../.."));
const HOOK_BIN = () => `${ROOT()}/packages/runner/bin/peppa-hook`;
export const HOOK_BIN = () => `${ROOT()}/packages/runner/bin/peppa-hook`;
const MCP_BIN = () => `${ROOT()}/packages/mcp/bin/peppa-mcp`;
export interface LaunchContext {
@ -24,25 +27,33 @@ export interface LaunchContext {
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<LaunchContext, "sessionId" | "generation">): Record<string, string> {
return provider === "opencode" ? { OPENCODE_CONFIG: join(runDir(c.sessionId, c.generation), "opencode.json") } : {};
export function providerEnv(provider: Provider, c: Pick<LaunchContext, "sessionId" | "generation" | "sandbox">): Record<string, string> {
return provider === "opencode" ? { OPENCODE_CONFIG: runFile(c, join(runDir(c.sessionId, c.generation), "opencode.json")) } : {};
}
function claudeCommand(c: LaunchContext): string[] {
return [
process.env.PEPPA_CLAUDE_BIN ?? "claude",
bin(c, "claude", "PEPPA_CLAUDE_BIN"),
"--settings",
writeRunSettings(c.sessionId, c.generation),
runFile(c, writeRunSettings(c.sessionId, c.generation, hookBin(c))),
"--append-system-prompt-file",
writeRunRules(c.sessionId, c.generation, c.rules),
runFile(c, writeRunRules(c.sessionId, c.generation, c.rules)),
"--permission-mode",
c.permissionMode ?? process.env.PEPPA_PERMISSION_MODE ?? "acceptEdits",
...(c.model ? ["--model", c.model] : []),
@ -61,7 +72,7 @@ function claudeCommand(c: LaunchContext): string[] {
function codexCommand(c: LaunchContext): string[] {
const toml = (v: unknown) => JSON.stringify(v);
return [
process.env.PEPPA_CODEX_BIN ?? "codex",
bin(c, "codex", "PEPPA_CODEX_BIN"),
"--no-alt-screen",
"--cd",
c.cwd,
@ -70,11 +81,11 @@ function codexCommand(c: LaunchContext): string[] {
// 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([HOOK_BIN(), "codex-notify"])}`,
`notify=${toml([hookBin(c), "codex-notify"])}`,
"-c",
`developer_instructions=${toml(c.rules)}`,
"-c",
`mcp_servers.peppa.command=${toml(MCP_BIN())}`,
`mcp_servers.peppa.command=${toml(mcpBin(c))}`,
...(c.resume ? ["resume", c.resume] : []),
"--",
c.prompt,
@ -93,15 +104,15 @@ function opencodeCommand(c: LaunchContext): string[] {
JSON.stringify(
{
$schema: "https://opencode.ai/config.json",
instructions: [writeRunRules(c.sessionId, c.generation, c.rules)],
mcp: { peppa: { type: "local", command: [MCP_BIN()], enabled: true } },
instructions: [runFile(c, writeRunRules(c.sessionId, c.generation, c.rules))],
mcp: { peppa: { type: "local", command: [mcpBin(c)], enabled: true } },
},
null,
2,
),
);
return [
process.env.PEPPA_OPENCODE_BIN ?? "opencode",
bin(c, "opencode", "PEPPA_OPENCODE_BIN"),
c.cwd,
...(c.model ? ["--model", c.model] : []),
...(c.resume ? ["--session", c.resume] : []),

View File

@ -22,7 +22,7 @@ import {
} from "@peppa/core";
import { projects, questions, sessions, tasks, type Db, type WatchState } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared";
import { resumeSession, stopSession } from "./sessions.ts";
import { killRunner, resumeSession, stopSession } from "./sessions.ts";
import * as tmux from "./tmux.ts";
export interface WatchdogSettings {
@ -198,7 +198,7 @@ export async function restartStalled(db: Db, s: SessionView, o: { now: Date; cfg
await logSessionEvent(db, s, "restart_skipped", { reason: "stall", why: blocker });
return false;
}
await tmux.killSession(s.tmuxName).catch(() => {});
await killRunner(s).catch(() => {});
await patchWatch(db, s, { stallAlertAt: undefined, restartAt: o.now.getTime(), restartReason: "stall" }, { status: "failed", endedAt: o.now });
await logSessionEvent(db, s, "restart_planned", { reason: "stall", attempt: restartsInWindow(s, o.cfg, o.now.getTime()).length + 1, of: o.cfg.restartMax });
await restartTick(db, o);

View File

@ -54,7 +54,7 @@ const hhmm = (d: Date) => d.toLocaleTimeString("ru-RU", { hour: "2-digit", minut
export async function rotateSession(db: Db, s: SessionView, target: Subscription, reason: RotateReason, now = new Date()): Promise<SessionView> {
const from = s.subscriptionId ? await getSubscription(db, s.subscriptionId).catch(() => null) : null;
const carried = s.provider === "codex" || !s.conversationId ? "fresh" : "resume";
if (await tmux.hasSession(s.tmuxName)) await tmux.killSession(s.tmuxName);
await (await import("./sessions.ts")).killRunner(s);
await expireSessionQuestions(db, s.id, "(неактуально: раннер переключён на другую подписку)");
await updateSession(db, s.id, {
subscriptionId: target.id,

View File

@ -30,13 +30,14 @@ export function writeRunRules(sessionId: number, generation: number, text: strin
return path;
}
export function writeRunSettings(sessionId: number, generation: number): string {
const hook = (event: string, timeout = 30) => ({ type: "command", command: `${hookBin()} ${event}`, timeout });
/** `bin` — the hook program as the agent sees it (PEP-17: `peppa-hook` from the runner image). */
export function writeRunSettings(sessionId: number, generation: number, bin: string = hookBin()): string {
const hook = (event: string, timeout = 30) => ({ type: "command", command: `${bin} ${event}`, timeout });
// PEP-33: steps of the agent; async — Claude doesn't wait for the hook process.
const step = { ...hook("tool-use", 15), async: true };
const settings = {
// PEP-5: Claude reports cost, context and the 5h/7d limit windows to the status line command.
statusLine: { type: "command", command: `${hookBin()} statusline`, padding: 0 },
statusLine: { type: "command", command: `${bin} statusline`, padding: 0 },
hooks: {
SessionStart: [{ hooks: [hook("session-start")] }],
UserPromptSubmit: [{ hooks: [hook("prompt")] }],

View File

@ -161,7 +161,7 @@ export async function advanceRunner(db: Db, sessionId: number, log: (m: string)
const note = agentAutonomyNote(await getAutonomy(db, s.projectId));
const work = [`Работай над стори ${ref.key} по правилам AGENTS.md.`, note, item.prompt].filter(Boolean).join("\n\n");
s = await getSession(db, s.id);
const alive = (await tmux.hasSession(s.tmuxName)) && !(await tmux.paneState(s.tmuxName)).dead;
const alive = (await tmux.hasSession(tmux.sessionPane(s))) && !(await tmux.paneState(tmux.sessionPane(s))).dead;
if (rs.context === "continue") {
const text = `${from ? `Стори ${from} закончена. ` : ""}Следующая стори в этом же разговоре. ${work}`;
if (alive) await sendToSession(db, s.id, text);
@ -271,7 +271,7 @@ export async function promoteRunner(db: Db, sessionId: number, t: { title: strin
await updateSession(db, s.id, { taskId: ref.task.id, autoNudges: 0 });
await activateRunnerTask(db, s.id, ref.task.id);
await logSessionEvent(db, await getSession(db, s.id), "task_promoted", { key: ref.key });
if (!FINISHED_SESSION_STATUSES.includes(s.status) && (await tmux.hasSession(s.tmuxName))) {
if (!FINISHED_SESSION_STATUSES.includes(s.status) && (await tmux.hasSession(tmux.sessionPane(s)))) {
await sendToSession(db, s.id, `Эта работа оформлена как стори ${ref.key} «${ref.task.title}». Дальше веди её по правилам Пеппы (peppa.get_task, OpenSpec change, PR, update_task(status: review)).`);
}
return ref;

View File

@ -0,0 +1,147 @@
// 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";
/** 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<string, string | undefined>;
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<string, any>) : {};
cfg.hasCompletedOnboarding = true;
cfg.projects ??= {};
const p = (cfg.projects[cwd] ??= {});
p.hasTrustDialogAccepted = true;
p.hasCompletedProjectOnboarding = true;
p.enabledMcpjsonServers = Array.from(new Set([...(p.enabledMcpjsonServers ?? []), "peppa"]));
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<string, string> {
const gitea = (loadEnv() as Record<string, string | undefined>).GITEA_URL?.replace(/\/$/, "");
if (!gitea) return {};
const base = `${relay}/api/agent/git/`;
return {
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<string, string>;
/** 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<ContainerSpec, "sessionId" | "generation" | "relay">, extra: Record<string, string>): Record<string, string> {
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<void> {
await runOn(target, [dockerBin(target), "rm", "-f", name]).catch(() => {});
}

View File

@ -44,6 +44,9 @@ import * as tmux from "./tmux.ts";
import { onReleaseAnswer } from "./deploy.ts";
import { ensureWorktree } from "./worktree.ts";
import { isRunnerClient, runnerCall } from "./runner-client.ts";
import { pickHost } from "@peppa/core";
import { containerEnv, containerName, dockerRunScript, prepareLocalHome, relayUrl, removeContainer, type Mount } from "./sandbox.ts";
import { ensureHostWorkspace, hostAgentHome, hostRunDir, pushRunDir } from "./hosts.ts";
export interface StartOptions {
/** Extra instructions appended to the default "work on <task>" prompt. */
@ -70,6 +73,13 @@ export async function assertBudgetOpen(db: Db, taskId: number | null | undefined
const shq = (s: string) => `'${s.replace(/'/g, `'\\''`)}'`;
/** Stops the runner's process: its tmux session and, in a sandbox, its container (PEP-17). */
export async function killRunner(s: SessionView): Promise<void> {
const pane = tmux.sessionPane(s);
if (await tmux.hasSession(pane)) await tmux.killSession(pane).catch(() => {});
if (s.container) await removeContainer(s.host, s.container);
}
/** Starts an interactive agent session (Claude Code or Codex) for a task in a detached tmux session. */
export async function startSession(db: Db, taskInput: string, opts: StartOptions = {}): Promise<SessionView> {
const ref = await resolveTask(db, taskInput, opts.defaultProjectKey);
@ -107,6 +117,11 @@ export async function startRunner(
if (!existsSync(dir)) throw new PeppaError(`Workspace ${dir} does not exist — bootstrap the project first`);
const rs = await resolveRunnerSettings(db, project.id, task?.id);
await assertRunnerSlot(db, project.id, rs.maxRunners);
// PEP-40: runners of the project go to the least busy online host of its list.
const host = rs.hosts.length ? await pickHost(db, rs.hosts) : null;
if (rs.hosts.length && !host) throw new PeppaError("Нет доступного хоста для раннера: все хосты проекта офлайн или отключены");
// PEP-17: a host always runs the agent in its container.
const sandboxed = rs.isolation === "container" || !!host;
// PEP-67: the first free active subscription of the chosen set decides the provider.
// PEP-41: the agent settings may ask for a provider; with none usable — the fallback one.
@ -126,11 +141,26 @@ export async function startRunner(
fallback = { from: wanted ?? null, reason: (e as Error).message };
}
const provider = sub?.provider ?? wanted ?? (process.env.PEPPA_PROVIDER as Provider | undefined) ?? "claude";
// The container has no login of this machine: the agent runs on its subscription.
if (sandboxed && !sub) throw new PeppaError("Для запуска агента в контейнере нужна подписка: добавьте её в пул проекта (раздел «Подписки»)");
if (host && provider === "codex") throw new PeppaError("Codex на удалённом хосте пока не поддерживается — выберите подписку Claude или OpenCode");
const session = await createSession(db, { projectId: project.id, taskId: task?.id ?? null, provider, subscriptionId: sub?.id ?? null, name: opts.name?.trim() || null });
if (fallback) await logSessionEvent(db, await getSession(db, session.id), "provider_fallback", { from: fallback.from, to: provider, subscriptionId: sub?.id ?? null, reason: fallback.reason });
const tmuxName = `peppa-${(task?.key ?? project.key).toLowerCase()}-s${session.id}`;
await updateSession(db, session.id, { tmuxName });
await updateSession(db, session.id, { tmuxName, hostId: host?.id ?? null, container: sandboxed ? containerName(session.id) : null });
if (task) await activateRunnerTask(db, session.id, task.id);
if (host) {
// The runner's own clone on the host, on the story's branch (through the relay: no token there).
try {
const ws = await ensureHostWorkspace(db, await getSession(db, session.id), project);
await updateSession(db, session.id, { workspacePath: ws.path });
await logSessionEvent(db, session, "host_workspace", { host: host.name, path: ws.path, branch: ws.branch });
} catch (e) {
await updateSession(db, session.id, { status: "failed", endedAt: new Date() });
throw new PeppaError(`Не удалось подготовить рабочую копию на хосте ${host.name}: ${(e as Error).message}`);
}
return launch(db, await getSession(db, session.id), (await getSession(db, session.id)).workspacePath!, opts);
}
let cwd = realpathSync(dir);
if (rs.workspace === "worktree") {
try {
@ -143,13 +173,15 @@ export async function startRunner(
throw new PeppaError(`Не удалось создать git worktree раннера: ${(e as Error).message}`);
}
}
if (provider === "claude") trustWorkspace(cwd);
if (provider === "claude" && !sandboxed) trustWorkspace(cwd);
return launch(db, await getSession(db, session.id), cwd, opts);
}
/** The runner's working copy: its own worktree (recreated if gone, PEP-27) or the project's. */
export async function runnerCwd(db: Db, s: SessionView): Promise<string> {
const [project] = await db.select().from(projects).where(eq(projects.id, s.projectId));
// PEP-40: the clone lives on the host (made again there if it was removed).
if (s.host) return (await ensureHostWorkspace(db, s, project!)).path;
if (!s.workspacePath) return realpathSync(project!.workspacePath);
if (!existsSync(s.workspacePath)) {
const wt = await ensureWorktree(project!, s.id, s.taskKey);
@ -169,13 +201,13 @@ export async function resumeSession(db: Db, sessionId: number, opts: StartOption
}
const s = await getSession(db, sessionId);
await assertBudgetOpen(db, s.taskId);
if (await tmux.hasSession(s.tmuxName)) {
if (!(await tmux.paneState(s.tmuxName)).dead) throw new PeppaError(`Session #${s.id} is still running`);
await tmux.killSession(s.tmuxName);
if (await tmux.hasSession(tmux.sessionPane(s))) {
if (!(await tmux.paneState(tmux.sessionPane(s))).dead) throw new PeppaError(`Session #${s.id} is still running`);
}
await killRunner(s);
await expireSessionQuestions(db, s.id, "(неактуально: сессия перезапущена)");
const cwd = await runnerCwd(db, s);
if (s.provider === "claude") trustWorkspace(cwd);
if (s.provider === "claude" && !s.container) trustWorkspace(cwd);
const prompt = [
s.taskKey
? `Продолжай работу над стори ${s.taskKey}: сессия была прервана. Сверься с peppa.get_task и tasks.md.`
@ -194,9 +226,9 @@ export async function resumeSession(db: Db, sessionId: number, opts: StartOption
*/
export async function relaunchFresh(db: Db, sessionId: number, prompt: string): Promise<SessionView> {
const s = await getSession(db, sessionId);
if (await tmux.hasSession(s.tmuxName)) await tmux.killSession(s.tmuxName);
await killRunner(s);
const cwd = await runnerCwd(db, s);
if (s.provider === "claude") trustWorkspace(cwd);
if (s.provider === "claude" && !s.container) trustWorkspace(cwd);
await updateSession(db, s.id, { conversationId: null, autoNudges: 0 });
return launch(db, await getSession(db, s.id), cwd, { prompt });
}
@ -210,7 +242,9 @@ async function launch(
const generation = s.generation + 1;
const rules = await loadSharedRules();
// PEP-30: the project's memory and recent stories go with the shared rules.
const memory = await memoryContext(db, s.projectId, cwd).catch(() => "");
// On a host (PEP-40) the working copy is not here: the project's own copy stands in.
const memDir = s.host ? (await db.select().from(projects).where(eq(projects.id, s.projectId)))[0]?.workspacePath ?? cwd : cwd;
const memory = await memoryContext(db, s.projectId, memDir).catch(() => "");
// The session's subscription (rotation changes it beforehand, PEP-39); none = this machine's login.
const sub = s.subscriptionId ? await getSubscription(db, s.subscriptionId).catch(() => null) : null;
// PEP-41: model and effort from the agent settings (escalated after failures of the story).
@ -226,6 +260,7 @@ async function launch(
escalated = lm.escalated;
if (esc?.fresh && lm.escalated) await logSessionEvent(db, s, "model_escalated", { to: lm.model, failures: esc.escalation!.failures });
}
const sandbox = !!s.container;
const argv = buildCommand(s.provider, {
sessionId: s.id,
generation,
@ -236,46 +271,81 @@ async function launch(
permissionMode: opts.permissionMode,
model,
effort,
sandbox,
});
// tmux runs a tiny launch script: keeps long argv (rules, prompts) out of the tmux
// command line, and leaves a record of exactly what was started.
const ctx = { sessionId: s.id, generation };
const launchScript = join(runDir(s.id, generation), "launch.sh");
const ctx = { sessionId: s.id, generation, sandbox };
const localRun = runDir(s.id, generation);
const launchScript = join(localRun, "launch.sh");
let env: Record<string, string>;
let script: string;
let tmuxCommand = shq(launchScript);
// PEP-54: project secrets reach the agent as env through a 0600 file the script sources
// and deletes at once — never in the tmux argv (visible in `ps`) or a file left on disk.
// In a container (PEP-17) docker passes them on by name (`-e NAME`).
const secrets = await projectSecretEnv(db, s.projectId);
const secretNames = Object.keys(secrets.env);
let preamble = "";
if (secretNames.length) {
const secretsFile = join(runDir(s.id, generation), "secrets.env");
const secretsFile = join(localRun, "secrets.env");
writeFileSync(secretsFile, secretNames.map((k) => `export ${k}=${shq(secrets.env[k]!)}\n`).join(""), { mode: 0o600 });
preamble = `. ${shq(secretsFile)}; rm -f ${shq(secretsFile)}\n`;
// On a host the launch dir is copied there first: source it from the host's copy.
const at = s.host ? join(await hostRunDir(s.host, s.id, generation), "secrets.env") : secretsFile;
preamble = `. ${shq(at)}; rm -f ${shq(at)}\n`;
}
writeFileSync(launchScript, `#!/bin/bash\n${preamble}exec ${argv.map(shq).join(" ")}\n`);
if (sandbox) {
// PEP-17: the agent in its container; only the run's own environment goes in.
const relay = relayUrl(s.host);
const subEnv = sub ? subscriptionEnv(sub) : {};
env = containerEnv({ sessionId: s.id, generation, relay }, { ...providerEnv(s.provider, ctx), ...subEnv });
const mounts: Mount[] = [];
let home: string;
let hostRun = localRun;
if (s.host) {
hostRun = await hostRunDir(s.host, s.id, generation);
home = await hostAgentHome(s.host, s.id, cwd);
} else {
home = prepareLocalHome(s.id, cwd);
// A worktree's .git file points into the project's .git: mount that too (only this project's).
if (s.workspacePath) {
const [project] = await db.select().from(projects).where(eq(projects.id, s.projectId));
const gitDir = join(realpathSync(project!.workspacePath), ".git");
if (existsSync(gitDir)) mounts.push({ src: gitDir, dst: gitDir });
}
// Codex keeps the subscription's login in its CODEX_HOME (PEP-67).
if (subEnv.CODEX_HOME) mounts.push({ src: subEnv.CODEX_HOME, dst: subEnv.CODEX_HOME });
}
script = dockerRunScript({ sessionId: s.id, generation, target: s.host, cwd, runDir: hostRun, home, mounts, relay, argv, env, passEnv: secretNames, preamble });
if (s.host) tmuxCommand = shq(join(hostRun, "launch.sh"));
} else {
env = {
PEPPA_SESSION_ID: String(s.id),
PEPPA_GENERATION: String(generation),
PEPPA_PROJECT_DIR: cwd,
// Hooks and the MCP server must talk to the same DB / state dir as the runner.
PEPPA_DB: loadEnv().PEPPA_DB,
...(process.env.PEPPA_HOME ? { PEPPA_HOME: process.env.PEPPA_HOME } : {}),
...providerEnv(s.provider, ctx),
// The subscription's login (PEP-67): Claude token, CODEX_HOME or an OpenCode key.
...(sub ? subscriptionEnv(sub) : {}),
...(process.env.PEPPA_HOOK_WAIT_SEC ? { PEPPA_HOOK_WAIT_SEC: process.env.PEPPA_HOOK_WAIT_SEC } : {}),
};
script = `#!/bin/bash\n${preamble}exec ${argv.map(shq).join(" ")}\n`;
}
writeFileSync(launchScript, script);
chmodSync(launchScript, 0o700);
await updateSession(db, s.id, { generation, status: "starting", endedAt: null });
try {
await tmux.newSession({
name: s.tmuxName,
cwd,
command: shq(launchScript),
env: {
PEPPA_SESSION_ID: String(s.id),
PEPPA_GENERATION: String(generation),
PEPPA_PROJECT_DIR: cwd,
// Hooks and the MCP server must talk to the same DB / state dir as the runner.
PEPPA_DB: loadEnv().PEPPA_DB,
...(process.env.PEPPA_HOME ? { PEPPA_HOME: process.env.PEPPA_HOME } : {}),
...providerEnv(s.provider, ctx),
// The subscription's login (PEP-67): Claude token, CODEX_HOME or an OpenCode key.
...(sub ? subscriptionEnv(sub) : {}),
...(process.env.PEPPA_HOOK_WAIT_SEC ? { PEPPA_HOOK_WAIT_SEC: process.env.PEPPA_HOOK_WAIT_SEC } : {}),
},
});
// PEP-40: the launch dir goes to the host (settings, rules, launch.sh; secrets.env 0600, removed by launch.sh).
if (s.host) await pushRunDir(s.host, localRun, await hostRunDir(s.host, s.id, generation));
await tmux.newSession({ name: s.tmuxName, host: s.host, cwd, command: tmuxCommand, env });
// The host has its copy now (sourced and removed by launch.sh); none stays here.
if (s.host) rmSync(join(localRun, "secrets.env"), { force: true });
} catch (e) {
rmSync(join(runDir(s.id, generation), "secrets.env"), { force: true });
await updateSession(db, s.id, { status: "failed", endedAt: new Date() });
throw new PeppaError(`tmux failed to start: ${(e as Error).message}`);
throw new PeppaError(`tmux failed to start${s.host ? ` on ${s.host.name}` : ""}: ${(e as Error).message}`);
}
await updateSession(db, s.id, { status: "running", lastActivityAt: new Date() });
if (secretNames.length || secrets.unreadable.length) {
@ -292,6 +362,8 @@ async function launch(
effort: effort ?? null,
...(escalated ? { escalated: true } : {}),
rulesSource: rules.source,
...(s.container ? { container: s.container } : {}),
...(s.host ? { host: s.host.name } : {}),
});
return getSession(db, s.id);
}
@ -299,17 +371,17 @@ async function launch(
export async function sendToSession(db: Db, sessionId: number, text: string): Promise<void> {
if (isRunnerClient()) return void (await runnerCall(db, "send", { sessionId, text }, { key: `session:${sessionId}` }));
const s = await getSession(db, sessionId);
if (!(await tmux.hasSession(s.tmuxName))) throw new PeppaError(`Session #${s.id} (${s.tmuxName}) is not running`);
if (!(await tmux.hasSession(tmux.sessionPane(s)))) throw new PeppaError(`Session #${s.id} (${s.tmuxName}) is not running`);
// Recorded before typing: the prompt hook answers only questions older than this input.
await logSessionEvent(db, s, "input_sent", { text });
await tmux.sendText(s.tmuxName, text);
await tmux.sendText(tmux.sessionPane(s), text);
await updateSession(db, s.id, { status: "running", lastActivityAt: new Date() });
}
export async function stopSession(db: Db, sessionId: number): Promise<void> {
if (isRunnerClient()) return void (await runnerCall(db, "stop", { sessionId }, { key: `session:${sessionId}` }));
const s = await getSession(db, sessionId);
if (await tmux.hasSession(s.tmuxName)) await tmux.killSession(s.tmuxName);
await killRunner(s);
await expireSessionQuestions(db, s.id, "(неактуально: сессия остановлена)");
await updateSession(db, s.id, { status: "done", endedAt: new Date() });
await finishRunnerTask(db, s.id);
@ -383,14 +455,14 @@ export async function answerAndDeliver(
return { delivered: true, question: q };
}
}
if (!(await tmux.hasSession(s.tmuxName))) return { delivered: false, question: q };
if (!(await tmux.hasSession(tmux.sessionPane(s)))) return { delivered: false, question: q };
if (q.kind === "permission") {
const key = PERMISSION_KEYS[answer.trim().toLowerCase()];
if (key) await tmux.sendKeys(s.tmuxName, key);
else await tmux.sendText(s.tmuxName, answer);
if (key) await tmux.sendKeys(tmux.sessionPane(s), key);
else await tmux.sendText(tmux.sessionPane(s), answer);
} else {
await tmux.sendText(s.tmuxName, message);
await tmux.sendText(tmux.sessionPane(s), message);
}
await updateSession(db, s.id, { status: "running", lastActivityAt: new Date() });
return { delivered: true, question: q };

View File

@ -55,6 +55,8 @@ const cursor = (i: tmux.PaneInfo) => `\x1b[${i.cursorY + 1};${i.cursorX + 1}H\x1
/** Polls one tmux session while it has listeners. */
export class TerminalFeed {
readonly name: string;
/** PEP-40: the pane, maybe on a runner host (polled over SSH). */
readonly pane: tmux.Pane;
readonly intervalMs: number;
private listeners = new Set<TerminalListener>();
/** Listeners that still need a full frame. */
@ -69,8 +71,9 @@ export class TerminalFeed {
/** Number of tmux polls so far (tests check that viewers share one loop). */
polls = 0;
constructor(name: string, opts: { intervalMs?: number; onIdle?: () => void; mask?: (line: string) => string } = {}) {
this.name = name;
constructor(pane: tmux.Pane, opts: { intervalMs?: number; onIdle?: () => void; mask?: (line: string) => string } = {}) {
this.pane = pane;
this.name = typeof pane === "string" ? pane : pane.name;
this.intervalMs = opts.intervalMs ?? TERMINAL_POLL_MS;
this.onIdle = opts.onIdle ?? (() => {});
this.mask = opts.mask ?? ((l) => l);
@ -142,10 +145,10 @@ export class TerminalFeed {
let info: tmux.PaneInfo;
let screen: string[];
try {
info = await tmux.paneInfo(this.name);
screen = fit(this.lines(await tmux.capturePaneAnsi(this.name, 0, info.rows - 1)), info.rows);
info = await tmux.paneInfo(this.pane);
screen = fit(this.lines(await tmux.capturePaneAnsi(this.pane, 0, info.rows - 1)), info.rows);
} catch (e) {
if (await tmux.hasSession(this.name)) throw e;
if (await tmux.hasSession(this.pane)) throw e;
const all = [...this.listeners];
this.listeners.clear();
this.fresh.clear();
@ -163,7 +166,7 @@ export class TerminalFeed {
if (data) this.emit(old, { type: "out", data });
}
if (needFrame.length) {
const hist = info.historySize ? this.lines(await tmux.capturePaneAnsi(this.name, -Math.min(info.historySize, TERMINAL_HISTORY_LINES), -1)) : [];
const hist = info.historySize ? this.lines(await tmux.capturePaneAnsi(this.pane, -Math.min(info.historySize, TERMINAL_HISTORY_LINES), -1)) : [];
const data = [...hist, ...screen].map((l) => `\x1b[0m${l}`).join("\r\n") + "\x1b[0m" + cursor(info);
this.emit(needFrame, { type: "frame", cols: info.cols, rows: info.rows, data });
for (const fn of needFrame) this.fresh.delete(fn);
@ -178,7 +181,7 @@ export class TerminalFeed {
if (k <= 0) return null;
// Not "the top of the previous screen": output between two polls may first fill the screen
// and then scroll, so the lines are taken from tmux's scrollback itself.
return this.lines(await tmux.capturePaneAnsi(this.name, -k, -1));
return this.lines(await tmux.capturePaneAnsi(this.pane, -k, -1));
}
private diff(prev: tmux.PaneInfo, info: tmux.PaneInfo, screen: string[], scrolled: string[] | null): string {
@ -204,10 +207,11 @@ type Registry = Map<string, TerminalFeed>;
const feeds: Registry = ((globalThis as { __peppaTerminalFeeds?: Registry }).__peppaTerminalFeeds ??= new Map());
/** Subscribes to the live pane of a tmux session; one shared poll loop per session. */
export function watchTerminal(name: string, fn: TerminalListener, opts: { mask?: (line: string) => string } = {}): () => void {
export function watchTerminal(pane: tmux.Pane, fn: TerminalListener, opts: { mask?: (line: string) => string } = {}): () => void {
const name = typeof pane === "string" ? pane : pane.name;
let feed = feeds.get(name);
if (!feed) {
const created = new TerminalFeed(name, { onIdle: () => feeds.get(name) === created && feeds.delete(name), mask: opts.mask });
const created = new TerminalFeed(pane, { onIdle: () => feeds.get(name) === created && feeds.delete(name), mask: opts.mask });
feeds.set(name, created);
feed = created;
} else if (opts.mask) feed.setMask(opts.mask);
@ -289,10 +293,10 @@ export async function terminalInput(db: Db, user: User, sessionId: number, input
if (Buffer.byteLength(paste, "utf8") > TERMINAL_MAX_PASTE_BYTES) throw new TerminalError(413, "Слишком длинная вставка");
if (FINISHED_SESSION_STATUSES.includes(s.status)) throw new TerminalError(409, "Сессия завершена");
rateCheck(`${user.id}:${s.id}`, now);
if (!(await tmux.hasSession(s.tmuxName))) throw new TerminalError(409, "Раннер не запущен");
if (!(await tmux.hasSession(tmux.sessionPane(s)))) throw new TerminalError(409, "Раннер не запущен");
if (paste) await tmux.sendText(s.tmuxName, paste, false);
if (keyBytes.length) await tmux.sendHex(s.tmuxName, keyBytes);
if (paste) await tmux.sendText(tmux.sessionPane(s), paste, false);
if (keyBytes.length) await tmux.sendHex(tmux.sessionPane(s), keyBytes);
// A human took over: the Stop hook may nudge the agent again from zero (PEP-7).
if (s.autoNudges > 0) await updateSession(db, s.id, { autoNudges: 0 });
@ -347,7 +351,7 @@ export async function terminalSse(db: Db, user: User, sessionId: number, signal:
// Tells EventSource how long to wait before reconnecting.
send("retry: 3000\n\n");
if (signal.aborted) return close();
unsubscribe = watchTerminal(s.tmuxName, (e) => {
unsubscribe = watchTerminal(tmux.sessionPane(s), (e) => {
send(`event: ${e.type}\ndata: ${JSON.stringify(e.type === "end" ? {} : e)}\n\n`);
if (e.type === "end") close();
}, { mask });

View File

@ -1,26 +1,28 @@
import { execFile, spawn } from "node:child_process";
import { readFileSync } from "node:fs";
import { promisify } from "node:util";
import { HostUnreachable, runOn, type HostTarget } from "./exec.ts";
import { isRunnerClient, runnerCall, runnerClientDb } from "./runner-client.ts";
const run = promisify(execFile);
const TMUX = process.env.PEPPA_TMUX_BIN ?? "tmux";
const TMUX = () => process.env.PEPPA_TMUX_BIN ?? "tmux";
// Separate tmux server (tmux -L) — tests use their own so they never touch real sessions.
const SOCKET = process.env.PEPPA_TMUX_SOCKET ? ["-L", process.env.PEPPA_TMUX_SOCKET] : [];
const SOCKET = () => (process.env.PEPPA_TMUX_SOCKET ? ["-L", process.env.PEPPA_TMUX_SOCKET] : []);
async function tmux(...args: string[]): Promise<string> {
const { stdout } = await run(TMUX, [...SOCKET, ...args]);
/**
* A runner's tmux session: its name, and the host it lives on (PEP-40; none = this machine).
* A bare name means this machine.
*/
export type Pane = string | { name: string; host?: HostTarget | null };
const paneName = (p: Pane) => (typeof p === "string" ? p : p.name);
const paneHost = (p: Pane) => (typeof p === "string" ? null : (p.host ?? null));
/** The pane of a session row (`SessionView`). */
export const sessionPane = (s: { tmuxName: string; host?: HostTarget | null }): Pane => ({ name: s.tmuxName, host: s.host ?? null });
async function tmuxOn(p: Pane, args: string[], input?: string): Promise<string> {
const host = paneHost(p);
// On a host tmux is whatever is on its PATH; PEPPA_TMUX_BIN is this machine's.
const { stdout } = await runOn(host, [host ? "tmux" : TMUX(), ...SOCKET(), ...args], { input });
return stdout;
}
export interface NewTmuxSession {
name: string;
cwd: string;
command: string;
env: Record<string, string>;
width?: number;
}
/**
* PEP-21 safety net: in a client process (web, bot) operations that create, kill or type into
* tmux sessions run in the runner service. Reading the screen stays local.
@ -29,23 +31,36 @@ async function viaService(op: string, args: unknown[]): Promise<void> {
await runnerCall(runnerClientDb(), "tmux", { op, args }, { timeoutMs: 15_000 });
}
export interface NewTmuxSession {
name: string;
/** PEP-40: the host to start it on (none = this machine). */
host?: HostTarget | null;
cwd: string;
command: string;
env: Record<string, string>;
width?: number;
}
export async function newSession(s: NewTmuxSession): Promise<void> {
if (isRunnerClient()) return viaService("newSession", [s]);
const envArgs = Object.entries(s.env).flatMap(([k, v]) => ["-e", `${k}=${v}`]);
const p: Pane = { name: s.name, host: s.host };
// Keep the server up when its last session ends: otherwise a session created while the
// previous last one is being killed can land on a server that is shutting down.
await tmux("start-server", ";", "set-option", "-s", "exit-empty", "off");
await tmux("new-session", "-d", "-s", s.name, "-c", s.cwd, "-x", String(s.width ?? 220), "-y", "50", ...envArgs, s.command);
await tmuxOn(p, ["start-server", ";", "set-option", "-s", "exit-empty", "off"]);
await tmuxOn(p, ["new-session", "-d", "-s", s.name, "-c", s.cwd, "-x", String(s.width ?? 220), "-y", "50", ...envArgs, s.command]);
// Keep the pane after claude exits so the watchdog can read the exit status.
await tmux("set-option", "-t", s.name, "remain-on-exit", "on");
await tmux("set-option", "-t", s.name, "history-limit", "20000");
await tmuxOn(p, ["set-option", "-t", s.name, "remain-on-exit", "on"]);
await tmuxOn(p, ["set-option", "-t", s.name, "history-limit", "20000"]);
}
export async function hasSession(name: string): Promise<boolean> {
/** False only when tmux says there is no such session; an unreachable host throws (state unknown). */
export async function hasSession(p: Pane): Promise<boolean> {
try {
await tmux("has-session", "-t", `=${name}`);
await tmuxOn(p, ["has-session", "-t", `=${paneName(p)}`]);
return true;
} catch {
} catch (e) {
if (e instanceof HostUnreachable) throw e;
return false;
}
}
@ -55,16 +70,17 @@ export interface PaneState {
exitStatus: number | null;
}
export async function paneState(name: string): Promise<PaneState> {
export async function paneState(p: Pane): Promise<PaneState> {
const name = paneName(p);
// tmux marks the pane dead when the pty closes, which can come before it reaps the child:
// then there is neither an exit status nor a signal yet. On Linux tmux sometimes never reaps
// it at all (seen in CI containers) — the zombie still holds its status in /proc.
for (let attempt = 0; ; attempt++) {
const out = (await tmux("display-message", "-p", "-t", `=${name}:`, "#{pane_dead} #{pane_dead_status} #{pane_dead_signal} #{pane_pid}")).trim();
const out = (await tmuxOn(p, ["display-message", "-p", "-t", `=${name}:`, "#{pane_dead} #{pane_dead_status} #{pane_dead_signal} #{pane_pid}"])).trim();
const [dead, status, signal, pid] = out.split(" ");
if (dead !== "1") return { dead: false, exitStatus: null };
if (status || signal) return { dead: true, exitStatus: status ? Number(status) : null };
const zombie = zombieExitStatus(Number(pid));
const zombie = paneHost(p) ? undefined : zombieExitStatus(Number(pid));
if (zombie !== undefined || attempt >= 10) return { dead: true, exitStatus: zombie ?? null };
await new Promise((r) => setTimeout(r, 100));
}
@ -84,42 +100,36 @@ function zombieExitStatus(pid: number): number | null | undefined {
}
/** Visible screen (plus `history` lines of scrollback) as plain text. */
export async function capturePane(name: string, history = 0): Promise<string> {
return tmux("capture-pane", "-p", "-J", "-t", `=${name}:`, "-S", String(-history));
export async function capturePane(p: Pane, history = 0): Promise<string> {
return tmuxOn(p, ["capture-pane", "-p", "-J", "-t", `=${paneName(p)}:`, "-S", String(-history)]);
}
/**
* Types text into the pane and submits it. Uses a bracketed paste so multi-line text
* lands as one prompt instead of being submitted line by line.
*/
export async function sendText(name: string, text: string, submit = true): Promise<void> {
if (isRunnerClient()) return viaService("sendText", [name, text, submit]);
export async function sendText(p: Pane, text: string, submit = true): Promise<void> {
if (isRunnerClient()) return viaService("sendText", [p, text, submit]);
const name = paneName(p);
const buffer = `peppa-${process.pid}-${Date.now()}`;
await new Promise<void>((resolve, reject) => {
const p = spawn(TMUX, [...SOCKET, "load-buffer", "-b", buffer, "-"], { stdio: ["pipe", "ignore", "pipe"] });
let err = "";
p.stderr.on("data", (d) => (err += d));
p.on("error", reject);
p.on("close", (code) => (code === 0 ? resolve() : reject(new Error(`tmux load-buffer failed: ${err}`))));
p.stdin.end(text);
});
await tmux("paste-buffer", "-p", "-d", "-b", buffer, "-t", `=${name}:`);
await tmuxOn(p, ["load-buffer", "-b", buffer, "-"], text);
await tmuxOn(p, ["paste-buffer", "-p", "-d", "-b", buffer, "-t", `=${name}:`]);
if (submit) {
// Give the TUI a moment to finish handling the paste before Enter.
await new Promise((r) => setTimeout(r, 400));
await tmux("send-keys", "-t", `=${name}:`, "Enter");
await tmuxOn(p, ["send-keys", "-t", `=${name}:`, "Enter"]);
}
}
/** Sends tmux key names (e.g. "1", "Enter", "Escape", "C-c"). */
export async function sendKeys(name: string, ...keys: string[]): Promise<void> {
if (isRunnerClient()) return viaService("sendKeys", [name, ...keys]);
await tmux("send-keys", "-t", `=${name}:`, ...keys);
export async function sendKeys(p: Pane, ...keys: string[]): Promise<void> {
if (isRunnerClient()) return viaService("sendKeys", [p, ...keys]);
await tmuxOn(p, ["send-keys", "-t", `=${paneName(p)}:`, ...keys]);
}
export async function killSession(name: string): Promise<void> {
if (isRunnerClient()) return viaService("killSession", [name]);
await tmux("kill-session", "-t", `=${name}`);
export async function killSession(p: Pane): Promise<void> {
if (isRunnerClient()) return viaService("killSession", [p]);
await tmuxOn(p, ["kill-session", "-t", `=${paneName(p)}`]);
}
export interface PaneInfo {
@ -133,8 +143,8 @@ export interface PaneInfo {
}
/** Size, cursor and scrollback length of the session's active pane. */
export async function paneInfo(name: string): Promise<PaneInfo> {
const out = (await tmux("display-message", "-p", "-t", `=${name}:`, "#{pane_width} #{pane_height} #{cursor_x} #{cursor_y} #{cursor_flag} #{history_size}")).trim();
export async function paneInfo(p: Pane): Promise<PaneInfo> {
const out = (await tmuxOn(p, ["display-message", "-p", "-t", `=${paneName(p)}:`, "#{pane_width} #{pane_height} #{cursor_x} #{cursor_y} #{cursor_flag} #{history_size}"])).trim();
const [cols, rows, x, y, flag, hist] = out.split(" ").map(Number);
return { cols: cols!, rows: rows!, cursorX: x!, cursorY: y!, cursorVisible: flag === 1, historySize: hist! };
}
@ -143,13 +153,13 @@ export async function paneInfo(name: string): Promise<PaneInfo> {
* Pane lines with colours (escape sequences), physical rows (no joining of wrapped lines).
* `start`/`end` are tmux line numbers: 0 = top of the screen, negative = scrollback.
*/
export async function capturePaneAnsi(name: string, start: number | "-", end?: number): Promise<string> {
return tmux("capture-pane", "-p", "-e", "-t", `=${name}:`, "-S", String(start), ...(end === undefined ? [] : ["-E", String(end)]));
export async function capturePaneAnsi(p: Pane, start: number | "-", end?: number): Promise<string> {
return tmuxOn(p, ["capture-pane", "-p", "-e", "-t", `=${paneName(p)}:`, "-S", String(start), ...(end === undefined ? [] : ["-E", String(end)])]);
}
/** Sends raw bytes to the pane as keys (`send-keys -H`): arrows, Ctrl-C, UTF-8 — as typed. */
export async function sendHex(name: string, bytes: Uint8Array): Promise<void> {
export async function sendHex(p: Pane, bytes: Uint8Array): Promise<void> {
if (!bytes.length) return;
if (isRunnerClient()) return viaService("sendHex", [name, Array.from(bytes)]);
await tmux("send-keys", "-t", `=${name}:`, "-H", ...Array.from(bytes, (b) => b.toString(16).padStart(2, "0")));
if (isRunnerClient()) return viaService("sendHex", [p, Array.from(bytes)]);
await tmuxOn(p, ["send-keys", "-t", `=${paneName(p)}:`, "-H", ...Array.from(bytes, (b) => b.toString(16).padStart(2, "0"))]);
}

View File

@ -18,7 +18,8 @@ import {
import type { Db } from "@peppa/db";
import * as tmux from "./tmux.ts";
import { recordLimit } from "./limits.ts";
import { resumeSession } from "./sessions.ts";
import { killRunner, resumeSession } from "./sessions.ts";
import { hostTick } from "./hosts.ts";
import { getSubscription, isUsable } from "@peppa/core";
import { planRotation, rotationEnabled, tryRotate, usageWarning } from "./rotation.ts";
import { monitorTick } from "./monitor.ts";
@ -72,6 +73,8 @@ async function tickInner(db: Db, opts: WatchdogOptions): Promise<void> {
await idleStopTick(db, { now, cfg, log }).catch((e) => log(`idle: ${(e as Error).message}`));
// Runner queues and worktrees (PEP-10/27): next story, orphaned queue items, cleanup.
await runnerTick(db, { log }).catch((e) => log(`runners: ${(e as Error).message}`));
// PEP-40: runner hosts — online/offline, load, versions (once a minute each).
await hostTick(db, { now: opts.now, log }).catch((e) => log(`hosts: ${(e as Error).message}`));
// Story budgets (PEP-43): over the limit → pause and ask the PM.
await budgetTick(db, { now: opts.now, log }).catch((e) => log(`budgets: ${(e as Error).message}`));
// Autonomous factory (PEP-23/24/25): auto-merge, auto-close, backlog dispatcher.
@ -107,7 +110,7 @@ async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, cfg:
}
const label = `#${s.id} ${s.taskKey ?? ""} (${s.tmuxName})`;
if (!(await tmux.hasSession(s.tmuxName))) {
if (!(await tmux.hasSession(tmux.sessionPane(s)))) {
log(`${label}: tmux session gone`);
await logSessionEvent(db, s, "tmux_gone");
// PEP-28: a story at work is restarted by itself (within the limit), else the PM is asked.
@ -115,19 +118,19 @@ async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, cfg:
return;
}
const pane = await tmux.paneState(s.tmuxName);
const pane = await tmux.paneState(tmux.sessionPane(s));
if (pane.dead) {
const ok = pane.exitStatus === 0;
log(`${label}: claude exited with ${pane.exitStatus}`);
const tail = screenTail(await tmux.capturePane(s.tmuxName, 200), 15);
const tail = screenTail(await tmux.capturePane(tmux.sessionPane(s), 200), 15);
await logSessionEvent(db, s, "exited", { exitStatus: pane.exitStatus, tail });
await tmux.killSession(s.tmuxName).catch(() => {});
await killRunner(s).catch(() => {});
if (ok) await updateSession(db, s.id, { status: "done", endedAt: new Date() });
else await onRunnerCrash(db, s, "crash", `Claude в ${s.taskKey ?? `сессии ${s.id}`} упал (код ${pane.exitStatus}).\n\n${tail}`, { now: nowDate, cfg, log });
return;
}
const screen = await tmux.capturePane(s.tmuxName);
const screen = await tmux.capturePane(tmux.sessionPane(s));
const hash = createHash("sha1").update(screen).digest("hex");
const now = (opts.now ?? new Date()).getTime();
let last = s.lastActivityAt?.getTime() ?? now;
@ -242,9 +245,9 @@ async function resumeAfterLimit(db: Db, s: SessionView, now: Date, log: (m: stri
};
// The limit message gets closed (Telegram shows it as resolved) — no new ping for the PM.
await expireSessionQuestions(db, s.id, "(лимит сброшен — раннер продолжил сам)");
const alive = (await tmux.hasSession(s.tmuxName)) && !(await tmux.paneState(s.tmuxName)).dead;
const alive = (await tmux.hasSession(tmux.sessionPane(s))) && !(await tmux.paneState(tmux.sessionPane(s))).dead;
if (alive) {
await tmux.sendText(s.tmuxName, `Лимит сброшен. Продолжай работу над ${s.taskKey ?? "стори"} с того места, где остановился (tasks.md).`);
await tmux.sendText(tmux.sessionPane(s), `Лимит сброшен. Продолжай работу над ${s.taskKey ?? "стори"} с того места, где остановился (tasks.md).`);
await updateSession(db, s.id, { ...counters, status: "running", lastActivityAt: now });
} else {
await updateSession(db, s.id, counters);

View File

@ -3,19 +3,80 @@
# Same calls and exit codes as the script uses from real docker; state lives in
# $MOCK_DOCKER_STATE: images (one tag per line), containers/<name> (its image), calls.log.
# MOCK_DOCKER_BUILD_FAIL=1 makes `docker build` fail; MOCK_DOCKER_SCREENSHOT_FAIL=1 — `docker run` (screenshot).
# PEP-17: `docker run … peppa/runner…` (the runner image) runs the command of the "container" right
# here, as real docker would inside it: env only from -e (NAME takes the client's value), PATH of
# the image = infra/runner/bin (+ $MOCK_DOCKER_PATH, then node and the system), -w as cwd; a mount
# whose target differs from its source (/peppa/run, /peppa/home) is mapped back in argv and env.
# Each run is logged to $MOCK_DOCKER_STATE/runs.jsonl (name, image, mounts, env names, argv).
# `docker rm -f <name>` drops containers/<name>; MOCK_DOCKER_RUNNER_FAIL=1 fails a runner run.
set -uo pipefail
# Called through symlinks (a `docker` on PATH): resolve to this file to find the repo.
_src="$0"; while [[ -L "$_src" ]]; do _l="$(readlink "$_src")"; [[ "$_l" == /* ]] && _src="$_l" || _src="$(dirname "$_src")/$_l"; done
ROOT="$(cd "$(dirname "$_src")/../../.." && pwd)"
st="${MOCK_DOCKER_STATE:?MOCK_DOCKER_STATE is required}"
mkdir -p "$st/containers"
touch "$st/images"
echo "docker $*" >> "$st/calls.log"
runner_run() {
local name="" workdir="" user="" image="" ; local -a mounts=() envs=() cmd=()
while [[ $# -gt 0 ]]; do
case "$1" in
--rm|-it|-i|-t|--init|-d) shift ;;
--name) name="$2"; shift 2 ;;
--label|--add-host|--memory|--cpus|--network|--pids-limit) shift 2 ;;
-w) workdir="$2"; shift 2 ;;
-v) mounts+=("$2"); shift 2 ;;
-e) envs+=("$2"); shift 2 ;;
--user) user="$2"; shift 2 ;;
-*) echo "mock-docker: unsupported run flag $1" >&2; return 125 ;;
*) image="$1"; shift; cmd=("$@"); break ;;
esac
done
[[ -n "${MOCK_DOCKER_RUNNER_FAIL:-}" ]] && { echo "docker: Error response from daemon: mock runner failure" >&2; return 125; }
local -a map_src=() map_dst=()
for m in "${mounts[@]+"${mounts[@]}"}"; do
local src="${m%%:*}" rest="${m#*:}"; local dst="${rest%%:*}"
[[ -e "$src" ]] || { echo "docker: Error response from daemon: invalid mount config: bind source path does not exist: $src" >&2; return 125; }
[[ "$src" != "$dst" ]] && { map_src+=("$src"); map_dst+=("$dst"); }
done
remap() { local v="$1" i; for i in "${!map_dst[@]}"; do v="${v//${map_dst[$i]}/${map_src[$i]}}"; done; printf '%s' "$v"; }
local -a envv=() names=()
for e in "${envs[@]+"${envs[@]}"}"; do
if [[ "$e" == *=* ]]; then envv+=("$(remap "$e")"); names+=("${e%%=*}");
elif [[ -n "${!e+x}" ]]; then envv+=("$e=$(remap "${!e}")"); names+=("$e"); fi
done
local -a argv=(); for a in "${cmd[@]+"${cmd[@]}"}"; do argv+=("$(remap "$a")"); done
node -e '
const a = process.argv.slice(1); const f = a.shift(); const take = () => a.splice(0, Number(a.shift()));
const [name, image, user, workdir] = a.splice(0, 4);
const mounts = take(), env = take(), argv = a;
require("fs").appendFileSync(f, JSON.stringify({ name, image, user, workdir, mounts, env, argv }) + "\n");
' "$st/runs.jsonl" "$name" "$image" "$user" "$workdir" "${#mounts[@]}" "${mounts[@]+"${mounts[@]}"}" "${#names[@]}" "${names[@]+"${names[@]}"}" "${cmd[@]+"${cmd[@]}"}"
[[ -n "$name" ]] && echo "$image" > "$st/containers/$name"
# node alone (its own dir may hold Peppa's real bins, e.g. ~/.local/bin): the image has node.
local nodedir="$st/image-node"; mkdir -p "$nodedir"; ln -sf "$(command -v node)" "$nodedir/node"
local path="$ROOT/infra/runner/bin${MOCK_DOCKER_PATH:+:$MOCK_DOCKER_PATH}:$nodedir:/usr/bin:/bin:/usr/sbin:/sbin"
( cd "${workdir:-/}" && exec env -i "PATH=$path" "${envv[@]+"${envv[@]}"}" "${argv[@]}" )
local code=$?
[[ -n "$name" ]] && rm -f "$st/containers/$name"
return $code
}
case "$1" in
inspect) # docker inspect -f '{{.Config.Image}}' <container>
c="${@: -1}"
[[ -f "$st/containers/$c" ]] || { echo "Error: No such object: $c" >&2; exit 1; }
cat "$st/containers/$c" ;;
version) echo "27.3.1-mock" ;;
rm) # docker rm -f <name>
c="${@: -1}"
[[ -f "$st/containers/$c" ]] || { echo "Error response from daemon: No such container: $c" >&2; exit 1; }
rm -f "$st/containers/$c"; echo "$c" ;;
image)
case "$2" in
inspect) grep -qxF "$3" "$st/images" || { echo "Error: No such image: $3" >&2; exit 1; }; echo "[{}]" ;;
inspect) img="${@: -1}"; grep -qxF "$img" "$st/images" || { echo "Error: No such image: $img" >&2; exit 1; }
if [[ "$3" == -f ]]; then echo "sha256:mock0123456789abcdef"; else echo "[{}]"; fi ;;
prune) exit 0 ;;
esac ;;
build) # docker build -t <image> ...
@ -31,7 +92,9 @@ case "$1" in
down) rm -f "$st/containers/$project-"*; echo "Removed $project" ;;
run) echo "ran in $IMAGE: ${*: -1}" ;;
esac ;;
run) # PEP-44: docker run … <chrome image> -c '<chromium --screenshot …; base64>' _ <url> → base64 PNG on stdout
run) # PEP-17: the runner image (see the header) — anything else is the screenshot run below.
for a in "$@"; do [[ "$a" == peppa/runner* || ( -n "${PEPPA_RUNNER_IMAGE:-}" && "$a" == "$PEPPA_RUNNER_IMAGE" ) ]] && { shift; runner_run "$@"; exit $?; }; done
# PEP-44: docker run … <chrome image> -c '<chromium --screenshot …; base64>' _ <url> → base64 PNG on stdout
url="${@: -1}"
echo "$url" >> "$st/screenshots.log"
[[ -n "${MOCK_DOCKER_SCREENSHOT_FAIL:-}" ]] && { echo "mock screenshot failed" >&2; exit 1; }

43
packages/testkit/bin/mock-ssh Executable file
View File

@ -0,0 +1,43 @@
#!/usr/bin/env bash
# mock-ssh — stands in for OpenSSH's client (PEPPA_SSH_BIN) in PEP-40 tests: a runner host is a
# directory, not a machine. Same syntax: `ssh [options] [user@]host command`; the command runs
# through `sh -c` "on the host" = in $MOCK_SSH_ROOT/<host> with its own HOME and TMUX_TMPDIR
# (its own tmux server; the socket dir is short — /tmp/mssh-<hash> — for the 104-byte socket path
# limit), stdin/stdout/exit code passed through like ssh does.
# MOCK_SSH_DOWN=host1,host2 → "Connection refused", exit 255 (as ssh on a dead host)
# <host>/home/.ssh/authorized_keys present → the -i key's .pub must be in it, else
# "Permission denied (publickey)", exit 255 (BatchMode, no password prompt).
# Every call is appended to $MOCK_SSH_ROOT/calls.log.
set -uo pipefail
root="${MOCK_SSH_ROOT:?MOCK_SSH_ROOT is required}"
key="" port=22
while [[ $# -gt 0 ]]; do
case "$1" in
-i) key="$2"; shift 2 ;;
-p) port="$2"; shift 2 ;;
-o|-l|-F|-J|-E|-S) shift 2 ;;
-T|-t|-tt|-q|-n|-v|-A|-N|-4|-6|-C) shift ;;
--) shift; break ;;
-*) echo "mock-ssh: unsupported option $1" >&2; exit 255 ;;
*) break ;;
esac
done
target="${1:?mock-ssh: no destination}"; shift
host="${target#*@}"
mkdir -p "$root"
printf '%s\t%s\t%s\n' "$target" "$port" "$*" >> "$root/calls.log"
if [[ ",${MOCK_SSH_DOWN:-}," == *",$host,"* ]]; then
echo "ssh: connect to host $host port $port: Connection refused" >&2; exit 255
fi
h="$root/$host"
tmuxdir="/tmp/mssh-$(printf '%s' "$h" | cksum | cut -d' ' -f1)"
mkdir -p "$h/home" "$tmuxdir"
chmod 700 "$tmuxdir"
auth="$h/home/.ssh/authorized_keys"
if [[ -f "$auth" ]]; then
if [[ -z "$key" || ! -f "$key.pub" ]] || ! grep -qF "$(cut -d' ' -f1,2 "$key.pub")" "$auth"; then
echo "$target: Permission denied (publickey)." >&2; exit 255
fi
fi
[[ $# -eq 0 ]] && { echo "mock-ssh: interactive sessions are not supported" >&2; exit 255; }
cd "$h/home" && HOME="$h/home" TMUX_TMPDIR="$tmuxdir" exec sh -c "$*"

View File

@ -38,7 +38,7 @@ describe("Настройки раннеров", () => {
await core.setSystemRunnerSettings(db, { workspace: "worktree" });
await core.setProjectRunnerSettings(db, pid, { mode: "queue", maxRunners: 2 });
await core.setTaskRunnerSettings(db, t.id, { mode: "story" });
assert.deepEqual(await core.resolveRunnerSettings(db, pid, t.id), { mode: "story", context: "fresh", workspace: "worktree", maxRunners: 2 });
assert.deepEqual(await core.resolveRunnerSettings(db, pid, t.id), { mode: "story", context: "fresh", workspace: "worktree", maxRunners: 2, isolation: "none", hosts: [] });
await assert.rejects(core.setTaskRunnerSettings(db, t.id, { workspace: "shared" } as never), /Неизвестная настройка/);
await core.setSystemRunnerSettings(db, {});
await core.setTaskRunnerSettings(db, t.id, {});

View File

@ -0,0 +1,370 @@
// PEP-17: the agent of a runner in its own container (mock-docker), hooks/MCP/git only through
// the agent relay. PEP-40: runner hosts over SSH (mock-ssh) — clone, tmux, terminal, outages.
import assert from "node:assert/strict";
import { execFile, execFileSync, spawn } from "node:child_process";
import { promisify } from "node:util";
import { existsSync, mkdirSync, readFileSync, symlinkSync, writeFileSync } from "node:fs";
import { createServer, type Server } from "node:http";
import type { AddressInfo } from "node:net";
import { join } from "node:path";
import { after, before, describe, test } from "node:test";
import { events } from "@peppa/db";
import { core, db, project, runner, setDefaultOwner, teardown, tick, waitFor, type TestProject } from "./helpers.ts";
import { agentRelayMcp } from "@peppa/mcp/relay";
const ROOT = join(import.meta.dirname, "../../..");
const TMP = join(process.env.PEPPA_HOME!, "..", "pep17");
const BIN = join(TMP, "bin");
const IMAGE_BIN = join(TMP, "image-bin");
const GIT_ROOT = join(TMP, "git");
const SSH_ROOT = join(TMP, "hosts");
const STATE = join(TMP, "docker");
const BOT_TOKEN = "mock-gitea-bot-token";
let relay: Server;
let gitServer: Server;
let relayUrl = "";
const gitAuth: string[] = [];
let pm: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
/** Smart-HTTP git server (git http-backend) standing in for Gitea; records the auth it got. */
function serveGit(): Promise<Server> {
const server = createServer((req, res) => {
gitAuth.push(String(req.headers.authorization ?? ""));
const url = new URL(req.url!, "http://x");
const cgi = spawn("git", ["http-backend"], {
env: {
...process.env,
GIT_PROJECT_ROOT: GIT_ROOT,
GIT_HTTP_EXPORT_ALL: "1",
REQUEST_METHOD: req.method!,
PATH_INFO: decodeURIComponent(url.pathname),
QUERY_STRING: url.search.slice(1),
CONTENT_TYPE: String(req.headers["content-type"] ?? ""),
HTTP_CONTENT_ENCODING: String(req.headers["content-encoding"] ?? ""),
GIT_PROTOCOL: String(req.headers["git-protocol"] ?? ""),
REMOTE_USER: "peppa-bot",
},
});
req.pipe(cgi.stdin);
let buf = Buffer.alloc(0);
let headersDone = false;
cgi.stdout.on("data", (d: Buffer) => {
if (headersDone) return void res.write(d);
buf = Buffer.concat([buf, d]);
const i = buf.indexOf("\r\n\r\n");
if (i < 0) return;
headersDone = true;
let status = 200;
for (const line of buf.subarray(0, i).toString().split("\r\n")) {
const [k, ...v] = line.split(":");
if (k!.toLowerCase() === "status") status = Number(v.join(":").trim().split(" ")[0]);
else res.setHeader(k!, v.join(":").trim());
}
res.statusCode = status;
res.write(buf.subarray(i + 4));
});
cgi.on("close", () => res.end());
});
return new Promise((r) => server.listen(0, "127.0.0.1", () => r(server)));
}
/** A bare repo test/<slug>.git with the project's Peppa files committed (the clone on a host needs them). */
function bareRepo(p: TestProject, slug: string) {
const work = join(TMP, "seed", slug);
mkdirSync(join(work, ".peppa"), { recursive: true });
for (const f of [".peppa/project.json", ".peppa/mock-scenario.json"]) writeFileSync(join(work, f), readFileSync(join(p.dir, f)));
writeFileSync(join(work, "README.md"), `# ${slug}\n`);
const g = (...a: string[]) => execFileSync("git", a, { cwd: work, stdio: "ignore" });
g("init", "-q", "-b", "main");
g("add", ".");
g("-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "-m", "init");
mkdirSync(join(GIT_ROOT, "test"), { recursive: true });
execFileSync("git", ["clone", "-q", "--bare", work, join(GIT_ROOT, "test", `${slug}.git`)]);
execFileSync("git", ["config", "http.receivepack", "true"], { cwd: join(GIT_ROOT, "test", `${slug}.git`) });
}
/** The agent in the container calls peppa-mcp from its PATH (the image's shim), like the template's .mcp.json. */
function containerMcp(p: TestProject) {
writeFileSync(join(p.dir, ".mcp.json"), JSON.stringify({ mcpServers: { peppa: { command: "peppa-mcp" } } }));
}
type Run = { name: string; image: string; mounts: string[]; env: string[]; argv: string[]; workdir: string };
const runs = (): Run[] => (existsSync(join(STATE, "runs.jsonl")) ? readFileSync(join(STATE, "runs.jsonl"), "utf8").trim().split("\n").map((l) => JSON.parse(l) as Run) : []);
const dockerCalls = () => (existsSync(join(STATE, "calls.log")) ? readFileSync(join(STATE, "calls.log"), "utf8") : "");
const evs = async (sid: number, type: string) => (await db.select().from(events)).filter((e) => e.sessionId === sid && e.type === type);
let seq = 0;
async function subscribed(p: TestProject) {
const sub = await runner.addSubscription(db, { provider: "claude", name: `Claude ${++seq}`, method: "token", secret: `sk-ant-oat01-mock${"x".repeat(24)}${seq}`, createdBy: pm.id });
const pool = await core.createPool(db, { name: `Пул ${seq}`, subscriptionIds: [sub.id] });
await core.setProjectPool(db, (await core.getProject(db, p.key)).id, pool.id);
return sub;
}
before(async () => {
process.env.PEPPA_SECRET = "mock-secret-for-tests";
pm = await core.upsertUserFromGitea(db, { id: 17, login: "mock-pm-17" }, { access_token: "x" });
setDefaultOwner(pm.id);
for (const d of [BIN, IMAGE_BIN, GIT_ROOT, SSH_ROOT, STATE]) mkdirSync(d, { recursive: true });
// The host's `docker` and the image's `claude` are mocks; Peppa's own docker — PEPPA_DOCKER_BIN.
symlinkSync(join(ROOT, "packages/testkit/bin/mock-docker"), join(BIN, "docker"));
symlinkSync(join(ROOT, "packages/testkit/bin/mock-claude"), join(IMAGE_BIN, "claude"));
gitServer = await serveGit();
relay = await runner.serveAgentRelay(db, 0, { mcp: agentRelayMcp });
relayUrl = `http://127.0.0.1:${(relay.address() as AddressInfo).port}`;
Object.assign(process.env, {
PATH: `${BIN}:${process.env.PATH}`,
PEPPA_DOCKER_BIN: join(ROOT, "packages/testkit/bin/mock-docker"),
PEPPA_SSH_BIN: join(ROOT, "packages/testkit/bin/mock-ssh"),
MOCK_DOCKER_STATE: STATE,
MOCK_DOCKER_PATH: IMAGE_BIN,
MOCK_SSH_ROOT: SSH_ROOT,
PEPPA_AGENT_URL: relayUrl,
PEPPA_RELAY_WAIT_MS: "500",
GITEA_URL: `http://127.0.0.1:${(gitServer.address() as AddressInfo).port}`,
GITEA_TOKEN: BOT_TOKEN,
});
});
after(async () => {
for (const h of ["build1", "build2"]) {
try {
execFileSync(process.env.PEPPA_SSH_BIN!, [h, `tmux -L ${process.env.PEPPA_TMUX_SOCKET} kill-server; rm -rf "$TMUX_TMPDIR"`], { stdio: "ignore" });
} catch {}
}
relay?.close();
gitServer?.close();
await teardown();
});
describe("PEP-17: агент в контейнере", () => {
test("Без настройки — как раньше: tmux без docker", async () => {
const p = await project({ turns: [[{ say: "ok" }]] });
const before = runs().length;
const sid = await p.start();
await p.waitQuestion(sid, "attention");
const s = await core.getSession(db, sid);
assert.equal(s.container, null);
assert.equal(s.host, null);
assert.equal(runs().length, before);
await runner.stopSession(db, sid);
});
test("Запуск в контейнере: только своя копия, свой токен; хуки, MCP и транскрипт — через релей", async () => {
const p = await project({
turns: [[
{ usage: { input: 1200, output: 300, costUsd: 0.42 } },
{ mcp: "report_progress", args: { task: "$TASK", text: "из контейнера" } },
{ permission: { tool: "Bash", input: { command: "rm -rf build" } } },
{ say: "Готово." },
]],
});
containerMcp(p);
await subscribed(p);
await core.setProjectRunnerSettings(db, (await core.getProject(db, p.key)).id, { isolation: "container" });
// PEP-54: the project's own secret goes in by name; its value never lands in launch.sh.
await core.setProjectSecret(db, pm.id, (await core.getProject(db, p.key)).id, "STRIPE_KEY", "mock-stripe-secret-value");
const sid = await p.start();
const s = await core.getSession(db, sid);
assert.equal(s.container, `peppa-s${sid}`);
// The run: the workspace, the launch dir read-only, the agent's own home — nothing else.
const run = await waitFor("docker run", async () => runs().find((r) => r.name === `peppa-s${sid}`));
const ws = execFileSync("realpath", [p.dir]).toString().trim();
assert.deepEqual(run.mounts, [
`${ws}:${ws}`,
`${join(process.env.PEPPA_HOME!, "runs", `s${sid}-g1`)}:/peppa/run:ro`,
`${join(process.env.PEPPA_HOME!, "sandboxes", `s${sid}`, "home")}:/peppa/home`,
]);
assert.equal(run.workdir, ws);
assert.ok(run.env.includes("CLAUDE_CODE_OAUTH_TOKEN") && run.env.includes("PEPPA_AGENT_TOKEN") && run.env.includes("STRIPE_KEY"));
for (const secret of ["PEPPA_DB", "PEPPA_HOME", "GITEA_TOKEN", "PEPPA_SECRET"]) assert.ok(!run.env.includes(secret), `${secret} must not enter the container`);
assert.equal(run.argv[0], "claude");
assert.ok(run.argv.includes("/peppa/run/settings.json"));
const settings = JSON.parse(readFileSync(join(process.env.PEPPA_HOME!, "runs", `s${sid}-g1`, "settings.json"), "utf8"));
assert.equal(settings.hooks.Stop[0].hooks[0].command, "peppa-hook stop");
const launch = readFileSync(join(process.env.PEPPA_HOME!, "runs", `s${sid}-g1`, "launch.sh"), "utf8");
assert.ok(!launch.includes("sk-ant-oat01") && !launch.includes("mock-stripe-secret-value"), "secrets stay out of launch.sh");
assert.ok(!existsSync(join(process.env.PEPPA_HOME!, "runs", `s${sid}-g1`, "secrets.env")), "the secrets file is sourced and removed");
// MCP through the relay; the permission hook blocks (wait + rid) until the PM answers.
await p.waitLog("mcp via relay", (e) => e.ev === "mcp" && e.tool === "report_progress" && e.isError === false);
const q = await p.waitQuestion(sid, "permission");
await new Promise((r) => setTimeout(r, 1200)); // longer than one relay wait
await runner.answerAndDeliver(db, q.id, "allow", "web");
await p.waitLog("permission allowed by hook", (e) => e.ev === "permission" && e.via === "hook" && e.behavior === "allow");
await p.waitQuestion(sid, "attention");
// Stop hook through the relay with the transcript: tokens counted as for a local agent.
assert.equal(core.usageTotals((await core.getSession(db, sid)).usage).total, 1500);
assert.ok((await evs(sid, "turn_end")).length >= 1);
await runner.stopSession(db, sid);
assert.match(dockerCalls(), new RegExp(`docker rm -f peppa-s${sid}`));
assert.ok(!existsSync(join(STATE, "containers", `peppa-s${sid}`)));
});
test("Нет подписки — контейнер не запускается", async () => {
const p = await project({ turns: [[{ say: "ok" }]] });
await core.setProjectRunnerSettings(db, (await core.getProject(db, p.key)).id, { isolation: "container" });
await assert.rejects(p.start(), /нужна подписка/);
});
});
describe("PEP-17: релей агента", () => {
const post = (path: string, token: string, body: unknown) =>
fetch(`${relayUrl}/api/agent${path}`, { method: "POST", headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json", Accept: "application/json, text/event-stream" }, body: JSON.stringify(body) });
test("Чужой или старый токен — 401; чужой проект через MCP — отказ; git только к своему репозиторию", async () => {
const a = await project({ turns: [[{ sleep: 60_000 }]] });
const b = await project({ turns: [[{ say: "ok" }]] });
const sid = await a.start();
const s = await core.getSession(db, sid);
const token = core.agentRelayToken(sid, s.generation);
assert.equal((await post("/hook", core.agentRelayToken(sid, s.generation - 1), { event: "stop", stdin: "{}" })).status, 401);
assert.equal((await post("/hook", `${token.slice(0, -2)}xx`, { event: "stop", stdin: "{}" })).status, 401);
assert.equal((await post("/hook", "nonsense", { event: "stop", stdin: "{}" })).status, 401);
const call = async (name: string, args: Record<string, unknown>) => {
const r = await post("/mcp", token, { jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } });
return (await r.json()) as { result: { isError?: boolean; content: Array<{ text: string }> } };
};
const own = await call("get_task", { task: a.taskKey });
assert.ok(!own.result.isError && own.result.content[0]!.text.includes(a.taskKey));
const other = await call("get_task", { task: b.taskKey });
assert.equal(other.result.isError, true);
assert.match(other.result.content[0]!.text, /Access denied/);
assert.equal((await call("list_tasks", { project: b.key })).result.isError, true);
const git = (path: string) => fetch(`${relayUrl}/api/agent/git/${path}`, { headers: { Authorization: `Bearer ${token}` } });
const before = gitAuth.length;
assert.equal((await git(`test/${b.key.toLowerCase()}.git/info/refs?service=git-upload-pack`)).status, 403);
assert.equal((await git(`test/${a.key.toLowerCase()}/../${b.key.toLowerCase()}.git/info/refs`)).status, 403);
assert.equal((await git(`api/v1/repos/test/${b.key.toLowerCase()}/pulls`)).status, 403);
assert.equal(gitAuth.length, before, "refused requests never reach Gitea");
assert.equal(runner.allowedGitPath({ giteaOwner: "test", giteaRepo: "pay" }, "api/v1/repos/test/pay/pulls"), true);
await runner.stopSession(db, sid);
// A finished session's token no longer runs hooks.
assert.equal((await post("/hook", token, { event: "stop", stdin: "{}" })).status, 401);
});
});
describe("PEP-40: хосты раннеров", () => {
let hostId = 0;
test("Подключить хост: ключ Пеппы, проверка — онлайн, версии", async () => {
const pub = await runner.ensureSshKey();
assert.match(pub, /^ssh-ed25519 /);
const h = await core.createHost(db, { name: "build1", sshTarget: "peppa@build1", peppaUrl: relayUrl });
hostId = h.id;
await assert.rejects(core.createHost(db, { name: "bad", sshTarget: "-oProxyCommand=x" }), /SSH-адрес/);
// Not authorized yet: the host refuses the key.
mkdirSync(join(SSH_ROOT, "build1", "home", ".ssh"), { recursive: true });
writeFileSync(join(SSH_ROOT, "build1", "home", ".ssh", "authorized_keys"), "ssh-ed25519 AAAAother other\n");
assert.equal((await runner.checkHost(db, h)).status, "offline");
writeFileSync(join(SSH_ROOT, "build1", "home", ".ssh", "authorized_keys"), `${pub}\n`);
writeFileSync(join(STATE, "images"), "peppa/runner:latest\n");
const ok = await runner.checkHost(db, h);
assert.equal(ok.status, "online");
assert.equal(ok.info?.docker, "27.3.1-mock");
assert.match(ok.info?.tmux ?? "", /^tmux /);
assert.ok(ok.info?.image);
});
test("Раннер на хосте: клон через релей, tmux и агент там, терминал в вебе через SSH", async () => {
const p = await project({ turns: [[{ mcp: "report_progress", args: { task: "$TASK", text: "с хоста" } }, { say: "Сделал на хосте." }]] });
const slug = p.key.toLowerCase();
containerMcp(p);
bareRepo(p, slug);
await subscribed(p);
await core.setProjectRunnerSettings(db, (await core.getProject(db, p.key)).id, { hosts: [hostId] });
const sid = await p.start();
const s = await core.getSession(db, sid);
assert.equal(s.host?.name, "build1");
assert.equal(s.container, `peppa-s${sid}`);
const remoteWs = join(SSH_ROOT, "build1", "home", "peppa", "ws", slug, `s${sid}`);
assert.equal(execFileSync("realpath", [s.workspacePath!]).toString().trim(), execFileSync("realpath", [remoteWs]).toString().trim());
// Cloned through the relay's git proxy with the bot token, on the story's branch.
assert.ok(gitAuth.some((a) => a === `token ${BOT_TOKEN}`));
assert.equal(execFileSync("git", ["branch", "--show-current"], { cwd: remoteWs }).toString().trim(), `task/${p.taskKey.toLowerCase()}`);
assert.ok(existsSync(join(remoteWs, ".mcp.json")), "untracked Peppa files copied to the host");
// tmux lives on the host, not here.
assert.equal(await runner.tmux.hasSession(s.tmuxName), false);
assert.equal(await runner.tmux.hasSession(runner.tmux.sessionPane(s)), true);
const log = join(remoteWs, ".peppa", "mock-log.jsonl");
await waitFor("mcp from the host", async () => existsSync(log) && readFileSync(log, "utf8").includes('"tool":"report_progress","args":{"task":"'));
assert.match(readFileSync(log, "utf8"), /"tool":"report_progress".*"isError":false/);
await p.waitQuestion(sid, "attention");
// PEP-9 over SSH: the frame comes from the host's pane.
const frame = await new Promise<string>((resolve, reject) => {
const t = setTimeout(() => reject(new Error("no terminal frame")), 10_000);
const off = runner.watchTerminal(runner.tmux.sessionPane(s), (e) => {
if (e.type === "frame") {
clearTimeout(t);
off();
resolve(JSON.stringify(e));
}
});
});
assert.match(frame, /Сделал на хосте/);
await runner.terminalInput(db, pm, sid, { paste: "привет с веба" });
// Git push from the host goes through the proxy too.
execFileSync("sh", ["-c", `cd ${remoteWs} && echo x > f.txt && git add f.txt && git -c user.name=a -c user.email=a@a commit -qm x`]);
const token = core.agentRelayToken(sid, (await core.getSession(db, sid)).generation);
const env = runner.gitRelayEnv(relayUrl, token);
// Async: the relay and the git server live in this process.
await promisify(execFile)("git", ["push", "-q", "origin", "HEAD"], { cwd: remoteWs, env: { ...process.env, ...env, GIT_TERMINAL_PROMPT: "0" } });
assert.ok(execFileSync("git", ["branch", "--list"], { cwd: join(GIT_ROOT, "test", `${slug}.git`) }).toString().includes(`task/${p.taskKey.toLowerCase()}`));
await runner.stopSession(db, sid);
assert.equal(await runner.tmux.hasSession(runner.tmux.sessionPane(await core.getSession(db, sid))), false);
});
test("Хост недоступен: офлайн, раннер не объявляется пропавшим; новый раннер — «нет доступного хоста»", async () => {
const p = await project({ turns: [[{ sleep: 60_000 }]] });
containerMcp(p);
bareRepo(p, p.key.toLowerCase());
await subscribed(p);
const pid = (await core.getProject(db, p.key)).id;
await core.setProjectRunnerSettings(db, pid, { hosts: [hostId] });
const sid = await p.start();
process.env.MOCK_SSH_DOWN = "build1";
try {
await tick();
assert.notEqual((await core.getSession(db, sid)).status, "failed");
assert.equal((await evs(sid, "tmux_gone")).length, 0);
await runner.hostTick(db, { force: true });
assert.equal((await core.getHost(db, hostId)).status, "offline");
const t2 = await core.createTask(db, { projectId: pid, title: "вторая", description: "x" });
await assert.rejects(runner.startSession(db, t2.key), /Нет доступного хоста/);
} finally {
delete process.env.MOCK_SSH_DOWN;
}
await runner.hostTick(db, { force: true });
assert.equal((await core.getHost(db, hostId)).status, "online");
await runner.stopSession(db, sid);
});
test("Выбор хоста: наименее занятый онлайн", async () => {
const h2 = await core.createHost(db, { name: "build2", sshTarget: "peppa@build2", peppaUrl: relayUrl });
assert.equal((await runner.checkHost(db, h2)).status, "online");
const p = await project({ turns: [[{ sleep: 60_000 }]] });
containerMcp(p);
bareRepo(p, p.key.toLowerCase());
await subscribed(p);
const pid = (await core.getProject(db, p.key)).id;
await core.setProjectRunnerSettings(db, pid, { hosts: [hostId, h2.id] });
const s1 = await p.start();
const t2 = await core.createTask(db, { projectId: pid, title: "вторая", description: "x" });
const s2 = (await runner.startSession(db, t2.key)).id;
const names = [(await core.getSession(db, s1)).host?.name, (await core.getSession(db, s2)).host?.name].sort();
assert.deepEqual(names, ["build1", "build2"]);
assert.equal((await core.listHosts(db)).find((h) => h.name === "build2")?.runners, 1);
await runner.stopSession(db, s1);
await runner.stopSession(db, s2);
});
});

17
scripts/runner-image.sh Executable file
View File

@ -0,0 +1,17 @@
#!/usr/bin/env bash
# PEP-17/40: builds the runner image (infra/runner) and, with --push <host…>, loads it on runner
# hosts over SSH (docker save | ssh host docker load) with Peppa's key.
# Versions of the agents: CLAUDE_CODE_VERSION / CODEX_VERSION / OPENCODE_VERSION (default latest).
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
IMAGE="${PEPPA_RUNNER_IMAGE:-peppa/runner:latest}"
docker build -t "$IMAGE" \
--build-arg CLAUDE_CODE_VERSION="${CLAUDE_CODE_VERSION:-latest}" \
--build-arg CODEX_VERSION="${CODEX_VERSION:-latest}" \
--build-arg OPENCODE_VERSION="${OPENCODE_VERSION:-latest}" \
"$ROOT/infra/runner"
echo "built $IMAGE"
if [[ "${1:-}" == "--push" ]]; then
shift
for h in "$@"; do "$ROOT/packages/cli/bin/peppa" host push-image "$h"; done
fi

View File

@ -136,6 +136,15 @@ PM отвечает только на **архитектурные стоппе
из env. Нужного секрета нет — `ask_pm`, чтобы PM завёл его в «⋯ Настройки проекта →
Секреты» (появится при следующем запуске сессии).
## Песочница раннера
Проект может запускать агентов в контейнере (на машине Пеппы или на отдельном хосте). Тогда
ты видишь только свою рабочую копию; токенов Gitea и файлов Пеппы в окружении нет.
- `git fetch/push` работают как обычно (через прокси Пеппы, только к репозиторию проекта).
- PR открывай MCP-инструментом `peppa.open_pull_request` (ссылку — в `update_task` как `pr_url`).
- Не ищи токены и не пытайся выйти за рабочую копию — это граница безопасности, а не ошибка.
## Спецификации — сценарии в формате Gherkin
Требования в `specs/**/spec.md` пиши как раньше (`### Requirement:` + текст с SHALL), а