// PEP-21: the runner service — the only process that starts, stops and types into agent // tmux sessions. Runs inside the watchdog (`peppa watchdog`). Clients (web, bot, remote MCP) // enqueue commands in `runner_commands` and poke `$PEPPA_HOME/runner.sock` (runner-client.ts). import { createServer, type Server } from "node:net"; import { rmSync } from "node:fs"; import { and, asc, desc, eq, inArray, lt } from "drizzle-orm"; import { PeppaError, resolveTask, runAsActor, type Actor, type Question } from "@peppa/core"; import { runnerCommands, type Db } from "@peppa/db"; import { pokeRunner, runAsRunnerService, runnerSocket } from "./runner-client.ts"; import { resumeSession, sendToSession, startSession, stopSession, answerAndDeliver, type StartOptions } from "./sessions.ts"; import { promoteRunner, queueTaskOnRunner, startFreeRunner, startTaskOnRunner, type FreeRunnerOptions } from "./runners.ts"; import { acceptStory, acceptTask, archiveTask, moveTask, type BoardColumn } from "./flow.ts"; import * as tmux from "./tmux.ts"; import { sendWithEscalation } from "./escalation.ts"; type P = Record; type Handler = (db: Db, p: P) => Promise; type Via = NonNullable; /** Commands the service runs. Payloads and results are plain JSON (ids, not views). */ export const RUNNER_COMMANDS: Record = { start: async (db, p) => ({ sessionId: (await startSession(db, p.task as string, p.opts as StartOptions)).id }), startFree: async (db, p) => ({ sessionId: (await startFreeRunner(db, p.projectId as number, p.opts as FreeRunnerOptions)).id }), assign: async (db, p) => startTaskOnRunner(db, await resolveTask(db, p.task), p.opts as StartOptions), resume: async (db, p) => ({ sessionId: (await resumeSession(db, p.sessionId, p.opts as StartOptions)).id }), stop: async (db, p) => (await stopSession(db, p.sessionId), {}), send: async (db, p) => (await sendToSession(db, p.sessionId, p.text), {}), // PEP-41: feedback that may relaunch the runner on the escalation model (one atomic step). sendEscalated: async (db, p) => ({ result: await sendWithEscalation(db, p.sessionId, p.text) }), move: async (db, p) => moveTask(db, await resolveTask(db, p.task), p.to as BoardColumn, p.start as StartOptions), archive: async (db, p) => archiveTask(db, await resolveTask(db, p.task), !!p.archived), accept: async (db, p) => ({ key: (await acceptTask(db, p.questionId, p.via as Via, p.answer)).key }), acceptStory: async (db, p) => ({ key: (await acceptStory(db, await resolveTask(db, p.task), p.via as Via)).key }), answer: async (db, p) => { const r = await answerAndDeliver(db, p.questionId, p.answer, p.via as Via); return { delivered: r.delivered, questionId: r.question.id }; }, queue: async (db, p) => (await queueTaskOnRunner(db, p.sessionId, await resolveTask(db, p.task), p.prompt), {}), promote: async (db, p) => ({ key: (await promoteRunner(db, p.sessionId, p.story)).key }), // Safety net: a mutating tmux call from a client path not covered above. tmux: async (_db, p) => { const a = p.args as any[]; switch (p.op) { case "newSession": return tmux.newSession(a[0]); case "killSession": return tmux.killSession(a[0]); case "sendText": return tmux.sendText(a[0], a[1], a[2]); case "sendKeys": return tmux.sendKeys(a[0], ...(a.slice(1) as string[])); case "sendHex": return tmux.sendHex(a[0], Uint8Array.from(a[1] as number[])); default: throw new Error(`unknown tmux op ${p.op}`); } }, }; export interface ServiceOptions { log?: (m: string) => void; /** Table poll interval (pokes wake it sooner). */ pollMs?: number; /** A queued command older than this is expired, not run (the client gave up). */ pickupMs?: number; } export interface RunnerService { stop(): Promise; /** Runs the queue now (tests). */ drain(): Promise; } const DAY = 24 * 60 * 60 * 1000; /** * Starts serving runner commands: listens on the socket, polls the table, runs commands * with the same key one after another and the rest at once. Refuses to start a second * service next to a live one. */ export async function serveRunnerCommands(db: Db, o: ServiceOptions = {}): Promise { const log = o.log ?? (() => {}); const pickupMs = o.pickupMs ?? (Number(process.env.PEPPA_RUNNER_PICKUP_SEC) > 0 ? Number(process.env.PEPPA_RUNNER_PICKUP_SEC) * 1000 : 15_000); if (await pokeRunner()) throw new PeppaError(`раннер-сервис уже запущен (${runnerSocket()})`); // Commands cut short by the previous run of the service. const orphans = await db .update(runnerCommands) .set({ status: "failed", error: "раннер-сервис перезапустился во время выполнения", errorKind: "internal", finishedAt: new Date() }) .where(eq(runnerCommands.status, "running")) .returning({ id: runnerCommands.id }); if (orphans.length) log(`runner service: ${orphans.length} command(s) interrupted by a restart`); const busyKeys = new Set(); const inflight = new Set>(); let draining = false; let again = false; let stopped = false; let lastCleanup = 0; const run = async (c: typeof runnerCommands.$inferSelect) => { const handler = RUNNER_COMMANDS[c.kind]; const actor = (c.actor as Actor | null) ?? { kind: "system", channel: "watchdog" }; // Raw tmux payloads may carry a launch env (tokens) or a login code: not kept once run. const payload = c.kind === "tmux" ? { op: c.payload.op, redacted: true } : c.payload; try { if (!handler) throw new Error(`неизвестная команда ${c.kind}`); const result = await runAsRunnerService(() => runAsActor(actor, () => handler(db, c.payload))); await db.update(runnerCommands).set({ status: "done", result: result ?? null, payload, finishedAt: new Date() }).where(eq(runnerCommands.id, c.id)); } catch (e) { const peppa = e instanceof PeppaError; if (!peppa) log(`runner command #${c.id} ${c.kind} failed: ${(e as Error).stack ?? e}`); await db .update(runnerCommands) .set({ status: "failed", error: (e as Error).message, errorKind: peppa ? "peppa" : "internal", payload, finishedAt: new Date() }) .where(eq(runnerCommands.id, c.id)); } }; const drainOnce = async () => { const now = Date.now(); const queued = await db.select().from(runnerCommands).where(eq(runnerCommands.status, "queued")).orderBy(asc(runnerCommands.id)).limit(100); const seen = new Set(); for (const c of queued) { if (now - c.createdAt.getTime() > pickupMs) { await db.update(runnerCommands).set({ status: "expired", finishedAt: new Date() }).where(and(eq(runnerCommands.id, c.id), eq(runnerCommands.status, "queued"))); log(`runner command #${c.id} ${c.kind} expired before it was taken`); continue; } // Same key: wait for the earlier one (in flight or earlier in this batch). if (c.key && (busyKeys.has(c.key) || seen.has(c.key))) { seen.add(c.key); continue; } if (c.key) seen.add(c.key); const [claimed] = await db .update(runnerCommands) .set({ status: "running", startedAt: new Date() }) .where(and(eq(runnerCommands.id, c.id), eq(runnerCommands.status, "queued"))) .returning(); if (!claimed) continue; if (claimed.key) busyKeys.add(claimed.key); const p = run(claimed).finally(() => { if (claimed.key) busyKeys.delete(claimed.key); inflight.delete(p); void drain(); // the next command with this key }); inflight.add(p); } if (now - lastCleanup > 60 * 60 * 1000) { lastCleanup = now; await db.delete(runnerCommands).where(and(inArray(runnerCommands.status, ["done", "failed", "expired"]), lt(runnerCommands.createdAt, new Date(now - DAY)))); } }; async function drain(): Promise { if (stopped) return; if (draining) { again = true; return; } draining = true; try { do { again = false; await drainOnce().catch((e) => log(`runner service: ${(e as Error).message}`)); } while (again && !stopped); } finally { draining = false; } } const path = runnerSocket(); rmSync(path, { force: true }); // left over from a crashed run const server: Server = createServer((sock) => { sock.on("data", () => void drain()); sock.on("error", () => {}); }); await new Promise((resolve, reject) => { server.once("error", reject); server.listen(path, resolve); }); const timer = setInterval(() => void drain(), o.pollMs ?? 500); timer.unref(); log(`runner service listening on ${path}`); void drain(); return { drain: async () => { await drain(); await Promise.all([...inflight]); }, stop: async () => { stopped = true; clearInterval(timer); await new Promise((resolve) => server.close(() => resolve())); rmSync(path, { force: true }); await Promise.all([...inflight]); }, }; } /** Recent commands for `peppa runner commands`. */ export async function recentRunnerCommands(db: Db, limit = 20) { return db.select().from(runnerCommands).orderBy(desc(runnerCommands.id)).limit(limit); }