rho-coding-agent 3.11.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! `rho/forge/status`: finding `gh` as a person set it or as a terminal
//! would, and saying whether it runs and which accounts it is signed in to,
//! ported from rho-ui's check (`forge/gh.rs`, its `SCRIPT` and
//! `check_here_in`). How `gh` is found without a setting is
//! [`GhCli::find`]'s, which the daemon's pull request reads share.

use std::{
    collections::BTreeMap,
    ffi::{OsStr, OsString},
    path::{Component, Path, PathBuf},
};

use rho_protocol::{
    methods::{
        ForgeStatusParams, GhAccount, GhAuth, GhFoundBy, GhState, GhStatus, GhTokenSource,
        HostPath, FORGE_STATUS,
    },
    Caller, ClientEnvironment, RpcError,
};
use serde::Deserialize;

use super::{
    blocking, failed, gh_command, host_path, log_call, supervised_output, var, within_deadline,
    Machine, Origin, LOGIN_SHELL_DEADLINE,
};
use crate::{
    app::pull_requests::{login_shell_gh, GhCli},
    executable::{find_on, is_executable_file},
};

/// What a `gh` too old for `gh auth status --json` is said to be.
pub(super) const TOO_OLD: &str = "This gh can't list its accounts as JSON (gh auth status --json). Update it to a newer release.";

/// Answers `rho/forge/status`: the `gh` the person set, or the one a
/// terminal would find, and its state. An empty setting is as if absent.
pub(super) async fn status(
    machine: &Machine,
    caller: Caller,
    params: ForgeStatusParams,
) -> Result<GhStatus, RpcError> {
    let setting = params.gh.filter(|gh| !gh.is_empty());
    tracing::info_span!("forge_status", gh = setting.as_deref())
        .in_scope(|| log_call(&caller, FORGE_STATUS, []));
    within_deadline(async {
        let (environment, origin) = machine.login_environment_and_origin().await;
        let (gh, found_by) = match setting {
            Some(setting) => (set_program(&setting, &environment), GhFoundBy::Setting),
            None => match find(&environment, origin).await? {
                Some(found) => found,
                None => return Ok(GhStatus::Missing),
            },
        };
        let path = host_path(&gh)?;
        let state = state_of(gh, &environment).await?;
        Ok(GhStatus::Found {
            found_by,
            path,
            state,
        })
    })
    .await
}

/// `gh` where a terminal finds it, in [`GhCli::find`]'s order: on the
/// login's `PATH`, then through the login shell, then among mise's shims.
/// The login shell is asked only when the environment isn't what it
/// printed, whose `PATH` is the shell's own, and then with that
/// environment, within [`LOGIN_SHELL_DEADLINE`].
async fn find(
    environment: &ClientEnvironment,
    origin: Origin,
) -> Result<Option<(PathBuf, GhFoundBy)>, RpcError> {
    let cli = GhCli::new(|name| var(environment, name).map(OsString::from));
    if let Some(gh) = cli.on_path() {
        return Ok(Some((gh, GhFoundBy::Path)));
    }
    let shell = var(environment, "SHELL").filter(|shell| !shell.is_empty());
    // A shell that printed the environment named its `PATH` already, and
    // one that hung would hang again.
    if let (Origin::Fallback, Some(shell)) = (origin, shell) {
        let asked = login_shell_gh(OsStr::new(shell), Some(environment));
        match tokio::time::timeout(LOGIN_SHELL_DEADLINE, asked).await {
            Ok(Some(gh)) => return Ok(Some((gh, GhFoundBy::LoginShell))),
            Ok(None) => {}
            Err(_) => {
                return Err(failed(format!(
                    "The login shell, {shell}, didn't say where gh is within {} s (LOGIN_SHELL_DEADLINE).",
                    LOGIN_SHELL_DEADLINE.as_secs()
                )))
            }
        }
    }
    Ok(cli.among_mise().map(|gh| (gh, GhFoundBy::Mise)))
}

/// The program a person set, found as the login's shell would find it: a
/// bare name on the `PATH`; a path from the home when it starts with `~`
/// or is relative, as an ssh login's shell starts in the home, where
/// rho-ui's check ran; an absolute path as it is. Without a home, a
/// relative one stays relative and names no program.
fn set_program(setting: &str, environment: &ClientEnvironment) -> PathBuf {
    if let Some(gh) = find_on(setting, var(environment, "PATH").map(OsStr::new)) {
        return gh;
    }
    let path = Path::new(setting);
    let mut parts = path.components();
    let rest = match parts.next() {
        Some(Component::Normal(first)) if first == "~" => parts.as_path(),
        _ => path,
    };
    let home = crate::paths::home_dir_from_env(|name| var(environment, name).map(OsString::from));
    match home {
        Some(home) if rest.is_relative() => home.join(rest),
        _ => rest.to_path_buf(),
    }
}

