rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! The `rho/host/shell/*` host calls on the daemon's machine
//! (`docs/protocol.md`, "A shell on the daemon's machine"): a terminal's
//! shell for a person's frontend, as ssh would start one, which rho-ui ran
//! over ssh and through `rho-ui serve` before.
//!
//! This module answers the calls and keeps each connection's shells;
//! `terminal.rs` runs one under a pseudo-terminal. A shell's output stream
//! names it, and stream ids repeat across connections, so shells are kept
//! by connection and id. Each open and end is logged with who made it and
//! the folder, never what is typed or printed.

use std::{
    collections::HashMap,
    path::PathBuf,
    sync::{Arc, Mutex, MutexGuard},
};

use rho_protocol::{
    methods::{
        HostShellForegroundParams, HostShellForegroundResponse, HostShellInputParams,
        HostShellInputResponse, HostShellOpenParams, HostShellOpenResponse, HostShellResizeParams,
        HostShellResizeResponse, HostStreamId, ShellInputLimit, HOST_SHELL_INPUT_MAX_BYTES,
        HOST_SHELL_OPEN,
    },
    Caller, ClientEnvironment, ConnectionId, ErrorCode, RpcError, ShellService, StreamPacing,
};

use super::machine::{absolute, blocking, failed, log_call, Machine};

mod terminal;

use terminal::{Ending, Handle, InputFull, Spawn, Terminal};

impl ShellService for Machine {
    async fn open(
        &self,
        caller: Caller,
        params: HostShellOpenParams,
    ) -> Result<HostShellOpenResponse, RpcError> {
        let HostShellOpenParams {
            cwd,
            term,
            columns,
            rows,
            variables,
            ..
        } = params;
        log_call(&caller, HOST_SHELL_OPEN, [&cwd]);
        let folder = absolute(&cwd)?.to_path_buf();
        let login = self.login_environment().await;
        let (program, args) = self.shell_program(&login);
        let environment: ClientEnvironment = login
            .into_iter()
            .chain([("TERM".to_owned(), term)])
            .chain(variables)
            .collect();
        // Opened first, so a connection at its limit starts no shell; the
        // call closes it if the shell does not start.
        let output = caller.open_stream_paced(StreamPacing::Interactive)?;
        let shell = output.id().clone();
        let spawn = Spawn {
            program,
            args,
            folder,
            environment,
            columns: columns.get(),
            rows: rows.get(),
        };
        let (terminal, handle) = blocking(move || {
            if !spawn.folder.is_dir() {
                anyhow::bail!("it isn't a folder");
            }
            Terminal::start(spawn)
        })
        .await?
        .map_err(|error| failed(format!("the shell did not start in {cwd}: {error:#}")))?;
        let key = (caller.connection, shell.clone());
        self.shells()
            .lock()
            .insert(key.clone(), Shell::Running(handle));
        let shells = self.shells().clone();
        tokio::spawn(async move {
            let ending = terminal.run(output).await;
            log_end(&caller, &key.1, &ending);
            shells.lock().insert(key.clone(), Shell::Ended);
            // An ended shell takes input until its connection closes.
            caller.left().await;
            shells.lock().remove(&key);
        });
        Ok(HostShellOpenResponse::new(shell))
    }

    fn input(
        &self,
        caller: &Caller,
        params: HostShellInputParams,
    ) -> Result<HostShellInputResponse, RpcError> {
        let bytes = params.bytes().map_err(|error| {
            RpcError::new(
                ErrorCode::InvalidParams,
                format!("`data` isn't base64: {error}"),
            )
        })?;
        if let Some(shell) = self.shells().running(caller.connection, &params.shell)? {
            shell.write(bytes).map_err(input_full)?;
        }
        Ok(HostShellInputResponse::default())
    }

    fn resize(
        &self,
        caller: &Caller,
        params: HostShellResizeParams,
    ) -> Result<HostShellResizeResponse, RpcError> {
        if let Some(shell) = self.shells().running(caller.connection, &params.shell)? {
            shell.resize(params.columns.get(), params.rows.get());
        }
        Ok(HostShellResizeResponse::default())
    }

