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
feat(embed): cap live agents and remove an agent from a running runtime (#7032)
oxoxDevc7441d99febb
diff --git a/crates/openhuman-embed/src/agent/build.rs b/crates/openhuman-embed/src/agent/build.rsindex 418e20351a..5edc8de3f8 100644--- a/crates/openhuman-embed/src/agent/build.rs+++ b/crates/openhuman-embed/src/agent/build.rs@@ -217,6 +217,7 @@ pub(crate) fn instantiate(runtime: &Runtime, spec: AgentSpec) -> Result<AgentInnaccess,layout,host_tools: parts.host_tools,+ lifecycle: super::lifecycle::Lifecycle::new(),})}diff --git a/crates/openhuman-embed/src/agent/lifecycle.rs b/crates/openhuman-embed/src/agent/lifecycle.rsnew file mode 100644index 0000000000..f59ecac3f2--- /dev/null+++ b/crates/openhuman-embed/src/agent/lifecycle.rs@@ -0,0 +1,98 @@+//! An agent's removal state: whether it still accepts turns, how many are in+//! flight, and the teardown of the per-agent state the core keeps for it.++use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};+use std::time::Duration;++use tokio::sync::{watch, Notify};++use crate::CoreError;++/// Turn admission and in-flight accounting for one agent.+pub(crate) struct Lifecycle {+ removed: watch::Sender<bool>,+ in_flight: AtomicUsize,+ idle: Notify,+ torn_down: AtomicBool,+}++impl Lifecycle {+ pub(crate) fn new() -> Self {+ Self {+ removed: watch::Sender::new(false),+ in_flight: AtomicUsize::new(0),+ idle: Notify::new(),+ torn_down: AtomicBool::new(false),+ }+ }++ /// Stops admitting turns and ends the ones in flight.+ pub(crate) fn mark_removed(&self) {+ self.removed.send_replace(true);+ }++ /// Runs `turn` unless the agent was removed, ending it early with+ /// [`CoreError::AgentRemoved`] if the agent is removed meanwhile.+ pub(crate) async fn admit<T>(+ &self,+ agent_id: &str,+ method: &'static str,+ turn: impl std::future::Future<Output = Result<T, CoreError>>,+ ) -> Result<T, CoreError> {+ let removed = || CoreError::AgentRemoved {+ method,+ agent_id: agent_id.to_string(),+ };+ let mut watcher = self.removed.subscribe();+ if *watcher.borrow_and_update() {+ log::debug!("[embed][agent] turn refused: agent removed id={agent_id}");+ return Err(removed());+ }+ let _in_flight = InFlight::enter(self);+ tokio::select! {+ biased;+ _ = watcher.wait_for(|removed| *removed) => {+ log::debug!("[embed][agent] in-flight turn ended: agent removed id={agent_id}");+ Err(removed())+ }+ outcome = turn => outcome,+ }+ }++ /// Waits until no turn is in flight, for at most `limit`. Returns whether+ /// the agent went idle in time.+ pub(crate) async fn wait_idle(&self, limit: Duration) -> bool {+ let wait = async {+ loop {+ let notified = self.idle.notified();+ if self.in_flight.load(Ordering::SeqCst) == 0 {+ return;+ }+ notified.await;+ }+ };+ tokio::time::timeout(limit, wait).await.is_ok()+ }++ /// Claims the one-time teardown. `false` when it already ran.+ pub(crate) fn begin_teardown(&self) -> bool {+ !self.torn_down.swap(true, Ordering::SeqCst)+ }+}++struct InFlight<'a>(&'a Lifecycle);++impl<'a> InFlight<'a> {+ fn enter(lifecycle: &'a Lifecycle) -> Self {+ lifecycle.in_flight.fetch_add(1, Ordering::SeqCst);+ Self(lifecycle)+ }+}++impl Drop for InFlight<'_> {+ fn drop(&mut self) {+ if self.0.in_flight.fetch_sub(1, Ordering::SeqCst) == 1 {+ self.0.idle.notify_waiters();+ }+ }+}diff --git a/crates/openhuman-embed/src/agent/mod.rs b/crates/openhuman-embed/src/agent/mod.rsindex 8d2969d75e..0ca9f7ead3 100644--- a/crates/openhuman-embed/src/agent/mod.rs+++ b/crates/openhuman-embed/src/agent/mod.rs@@ -16,6 +16,7 @@mod approvals;mod attachments;+pub(crate) mod lifecycle;pub use approvals::{ApprovalDecision, Approvals, ApprovalsError, PendingApproval};pub use attachments::ToolAttachmentError;pub(crate) mod build;@@ -81,6 +82,18 @@ pub enum AgentError {/// …), which the delegation catalogue would resolve instead of this agent.#[error("agent id {0:?} is reserved for a built-in agent definition")]ReservedId(String),++ /// The runtime already hosts its configured maximum of live agents+ /// ([`RuntimeBuilder::max_agents`](crate::RuntimeBuilder::max_agents)).+ #[error("the runtime already hosts its limit of {limit} agents")]+ AgentLimit {+ /// The configured maximum.+ limit: usize,+ },++ /// No live agent with this id is registered on the runtime.+ #[error("no agent {0:?} is registered on this runtime")]+ UnknownId(String),}/// The assembled state behind an [`Agent`], shared by every clone of it and@@ -104,11 +117,46 @@ pub(crate) struct AgentInner {/// The agent's own in-process tools, rebuilt per turn. See/// [`AgentSpec::tools`](super::AgentSpec::tools) for why it is a factory.pub(crate) host_tools: Option<openhuman_core::agent::HostTools>,+ pub(crate) lifecycle: lifecycle::Lifecycle,+}++impl AgentInner {+ /// Releases what the core keeps for this agent: parked approvals are+ /// denied with `resolution`, its state slots and MCP host are dropped,+ /// and its context leaves the registry. Runs once.+ pub(crate) fn teardown(&self, resolution: &str) {+ if !self.lifecycle.begin_teardown() {+ return;+ }+ if let Some(gate) = openhuman_core::security::approval::ApprovalGate::try_global() {+ match gate.deny_all_for_agent(&self.id, resolution) {+ Ok(denied) => log::debug!(+ "[embed][agent] teardown id={} denied_approvals={denied}",+ self.id+ ),+ Err(error) => log::warn!(+ "[embed][agent] teardown id={} could not deny approvals: {error}",+ self.id+ ),+ }+ }+ 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+ );+ }+ openhuman_core::core::runtime::AgentContextRegistry::deregister(&self.id, &self.ctx);+ log::debug!("[embed][agent] teardown complete id={}", self.id);+ }}impl Drop for AgentInner {fn drop(&mut self) {- openhuman_core::core::runtime::AgentContextRegistry::deregister(&self.id, &self.ctx);+ self.teardown("agent_dropped");}}diff --git a/crates/openhuman-embed/src/error.rs b/crates/openhuman-embed/src/error.rsindex 7aa15f9fc7..ad42eb1e55 100644--- a/crates/openhuman-embed/src/error.rs+++ b/crates/openhuman-embed/src/error.rs@@ -106,6 +106,16 @@ pub enum CoreError {/// RPC method the invalid route was attached to.method: &'static str,},++ /// The agent was removed from its runtime: a turn sent afterwards is+ /// refused, and one in flight when it was removed ends with this.+ #[error("{method}: agent {agent_id:?} was removed")]+ AgentRemoved {+ /// RPC method the turn was dispatching.+ method: &'static str,+ /// The removed agent.+ agent_id: String,+ },}impl CoreError {@@ -156,7 +166,8 @@ impl CoreError {| CoreError::Encode { method, .. }| CoreError::Decode { method, .. }| CoreError::InsecureRoute { method, .. }- | CoreError::InvalidRoute { method } => method,+ | CoreError::InvalidRoute { method }+ | CoreError::AgentRemoved { method, .. } => method,}}diff --git a/crates/openhuman-embed/src/harness/error.rs b/crates/openhuman-embed/src/harness/error.rsindex fdbbdf80c4..09df94e90d 100644--- a/crates/openhuman-embed/src/harness/error.rs+++ b/crates/openhuman-embed/src/harness/error.rs@@ -88,9 +88,12 @@ impl From<crate::AgentError> for HarnessError {match err {A::Call(e) => Self::Call(e),A::Workspace { what, source } => Self::Workspace { what, source },- A::DuplicateId(_) | A::InvalidId { .. } | A::WidensRuntime(_) | A::ReservedId(_) => {- Self::Invalid(err_text(&err))- }+ A::DuplicateId(_)+ | A::InvalidId { .. }+ | A::WidensRuntime(_)+ | A::ReservedId(_)+ | A::AgentLimit { .. }+ | A::UnknownId(_) => Self::Invalid(err_text(&err)),A::Invalid(msg) => Self::Invalid(msg),}}diff --git a/crates/openhuman-embed/src/lib.rs b/crates/openhuman-embed/src/lib.rsindex 73d2b94bfc..6d40980fd9 100644--- a/crates/openhuman-embed/src/lib.rs+++ b/crates/openhuman-embed/src/lib.rs@@ -110,7 +110,8 @@ pub use harness::{};#[cfg(feature = "mcp")]pub use harness::{HttpHeader, McpAuthConfig, McpServer};-pub use runtime::{ApiKey, Runtime, RuntimeBuilder, RuntimeError};+pub use runtime::builder::DEFAULT_MAX_AGENTS;+pub use runtime::{ApiKey, RemoveAgent, Runtime, RuntimeBuilder, RuntimeError};/// The session store port: what a host implements to keep every agent's/// conversations in its own database ([`RuntimeBuilder::session_store`]),diff --git a/crates/openhuman-embed/src/runtime/builder.rs b/crates/openhuman-embed/src/runtime/builder.rsindex 77b506ba7f..64949b3b9c 100644--- a/crates/openhuman-embed/src/runtime/builder.rs+++ b/crates/openhuman-embed/src/runtime/builder.rs@@ -52,8 +52,13 @@ pub struct RuntimeBuilder {backend_transport: Option<Arc<dyn BackendTransport>>,memory_engine: Option<Arc<dyn tinymemory_api::MemoryEngine>>,session_store: Option<Arc<dyn SessionStoreProvider>>,+ max_agents: usize,}+/// Live agents a runtime hosts unless [`RuntimeBuilder::max_agents`] says+/// otherwise.+pub const DEFAULT_MAX_AGENTS: usize = 1024;+impl Default for RuntimeBuilder {fn default() -> Self {Self::new()@@ -80,6 +85,7 @@ impl RuntimeBuilder {backend_transport: None,memory_engine: None,session_store: None,+ max_agents: DEFAULT_MAX_AGENTS,}}@@ -125,6 +131,15 @@ impl RuntimeBuilder {self}+ /// The most agents this runtime hosts at once; [`Runtime::agent`]+ /// returns [`AgentError::AgentLimit`](crate::AgentError::AgentLimit)+ /// beyond it. Removed and dropped agents do not count. Defaults to+ /// [`DEFAULT_MAX_AGENTS`].+ pub fn max_agents(mut self, limit: usize) -> Self {+ self.max_agents = limit;+ self+ }+/// Where the runtime keeps its credential store, session database and/// every agent's memory, transcripts and skills.pub fn workspace(mut self, workspace: Workspace) -> Self {@@ -381,6 +396,7 @@ impl RuntimeBuilder {tool_groups,self.provider,self.access,+ self.max_agents,))}}diff --git a/crates/openhuman-embed/src/runtime/lifecycle.rs b/crates/openhuman-embed/src/runtime/lifecycle.rsnew file mode 100644index 0000000000..ed49c4b8a2--- /dev/null+++ b/crates/openhuman-embed/src/runtime/lifecycle.rs@@ -0,0 +1,90 @@+//! Removing an agent from a running [`Runtime`].++use std::future::{Future, IntoFuture};+use std::pin::Pin;+use std::time::Duration;++use super::Runtime;+use crate::agent::AgentError;++/// How long [`Runtime::remove_agent`] waits for in-flight turns to unwind.+const REMOVE_IDLE_WAIT: Duration = Duration::from_secs(10);++/// A pending [`Runtime::remove_agent`]. Await it, optionally after+/// [`purge`](Self::purge).+#[must_use = "an agent is removed only when this is awaited"]+pub struct RemoveAgent<'a> {+ runtime: &'a Runtime,+ id: String,+ purge: bool,+}++impl RemoveAgent<'_> {+ /// Also delete the agent's home, `<workspace>/agents/<id>/`, with its+ /// transcripts, skills, job store and MCP store. Kept by default.+ pub fn purge(mut self) -> Self {+ self.purge = true;+ self+ }+}++impl<'a> IntoFuture for RemoveAgent<'a> {+ type Output = Result<(), AgentError>;+ type IntoFuture = Pin<Box<dyn Future<Output = Self::Output> + Send + 'a>>;++ fn into_future(self) -> Self::IntoFuture {+ Box::pin(async move { self.runtime.remove(&self.id, self.purge).await })+ }+}++impl Runtime {+ /// Remove agent `id` from this runtime.+ ///+ /// In order: new turns on any handle to it are refused with+ /// [`CoreError::AgentRemoved`](crate::CoreError::AgentRemoved); turns in+ /// flight end with the same error, waited on for up to ten seconds; its+ /// parked approvals are denied with resolution `agent_removed`; its state+ /// slots and MCP host are dropped and its context deregistered, so its+ /// cron jobs stay dormant. The id is free for reuse once this returns.+ ///+ /// Cancellation is cooperative: a tool already executing when the agent+ /// is removed, or a sub-agent it detached, may finish after this returns.+ pub fn remove_agent(&self, id: &str) -> RemoveAgent<'_> {+ RemoveAgent {+ runtime: self,+ id: id.to_string(),+ purge: false,+ }+ }++ async fn remove(&self, id: &str, purge: bool) -> Result<(), AgentError> {+ let inner = {+ let mut agents = self.agents.lock().unwrap_or_else(|e| e.into_inner());+ agents.retain(|_, weak| weak.strong_count() > 0);+ agents+ .remove(id)+ .and_then(|weak| weak.upgrade())+ .ok_or_else(|| AgentError::UnknownId(id.to_string()))?+ };+ log::debug!("[embed][runtime] removing agent id={id} purge={purge}");+ inner.lifecycle.mark_removed();+ if !inner.lifecycle.wait_idle(REMOVE_IDLE_WAIT).await {+ log::warn!(+ "[embed][runtime] agent id={id} still had turns unwinding after {}s",+ REMOVE_IDLE_WAIT.as_secs()+ );+ }+ inner.teardown("agent_removed");+ if purge {+ let home = inner.layout.home.clone();+ if home.exists() {+ std::fs::remove_dir_all(&home).map_err(|source| AgentError::Workspace {+ what: "delete the removed agent's home",+ source,+ })?;+ }+ }+ log::debug!("[embed][runtime] agent removed id={id}");+ Ok(())+ }+}diff --git a/crates/openhuman-embed/src/runtime/mod.rs b/crates/openhuman-embed/src/runtime/mod.rsindex 44e9d192cf..288e25ffdd 100644--- a/crates/openhuman-embed/src/runtime/mod.rs+++ b/crates/openhuman-embed/src/runtime/mod.rs@@ -69,9 +69,11 @@mod api_key;pub(crate) mod builder;+mod lifecycle;pub use api_key::ApiKey;pub use builder::RuntimeBuilder;+pub use lifecycle::RemoveAgent;use std::collections::HashMap;use std::path::Path;@@ -219,6 +221,7 @@ pub struct Runtime {provider: Provider,access: Access,agents: Mutex<HashMap<String, Weak<AgentInner>>>,+ max_agents: usize,}impl Runtime {@@ -252,6 +255,15 @@ impl Runtime {if agents.contains_key(&id) {return Err(AgentError::DuplicateId(id));}+ if agents.len() >= self.max_agents {+ log::warn!(+ "[embed][runtime] agent refused id={id}: {} live agents is the limit",+ self.max_agents+ );+ return Err(AgentError::AgentLimit {+ limit: self.max_agents,+ });+ }let inner = Arc::new(crate::agent::build::instantiate(self, spec)?);agents.insert(id.clone(), Arc::downgrade(&inner));drop(agents);@@ -381,6 +393,7 @@ impl Runtime {tool_groups: ToolGroups,provider: Provider,access: Access,+ max_agents: usize,) -> Self {Self {id: uuid::Uuid::new_v4().to_string(),@@ -397,6 +410,7 @@ impl Runtime {provider,access,agents: Mutex::new(HashMap::new()),+ max_agents,}}}diff --git a/crates/openhuman-embed/src/turn.rs b/crates/openhuman-embed/src/turn.rsindex 1ea9f36974..36eb588639 100644--- a/crates/openhuman-embed/src/turn.rs+++ b/crates/openhuman-embed/src/turn.rs@@ -498,6 +498,7 @@ impl Turn {crate::error::CoreError::Decode { .. } => "decode",crate::error::CoreError::InsecureRoute { .. } => "insecure_route",crate::error::CoreError::InvalidRoute { .. } => "invalid_route",+ crate::error::CoreError::AgentRemoved { .. } => "agent_removed",};log::debug!("[embed][agent] turn_failed session={session_id} kind={tag}");});@@ -616,7 +617,10 @@ async fn dispatch(.map(|outcome| outcome.value).map_err(|raw| CoreError::from_rpc_string(AGENT_CHAT, raw))});- runtime.run_in(ctx, turn).await+ agent+ .lifecycle+ .admit(&agent.id, AGENT_CHAT, runtime.run_in(ctx, turn))+ .await}}}