// PEP-21: the client side of the runner service. Web, bot and the remote MCP are "clients": // they never start, stop or type into agent tmux sessions themselves — they enqueue a // command in `runner_commands`, poke the service over a unix socket and wait for the result. // The service lives in the watchdog process (runner-service.ts). import { m } from "@peppa/shared/i18n"; import { AsyncLocalStorage } from "node:async_hooks"; import { connect } from "node:net"; import { existsSync } from "node:fs"; import { join } from "node:path"; import { and, eq } from "drizzle-orm"; import { currentActor, PeppaError } from "@peppa/core"; import { runnerCommands, type Db } from "@peppa/db"; import { peppaHome } from "@peppa/shared"; export const runnerSocket = () => join(peppaHome(), "runner.sock"); const CLIENT_FLAG = Symbol.for("peppa.runnerClient"); const DB_KEY = Symbol.for("peppa.runnerClientDb"); const SERVICE_CTX = Symbol.for("peppa.runnerServiceCtx"); type G = { [CLIENT_FLAG]?: boolean; [DB_KEY]?: Db; [SERVICE_CTX]?: AsyncLocalStorage }; const g = globalThis as G; const serviceCtx = (g[SERVICE_CTX] ??= new AsyncLocalStorage()); /** Runs `fn` as the runner service: lifecycle calls inside run here, never re-enqueued. */ export function runAsRunnerService(fn: () => T): T { return serviceCtx.run(true, fn); } /** * Declares this process a client of the runner service (web: instrumentation.ts, bot: its * bin). Kept on globalThis — Next loads instrumentation and server actions as separate * bundles of one process. `PEPPA_RUNNER_MODE=inline` is the escape hatch: run in-process * as before PEP-21. `db` is used by the tmux safety net, which has no db of its own. */ export function setRunnerClient(on: boolean, db?: Db): void { g[CLIENT_FLAG] = on && process.env.PEPPA_RUNNER_MODE !== "inline"; if (db) g[DB_KEY] = db; } export function isRunnerClient(): boolean { return g[CLIENT_FLAG] === true && !serviceCtx.getStore(); } export function runnerClientDb(): Db { const db = g[DB_KEY]; if (!db) throw new PeppaError(m("Служба запуска агентов не настроена (нет базы)")); return db; } /** The runner service failed to take or finish a command (not a domain error). */ export class RunnerUnavailableError extends PeppaError {} const SERVICE_HINT = m("Попробуйте через минуту или напишите администратору."); /** Pokes the service; false when nobody listens on the socket (service not running). */ export function pokeRunner(): Promise { return new Promise((resolve) => { const path = runnerSocket(); if (!existsSync(path)) return resolve(false); const sock = connect(path); sock.setTimeout(500, () => (sock.destroy(), resolve(false))); // Connected = someone listens; the poke is in the kernel buffer once written. sock.on("connect", () => sock.end("poke\n", () => (sock.destroy(), resolve(true)))); sock.on("error", () => resolve(false)); }); } /** Whether the runner service answers on its socket (CLI fallback, `peppa status`). */ export const runnerServiceAlive = (): Promise => pokeRunner(); export interface CallOptions { /** Serialization key: commands with the same key run one after another. */ key?: string | null; /** How long the service may take to pick the command up (default 15 s). */ pickupMs?: number; /** How long to wait for the result once it runs (default 120 s). */ timeoutMs?: number; } const sec = (env: string | undefined, def: number) => (env && Number(env) > 0 ? Number(env) * 1000 : def); /** * Enqueues a command and waits for its result. Errors are never silent: the service not * running or not picking the command up expires it (it will not run later) and throws; * a domain error from the service comes back as a PeppaError with the same text. */ export async function runnerCall(db: Db, kind: string, payload: Record, o: CallOptions = {}): Promise { const pickupMs = o.pickupMs ?? sec(process.env.PEPPA_RUNNER_PICKUP_SEC, 15_000); const timeoutMs = o.timeoutMs ?? sec(process.env.PEPPA_RUNNER_TIMEOUT_SEC, 120_000); const actor = currentActor(); const [row] = await db .insert(runnerCommands) .values({ kind, payload, key: o.key ?? null, actor: actor ? { ...actor } : null }) .returning({ id: runnerCommands.id }); const id = row!.id; const expire = async () => (await db .update(runnerCommands) .set({ status: "expired", finishedAt: new Date() }) .where(and(eq(runnerCommands.id, id), eq(runnerCommands.status, "queued"))) .returning({ id: runnerCommands.id })).length > 0; if (!(await pokeRunner())) { if (await expire()) throw new RunnerUnavailableError(m("Агенты сейчас не запускаются: служба запуска не работает. {hint}", { hint: SERVICE_HINT })); } const started = Date.now(); let runningSince: number | null = null; for (let delay = 20; ; delay = Math.min(delay * 2, 100)) { await new Promise((r) => setTimeout(r, delay)); const [c] = await db.select().from(runnerCommands).where(eq(runnerCommands.id, id)); if (!c) throw new RunnerUnavailableError(m("Запрос к службе запуска агентов #{id} пропал", { id })); if (c.status === "done") return c.result as T; if (c.status === "failed") { if (c.errorKind === "peppa") throw new PeppaError(c.error ?? m("ошибка")); throw new RunnerUnavailableError(m("Служба запуска агентов: {error}", { error: c.error ?? m("ошибка") })); } if (c.status === "expired") throw new RunnerUnavailableError(m("Запрос к службе запуска агентов #{id} устарел — не выполнен", { id })); if (c.status === "queued" && Date.now() - started > pickupMs) { if (await expire()) throw new RunnerUnavailableError(m("Служба запуска агентов не ответила за {n} с — действие не выполнено. {hint}", { n: Math.round(pickupMs / 1000), hint: SERVICE_HINT })); } if (c.status === "running") { runningSince ??= Date.now(); if (Date.now() - runningSince > timeoutMs) throw new RunnerUnavailableError(m("Действие «{kind}» выполняется дольше {n} с — результат появится на странице", { kind, n: Math.round(timeoutMs / 1000) })); } } }