rho-coding-agent 3.13.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! The home's LaunchAgent, which starts the daemon in the user's GUI login
//! on macOS for a client outside it, such as one in an ssh login
//! ([`super::gui_login::placement`]). A daemon there can use the login
//! keychain, and so can every process it starts.
//!
//! The definition lives in the home's state directory, not in
//! `~/Library/LaunchAgents`, so launchd loads it only when a client
//! bootstraps it, never at login. It is not kept alive: the daemon still
//! runs only once a client starts it, and stops as any daemon does. The
//! label is the home's, so the daemons of two homes, a scratch one beside
//! the user's say, never share an agent. The agent runs the command the
//! spawner built, with that command's environment, to which launchd adds
//! its own base variables, such as its `SSH_AUTH_SOCK`.
//!
//! Once the daemon exits, launchd keeps the agent loaded until the user
//! logs out, and the next start replaces it ([`LaunchAgent::start`]). A
//! daemon there ends with the GUI login, as one a terminal there starts
//! does: launchd stops it when the user logs out at the screen, and the
//! next client starts one where it is.

use std::{
    ffi::OsStr,
    io::{self, Write},
    os::unix::ffi::OsStrExt,
    path::{Path, PathBuf},
    process::Command,
};

use sha2::{Digest, Sha256};

use crate::daemon::{paths::DaemonPaths, service::xml_escape};

/// The agent of one rho home.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct LaunchAgent {
    /// `dev.rho.daemon.<hash of the home's canonical path>`.
    label: String,
    /// `<state dir>/launch-agent.plist`.
    definition: PathBuf,
}

impl LaunchAgent {
    pub(super) fn of(paths: &DaemonPaths) -> Self {
        let digest = Sha256::digest(paths.home.as_os_str().as_bytes());
        Self {
            label: format!("dev.rho.daemon.{}", hex::encode(&digest[..8])),
            definition: paths.state_dir.join("launch-agent.plist"),
        }
    }

    /// The agent's property list for running `command`: its program,
    /// arguments, working directory, and the variables it sets. A property
    /// list holds only UTF-8, so a command that is not fails.
    pub(super) fn plist(&self, command: &Command) -> io::Result<String> {
        let string = |value: &str| format!("<string>{}</string>", xml_escape(value));
        let mut arguments = String::new();
        for argument in std::iter::once(command.get_program()).chain(command.get_args()) {
            arguments.push_str(&format!("\n    {}", string(utf8(argument)?)));
        }
        let mut environment = String::new();
        // A variable the command removes is not set, as launchd starts
        // the agent from its own environment.
        for (name, value) in command.get_envs() {
            if let Some(value) = value {
                environment.push_str(&format!(
                    "\n    <key>{}</key>\n    {}",
                    xml_escape(utf8(name)?),
                    string(utf8(value)?)
                ));
            }
        }
        let directory = utf8(
            command
                .get_current_dir()
                .unwrap_or(Path::new("/"))
                .as_os_str(),
        )?;
        Ok(format!(
            r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  {label}
  <key>ProgramArguments</key>
  <array>{arguments}
  </array>
  <key>EnvironmentVariables</key>
  <dict>{environment}
  </dict>
  <key>WorkingDirectory</key>
  {directory}
  <key>RunAtLoad</key>
  <true/>
  <!-- Unthrottled, as a daemon a terminal starts: launchd throttles the CPU and I/O of an agent with no type. -->
  <key>ProcessType</key>
  <string>Interactive</string>
  <!-- The processes the daemon leaves behind outlive it, as they do where a client starts it. -->
  <key>AbandonProcessGroup</key>
  <true/>
</dict>
</plist>
"#,
            label = string(&self.label),
            directory = string(directory),
        ))
    }

    /// Has launchd run this agent, defined by `plist`, in `domain`, asking
    /// it through `launchctl`, which runs one `launchctl` command. No daemon
    /// of the home runs: the caller holds the spawn lock and found the
    /// daemon lock free.
    ///
    /// An agent still loaded from an earlier start is unloaded and loaded
    /// again, never kickstarted: launchd holds a kickstart of a job that
    /// exited under 10 s ago until its throttle interval passes (9.1 to 9.3 s
    /// in 3 runs on a macOS 26 runner), past the client's
    /// `DAEMON_START_TIMEOUT`, while unloading and loading it again started
    /// it within 77 ms. That also drops a definition another client's
    /// executable or environment wrote.
    pub(super) fn start(
        &self,
        domain: &str,
        plist: &str,
        launchctl: &dyn Fn(&[&str]) -> io::Result<()>,
    ) -> io::Result<()> {
        let target = format!("{domain}/{}", self.label);
        // `print` succeeds only for a loaded agent.
        if launchctl(&["print", &target]).is_ok() {
            super::service::bootout(&target, launchctl)?;
        }
        self.save(plist)?;
        launchctl(&["bootstrap", domain, utf8(self.definition.as_os_str())?])
    }

    /// Writes `plist` as the definition, atomically, so launchd never
    /// reads a partial one.
    fn save(&self, plist: &str) -> io::Result<()> {
        let dir = self
            .definition
            .parent()
            .expect("the definition is a file in the state directory");
        let mut file = tempfile::NamedTempFile::new_in(dir)?;
        file.write_all(plist.as_bytes())?;
        file.persist(&self.definition)
            .map_err(|error| error.error)?;
        Ok(())
    }
}

/// `value` as a property list can hold it.
fn utf8(value: &OsStr) -> io::Result<&str> {
    value.to_str().ok_or_else(|| {
        io::Error::new(
            io::ErrorKind::InvalidInput,
            format!(
                "{} is not UTF-8, which a launchd agent cannot hold",
                Path::new(value).display()
            ),
        )
    })
}

/// Starts the daemon `command` runs as the home's agent in this user's GUI
/// login.
#[cfg(target_os = "macos")]
pub(super) fn start_in_gui_login(command: &Command, paths: &DaemonPaths) -> io::Result<()> {
    paths.prepare_state_dir().map_err(io::Error::other)?;
    let agent = LaunchAgent::of(paths);
    let plist = agent.plist(command)?;
    agent.start(&super::service::launchd_domain(), &plist, &|args| {
        super::service::run_manager_command("launchctl", args)
    })
}

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