rho-coding-agent 3.10.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! A stdio server's process as a probe runs it: the end of its standard
//! error kept and its exit status read, so a server that fails to start can
//! say why. A session's servers run unwatched, with their standard error
//! discarded, since nothing reads it there.

use std::{
    collections::VecDeque,
    process::ExitStatus,
    sync::{Arc, Mutex, PoisonError},
    time::Duration,
};

use tokio::{
    io::AsyncReadExt,
    process::{Child, ChildStderr},
    task::JoinHandle,
};

/// The most of a server's standard error a probe keeps: its end, which is
/// where a crash's reason is. Measured: a Python import error is 156 bytes,
/// and a traceback through four frames 1,033; this keeps one eight times
/// that size whole.
const STDERR_TAIL_BYTES: usize = 8 * 1024;

/// How long a probe waits for the process to report its exit once it is
/// done with it, and again for its standard error to close once it exited
/// or was killed. Measured: a process's exit is reaped 0.02 ms (at most
/// 0.04 ms in 50 runs) after its output closes, so this only separates a
/// process that exited from one that closed its output and kept running, or
/// one whose child holds its standard error open.
const EXIT_REPORT_GRACE: Duration = Duration::from_secs(1);

/// How a connect runs a stdio server's process.
pub(crate) enum McpStdio {
    /// Its standard error discarded, as a session's servers run.
    Unwatched,
    /// Watched by an `McpStdioWatch`, as a probe runs one.
    Watched(McpStdioWatch),
}

/// The process a probe started, once it started one. Clones share it.
#[derive(Clone, Default)]
pub(crate) struct McpStdioWatch {
    process: Arc<Mutex<Option<WatchedProcess>>>,
}

/// Spawned with `kill_on_drop`, so dropping it stops it.
struct WatchedProcess {
    child: Child,
    stderr: Arc<Mutex<Tail>>,
    /// Ends once its standard error closes.
    stderr_closed: JoinHandle<()>,
}

/// What a watched process left behind.
#[derive(Debug, Default, PartialEq, Eq)]
pub(crate) struct McpStdioReport {
    /// Its exit status, when it exited on its own.
    pub(crate) exit: Option<ExitStatus>,
    /// The end of its standard error, empty when it wrote none.
    pub(crate) stderr: Vec<u8>,
    /// Whether `stderr` was cut from a longer output.
    pub(crate) stderr_cut: bool,
}

/// The end of a process's standard error.
#[derive(Default)]
struct Tail {
    bytes: VecDeque<u8>,
    cut: bool,
}

impl McpStdioWatch {
    /// Watches `child`, whose standard error is `stderr`, keeping the end of
    /// what it writes there.
    pub(crate) fn attach(&self, child: Child, stderr: ChildStderr) {
        let tail = Arc::new(Mutex::new(Tail::default()));
        let stderr_closed = tokio::spawn(keep_tail(stderr, Arc::clone(&tail)));
        *self.lock() = Some(WatchedProcess {
            child,
            stderr: tail,
            stderr_closed,
        });
    }

    /// What the process left: its exit status if it exits within
    /// [`EXIT_REPORT_GRACE`], else it is killed, and its standard error.
    pub(crate) async fn finish(&self) -> McpStdioReport {
        let Some(WatchedProcess {
            mut child,
            stderr,
            mut stderr_closed,
        }) = self.lock().take()
        else {
            return McpStdioReport::default();
        };
        let exit = tokio::time::timeout(EXIT_REPORT_GRACE, child.wait())
            .await
            .ok()
            .and_then(Result::ok);
        drop(child);
        if tokio::time::timeout(EXIT_REPORT_GRACE, &mut stderr_closed)
            .await
            .is_err()
        {
            stderr_closed.abort();
        }
        let tail = std::mem::take(&mut *stderr.lock().unwrap_or_else(PoisonError::into_inner));
        McpStdioReport {
            exit,
            stderr: tail.bytes.into(),
            stderr_cut: tail.cut,
        }
    }

    fn lock(&self) -> std::sync::MutexGuard<'_, Option<WatchedProcess>> {
        self.process.lock().unwrap_or_else(PoisonError::into_inner)
    }
}

/// Reads `stderr` until it closes, keeping its last [`STDERR_TAIL_BYTES`]
/// in `tail`, so a chatty server never blocks on a full pipe.
async fn keep_tail(mut stderr: ChildStderr, tail: Arc<Mutex<Tail>>) {
    let mut buffer = [0u8; 4096];
    while let Ok(read) = stderr.read(&mut buffer).await {
        if read == 0 {
            break;
        }
        let mut tail = tail.lock().unwrap_or_else(PoisonError::into_inner);
        tail.bytes.extend(&buffer[..read]);
        let excess = tail.bytes.len().saturating_sub(STDERR_TAIL_BYTES);
        if excess > 0 {
            tail.bytes.drain(..excess);
            tail.cut = true;
        }
    }
}