Skip to content

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

merge: integrate canonical MCP cleanup and admitted tool changes

Steven Enamakel542434bcac83
diff --cc crates/openhuman-core/src/mcp/agent_cleanup.rs
index 7324a9e04a,0000000000..d8ba90007e
mode 100644,000000..100644
--- a/crates/openhuman-core/src/mcp/agent_cleanup.rs
+++ b/crates/openhuman-core/src/mcp/agent_cleanup.rs
@@@ -1,97 -1,0 +1,87 @@@
+//! Captured cleanup of an agent's existing configured module object.
+use super::*;
+
+/// A retired agent's original MCP owner and its retryable close receipts.
+/// Capturing this handle never creates a client or loads a module.
+#[derive(Clone)]
+pub struct AgentMcpCleanup {
+ directory: PathBuf,
+ client: Arc<McpConfiguredClient>,
+}
+
+/// Retire the existing configured client for this exact agent directory.
+/// An absent entry requires no cleanup and leaves the module loader untouched.
+pub fn take_agent_cleanup(workspace: &std::path::Path, agent_id: &str) -> Option<AgentMcpCleanup> {
+ let directory = workspace.join("agents").join(agent_id);
+ let clients = CLIENTS
+ .get()?
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ let client = Arc::clone(clients.get(&directory)?);
- client.retired.store(true, Ordering::Release);
++ client.retiring.store(true, Ordering::Release);
+ Some(AgentMcpCleanup { directory, client })
+}
+
- pub(super) fn agent_is_removed() -> bool {
- crate::core::runtime::CoreContext::current().is_some_and(|ctx| {
- ctx.session_agent().is_some()
- && ctx
- .host_overrides()
- .and_then(|overrides| overrides.approval_scope())
- .is_some_and(|scope| scope.is_closed())
- })
- }
-
+impl AgentMcpCleanup {
+ /// Close the original object and evict it only after confirmed cleanup.
+ /// The whole attempt, including lock acquisition and bus calls, has a
+ /// 30-second deadline. Timeout returns `TransportFailed`; cancellation or
+ /// error retains the same client and transition receipt for explicit retry.
+ pub async fn finish(&self) -> Result<(), ModuleCallError> {
+ tokio::time::timeout(TRANSITION_TIMEOUT, self.client.close())
+ .await
+ .map_err(|_| ModuleCallError::TransportFailed)??;
+ self.evict();
+ Ok(())
+ }
+
+ /// Finish an unused client without starting an asynchronous executor.
+ /// An accepted call holding the lifecycle lock requires asynchronous drain.
+ pub fn finish_if_idle(&self) -> bool {
+ let Ok(state) = self.client.state.try_lock() else {
+ return false;
+ };
+ if !matches!(*state, State::Closed) {
+ return false;
+ }
+ self.evict();
+ true
+ }
+
+ fn evict(&self) {
+ let Some(clients) = CLIENTS.get() else {
+ return;
+ };
+ let mut clients = clients
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ if clients
+ .get(&self.directory)
+ .is_some_and(|current| Arc::ptr_eq(current, &self.client))
+ {
+ clients.remove(&self.directory);
+ }
+ }
+}
+
+/// 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)
+ }
+}
diff --cc crates/openhuman-core/src/mcp/cached_cleanup.rs
index 0000000000,0000000000..b46984b764
new file mode 100644
--- /dev/null
+++ b/crates/openhuman-core/src/mcp/cached_cleanup.rs
@@@ -1,0 -1,0 +1,255 @@@
++//! Existing scoped cleanup and callback reservations.
++use super::*;
++
++impl McpConfiguredClient {
++ /// Close an already-open agent-scoped client without creating one. A
++ /// failed close remains in the cache, marked unavailable, so shutdown or
++ /// a later cleanup attempt can retry the module's retained transition.
++ pub(crate) async fn close_agent_data_dir(data_dir: &std::path::Path) -> bool {
++ let key = data_dir.to_path_buf();
++ let reservation = Self::reservation_for(&key);
++ let Some(client) = Self::retire_cached_client(&key) else {
++ return Self::finish_cleanup(&key, None, reservation);
++ };
++ if let Some(cleaned) = Self::finish_closed_client_synchronously(&key, &client, &reservation)
++ {
++ return cleaned;
++ }
++ Self::close_retired_client(key, client, reservation).await
++ }
++
++ /// Marks the exact cached client unavailable before scheduling cleanup.
++ /// If no Tokio runtime is active, the retired client remains cached for the
++ /// registered shutdown hook to close later.
++ pub(crate) fn schedule_agent_close_data_dir(data_dir: &std::path::Path) {
++ let key = data_dir.to_path_buf();
++ let reservation = Self::reservation_for(&key);
++ let Some(client) = Self::retire_cached_client(&key) else {
++ Self::finish_cleanup(&key, None, reservation);
++ return;
++ };
++ if Self::finish_closed_client_synchronously(&key, &client, &reservation).is_some() {
++ return;
++ }
++ let Ok(runtime) = tokio::runtime::Handle::try_current() else {
++ return;
++ };
++ runtime.spawn(async move {
++ if !Self::close_retired_client(key, client, reservation).await {
++ tracing::warn!("[mcp] agent client close remains pending for retry");
++ }
++ });
++ }
++
++ /// Retires the exact scoped client and runs `after_close` only after the
++ /// module acknowledges its close. The path remains unavailable until the
++ /// callback succeeds, so a replacement cannot reuse files being purged.
++ pub(crate) fn schedule_agent_close_and_cleanup(
++ data_dir: &std::path::Path,
++ after_close: CleanupAction,
++ ) {
++ let key = data_dir.to_path_buf();
++ let reservation = Self::reservation_with_action(&key, after_close);
++ let Some(client) = Self::retire_cached_client(&key) else {
++ if !Self::finish_cleanup(&key, None, reservation) {
++ tracing::warn!("[mcp] agent cleanup remains pending for retry");
++ }
++ return;
++ };
++ if Self::finish_closed_client_synchronously(&key, &client, &reservation).is_some() {
++ return;
++ }
++ let Ok(runtime) = tokio::runtime::Handle::try_current() else {
++ return;
++ };
++ runtime.spawn(async move {
++ if !Self::close_retired_client(key, client, reservation).await {
++ tracing::warn!("[mcp] agent close and cleanup remain pending for retry");
++ }
++ });
++ }
++
++ pub(super) fn retry_orphaned_cleanups() {
++ let reservations = CLEANUP_RESERVATIONS
++ .get()
++ .map(|reservations| {
++ reservations
++ .lock()
++ .unwrap_or_else(std::sync::PoisonError::into_inner)
++ .iter()
++ .map(|(path, reservation)| (path.clone(), Arc::clone(reservation)))
++ .collect::<Vec<_>>()
++ })
++ .unwrap_or_default();
++ for (data_dir, reservation) in reservations {
++ let has_client = CLIENTS.get().is_some_and(|clients| {
++ clients
++ .lock()
++ .unwrap_or_else(std::sync::PoisonError::into_inner)
++ .contains_key(&data_dir)
++ });
++ if !has_client {
++ Self::finish_cleanup(&data_dir, None, reservation);
++ }
++ }
++ }
++
++ pub(crate) fn agent_close_pending(data_dir: &std::path::Path) -> bool {
++ Self::cleanup_pending(data_dir)
++ || CLIENTS
++ .get()
++ .and_then(|clients| {
++ clients
++ .lock()
++ .unwrap_or_else(std::sync::PoisonError::into_inner)
++ .get(data_dir)
++ .map(|client| client.retiring.load(Ordering::Acquire))
++ })
++ .unwrap_or(false)
++ }
++
++ pub(super) fn cleanup_pending(data_dir: &std::path::Path) -> bool {
++ CLEANUP_RESERVATIONS.get().is_some_and(|reservations| {
++ reservations
++ .lock()
++ .unwrap_or_else(std::sync::PoisonError::into_inner)
++ .contains_key(data_dir)
++ })
++ }
++
++ pub(super) fn reservation_for(data_dir: &std::path::Path) -> Arc<CleanupReservation> {
++ let reservations = CLEANUP_RESERVATIONS.get_or_init(|| Mutex::new(HashMap::new()));
++ let mut reservations = reservations
++ .lock()
++ .unwrap_or_else(std::sync::PoisonError::into_inner);
++ Arc::clone(
++ reservations
++ .entry(data_dir.to_path_buf())
++ .or_insert_with(|| Arc::new(CleanupReservation::default())),
++ )
++ }
++
++ pub(super) fn reservation_with_action(
++ data_dir: &std::path::Path,
++ action: CleanupAction,
++ ) -> Arc<CleanupReservation> {
++ loop {
++ let reservation = Self::reservation_for(data_dir);
++ let mut after_close = reservation
++ .after_close
++ .lock()
++ .unwrap_or_else(std::sync::PoisonError::into_inner);
++ let current = CLEANUP_RESERVATIONS
++ .get()
++ .and_then(|reservations| {
++ reservations
++ .lock()
++ .unwrap_or_else(std::sync::PoisonError::into_inner)
++ .get(data_dir)
++ .is_some_and(|stored| Arc::ptr_eq(stored, &reservation))
++ .then_some(())
++ })
++ .is_some();
++ if !current {
++ continue;
++ }
++ after_close.get_or_insert(action);
++ return Arc::clone(&reservation);
++ }
++ }
++
++ pub(super) fn retire_cached_client(data_dir: &std::path::Path) -> Option<Arc<Self>> {
++ let clients = CLIENTS.get().map(|clients| {
++ clients
++ .lock()
++ .unwrap_or_else(std::sync::PoisonError::into_inner)
++ })?;
++ let client = clients.get(data_dir)?;
++ client.retiring.store(true, Ordering::Release);
++ Some(Arc::clone(client))
++ }
++
++ pub(super) fn finish_closed_client_synchronously(
++ data_dir: &std::path::Path,
++ client: &Arc<Self>,
++ reservation: &Arc<CleanupReservation>,
++ ) -> Option<bool> {
++ let Ok(state) = client.state.try_lock() else {
++ return None;
++ };
++ let is_closed = matches!(&*state, State::Closed);
++ drop(state);
++ is_closed.then(|| {
++ Self::finish_cleanup(data_dir, Some(Arc::clone(client)), Arc::clone(reservation))
++ })
++ }
++
++ pub(super) async fn close_retired_client(
++ data_dir: PathBuf,
++ client: Arc<Self>,
++ reservation: Arc<CleanupReservation>,
++ ) -> bool {
++ match client.close().await {
++ Ok(()) => Self::finish_cleanup(&data_dir, Some(client), reservation),
++ Err(error) => {
++ tracing::warn!(?error, "[mcp] agent client close remains pending");
++ false
++ }
++ }
++ }
++
++ pub(super) fn finish_cleanup(
++ data_dir: &std::path::Path,
++ client: Option<Arc<Self>>,
++ reservation: Arc<CleanupReservation>,
++ ) -> bool {
++ let after_close = reservation
++ .after_close
++ .lock()
++ .unwrap_or_else(std::sync::PoisonError::into_inner);
++ let reservations = CLEANUP_RESERVATIONS.get_or_init(|| Mutex::new(HashMap::new()));
++ let is_current = reservations
++ .lock()
++ .unwrap_or_else(std::sync::PoisonError::into_inner)
++ .get(data_dir)
++ .is_some_and(|stored| Arc::ptr_eq(stored, &reservation));
++ if !is_current {
++ return false;
++ }
++ let mut clients = if let Some(client) = client.as_ref() {
++ let Some(clients) = CLIENTS.get() else {
++ return false;
++ };
++ let clients = clients
++ .lock()
++ .unwrap_or_else(std::sync::PoisonError::into_inner);
++ if !clients
++ .get(data_dir)
++ .is_some_and(|current| Arc::ptr_eq(current, client))
++ {
++ return false;
++ }
++ Some(clients)
++ } else {
++ None
++ };
++ if after_close.as_ref().is_some_and(|action| !action()) {
++ return false;
++ }
++ if let Some(clients) = clients.as_mut() {
++ clients.remove(data_dir);
++ }
++ let mut reservations = reservations
++ .lock()
++ .unwrap_or_else(std::sync::PoisonError::into_inner);
++ if reservations
++ .get(data_dir)
++ .is_some_and(|stored| Arc::ptr_eq(stored, &reservation))
++ {
++ reservations.remove(data_dir);
++ true
++ } else {
++ false
++ }
++ }
++}
diff --cc crates/openhuman-core/src/mcp/module_client.rs
index 039ed96835,6026b323be..e739b0329e
--- a/crates/openhuman-core/src/mcp/module_client.rs
+++ b/crates/openhuman-core/src/mcp/module_client.rs
@@@ -114,12 -127,115 +127,15 @@@ pub(crate) trait McpModulePort: Send +
}
}
-struct TinyMcpPort {
- root: ModuleClient,
-}
-
-#[async_trait]
-impl McpModulePort for TinyMcpPort {
- async fn open_configured(
- &self,
- data_dir: &str,
- config: &McpClientConfig,
- ) -> Result<OpenConfiguredResponse, ModuleCallError> {
- self.root
- .call_confidential(
- MODULE,
- names::methods::OPEN_CONFIGURED,
- (OpenConfiguredRequest {
- data_dir: data_dir.to_owned(),
- client: config.clone(),
- },),
- )
- .await
- }
-
- async fn close(&self, data_dir: &str) -> Result<Option<String>, ModuleCallError> {
- self.root
- .call(MODULE, names::methods::CLOSE, (data_dir.to_owned(),))
- .await
- }
-
- async fn transition_status(
- &self,
- transition_id: &str,
- ) -> Result<TransitionStatus, ModuleCallError> {
- self.root
- .call(
- MODULE,
- names::methods::TRANSITION_STATUS,
- (transition_id.to_owned(),),
- )
- .await
- }
-
- async fn call_object(
- &self,
- object_path: &str,
- member: &str,
- args: Value,
- confidential: bool,
- ) -> Result<Value, ModuleCallError> {
- #[cfg(feature = "modules")]
- {
- let object = self.root.object_client(MODULE, object_path).await?;
- if confidential {
- object.call_confidential(member, args).await
- } else {
- object.call(member, args).await
- }
- }
- #[cfg(not(feature = "modules"))]
- {
- let _ = (object_path, member, args, confidential);
- Err(ModuleCallError::Unavailable)
- }
- }
-
- async fn prepare_agent_tools(
- &self,
- request: PrepareAgentToolsRequest,
- ) -> Result<Vec<McpToolPresentation>, ModuleCallError> {
- self.root
- .call(MODULE, names::methods::PREPARE_AGENT_TOOLS, (request,))
- .await
- }
-
- async fn validate_server_arguments(
- &self,
- request: ValidateServerArgumentsRequest,
- ) -> Result<ServerArgumentsValidation, ModuleCallError> {
- self.root
- .call_confidential(
- MODULE,
- names::methods::VALIDATE_SERVER_ARGUMENTS,
- (request,),
- )
- .await
- }
+#[path = "module_port.rs"]
+mod module_port;
+use module_port::TinyMcpPort;
- async fn normalize_tool_arguments(
- &self,
- arguments: Option<Value>,
- ) -> Result<Map<String, Value>, ModuleCallError> {
- self.root
- .call_confidential(
- MODULE,
- names::methods::NORMALIZE_TOOL_ARGUMENTS,
- (arguments,),
- )
- .await
- }
++#[path = "cached_cleanup.rs"]
++mod cached_cleanup;
+
- async fn transform_text(
- &self,
- request: tinymcp_bus::TransformTextRequest,
- ) -> Result<String, ModuleCallError> {
- self.root
- .call_confidential(MODULE, names::methods::TRANSFORM_TEXT, (request,))
- .await
- }
-}
+#[path = "agent_cleanup.rs"]
+pub(crate) mod agent_cleanup;
/// One workspace's serialized TinyMCP lifecycle and private object proxy.
pub(crate) struct McpConfiguredClient {
@@@ -309,8 -705,10 +352,8 @@@ impl McpConfiguredClient
&self,
request: PrepareAgentToolsRequest,
) -> Result<Vec<McpToolPresentation>, ModuleCallError> {
- if SHUTTING_DOWN.load(Ordering::Acquire) {
- return Err(ModuleCallError::Unavailable);
- }
- if self.retiring.load(Ordering::Acquire) {
+ let _accepted = self.state.lock().await;
- if SHUTTING_DOWN.load(Ordering::Acquire) || self.retired.load(Ordering::Acquire) {
++ if SHUTTING_DOWN.load(Ordering::Acquire) || self.retiring.load(Ordering::Acquire) {
return Err(ModuleCallError::Unavailable);
}
self.port.prepare_agent_tools(request).await
@@@ -339,8 -737,10 +382,8 @@@
&self,
request: ValidateServerArgumentsRequest,
) -> Result<ServerArgumentsValidation, ModuleCallError> {
- if SHUTTING_DOWN.load(Ordering::Acquire) {
- return Err(ModuleCallError::Unavailable);
- }
- if self.retiring.load(Ordering::Acquire) {
+ let _accepted = self.state.lock().await;
- if SHUTTING_DOWN.load(Ordering::Acquire) || self.retired.load(Ordering::Acquire) {
++ if SHUTTING_DOWN.load(Ordering::Acquire) || self.retiring.load(Ordering::Acquire) {
return Err(ModuleCallError::Unavailable);
}
self.port.validate_server_arguments(request).await
@@@ -352,8 -752,10 +395,8 @@@
&self,
arguments: Option<Value>,
) -> Result<Map<String, Value>, ModuleCallError> {
- if SHUTTING_DOWN.load(Ordering::Acquire) {
- return Err(ModuleCallError::Unavailable);
- }
- if self.retiring.load(Ordering::Acquire) {
+ let _accepted = self.state.lock().await;
- if SHUTTING_DOWN.load(Ordering::Acquire) || self.retired.load(Ordering::Acquire) {
++ if SHUTTING_DOWN.load(Ordering::Acquire) || self.retiring.load(Ordering::Acquire) {
return Err(ModuleCallError::Unavailable);
}
self.port.normalize_tool_arguments(arguments).await
@@@ -364,8 -766,10 +407,8 @@@
&self,
value: &str,
) -> Result<String, ModuleCallError> {
- if SHUTTING_DOWN.load(Ordering::Acquire) {
- return Err(ModuleCallError::Unavailable);
- }
- if self.retiring.load(Ordering::Acquire) {
+ let _accepted = self.state.lock().await;
- if SHUTTING_DOWN.load(Ordering::Acquire) || self.retired.load(Ordering::Acquire) {
++ if SHUTTING_DOWN.load(Ordering::Acquire) || self.retiring.load(Ordering::Acquire) {
return Err(ModuleCallError::Unavailable);
}
self.port
diff --cc crates/openhuman-core/src/mcp/module_client_owner_tests.rs
index fce94fcda9,0000000000..d6745a948c
mode 100644,000000..100644
--- a/crates/openhuman-core/src/mcp/module_client_owner_tests.rs
+++ b/crates/openhuman-core/src/mcp/module_client_owner_tests.rs
@@@ -1,410 -1,0 +1,410 @@@
+use super::*;
+use std::sync::atomic::AtomicUsize;
+use tinybus::{broker::Broker, transport::memory::MemoryBus, Connection, ObjectPath};
+
+#[derive(Clone, Default)]
+struct LifecycleFixture {
+ closes: Arc<AtomicUsize>,
+ polls: Arc<AtomicUsize>,
+ block_close_poll: Arc<AtomicBool>,
+ close_poll_started: Arc<tokio::sync::Notify>,
+ release_close_poll: Arc<tokio::sync::Notify>,
+ fail_close: Arc<AtomicBool>,
+ block_close: Arc<AtomicBool>,
+ close_started: Arc<tokio::sync::Notify>,
+ release_close: Arc<tokio::sync::Notify>,
+}
+
+#[tinybus::interface(name = "ai.tinyhumans.tinymcp.Mcp")]
+impl LifecycleFixture {
+ async fn close(&self, _data_dir: String) -> tinybus::Result<Option<String>> {
+ self.closes.fetch_add(1, Ordering::SeqCst);
+ if self.block_close.swap(false, Ordering::SeqCst) {
+ self.close_started.notify_one();
+ self.release_close.notified().await;
+ }
+ if self.fail_close.load(Ordering::SeqCst) {
+ return Err(tinybus::Error::failed("fixture cleanup unavailable"));
+ }
+ Ok(Some("original-close".into()))
+ }
+
+ async fn transition_status(&self, receipt: String) -> tinybus::Result<TransitionStatus> {
+ self.polls.fetch_add(1, Ordering::SeqCst);
+ if receipt == "original-close" && self.block_close_poll.swap(false, Ordering::SeqCst) {
+ self.close_poll_started.notify_one();
+ self.release_close_poll.notified().await;
+ }
+ Ok(TransitionStatus::Complete)
+ }
+}
+
+#[tokio::test]
+async fn failed_agent_cleanup_retains_the_retired_owner_and_can_retry() {
+ let scratch = tempfile::tempdir().unwrap();
+ let directory = scratch.path().join("agents/worker");
+ let bus = MemoryBus::new();
+ Broker::new().spawn(bus.clone());
+ let service = Connection::connect(bus.connect().await.unwrap())
+ .await
+ .unwrap();
+ let caller = Connection::connect(bus.connect().await.unwrap())
+ .await
+ .unwrap();
+ let fixture = LifecycleFixture::default();
+ service
+ .serve_at(
+ ObjectPath::new(names::OBJECT_PATH).unwrap(),
+ fixture.clone(),
+ )
+ .await
+ .unwrap();
+ service.request_name(names::INTERFACE).await.unwrap();
+ let port = TinyMcpPort::new(ModuleClient::fixture(
+ caller
+ .proxy(names::INTERFACE, names::OBJECT_PATH, names::INTERFACE)
+ .unwrap(),
+ ));
+ port.transition_status("original-open").await.unwrap();
+ let client = Arc::new(McpConfiguredClient::with_port(
+ directory.to_str().unwrap().into(),
+ Box::new(port),
+ ));
+ *client.state.lock().await = State::Open(OpenObject {
+ config: McpClientConfig::default(),
+ object_path: "/test/original-child".into(),
+ });
+ CLIENTS
+ .get_or_init(|| Mutex::new(HashMap::new()))
+ .lock()
+ .unwrap()
+ .insert(directory.clone(), Arc::clone(&client));
+ let cleanup = agent_cleanup::take_agent_cleanup(scratch.path(), "worker").unwrap();
+ fixture.fail_close.store(true, Ordering::SeqCst);
+ assert_eq!(cleanup.finish().await, Err(ModuleCallError::ModuleFault));
+ assert!(Arc::ptr_eq(
+ CLIENTS
+ .get()
+ .unwrap()
+ .lock()
+ .unwrap()
+ .get(&directory)
+ .unwrap(),
+ &client
+ ));
+ assert!(matches!(
+ &*client.state.lock().await,
+ State::StartingClose(_)
+ ));
+ assert_eq!(
+ client
+ .call::<Value>(&McpClientConfig::default(), "NeverReopen", ())
+ .await,
+ Err(ModuleCallError::Unavailable)
+ );
+ fixture.fail_close.store(false, Ordering::SeqCst);
+ cleanup.finish().await.unwrap();
+ assert!(!CLIENTS
+ .get()
+ .unwrap()
+ .lock()
+ .unwrap()
+ .contains_key(&directory));
+ // Retrying the old completed handle cannot evict a later owner.
+ let successor = Arc::new(McpConfiguredClient::new(&directory, &Config::default()).unwrap());
+ CLIENTS
+ .get()
+ .unwrap()
+ .lock()
+ .unwrap()
+ .insert(directory.clone(), Arc::clone(&successor));
+ assert!(cleanup.finish_if_idle());
+ assert!(Arc::ptr_eq(
+ CLIENTS
+ .get()
+ .unwrap()
+ .lock()
+ .unwrap()
+ .get(&directory)
+ .unwrap(),
+ &successor
+ ));
+ CLIENTS.get().unwrap().lock().unwrap().remove(&directory);
+}
+
+#[test]
+fn an_absent_agent_cleanup_does_not_create_a_configured_client() {
+ let scratch = tempfile::tempdir().unwrap();
+ assert!(agent_cleanup::take_agent_cleanup(scratch.path(), "never-opened").is_none());
+ assert!(CLIENTS.get().is_none_or(|clients| !clients
+ .lock()
+ .unwrap()
+ .contains_key(&scratch.path().join("agents/never-opened"))));
+}
+
+#[tokio::test]
+async fn an_old_closed_context_cannot_create_the_reused_agents_first_client() {
+ use crate::core::runtime::{ContextOverlay, CoreContext, DomainSet};
+ use crate::tools::toolpacks::ToolGroups;
+ let scratch = tempfile::tempdir().unwrap();
+ let mut config = Config::default();
+ config.workspace_dir = scratch.path().into();
+ let parent = CoreContext::for_test(DomainSet::full(), Some(config.workspace_dir.clone()));
+ let old_scope = Arc::new(crate::security::approval::ApprovalScope::default());
+ let mut old_overrides = crate::agent::host_overrides::HostOverrides::default();
+ old_overrides.approval_scope = Some(Arc::clone(&old_scope));
+ let old_overrides = Arc::new(old_overrides);
+ let mut overlay = ContextOverlay::new(config.clone(), DomainSet::full(), ToolGroups::none())
+ .session_agent("worker");
+ overlay.host_overrides = Some(old_overrides);
+ let old_context = parent.derive_with(overlay);
+ old_scope.close("agent_removed");
+ CoreContext::scope(old_context, async {
+ assert!(matches!(
+ McpConfiguredClient::for_config(&config),
+ Err(ModuleCallError::Unavailable)
+ ));
+ })
+ .await;
+ let directory = config.workspace_dir.join("agents/worker");
+ assert!(CLIENTS
+ .get()
+ .is_none_or(|clients| !clients.lock().unwrap().contains_key(&directory)));
+ let mut new_overlay =
+ ContextOverlay::new(config.clone(), DomainSet::full(), ToolGroups::none())
+ .session_agent("worker");
+ let mut new_overrides = crate::agent::host_overrides::HostOverrides::default();
+ new_overrides.approval_scope =
+ Some(Arc::new(crate::security::approval::ApprovalScope::default()));
+ new_overlay.host_overrides = Some(Arc::new(new_overrides));
+ CoreContext::scope(parent.derive_with(new_overlay), async {
+ McpConfiguredClient::for_config(&config)
+ .expect("the new instance has an open lifecycle scope");
+ })
+ .await;
+ assert!(
+ agent_cleanup::take_agent_cleanup(&config.workspace_dir, "worker")
+ .unwrap()
+ .finish_if_idle()
+ );
+}
+
+#[tokio::test]
+async fn cancelled_close_retries_its_receipt_on_the_original_owner() {
+ let bus = MemoryBus::new();
+ Broker::new().spawn(bus.clone());
+ let original = Connection::connect(bus.connect().await.unwrap())
+ .await
+ .unwrap();
+ let replacement = Connection::connect(bus.connect().await.unwrap())
+ .await
+ .unwrap();
+ let caller = Connection::connect(bus.connect().await.unwrap())
+ .await
+ .unwrap();
+ let original_fixture = LifecycleFixture::default();
+ let replacement_fixture = LifecycleFixture::default();
+ for (connection, fixture) in [
+ (&original, original_fixture.clone()),
+ (&replacement, replacement_fixture.clone()),
+ ] {
+ connection
+ .serve_at(ObjectPath::new(names::OBJECT_PATH).unwrap(), fixture)
+ .await
+ .unwrap();
+ }
+ original.request_name(names::INTERFACE).await.unwrap();
+ let port = TinyMcpPort::new(ModuleClient::fixture(
+ caller
+ .proxy(names::INTERFACE, names::OBJECT_PATH, names::INTERFACE)
+ .unwrap(),
+ ));
+ assert_eq!(
+ port.transition_status("original-open").await,
+ Ok(TransitionStatus::Complete)
+ );
+ let client = Arc::new(McpConfiguredClient::with_port(
+ "/test/agent".into(),
+ Box::new(port),
+ ));
+ *client.state.lock().await = State::Open(OpenObject {
+ config: McpClientConfig::default(),
+ object_path: "/test/original-child".into(),
+ });
+ original_fixture
+ .block_close_poll
+ .store(true, Ordering::SeqCst);
+ let closing = tokio::spawn({
+ let client = Arc::clone(&client);
+ async move { client.close().await }
+ });
+ tokio::time::timeout(
+ Duration::from_secs(10),
+ original_fixture.close_poll_started.notified(),
+ )
+ .await
+ .expect("close receipt reaches the original module");
+ closing.abort();
+ assert!(closing.await.unwrap_err().is_cancelled());
+ original_fixture.release_close_poll.notify_one();
+ assert!(
+ matches!(&*client.state.lock().await, State::Closing { transition_id, .. } if transition_id == "original-close")
+ );
+ original.release_name(names::INTERFACE).await.unwrap();
+ replacement.request_name(names::INTERFACE).await.unwrap();
+ client.close().await.unwrap();
+ assert_eq!(original_fixture.closes.load(Ordering::SeqCst), 1);
+ assert_eq!(
+ original_fixture.polls.load(Ordering::SeqCst),
+ 3,
+ "retry must poll the retained receipt on the original owner"
+ );
+ assert_eq!(replacement_fixture.closes.load(Ordering::SeqCst), 0);
+ assert_eq!(replacement_fixture.polls.load(Ordering::SeqCst), 0);
+}
+
+#[tokio::test]
+async fn cleanup_receipts_stay_with_the_original_module_after_alias_replacement() {
+ let bus = MemoryBus::new();
+ Broker::new().spawn(bus.clone());
+ let original = Connection::connect(bus.connect().await.unwrap())
+ .await
+ .unwrap();
+ let replacement = Connection::connect(bus.connect().await.unwrap())
+ .await
+ .unwrap();
+ let caller = Connection::connect(bus.connect().await.unwrap())
+ .await
+ .unwrap();
+ let original_fixture = LifecycleFixture::default();
+ let replacement_fixture = LifecycleFixture::default();
+ for (connection, fixture) in [
+ (&original, original_fixture.clone()),
+ (&replacement, replacement_fixture.clone()),
+ ] {
+ connection
+ .serve_at(ObjectPath::new(names::OBJECT_PATH).unwrap(), fixture)
+ .await
+ .unwrap();
+ }
+ original.request_name(names::INTERFACE).await.unwrap();
+ let root = ModuleClient::fixture(
+ caller
+ .proxy(names::INTERFACE, names::OBJECT_PATH, names::INTERFACE)
+ .unwrap(),
+ );
+ let port = TinyMcpPort::new(root);
+ // Resolve the original owner through a real bus call. No secret is sent
+ // to these deliberately unattested lifecycle fixtures.
+ assert_eq!(
+ port.transition_status("original-open").await,
+ Ok(TransitionStatus::Complete)
+ );
+ let client = McpConfiguredClient::with_port("/test/agent".into(), Box::new(port));
+ *client.state.lock().await = State::Open(OpenObject {
+ config: McpClientConfig::default(),
+ object_path: "/test/original-child".into(),
+ });
+ original.release_name(names::INTERFACE).await.unwrap();
+ replacement.request_name(names::INTERFACE).await.unwrap();
+
+ client.close().await.unwrap();
+ assert_eq!(
+ original_fixture.closes.load(Ordering::SeqCst),
+ 1,
+ "cleanup must address the original module instance"
+ );
+ assert_eq!(
+ original_fixture.polls.load(Ordering::SeqCst),
+ 2,
+ "the close receipt must be polled on its original owner"
+ );
+ assert_eq!(replacement_fixture.closes.load(Ordering::SeqCst), 0);
+ assert_eq!(replacement_fixture.polls.load(Ordering::SeqCst), 0);
+}
+
+#[tokio::test(start_paused = true)]
+async fn a_blocked_close_has_an_overall_cleanup_deadline_and_keeps_the_owner_for_retry() {
+ let scratch = tempfile::tempdir().unwrap();
+ let directory = scratch.path().join("agents/blocked-close");
+ let bus = MemoryBus::new();
+ Broker::new().spawn(bus.clone());
+ let service = Connection::connect(bus.connect().await.unwrap())
+ .await
+ .unwrap();
+ let caller = Connection::connect(bus.connect().await.unwrap())
+ .await
+ .unwrap();
+ let fixture = LifecycleFixture::default();
+ service
+ .serve_at(
+ ObjectPath::new(names::OBJECT_PATH).unwrap(),
+ fixture.clone(),
+ )
+ .await
+ .unwrap();
+ service.request_name(names::INTERFACE).await.unwrap();
+ let port = TinyMcpPort::new(
+ ModuleClient::fixture(
+ caller
+ .proxy(names::INTERFACE, names::OBJECT_PATH, names::INTERFACE)
+ .unwrap(),
+ )
+ .with_timeout(Duration::from_secs(120)),
+ );
+ port.transition_status("original-open").await.unwrap();
+ let client = Arc::new(McpConfiguredClient::with_port(
+ directory.to_str().unwrap().into(),
+ Box::new(port),
+ ));
+ // The acknowledged object isolates lifecycle routing from module admission.
+ *client.state.lock().await = State::Open(OpenObject {
+ config: McpClientConfig::default(),
+ object_path: "/test/original-child".into(),
+ });
+ CLIENTS
+ .get_or_init(|| Mutex::new(HashMap::new()))
+ .lock()
+ .unwrap()
+ .insert(directory.clone(), Arc::clone(&client));
+ let cleanup = agent_cleanup::take_agent_cleanup(scratch.path(), "blocked-close").unwrap();
+ fixture.block_close.store(true, Ordering::SeqCst);
+ let attempt = cleanup.clone();
+ let mut task = tokio::spawn(async move { attempt.finish().await });
+ fixture.close_started.notified().await;
+ let outcome = tokio::time::timeout(Duration::from_secs(31), &mut task).await;
+ if outcome.is_err() {
+ task.abort();
+ let _ = task.await;
+ fixture.release_close.notify_one();
+ CLIENTS.get().unwrap().lock().unwrap().remove(&directory);
+ }
+ let result = outcome.expect("cleanup must return within 30 seconds even when Close has a 120-second operation timeout")
+ .expect("cleanup task must complete normally");
+ assert_eq!(result, Err(ModuleCallError::TransportFailed));
+ assert!(matches!(
+ &*client.state.lock().await,
+ State::StartingClose(_)
+ ));
+ assert!(Arc::ptr_eq(
+ CLIENTS
+ .get()
+ .unwrap()
+ .lock()
+ .unwrap()
+ .get(&directory)
+ .unwrap(),
+ &client
+ ));
- assert!(client.retired.load(Ordering::Acquire));
++ assert!(client.retiring.load(Ordering::Acquire));
+ // Retry the captured owner; timing out must not evict its close intent.
+ fixture.release_close.notify_one();
+ cleanup.finish().await.unwrap();
+ assert_eq!(fixture.closes.load(Ordering::SeqCst), 2);
+ assert!(!CLIENTS
+ .get()
+ .unwrap()
+ .lock()
+ .unwrap()
+ .contains_key(&directory));
+}