/// Whether `gh` runs, as `gh --version` says, and the accounts
/// `gh auth status --json hosts` lists. A `gh` that fails to list them is
/// broken; one that lists a failing account still lists it, whatever it
/// exits with.
async fn state_of(gh: PathBuf, environment: &ClientEnvironment) -> Result<GhState, RpcError> {
    let broken = |why: String| Ok(GhState::Broken { why });
    let program = gh.clone();
    if !blocking(move || is_executable_file(&program)).await? {
        return broken("There's no program there.".to_owned());
    }
    let mut command = gh_command(&gh, environment);
    command.arg("--version");
    let version = match supervised_output(&mut command).await {
        Err(error) => return broken(format!("Couldn't run it: {error}")),
        Ok(output) if !output.status.success() => {
            let said = [output.stdout, output.stderr].concat();
            let said = String::from_utf8_lossy(&said);
            return broken(match said.trim() {
                "" => format!("It exited with {}.", output.status),
                said => said.to_owned(),
            });
        }
        Ok(output) => version_number(&String::from_utf8_lossy(&output.stdout)),
    };
    let mut command = gh_command(&gh, environment);
    command.args(["auth", "status", "--json", "hosts"]);
    let listed = match supervised_output(&mut command).await {
        Err(error) => return broken(format!("Couldn't run it: {error}")),
        Ok(output) => output.stdout,
    };
    let Some(accounts) = accounts(&listed) else {
        return broken(TOO_OLD.to_owned());
    };
    Ok(GhState::Ready { version, accounts })
}

/// `2.99.0` from `gh version 2.99.0 (2026-09-01)`, or the first line as it
/// is when it reads otherwise.
fn version_number(version: &str) -> String {
    let first = version.lines().next().unwrap_or_default();
    first
        .strip_prefix("gh version ")
        .and_then(|rest| rest.split_whitespace().next())
        .unwrap_or(first)
        .to_owned()
}

/// `gh auth status --json hosts`: each host's accounts.
#[derive(Deserialize)]
struct AuthStatus {
    hosts: BTreeMap<String, Vec<AuthAccount>>,
}

/// One account as `gh auth status` lists it. `state` is `success` once
/// the forge took its token; otherwise `error` says why.
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct AuthAccount {
    state: String,
    #[serde(default)]
    error: Option<String>,
    #[serde(default)]
    active: bool,
    host: String,
    #[serde(default)]
    login: String,
    #[serde(default)]
    token_source: Option<String>,
    #[serde(default)]
    scopes: Option<String>,
    #[serde(default)]
    git_protocol: Option<String>,
}

/// The accounts `listed`, what `gh auth status --json hosts` printed,
/// names, by host; `None` when it isn't that JSON, as from a `gh` too old
/// to print it.
fn accounts(listed: &[u8]) -> Option<Vec<GhAccount>> {
    let status: AuthStatus = serde_json::from_slice(listed).ok()?;
    Some(status.hosts.into_values().flatten().map(account).collect())
}

/// `listed` as the wire carries it. A token the forge refused reaches `gh`
/// as a raw 401, which says nothing a person needs; any other failure is
/// `gh` not reaching the forge, said in its first line.
fn account(listed: AuthAccount) -> GhAccount {
    let auth = if listed.state == "success" {
        GhAuth::SignedIn
    } else {
        let why = listed.error.unwrap_or(listed.state);
        if why.contains("401") || why.contains("Bad credentials") {
            GhAuth::Refused {
                why: "GitHub refused its token.".to_owned(),
            }
        } else {
            let line = why.lines().next().unwrap_or_default().trim();
            GhAuth::Unreachable {
                why: line.to_owned(),
            }
        }
    };
    GhAccount::new(listed.host, listed.login, listed.active, auth).with_details(
        listed.git_protocol,
        listed.token_source.as_deref().and_then(token_source),
        listed.scopes.filter(|scopes| !scopes.is_empty()),
    )
}

/// Where `gh` says a token comes from: `keyring`, the name of a variable
/// such as `GH_TOKEN`, or the path of a file, as its `hosts.yml`.
fn token_source(source: &str) -> Option<GhTokenSource> {
    let variable = source
        .chars()
        .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_');
    match source {
        "" => None,
        "keyring" => Some(GhTokenSource::Keyring),
        _ if variable => Some(GhTokenSource::Variable {
            name: source.to_owned(),
        }),
        _ => Some(GhTokenSource::File {
            path: HostPath::new(source),
        }),
    }
}