Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

feat(agent): defer MCP cleanup when agent teardown fails

Steven Enamakel7d9cab37edb4
diff --git a/crates/openhuman-embed/src/agent/build.rs b/crates/openhuman-embed/src/agent/build.rs
index cfc609e42f..ab72d1eaad 100644
--- a/crates/openhuman-embed/src/agent/build.rs
+++ b/crates/openhuman-embed/src/agent/build.rs
@@ -338,6 +338,7 @@ pub(crate) fn instantiate(runtime: &Runtime, spec: AgentSpec) -> Result<AgentInn
host_tools: parts.host_tools,
hooks: parts.hooks,
lifecycle,
+ mcp_cleanup: Default::default(),
host_only,
})
}
diff --git a/crates/openhuman-embed/src/agent/mcp_cleanup.rs b/crates/openhuman-embed/src/agent/mcp_cleanup.rs
new file mode 100644
index 0000000000..c0065d76dd
--- /dev/null
+++ b/crates/openhuman-embed/src/agent/mcp_cleanup.rs
@@ -0,0 +1,89 @@
+//! Retiring one captured agent owner before its id or home is reusable.
+use super::*;
+use std::sync::{atomic::Ordering, Weak};
+
+fn finish_removal(
+ registry: &crate::runtime::AgentMap,
+ id: &str,
+ instance: &Weak<AgentInner>,
+ home: &Path,
+ purge: bool,
+) -> Result<(), AgentError> {
+ let mut agents = registry.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
+ if !agents.get(id).is_some_and(|current| Weak::ptr_eq(current, instance)) {
+ return Ok(());
+ }
+ // Keep the id reserved during purge. A second cleanup cannot delete the
+ // home of a replacement that another caller has already instantiated.
+ if purge && home.exists() {
+ std::fs::remove_dir_all(home).map_err(|source| AgentError::Workspace {
+ what: "delete the removed agent's home", source,
+ })?;
+ }
+ agents.remove(id);
+ Ok(())
+}
+
+impl AgentInner {
+ pub(crate) fn cleanup_is_pending(&self) -> bool {
+ self.mcp_cleanup.lock().unwrap_or_else(std::sync::PoisonError::into_inner).is_some()
+ }
+
+ pub(crate) async fn finish_mcp_cleanup(&self) -> Result<(), AgentError> {
+ let cleanup = self.mcp_cleanup.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone();
+ if let Some(cleanup) = cleanup {
+ cleanup.finish().await.map_err(AgentError::McpCleanup)?;
+ self.mcp_cleanup.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take();
+ }
+ Ok(())
+ }
+
+ pub(crate) fn finish_removal(&self, purge: bool) -> Result<(), AgentError> {
+ let instance = self.registry.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
+ .get(&self.id).filter(|weak| std::ptr::eq(weak.as_ptr(), self)).cloned();
+ if let Some(instance) = instance {
+ finish_removal(&self.registry, &self.id, &instance, &self.layout.home, purge)?;
+ }
+ Ok(())
+ }
+
+ /// Retry independently of the caller runtime. The task, rather than a
+ /// process-global callback, holds the workspace guard while cleanup runs.
+ pub(crate) fn defer_cleanup(&self, purge: bool) {
+ let cleanup = self.mcp_cleanup.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone();
+ if cleanup.as_ref().is_none_or(|cleanup| cleanup.finish_if_idle()) {
+ if let Err(error) = self.finish_removal(purge) {
+ log::warn!("[embed][agent] removed home cleanup failed: {error}");
+ }
+ return;
+ }
+ if self.cleanup_started.swap(true, Ordering::AcqRel) { return; }
+ let Some(cleanup) = cleanup else { return; };
+ let instance = self.registry.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
+ .get(&self.id).filter(|weak| std::ptr::eq(weak.as_ptr(), self)).cloned();
+ let Some(instance) = instance else { return; };
+ let registry = Arc::clone(&self.registry);
+ let guard = Arc::clone(&self._runtime_guard);
+ let home = self.layout.home.clone();
+ let id = self.id.clone();
+ let future = async move {
+ let _guard = guard;
+ let mut delay = std::time::Duration::from_millis(250);
+ loop {
+ let result = match cleanup.finish().await {
+ Ok(()) => finish_removal(&registry, &id, &instance, &home, purge),
+ Err(error) => Err(AgentError::McpCleanup(error)),
+ };
+ match result {
+ Ok(()) => return,
+ Err(error) => log::warn!("[embed][agent] captured cleanup remains pending: {error}"),
+ }
+ tokio::time::sleep(delay).await;
+ delay = (delay * 2).min(std::time::Duration::from_secs(5));
+ }
+ };
+ if let Err(error) = openhuman_core::mcp::host::spawn_agent_cleanup(future) {
+ log::warn!("[embed][agent] cleanup executor unavailable: {error}");
+ }
+ }
+}
diff --git a/crates/openhuman-embed/src/agent/mod.rs b/crates/openhuman-embed/src/agent/mod.rs
index 13ea47e015..9de9320956 100644
--- a/crates/openhuman-embed/src/agent/mod.rs
+++ b/crates/openhuman-embed/src/agent/mod.rs
@@ -19,6 +19,7 @@ mod approvals;
pub use approval_handler::{ApprovalHandler, ApprovalSubscription};
mod attachments;
pub(crate) mod lifecycle;
+pub(crate) mod mcp_cleanup;
pub use approvals::{ApprovalDecision, Approvals, ApprovalsError, PendingApproval};
pub use attachments::ToolAttachmentError;
pub(crate) mod build;
@@ -102,6 +103,10 @@ pub enum AgentError {
/// A named built-in definition does not exist.
#[error("unknown built-in agent definition {0:?}")]
UnknownDefinition(String),
+ /// The agent is removed, but its original MCP owner still needs cleanup.
+ /// Its id and home remain reserved while detached cleanup retries.
+ #[error("agent MCP cleanup is still pending: {0}")]
+ McpCleanup(#[source] openhuman_core::modules::client::ModuleCallError),
}
/// The assembled state behind an [`Agent`], shared by every clone of it and
@@ -132,6 +137,7 @@ pub(crate) struct AgentInner {
pub(crate) host_tools: Option<openhuman_core::agent::HostTools>,
pub(crate) hooks: openhuman_core::agent::hooks::HookScope,
pub(crate) lifecycle: lifecycle::Lifecycle,
+ pub(crate) mcp_cleanup: std::sync::Mutex<Option<openhuman_core::mcp::host::AgentMcpCleanup>>,
/// Built from [`ToolScopeSpec::HostOnly`]: every turn's session is built
/// from the host tools alone.
pub(crate) host_only: bool,
@@ -153,14 +159,8 @@ impl AgentInner {
);
self.deny_approvals(resolution);
self.ctx.agent_state().clear();
- if openhuman_core::mcp::host::take_agent_host(&self.config.workspace_dir, &self.id)
- .is_some()
- {
- log::debug!(
- "[embed][agent] teardown id={} evicted its MCP host",
- self.id
- );
- }
+ *self.mcp_cleanup.lock().unwrap_or_else(std::sync::PoisonError::into_inner) =
+ openhuman_core::mcp::host::take_agent_cleanup(&self.config.workspace_dir, &self.id);
openhuman_core::core::runtime::AgentContextRegistry::deregister(&self.id, &self.ctx);
log::debug!("[embed][agent] teardown complete id={}", self.id);
}
@@ -189,13 +189,7 @@ impl AgentInner {
impl Drop for AgentInner {
fn drop(&mut self) {
self.teardown("agent_dropped");
- let mut agents = self.registry.lock().unwrap_or_else(|e| e.into_inner());
- if agents
- .get(&self.id)
- .is_some_and(|current| std::ptr::eq(current.as_ptr(), self))
- {
- agents.remove(&self.id);
- }
+ self.defer_cleanup(false);
}
}
diff --git a/crates/openhuman-embed/src/runtime/host_agents.rs b/crates/openhuman-embed/src/runtime/host_agents.rs
index 8cadfbcdb8..1a910aee48 100644
--- a/crates/openhuman-embed/src/runtime/host_agents.rs
+++ b/crates/openhuman-embed/src/runtime/host_agents.rs
@@ -15,7 +15,33 @@ use openhuman_core::agent::host_agents::{HostAgent, HostAgentResolver};
use crate::agent::AgentInner;
/// The live agents of one runtime, by id.
-pub(crate) type AgentMap = Mutex<HashMap<String, Weak<AgentInner>>>;
+pub(crate) type AgentMap = Mutex<AgentRegistry>;
+
+/// Failed cleanup retains its captured owner and purge intent, without keeping
+/// an agent or the runtime guard alive. `remove_agent` can retry this record.
+#[derive(Clone)]
+pub(crate) struct PendingCleanup {
+ pub(crate) cleanup: Option<openhuman_core::mcp::host::AgentMcpCleanup>,
+ pub(crate) instance: Weak<AgentInner>,
+ pub(crate) home: std::path::PathBuf,
+ pub(crate) purge: bool,
+ pub(crate) retry_running: Arc<std::sync::atomic::AtomicBool>,
+}
+
+#[derive(Default)]
+pub(crate) struct AgentRegistry {
+ live: HashMap<String, Weak<AgentInner>>,
+ pub(crate) pending: HashMap<String, PendingCleanup>,
+}
+
+impl std::ops::Deref for AgentRegistry {
+ type Target = HashMap<String, Weak<AgentInner>>;
+ fn deref(&self) -> &Self::Target { &self.live }
+}
+
+impl std::ops::DerefMut for AgentRegistry {
+ fn deref_mut(&mut self) -> &mut Self::Target { &mut self.live }
+}
pub(crate) struct RuntimeAgents(pub(crate) Arc<AgentMap>);
diff --git a/crates/openhuman-embed/src/runtime/mod.rs b/crates/openhuman-embed/src/runtime/mod.rs
index 253444024a..5c89640207 100644
--- a/crates/openhuman-embed/src/runtime/mod.rs
+++ b/crates/openhuman-embed/src/runtime/mod.rs
@@ -72,6 +72,7 @@ pub(crate) mod builder;
mod defaults;
mod host_agents;
pub(crate) use host_agents::AgentMap;
+pub(crate) use host_agents::PendingCleanup;
mod info;
mod lifecycle;
mod live_hooks;
@@ -596,7 +597,7 @@ impl Runtime {
storage_info: StorageInfo,
storage_backend: Option<Arc<dyn openhuman_core::storage::StorageBackend>>,
) -> Self {
- let agents: Arc<host_agents::AgentMap> = Arc::new(Mutex::new(HashMap::new()));
+ let agents: Arc<host_agents::AgentMap> = Arc::new(Mutex::new(Default::default()));
let resolver: Arc<dyn openhuman_core::agent::host_agents::HostAgentResolver> =
Arc::new(host_agents::RuntimeAgents(Arc::clone(&agents)));
openhuman_core::agent::host_agents::install(Arc::clone(&resolver));