rho-coding-agent 3.13.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! The bridge's side of `rho/device/pair`: where a new device reaches the
//! bridge, as `rho daemon bridge setup` recorded it, and minting the
//! one-time code it redeems there ([`PairingCodeSet`]).

use rho_protocol::{BridgeUrl, CodePairing};

use super::pairing_codes::{DeviceName, PairingCodeSet};
use crate::app::mcp_server::token_store;

/// A device's pairing, minted.
#[derive(Debug)]
pub(crate) struct Paired {
    /// The version-2 pairing string's contents, code included.
    pub(crate) pairing: CodePairing,
    /// Unix seconds after which the code is no longer good.
    pub(crate) expires_at: u64,
    /// How many expired codes the mint pruned.
    pub(crate) pruned: usize,
}

/// Why no device was paired.
#[derive(Debug)]
pub(crate) enum PairRefused {
    /// No bridge a device can be paired with: why, and what to run.
    NoBridge(String),
    /// Reading the bridge's record or the credential store failed.
    Failed(anyhow::Error),
}

/// Mints a code, good from `now`, that pairs a device named as `name` says
/// with the bridge setup installed, in the credential store rho opened.
pub(crate) fn pair(name: DeviceName, now: u64) -> Result<Paired, PairRefused> {
    let url = bridge_url()?;
    let minted = token_store::update(|codes: &mut PairingCodeSet| codes.mint(name, now))
        .map_err(PairRefused::Failed)?;
    Ok(Paired {
        pairing: CodePairing::new(url, minted.code, machine_name()),
        expires_at: minted.expires_at,
        pruned: minted.pruned,
    })
}

/// Where clients reach the bridge setup installed, as it recorded it.
#[cfg(unix)]
fn bridge_url() -> Result<BridgeUrl, PairRefused> {
    use super::{setup, setup_service::Installed, setup_service::Unpairable};

    let (service, _home) =
        setup::bridge_service().map_err(|error| PairRefused::NoBridge(format!("{error:#}")))?;
    let installed = Installed::of(&service).map_err(PairRefused::Failed)?;
    match installed.pair_with() {
        Ok(target) => Ok(target.url),
        Err(error) => match error.downcast::<Unpairable>() {
            Ok(unpairable) => Err(PairRefused::NoBridge(unpairable.to_string())),
            Err(error) => Err(PairRefused::Failed(error)),
        },
    }
}

#[cfg(not(unix))]
fn bridge_url() -> Result<BridgeUrl, PairRefused> {
    Err(PairRefused::NoBridge(
        "`rho daemon bridge setup` does not run on this OS, so no bridge records where devices reach it".to_owned(),
    ))
}

/// This machine's host name, up to its first dot, as setup names it in a
/// pairing string.
fn machine_name() -> String {
    let name = gethostname::gethostname().to_string_lossy().into_owned();
    name.split('.').next().unwrap_or_default().to_owned()
}