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,
};
pub(super) const MODEL_CONFIG_ID: &str = "model";
const CACHE_FILE_NAME: &str = "antigravity-models.json";
const PROBE_BUDGET: Duration = Duration::from_secs(5);
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct SeenModels {
pub(crate) models: Vec<SeenModel>,
pub(crate) default: String,
pub(crate) seen_at: u64,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct SeenModel {
pub(crate) model: String,
pub(crate) name: String,
}
impl SeenModels {
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,
})
}
}
pub(super) fn record(options: &[SessionConfigOption]) {
let Some(seen) = SeenModels::from_options(options, crate::export::now_unix_secs()) else {
return;
};
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:#}");
}
}
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()
}
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}"))?;
let mut policy = AntigravityAcpPolicy::new(
None,
vec![AntigravityTool::ReadFile],
PermissionMode::Plan,
dir.path().to_path_buf(),
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;