rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! `rho update` for a rho the install script put on Windows: rho downloads
//! the release's Windows archive, verifies it against its published SHA-256
//! as `install.ps1` does, and replaces its own executable. No shell runs: a
//! hidden PowerShell child got rho flagged by security software (rho#106).
//!
//! Windows refuses to write over the file of a running program, as this
//! rho, its daemon, and any open TUI are, but lets it be renamed. So the
//! running file moves aside within its directory, the new one takes its
//! name, and the processes that run the old file keep running it from
//! there. A later rho removes it once nothing runs it
//! ([`remove_update_leftovers`]). If the new file cannot take the name, the old
//! one moves back, so a failed update leaves the rho that was there.

use std::{
    ffi::OsString,
    fs,
    io::{self, Cursor, Read},
    path::{Path, PathBuf},
    time::{Duration, SystemTime, UNIX_EPOCH},
};

use anyhow::Context;
use bytes::Bytes;
use sha2::{Digest, Sha256};

use super::{Report, UpdateInfo};
use crate::daemon;

const RELEASE_DOWNLOAD_URL: &str = "https://github.com/matthewyjiang/rho/releases/download";
/// The archive each release publishes for Windows, as `install.ps1` names it.
const ARCHIVE: &str = "rho-x86_64-pc-windows-msvc.zip";
/// The executable in [`ARCHIVE`].
const ARCHIVE_EXECUTABLE: &str = "rho.exe";

/// How long connecting to GitHub may take: the 10 s the release lookup
/// allows its whole request.
const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
/// How long the download may go without receiving anything.
//
// Tripwire. The 3.9.0 archive (28.9 MB) downloaded in 1.37 s from a home
// connection. The limit is on silence, not on the whole download, so a slow
// link still finishes; 30 s without a byte means the transfer stalled.
const READ_TIMEOUT: Duration = Duration::from_secs(30);

/// Downloads `update`'s release, saying so to `report`, verifies it, and
/// puts it in place of `installed`, the running rho. Returns where the old
/// file went.
pub(super) async fn update(
    update: &UpdateInfo,
    installed: &Path,
    report: &mut impl Report,
) -> anyhow::Result<PathBuf> {
    let executable = fetch(&update.latest_tag, report).await?;
    install(installed, &executable, &update.latest_version).await
}

/// The verified `rho.exe` of release `tag`.
async fn fetch(tag: &str, report: &mut impl Report) -> anyhow::Result<Vec<u8>> {
    let url = format!("{RELEASE_DOWNLOAD_URL}/{tag}/{ARCHIVE}");
    report.say(&format!("downloading {url}"));
    let client = crate::reqwest_client_builder()
        .user_agent("rho-coding-agent")
        .connect_timeout(CONNECT_TIMEOUT)
        .read_timeout(READ_TIMEOUT)
        .build()?;
    let archive = download(&client, &url).await?;
    let checksum = download(&client, &format!("{url}.sha256")).await?;
    verify_checksum(&archive, &String::from_utf8_lossy(&checksum))
        .with_context(|| format!("could not verify {url}"))?;
    extract_executable(&archive)
        .with_context(|| format!("could not unpack {ARCHIVE_EXECUTABLE} from {url}"))
}

/// Writes `executable` beside `installed`, checks that it runs as rho
/// `version`, and swaps it in. Returns where the old file went; on failure
/// `installed` is as it was, unless the error says otherwise, and nothing
/// staged is left.
async fn install(installed: &Path, executable: &[u8], version: &str) -> anyhow::Result<PathBuf> {
    remove_update_leftovers(installed);
    let staged = stage(installed, executable).with_context(|| {
        format!(
            "could not write the new rho next to {}",
            installed.display()
        )
    })?;
    let placed = match daemon::probe_version(&staged).await {
        Ok(printed) if printed == version => swap(installed, &staged).map_err(anyhow::Error::from),
        Ok(printed) => Err(anyhow::anyhow!(
            "the downloaded rho reports version {printed}, not {version}"
        )),
        Err(error) => Err(anyhow::Error::new(error).context("the downloaded rho does not run")),
    };
    if placed.is_err() {
        let _ = fs::remove_file(&staged);
    }
    placed
}

