rho-coding-agent 3.10.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! The daemon's side of `rho/provider/list`: the providers a setup screen
//! offers, as a person picks them, and how to sign in to each.
//!
//! An entry is one of the login groups the TUI's `/login` picker offers
//! ([`catalog::login_groups`]), so OpenAI's API key and ChatGPT account are
//! one entry, as Moonshot AI's key and Kimi Code's login, and OpenCode Zen
//! and Go, are. Its methods are the profiles `rho/auth/list` offers, plus
//! its providers' keyless modes, which that list leaves out: a local Ollama
//! server, or a custom provider without a key, so a machine with only those
//! can finish setup. Every such provider also takes a key, so it has a
//! login group; one that took no credential at all would have none, and no
//! entry. Decision-model hosts, which cannot hold a conversation, are left
//! out.

use rho_protocol::{
    AuthKind, ErrorCode, ProviderEntry, ProviderListParams, ProviderListResponse, RpcError,
    SignInMethod,
};
use rho_providers::{
    model::catalog::{self, LoginGroup},
    provider::{self, AuthMode, ProviderAuthKind, ProviderDescriptor, KEYLESS_AUTH},
};

use super::auth::{self, off_workers, repository};

/// The entries a setup screen shows before the rest, in this order.
const POPULAR: [&str; 4] = ["anthropic", "openai", "xai", "meta"];

/// Answers `rho/provider/list` from the built-in providers and the custom
/// providers of the daemon's config, which it publishes as `rho/auth/list`
/// does. Config blocks, so it runs off the async workers.
pub(super) async fn list(_: ProviderListParams) -> Result<ProviderListResponse, RpcError> {
    let providers = off_workers(|| -> anyhow::Result<_> {
        repository().load()?.providers.activate()?;
        Ok(entries())
    })
    .await?
    .map_err(|error| {
        RpcError::new(
            ErrorCode::InternalError,
            format!("could not load config: {error:#}"),
        )
    })?;
    Ok(ProviderListResponse::new(providers))
}

/// Every entry of the providers visible now: [`POPULAR`] in its order, then
/// the rest by name, case-insensitively.
fn entries() -> Vec<ProviderEntry> {
    let mut entries: Vec<_> = catalog::login_groups()
        .into_iter()
        .filter_map(entry)
        .collect();
    entries.sort_by_cached_key(|entry| {
        let popular = POPULAR.iter().position(|id| *id == entry.id);
        (
            popular.unwrap_or(POPULAR.len()),
            entry.name.to_lowercase(),
            entry.id.clone(),
        )
    });
    entries
}

/// `group` as a setup screen offers it: its methods that lead to chat
/// models, with their providers' keyless modes, the leading ones of
/// [`offer`] first. `None` when no method leads to chat models.
fn entry(group: LoginGroup) -> Option<ProviderEntry> {
    let mut providers: Vec<&'static ProviderDescriptor> = Vec::new();
    let mut methods = Vec::new();
    for login in &group.methods {
        let Some((descriptor, mode)) = provider::resolve_auth_mode(&login.target.auth)
            .filter(|(descriptor, _)| descriptor.serves_chat())
        else {
            continue;
        };
        if !providers.iter().any(|known| known.name == descriptor.name) {
            providers.push(descriptor);
        }
        methods.push(method(descriptor, mode));
    }
    for descriptor in providers {
        for mode in descriptor
            .auth_modes()
            .filter(|mode| matches!(mode.auth_kind, ProviderAuthKind::None))
        {
            debug_assert_eq!(mode.id, KEYLESS_AUTH, "the wire promises `none`");
            methods.push(method(descriptor, mode));
        }
    }
    if methods.is_empty() {
        return None;
    }
    methods.sort_by_key(|(leads, _)| !leads);
    let methods = methods.into_iter().map(|(_, method)| method).collect();
    let entry = ProviderEntry::new(group.id, group.prompt, methods);
    Some(match POPULAR.contains(&entry.id.as_str()) {
        true => entry.with_popular(),
        false => entry,
    })
}

/// `mode` of `descriptor` as a setup screen offers it, and whether it leads
/// its entry's methods.
fn method(descriptor: &ProviderDescriptor, mode: AuthMode) -> (bool, SignInMethod) {
    let offered = offer(mode.auth_kind);
    // A group names a method itself where its kind would not tell the
    // group's methods apart, as OpenCode's two API keys.
    let label = catalog::named_login_method_prompt(mode.id).unwrap_or(offered.label);
    // A keyless mode is the one `rho/auth/list` leaves out.
    let kind = auth::kind(mode.id).unwrap_or(AuthKind::Keyless);
    let method = SignInMethod::new(mode.id, descriptor.name, label, kind);
    // A host logged in through its address offers the one it runs at
    // when none is set, as the provider table holds it.
    let method = match (
        descriptor.collects_login_endpoint(),
        descriptor.runtime.default_api_base(),
    ) {
        (true, Some(endpoint)) => method.with_needs_endpoint().with_default_endpoint(endpoint),
        (true, None) => method.with_needs_endpoint(),
        (false, _) => method,
    };
    (offered.leads, method)
}

/// How a setup screen presents an auth mode.
struct Offer {
    /// A short label read beside the entry's name.
    label: &'static str,
    /// Whether it comes before the entry's other methods.
    leads: bool,
}

/// The setup screen's policy for an auth mode of `auth_kind`. The long
/// labels of `rho/auth/list` serve screens that show a profile alone.
fn offer(auth_kind: ProviderAuthKind) -> Offer {
    let (label, leads) = match auth_kind {
        // Nothing to ask for, so a machine with only this finishes first.
        ProviderAuthKind::None => ("No sign-in", true),
        ProviderAuthKind::ApiKey { .. } => ("API key", false),
        // How most people pay for OpenAI, so it comes before the API key.
        ProviderAuthKind::CodexOAuth { .. } => ("ChatGPT account", true),
        ProviderAuthKind::GithubCopilotDevice { .. } | ProviderAuthKind::OllamaDeviceKey { .. } => {
            ("Device login", false)
        }
        ProviderAuthKind::MetaOAuth { .. } => ("Subscription", false),
        ProviderAuthKind::XaiOAuth { .. }
        | ProviderAuthKind::KimiOAuth { .. }
        | ProviderAuthKind::BearerCredential { .. } => ("Account", false),
    };
    Offer { label, leads }
}

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