Cotton code
345 lines · 11.9 KB · RustRaw
//! The pseudo-terminal: one per session, owned by this process.//!//! WHY A REAL PSEUDO-TERMINAL AND NOT THE AGENTS' STRUCTURED FACES. Both//! agents have one (`claude -p --output-format stream-json`, Codex's//! `app-server`), and an editor that uses it gives up the interactive surface://! plugins, slash commands, subagents, the TUI. The rule is that nothing is//! given up relative to a terminal, so the interactive binary runs unmodified//! in a real pseudo-terminal — and every fact about what it is DOING comes//! from its own hook system, never from these bytes.//!//! This module is the supervision, separated from the socket the way//! `cotton-client`'s `backup/process.rs` is separated from its runtime: the//! schedule, the resize and the exit are testable against `/bin/sh`, with no//! daemon around them.//!//! **macOS answers `EIO`, not end-of-file.** When the last slave descriptor//! closes, a read of the master on macOS fails with `EIO` where Linux returns//! `Ok(0)`. Both mean the same thing — the child hung up — and//! [`is_hangup`] is the one place that says so.use std::collections::BTreeMap;use std::path::Path;use std::sync::Arc;use std::time::Duration;use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};use tokio::sync::{mpsc, watch, Mutex};/// How much terminal output one read hands over.////// The design's frame cap on the phone's own hop is 16 KiB; this is four of/// them, so a busy build fills a socket line rather than a thousand of them,/// and a `data` line stays two orders of magnitude below/// [`crate::protocol::MAX_LINE_BYTES`].pub const READ_CHUNK_BYTES: usize = 64 * 1024;/// The three signals a stop sends, and how long it waits between them.////// SIGINT first, because both agents treat it as "stop what you are doing" and/// save their transcript; SIGTERM when the interrupt did not take; SIGKILL/// when nothing else did. A stop that waited for ever would be a card on the/// phone with a button that does nothing.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct StopSchedule {    /// How long SIGINT gets.    pub interrupt_grace: Duration,    /// How long SIGTERM gets after that.    pub terminate_grace: Duration,}impl Default for StopSchedule {    fn default() -> Self {        Self {            interrupt_grace: Duration::from_secs(10),            terminate_grace: Duration::from_secs(10),        }    }}/// `SIGINT`.const SIGINT: i32 = 2;/// `SIGTERM`.const SIGTERM: i32 = 15;/// `SIGKILL`.const SIGKILL: i32 = 9;/// What a stop had to reach for.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum StoppedBy {    /// It was already gone.    AlreadyGone,    /// SIGINT was enough.    Interrupt,    /// SIGTERM was needed.    Terminate,    /// SIGKILL was needed.    Kill,}/// How a child went away.#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]pub struct Exited {    /// Its exit code, when it had one.    pub code: Option<i32>,    /// The signal that ended it, when one did.    pub signal: Option<i32>,}/// What can go wrong starting or driving one.#[derive(Debug, thiserror::Error)]pub enum PtyError {    /// The pseudo-terminal itself.    #[error("this Mac would not open a pseudo-terminal — {0}")]    Open(String),    /// The child.    #[error("{program} would not start in {cwd} — {said}")]    Spawn {        /// What we tried to run.        program: String,        /// Where.        cwd: String,        /// Why not. Named `said` rather than `source`: thiserror reads a        /// field called `source` as an error to chain, and this is a sentence        /// the operating system produced.        said: String,    },    /// Writing to, resizing or reading the master side.    #[error("the pseudo-terminal: {0}")]    Io(#[from] std::io::Error),}/// Everything needed to start one.#[derive(Debug, Clone, PartialEq, Eq)]pub struct SpawnPlan {    /// The program and its arguments. `argv[0]` is the program.    pub argv: Vec<String>,    /// The child's whole environment: nothing of this process's is inherited.    pub env: BTreeMap<String, String>,    /// The working directory.    pub cwd: String,    /// Terminal width.    pub cols: u16,    /// Terminal height.    pub rows: u16,}/// A running pseudo-terminal and the process inside it.////// ONE TASK WAITS ON THE CHILD, and everybody else reads what it saw. A/// `Child` can only be awaited once, so a supervisor that let both the stop/// path and the serve loop call `wait` would have them contend for the handle/// — and a stop blocked behind somebody else's wait would report SIGKILL for a/// child SIGINT had already ended. The waiter publishes to a watch channel;/// `wait` and `stop` observe it.#[derive(Debug)]pub struct PtySession {    write: Arc<Mutex<pty_process::OwnedWritePty>>,    exit: watch::Receiver<Option<Exited>>,    pid: Option<u32>,}impl PtySession {    /// Start `plan`, streaming everything the child writes into `output`.    ///    /// The reader task ends on a hangup and drops `output`, which is how the    /// caller learns the terminal is finished without polling anything.    pub fn spawn(        plan: &SpawnPlan,        output: mpsc::UnboundedSender<Vec<u8>>,    ) -> Result<Self, PtyError> {        let Some(program) = plan.argv.first() else {            return Err(PtyError::Spawn {                program: String::new(),                cwd: plan.cwd.clone(),                said: "the spawn plan named no program at all".to_string(),            });        };        let (pty, pts) = pty_process::open().map_err(|error| PtyError::Open(error.to_string()))?;        pty.resize(pty_process::Size::new(plan.rows, plan.cols))            .map_err(|error| PtyError::Open(error.to_string()))?;        // THE PLAN'S ENVIRONMENT AND NOTHING ELSE. This process was started by        // launchd (or a test, or a terminal), and what it was handed is not        // what a session was declared to have (`launch_env`, `login_env`):        // inherited underneath, it would decide which program a session finds        // whenever the plan said nothing.        let mut command = pty_process::Command::new(program)            .args(&plan.argv[1..])            .env_clear();        for (name, value) in &plan.env {            command = command.env(name, value);        }        command = command.current_dir(Path::new(&plan.cwd));        // NOT `kill_on_drop`: this host owns the stop schedule, and a dropped        // handle killing an agent mid-turn is exactly the surprise        // `StopSchedule` exists to replace.        command = command.kill_on_drop(false);        let child = command.spawn(pts).map_err(|error| PtyError::Spawn {            program: program.clone(),            cwd: plan.cwd.clone(),            said: error.to_string(),        })?;        let pid = child.id();        let (exited_to, exit) = watch::channel(None);        tokio::spawn(async move {            let mut child = child;            let seen = match child.wait().await {                Ok(status) => exited(&status),                // The child is gone and the operating system would not say                // how. An honest unknown — never a fabricated 0.                Err(_) => Exited::default(),            };            let _ = exited_to.send(Some(seen));        });        let (mut read, write) = pty.into_split();        tokio::spawn(async move {            let mut buffer = vec![0u8; READ_CHUNK_BYTES];            loop {                match read.read(&mut buffer).await {                    // End of file on Linux.                    Ok(0) => return,                    Ok(taken) => {                        if output.send(buffer[..taken].to_vec()).is_err() {                            return;                        }                    }                    Err(error) if is_hangup(&error) => return,                    Err(_) => return,                }            }        });        Ok(Self {            write: Arc::new(Mutex::new(write)),            exit,            pid,        })    }    /// The child's pid, while it has one.    pub fn pid(&self) -> Option<u32> {        self.pid    }    /// Type at it.    pub async fn write(&self, bytes: &[u8]) -> Result<(), PtyError> {        let mut write = self.write.lock().await;        write.write_all(bytes).await?;        write.flush().await?;        Ok(())    }    /// Tell the child the window changed — `TIOCSWINSZ`, and the `SIGWINCH`    /// the kernel sends with it.    pub async fn resize(&self, cols: u16, rows: u16) -> Result<(), PtyError> {        self.write            .lock()            .await            .resize(pty_process::Size::new(rows, cols))            .map_err(|error| PtyError::Open(error.to_string()))    }    /// Wait for the child. Any number of callers may.    pub async fn wait(&self) -> Exited {        let mut exit = self.exit.clone();        loop {            if let Some(seen) = *exit.borrow_and_update() {                return seen;            }            if exit.changed().await.is_err() {                // The waiter task is gone without having sent — which it                // cannot do — so there is nothing left to learn.                return Exited::default();            }        }    }    /// Whether the child has already gone, without waiting for it.    pub fn finished(&self) -> Option<Exited> {        *self.exit.borrow()    }    /// End it: SIGINT, then SIGTERM, then SIGKILL, on `schedule`.    ///    /// Bounded at every step, and the step it needed is the answer — a stop    /// that had to reach SIGKILL is a fact worth logging, not a detail.    pub async fn stop(&self, schedule: StopSchedule) -> Result<StoppedBy, PtyError> {        let Some(pid) = self.pid else {            return Ok(StoppedBy::AlreadyGone);        };        if self.finished().is_some() {            return Ok(StoppedBy::AlreadyGone);        }        signal(pid, SIGINT);        if self.gone_within(schedule.interrupt_grace).await {            return Ok(StoppedBy::Interrupt);        }        signal(pid, SIGTERM);        if self.gone_within(schedule.terminate_grace).await {            return Ok(StoppedBy::Terminate);        }        signal(pid, SIGKILL);        // No wait after SIGKILL: the kernel does not negotiate, and the        // reaping happens in `wait`, which somebody is already in.        Ok(StoppedBy::Kill)    }    async fn gone_within(&self, grace: Duration) -> bool {        tokio::time::timeout(grace, self.wait()).await.is_ok()    }}/// Whether the read error means the child hung up.////// macOS raises `EIO` on the master when the last slave descriptor closes;/// Linux returns `Ok(0)`. One place says both mean the same thing.pub fn is_hangup(error: &std::io::Error) -> bool {    error.raw_os_error() == Some(libc::EIO) || error.kind() == std::io::ErrorKind::UnexpectedEof}/// Split an exit status into the two things anybody asks about it.pub fn exited(status: &std::process::ExitStatus) -> Exited {    #[cfg(unix)]    {        use std::os::unix::process::ExitStatusExt as _;        Exited {            code: status.code(),            signal: status.signal(),        }    }    #[cfg(not(unix))]    {        Exited {            code: status.code(),            signal: None,        }    }}/// Is that pid a process that still exists?////// `kill(pid, 0)`, which is the question without the verb.pub fn alive(pid: u32) -> bool {    // SAFETY: `kill(2)` with signal 0 sends nothing; it asks whether the    // process exists and whether we may signal it. A reaped pid answers    // ESRCH, which is the state we were asking about.    unsafe { libc::kill(pid as libc::pid_t, 0) == 0 }}fn signal(pid: u32, signal: i32) {    // SAFETY: `kill(2)` with a pid this process spawned and a constant signal.    // A pid already reaped answers ESRCH, which is the state we wanted anyway.    unsafe {        let _ = libc::kill(pid as libc::pid_t, signal);    }}#[cfg(test)]#[path = "pty_tests.rs"]mod pty_tests;