async fn download(client: &reqwest::Client, url: &str) -> anyhow::Result<Bytes> {
    client
        .get(url)
        .send()
        .await
        .and_then(reqwest::Response::error_for_status)
        .with_context(|| format!("could not download {url}"))?
        .bytes()
        .await
        .with_context(|| format!("could not download {url}"))
}

/// Checks `archive` against `checksum`, a `.sha256` file's text: the hex
/// digest, then optionally whitespace and the file name.
fn verify_checksum(archive: &[u8], checksum: &str) -> anyhow::Result<()> {
    let Some(expected) = checksum.split_whitespace().next() else {
        anyhow::bail!("the published checksum is empty");
    };
    let actual = hex::encode(Sha256::digest(archive));
    if !expected.eq_ignore_ascii_case(&actual) {
        anyhow::bail!("its SHA-256 is {actual}, but the release publishes {expected}");
    }
    Ok(())
}

/// The bytes of [`ARCHIVE_EXECUTABLE`] in the zip `archive`.
fn extract_executable(archive: &[u8]) -> anyhow::Result<Vec<u8>> {
    let mut archive = zip::ZipArchive::new(Cursor::new(archive))?;
    let mut entry = archive.by_name(ARCHIVE_EXECUTABLE)?;
    let mut executable = Vec::new();
    entry.read_to_end(&mut executable)?;
    Ok(executable)
}

/// Writes `executable` next to `installed`, in the same directory so it can
/// be renamed into place, and returns its path.
fn stage(installed: &Path, executable: &[u8]) -> io::Result<PathBuf> {
    let staged = sibling(installed, &format!("{STAGED}{}", std::process::id()));
    fs::write(&staged, executable)?;
    Ok(staged)
}

/// Why [`swap`] did not put the new rho in place.
#[derive(Debug, thiserror::Error)]
enum SwapError {
    #[error("could not move {} aside: {error}; it was left as it was", installed.display())]
    MoveAside {
        installed: PathBuf,
        error: io::Error,
    },
    #[error("could not move the new rho to {}: {error}; the previous rho was put back", installed.display())]
    Place {
        installed: PathBuf,
        error: io::Error,
    },
    #[error(
        "could not move the new rho to {}: {error}, nor put the previous rho back: {rollback}; move {} to {} to restore it",
        installed.display(), aside.display(), installed.display()
    )]
    Stranded {
        installed: PathBuf,
        aside: PathBuf,
        error: io::Error,
        rollback: io::Error,
    },
}

/// Puts `staged` at `installed`, moving the file there aside first, and
/// returns where it went. Unless the error says otherwise, a failure leaves
/// `installed` as it was.
fn swap(installed: &Path, staged: &Path) -> Result<PathBuf, SwapError> {
    let aside = sibling(installed, &format!("{MOVED_ASIDE}{}", unique_suffix()));
    fs::rename(installed, &aside).map_err(|error| SwapError::MoveAside {
        installed: installed.to_path_buf(),
        error,
    })?;
    let Err(error) = fs::rename(staged, installed) else {
        return Ok(aside);
    };
    match fs::rename(&aside, installed) {
        Ok(()) => Err(SwapError::Place {
            installed: installed.to_path_buf(),
            error,
        }),
        Err(rollback) => Err(SwapError::Stranded {
            installed: installed.to_path_buf(),
            aside,
            error,
            rollback,
        }),
    }
}

/// Tags of the files an update leaves beside the installed rho: the old
/// one it moved aside, and the new one it staged, which an update that was
/// killed before the swap leaves behind.
const MOVED_ASIDE: &str = "old-";
const STAGED: &str = "new-";

/// A file an update left beside the installed rho: the old rho it moved
/// aside, `<stem>.old-<nanos>-<pid>`, which it needs to roll back until it
/// ends, or the new one it staged, `<stem>.new-<pid>`, until it swaps it in.
#[derive(Debug, PartialEq, Eq)]
struct Leftover {
    /// The process of the update that made it.
    update_pid: u32,
}

/// Removes the executables updates that no longer run moved aside or
/// staged from `installed`'s directory. Every rho start on Windows sweeps,
/// also while an update runs, so what a running update still needs is
/// kept. One that a process still runs resists removal on Windows and is
/// left for a later run.
pub(crate) fn remove_update_leftovers(installed: &Path) {
    let Some(dir) = installed.parent() else {
        return;
    };
    let Ok(entries) = fs::read_dir(dir) else {
        return;
    };
    for entry in entries.flatten() {
        match leftover(installed, &entry.file_name()) {
            Some(Leftover { update_pid }) if !process_runs(update_pid) => {}
            Some(_) | None => continue,
        }
        let path = entry.path();
        if let Err(error) = fs::remove_file(&path) {
            tracing::debug!(path = %path.display(), %error, "kept a rho executable an update left");
        }
    }
}

