rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! The models agy offers, as its sessions last showed them, kept so a
//! client can pick one before a session on Antigravity runs.
//!
//! agy names its models only in a session's `model` select option: `agy
//! models` lists effort-suffixed ids (`gemini-4-neon-high`) the option does
//! not take (`gemini-4-neon`), and takes 6.5 s (agy 1.5.21). Every new agy
//! session Rho opens, by any Rho process, records the options it offered
//! before Rho set any ([`super::policy`]), and [`probe`] opens one for them
//! without a run, 0.06 s to initialize and 0.8 s to open (agy 1.5.21).

use std::{path::PathBuf, time::Duration};

use agent_client_protocol::v1::schema::{
    SessionConfigKind, SessionConfigOption, SessionConfigSelectOption, SessionConfigSelectOptions,
};
use serde::{Deserialize, Serialize};

use super::policy::AntigravityAcpPolicy;
use crate::{
    acp_runtime::config_probe::probe_session_config,
    agent::{AntigravityTool, PromptPolicy},
    permission::PermissionMode,
    session_environment::Ambient,
};

/// agy's model select option id.
pub(super) const MODEL_CONFIG_ID: &str = "model";

const CACHE_FILE_NAME: &str = "antigravity-models.json";

/// The whole probe, spawn to exit: 0.84 s measured (agy 1.5.21), and the
/// models.dev fetch a full refresh waits for alongside it has 5 s, so a
/// stalled agy never holds the refresh longer than that fetch can.
const PROBE_BUDGET: Duration = Duration::from_secs(5);

/// agy's models as one session offered them.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct SeenModels {
    pub(crate) models: Vec<SeenModel>,
    /// The model the session was on before Rho chose one, which a new
    /// session opens on.
    pub(crate) default: String,
    /// Unix seconds.
    pub(crate) seen_at: u64,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct SeenModel {
    /// The option's value, the id a session takes.
    pub(crate) model: String,
    /// agy's name for it.
    pub(crate) name: String,
}

impl SeenModels {
    /// The models in `options`' `model` select, grouped or not; `None`
    /// without one.
    pub(crate) fn from_options(options: &[SessionConfigOption], seen_at: u64) -> Option<Self> {
        let option = options
            .iter()
            .find(|option| option.id.0.as_ref() == MODEL_CONFIG_ID)?;
        let SessionConfigKind::Select(select) = &option.kind else {
            return None;
        };
        let seen = |option: &SessionConfigSelectOption| SeenModel {
            model: option.value.to_string(),
            name: option.name.clone(),
        };
        let models = match &select.options {
            SessionConfigSelectOptions::Ungrouped(options) => options.iter().map(seen).collect(),
            SessionConfigSelectOptions::Grouped(groups) => groups
                .iter()
                .flat_map(|group| &group.options)
                .map(seen)
                .collect(),
            _ => return None,
        };
        Some(Self {
            models,
            default: select.current_value.to_string(),
            seen_at,
        })
    }
}

/// Keeps the models in `options`, if they name any, as the last seen. A
/// failure is logged: the cache never fails a run.
pub(super) fn record(options: &[SessionConfigOption]) {
    let Some(seen) = SeenModels::from_options(options, crate::export::now_unix_secs()) else {
        return;
    };
    // Losing it to a crash only lists the models as unlisted again.
    let written = cache_path().and_then(|path| {
        let bytes = serde_json::to_vec(&seen)?;
        crate::config_writer::write_bytes_atomically_with_durability(
            &path,
            &bytes,
            crate::config_writer::WriteDurability::Replaceable,
        )?;
        Ok(())
    });
    if let Err(error) = written {
        tracing::warn!("antigravity: could not keep the models it offered: {error:#}");
    }
}

/// The models [`record`] last kept, if any.
pub(crate) fn last_seen() -> Option<SeenModels> {
    let path = cache_path().ok()?;
    let bytes = match std::fs::read(&path) {
        Ok(bytes) => bytes,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return None,
        Err(error) => {
            tracing::warn!("antigravity: could not read {}: {error}", path.display());
            return None;
        }
    };
    serde_json::from_slice(&bytes)
        .inspect_err(|error| {
            tracing::warn!("antigravity: could not read {}: {error}", path.display());
        })
        .ok()
}

/// Opens an agy session in `environment`, without a run, whose policy
/// [`record`]s the models it offers. agy may keep the empty session among
/// its own.
pub(crate) async fn probe(environment: &Ambient) -> Result<(), String> {
    let dir = tempfile::Builder::new()
        .prefix("rho-agy-probe-")
        .tempdir()
        .map_err(|error| format!("antigravity: could not make a probe directory: {error}"))?;
    // The narrowest fence, for an agent file that only reads; the session
    // is never prompted, so its mode is never set.
    let mut policy = AntigravityAcpPolicy::new(
        /*model*/ None,
        vec![AntigravityTool::ReadFile],
        PermissionMode::Plan,
        dir.path().to_path_buf(),
        // A session never prompted needs no instructions.
        PromptPolicy::Extend(String::new()),
    );
    crate::acp_runtime::AcpAgentPolicy::prepare(&mut policy, dir.path())?;
    tokio::time::timeout(PROBE_BUDGET, probe_session_config(policy, environment))
        .await
        .unwrap_or_else(|_| {
            Err(format!(
                "antigravity: the model probe exceeded its budget of {} s",
                PROBE_BUDGET.as_secs()
            ))
        })
}

fn cache_path() -> anyhow::Result<PathBuf> {
    Ok(crate::paths::rho_dir()?.join("cache").join(CACHE_FILE_NAME))
}

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