peppa/packages/runner/src/hosts.ts
2026-11-15 14:47:50 +05:00

155 lines
7.5 KiB
TypeScript

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