/// What `name` is when [`sibling`] made it for an update of `installed`,
/// in exactly the format [`swap`] and [`stage`] write. Anything else, such
/// as a backup a person named `rho.old-2026-12-01.exe`, is none.
fn leftover(installed: &Path, name: &std::ffi::OsStr) -> Option<Leftover> {
    let stem = installed.file_stem()?.to_str()?;
    let rest = name.to_str()?.strip_prefix(stem)?.strip_prefix('.')?;
    let tagged = match installed.extension() {
        Some(extension) => rest.strip_suffix(extension.to_str()?)?.strip_suffix('.')?,
        None => rest,
    };
    let update_pid = match tagged.strip_prefix(MOVED_ASIDE) {
        Some(suffix) => {
            let (nanos, pid) = suffix.split_once('-')?;
            number::<u128>(nanos)?;
            number(pid)?
        }
        None => number(tagged.strip_prefix(STAGED)?)?,
    };
    Some(Leftover { update_pid })
}

/// `text` as a number, when it is nothing but ASCII digits: `parse` alone
/// also takes a leading `+`.
fn number<T: std::str::FromStr>(text: &str) -> Option<T> {
    if text.is_empty() || !text.bytes().all(|byte| byte.is_ascii_digit()) {
        return None;
    }
    text.parse().ok()
}

/// Whether process `pid` is running. A pid the OS since gave to another
/// process reads as running, which only keeps a leftover until that one
/// exits.
#[cfg(unix)]
fn process_runs(pid: u32) -> bool {
    // `kill(0, _)` and negative pids address process groups, not one process.
    let Some(pid) = i32::try_from(pid).ok().filter(|pid| *pid > 0) else {
        return false;
    };
    // SAFETY: signal 0 only checks that the process exists and may be
    // signalled; nothing is sent.
    if unsafe { libc::kill(pid, 0) } == 0 {
        return true;
    }
    // It exists, but belongs to another user.
    io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
}

/// Whether process `pid` is running. A pid the OS since gave to another
/// process reads as running, which only keeps a leftover until that one
/// exits.
#[cfg(windows)]
fn process_runs(pid: u32) -> bool {
    use windows_sys::Win32::{
        Foundation::{CloseHandle, WAIT_TIMEOUT},
        System::Threading::{OpenProcess, WaitForSingleObject, PROCESS_SYNCHRONIZE},
    };
    // SAFETY: the call takes no pointers.
    let process = unsafe {
        OpenProcess(PROCESS_SYNCHRONIZE, /*bInheritHandle*/ 0, pid)
    };
    if process.is_null() {
        // No such process, or one this user cannot open, which an update
        // of this user's rho is not.
        return false;
    }
    // SAFETY: `process` is the open handle `OpenProcess` returned, closed
    // once, after the wait.
    unsafe {
        let waited = WaitForSingleObject(process, /*dwMilliseconds*/ 0);
        CloseHandle(process);
        waited == WAIT_TIMEOUT
    }
}

/// `<dir>/<stem>.<tag><.extension>`, beside `installed`: `rho.old-1.exe`.
fn sibling(installed: &Path, tag: &str) -> PathBuf {
    let mut name = sibling_prefix(installed, tag).unwrap_or_else(|| OsString::from(tag));
    if let Some(extension) = installed.extension() {
        name.push(".");
        name.push(extension);
    }
    installed.with_file_name(name)
}

/// `<stem>.<tag>`, the start of [`sibling`]'s file name.
fn sibling_prefix(installed: &Path, tag: &str) -> Option<OsString> {
    let mut prefix = installed.file_stem()?.to_os_string();
    prefix.push(".");
    prefix.push(tag);
    Some(prefix)
}

/// Distinct for each update: the time in nanoseconds and this process,
/// `<nanos>-<pid>`, as [`leftover`] reads it back.
fn unique_suffix() -> String {
    let nanos = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |since| since.as_nanos());
    format!("{nanos}-{}", std::process::id())
}

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