use std::sync::OnceLock;
use rho_protocol::{ConfigRevision, ErrorCode, McpConfigGetResponse, RpcError};
use tokio::sync::MutexGuard;
use super::{change_error, file, AgentFile, ConfigStore};
use crate::config::{
mcp_server_entries, mcp_servers_revision, ChangeError, Config, ConfigDocument, ConfigWarning,
};
impl ConfigStore {
pub(in crate::app::daemon_host) fn agent_document(&self) -> Result<ConfigDocument, RpcError> {
file::read_document(&self.agent_path)
}
pub(in crate::app::daemon_host) fn mcp_config(&self) -> Result<McpConfigGetResponse, RpcError> {
let doc = self.agent_document()?;
Ok(McpConfigGetResponse::new(
mcp_revision(&doc),
mcp_server_entries(&doc),
))
}
pub(in crate::app::daemon_host) async fn edit_mcp_at(
&self,
revision: &ConfigRevision,
) -> Result<McpEdit<'_>, RpcError> {
let edit = self.edit_mcp().await?;
if *revision != mcp_revision(edit.doc()) {
return Err(RpcError::new(
ErrorCode::ConfigConflict,
"the MCP servers changed since that revision; read them again",
));
}
Ok(edit)
}
pub(in crate::app::daemon_host) async fn edit_mcp(&self) -> Result<McpEdit<'_>, RpcError> {
let file = self.agent.lock().await;
let edit = file::Edit::open(&self.agent_path)?;
Ok(McpEdit {
store: self,
file,
edit,
})
}
}
pub(in crate::app::daemon_host) struct McpEdit<'a> {
store: &'a ConfigStore,
file: MutexGuard<'a, AgentFile>,
edit: file::Edit,
}
impl<'a> McpEdit<'a> {
pub(in crate::app::daemon_host) fn doc(&self) -> &ConfigDocument {
&self.edit.doc
}
pub(in crate::app::daemon_host) fn apply(
mut self,
change: impl FnOnce(&mut ConfigDocument) -> Result<(Config, Vec<ConfigWarning>), ChangeError>,
) -> Result<AppliedMcpEdit<'a>, RpcError> {
let loaded = change(&mut self.edit.doc).map_err(change_error)?;
Ok(AppliedMcpEdit { open: self, loaded })
}
}
pub(in crate::app::daemon_host) struct AppliedMcpEdit<'a> {
open: McpEdit<'a>,
loaded: (Config, Vec<ConfigWarning>),
}
impl AppliedMcpEdit<'_> {
pub(in crate::app::daemon_host) fn doc(&self) -> &ConfigDocument {
self.open.doc()
}
pub(in crate::app::daemon_host) fn save(self) -> Result<ConfigRevision, RpcError> {
let McpEdit {
store,
mut file,
edit,
} = self.open;
let (doc, _) = store.save_agent(&mut file, edit, self.loaded)?;
Ok(mcp_revision(&doc))
}
}
fn mcp_revision(doc: &ConfigDocument) -> ConfigRevision {
static KEY: OnceLock<[u8; 32]> = OnceLock::new();
let key = KEY.get_or_init(|| {
use rand::{rand_core::UnwrapErr, rngs::SysRng, Rng};
let mut key = [0_u8; 32];
UnwrapErr(SysRng).fill_bytes(&mut key);
key
});
mcp_servers_revision(doc, key)
}