Skip to content

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

fix(approval): scope agent approval lookups to the caller's dispatch context

Steven Enamakel9845926cd4ba
diff --git a/crates/openhuman-core/src/security/approval/gate_state.rs b/crates/openhuman-core/src/security/approval/gate_state.rs
index 09cd94de43..726229ba90 100644
--- a/crates/openhuman-core/src/security/approval/gate_state.rs
+++ b/crates/openhuman-core/src/security/approval/gate_state.rs
@@ -155,11 +155,16 @@ impl ApprovalGate {
/// Deny every undecided request `agent` parked, resolving its waiters.
/// Returns how many rows were denied.
- pub fn deny_all_for_agent(&self, agent: &str, resolution: &str) -> anyhow::Result<usize> {
+ pub fn deny_all_for_agent(
+ &self,
+ ctx: &DispatchCtx,
+ agent: &str,
+ resolution: &str,
+ ) -> anyhow::Result<usize> {
if !store::exists(&self.config) {
return Ok(0);
}
- let rows = store::list_pending_for_agent(&self.config, Some(agent))?;
+ let rows = store::list_pending_for_agent(ctx, &self.config, Some(agent))?;
let mut denied = 0;
for row in rows {
let Some(decided) =
@@ -248,9 +253,10 @@ impl ApprovalGate {
/// process's own rows.
pub fn list_pending_for_agent(
&self,
+ ctx: &DispatchCtx,
agent: Option<&str>,
) -> anyhow::Result<Vec<PendingApproval>> {
- store::list_pending_for_agent(&self.config, agent)
+ store::list_pending_for_agent(ctx, &self.config, agent)
}
/// List recently decided rows for durable audit views.
diff --git a/crates/openhuman-core/src/security/approval/rpc.rs b/crates/openhuman-core/src/security/approval/rpc.rs
index 2cadf1ed4c..5576e35a62 100644
--- a/crates/openhuman-core/src/security/approval/rpc.rs
+++ b/crates/openhuman-core/src/security/approval/rpc.rs
@@ -52,6 +52,7 @@ pub async fn approval_get_gate_state() -> anyhow::Result<Outcome<ApprovalGateBoo
///
/// `agent_id` narrows the list to the rows one embedded agent parked.
pub async fn approval_list_pending(
+ ctx: &DispatchCtx,
agent_id: Option<&str>,
) -> anyhow::Result<Outcome<Vec<PendingApproval>>> {
tracing::debug!(
@@ -63,7 +64,7 @@ pub async fn approval_list_pending(
return Ok(Outcome::new(Vec::new(), vec![]));
};
let listed = match agent_id {
- Some(agent) => gate.list_pending_for_agent(Some(agent)),
+ Some(agent) => gate.list_pending_for_agent(ctx, Some(agent)),
None => gate.list_pending(),
};
let rows = match listed {
diff --git a/crates/openhuman-core/src/security/approval/schemas.rs b/crates/openhuman-core/src/security/approval/schemas.rs
index fb81a4dccf..397f38295e 100644
--- a/crates/openhuman-core/src/security/approval/schemas.rs
+++ b/crates/openhuman-core/src/security/approval/schemas.rs
@@ -180,10 +180,10 @@ pub fn schemas(function: &str) -> ControllerSchema {
}
}
-fn handle_list_pending(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_list_pending(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let agent_id = read_optional_string(&params, "agent_id")?;
- let outcome = approval_rpc::approval_list_pending(agent_id.as_deref())
+ let outcome = approval_rpc::approval_list_pending(&ctx, agent_id.as_deref())
.await
.map_err(|e| e.to_string())?;
to_json(outcome)
diff --git a/crates/openhuman-core/src/security/approval/store_agent.rs b/crates/openhuman-core/src/security/approval/store_agent.rs
index 22b7338987..e08b6ff868 100644
--- a/crates/openhuman-core/src/security/approval/store_agent.rs
+++ b/crates/openhuman-core/src/security/approval/store_agent.rs
@@ -3,6 +3,8 @@
use anyhow::Result;
+use crate::core::runtime::DispatchCtx;
+
use super::{Config, PendingApproval};
/// Whether the approval store exists for `config`'s workspace. The document
@@ -19,11 +21,12 @@ pub fn exists(_config: &Config) -> bool {
/// scope the caller runs in (under a SaaS profile every agent shares the
/// profile's scope, which is the caller's).
pub fn list_pending_for_agent(
+ ctx: &DispatchCtx,
config: &Config,
agent: Option<&str>,
) -> Result<Vec<PendingApproval>> {
let mut rows = super::list_pending(config)?;
- if let Some(agent) = agent.filter(|_| !acts_for_a_profile()) {
+ if let Some(agent) = agent.filter(|_| !acts_for_a_profile(ctx)) {
let docs = super::super::store_documents::for_agent(config, agent)?;
super::publish_expired(&docs.expire_stale(chrono::Utc::now())?);
for row in docs.list_pending()? {
@@ -39,8 +42,8 @@ pub fn list_pending_for_agent(
}
/// Whether the calling task serves a SaaS profile, whose agents share one scope.
-fn acts_for_a_profile() -> bool {
- crate::core::runtime::current_tenant().is_ok_and(|tenant| tenant.profile.is_some())
+fn acts_for_a_profile(ctx: &DispatchCtx) -> bool {
+ ctx.tenant().is_ok_and(|tenant| tenant.profile.is_some())
}
/// The agent that parked the still-undecided `request_id`: `Ok(None)` when no
diff --git a/crates/openhuman-embed/src/agent/approval_handler.rs b/crates/openhuman-embed/src/agent/approval_handler.rs
index 3e03f76f37..00f913abb6 100644
--- a/crates/openhuman-embed/src/agent/approval_handler.rs
+++ b/crates/openhuman-embed/src/agent/approval_handler.rs
@@ -27,6 +27,7 @@ impl ApprovalSubscription {
handler: Arc<dyn ApprovalHandler>,
removed: tokio::sync::watch::Receiver<bool>,
lifecycle: Arc<super::lifecycle::ApprovalState>,
+ core: Option<std::sync::Weak<openhuman_core::core::runtime::CoreContext>>,
) -> Self {
let cancellation = CancellationToken::new();
let subscriber = Arc::new(Handler {
@@ -35,6 +36,7 @@ impl ApprovalSubscription {
cancellation: cancellation.clone(),
removed,
lifecycle,
+ core,
});
Self {
_subscription: BUS.subscribe(subscriber),
@@ -48,6 +50,7 @@ struct Handler {
cancellation: CancellationToken,
removed: tokio::sync::watch::Receiver<bool>,
lifecycle: Arc<super::lifecycle::ApprovalState>,
+ core: Option<std::sync::Weak<openhuman_core::core::runtime::CoreContext>>,
}
#[async_trait::async_trait]
impl EventHandler<DomainEvent> for Handler {
@@ -67,7 +70,12 @@ impl EventHandler<DomainEvent> for Handler {
return;
}
let approvals =
- Approvals::new(&self.agent_id, self.removed.clone(), self.lifecycle.clone());
+ Approvals::new(
+ &self.agent_id,
+ self.removed.clone(),
+ self.lifecycle.clone(),
+ self.core.clone(),
+ );
let Ok(pending) = approvals.pending() else {
return;
};
diff --git a/crates/openhuman-embed/src/agent/approvals.rs b/crates/openhuman-embed/src/agent/approvals.rs
index 822dd284c4..e87e93550d 100644
--- a/crates/openhuman-embed/src/agent/approvals.rs
+++ b/crates/openhuman-embed/src/agent/approvals.rs
@@ -4,6 +4,7 @@
//! every agent on the runtime. Each request records the agent that parked it,
//! and an [`Approvals`] handle lists and decides only its own agent's.
+use openhuman_core::core::runtime::{CoreContext, DispatchCtx};
use openhuman_core::security::approval::{ApprovalError, ApprovalGate};
pub use openhuman_core::security::approval::{ApprovalDecision, PendingApproval};
@@ -33,6 +34,8 @@ pub struct Approvals {
agent_id: String,
removed: tokio::sync::watch::Receiver<bool>,
lifecycle: std::sync::Arc<super::lifecycle::ApprovalState>,
+ /// The agent's own context, held weakly so a handle never keeps it alive.
+ core: Option<std::sync::Weak<CoreContext>>,
}
impl Approvals {
@@ -40,11 +43,21 @@ impl Approvals {
agent_id: &str,
removed: tokio::sync::watch::Receiver<bool>,
lifecycle: std::sync::Arc<super::lifecycle::ApprovalState>,
+ core: Option<std::sync::Weak<CoreContext>>,
) -> Self {
Self {
agent_id: agent_id.to_string(),
removed,
lifecycle,
+ core,
+ }
+ }
+
+ /// The context this agent acts under; unbound once the agent is gone.
+ fn dispatch(&self) -> DispatchCtx {
+ match self.core.as_ref().and_then(std::sync::Weak::upgrade) {
+ Some(core) => DispatchCtx::new(core),
+ None => DispatchCtx::unbound(),
}
}
@@ -62,7 +75,7 @@ impl Approvals {
let Some(gate) = ApprovalGate::try_global() else {
return Ok(Vec::new());
};
- gate.list_pending_for_agent(Some(&self.agent_id))
+ gate.list_pending_for_agent(&self.dispatch(), Some(&self.agent_id))
.map_err(|err| ApprovalsError::Store(err.to_string()))
}
diff --git a/crates/openhuman-embed/src/agent/lifecycle_tests.rs b/crates/openhuman-embed/src/agent/lifecycle_tests.rs
index cc3e3390a2..d5da23ca9e 100644
--- a/crates/openhuman-embed/src/agent/lifecycle_tests.rs
+++ b/crates/openhuman-embed/src/agent/lifecycle_tests.rs
@@ -137,7 +137,7 @@ async fn a_claimed_removal_refuses_turns_before_approvals_are_settled() {
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 approvals = crate::Approvals::new("a", lifecycle.removed(), lifecycle.approval_state(), None);
let removing = lifecycle.clone();
let (entered, callback_entered) = std::sync::mpsc::channel();
let (release, callback_release) = std::sync::mpsc::channel();
diff --git a/crates/openhuman-embed/src/agent/mod.rs b/crates/openhuman-embed/src/agent/mod.rs
index 84742d2b27..27836dd694 100644
--- a/crates/openhuman-embed/src/agent/mod.rs
+++ b/crates/openhuman-embed/src/agent/mod.rs
@@ -197,7 +197,11 @@ impl AgentInner {
let Some(gate) = openhuman_core::security::approval::ApprovalGate::try_global() else {
return;
};
- match gate.deny_all_for_agent(&self.id, resolution) {
+ match gate.deny_all_for_agent(
+ &openhuman_core::core::runtime::DispatchCtx::new(Arc::clone(&self.ctx)),
+ &self.id,
+ resolution,
+ ) {
Ok(denied) => log::debug!(
"[embed][agent] id={} denied_approvals={denied} resolution={resolution}",
self.id
@@ -296,6 +300,7 @@ impl Agent {
handler,
self.inner.lifecycle.removed(),
self.inner.lifecycle.approval_state(),
+ Some(Arc::downgrade(&self.inner.ctx)),
)
}
@@ -316,6 +321,7 @@ impl Agent {
&self.inner.id,
self.inner.lifecycle.removed(),
self.inner.lifecycle.approval_state(),
+ Some(Arc::downgrade(&self.inner.ctx)),
)
}