rho-coding-agent 3.13.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! The service files `docs/daemon.md` has a user save for
//! `rho mcp serve --http` and `rho daemon serve --http`, the processes that
//! need a service: the daemon itself has no unit of its own, and no install
//! method writes one. `rho doctor` reports them and `rho uninstall` removes
//! them (#1666).
//!
//! Finding them reads files only, so it also answers where no user service
//! manager can be asked, as in an SSH login without a session bus. Each is
//! looked for on every platform, as the other's file is simply not there.

use std::{
    fs, io,
    path::{Path, PathBuf},
};

use super::platform;

/// The systemd user unit `docs/daemon.md` has you save for `rho mcp serve --http`.
pub(crate) const SYSTEMD_UNIT: &str = "rho-mcp.service";
/// The systemd user unit `docs/daemon.md` has you save for `rho daemon serve --http`.
pub(crate) const DAEMON_HTTP_SYSTEMD_UNIT: &str = "rho-daemon-http.service";
/// The launchd label of `rho mcp serve --http` on macOS.
pub(crate) const LAUNCHD_LABEL: &str = "dev.rho.mcp";
/// The launchd label of `rho daemon serve --http` on macOS.
pub(crate) const DAEMON_HTTP_LAUNCHD_LABEL: &str = "dev.rho.daemon-http";

const SYSTEMD_UNITS: [&str; 2] = [SYSTEMD_UNIT, DAEMON_HTTP_SYSTEMD_UNIT];
const LAUNCHD_LABELS: [&str; 2] = [LAUNCHD_LABEL, DAEMON_HTTP_LAUNCHD_LABEL];

/// Escapes `value` for a launchd property list's `<string>` or `<key>`.
pub(crate) fn xml_escape(value: &str) -> String {
    let mut escaped = String::with_capacity(value.len());
    for c in value.chars() {
        match c {
            '&' => escaped.push_str("&amp;"),
            '<' => escaped.push_str("&lt;"),
            '>' => escaped.push_str("&gt;"),
            '"' => escaped.push_str("&quot;"),
            '\'' => escaped.push_str("&apos;"),
            c => escaped.push(c),
        }
    }
    escaped
}

/// What runs a saved service.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ServiceManager {
    Systemd,
    Launchd,
}

/// One saved service, under the name the docs give it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct ServiceFiles {
    pub(crate) manager: ServiceManager,
    /// Unit name (`rho-mcp.service`, `rho-daemon-http.service`) or launchd
    /// label (`dev.rho.mcp`, `dev.rho.daemon-http`).
    pub(crate) unit: &'static str,
    /// The unit or the agent's property list.
    pub(crate) definition: PathBuf,
    /// The links that make a target start the unit, which
    /// `systemctl --user enable` creates. launchd has none.
    pub(crate) enabled_by: Vec<PathBuf>,
}

/// The services saved in `home`, systemd units before launchd agents.
/// `xdg_config_home` is `XDG_CONFIG_HOME`; a relative value is invalid there
/// and is ignored.
pub(crate) fn find_services(home: &Path, xdg_config_home: Option<PathBuf>) -> Vec<ServiceFiles> {
    let xdg_config_home = xdg_config_home.as_deref();
    let systemd = SYSTEMD_UNITS.map(|unit| (ServiceManager::Systemd, unit));
    let launchd = LAUNCHD_LABELS.map(|label| (ServiceManager::Launchd, label));
    systemd
        .into_iter()
        .chain(launchd)
        .map(|(manager, unit)| ServiceFiles::locate(manager, unit, home, xdg_config_home))
        .filter(|service| service.definition.exists())
        .collect()
}

fn systemd_user_dir(home: &Path, xdg_config_home: Option<&Path>) -> PathBuf {
    xdg_config_home
        .filter(|dir| dir.is_absolute())
        .map_or_else(|| home.join(".config"), Path::to_path_buf)
        .join("systemd/user")
}

