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): close instance registration before removal snapshot
Steven Enamakel01457297be06
diff --git a/crates/openhuman-core/src/agent/host_overrides.rs b/crates/openhuman-core/src/agent/host_overrides.rsindex f87001346a..30c8d732b2 100644--- a/crates/openhuman-core/src/agent/host_overrides.rs+++ b/crates/openhuman-core/src/agent/host_overrides.rs@@ -17,6 +17,8 @@ pub use tinyagents_harness::cancel::CancellationToken;pub struct HostOverrides {/// Parent runtime adapters; local hook registration never edits this parent.pub parent: Option<Arc<HostOverrides>>,+ /// Approval registration barrier owned by this agent instance.+ pub approval_scope: Option<Arc<crate::security::approval::ApprovalScope>>,post_turn_hooks: RwLock<BTreeMap<String, Arc<dyn PostTurnHook>>>,tool_hooks: RwLock<BTreeMap<String, Arc<dyn ToolHook>>>,/// Native inference used by this agent instead of config-routed inference.@@ -38,6 +40,13 @@ impl std::fmt::Debug for HostOverrides {}impl HostOverrides {+ /// Resolve the instance barrier inherited by derived turn contexts.+ pub fn approval_scope(&self) -> Option<Arc<crate::security::approval::ApprovalScope>> {+ self.approval_scope+ .clone()+ .or_else(|| self.parent.as_ref().and_then(|p| p.approval_scope()))+ }+/// Add or replace an agent-local post-turn hook by name; `None` removes it.pub fn post_turn_hook(&self, name: &str, hook: Option<Arc<dyn PostTurnHook>>) {let mut hooks = selfdiff --git a/crates/openhuman-core/src/security/approval/gate_intercept.rs b/crates/openhuman-core/src/security/approval/gate_intercept.rsindex 7e0b91d0dd..d15d9455d4 100644--- a/crates/openhuman-core/src/security/approval/gate_intercept.rs+++ b/crates/openhuman-core/src/security/approval/gate_intercept.rs@@ -501,74 +501,88 @@ impl ApprovalGate {// to time out and return `Deny` incorrectly. (CodeRabbit// review on PR #2149.)let (tx, rx) = oneshot::channel::<ApprovalDecision>();- {- let mut waiters = self.waiters.lock();- waiters.insert(request_id.clone(), tx);- }- // Record the thread → request mapping so an inbound chat reply on this- // thread can be routed to `approval_decide` (see web channel ingress).- if let Some(thread_key) = thread_key.as_ref() {- self.thread_to_request- .lock()- .insert(thread_key.clone(), request_id.clone());- }- // Record the full routing correlation (thread/client/tool_call_id) so- // whichever path resolves this request's decision — `decide()`, the- // TTL timeout, or a dropped decision channel, all below — can mirror- // it onto `ApprovalDecided` without re-deriving it from ambient- // task-locals that may no longer be in scope by then.- self.insert_request_route(- &request_id,- RequestRoute {+ let register = || -> anyhow::Result<()> {+ {+ let mut waiters = self.waiters.lock();+ waiters.insert(request_id.clone(), tx);+ }+ // Record the thread → request mapping so an inbound chat reply on this+ // thread can be routed to `approval_decide` (see web channel ingress).+ if let Some(thread_key) = thread_key.as_ref() {+ self.thread_to_request+ .lock()+ .insert(thread_key.clone(), request_id.clone());+ }+ // Record the full routing correlation (thread/client/tool_call_id) so+ // whichever path resolves this request's decision — `decide()`, the+ // TTL timeout, or a dropped decision channel, all below — can mirror+ // it onto `ApprovalDecided` without re-deriving it from ambient+ // task-locals that may no longer be in scope by then.+ self.insert_request_route(+ &request_id,+ RequestRoute {+ thread_id: chat_thread_id.clone(),+ client_id: chat_client_id.clone(),+ tool_call_id: tool_call_id.map(str::to_string),+ forced,+ agent_id: agent_id.clone(),+ thread_key: thread_key.clone(),+ detached,+ },+ );+ store::insert_pending(&self.config, &pending, &self.session_id)?;++ tracing::info!(+ request_id = %request_id,+ tool = tool_name,+ thread_id = chat_thread_id.as_deref().unwrap_or("<none>"),+ client_id = chat_client_id.as_deref().unwrap_or("<none>"),+ agent_id = agent_id.as_deref().unwrap_or("<none>"),+ "[approval::gate] publishing ApprovalRequested (surface fires only if thread_id+client_id are both set)"+ );+ BUS.publish(DomainEvent::ApprovalRequested {+ request_id: request_id.clone(),+ tool_name: tool_name.to_string(),+ action_summary: action_summary.to_string(),+ args_redacted,thread_id: chat_thread_id.clone(),client_id: chat_client_id.clone(),tool_call_id: tool_call_id.map(str::to_string),- forced,+ expires_at: expires_at.map(|t| t.to_rfc3339()),agent_id: agent_id.clone(),- thread_key: thread_key.clone(),- detached,- },- );- if let Err(err) = store::insert_pending(&self.config, &pending, &self.session_id) {- self.evict_waiter(&request_id);- self.clear_thread(&thread_key, &request_id);- self.take_request_route(&request_id);- tracing::error!(- error = %err,- tool = tool_name,- "[approval::gate] failed to persist pending row — failing closed"- );- return (- GateOutcome::Deny {- reason: format!(- "{POLICY_DENIED_MARKER} Approval gate could not persist the request — \- denying for safety: {err}"- ),- },- None,- );+ });+ 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),+ None => Ok(register()),+ };+ match registered {+ Err(resolution) => {+ return (+ GateOutcome::Deny {+ reason: format!("{POLICY_DENIED_MARKER} Agent approval registration closed: {resolution}"),+ },+ None,+ );+ }+ Ok(Err(err)) => {+ self.evict_waiter(&request_id);+ self.clear_thread(&thread_key, &request_id);+ self.take_request_route(&request_id);+ tracing::error!(error = %err, tool = tool_name, "[approval::gate] failed to persist pending row — failing closed");+ return (+ GateOutcome::Deny {+ reason: format!("{POLICY_DENIED_MARKER} Approval gate could not persist the request — denying for safety: {err}"),+ },+ None,+ );+ }+ Ok(Ok(())) => {}}- tracing::info!(- request_id = %request_id,- tool = tool_name,- thread_id = chat_thread_id.as_deref().unwrap_or("<none>"),- client_id = chat_client_id.as_deref().unwrap_or("<none>"),- agent_id = agent_id.as_deref().unwrap_or("<none>"),- "[approval::gate] publishing ApprovalRequested (surface fires only if thread_id+client_id are both set)"- );- BUS.publish(DomainEvent::ApprovalRequested {- request_id: request_id.clone(),- tool_name: tool_name.to_string(),- action_summary: action_summary.to_string(),- args_redacted,- thread_id: chat_thread_id.clone(),- client_id: chat_client_id.clone(),- tool_call_id: tool_call_id.map(str::to_string),- expires_at: expires_at.map(|t| t.to_rfc3339()),- agent_id: agent_id.clone(),- });-// Flow-origin surface bridge (flow-approval-surface, PR3): a flow run// has no chat thread/client to route the generic `ApprovalRequested`// through (both are `None` above, so the web-channel bridge silentlydiff --git a/crates/openhuman-core/src/security/approval/mod.rs b/crates/openhuman-core/src/security/approval/mod.rsindex 188c6a94d5..030be04e7a 100644--- a/crates/openhuman-core/src/security/approval/mod.rs+++ b/crates/openhuman-core/src/security/approval/mod.rs@@ -15,6 +15,8 @@pub mod gate;pub mod redact;+mod registration_scope;+pub use registration_scope::ApprovalScope;pub mod rpc;pub mod schemas;pub mod store;diff --git a/crates/openhuman-core/src/security/approval/registration_scope.rs b/crates/openhuman-core/src/security/approval/registration_scope.rsnew file mode 100644index 0000000000..bf0c0e47fb--- /dev/null+++ b/crates/openhuman-core/src/security/approval/registration_scope.rs@@ -0,0 +1,40 @@+//! Serializes an agent instance's approval registration with its removal.++use std::sync::Mutex;++/// An instance-owned barrier; reusing an agent ID requires a fresh scope.+#[derive(Default)]+pub struct ApprovalScope {+ closed: Mutex<Option<String>>,+}++impl ApprovalScope {+ /// Stop registration and wait for any accepted registration to finish.+ /// The first teardown reason remains authoritative.+ pub fn close(&self, reason: &str) {+ let mut closed = self+ .closed+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ if closed.is_none() {+ *closed = Some(reason.to_owned());+ }+ }++ pub(crate) fn register<T>(&self, register: impl FnOnce() -> T) -> Result<T, String> {+ let closed = self+ .closed+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ if let Some(reason) = closed.as_ref() {+ return Err(reason.clone());+ }+ // Keep the barrier through persistence and ApprovalRequested publication.+ // No asynchronous work or user callbacks run in this critical section.+ Ok(register())+ }+}++#[cfg(test)]+#[path = "registration_scope_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/security/approval/registration_scope_tests.rs b/crates/openhuman-core/src/security/approval/registration_scope_tests.rsnew file mode 100644index 0000000000..c2e2c11a7b--- /dev/null+++ b/crates/openhuman-core/src/security/approval/registration_scope_tests.rs@@ -0,0 +1,52 @@+use super::ApprovalScope;+use std::sync::{mpsc, Arc};++#[test]+fn removal_refuses_late_registration_without_creating_a_pending_row() {+ let scope = ApprovalScope::default();+ scope.close("agent_removed");+ let mut created = false;+ let result = scope.register(|| created = true);+ assert_eq!(result, Err("agent_removed".to_owned()));+ assert!(!created);+}++#[test]+fn removal_waits_for_accepted_registration_before_taking_its_snapshot() {+ let scope = Arc::new(ApprovalScope::default());+ let (entered_tx, entered_rx) = mpsc::channel();+ let (release_tx, release_rx) = mpsc::channel();+ let (closed_tx, closed_rx) = mpsc::channel();+ let registering = scope.clone();+ let registration = std::thread::spawn(move || {+ registering.register(|| {+ entered_tx.send(()).unwrap();+ release_rx.recv().unwrap();+ })+ });+ entered_rx.recv().unwrap();+ let removing = scope.clone();+ let removal = std::thread::spawn(move || {+ removing.close("agent_removed");+ closed_tx.send(()).unwrap();+ });+ let closed_early = closed_rx+ .recv_timeout(std::time::Duration::from_millis(100))+ .is_ok();+ release_tx.send(()).unwrap();+ assert_eq!(registration.join().unwrap(), Ok(()));+ removal.join().unwrap();+ assert!(+ !closed_early,+ "removal snapshot raced an accepted registration"+ );+}++#[test]+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));+}diff --git a/crates/openhuman-embed/src/agent/build.rs b/crates/openhuman-embed/src/agent/build.rsindex 4b7786e867..7279943654 100644--- a/crates/openhuman-embed/src/agent/build.rs+++ b/crates/openhuman-embed/src/agent/build.rs@@ -265,6 +265,9 @@ 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(),+ ));overrides.model = provider.custom_model();overrides.role_models = provider.role_models().clone();overrides.session_store = parts.session_store;diff --git a/crates/openhuman-embed/src/agent/mod.rs b/crates/openhuman-embed/src/agent/mod.rsindex 259e1cfcf2..9d3c52e064 100644--- a/crates/openhuman-embed/src/agent/mod.rs+++ b/crates/openhuman-embed/src/agent/mod.rs@@ -167,6 +167,9 @@ impl AgentInner {/// Denies every approval this agent has parked, with `resolution`.pub(crate) fn deny_approvals(&self, resolution: &str) {+ if let Some(scope) = self.ctx.host_overrides().and_then(|o| o.approval_scope()) {+ scope.close(resolution);+ }let Some(gate) = openhuman_core::security::approval::ApprovalGate::try_global() else {return;};diff --git a/crates/openhuman-embed/tests/agent_lifecycle.rs b/crates/openhuman-embed/tests/agent_lifecycle.rsindex 9ba36d31ba..408b7f94f1 100644--- a/crates/openhuman-embed/tests/agent_lifecycle.rs+++ b/crates/openhuman-embed/tests/agent_lifecycle.rs@@ -127,7 +127,8 @@ fn removing_an_agent_releases_everything_it_held() {.and_then(|rows| rows.into_iter().next())}).await;- assert!(AgentContextRegistry::get("parker").is_some());+ let old_context =+ AgentContextRegistry::get("parker").expect("agent context registered");runtime.remove_agent("parker")@@ -135,6 +136,35 @@ fn removing_an_agent_releases_everything_it_held() {.expect("parker is removed");removed(turn.await.expect("turn task"), "parker");assert!(parker.approvals().pending().unwrap().is_empty());+ // A turn admitted before removal may reach the gate after the denial+ // snapshot. Its retained context must refuse registration entirely.+ let gate = openhuman_core::security::approval::ApprovalGate::try_global().unwrap();+ let late = tokio::time::timeout(+ Duration::from_millis(500),+ openhuman_core::core::runtime::CoreContext::scope(+ old_context,+ openhuman_core::agent::turn_origin::with_origin(+ AgentTurnOrigin::WebChat {+ thread_id: "late-lifecycle-thread".into(),+ client_id: "late-lifecycle-client".into(),+ request_id: None,+ },+ gate.intercept_forced(+ "shell",+ "late removal registration",+ serde_json::json!({}),+ ),+ ),+ ),+ )+ .await+ .expect("a removed instance cannot park a late approval");+ assert!(matches!(+ late,+ openhuman_core::security::approval::GateOutcome::Deny { reason }+ if reason.contains("agent_removed")+ ));+ assert!(parker.approvals().pending().unwrap().is_empty());let decided = loop {match tokio::time::timeout(Duration::from_secs(10), events.recv()).awaitdiff --git a/docs/TEST-COVERAGE-MATRIX.md b/docs/TEST-COVERAGE-MATRIX.mdindex e827603f76..89398dc9ba 100644--- a/docs/TEST-COVERAGE-MATRIX.md+++ b/docs/TEST-COVERAGE-MATRIX.md@@ -659,7 +659,7 @@ The thread JSONL store moved to `tinyagents_session::threads` (`vendor/tinyagent| 16.1.8 | MCP servers declared programmatically | RU | `crates/openhuman-embed/src/harness/mcp_tests.rs` | ✅ | stdio/HTTP transports mutually exclusive, enabled by default, env accumulation, allow/deny filters, auth carried through || 16.1.9 | Skill bundles installed into the workspace | RU | `crates/openhuman-embed/src/harness/skills_tests.rs` | ✅ | Copied not linked (discovery rejects symlinked bundles and manifests by design); symlinks skipped both as bundles and inside them; `Inherit` refuses the copy || 16.1.10 | One runtime per process | RU+RI | `crates/openhuman-embed/src/runtime/builder_tests.rs`, `crates/openhuman-embed/tests/harness_embed.rs` | ✅ | A second `Runtime` (or `Harness`) returns `AlreadyRunning` rather than sharing process-global keyring/event-bus/subscribers; a failed build releases the slot so a retry is possible |-| 16.1.11 | Many agents on one runtime | RU+RI | `crates/openhuman-embed/src/agent/spec_tests.rs`, `crates/openhuman-embed/tests/runtime_agents.rs`, `crates/openhuman-embed/tests/agent_lifecycle.rs` | ✅ | Three agents with different providers, access tiers, skills, MCP servers and action dirs; turns land on their own provider; per-agent MCP visibility; thread-scoped resume; duplicate/invalid ids and widening are refused; removal settles pending approvals with `agent_removed` before cancelling turns; a claimed removal immediately refuses new admission |+| 16.1.11 | Many agents on one runtime | RU+RI | `crates/openhuman-embed/src/agent/spec_tests.rs`, `crates/openhuman-embed/tests/runtime_agents.rs`, `crates/openhuman-embed/tests/agent_lifecycle.rs`, `crates/openhuman-core/src/security/approval/registration_scope_tests.rs` | ✅ | Three agents with different providers, access tiers, skills, MCP servers and action dirs; turns land on their own provider; per-agent MCP visibility; thread-scoped resume; duplicate/invalid ids and widening are refused; removal settles pending approvals with `agent_removed` before cancelling turns; a claimed removal immediately refuses new admission; instance-owned approval registration closes before the denial snapshot and rejects late registrations without persisting rows || 16.1.12 | API-key credential for library mode | RU+RI | `crates/openhuman-core/src/security/credentials/api_key_tests.rs`, `crates/openhuman-embed/tests/runtime_agents.rs` | ✅ | Key stored as an `api-key` auth profile; wins over an expired session; managed inference sends it as a bearer with no `x-api-key`; auth state reports `credential = "api-key"` || 16.1.14 | Host-backed read-only repository toolset | RI | `crates/openhuman-embed/tests/repository_tools.rs`, `crates/openhuman-embed/tests/repository_host_only.rs` | ✅ | Validated tree/range/search/symbol/git queries delegate only to the host; mandatory redaction, fenced bounded output, sanitized failures, and real HostOnly + readonly + untrusted-input refusal of shell/write/network. || 16.1.15 | Strict structured output and bounded repair | RI | `crates/openhuman-embed/tests/structured_validation.rs`, `crates/openhuman-embed/tests/structured_turns.rs`, `crates/openhuman-embed/tests/unit/turn_usage.rs` | ✅ | Wrong types and numeric combinators refused, invalid/external schemas make no call, repair bounded with usage, terminal length rejected even for complete JSON; successful charged usage reaches outcome/meter, invalid buyer charges stay unknown, root overlays retain child spend and session context. |