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
fix(embed): never hold the runtime slot in a deferred agent cleanup
M3gA-Mind8ee2b67e1f60
diff --git a/crates/openhuman-embed/src/agent/mod.rs b/crates/openhuman-embed/src/agent/mod.rsindex d8499dd17a..d07ddddfe4 100644--- a/crates/openhuman-embed/src/agent/mod.rs+++ b/crates/openhuman-embed/src/agent/mod.rs@@ -172,10 +172,11 @@ impl AgentInner {if schedule_mcp_cleanup {// Keep an ephemeral runtime workspace alive until an outstanding// module close is acknowledged. The cleanup callback is retained- // by the path reservation if close needs a later retry.- let runtime_guard = Arc::clone(&self._runtime_guard);+ // by the path reservation if close needs a later retry, so it+ // holds only the workspace, never the runtime's process slot.+ let workspace = self._runtime_guard.workspace_keepalive();let keep_workspace = Arc::new(move || {- let _ = &runtime_guard;+ let _ = &workspace;true});openhuman_core::mcp::host::schedule_agent_close_with_cleanup(diff --git a/crates/openhuman-embed/src/harness/workspace.rs b/crates/openhuman-embed/src/harness/workspace.rsindex 6240b9e4bc..3439e14c10 100644--- a/crates/openhuman-embed/src/harness/workspace.rs+++ b/crates/openhuman-embed/src/harness/workspace.rs@@ -92,7 +92,43 @@ pub(crate) struct ResolvedWorkspace {/// operator's real `~/.openhuman` credentials while looking hermetic.pub(crate) config_path: PathBuf,/// `None` for `Dir` / `Inherit`; those directories outlive the runtime.- pub(crate) _temp: Option<tempfile::TempDir>,+ pub(crate) _temp: Option<std::sync::Arc<EphemeralRoot>>,+}++/// The temp root of an ephemeral workspace, removed when its last holder+/// drops: the runtime, or a deferred agent cleanup that must keep the files+/// until the MCP module acknowledges its close. Shared on its own so that+/// cleanup never has to hold the whole runtime (and its process slot).+pub(crate) struct EphemeralRoot(Option<tempfile::TempDir>);++impl Drop for EphemeralRoot {+ fn drop(&mut self) {+ let Some(temp) = self.0.take() else {+ return;+ };+ // Take ownership of the temp path and remove it with a short retry.+ // The core's memory/session writers keep running a moment after a+ // turn returns and can recreate workspace subdirectories while+ // `TempDir`'s own drop-time removal is racing them, leaving an empty+ // directory behind. A bounded retry lets those writes settle before+ // giving up.+ let root = temp.keep();+ let mut quiet_passes = 0;+ for _ in 0..20 {+ match std::fs::remove_dir_all(&root) {+ Ok(()) => quiet_passes += 1,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {+ quiet_passes += 1;+ }+ Err(_) => quiet_passes = 0,+ }+ if quiet_passes >= 5 {+ break;+ }+ std::thread::sleep(std::time::Duration::from_millis(50));+ }+ let _ = std::fs::remove_dir_all(&root);+ }}impl ResolvedWorkspace {@@ -138,7 +174,7 @@ impl ResolvedWorkspace {workspace_dir,action_dir,config_path: root.join("config.toml"),- _temp: Some(temp),+ _temp: Some(std::sync::Arc::new(EphemeralRoot(Some(temp)))),})}Workspace::Dir(dir) => {diff --git a/crates/openhuman-embed/src/harness/workspace_tests.rs b/crates/openhuman-embed/src/harness/workspace_tests.rsindex 9dd18447c3..e6b56267d0 100644--- a/crates/openhuman-embed/src/harness/workspace_tests.rs+++ b/crates/openhuman-embed/src/harness/workspace_tests.rs@@ -19,6 +19,20 @@ fn ephemeral_creates_both_dirs_and_removes_them_on_drop() {assert!(!root.exists(), "ephemeral workspace outlived its owner");}+/// A deferred agent cleanup holds only the ephemeral root, not the runtime:+/// the files outlive the runtime's own handle until that cleanup lets go, and+/// are removed when the last holder drops.+#[test]+fn an_ephemeral_root_lives_until_its_last_holder_drops() {+ let mut ws = ResolvedWorkspace::resolve(&Workspace::Ephemeral, None).unwrap();+ let root = ws.workspace_dir.parent().unwrap().to_path_buf();+ let cleanup = ws._temp.clone().expect("an ephemeral workspace has a root");+ drop(ws._temp.take());+ assert!(root.exists(), "a pending cleanup still holds the root");+ drop(cleanup);+ assert!(!root.exists(), "the last holder removes the root");+}+#[test]fn the_action_dir_is_never_inside_the_workspace() {// `is_workspace_internal_path` blocks agent writes beneath the workspacediff --git a/crates/openhuman-embed/src/runtime/README.md b/crates/openhuman-embed/src/runtime/README.mdindex c60ea5d8dd..c546aa9dde 100644--- a/crates/openhuman-embed/src/runtime/README.md+++ b/crates/openhuman-embed/src/runtime/README.md@@ -55,9 +55,13 @@ an ephemeral one), and the installed session store. Both `Runtime` and everyagent or in-flight turn exists, even after the host drops its `Runtime`. Whenthe last owner drops, the guard drops the core while the process slot isstill claimed, restores the previous session store if it still owns the-slot, removes an ephemeral workspace with a short retry loop (background-writers can recreate subdirectories just after a turn returns), and only then-releases `RUNTIME_LIVE`.+slot, drops its handle on an ephemeral workspace, and releases `RUNTIME_LIVE`.+The ephemeral root (`EphemeralRoot`) is removed with a short retry loop+(background writers can recreate subdirectories just after a turn returns)+when its last holder drops. A dropped agent's deferred MCP cleanup holds that+root, never the `CoreGuard`: an embedded host runs no shutdown hook, so a close+the module never acknowledges would otherwise hold the process slot forever and+every later `Runtime::builder().build()` would fail with `AlreadyRunning`.## Layoutdiff --git a/crates/openhuman-embed/src/runtime/lifecycle.rs b/crates/openhuman-embed/src/runtime/lifecycle.rsindex 16af5b4085..d0a6bca49b 100644--- a/crates/openhuman-embed/src/runtime/lifecycle.rs+++ b/crates/openhuman-embed/src/runtime/lifecycle.rs@@ -44,19 +44,22 @@ impl Drop for RemovalSlot<'_> {if self.purge && !self.mcp_cleanup_confirmed {self.inner.teardown_without_mcp_cleanup("agent_removed");let home = self.inner.layout.home.clone();- let runtime_guard = Arc::clone(&self.inner._runtime_guard);+ // Only the workspace outlives this removal: the retained callback+ // must not hold the runtime's process slot (see+ // `CoreGuard::workspace_keepalive`).+ let workspace = self.inner._runtime_guard.workspace_keepalive();let cleanup = Arc::new(move || match std::fs::remove_dir_all(&home) {Ok(()) => {- let _ = &runtime_guard;+ let _ = &workspace;true}Err(error) if error.kind() == std::io::ErrorKind::NotFound => {- let _ = &runtime_guard;+ let _ = &workspace;true}Err(error) => {log::warn!("[embed][runtime] deferred agent purge failed: {error}");- let _ = &runtime_guard;+ let _ = &workspace;false}});diff --git a/crates/openhuman-embed/src/runtime/mod.rs b/crates/openhuman-embed/src/runtime/mod.rsindex 253444024a..92f5ceea8d 100644--- a/crates/openhuman-embed/src/runtime/mod.rs+++ b/crates/openhuman-embed/src/runtime/mod.rs@@ -189,8 +189,9 @@ pub enum RuntimeError {pub(crate) struct CoreGuard {pub(crate) events: Arc<crate::events::EventHub>,core: Option<Core>,- /// Held for its `Drop`: an ephemeral workspace lives exactly as long as- /// the last owner of this guard.+ /// Held for its `Drop`: an ephemeral workspace lives as long as the last+ /// owner of this guard, or of a deferred cleanup's+ /// [`workspace_keepalive`](Self::workspace_keepalive).workspace: ResolvedWorkspace,/// The provider this runtime installed, if any. It is removed only while/// it still owns the process slot.@@ -207,6 +208,19 @@ pub(crate) struct CoreGuard {seams: Mutex<Option<seams::InstalledSeams>>,}+impl CoreGuard {+ /// What a deferred agent cleanup holds to keep an ephemeral workspace's+ /// files until the MCP module acknowledges its close. Never the guard+ /// itself: a close that is never acknowledged (no shutdown hook runs in an+ /// embedded host) would then hold the process slot forever and every later+ /// `Runtime::builder().build()` would fail with `AlreadyRunning`.+ pub(crate) fn workspace_keepalive(+ &self,+ ) -> Option<Arc<crate::harness::workspace::EphemeralRoot>> {+ self.workspace._temp.clone()+ }+}+impl Drop for CoreGuard {fn drop(&mut self) {// Stop handing this runtime's agents and handlers to the core's@@ -232,30 +246,10 @@ impl Drop for CoreGuard {.unwrap_or_else(std::sync::PoisonError::into_inner).take(),);- // For an ephemeral workspace, take ownership of the temp path and- // remove it with a short retry. The core's memory/session writers keep- // running a moment after a turn returns and can recreate workspace- // subdirectories while `TempDir`'s own drop-time removal is racing- // them, leaving an empty directory behind. A bounded retry lets those- // writes settle before giving up.- if let Some(temp) = self.workspace._temp.take() {- let root = temp.keep();- let mut quiet_passes = 0;- for _ in 0..20 {- match std::fs::remove_dir_all(&root) {- Ok(()) => quiet_passes += 1,- Err(error) if error.kind() == std::io::ErrorKind::NotFound => {- quiet_passes += 1;- }- Err(_) => quiet_passes = 0,- }- if quiet_passes >= 5 {- break;- }- std::thread::sleep(std::time::Duration::from_millis(50));- }- let _ = std::fs::remove_dir_all(&root);- }+ // An ephemeral workspace is removed here unless a deferred agent+ // cleanup still holds it (see `EphemeralRoot`); either way the process+ // slot below is released now.+ drop(self.workspace._temp.take());RUNTIME_LIVE.store(false, std::sync::atomic::Ordering::Release);log::debug!("[embed][runtime] released");}diff --git a/crates/openhuman-embed/tests/session_store.rs b/crates/openhuman-embed/tests/session_store.rsindex 404fa7a157..5efeeb5c4d 100644--- a/crates/openhuman-embed/tests/session_store.rs+++ b/crates/openhuman-embed/tests/session_store.rs@@ -111,6 +111,14 @@ fn a_stateless_runtime_keeps_every_conversation_in_its_session_store() {.send().await.expect("second turn");+ // Reusing an id waits for the old instance's cleanup: dropping a+ // handle only schedules its MCP close, and the id stays reserved+ // until that close is acknowledged (`CleanupPending`). Removing+ // awaits the close, so the reopen below is deterministic.+ runtime+ .remove_agent("asha")+ .await+ .expect("asha is removed and its cleanup acknowledged");drop(asha);// ── reopened, asha resumes from the store ─────────────────────