166 lines
7.6 KiB
TypeScript
166 lines
7.6 KiB
TypeScript
import { readFileSync } from "node:fs";
|
|
import { HostUnreachable, runOn, type HostTarget } from "./exec.ts";
|
|
import { isRunnerClient, runnerCall, runnerClientDb } from "./runner-client.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] : []);
|
|
|
|
/**
|
|
* 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;
|
|
}
|
|
|
|
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 };
|
|
// 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 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 };
|
|
const zombie = paneHost(p) ? 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! };
|
|
}
|
|
|
|
/**
|
|
* 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"))]);
|
|
}
|