peppa/packages/runner/src/exec.ts
Асель ca57f9543b PEP-17/40: agent sandbox per runner (docker + agent relay) and runner hosts over SSH
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 07:57:28 +05:00

129 lines
5.3 KiB
TypeScript

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