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(approval): guard shared gate decisions during instance removal
Steven Enamakel3c9d383f5b61
diff --git a/crates/openhuman-core/src/security/approval/gate.rs b/crates/openhuman-core/src/security/approval/gate.rsindex 8563e72346..d413d50555 100644--- a/crates/openhuman-core/src/security/approval/gate.rs+++ b/crates/openhuman-core/src/security/approval/gate.rs@@ -268,6 +268,8 @@ pub(crate) struct RequestRoute {pub(crate) tool_call_id: Option<String>,pub(crate) forced: bool,pub(crate) agent_id: Option<String>,+ /// Instance barrier captured at registration, independent of decision context.+ pub(crate) approval_scope: Option<Arc<super::ApprovalScope>>,/// The [`thread_route_key`] the request was parked under, so a decision/// made outside the parking task's scope clears the right route.pub(crate) thread_key: Option<String>,diff --git a/crates/openhuman-core/src/security/approval/gate_intercept.rs b/crates/openhuman-core/src/security/approval/gate_intercept.rsindex d15d9455d4..d4d95a3ec9 100644--- a/crates/openhuman-core/src/security/approval/gate_intercept.rs+++ b/crates/openhuman-core/src/security/approval/gate_intercept.rs@@ -501,6 +501,8 @@ impl ApprovalGate {// to time out and return `Deny` incorrectly. (CodeRabbit// review on PR #2149.)let (tx, rx) = oneshot::channel::<ApprovalDecision>();+ let scope = crate::core::runtime::CoreContext::current_host_overrides()+ .and_then(|overrides| overrides.approval_scope());let register = || -> anyhow::Result<()> {{let mut waiters = self.waiters.lock();@@ -526,6 +528,7 @@ impl ApprovalGate {tool_call_id: tool_call_id.map(str::to_string),forced,agent_id: agent_id.clone(),+ approval_scope: scope.clone(),thread_key: thread_key.clone(),detached,},@@ -553,10 +556,8 @@ impl ApprovalGate {});Ok(())};- let scope = crate::core::runtime::CoreContext::current_host_overrides()- .and_then(|overrides| overrides.approval_scope());- let registered = match scope {- Some(scope) => scope.register(register),+ let registered = match scope.as_ref() {+ Some(scope) => scope.with_open(register),None => Ok(register()),};match registered {diff --git a/crates/openhuman-core/src/security/approval/gate_state.rs b/crates/openhuman-core/src/security/approval/gate_state.rsindex 4538cc4b3c..2987561b1d 100644--- a/crates/openhuman-core/src/security/approval/gate_state.rs+++ b/crates/openhuman-core/src/security/approval/gate_state.rs@@ -39,6 +39,23 @@ impl ApprovalGate {&self,request_id: &str,decision: ApprovalDecision,+ ) -> anyhow::Result<Option<PendingApproval>> {+ // Release the routing lock before acquiring the instance barrier:+ // registration holds that barrier while inserting its route.+ let scope = self.request_scope(request_id);+ match scope {+ Some(scope) => scope+ .with_open(|| self.decide_open(request_id, decision))+ .unwrap_or(Ok(None)),+ None => self.decide_open(request_id, decision),+ }+ }++ /// Commit a decision and release its waiter while the instance is still open.+ fn decide_open(+ &self,+ request_id: &str,+ decision: ApprovalDecision,) -> anyhow::Result<Option<PendingApproval>> {if !matches!(decision,@@ -159,11 +176,12 @@ impl ApprovalGate {}/// Classify a [`Self::decide`] miss — i.e. when `decide` returned- /// `Ok(None)` because its conditional `UPDATE ... WHERE decided_at IS NULL`- /// matched 0 rows. Two very different states collapse into that `None`:+ /// `Ok(None)` because the instance was closed or its conditional+ /// `UPDATE ... WHERE decided_at IS NULL` matched 0 rows.////// - [`DecideMiss::AlreadyResolved`] — the row exists but was **already- /// decided, lazily expired (denied), or superseded**. This is the benign+ /// decided, lazily expired (denied), superseded, or closed for removal**.+ /// This is the benign/// double-tap / two-operator / expiry-while-live race the inline-approvals/// design spec classifies as benign (TAURI-RUST-5EH)./// - [`DecideMiss::NeverRegistered`] — no row was ever persisted for this@@ -174,10 +192,17 @@ impl ApprovalGate {/// We disambiguate by consulting [`store::get_decision`], which returns a/// decision only when `decided_at IS NOT NULL` — exactly the already-resolved/// case (expiry writes a `Deny` decision, so expired rows report here too).- /// A `decide` miss can't be an undecided-but-present row: that row would have- /// matched the `UPDATE`. If the lookup itself errors we conservatively keep+ /// A closed instance can still have an undecided row while removal takes+ /// its denial snapshot; this is also a benign refusal. If the lookup itself+ /// errors we conservatively keep/// the event visible (`NeverRegistered`) rather than silently demoting.pub fn classify_decide_miss(&self, request_id: &str) -> DecideMiss {+ if self+ .request_scope(request_id)+ .is_some_and(|scope| scope.is_closed())+ {+ return DecideMiss::AlreadyResolved;+ }match store::get_decision(&self.config, request_id) {Ok(Some(_)) => DecideMiss::AlreadyResolved,Ok(None) => DecideMiss::NeverRegistered,@@ -279,6 +304,14 @@ impl ApprovalGate {&self.session_id}+ /// Clone the instance barrier without retaining the routing-map lock.+ fn request_scope(&self, request_id: &str) -> Option<Arc<super::ApprovalScope>> {+ self.request_routes+ .lock()+ .get(request_id)+ .and_then(|route| route.approval_scope.clone())+ }+fn take_waiter(&self, request_id: &str) -> Option<oneshot::Sender<ApprovalDecision>> {let mut waiters = self.waiters.lock();waiters.remove(request_id)diff --git a/crates/openhuman-core/src/security/approval/registration_scope.rs b/crates/openhuman-core/src/security/approval/registration_scope.rsindex bf0c0e47fb..3017d2f70d 100644--- a/crates/openhuman-core/src/security/approval/registration_scope.rs+++ b/crates/openhuman-core/src/security/approval/registration_scope.rs@@ -1,15 +1,15 @@-//! Serializes an agent instance's approval registration with its removal.+//! Serializes an agent instance's approval registration and decisions with removal.use std::sync::Mutex;/// An instance-owned barrier; reusing an agent ID requires a fresh scope.-#[derive(Default)]+#[derive(Debug, Default)]pub struct ApprovalScope {closed: Mutex<Option<String>>,}impl ApprovalScope {- /// Stop registration and wait for any accepted registration to finish.+ /// Stop registration and decisions; wait for accepted work to finish./// The first teardown reason remains authoritative.pub fn close(&self, reason: &str) {let mut closed = self@@ -21,7 +21,16 @@ impl ApprovalScope {}}- pub(crate) fn register<T>(&self, register: impl FnOnce() -> T) -> Result<T, String> {+ /// Whether removal has closed this instance's registration and decision barrier.+ pub fn is_closed(&self) -> bool {+ self.closed+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .is_some()+ }++ /// Run synchronous registration or a decision while holding the removal barrier.+ pub(crate) fn with_open<T>(&self, register: impl FnOnce() -> T) -> Result<T, String> {let closed = self.closed.lock()@@ -29,7 +38,7 @@ impl ApprovalScope {if let Some(reason) = closed.as_ref() {return Err(reason.clone());}- // Keep the barrier through persistence and ApprovalRequested publication.+ // Keep the barrier through persistence and approval event/waiter publication.// No asynchronous work or user callbacks run in this critical section.Ok(register())}diff --git a/crates/openhuman-core/src/security/approval/registration_scope_tests.rs b/crates/openhuman-core/src/security/approval/registration_scope_tests.rsindex 06778f5471..7436514b9a 100644--- a/crates/openhuman-core/src/security/approval/registration_scope_tests.rs+++ b/crates/openhuman-core/src/security/approval/registration_scope_tests.rs@@ -4,9 +4,11 @@ use std::sync::{mpsc, Arc};#[test]fn removal_refuses_late_registration_without_creating_a_pending_row() {let scope = ApprovalScope::default();+ assert!(!scope.is_closed());scope.close("agent_removed");+ assert!(scope.is_closed());let mut created = false;- let result = scope.register(|| created = true);+ let result = scope.with_open(|| created = true);assert_eq!(result, Err("agent_removed".to_owned()));assert!(!created);}@@ -18,7 +20,7 @@ fn accepted_registration_holds_the_removal_barrier_until_it_finishes() {let (release_tx, release_rx) = mpsc::channel();let registering = scope.clone();let registration = std::thread::spawn(move || {- registering.register(|| {+ registering.with_open(|| {entered_tx.send(()).unwrap();release_rx.recv().unwrap();})@@ -37,7 +39,7 @@ fn accepted_registration_holds_the_removal_barrier_until_it_finishes() {"registration released the removal barrier before finishing");scope.close("agent_removed");- assert_eq!(scope.register(|| ()), Err("agent_removed".to_owned()));+ assert_eq!(scope.with_open(|| ()), Err("agent_removed".to_owned()));}#[test]@@ -45,6 +47,6 @@ fn a_reused_agent_id_has_a_fresh_scope_and_preserves_the_old_removal_reason() {let old = ApprovalScope::default();old.close("agent_removed");old.close("agent_dropped");- assert_eq!(old.register(|| ()), Err("agent_removed".to_owned()));- assert_eq!(ApprovalScope::default().register(|| 42), Ok(42));+ assert_eq!(old.with_open(|| ()), Err("agent_removed".to_owned()));+ assert_eq!(ApprovalScope::default().with_open(|| 42), Ok(42));}diff --git a/crates/openhuman-embed/src/agent/build.rs b/crates/openhuman-embed/src/agent/build.rsindex e6b5a87a6e..cfc609e42f 100644--- a/crates/openhuman-embed/src/agent/build.rs+++ b/crates/openhuman-embed/src/agent/build.rs@@ -265,9 +265,8 @@ pub(crate) fn instantiate(runtime: &Runtime, spec: AgentSpec) -> Result<AgentInn});let mut overrides = openhuman_core::agent::host_overrides::HostOverrides::default();overrides.parent = runtime.core_runtime().context().host_overrides();- overrides.approval_scope = Some(std::sync::Arc::new(- openhuman_core::security::approval::ApprovalScope::default(),- ));+ let lifecycle = super::lifecycle::Lifecycle::new();+ overrides.approval_scope = Some(lifecycle.approval_scope());overrides.model = provider.custom_model();overrides.role_models = provider.role_models().clone();overrides.session_store = parts.session_store;@@ -278,7 +277,6 @@ pub(crate) fn instantiate(runtime: &Runtime, spec: AgentSpec) -> Result<AgentInnfor hook in parts.tool_hooks {overrides.tool_hook(hook.name(), Some(hook.clone()));}- let lifecycle = super::lifecycle::Lifecycle::new();let approval_subscription = parts.approval_handler.map(|handler| {super::approval_handler::ApprovalSubscription::new(&id,diff --git a/crates/openhuman-embed/src/agent/lifecycle.rs b/crates/openhuman-embed/src/agent/lifecycle.rsindex 85f02e4cee..d112e96360 100644--- a/crates/openhuman-embed/src/agent/lifecycle.rs+++ b/crates/openhuman-embed/src/agent/lifecycle.rs@@ -23,6 +23,7 @@ pub(crate) struct Lifecycle {pub(crate) struct ApprovalState {claimed: AtomicBool,decisions: Mutex<()>,+ scope: Arc<openhuman_core::security::approval::ApprovalScope>,}impl ApprovalState {@@ -38,11 +39,14 @@ impl ApprovalState {}}- fn claim_removal(&self) -> bool {+ fn claim_removal(&self, reason: &str) -> bool {let _decision = self.decisions.lock().unwrap_or_else(std::sync::PoisonError::into_inner);+ // The shared gate closes before this claim becomes observable, so+ // RPC/chat decisions cannot approve during the later denial snapshot.+ self.scope.close(reason);!self.claimed.swap(true, Ordering::SeqCst)}}@@ -60,13 +64,13 @@ impl Lifecycle {/// Stops admitting turns and ends the ones in flight; returns whether this/// caller claimed removal before another caller.- pub(crate) fn mark_removed(&self) -> bool {- self.mark_removed_with(|| {})+ pub(crate) fn mark_removed(&self, reason: &str) -> bool {+ self.mark_removed_with(reason, || {})}/// Claim removal and settle owned approvals before waking in-flight turns.- pub(crate) fn mark_removed_with(&self, before_notify: impl FnOnce()) -> bool {- if !self.approvals.claim_removal() {+ pub(crate) fn mark_removed_with(&self, reason: &str, before_notify: impl FnOnce()) -> bool {+ if !self.approvals.claim_removal(reason) {return false;}before_notify();@@ -80,6 +84,11 @@ impl Lifecycle {self.approvals.clone()}+ /// The same instance barrier captured by every request at the shared gate.+ pub(crate) fn approval_scope(&self) -> Arc<openhuman_core::security::approval::ApprovalScope> {+ self.approvals.scope.clone()+ }+/// Bind handles to this agent instance, even after its public id is reused.pub(crate) fn removed(&self) -> watch::Receiver<bool> {self.removed.subscribe()diff --git a/crates/openhuman-embed/src/agent/lifecycle_tests.rs b/crates/openhuman-embed/src/agent/lifecycle_tests.rsindex 2890887c3a..85ce46721a 100644--- a/crates/openhuman-embed/src/agent/lifecycle_tests.rs+++ b/crates/openhuman-embed/src/agent/lifecycle_tests.rs@@ -16,7 +16,7 @@ async fn a_live_agent_runs_its_turns() {#[tokio::test]async fn a_removed_agent_refuses_new_turns() {let lifecycle = Lifecycle::new();- lifecycle.mark_removed();+ lifecycle.mark_removed("agent_removed");let ran = Arc::new(AtomicBool::new(false));let flag = Arc::clone(&ran);let outcome = lifecycle@@ -43,7 +43,7 @@ async fn removal_ends_a_turn_in_flight_and_the_agent_goes_idle() {}assert!(!lifecycle.wait_idle(Duration::from_millis(10)).await);- lifecycle.mark_removed();+ lifecycle.mark_removed("agent_removed");assert!(removed(turn.await.expect("turn task")));assert!(lifecycle.wait_idle(Duration::from_secs(1)).await);@@ -63,7 +63,7 @@ async fn a_claimed_removal_refuses_turns_before_approvals_are_settled() {let (entered, callback_entered) = std::sync::mpsc::channel();let (release, callback_release) = std::sync::mpsc::channel();let removal = std::thread::spawn(move || {- removing.mark_removed_with(|| {+ removing.mark_removed_with("agent_removed", || {entered.send(()).unwrap();callback_release.recv().unwrap();})@@ -88,20 +88,26 @@ async fn a_claimed_removal_refuses_turns_before_approvals_are_settled() {#[test]fn a_claimed_removal_refuses_approval_decisions_before_denial_finishes() {let lifecycle = Arc::new(Lifecycle::new());+ let shared_scope = lifecycle.approval_scope();let approvals = crate::Approvals::new("a", lifecycle.removed(), lifecycle.approval_state());let removing = lifecycle.clone();let (entered, callback_entered) = std::sync::mpsc::channel();let (release, callback_release) = std::sync::mpsc::channel();let removal = std::thread::spawn(move || {- removing.mark_removed_with(|| {+ removing.mark_removed_with("agent_removed", || {entered.send(()).unwrap();callback_release.recv().unwrap();})});callback_entered.recv().unwrap();+ let core_closed = shared_scope.is_closed();let outcome = approvals.decide("pending-request", crate::ApprovalDecision::ApproveOnce);release.send(()).unwrap();assert!(removal.join().unwrap());+ assert!(+ core_closed,+ "the shared gate remained open after removal was claimed"+ );assert!(matches!(outcome, Err(crate::ApprovalsError::NotFound(_))),"{outcome:?}"@@ -132,7 +138,7 @@ fn accepted_approval_decisions_hold_the_removal_claim_barrier() {held,"removal could claim while a decision was still being applied");- assert!(state.claim_removal());+ assert!(state.claim_removal("agent_removed"));let mut ran = false;assert_eq!(state.with_live(|| ran = true), None);assert!(!ran);diff --git a/crates/openhuman-embed/src/agent/mod.rs b/crates/openhuman-embed/src/agent/mod.rsindex 61d178dfd6..13ea47e015 100644--- a/crates/openhuman-embed/src/agent/mod.rs+++ b/crates/openhuman-embed/src/agent/mod.rs@@ -145,7 +145,7 @@ impl AgentInner {if !self.lifecycle.begin_teardown() {return;}- self.lifecycle.mark_removed();+ self.lifecycle.mark_removed(resolution);self._runtime_guard.events.emit(Some(self.id.clone()),None,diff --git a/crates/openhuman-embed/src/runtime/lifecycle.rs b/crates/openhuman-embed/src/runtime/lifecycle.rsindex c216451c61..13587a4c90 100644--- a/crates/openhuman-embed/src/runtime/lifecycle.rs+++ b/crates/openhuman-embed/src/runtime/lifecycle.rs@@ -115,7 +115,7 @@ impl Runtime {};if !inner.lifecycle- .mark_removed_with(|| inner.deny_approvals("agent_removed"))+ .mark_removed_with("agent_removed", || inner.deny_approvals("agent_removed")){return Err(AgentError::UnknownId(id.to_string()));}diff --git a/crates/openhuman-embed/tests/agent_lifecycle.rs b/crates/openhuman-embed/tests/agent_lifecycle.rsindex 7e1169153c..e491275512 100644--- a/crates/openhuman-embed/tests/agent_lifecycle.rs+++ b/crates/openhuman-embed/tests/agent_lifecycle.rs@@ -101,6 +101,90 @@ fn removing_an_agent_releases_everything_it_held() {.receiver();let scratch = tempfile::tempdir().expect("scratch dir");+ // The removal barrier must govern every shared-gate entry point,+ // including RPC/chat calls made outside the Embed approvals facade.+ // Close the exact instance scope before its denial snapshot runs.+ let (closing, _closing_provider) =+ parking_agent(&runtime, "closing", scratch.path()).await;+ let closing_turn = {+ let closing = closing.clone();+ tokio::spawn(async move { closing.turn("write the marker").send().await })+ };+ let closing_request = eventually("closing agent to park", || {+ closing.approvals().pending().ok()?.into_iter().next()+ })+ .await;+ let closing_context = AgentContextRegistry::get("closing").unwrap();+ closing_context+ .host_overrides()+ .unwrap()+ .approval_scope()+ .unwrap()+ .close("agent_removed");+ let gate = openhuman_core::security::approval::ApprovalGate::try_global().unwrap();+ for decision in [+ openhuman_embed::ApprovalDecision::ApproveOnce,+ openhuman_embed::ApprovalDecision::ApproveAlwaysForTool,+ openhuman_embed::ApprovalDecision::Deny,+ ] {+ assert!(+ gate.decide(&closing_request.request_id, decision)+ .unwrap()+ .is_none(),+ "a closed instance must refuse direct gate decisions"+ );+ assert!(gate+ .decide_for_agent("closing", &closing_request.request_id, decision)+ .unwrap()+ .is_none());+ }+ assert_eq!(+ gate.classify_decide_miss(&closing_request.request_id),+ openhuman_core::security::approval::gate::DecideMiss::AlreadyResolved,+ "a removal barrier is a benign decision miss, not a lost registration"+ );+ for owner in [None, Some("closing")] {+ assert!(openhuman_core::security::approval::rpc::approval_decide(+ &closing_request.request_id,+ openhuman_embed::ApprovalDecision::ApproveOnce,+ owner,+ )+ .await+ .is_err());+ }+ assert_eq!(closing.approvals().pending().unwrap().len(), 1);+ runtime.remove_agent("closing").await.unwrap();+ removed(closing_turn.await.unwrap(), "closing");+ assert!(!scratch.path().join("closing-wrote").exists());+ assert!(gate+ .list_pending_for_agent(Some("closing"))+ .unwrap()+ .is_empty());++ // Reusing the public id installs a fresh barrier: the new request+ // remains answerable through the same context-free gate entry point.+ let (replacement, _replacement_provider) =+ parking_agent(&runtime, "closing", scratch.path()).await;+ let replacement_turn = {+ let replacement = replacement.clone();+ tokio::spawn(async move { replacement.turn("write the marker").send().await })+ };+ let replacement_request = eventually("replacement to park", || {+ replacement.approvals().pending().ok()?.into_iter().next()+ })+ .await;+ assert_ne!(replacement_request.request_id, closing_request.request_id);+ assert!(gate+ .decide(+ &replacement_request.request_id,+ openhuman_embed::ApprovalDecision::ApproveOnce,+ )+ .unwrap()+ .is_some());+ assert!(replacement_turn.await.unwrap().is_ok());+ assert!(scratch.path().join("closing-wrote").exists());+ runtime.remove_agent("closing").await.unwrap();+// ── an unknown id is refused ──let unknown = runtime.remove_agent("nope")