    fn foreground(
        &self,
        caller: &Caller,
        params: HostShellForegroundParams,
    ) -> Result<HostShellForegroundResponse, RpcError> {
        let shell = self.shells().running(caller.connection, &params.shell)?;
        Ok(HostShellForegroundResponse::new(
            shell.and_then(|shell| shell.foreground()),
        ))
    }
}

impl Machine {
    /// The program a shell runs, and its arguments: on Unix the user's
    /// login shell, else the environment's `SHELL`, else `/bin/sh`, as a
    /// login shell (`-l`, which sh, bash, zsh and fish all read) as sshd
    /// starts one; on Windows `%ComSpec%`, else `cmd.exe`, as a console
    /// starts.
    fn shell_program(&self, environment: &ClientEnvironment) -> (PathBuf, &'static [&'static str]) {
        let named = |wanted: &str| {
            environment
                .iter()
                .find(|(name, value)| {
                    let same = if cfg!(windows) {
                        name.eq_ignore_ascii_case(wanted)
                    } else {
                        *name == wanted
                    };
                    same && !value.is_empty()
                })
                .map(|(_, value)| PathBuf::from(value))
        };
        if cfg!(windows) {
            let program = named("ComSpec").unwrap_or_else(|| PathBuf::from("cmd.exe"));
            (program, &[])
        } else {
            let program = self
                .login_shell()
                .or_else(|| named("SHELL"))
                .unwrap_or_else(|| PathBuf::from("/bin/sh"));
            (program, &["-l"])
        }
    }
}

/// [`ErrorCode::ShellInputFull`] for input the shell has no room for.
fn input_full(InputFull { queued, asked }: InputFull) -> RpcError {
    RpcError::new(
        ErrorCode::ShellInputFull,
        format!(
            "the shell holds {queued} bytes of input it hasn't read, and {asked} more would pass the {HOST_SHELL_INPUT_MAX_BYTES}-byte limit (HOST_SHELL_INPUT_MAX_BYTES); send it again once the shell reads"
        ),
    )
    .with_data(
        serde_json::to_value(ShellInputLimit::new(HOST_SHELL_INPUT_MAX_BYTES, asked))
            .expect("a limit is JSON"),
    )
}

/// The shells of every connection, by connection and output stream, since
/// stream ids repeat across connections. Each shell's task keeps its own
/// entry, from its start to its connection's end.
#[derive(Clone, Default)]
pub(super) struct Shells(Arc<Mutex<HashMap<(ConnectionId, HostStreamId), Shell>>>);

enum Shell {
    Running(Handle),
    /// It ended; the protocol has its input and resizes taken and ignored.
    Ended,
}

impl Shells {
    fn lock(&self) -> MutexGuard<'_, HashMap<(ConnectionId, HostStreamId), Shell>> {
        self.0
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
    }

    /// The handle of `connection`'s running `shell`: `None` for one that
    /// ended.
    ///
    /// # Errors
    ///
    /// [`ErrorCode::InvalidParams`] for a stream of the connection that is
    /// no shell of it, such as a diff's.
    fn running(
        &self,
        connection: ConnectionId,
        shell: &HostStreamId,
    ) -> Result<Option<Handle>, RpcError> {
        match self.lock().get(&(connection, shell.clone())) {
            Some(Shell::Running(handle)) => Ok(Some(handle.clone())),
            Some(Shell::Ended) => Ok(None),
            None => Err(RpcError::new(
                ErrorCode::InvalidParams,
                format!("host stream {shell} isn't a shell of this connection"),
            )),
        }
    }
}

/// Logs how a shell ended, with who opened it; never what it printed.
fn log_end(caller: &Caller, shell: &HostStreamId, ending: &Ending) {
    tracing::info!(
        connection = ?caller.connection,
        client = ?caller.client.name,
        client_version = ?caller.client.version,
        %shell,
        ending = ?ending,
        "host shell ended"
    );
}

#[cfg(test)]
#[path = "machine_shell_tests.rs"]
mod tests;