Красные проверки: все тесты кадра терминала в CI ждали первый кадр, tmux-сервер после этого пропадал. Запрос размера pane снова прежний (один display-message), строка статуса читается отдельно, с таймаутом, раз в секунду и без ожидания; сбой — кадр без строки и одно предупреждение в журнал. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
247 lines
12 KiB
TypeScript
247 lines
12 KiB
TypeScript
import { readFileSync } from "node:fs";
|
|
import { HostUnreachable, runOn, type HostTarget } from "./exec.ts";
|
|
import { isRunnerClient, runnerCall, runnerClientDb } from "./runner-client.ts";
|
|
import { renderStatusLine } from "./tmux-status.ts";
|
|
|
|
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] : []);
|
|
|
|
/**
|
|
* PEP-256: on the server the agents' tmux server is its own long-lived container (`peppa-tmux`),
|
|
* and the watchdog and the web are only clients of its socket — a platform deploy recreates them
|
|
* without killing the agents. Then a client must never start a server of its own (it would die
|
|
* with the next deploy, taking its agents along), and pane pids belong to another pid namespace.
|
|
*/
|
|
export const externalTmuxServer = () => process.env.PEPPA_TMUX_EXTERNAL === "1";
|
|
export const TMUX_SERVER_DOWN = "the agents' tmux server (peppa-tmux) is not running";
|
|
|
|
/**
|
|
* 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<string> {
|
|
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;
|
|
}
|
|
|
|
/**
|
|
* 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.
|
|
*/
|
|
async function viaService(op: string, args: unknown[]): Promise<void> {
|
|
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<string, string>;
|
|
width?: number;
|
|
}
|
|
|
|
/**
|
|
* PEP-69: names that must never come from a tmux server's global environment. Every session
|
|
* inherits it, and a server started by some test run or tool shell carries that process's
|
|
* GITEA_*, PEPPA_*, DATABASE_URL, MOCK_* — agents and their MCP then talk to the wrong place.
|
|
* What an agent needs is passed per session (`new-session -e`) or read from `.env`.
|
|
*/
|
|
const FOREIGN_ENV = /^(GITEA_|PEPPA_|MOCK_|DATABASE_URL$)/;
|
|
|
|
/** Foreign variables in the global environment of the tmux server (default server only). */
|
|
export async function foreignServerEnv(p: Pane = { name: "" }, opts: { anySocket?: boolean } = {}): Promise<string[]> {
|
|
// A dedicated socket (-L, tests) is its owner's own server: nothing foreign in it.
|
|
if (process.env.PEPPA_TMUX_SOCKET && !opts.anySocket) return [];
|
|
let out: string;
|
|
try {
|
|
out = await tmuxOn(p, ["show-environment", "-g"]);
|
|
} catch (e) {
|
|
if (e instanceof HostUnreachable) throw e;
|
|
return []; // no server running
|
|
}
|
|
return out.split("\n").map((l) => l.split("=")[0]!.trim()).filter((k) => FOREIGN_ENV.test(k));
|
|
}
|
|
|
|
/** Removes them from the server's global environment; returns the names removed. */
|
|
export async function scrubServerEnv(p: Pane = { name: "" }, opts: { anySocket?: boolean } = {}): Promise<string[]> {
|
|
const names = await foreignServerEnv(p, opts);
|
|
for (const n of names) await tmuxOn(p, ["set-environment", "-g", "-u", n]);
|
|
return names;
|
|
}
|
|
|
|
export async function newSession(s: NewTmuxSession): Promise<void> {
|
|
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 };
|
|
if (externalTmuxServer() && !s.host) {
|
|
// PEP-256: the server is `tmux -D` in peppa-tmux (exit-empty off). No server — fail, do not
|
|
// start one here: `show-options` never starts a server, `start-server`/`new-session` would.
|
|
await tmuxOn(p, ["show-options", "-s", "-v", "exit-empty"]).catch((e) => {
|
|
throw new Error(`${TMUX_SERVER_DOWN}: ${(e as Error).message.trim()}`);
|
|
});
|
|
} else {
|
|
// 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 tmuxOn(p, ["start-server", ";", "set-option", "-s", "exit-empty", "off"]);
|
|
}
|
|
await scrubServerEnv(p).catch(() => {}); // PEP-69
|
|
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 tmuxOn(p, ["set-option", "-t", s.name, "remain-on-exit", "on"]);
|
|
await tmuxOn(p, ["set-option", "-t", s.name, "history-limit", "20000"]);
|
|
}
|
|
|
|
/** False only when tmux says there is no such session; an unreachable host throws (state unknown). */
|
|
export async function hasSession(p: Pane): Promise<boolean> {
|
|
try {
|
|
await tmuxOn(p, ["has-session", "-t", `=${paneName(p)}`]);
|
|
return true;
|
|
} catch (e) {
|
|
if (e instanceof HostUnreachable) throw e;
|
|
return false;
|
|
}
|
|
}
|
|
|
|
export interface PaneState {
|
|
dead: boolean;
|
|
exitStatus: number | null;
|
|
}
|
|
|
|
export async function paneState(p: Pane): Promise<PaneState> {
|
|
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 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 };
|
|
// PEP-256: an external server's pane pid is in its container's pid namespace, not ours.
|
|
const zombie = paneHost(p) || externalTmuxServer() ? undefined : zombieExitStatus(Number(pid));
|
|
if (zombie !== undefined || attempt >= 10) return { dead: true, exitStatus: zombie ?? null };
|
|
await new Promise((r) => setTimeout(r, 100));
|
|
}
|
|
}
|
|
|
|
/** Exit code of a not-yet-reaped process from /proc (Linux); null if it died by a signal. */
|
|
function zombieExitStatus(pid: number): number | null | undefined {
|
|
try {
|
|
const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
|
|
const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
|
|
if (fields[0] !== "Z") return undefined;
|
|
const wait = Number(fields[49]); // field 52: exit_code, in waitpid() format
|
|
return (wait & 0x7f) === 0 ? (wait >> 8) & 0xff : null;
|
|
} catch {
|
|
return undefined;
|
|
}
|
|
}
|
|
|
|
/** Visible screen (plus `history` lines of scrollback) as plain text. */
|
|
export async function capturePane(p: Pane, history = 0): Promise<string> {
|
|
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(p: Pane, text: string, submit = true): Promise<void> {
|
|
if (isRunnerClient()) return viaService("sendText", [p, text, submit]);
|
|
const name = paneName(p);
|
|
const buffer = `peppa-${process.pid}-${Date.now()}`;
|
|
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 tmuxOn(p, ["send-keys", "-t", `=${name}:`, "Enter"]);
|
|
}
|
|
}
|
|
|
|
/** Sends tmux key names (e.g. "1", "Enter", "Escape", "C-c"). */
|
|
export async function sendKeys(p: Pane, ...keys: string[]): Promise<void> {
|
|
if (isRunnerClient()) return viaService("sendKeys", [p, ...keys]);
|
|
await tmuxOn(p, ["send-keys", "-t", `=${paneName(p)}:`, ...keys]);
|
|
}
|
|
|
|
export async function killSession(p: Pane): Promise<void> {
|
|
if (isRunnerClient()) return viaService("killSession", [p]);
|
|
await tmuxOn(p, ["kill-session", "-t", `=${paneName(p)}`]);
|
|
}
|
|
|
|
export interface PaneInfo {
|
|
cols: number;
|
|
rows: number;
|
|
cursorX: number;
|
|
cursorY: number;
|
|
cursorVisible: boolean;
|
|
/** Lines in the pane's scrollback; grows when lines scroll off the top (PEP-9). */
|
|
historySize: number;
|
|
}
|
|
|
|
/** Size, cursor and scrollback length of the session's active pane. */
|
|
export async function paneInfo(p: Pane): Promise<PaneInfo> {
|
|
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! };
|
|
}
|
|
|
|
/** Status lines tmux can have (`status` on | 2..5). */
|
|
const STATUS_MAX = 5;
|
|
|
|
/** PEP-257: tmux status lines of a session — rendered to SGR on `cols` cells, and where they go. */
|
|
export interface StatusLines {
|
|
top: boolean;
|
|
lines: string[];
|
|
}
|
|
|
|
/**
|
|
* PEP-257: the status lines as an attached client sees them — tmux expands its own
|
|
* `status-format[i]` (`#{T:…}`), the `#[…]` styles become SGR on `cols` cells; `status off` —
|
|
* none. Separate, time-limited calls: the picture of the pane never waits for them.
|
|
*/
|
|
export async function statusLines(p: Pane, cols: number, timeoutMs = 2000): Promise<StatusLines> {
|
|
const t = `=${paneName(p)}:`;
|
|
const show = (f: string) => runTmux(p, ["display-message", "-p", "-t", t, f], timeoutMs).then((o) => o.replace(/\n$/, ""));
|
|
const [status, position] = (await show("#{status} #{status-position}")).trim().split(" ");
|
|
const n = status === "on" ? 1 : !status || status === "off" ? 0 : Math.min(Number(status) || 0, STATUS_MAX);
|
|
if (!n) return { top: false, lines: [] };
|
|
const style = await show("#{E:status-style}");
|
|
const lines: string[] = [];
|
|
for (let i = 0; i < n; i++) lines.push(renderStatusLine(await show(`#{T:status-format[${i}]}`), cols, style));
|
|
return { top: position === "top", lines };
|
|
}
|
|
|
|
async function runTmux(p: Pane, args: string[], timeoutMs: number): Promise<string> {
|
|
const host = paneHost(p);
|
|
const { stdout } = await runOn(host, [host ? "tmux" : TMUX(), ...SOCKET(), ...args], { timeoutMs });
|
|
return stdout;
|
|
}
|
|
|
|
/**
|
|
* 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(p: Pane, start: number | "-", end?: number): Promise<string> {
|
|
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(p: Pane, bytes: Uint8Array): Promise<void> {
|
|
if (!bytes.length) return;
|
|
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"))]);
|
|
}
|