diff --git a/AGENTS.md b/AGENTS.md index 893058e8..1ddee46e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -21,6 +21,7 @@ - **Раннеры (PEP-10/27/53)**: настройки `core/runners.ts` с наследованием `platform.runner` → `project.runner:` → `task.runner:` (строки `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//s`, `sessions.workspace_path`, ветка `task/`, уборка когда чисто и всё запушено). Свободный раннер — `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:`/`session:` — одна стори по очереди. Нет сокета → сразу ошибка «Раннер-сервис не запущен», не взял за 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` образа `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` в вачдоге раз в минуту, клон `/ws//s` одноразовым контейнером через релей, каталог запуска 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/`, свой tmux, `MOCK_SSH_DOWN`) - хуки не в репо проекта, а в генерируемом `~/.peppa/runs/s-g/settings.json` (`claude --settings`) - `PEPPA_SESSION_ID` + `PEPPA_GENERATION`: хук из старого поколения (до resume) игнорируется - PermissionRequest и AskUserQuestion блокируют и ждут ответ PM из БД (`PEPPA_HOOK_WAIT_SEC`, 540с), потом откат на диалог в терминале; `questions.awaiting_hook` не даёт ответу уйти ещё и в tmux diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts index e571ab09..250e91f2 100644 --- a/apps/web/app/(app)/actions.ts +++ b/apps/web/app/(app)/actions.ts @@ -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) } : {}), }); }); } diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx index 833c0ec6..7c7e4331 100644 --- a/apps/web/app/(app)/help/page.tsx +++ b/apps/web/app/(app)/help/page.tsx @@ -74,6 +74,7 @@ export default async function Help() {
  • Раннер — агент, запущенный по стори в tmux на машине Пеппы. Все раннеры твоих и общих проектов — в разделе Раннеры: статус, стори, команда tmux attach, сообщение, остановка и resume; фильтры-счётчики «ждут тебя / работают / упали / готово» и поиск; строки, где нужен ты, подсвечены, у раннера на лимите — «остановлена · продолжит в HH:MM». Выбери раннер — справа его детали, вопросы, действия и живой терминал: экран агента в реальном времени с историей (прокрутка), размер шрифта A−/A+ и режим во весь экран. Кнопка «Ввод» позволяет печатать агенту прямо в терминал (вставка многострочного текста уходит одной вставкой, для телефона есть Esc, Tab, стрелки, Enter, Ctrl-C); ввод сбрасывает счётчик автопродолжений и отмечается в событиях раннера. Тот же терминал — на странице стори у работающего раннера. Терминал доступен владельцу и участникам проекта.
  • Новый терминал — раннер без стори: в «Раннерах» или на вкладке «Сессии» проекта выбери проект, имя, агента и напиши промпт (можно голосом — кнопка «Голосом» в браузерах с распознаванием речи). После ходов такой раннер не пингует — им управляешь ты в терминале. Получилась работа — «Оформить стори» в карточке раннера: стори создаётся в работе, раннер ведёт её дальше. Раннер можно переименовать.
  • Раннеры и стори — «⋯ Настройки проекта → Раннеры» (и на странице стори — для неё одной): «один раннер на стори» (по умолчанию) или «раннер ведёт очередь стори» — стори достаётся свободному раннеру, при лимите раннеров проекта ждёт в его очереди, а «Принять» не останавливает раннер, а даёт ему следующую стори; переход — «свежий контекст» (тот же терминал, новый разговор) или «один разговор». «Свой git worktree на раннер» — у каждого раннера своя копия и ветка task/…, параллельные стори не мешают друг другу; копия убирается, когда всё запушено. В карточке раннера — история его стори и очередь.
  • +
  • Изоляция и хосты — там же: «Контейнер на раннер» запускает агента в docker-образе раннера — он видит только свою рабочую копию, работает на подписке из пула проекта и не видит токенов Пеппы и чужих проектов; хуки, MCP и git идут в Пеппу через релей и только к репозиторию проекта (PR агент открывает инструментом open_pull_request). «Где запускать раннеры» — Mac Пеппы или отмеченные хосты: раннер уходит на наименее занятый онлайн-хост, там клонируется рабочая копия, а терминал, ввод и ответы работают как обычно. Хосты подключает суперадмин в разделе «Хосты» (SSH-ключ Пеппы на хосте, tmux и docker); недоступный хост помечается «офлайн», его раннеры не считаются упавшими.
  • Главная — вопросы агентов (только архитектурные стопперы) и «готово к ревью», активные раннеры и проекты. Отвечать можно в вебе, Telegram или через MCP. Список проектов и «Новый проект» — в разделе Проекты.
  • diff --git a/apps/web/app/(app)/hosts/actions.ts b/apps/web/app/(app)/hosts/actions.ts new file mode 100644 index 00000000..ee0011f6 --- /dev/null +++ b/apps/web/app/(app)/hosts/actions.ts @@ -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): Promise { + 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"))); + }); +} diff --git a/apps/web/app/(app)/hosts/page.tsx b/apps/web/app/(app)/hosts/page.tsx new file mode 100644 index 00000000..bf81723d --- /dev/null +++ b/apps/web/app/(app)/hosts/page.tsx @@ -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 отключён; + return {HOST_STATUS_RU[h.status]}; +} + +function HostFields({ h }: { h?: RunnerHostView }) { + return ( +
    + + + + +
    + ); +} + +function HostCard({ h }: { h: RunnerHostView }) { + const i = h.info ?? {}; + return ( + +
    + {h.name} + {h.sshTarget}{h.sshPort !== 22 ? `:${h.sshPort}` : ""} + + раннеров: {h.runners} +
    +
    + {i.load != null && загрузка {i.load}{i.cpus ? ` / ${i.cpus} CPU` : ""}} + {i.docker && docker {i.docker}} + {i.tmux && {i.tmux}} + {i.os && {i.os}} + образ раннера: {i.image ? {i.image} : "не загружен"} + проверен {ago(h.lastSeenAt)} +
    + {h.lastError &&

    {h.lastError}

    } +
    +
    + + + +
    + + + +
    + + + +
    + +
    + + + + +
    +
    + ); +} + +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 ( + +
    + + Хосты}> + Серверы, на которых работают раннеры. Пеппа заходит на хост по SSH своим ключом и запускает там tmux с агентом в контейнере образа раннера; агент ходит в Пеппу только через релей. Демона на хосте нет — нужны sshd, tmux и docker. Проект выбирает хосты в «⋯ Настройки проекта → Раннеры». Раздел видят только суперадмины. + + +
    + {hosts.length === 0 ? Хостов нет — раннеры работают на Mac Пеппы. : hosts.map((h) => )} + Подключить хост}> +
    + + + + +
    +
    + +
    +
      +
    1. + Добавьте ключ Пеппы в ~/.ssh/authorized_keys пользователя на хосте: +
      {pub}
      +
    2. +
    3. Установите tmux и docker; пользователь должен иметь доступ к docker.
    4. +
    5. + Загрузите образ раннера {runnerImage()}: scripts/runner-image.sh --push <имя хоста> (или peppa host push-image <имя>). +
    6. +
    7. Адрес Пеппы для хоста должен открываться с хоста (по умолчанию — адрес веба); через него идут хуки, MCP и git агента.
    8. +
    +
    +
    +
    + ); +} diff --git a/apps/web/app/(app)/p/[key]/page.tsx b/apps/web/app/(app)/p/[key]/page.tsx index 37611a6d..12d11fea 100644 --- a/apps/web/app/(app)/p/[key]/page.tsx +++ b/apps/web/app/(app)/p/[key]/page.tsx @@ -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 - + diff --git a/apps/web/app/(app)/settings/page.tsx b/apps/web/app/(app)/settings/page.tsx index 2105adc6..54e35797 100644 --- a/apps/web/app/(app)/settings/page.tsx +++ b/apps/web/app/(app)/settings/page.tsx @@ -89,6 +89,9 @@ export default async function Settings({ searchParams }: { searchParams: Promise + diff --git a/apps/web/app/api/agent/[...path]/route.ts b/apps/web/app/api/agent/[...path]/route.ts new file mode 100644 index 00000000..540739cd --- /dev/null +++ b/apps/web/app/api/agent/[...path]/route.ts @@ -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; diff --git a/apps/web/components/RunnerConsole.tsx b/apps/web/components/RunnerConsole.tsx index 72cf4537..68c46d9c 100644 --- a/apps/web/components/RunnerConsole.tsx +++ b/apps/web/components/RunnerConsole.tsx @@ -146,6 +146,11 @@ export function RunnerDetails({ s, questions, events, steps, stories, back, clos {s.subscriptionName ?? (s.subscriptionId ? `#${s.subscriptionId}` : "вход машины")} {s.subscriptionSwitches > 0 && · переключений {s.subscriptionSwitches}} +
    Где
    +
    + {s.host ? `хост ${s.host.name}` : "Mac Пеппы"} + {s.container ? · контейнер {s.container} : · без изоляции} +
    Запущен
    {ago(s.startedAt)}
    Активность
    diff --git a/apps/web/components/Runners.tsx b/apps/web/components/Runners.tsx index a3af9360..07d261b0 100644 --- a/apps/web/components/Runners.tsx +++ b/apps/web/components/Runners.tsx @@ -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[] }) { + const hostNames = (ids: number[]) => (ids.length ? ids.map((id) => hosts.find((h) => h.id === id)?.name ?? `#${id}`).join(", ") : "Mac Пеппы"); return (
    @@ -104,6 +109,36 @@ export function RunnerSettingsPanel({ projectId, own, inherited, back }: { proje Лимит раннеров проекта (пусто — {inherited.maxRunners ? `как выше: ${inherited.maxRunners}` : "без лимита"}, 0 — без лимита) + + + {hosts.length > 0 && ( +
    + {hosts.map((h) => ( + + ))} +
    + )} +

    + Контейнер: агент работает в docker-образе раннера и видит только свою рабочую копию; токены Пеппы и чужие проекты ему недоступны, нужна подписка в пуле проекта. На хосте агент всегда в контейнере. +

    Очередь: стори достаётся свободному раннеру, при лимите ждёт в очереди; «Принять» не останавливает раннер, а даёт ему следующую стори. Свой worktree: у каждого раннера своя копия и ветка task/…, параллельные стори не мешают друг другу.

    diff --git a/apps/web/components/Sidebar.tsx b/apps/web/components/Sidebar.tsx index 90b60515..dc34717d 100644 --- a/apps/web/components/Sidebar.tsx +++ b/apps/web/components/Sidebar.tsx @@ -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") }, diff --git a/apps/web/components/cards.tsx b/apps/web/components/cards.tsx index 2a8dccff..9d20dc88 100644 --- a/apps/web/components/cards.tsx +++ b/apps/web/components/cards.tsx @@ -130,6 +130,8 @@ export function SessionCard({ s, back, showTitle = false, terminal = false, step #{s.id} · {s.provider} {s.subscriptionName && <> · {s.subscriptionName}} + {s.host && <> · {s.host.name}} + {s.container && <> · в контейнере} {s.subscriptionSwitches > 0 && <> · переключений {s.subscriptionSwitches}} · пок. {s.generation} · {ago(s.lastActivityAt)} diff --git a/infra/runner/Dockerfile b/infra/runner/Dockerfile new file mode 100644 index 00000000..ebe17134 --- /dev/null +++ b/infra/runner/Dockerfile @@ -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" diff --git a/infra/runner/bin/peppa-agent.mjs b/infra/runner/bin/peppa-agent.mjs new file mode 120000 index 00000000..58f0d940 --- /dev/null +++ b/infra/runner/bin/peppa-agent.mjs @@ -0,0 +1 @@ +../peppa-agent.mjs \ No newline at end of file diff --git a/infra/runner/bin/peppa-hook b/infra/runner/bin/peppa-hook new file mode 100755 index 00000000..8711add6 --- /dev/null +++ b/infra/runner/bin/peppa-hook @@ -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 "$@" diff --git a/infra/runner/bin/peppa-mcp b/infra/runner/bin/peppa-mcp new file mode 100755 index 00000000..13630271 --- /dev/null +++ b/infra/runner/bin/peppa-mcp @@ -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 "$@" diff --git a/infra/runner/peppa-agent.mjs b/infra/runner/peppa-agent.mjs new file mode 100644 index 00000000..e09f17ad --- /dev/null +++ b/infra/runner/peppa-agent.mjs @@ -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 [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 [args…] | peppa-agent mcp\n"); + process.exit(2); +} diff --git a/openspec/changes/archive/2026-11-14-pep-17-agent-sandbox-hosts/design.md b/openspec/changes/archive/2026-11-14-pep-17-agent-sandbox-hosts/design.md new file mode 100644 index 00000000..632d2e3d --- /dev/null +++ b/openspec/changes/archive/2026-11-14-pep-17-agent-sandbox-hosts/design.md @@ -0,0 +1,90 @@ +# Design: PEP-17 + PEP-40 + +## Где что выполняется +``` +Пеппа (Mac) хост (Mac Пеппы или SSH-сервер) + runner ── exec(local | ssh host) ──▶ tmux peppa--s + └─ 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 --user `: +- `-v <рабочая копия>:<тот же путь>` (+ `-v <проект>/.git:<тот же путь>` для worktree, чтобы + `.git`-файл worktree указывал в смонтированное), +- `-v -g>:/peppa/run:ro` — settings.json, rules.md, opencode.json; argv + агента ссылается на `/peppa/run/…`, хуки — голые `peppa-hook ` из образа, +- `-v /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` (клиент 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//.git/…` и `/api/agent/git/api/v1/repos///…` — + прокси в Gitea с токеном peppa-bot, только к репозиторию проекта сессии. В контейнере git + направлен туда через `GIT_CONFIG_*` (`url..insteadOf ` + заголовок + авторизации), так что `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`): `/ws//s` — клон + репозитория на ветке `task/` (через одноразовый контейнер с релеем: на хосте нет + токена), `/runs/s-g` — каталог запуска (tar по SSH), + `/home/s`. +- Выбор хоста: `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/`: свой `HOME`, свой `TMUX_TMPDIR` → свой tmux-сервер), + `MOCK_SSH_DOWN=` — код 255. + +## Альтернативы +- Отдельный системный пользователь macOS вместо docker — не переносится на хосты, PM выбрал контейнер. +- Монтировать базу в контейнер ради хуков — ломает изоляцию; релей по HTTP проще и общий для хостов. +- Deploy-ключи Gitea на проект — честнее прокси, но требует SSH-доступа к Gitea из контейнеров; + прокси даёт ту же границу (только свой репозиторий) без новых портов. diff --git a/openspec/changes/archive/2026-11-14-pep-17-agent-sandbox-hosts/proposal.md b/openspec/changes/archive/2026-11-14-pep-17-agent-sandbox-hosts/proposal.md new file mode 100644 index 00000000..6897a71e --- /dev/null +++ b/openspec/changes/archive/2026-11-14-pep-17-agent-sandbox-hosts/proposal.md @@ -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`, без хостов). diff --git a/openspec/changes/archive/2026-11-14-pep-17-agent-sandbox-hosts/specs/agent-sandbox/spec.md b/openspec/changes/archive/2026-11-14-pep-17-agent-sandbox-hosts/specs/agent-sandbox/spec.md new file mode 100644 index 00000000..6f7cc2a2 --- /dev/null +++ b/openspec/changes/archive/2026-11-14-pep-17-agent-sandbox-hosts/specs/agent-sandbox/spec.md @@ -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 запрос не уходит diff --git a/openspec/changes/archive/2026-11-14-pep-17-agent-sandbox-hosts/specs/runner-hosts/spec.md b/openspec/changes/archive/2026-11-14-pep-17-agent-sandbox-hosts/specs/runner-hosts/spec.md new file mode 100644 index 00000000..879d9c9b --- /dev/null +++ b/openspec/changes/archive/2026-11-14-pep-17-agent-sandbox-hosts/specs/runner-hosts/spec.md @@ -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** запуск отклоняется с сообщением «нет доступного хоста» diff --git a/openspec/changes/archive/2026-11-14-pep-17-agent-sandbox-hosts/tasks.md b/openspec/changes/archive/2026-11-14-pep-17-agent-sandbox-hosts/tasks.md new file mode 100644 index 00000000..1cac39d4 --- /dev/null +++ b/openspec/changes/archive/2026-11-14-pep-17-agent-sandbox-hosts/tasks.md @@ -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` diff --git a/openspec/specs/agent-sandbox/spec.md b/openspec/specs/agent-sandbox/spec.md new file mode 100644 index 00000000..e0c76838 --- /dev/null +++ b/openspec/specs/agent-sandbox/spec.md @@ -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 запрос не уходит diff --git a/openspec/specs/runner-hosts/spec.md b/openspec/specs/runner-hosts/spec.md new file mode 100644 index 00000000..04c17596 --- /dev/null +++ b/openspec/specs/runner-hosts/spec.md @@ -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** запуск отклоняется с сообщением «нет доступного хоста» diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index ff7f03cf..7d3977cf 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -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 [-p <промпт>] (story into the runner's queue, PEP-10) peppa runner show (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 [port=22] [workdir=peppa] [url=https://…] (url — where the host reaches the agent relay) + peppa host set [port=… workdir=… url=…|url=-] + peppa host check|disable|enable|rm|push-image (PEP-10/27: system → project → story; a story overrides mode/context only) peppa platform allowlist | allow | deny (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 { 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 { 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)[k] = v; + else if (k === "mode" || k === "context" || k === "workspace" || k === "isolation") (patch as Record)[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 { } 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`); diff --git a/packages/core/src/crypto.ts b/packages/core/src/crypto.ts index 52e8b071..982cbf30 100644 --- a/packages/core/src/crypto.ts +++ b/packages/core/src/crypto.ts @@ -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..`. + * 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]) }; +} diff --git a/packages/core/src/hosts.ts b/packages/core/src/hosts.ts new file mode 100644 index 00000000..f78cf652 --- /dev/null +++ b/packages/core/src/hosts.ts @@ -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) { + 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 { + 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): Promise { + 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 { + 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 { + 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`(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 { + 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 { + 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 { + const [live] = await db + .select({ n: sql`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 { + 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 { + 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 = { unknown: "не проверен", online: "онлайн", offline: "офлайн" }; diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index fa318d55..57b2f81c 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -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"; diff --git a/packages/core/src/runners.ts b/packages/core/src/runners.ts index c2fe5fea..7b55e6e0 100644 --- a/packages/core/src/runners.ts +++ b/packages/core/src/runners.ts @@ -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; /** Which settings a story may override. */ export type TaskRunnerPatch = Partial>; -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 = { story: "Один раннер на стори", queue: "Раннер ведёт очередь стори" }; export const RUNNER_CONTEXT_RU: Record = { fresh: "Свежий контекст на стори", continue: "Один разговор на все стори" }; export const RUNNER_WORKSPACE_RU: Record = { shared: "Общая рабочая копия", worktree: "Свой git worktree на раннер" }; +export const RUNNER_ISOLATION_RU: Record = { 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 | null, allow: Array | null, allow: Array = ["mode", "context", "workspace", "maxRunners"]; +const ALL: Array = ["mode", "context", "workspace", "maxRunners", "isolation", "hosts"]; const TASK: Array = ["mode", "context"]; export async function getSystemRunnerSettings(db: Db): Promise { @@ -80,7 +91,8 @@ async function store(db: Db, key: string, patch: Record, 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); diff --git a/packages/core/src/sessions.ts b/packages/core/src/sessions.ts index f8c4d444..bb35313f 100644 --- a/packages/core/src/sessions.ts +++ b/packages/core/src/sessions.ts @@ -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>, + patch: Partial>, ): Promise { 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`(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, }; } diff --git a/packages/db/migrations/0013_runner_hosts.sql b/packages/db/migrations/0013_runner_hosts.sql new file mode 100644 index 00000000..cd9aea45 --- /dev/null +++ b/packages/db/migrations/0013_runner_hosts.sql @@ -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; \ No newline at end of file diff --git a/packages/db/migrations/meta/0013_snapshot.json b/packages/db/migrations/meta/0013_snapshot.json new file mode 100644 index 00000000..8932c4fd --- /dev/null +++ b/packages/db/migrations/meta/0013_snapshot.json @@ -0,0 +1,3652 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "300fd72c-077a-4631-88cc-8d38bf2ee05f", + "prevId": "ae1ab7d5-713e-4d63-818f-23fffee72696", + "tables": { + "check_runs": { + "name": "check_runs", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "sha": { + "name": "sha", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "branch": { + "name": "branch", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "check": { + "name": "check", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "run_url": { + "name": "run_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "log_tail": { + "name": "log_tail", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "duration_sec": { + "name": "duration_sec", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'report'" + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "check_runs_project_sha_check": { + "name": "check_runs_project_sha_check", + "columns": [ + "project_id", + "sha", + "check" + ], + "isUnique": true + } + }, + "foreignKeys": { + "check_runs_project_id_projects_id_fk": { + "name": "check_runs_project_id_projects_id_fk", + "tableFrom": "check_runs", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "check_runs_task_id_tasks_id_fk": { + "name": "check_runs_task_id_tasks_id_fk", + "tableFrom": "check_runs", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "code_reviews": { + "name": "code_reviews", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sha": { + "name": "sha", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'queued'" + }, + "verdict": { + "name": "verdict", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "summary": { + "name": "summary", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "findings": { + "name": "findings", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "started_at": { + "name": "started_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "code_reviews_project_id_projects_id_fk": { + "name": "code_reviews_project_id_projects_id_fk", + "tableFrom": "code_reviews", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "code_reviews_task_id_tasks_id_fk": { + "name": "code_reviews_task_id_tasks_id_fk", + "tableFrom": "code_reviews", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "error_sources": { + "name": "error_sources", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "bugsink_project_id": { + "name": "bugsink_project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "dsn": { + "name": "dsn", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "error_sources_bugsink_project_id_unique": { + "name": "error_sources_bugsink_project_id_unique", + "columns": [ + "bugsink_project_id" + ], + "isUnique": true + }, + "error_sources_project_kind": { + "name": "error_sources_project_kind", + "columns": [ + "project_id", + "kind" + ], + "isUnique": true + } + }, + "foreignKeys": { + "error_sources_project_id_projects_id_fk": { + "name": "error_sources_project_id_projects_id_fk", + "tableFrom": "error_sources", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "events": { + "name": "events", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "payload": { + "name": "payload", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "actor_kind": { + "name": "actor_kind", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "actor_user_id": { + "name": "actor_user_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "actor_channel": { + "name": "actor_channel", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "actor_client_id": { + "name": "actor_client_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "events_created_at": { + "name": "events_created_at", + "columns": [ + "created_at" + ], + "isUnique": false + } + }, + "foreignKeys": { + "events_project_id_projects_id_fk": { + "name": "events_project_id_projects_id_fk", + "tableFrom": "events", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "events_task_id_tasks_id_fk": { + "name": "events_task_id_tasks_id_fk", + "tableFrom": "events", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "events_session_id_sessions_id_fk": { + "name": "events_session_id_sessions_id_fk", + "tableFrom": "events", + "tableTo": "sessions", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "events_actor_user_id_users_id_fk": { + "name": "events_actor_user_id_users_id_fk", + "tableFrom": "events", + "tableTo": "users", + "columnsFrom": [ + "actor_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "goals": { + "name": "goals", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'open'" + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "goals_project_id_projects_id_fk": { + "name": "goals_project_id_projects_id_fk", + "tableFrom": "goals", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "incident_settings": { + "name": "incident_settings", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "hook_secret": { + "name": "hook_secret", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "policy": { + "name": "policy", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'backlog'" + }, + "triage_prompt": { + "name": "triage_prompt", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "environments": { + "name": "environments", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[\"prod\",\"production\"]'" + }, + "daily_limit": { + "name": "daily_limit", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 5 + }, + "ignore_pattern": { + "name": "ignore_pattern", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "goal_id": { + "name": "goal_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "webhook_auto": { + "name": "webhook_auto", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "incident_settings_hook_secret_unique": { + "name": "incident_settings_hook_secret_unique", + "columns": [ + "hook_secret" + ], + "isUnique": true + } + }, + "foreignKeys": { + "incident_settings_project_id_projects_id_fk": { + "name": "incident_settings_project_id_projects_id_fk", + "tableFrom": "incident_settings", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "incident_settings_goal_id_goals_id_fk": { + "name": "incident_settings_goal_id_goals_id_fk", + "tableFrom": "incident_settings", + "tableTo": "goals", + "columnsFrom": [ + "goal_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "incidents": { + "name": "incidents", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "bugsink_issue_id": { + "name": "bugsink_issue_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "friendly_id": { + "name": "friendly_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "culprit": { + "name": "culprit", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "level": { + "name": "level", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "environment": { + "name": "environment", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "first_release": { + "name": "first_release", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_release": { + "name": "last_release", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "events": { + "name": "events", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "first_seen": { + "name": "first_seen", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_seen": { + "name": "last_seen", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "stack": { + "name": "stack", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'new'" + }, + "decision": { + "name": "decision", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "decided_by": { + "name": "decided_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "decision_reason": { + "name": "decision_reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "task_created_at": { + "name": "task_created_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "resolved_release": { + "name": "resolved_release", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "resolved_at": { + "name": "resolved_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "regressions": { + "name": "regressions", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "incidents_bugsink_issue_id_unique": { + "name": "incidents_bugsink_issue_id_unique", + "columns": [ + "bugsink_issue_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "incidents_project_id_projects_id_fk": { + "name": "incidents_project_id_projects_id_fk", + "tableFrom": "incidents", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "incidents_task_id_tasks_id_fk": { + "name": "incidents_task_id_tasks_id_fk", + "tableFrom": "incidents", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "oauth_clients": { + "name": "oauth_clients", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "redirect_uris": { + "name": "redirect_uris", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "oauth_codes": { + "name": "oauth_codes", + "columns": { + "code_hash": { + "name": "code_hash", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "redirect_uri": { + "name": "redirect_uri", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "code_challenge": { + "name": "code_challenge", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "used_at": { + "name": "used_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "oauth_codes_client_id_oauth_clients_id_fk": { + "name": "oauth_codes_client_id_oauth_clients_id_fk", + "tableFrom": "oauth_codes", + "tableTo": "oauth_clients", + "columnsFrom": [ + "client_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_codes_user_id_users_id_fk": { + "name": "oauth_codes_user_id_users_id_fk", + "tableFrom": "oauth_codes", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "oauth_tokens": { + "name": "oauth_tokens", + "columns": { + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "revoked_at": { + "name": "revoked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "last_used_at": { + "name": "last_used_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "oauth_tokens_client_id_oauth_clients_id_fk": { + "name": "oauth_tokens_client_id_oauth_clients_id_fk", + "tableFrom": "oauth_tokens", + "tableTo": "oauth_clients", + "columnsFrom": [ + "client_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_tokens_user_id_users_id_fk": { + "name": "oauth_tokens_user_id_users_id_fk", + "tableFrom": "oauth_tokens", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "project_invites": { + "name": "project_invites", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "login": { + "name": "login", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "invited_by": { + "name": "invited_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "project_invites_project_id_projects_id_fk": { + "name": "project_invites_project_id_projects_id_fk", + "tableFrom": "project_invites", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_invites_invited_by_users_id_fk": { + "name": "project_invites_invited_by_users_id_fk", + "tableFrom": "project_invites", + "tableTo": "users", + "columnsFrom": [ + "invited_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "project_invites_project_id_login_pk": { + "columns": [ + "project_id", + "login" + ], + "name": "project_invites_project_id_login_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "project_members": { + "name": "project_members", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "added_by": { + "name": "added_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "project_members_project_id_projects_id_fk": { + "name": "project_members_project_id_projects_id_fk", + "tableFrom": "project_members", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_members_user_id_users_id_fk": { + "name": "project_members_user_id_users_id_fk", + "tableFrom": "project_members", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_members_added_by_users_id_fk": { + "name": "project_members_added_by_users_id_fk", + "tableFrom": "project_members", + "tableTo": "users", + "columnsFrom": [ + "added_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "project_members_project_id_user_id_pk": { + "columns": [ + "project_id", + "user_id" + ], + "name": "project_members_project_id_user_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "project_secrets": { + "name": "project_secrets", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "value_enc": { + "name": "value_enc", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updated_by": { + "name": "updated_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "last_used_at": { + "name": "last_used_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "project_secrets_project_name": { + "name": "project_secrets_project_name", + "columns": [ + "project_id", + "name" + ], + "isUnique": true + } + }, + "foreignKeys": { + "project_secrets_project_id_projects_id_fk": { + "name": "project_secrets_project_id_projects_id_fk", + "tableFrom": "project_secrets", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_secrets_created_by_users_id_fk": { + "name": "project_secrets_created_by_users_id_fk", + "tableFrom": "project_secrets", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "project_secrets_updated_by_users_id_fk": { + "name": "project_secrets_updated_by_users_id_fk", + "tableFrom": "project_secrets", + "tableTo": "users", + "columnsFrom": [ + "updated_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "projects": { + "name": "projects", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "gitea_owner": { + "name": "gitea_owner", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "gitea_repo": { + "name": "gitea_repo", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "default_branch": { + "name": "default_branch", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'main'" + }, + "workspace_path": { + "name": "workspace_path", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "owner_id": { + "name": "owner_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "next_task_number": { + "name": "next_task_number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "subscription_pool_id": { + "name": "subscription_pool_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "projects_slug_unique": { + "name": "projects_slug_unique", + "columns": [ + "slug" + ], + "isUnique": true + }, + "projects_key_unique": { + "name": "projects_key_unique", + "columns": [ + "key" + ], + "isUnique": true + } + }, + "foreignKeys": { + "projects_owner_id_users_id_fk": { + "name": "projects_owner_id_users_id_fk", + "tableFrom": "projects", + "tableTo": "users", + "columnsFrom": [ + "owner_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "projects_subscription_pool_id_subscription_pools_id_fk": { + "name": "projects_subscription_pool_id_subscription_pools_id_fk", + "tableFrom": "projects", + "tableTo": "subscription_pools", + "columnsFrom": [ + "subscription_pool_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "push_outbox": { + "name": "push_outbox", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "subscription_id": { + "name": "subscription_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "payload": { + "name": "payload", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "urgency": { + "name": "urgency", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'normal'" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "sent_at": { + "name": "sent_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "push_outbox_dedupe_key_unique": { + "name": "push_outbox_dedupe_key_unique", + "columns": [ + "dedupe_key" + ], + "isUnique": true + } + }, + "foreignKeys": { + "push_outbox_subscription_id_push_subscriptions_id_fk": { + "name": "push_outbox_subscription_id_push_subscriptions_id_fk", + "tableFrom": "push_outbox", + "tableTo": "push_subscriptions", + "columnsFrom": [ + "subscription_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "push_subscriptions": { + "name": "push_subscriptions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "endpoint": { + "name": "endpoint", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "p256dh": { + "name": "p256dh", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "auth": { + "name": "auth", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_agent": { + "name": "user_agent", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "last_ok_at": { + "name": "last_ok_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "push_subscriptions_endpoint_unique": { + "name": "push_subscriptions_endpoint_unique", + "columns": [ + "endpoint" + ], + "isUnique": true + } + }, + "foreignKeys": { + "push_subscriptions_user_id_users_id_fk": { + "name": "push_subscriptions_user_id_users_id_fk", + "tableFrom": "push_subscriptions", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "questions": { + "name": "questions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "options": { + "name": "options", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "answer": { + "name": "answer", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "answered_via": { + "name": "answered_via", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_message_id": { + "name": "telegram_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "awaiting_hook": { + "name": "awaiting_hook", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "reminders": { + "name": "reminders", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "answered_at": { + "name": "answered_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "questions_project_id_projects_id_fk": { + "name": "questions_project_id_projects_id_fk", + "tableFrom": "questions", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "questions_task_id_tasks_id_fk": { + "name": "questions_task_id_tasks_id_fk", + "tableFrom": "questions", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "questions_session_id_sessions_id_fk": { + "name": "questions_session_id_sessions_id_fk", + "tableFrom": "questions", + "tableTo": "sessions", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "releases": { + "name": "releases", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "env": { + "name": "env", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sha": { + "name": "sha", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "previous_sha": { + "name": "previous_sha", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "host": { + "name": "host", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tasks": { + "name": "tasks", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'deploying'" + }, + "deployed_by": { + "name": "deployed_by", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'ci'" + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "run_url": { + "name": "run_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "log_tail": { + "name": "log_tail", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "screenshots": { + "name": "screenshots", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "releases_project_id_projects_id_fk": { + "name": "releases_project_id_projects_id_fk", + "tableFrom": "releases", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "review_settings": { + "name": "review_settings", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "max_iterations": { + "name": "max_iterations", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 2 + }, + "rules": { + "name": "rules", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "review_settings_project_id_projects_id_fk": { + "name": "review_settings_project_id_projects_id_fk", + "tableFrom": "review_settings", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "runner_commands": { + "name": "runner_commands", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "payload": { + "name": "payload", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'queued'" + }, + "result": { + "name": "result", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error_kind": { + "name": "error_kind", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "actor": { + "name": "actor", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "host": { + "name": "host", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "started_at": { + "name": "started_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "finished_at": { + "name": "finished_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "runner_commands_status_idx": { + "name": "runner_commands_status_idx", + "columns": [ + "status", + "id" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "runner_hosts": { + "name": "runner_hosts", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ssh_target": { + "name": "ssh_target", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ssh_port": { + "name": "ssh_port", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 22 + }, + "workdir": { + "name": "workdir", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'peppa'" + }, + "peppa_url": { + "name": "peppa_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'unknown'" + }, + "info": { + "name": "info", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_seen_at": { + "name": "last_seen_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "disabled_at": { + "name": "disabled_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "runner_hosts_name_unique": { + "name": "runner_hosts_name_unique", + "columns": [ + "name" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "runner_tasks": { + "name": "runner_tasks", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "prompt": { + "name": "prompt", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "front": { + "name": "front", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "started_at": { + "name": "started_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ended_at": { + "name": "ended_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "runner_tasks_session_idx": { + "name": "runner_tasks_session_idx", + "columns": [ + "session_id", + "status" + ], + "isUnique": false + } + }, + "foreignKeys": { + "runner_tasks_session_id_sessions_id_fk": { + "name": "runner_tasks_session_id_sessions_id_fk", + "tableFrom": "runner_tasks", + "tableTo": "sessions", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "runner_tasks_task_id_tasks_id_fk": { + "name": "runner_tasks_task_id_tasks_id_fk", + "tableFrom": "runner_tasks", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "sessions": { + "name": "sessions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tmux_name": { + "name": "tmux_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'claude'" + }, + "subscription_id": { + "name": "subscription_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "claude_session_id": { + "name": "claude_session_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "auto_nudges": { + "name": "auto_nudges", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "resume_at": { + "name": "resume_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "limit_probe_min": { + "name": "limit_probe_min", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "limit_resumes": { + "name": "limit_resumes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "limit_resumes_day": { + "name": "limit_resumes_day", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "limit_resumed_at": { + "name": "limit_resumed_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "rotate_reason": { + "name": "rotate_reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "workspace_path": { + "name": "workspace_path", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "host_id": { + "name": "host_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "container": { + "name": "container", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "usage": { + "name": "usage", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "watch_state": { + "name": "watch_state", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'starting'" + }, + "last_activity_at": { + "name": "last_activity_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "ended_at": { + "name": "ended_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "sessions_tmux_name_unique": { + "name": "sessions_tmux_name_unique", + "columns": [ + "tmux_name" + ], + "isUnique": true + } + }, + "foreignKeys": { + "sessions_project_id_projects_id_fk": { + "name": "sessions_project_id_projects_id_fk", + "tableFrom": "sessions", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "sessions_task_id_tasks_id_fk": { + "name": "sessions_task_id_tasks_id_fk", + "tableFrom": "sessions", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "sessions_subscription_id_subscriptions_id_fk": { + "name": "sessions_subscription_id_subscriptions_id_fk", + "tableFrom": "sessions", + "tableTo": "subscriptions", + "columnsFrom": [ + "subscription_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "sessions_host_id_runner_hosts_id_fk": { + "name": "sessions_host_id_runner_hosts_id_fk", + "tableFrom": "sessions", + "tableTo": "runner_hosts", + "columnsFrom": [ + "host_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "settings": { + "name": "settings", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "subscription_pool_members": { + "name": "subscription_pool_members", + "columns": { + "pool_id": { + "name": "pool_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "subscription_id": { + "name": "subscription_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "subscription_pool_members_pool_id_subscription_pools_id_fk": { + "name": "subscription_pool_members_pool_id_subscription_pools_id_fk", + "tableFrom": "subscription_pool_members", + "tableTo": "subscription_pools", + "columnsFrom": [ + "pool_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "subscription_pool_members_subscription_id_subscriptions_id_fk": { + "name": "subscription_pool_members_subscription_id_subscriptions_id_fk", + "tableFrom": "subscription_pool_members", + "tableTo": "subscriptions", + "columnsFrom": [ + "subscription_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "subscription_pool_members_pool_id_subscription_id_pk": { + "columns": [ + "pool_id", + "subscription_id" + ], + "name": "subscription_pool_members_pool_id_subscription_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "subscription_pools": { + "name": "subscription_pools", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "subscription_pools_name_unique": { + "name": "subscription_pools_name_unique", + "columns": [ + "name" + ], + "isUnique": true + } + }, + "foreignKeys": { + "subscription_pools_created_by_users_id_fk": { + "name": "subscription_pools_created_by_users_id_fk", + "tableFrom": "subscription_pools", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "subscriptions": { + "name": "subscriptions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "auth_kind": { + "name": "auth_kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "secret_enc": { + "name": "secret_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "key_provider": { + "name": "key_provider", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "limited_until": { + "name": "limited_until", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "checked_at": { + "name": "checked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "activated_at": { + "name": "activated_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "subscriptions_created_by_users_id_fk": { + "name": "subscriptions_created_by_users_id_fk", + "tableFrom": "subscriptions", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "task_deps": { + "name": "task_deps", + "columns": { + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "blocked_by_id": { + "name": "blocked_by_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "task_deps_blocked_by": { + "name": "task_deps_blocked_by", + "columns": [ + "blocked_by_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "task_deps_task_id_tasks_id_fk": { + "name": "task_deps_task_id_tasks_id_fk", + "tableFrom": "task_deps", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "task_deps_blocked_by_id_tasks_id_fk": { + "name": "task_deps_blocked_by_id_tasks_id_fk", + "tableFrom": "task_deps", + "tableTo": "tasks", + "columnsFrom": [ + "blocked_by_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "task_deps_task_id_blocked_by_id_pk": { + "columns": [ + "task_id", + "blocked_by_id" + ], + "name": "task_deps_task_id_blocked_by_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "tasks": { + "name": "tasks", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "goal_id": { + "name": "goal_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "number": { + "name": "number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'backlog'" + }, + "openspec_change": { + "name": "openspec_change", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pr_url": { + "name": "pr_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ci_attempts": { + "name": "ci_attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "ci_failed_sha": { + "name": "ci_failed_sha", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "gitea_issue": { + "name": "gitea_issue", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "position": { + "name": "position", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "archived_at": { + "name": "archived_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "tasks_project_number": { + "name": "tasks_project_number", + "columns": [ + "project_id", + "number" + ], + "isUnique": true + }, + "tasks_project_issue": { + "name": "tasks_project_issue", + "columns": [ + "project_id", + "gitea_issue" + ], + "isUnique": true + } + }, + "foreignKeys": { + "tasks_project_id_projects_id_fk": { + "name": "tasks_project_id_projects_id_fk", + "tableFrom": "tasks", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "tasks_goal_id_goals_id_fk": { + "name": "tasks_goal_id_goals_id_fk", + "tableFrom": "tasks", + "tableTo": "goals", + "columnsFrom": [ + "goal_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "telegram_outbox": { + "name": "telegram_outbox", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "method": { + "name": "method", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "params": { + "name": "params", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "question_id": { + "name": "question_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "telegram_message_id": { + "name": "telegram_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "sent_at": { + "name": "sent_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "telegram_outbox_dedupe_key_unique": { + "name": "telegram_outbox_dedupe_key_unique", + "columns": [ + "dedupe_key" + ], + "isUnique": true + } + }, + "foreignKeys": { + "telegram_outbox_question_id_questions_id_fk": { + "name": "telegram_outbox_question_id_questions_id_fk", + "tableFrom": "telegram_outbox", + "tableTo": "questions", + "columnsFrom": [ + "question_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "telegram_updates": { + "name": "telegram_updates", + "columns": { + "update_id": { + "name": "update_id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "users": { + "name": "users", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "gitea_id": { + "name": "gitea_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "login": { + "name": "login", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "avatar_url": { + "name": "avatar_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "access_token_enc": { + "name": "access_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "refresh_token_enc": { + "name": "refresh_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "token_expires_at": { + "name": "token_expires_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "claude_token_enc": { + "name": "claude_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "claude_token_set_at": { + "name": "claude_token_set_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_chat_id": { + "name": "telegram_chat_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_user_id": { + "name": "telegram_user_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_username": { + "name": "telegram_username", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_paired_at": { + "name": "telegram_paired_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "egov_iin": { + "name": "egov_iin", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "egov_linked_at": { + "name": "egov_linked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "password_hash": { + "name": "password_hash", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "password_set_at": { + "name": "password_set_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "disabled_at": { + "name": "disabled_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "last_login_at": { + "name": "last_login_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "users_gitea_id_unique": { + "name": "users_gitea_id_unique", + "columns": [ + "gitea_id" + ], + "isUnique": true + }, + "users_login_unique": { + "name": "users_login_unique", + "columns": [ + "login" + ], + "isUnique": true + }, + "users_telegram_chat_id_unique": { + "name": "users_telegram_chat_id_unique", + "columns": [ + "telegram_chat_id" + ], + "isUnique": true + }, + "users_egov_iin_unique": { + "name": "users_egov_iin_unique", + "columns": [ + "egov_iin" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + } + }, + "views": {}, + "enums": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "indexes": {} + } +} \ No newline at end of file diff --git a/packages/db/migrations/meta/_journal.json b/packages/db/migrations/meta/_journal.json index 46b59e11..ab59703e 100644 --- a/packages/db/migrations/meta/_journal.json +++ b/packages/db/migrations/meta/_journal.json @@ -92,6 +92,13 @@ "when": 1794623649272, "tag": "0012_runner_service", "breakpoints": true + }, + { + "idx": 13, + "version": "6", + "when": 1794624555440, + "tag": "0013_runner_hosts", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts index dfa13a02..07387751 100644 --- a/packages/db/src/schema.ts +++ b/packages/db/src/schema.ts @@ -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(), + 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(), diff --git a/packages/mcp/package.json b/packages/mcp/package.json index 4c6995bd..24c55fde 100644 --- a/packages/mcp/package.json +++ b/packages/mcp/package.json @@ -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" } } diff --git a/packages/mcp/src/agent.ts b/packages/mcp/src/agent.ts new file mode 100644 index 00000000..6ff56feb --- /dev/null +++ b/packages/mcp/src/agent.ts @@ -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( + name: string, + description: string, + inputSchema: S, + run: (args: z.infer>) => Promise, + ) { + server.registerTool(name, { description, inputSchema }, (async (args: z.infer>): Promise => { + 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/) 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/") }, + 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; +} diff --git a/packages/mcp/src/index.ts b/packages/mcp/src/index.ts index d2e9e628..95194db7 100644 --- a/packages/mcp/src/index.ts +++ b/packages/mcp/src/index.ts @@ -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( - name: string, - description: string, - inputSchema: S, - run: (args: z.infer>) => Promise, -) { - server.registerTool(name, { description, inputSchema }, (async (args: z.infer>): Promise => { - 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()); diff --git a/packages/mcp/src/relay.ts b/packages/mcp/src/relay.ts new file mode 100644 index 00000000..c542f866 --- /dev/null +++ b/packages/mcp/src/relay.ts @@ -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 { + 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); + }); +} diff --git a/packages/runner/src/agent-relay.ts b/packages/runner/src/agent-relay.ts new file mode 100644 index 00000000..3cde2a5a --- /dev/null +++ b/packages/runner/src/agent-relay.ts @@ -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; + +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 { + 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; +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; + 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((res) => (timer = setTimeout(() => res(null), ms)))]); + clearTimeout(timer); + return r; +} + +async function hookRequest(db: Db, req: Request): Promise { + 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, 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 { + // 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).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 { + 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 { + 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) res.write(chunk); + res.end(); + }); + return new Promise((resolve) => server.listen(port, opts.host ?? "127.0.0.1", () => resolve(server))); +} diff --git a/packages/runner/src/budgets.ts b/packages/runner/src/budgets.ts index 4439920f..d8f2b13b 100644 --- a/packages/runner/src/budgets.ts +++ b/packages/runner/src/budgets.ts @@ -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(() => {}); } } diff --git a/packages/runner/src/exec.ts b/packages/runner/src/exec.ts new file mode 100644 index 00000000..8b66ec82 --- /dev/null +++ b/packages/runner/src/exec.ts @@ -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 { + 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; + timeoutMs?: number; +} + +/** argv → the command line ssh hands to the host's shell. */ +export function remoteCommand(argv: string[], opts: Pick = {}): 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); diff --git a/packages/runner/src/hosts.ts b/packages/runner/src/hosts.ts new file mode 100644 index 00000000..64e99d1a --- /dev/null +++ b/packages/runner/src/hosts.ts @@ -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; + +// Absolute workdir per host (the configured one may be relative to the SSH user's home). +const workdirs = new Map(); + +/** `` on the host as an absolute path; creates ws/, runs/, home/. */ +export async function hostWorkdir(h: Host): Promise { + 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 { + 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 { + 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 (`/ws//s`) 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 { + 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(); + +/** 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 { + 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 { + 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 }); +} diff --git a/packages/runner/src/index.ts b/packages/runner/src/index.ts index 42f98810..d70cf480 100644 --- a/packages/runner/src/index.ts +++ b/packages/runner/src/index.ts @@ -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"; diff --git a/packages/runner/src/providers.ts b/packages/runner/src/providers.ts index 118a68e5..349b6876 100644 --- a/packages/runner/src/providers.ts +++ b/packages/runner/src/providers.ts @@ -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): Record { - return provider === "opencode" ? { OPENCODE_CONFIG: join(runDir(c.sessionId, c.generation), "opencode.json") } : {}; +export function providerEnv(provider: Provider, c: Pick): Record { + return provider === "opencode" ? { OPENCODE_CONFIG: runFile(c, join(runDir(c.sessionId, c.generation), "opencode.json")) } : {}; } function claudeCommand(c: LaunchContext): string[] { return [ - 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] : []), diff --git a/packages/runner/src/recovery.ts b/packages/runner/src/recovery.ts index 01d0689b..4d156bdb 100644 --- a/packages/runner/src/recovery.ts +++ b/packages/runner/src/recovery.ts @@ -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); diff --git a/packages/runner/src/rotation.ts b/packages/runner/src/rotation.ts index 2ebc5cd0..fdc6a92e 100644 --- a/packages/runner/src/rotation.ts +++ b/packages/runner/src/rotation.ts @@ -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 { 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, diff --git a/packages/runner/src/run-settings.ts b/packages/runner/src/run-settings.ts index 555591c3..89ee8fe6 100644 --- a/packages/runner/src/run-settings.ts +++ b/packages/runner/src/run-settings.ts @@ -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")] }], diff --git a/packages/runner/src/runners.ts b/packages/runner/src/runners.ts index 5c828a5f..5cedc1dc 100644 --- a/packages/runner/src/runners.ts +++ b/packages/runner/src/runners.ts @@ -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; diff --git a/packages/runner/src/sandbox.ts b/packages/runner/src/sandbox.ts new file mode 100644 index 00000000..38188718 --- /dev/null +++ b/packages/runner/src/sandbox.ts @@ -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; + if (host) return (host.peppaUrl || env.PEPPA_WEB_URL || "https://peppa.telecom.quest").replace(/\/$/, ""); + return (process.env.PEPPA_AGENT_URL ?? `http://host.docker.internal:${process.env.PEPPA_WEB_PORT ?? 3100}`).replace(/\/$/, ""); +} + +/** The agent's own HOME on this machine (conversation history for --resume, claude config). */ +export const localAgentHome = (sessionId: number) => join(peppaHome(), "sandboxes", `s${sessionId}`, "home"); + +/** Claude config for the container: onboarding done, the workspace trusted, the peppa MCP server enabled. */ +export function claudeConfigFor(existing: string | null, cwd: string): string { + const cfg = existing ? (JSON.parse(existing) as Record) : {}; + cfg.hasCompletedOnboarding = true; + 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 { + const gitea = (loadEnv() as Record).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; + /** More names for docker `-e` whose values the script sets itself (PEP-54 project secrets). */ + passEnv?: string[]; + /** Shell lines before `docker run` (sourcing the secrets file). */ + preamble?: string; +} + +/** The run's environment: session, relay, git through the relay, plus the subscription/provider env. */ +export function containerEnv(spec: Pick, extra: Record): Record { + const token = agentRelayToken(spec.sessionId, spec.generation); + return { + PEPPA_SESSION_ID: String(spec.sessionId), + PEPPA_GENERATION: String(spec.generation), + PEPPA_AGENT_URL: spec.relay, + PEPPA_AGENT_TOKEN: token, + ...gitRelayEnv(spec.relay, token), + ...extra, + }; +} + +/** + * launch.sh for tmux: `docker run` of the runner image. Values of the environment stay out of + * the script (it is mounted into the container and kept on disk): `-e NAME` takes them from + * the docker client's environment, which tmux sets. + */ +export function dockerRunScript(spec: ContainerSpec): string { + const name = containerName(spec.sessionId); + const mounts: Mount[] = [ + { src: spec.cwd, dst: spec.cwd }, + { src: spec.runDir, dst: RUN_MOUNT, ro: true }, + { src: spec.home, dst: CONTAINER_HOME }, + ...(spec.mounts ?? []), + ]; + const args = [ + dockerBin(spec.target), "run", "--rm", "-it", "--init", + "--name", name, + "--label", `peppa.session=${spec.sessionId}`, + "--add-host", "host.docker.internal:host-gateway", + "-w", spec.cwd, + ...mounts.flatMap((m) => ["-v", `${m.src}:${m.dst}${m.ro ? ":ro" : ""}`]), + "-e", `HOME=${CONTAINER_HOME}`, + ...[...new Set([...Object.keys(spec.env), ...(spec.passEnv ?? [])])].sort().flatMap((k) => ["-e", k]), + ...(process.env.PEPPA_SANDBOX_DOCKER_ARGS ?? "").split(" ").filter(Boolean), + ]; + // Files written by the agent belong to the host user, not root (Linux hosts). + return [ + "#!/bin/bash", + `# PEP-17: agent of session ${spec.sessionId} (generation ${spec.generation}) in its container`, + `${dockerBin(spec.target)} rm -f ${name} >/dev/null 2>&1`, + ...(spec.preamble ? [spec.preamble.trimEnd()] : []), + `exec ${args.map(shq).join(" ")} --user "$(id -u):$(id -g)" ${shq(runnerImage())} ${spec.argv.map(shq).join(" ")}`, + "", + ].join("\n"); +} + +/** Removes the runner's container (its docker client under tmux may die first). */ +export async function removeContainer(target: Target, name: string): Promise { + await runOn(target, [dockerBin(target), "rm", "-f", name]).catch(() => {}); +} diff --git a/packages/runner/src/sessions.ts b/packages/runner/src/sessions.ts index e91061ba..9731788b 100644 --- a/packages/runner/src/sessions.ts +++ b/packages/runner/src/sessions.ts @@ -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 " 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 { + 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 { 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 { 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 { 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; + 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 { 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 { 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 }; diff --git a/packages/runner/src/terminal.ts b/packages/runner/src/terminal.ts index 82827ccd..b4cc2eda 100644 --- a/packages/runner/src/terminal.ts +++ b/packages/runner/src/terminal.ts @@ -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(); /** 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; 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 }); diff --git a/packages/runner/src/tmux.ts b/packages/runner/src/tmux.ts index d9fb996b..71ad3c8c 100644 --- a/packages/runner/src/tmux.ts +++ b/packages/runner/src/tmux.ts @@ -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 { - 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 { + 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; - 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 { 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; + width?: number; +} + export async function newSession(s: NewTmuxSession): Promise { 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 { +/** False only when tmux says there is no such session; an unreachable host throws (state unknown). */ +export async function hasSession(p: Pane): Promise { 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 { +export async function paneState(p: Pane): Promise { + 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 { - return tmux("capture-pane", "-p", "-J", "-t", `=${name}:`, "-S", String(-history)); +export async function capturePane(p: Pane, history = 0): Promise { + 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 { - if (isRunnerClient()) return viaService("sendText", [name, text, submit]); +export async function sendText(p: Pane, text: string, submit = true): Promise { + if (isRunnerClient()) return viaService("sendText", [p, text, submit]); + const name = paneName(p); const buffer = `peppa-${process.pid}-${Date.now()}`; - await new Promise((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 { - if (isRunnerClient()) return viaService("sendKeys", [name, ...keys]); - await tmux("send-keys", "-t", `=${name}:`, ...keys); +export async function sendKeys(p: Pane, ...keys: string[]): Promise { + if (isRunnerClient()) return viaService("sendKeys", [p, ...keys]); + await tmuxOn(p, ["send-keys", "-t", `=${paneName(p)}:`, ...keys]); } -export async function killSession(name: string): Promise { - if (isRunnerClient()) return viaService("killSession", [name]); - await tmux("kill-session", "-t", `=${name}`); +export async function killSession(p: Pane): Promise { + 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 { - 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 { + 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 { * 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 { - 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 { + 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 { +export async function sendHex(p: Pane, bytes: Uint8Array): Promise { 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"))]); } diff --git a/packages/runner/src/watchdog.ts b/packages/runner/src/watchdog.ts index 644a1f9c..3175e7a0 100644 --- a/packages/runner/src/watchdog.ts +++ b/packages/runner/src/watchdog.ts @@ -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 { 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); diff --git a/packages/testkit/bin/mock-docker b/packages/testkit/bin/mock-docker index eef55e1b..2863aedf 100755 --- a/packages/testkit/bin/mock-docker +++ b/packages/testkit/bin/mock-docker @@ -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/ (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 ` drops containers/; 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}}' 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 + 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 ... @@ -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 … -c '' _ → 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 … -c '' _ → base64 PNG on stdout url="${@: -1}" echo "$url" >> "$st/screenshots.log" [[ -n "${MOCK_DOCKER_SCREENSHOT_FAIL:-}" ]] && { echo "mock screenshot failed" >&2; exit 1; } diff --git a/packages/testkit/bin/mock-ssh b/packages/testkit/bin/mock-ssh new file mode 100755 index 00000000..216c2e89 --- /dev/null +++ b/packages/testkit/bin/mock-ssh @@ -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/ with its own HOME and TMUX_TMPDIR +# (its own tmux server; the socket dir is short — /tmp/mssh- — 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) +# /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 "$*" diff --git a/packages/testkit/test/runners.test.ts b/packages/testkit/test/runners.test.ts index 3f410ac9..48ef289d 100644 --- a/packages/testkit/test/runners.test.ts +++ b/packages/testkit/test/runners.test.ts @@ -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, {}); diff --git a/packages/testkit/test/sandbox-hosts.test.ts b/packages/testkit/test/sandbox-hosts.test.ts new file mode 100644 index 00000000..99acf535 --- /dev/null +++ b/packages/testkit/test/sandbox-hosts.test.ts @@ -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>; + +/** Smart-HTTP git server (git http-backend) standing in for Gitea; records the auth it got. */ +function serveGit(): Promise { + 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/.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) => { + 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((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); + }); +}); diff --git a/scripts/runner-image.sh b/scripts/runner-image.sh new file mode 100755 index 00000000..d256c598 --- /dev/null +++ b/scripts/runner-image.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +# PEP-17/40: builds the runner image (infra/runner) and, with --push , 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 diff --git a/template/RULES.md b/template/RULES.md index 0d680905..31a2a008 100644 --- a/template/RULES.md +++ b/template/RULES.md @@ -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), а