peppa/packages/runner/src/terminal.ts
2026-11-16 09:52:35 +05:00

374 lines
15 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// glossary-ignore-file: терминал агента есть только в виде «Инженер»
// Live runner terminal in the web (PEP-9): the pane is polled with capture-pane (one loop per
// runner, shared by all viewers), changes go out as xterm.js data; input goes back with
// send-keys -H / paste-buffer after access, liveness, size and rate checks.
import { m } from "@peppa/shared/i18n";
import { FINISHED_SESSION_STATUSES, getSession, logSessionEvent, PeppaError, projectForUser, projectSecretMasker, updateSession, type SessionView, type User } from "@peppa/core";
import type { Db } from "@peppa/db";
import * as tmux from "./tmux.ts";
export const TERMINAL_POLL_MS = 250;
/** Lines of pane scrollback sent in the first frame. */
export const TERMINAL_HISTORY_LINES = 1000;
export const TERMINAL_MAX_KEYS_BYTES = 1024;
export const TERMINAL_MAX_PASTE_BYTES = 64 * 1024;
export const TERMINAL_RATE_WINDOW_MS = 5000;
export const TERMINAL_RATE_MAX = 40;
export const TERMINAL_MAX_VIEWERS_PER_USER = 8;
/** One `terminal_input` journal event per user and runner per this interval. */
export const TERMINAL_LOG_EVERY_MS = 60_000;
export type TerminalEvent =
/** Full picture: the client resets xterm, sizes it to cols×rows and writes `data`. */
| { type: "frame"; cols: number; rows: number; data: string }
/** Changes since the previous event. */
| { type: "out"; data: string }
/** The tmux session is gone. */
| { type: "end" };
export type TerminalListener = (e: TerminalEvent) => void;
const SGR = /\x1b\[([0-9;:]*)m/g;
/**
* capture-pane -e carries colours over from line to line; makes every line self-contained by
* prefixing the SGR state accumulated since the last reset. Drops the final newline.
*/
export function normalizeAnsiLines(text: string): string[] {
const raw = text.split("\n");
if (raw.at(-1) === "") raw.pop();
let state: string[] = [];
return raw.map((line) => {
const prefix = state.length ? `\x1b[${state.join(";")}m` : "";
for (const m of line.matchAll(SGR)) {
const p = m[1]!;
if (p === "" || p === "0") state = [];
else if (p.startsWith("0;")) state = [p.slice(2)];
else state = [...state, p].slice(-16);
}
return prefix + line;
});
}
const fit = (lines: string[], rows: number) => (lines.length >= rows ? lines.slice(0, rows) : [...lines, ...Array<string>(rows - lines.length).fill("")]);
const lineAt = (row: number, line: string) => `\x1b[${row + 1};1H\x1b[0m\x1b[2K${line}\x1b[0m`;
const cursor = (i: tmux.PaneInfo) => `\x1b[${i.cursorY + 1};${i.cursorX + 1}H\x1b[?25${i.cursorVisible ? "h" : "l"}`;
/** Polls one tmux session while it has listeners. */
export class TerminalFeed {
readonly name: string;
/** PEP-40: the pane, maybe on a runner host (polled over SSH). */
readonly pane: tmux.Pane;
readonly intervalMs: number;
private listeners = new Set<TerminalListener>();
/** Listeners that still need a full frame. */
private fresh = new Set<TerminalListener>();
private info: tmux.PaneInfo | null = null;
private screen: string[] = [];
private timer: ReturnType<typeof setTimeout> | null = null;
private running = false;
private onIdle: () => void;
/** PEP-54: hides the project's secret values in every line sent to viewers. */
private mask: (line: string) => string;
/** Number of tmux polls so far (tests check that viewers share one loop). */
polls = 0;
constructor(pane: tmux.Pane, opts: { intervalMs?: number; onIdle?: () => void; mask?: (line: string) => string } = {}) {
this.pane = pane;
this.name = typeof pane === "string" ? pane : pane.name;
this.intervalMs = opts.intervalMs ?? TERMINAL_POLL_MS;
this.onIdle = opts.onIdle ?? (() => {});
this.mask = opts.mask ?? ((l) => l);
}
/** New secret values apply from the next poll (a fresh viewer refreshes them). */
setMask(mask: (line: string) => string) {
this.mask = mask;
}
private lines(text: string): string[] {
return normalizeAnsiLines(text).map((l) => this.mask(l));
}
get size() {
return this.listeners.size;
}
subscribe(fn: TerminalListener): () => void {
this.listeners.add(fn);
this.fresh.add(fn);
if (!this.running) {
this.running = true;
this.schedule(0);
} else if (this.timer) {
// Give the newcomer its frame right away instead of waiting for the next poll.
clearTimeout(this.timer);
this.schedule(0);
}
return () => {
this.listeners.delete(fn);
this.fresh.delete(fn);
if (!this.listeners.size) this.stop();
};
}
private stop() {
if (this.timer) clearTimeout(this.timer);
this.timer = null;
this.running = false;
this.info = null;
this.screen = [];
this.onIdle();
}
private schedule(ms: number) {
this.timer = setTimeout(() => {
this.timer = null;
this.tick().then(
() => this.running && !this.timer && this.schedule(this.intervalMs),
() => this.running && !this.timer && this.schedule(this.intervalMs),
);
}, ms);
}
private emit(fns: Iterable<TerminalListener>, e: TerminalEvent) {
for (const fn of fns) {
try {
fn(e);
} catch {
// A broken viewer must not stop the others.
}
}
}
private async tick() {
if (!this.listeners.size) return;
this.polls++;
let info: tmux.PaneInfo;
let screen: string[];
try {
info = await tmux.paneInfo(this.pane);
screen = fit(this.lines(await tmux.capturePaneAnsi(this.pane, 0, info.rows - 1)), info.rows);
} catch (e) {
if (await tmux.hasSession(this.pane)) throw e;
const all = [...this.listeners];
this.listeners.clear();
this.fresh.clear();
this.emit(all, { type: "end" });
this.stop();
return;
}
const prev = this.info;
const resized = !prev || prev.cols !== info.cols || prev.rows !== info.rows;
const old = [...this.listeners].filter((fn) => !this.fresh.has(fn));
const needFrame = resized ? [...this.listeners] : [...this.fresh];
if (old.length && !resized) {
const data = this.diff(prev!, info, screen, await this.scrolled(prev!, info));
if (data) this.emit(old, { type: "out", data });
}
if (needFrame.length) {
const hist = info.historySize ? this.lines(await tmux.capturePaneAnsi(this.pane, -Math.min(info.historySize, TERMINAL_HISTORY_LINES), -1)) : [];
const data = [...hist, ...screen].map((l) => `\x1b[0m${l}`).join("\r\n") + "\x1b[0m" + cursor(info);
this.emit(needFrame, { type: "frame", cols: info.cols, rows: info.rows, data });
for (const fn of needFrame) this.fresh.delete(fn);
}
this.info = info;
this.screen = screen;
}
/** Lines that left the screen for scrollback since the last poll (oldest first); null if none. */
private async scrolled(prev: tmux.PaneInfo, info: tmux.PaneInfo): Promise<string[] | null> {
const k = Math.min(info.historySize - prev.historySize, TERMINAL_HISTORY_LINES);
if (k <= 0) return null;
// Not "the top of the previous screen": output between two polls may first fill the screen
// and then scroll, so the lines are taken from tmux's scrollback itself.
return this.lines(await tmux.capturePaneAnsi(this.pane, -k, -1));
}
private diff(prev: tmux.PaneInfo, info: tmux.PaneInfo, screen: string[], scrolled: string[] | null): string {
let out = "";
if (scrolled) {
// Clear the screen (ED2 keeps xterm's scrollback as is), write the lines from the top
// (beyond the height they scroll out on their own), then scroll the rest out with LFs
// at the bottom row, and redraw the screen.
out += `\x1b[0m\x1b[H\x1b[2J${scrolled.map((l) => `\x1b[0m${l}`).join("\r\n")}\x1b[0m`;
out += `\x1b[${info.rows};1H${"\n".repeat(Math.min(scrolled.length, info.rows))}`;
screen.forEach((l, r) => (out += lineAt(r, l)));
} else {
screen.forEach((l, r) => {
if (l !== this.screen[r]) out += lineAt(r, l);
});
}
const moved = prev.cursorX !== info.cursorX || prev.cursorY !== info.cursorY || prev.cursorVisible !== info.cursorVisible;
return out || moved ? out + cursor(info) : "";
}
}
type Registry = Map<string, TerminalFeed>;
const feeds: Registry = ((globalThis as { __peppaTerminalFeeds?: Registry }).__peppaTerminalFeeds ??= new Map());
/** Subscribes to the live pane of a tmux session; one shared poll loop per session. */
export function watchTerminal(pane: tmux.Pane, fn: TerminalListener, opts: { mask?: (line: string) => string } = {}): () => void {
const name = typeof pane === "string" ? pane : pane.name;
let feed = feeds.get(name);
if (!feed) {
const created = new TerminalFeed(pane, { onIdle: () => feeds.get(name) === created && feeds.delete(name), mask: opts.mask });
feeds.set(name, created);
feed = created;
} else if (opts.mask) feed.setMask(opts.mask);
return feed.subscribe(fn);
}
/** The shared feed of a session, if someone watches it (tests). */
export const terminalFeed = (name: string) => feeds.get(name);
/** An error with an HTTP status for the web route. */
export class TerminalError extends PeppaError {
readonly status: number;
constructor(status: number, message: string) {
super(message);
this.status = status;
}
}
/** The session if the user owns or shares its project; 404 otherwise (no existence leak). */
export async function terminalSession(db: Db, user: User, sessionId: number): Promise<SessionView> {
try {
const s = await getSession(db, sessionId);
await projectForUser(db, user.id, s.projectId);
return s;
} catch (e) {
if (e instanceof PeppaError) throw new TerminalError(404, m("Не найдено"));
throw e;
}
}
const viewers = new Map<number, number>();
/** Counts an open stream of the user; throws 429 above the limit. Returns the release. */
export function acquireViewer(userId: number): () => void {
const n = viewers.get(userId) ?? 0;
if (n >= TERMINAL_MAX_VIEWERS_PER_USER) throw new TerminalError(429, m("Слишком много открытых терминалов"));
viewers.set(userId, n + 1);
let done = false;
return () => {
if (done) return;
done = true;
const left = (viewers.get(userId) ?? 1) - 1;
if (left > 0) viewers.set(userId, left);
else viewers.delete(userId);
};
}
const hits = new Map<string, number[]>();
const lastLogged = new Map<string, number>();
function rateCheck(key: string, now: number) {
const recent = (hits.get(key) ?? []).filter((t) => now - t < TERMINAL_RATE_WINDOW_MS);
if (recent.length >= TERMINAL_RATE_MAX) {
hits.set(key, recent);
throw new TerminalError(429, m("Слишком часто — подождите пару секунд"));
}
recent.push(now);
hits.set(key, recent);
}
export interface TerminalInput {
/** Bytes typed in xterm (`onData`), sent to the pane as they are. */
keys?: string;
/** Pasted text: one bracketed paste, not line by line. */
paste?: string;
}
/**
* Human input into a runner's pane: only for owners/members, only into a live session, within
* size and rate limits. Resets the auto-continue counter and notes it in the session journal.
*/
export async function terminalInput(db: Db, user: User, sessionId: number, input: TerminalInput, now = Date.now()): Promise<void> {
const s = await terminalSession(db, user, sessionId);
const keys = typeof input.keys === "string" ? input.keys : "";
const paste = typeof input.paste === "string" ? input.paste : "";
if (!keys && !paste) throw new TerminalError(400, m("Пустой ввод"));
const keyBytes = Buffer.from(keys, "utf8");
if (keyBytes.length > TERMINAL_MAX_KEYS_BYTES) throw new TerminalError(413, m("Слишком длинный ввод"));
if (Buffer.byteLength(paste, "utf8") > TERMINAL_MAX_PASTE_BYTES) throw new TerminalError(413, m("Слишком длинная вставка"));
if (FINISHED_SESSION_STATUSES.includes(s.status)) throw new TerminalError(409, m("Сессия завершена"));
rateCheck(`${user.id}:${s.id}`, now);
if (!(await tmux.hasSession(tmux.sessionPane(s)))) throw new TerminalError(409, m("Раннер не запущен"));
if (paste) await tmux.sendText(tmux.sessionPane(s), paste, false);
if (keyBytes.length) await tmux.sendHex(tmux.sessionPane(s), keyBytes);
// A human took over: the Stop hook may nudge the agent again from zero (PEP-7).
if (s.autoNudges > 0) await updateSession(db, s.id, { autoNudges: 0 });
const logKey = `${user.id}:${s.id}`;
if (now - (lastLogged.get(logKey) ?? -Infinity) >= TERMINAL_LOG_EVERY_MS) {
lastLogged.set(logKey, now);
await logSessionEvent(db, s, "terminal_input", { login: user.login });
}
}
export const TERMINAL_PING_MS = 15_000;
/**
* Server-Sent Events stream of a runner's terminal: `frame` / `out` / `end` events with JSON
* data, a comment ping every 15 s (Cloudflare closes silent connections after 100 s).
* Access is checked before anything is sent; the stream ends when `signal` aborts.
*/
export async function terminalSse(db: Db, user: User, sessionId: number, signal: AbortSignal, opts: { pingMs?: number } = {}): Promise<Response> {
const s = await terminalSession(db, user, sessionId);
const mask = await projectSecretMasker(db, s.projectId);
const release = acquireViewer(user.id);
const enc = new TextEncoder();
let cleanup = () => {};
const body = new ReadableStream<Uint8Array>({
start(controller) {
let closed = false;
const send = (chunk: string) => {
if (closed) return;
try {
controller.enqueue(enc.encode(chunk));
} catch {
close();
}
};
const ping = setInterval(() => send(": ping\n\n"), opts.pingMs ?? TERMINAL_PING_MS);
let unsubscribe = () => {};
const close = () => {
if (closed) return;
closed = true;
clearInterval(ping);
unsubscribe();
release();
signal.removeEventListener("abort", close);
try {
controller.close();
} catch {
// already closed by the client
}
};
cleanup = close;
signal.addEventListener("abort", close);
// Tells EventSource how long to wait before reconnecting.
send("retry: 3000\n\n");
if (signal.aborted) return close();
unsubscribe = watchTerminal(tmux.sessionPane(s), (e) => {
send(`event: ${e.type}\ndata: ${JSON.stringify(e.type === "end" ? {} : e)}\n\n`);
if (e.type === "end") close();
}, { mask });
},
cancel() {
cleanup();
},
});
return new Response(body, {
headers: {
"Content-Type": "text/event-stream; charset=utf-8",
"Cache-Control": "no-cache, no-transform",
"X-Accel-Buffering": "no",
Connection: "keep-alive",
},
});
}