impl ServiceFiles {
    /// Where `manager` keeps `unit`, a unit name or launchd label, in `home`,
    /// whether or not it is saved; see [`find_services`] for
    /// `xdg_config_home`.
    fn locate(
        manager: ServiceManager,
        unit: &'static str,
        home: &Path,
        xdg_config_home: Option<&Path>,
    ) -> Self {
        let (definition, enabled_by) = match manager {
            ServiceManager::Systemd => {
                let units = systemd_user_dir(home, xdg_config_home);
                // A target's `.wants` or `.requires` directory links to the
                // unit. The link's target may be anywhere, so only its own
                // existence counts.
                let mut enabled_by: Vec<PathBuf> = fs::read_dir(&units)
                    .into_iter()
                    .flatten()
                    .flatten()
                    .map(|entry| entry.path())
                    .filter(|dir| {
                        dir.extension().is_some_and(|extension| {
                            extension == "wants" || extension == "requires"
                        })
                    })
                    .map(|dir| dir.join(unit))
                    .filter(|link| link.symlink_metadata().is_ok())
                    .collect();
                enabled_by.sort();
                (units.join(unit), enabled_by)
            }
            ServiceManager::Launchd => (
                home.join("Library/LaunchAgents")
                    .join(format!("{unit}.plist")),
                Vec::new(),
            ),
        };
        Self {
            manager,
            unit,
            definition,
            enabled_by,
        }
    }

    /// The service of `rho daemon serve --http` under `manager`, saved or
    /// not, as `rho daemon bridge setup` installs it.
    #[cfg(unix)]
    pub(crate) fn daemon_http(
        manager: ServiceManager,
        home: &Path,
        xdg_config_home: Option<&Path>,
    ) -> Self {
        let unit = match manager {
            ServiceManager::Systemd => DAEMON_HTTP_SYSTEMD_UNIT,
            ServiceManager::Launchd => DAEMON_HTTP_LAUNCHD_LABEL,
        };
        Self::locate(manager, unit, home, xdg_config_home)
    }

    /// Writes `text` as the service's definition and has its manager start
    /// it now and at every login. Stop an earlier definition first.
    #[cfg(unix)]
    pub(crate) fn install(&self, text: &str) -> io::Result<()> {
        if let Some(dir) = self.definition.parent() {
            fs::create_dir_all(dir)?;
        }
        fs::write(&self.definition, text)?;
        self.start()
    }

    /// Has the manager read the saved service's definition again, in case
    /// an earlier write was never loaded, and start it, now and at every
    /// login, unless it runs already.
    #[cfg(unix)]
    pub(crate) fn start(&self) -> io::Result<()> {
        platform::reload_services(self.manager)?;
        platform::start_service(self.manager, self.unit, &self.definition)
    }

    /// Every file of the service, the links before what they point to.
    pub(crate) fn paths(&self) -> impl Iterator<Item = &Path> {
        self.enabled_by
            .iter()
            .chain([&self.definition])
            .map(PathBuf::as_path)
    }

    /// Asks the service's manager to stop it and no longer start it, so
    /// nothing runs a `rho` that is about to be removed. Fails when the
    /// manager cannot be asked or refuses; the files can be deleted all the
    /// same, and the error says what is left to do by hand.
    pub(crate) fn stop(&self) -> io::Result<()> {
        platform::stop_service(self.manager, self.unit)
    }

    /// Has the manager forget the service once its files are deleted, so it
    /// is not left listed as `not-found`.
    #[cfg(unix)]
    pub(crate) fn forget(&self) -> io::Result<()> {
        platform::reload_services(self.manager)
    }

    /// Deletes the service's files. One already gone is not an error: the
    /// manager removes the links itself as it disables the unit.
    pub(crate) fn delete(&self) -> io::Result<()> {
        for path in self.paths() {
            match fs::remove_file(path) {
                Ok(()) => {}
                Err(error) if error.kind() == io::ErrorKind::NotFound => {}
                Err(error) => return Err(error),
            }
        }
        Ok(())
    }
}