The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
refactor(mcp): move host cleanup out of the mcp feature gate
Steven Enamakelf07267de349b
diff --git a/crates/openhuman-core/src/mcp/agent_cleanup.rs b/crates/openhuman-core/src/mcp/agent_cleanup.rsindex 782a48f099..866484b20b 100644--- a/crates/openhuman-core/src/mcp/agent_cleanup.rs+++ b/crates/openhuman-core/src/mcp/agent_cleanup.rs@@ -63,85 +63,3 @@ impl AgentMcpCleanup {}}}--/// Run captured cleanup on the process module executor when modules are enabled.-/// Without modules, the caller must keep its current Tokio runtime alive.-/// This creates no configured client and loads no MCP artifact.-pub fn spawn_agent_cleanup<F>(- future: F,-) -> Result<tokio::task::JoinHandle<F::Output>, ModuleCallError>-where- F: std::future::Future + Send + 'static,- F::Output: Send + 'static,-{- #[cfg(feature = "modules")]- {- crate::modules::host::spawn_cleanup(future).map_err(|_| ModuleCallError::TransportFailed)- }- #[cfg(not(feature = "modules"))]- {- tokio::runtime::Handle::try_current()- .map(|handle| handle.spawn(future))- .map_err(|_| ModuleCallError::Unavailable)- }-}--/// A process-local directory reservation with no runtime guard or callback.-/// Dropping the token retains the fence; only confirmed host completion clears it.-#[derive(Clone)]-pub struct AgentDirectoryCleanup {- directory: PathBuf,- reservation: Arc<CleanupReservation>,-}--/// Reserve an agent's directory until host-owned cleanup succeeds.-/// This never creates a client or loads a module.-pub fn reserve_agent_directory(- workspace: &std::path::Path,- agent_id: &str,-) -> AgentDirectoryCleanup {- let directory = workspace.join("agents").join(agent_id);- let mut reservations = CLEANUP_RESERVATIONS- .get_or_init(|| Mutex::new(HashMap::new()))- .lock()- .unwrap_or_else(std::sync::PoisonError::into_inner);- let reservation = Arc::clone(- reservations- .entry(directory.clone())- .or_insert_with(|| Arc::new(CleanupReservation::default())),- );- reservation- .host_completion_pending- .store(true, Ordering::Release);- AgentDirectoryCleanup {- directory,- reservation,- }-}--impl AgentDirectoryCleanup {- /// Release this exact reservation after module close and host purge succeed.- /// An independently registered canonical callback keeps its own reservation.- pub fn complete(&self) {- let after_close = self- .reservation- .after_close- .lock()- .unwrap_or_else(std::sync::PoisonError::into_inner);- let mut reservations = CLEANUP_RESERVATIONS- .get_or_init(|| Mutex::new(HashMap::new()))- .lock()- .unwrap_or_else(std::sync::PoisonError::into_inner);- if reservations- .get(&self.directory)- .is_some_and(|current| Arc::ptr_eq(current, &self.reservation))- {- self.reservation- .host_completion_pending- .store(false, Ordering::Release);- if after_close.is_none() {- reservations.remove(&self.directory);- }- }- }-}diff --git a/crates/openhuman-core/src/mcp/host.rs b/crates/openhuman-core/src/mcp/host.rsindex 1192e716a4..2d03ed90ec 100644--- a/crates/openhuman-core/src/mcp/host.rs+++ b/crates/openhuman-core/src/mcp/host.rs@@ -9,10 +9,13 @@ use std::sync::OnceLock;use crate::config::Config;-pub use super::module_client::agent_cleanup::{- reserve_agent_directory, spawn_agent_cleanup, take_agent_cleanup, AgentDirectoryCleanup,- AgentMcpCleanup,+pub use super::host_cleanup::{+ reserve_agent_directory, spawn_agent_cleanup, AgentDirectoryCleanup,};+#[cfg(not(feature = "mcp"))]+pub use super::host_cleanup::{take_agent_cleanup, AgentMcpCleanup};+#[cfg(feature = "mcp")]+pub use super::module_client::agent_cleanup::{take_agent_cleanup, AgentMcpCleanup};const PROXY_SERVICE_KEY: &str = "tool.mcp_client";const DEFAULT_CORE_PORT: u16 = 7788;@@ -100,10 +103,10 @@ pub fn schedule_agent_close_with_cleanup(let _ = after_close();}-/// No agent-scoped module cleanup is pending when MCP is disabled.+/// Host-owned directory cleanup can remain pending even without MCP.#[cfg(not(feature = "mcp"))]-pub fn agent_close_pending(_workspace_dir: &std::path::Path, _agent_id: &str) -> bool {- false+pub fn agent_close_pending(workspace_dir: &std::path::Path, agent_id: &str) -> bool {+ super::host_cleanup::directory_pending(workspace_dir, agent_id)}/// Converts the MCP section of product configuration to the module contract.diff --git a/crates/openhuman-core/src/mcp/host_cleanup.rs b/crates/openhuman-core/src/mcp/host_cleanup.rsnew file mode 100644index 0000000000..ebb3e37375--- /dev/null+++ b/crates/openhuman-core/src/mcp/host_cleanup.rs@@ -0,0 +1,139 @@+//! Process-local host cleanup fencing, also used when MCP is compiled out.+use crate::modules::client::ModuleCallError;+use std::{+ collections::HashMap,+ path::PathBuf,+ sync::{+ atomic::{AtomicBool, Ordering},+ Arc, Mutex, OnceLock,+ },+};++pub(super) type CleanupAction = Arc<dyn Fn() -> bool + Send + Sync>;++#[derive(Default)]+pub(super) struct CleanupReservation {+ pub(super) after_close: Mutex<Option<CleanupAction>>,+ pub(super) host_completion_pending: AtomicBool,+}++pub(super) static CLEANUP_RESERVATIONS: OnceLock<Mutex<HashMap<PathBuf, Arc<CleanupReservation>>>> =+ OnceLock::new();++pub(super) fn directory_pending(workspace: &std::path::Path, agent_id: &str) -> bool {+ CLEANUP_RESERVATIONS.get().is_some_and(|reservations| {+ reservations+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .contains_key(&workspace.join("agents").join(agent_id))+ })+}++/// Run captured cleanup on the process module executor when modules are enabled.+/// Without modules, the caller must keep its current Tokio runtime alive.+/// This creates no configured client and loads no MCP artifact.+pub fn spawn_agent_cleanup<F>(+ future: F,+) -> Result<tokio::task::JoinHandle<F::Output>, ModuleCallError>+where+ F: std::future::Future + Send + 'static,+ F::Output: Send + 'static,+{+ #[cfg(feature = "modules")]+ {+ crate::modules::host::spawn_cleanup(future).map_err(|_| ModuleCallError::TransportFailed)+ }+ #[cfg(not(feature = "modules"))]+ {+ tokio::runtime::Handle::try_current()+ .map(|handle| handle.spawn(future))+ .map_err(|_| ModuleCallError::Unavailable)+ }+}++/// A process-local directory reservation with no runtime guard or callback.+/// Dropping the token retains the fence; only confirmed host completion clears it.+#[derive(Clone)]+pub struct AgentDirectoryCleanup {+ directory: PathBuf,+ reservation: Arc<CleanupReservation>,+}++/// Reserve an agent's directory until host-owned cleanup succeeds.+/// This never creates a client or loads a module.+pub fn reserve_agent_directory(+ workspace: &std::path::Path,+ agent_id: &str,+) -> AgentDirectoryCleanup {+ let directory = workspace.join("agents").join(agent_id);+ let mut reservations = CLEANUP_RESERVATIONS+ .get_or_init(|| Mutex::new(HashMap::new()))+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ let reservation = Arc::clone(+ reservations+ .entry(directory.clone())+ .or_insert_with(|| Arc::new(CleanupReservation::default())),+ );+ reservation+ .host_completion_pending+ .store(true, Ordering::Release);+ AgentDirectoryCleanup {+ directory,+ reservation,+ }+}++impl AgentDirectoryCleanup {+ /// Release this exact reservation after module close and host purge succeed.+ /// An independently registered canonical callback keeps its own reservation.+ pub fn complete(&self) {+ let after_close = self+ .reservation+ .after_close+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ let mut reservations = CLEANUP_RESERVATIONS+ .get_or_init(|| Mutex::new(HashMap::new()))+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ if reservations+ .get(&self.directory)+ .is_some_and(|current| Arc::ptr_eq(current, &self.reservation))+ {+ self.reservation+ .host_completion_pending+ .store(false, Ordering::Release);+ if after_close.is_none() {+ reservations.remove(&self.directory);+ }+ }+ }+}++/// An opaque cleanup handle for a build with no MCP client capability.+/// Such a build cannot create the handle or hold MCP resources.+#[cfg(not(feature = "mcp"))]+#[derive(Clone)]+pub struct AgentMcpCleanup {+ _unconstructible: (),+}++#[cfg(not(feature = "mcp"))]+impl AgentMcpCleanup {+ /// There are no MCP resources in this compiled-out capability.+ pub async fn finish(&self) -> Result<(), ModuleCallError> {+ Ok(())+ }++ /// There are no MCP resources to drain or retire.+ pub fn finish_if_idle(&self) -> bool {+ true+ }+}++/// A build without MCP cannot contain a configured MCP client.+#[cfg(not(feature = "mcp"))]+pub fn take_agent_cleanup(_workspace: &std::path::Path, _id: &str) -> Option<AgentMcpCleanup> {+ None+}diff --git a/crates/openhuman-core/src/mcp/mod.rs b/crates/openhuman-core/src/mcp/mod.rsindex bc1236ad57..fa985b1039 100644--- a/crates/openhuman-core/src/mcp/mod.rs+++ b/crates/openhuman-core/src/mcp/mod.rs@@ -65,6 +65,8 @@ pub fn start(config: &crate::config::Config) {#[cfg(feature = "mcp")]pub(crate) mod module_client;+mod host_cleanup;+/// Brings this domain up — the build without it, where there is nothing to do.#[cfg(not(feature = "mcp"))]pub fn start(_config: &crate::config::Config) {}diff --git a/crates/openhuman-core/src/mcp/module_client.rs b/crates/openhuman-core/src/mcp/module_client.rsindex 1bc36f1eb1..dc46de5004 100644--- a/crates/openhuman-core/src/mcp/module_client.rs+++ b/crates/openhuman-core/src/mcp/module_client.rs@@ -26,6 +26,8 @@ use tinymcp_bus::{ValidateServerArgumentsRequest,};+use super::host_cleanup::{CleanupAction, CleanupReservation, CLEANUP_RESERVATIONS};+use crate::{config::Config,modules::{client::ModuleCallError, client::ModuleClient},@@ -35,16 +37,6 @@ const MODULE: &str = "tinymcp";const TRANSITION_TIMEOUT: Duration = Duration::from_secs(30);const TRANSITION_POLL_INTERVAL: Duration = Duration::from_millis(20);static CLIENTS: OnceLock<Mutex<HashMap<PathBuf, Arc<McpConfiguredClient>>>> = OnceLock::new();-type CleanupAction = Arc<dyn Fn() -> bool + Send + Sync>;--#[derive(Default)]-struct CleanupReservation {- after_close: Mutex<Option<CleanupAction>>,- host_completion_pending: AtomicBool,-}--static CLEANUP_RESERVATIONS: OnceLock<Mutex<HashMap<PathBuf, Arc<CleanupReservation>>>> =- OnceLock::new();static SHUTDOWN_REGISTERED: AtomicBool = AtomicBool::new(false);static SHUTTING_DOWN: AtomicBool = AtomicBool::new(false);diff --git a/crates/openhuman-core/src/mcp/module_client_owner_tests.rs b/crates/openhuman-core/src/mcp/module_client_owner_tests.rsindex 4328af03c8..fece60a8c9 100644--- a/crates/openhuman-core/src/mcp/module_client_owner_tests.rs+++ b/crates/openhuman-core/src/mcp/module_client_owner_tests.rs@@ -413,7 +413,7 @@ async fn a_blocked_close_has_an_overall_cleanup_deadline_and_keeps_the_owner_forfn orphaned_shutdown_cleanup_keeps_a_host_directory_reservation_until_confirmed() {let scratch = tempfile::tempdir().unwrap();let directory = scratch.path().join("agents/purge-pending");- let token = agent_cleanup::reserve_agent_directory(scratch.path(), "purge-pending");+ let token = crate::mcp::host::reserve_agent_directory(scratch.path(), "purge-pending");McpConfiguredClient::retry_orphaned_cleanups();assert!(McpConfiguredClient::agent_close_pending(&directory));let reservation = McpConfiguredClient::reservation_for(&directory);diff --git a/crates/openhuman-embed/src/agent/mcp_cleanup.rs b/crates/openhuman-embed/src/agent/mcp_cleanup.rsindex 2e09a2996d..fab6927e9b 100644--- a/crates/openhuman-embed/src/agent/mcp_cleanup.rs+++ b/crates/openhuman-embed/src/agent/mcp_cleanup.rs@@ -127,6 +127,7 @@ wherematch result {Ok(()) => {owner.confirmed = true;+ drop(owner);return;}Err(error) => {