Skip to content

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

feat(security): record which agent parked each approval (#7032)

oxoxDevf84e884b37cc
diff --git a/crates/openhuman-core/src/channels/host/channel_events_tests.rs b/crates/openhuman-core/src/channels/host/channel_events_tests.rs
index cccf6ec3a6..f2f5ec1079 100644
--- a/crates/openhuman-core/src/channels/host/channel_events_tests.rs
+++ b/crates/openhuman-core/src/channels/host/channel_events_tests.rs
@@ -81,6 +81,7 @@ fn approval(thread_id: Option<&str>, client_id: Option<&str>) -> DomainEvent {
client_id: client_id.map(str::to_string),
tool_call_id: None,
expires_at: None,
+ agent_id: None,
}
}
diff --git a/crates/openhuman-core/src/core/bus.rs b/crates/openhuman-core/src/core/bus.rs
index bbb3efb305..efba0df950 100644
--- a/crates/openhuman-core/src/core/bus.rs
+++ b/crates/openhuman-core/src/core/bus.rs
@@ -83,7 +83,9 @@ pub const EVENTS_INTERFACE: &str = "ai.tinyhumans.openhuman.Events";
/// `MemoryTreeBuildProgress`, `CacheRebuilt`) — nothing publishes them any
/// more — and adds `ConversationTurnCommitted` (memory's conversation
/// ingestion) and `CronSystemJobDue` (host-owned cron jobs).
-pub const EVENTS_VERSION: Version = Version::new(1, 8, 0);
+/// `1.9.0` adds an optional `agent_id` to `ApprovalRequested`,
+/// `ApprovalDecided` and `FlowApprovalRequested` (additive).
+pub const EVENTS_VERSION: Version = Version::new(1, 9, 0);
/// The bus. Initialised once by [`init`]; safe to touch before that.
pub static BUS: OnceBus<DomainEvent> = OnceBus::new();
diff --git a/crates/openhuman-core/src/core/events.rs b/crates/openhuman-core/src/core/events.rs
index c38b5113f7..36e4264407 100644
--- a/crates/openhuman-core/src/core/events.rs
+++ b/crates/openhuman-core/src/core/events.rs
@@ -570,6 +570,10 @@ pub enum DomainEvent {
/// expiry or the publish site hasn't been updated yet.
#[serde(default, skip_serializing_if = "Option::is_none")]
expires_at: Option<String>,
+ /// The embedded agent whose turn parked this call. `None` for the
+ /// process's own sessions.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ agent_id: Option<String>,
},
/// User decided a pending approval. Published by `approval_decide`
/// RPC handler after the gate's parked future resolves.
@@ -600,6 +604,10 @@ pub enum DomainEvent {
/// decision (approve or a deliberate deny).
#[serde(default, skip_serializing_if = "Option::is_none")]
resolution: Option<String>,
+ /// The embedded agent the decided request belongs to, mirrored from
+ /// `ApprovalRequested::agent_id`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ agent_id: Option<String>,
},
/// A `Workflow`-origin tool call parked in the `ApprovalGate` (issue
/// flow-approval-surface, PR2/PR3). Unlike `ApprovalRequested`, this
@@ -625,6 +633,9 @@ pub enum DomainEvent {
/// Short human-readable summary of the action (redacted, same as
/// `ApprovalRequested::action_summary`).
summary: String,
+ /// The embedded agent whose flow run parked this call.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ agent_id: Option<String>,
},
// ── Egress (privacy spine) ──────────────────────────────────────────
diff --git a/crates/openhuman-core/src/core/events_tests.rs b/crates/openhuman-core/src/core/events_tests.rs
index 6237de5c80..aefefa9920 100644
--- a/crates/openhuman-core/src/core/events_tests.rs
+++ b/crates/openhuman-core/src/core/events_tests.rs
@@ -555,6 +555,7 @@ fn approval_requested_does_not_surface_session_id() {
client_id: Some("c-1".to_string()),
tool_call_id: None,
expires_at: None,
+ agent_id: None,
};
let dbg = format!("{event:?}");
assert!(
diff --git a/crates/openhuman-core/src/security/approval/gate.rs b/crates/openhuman-core/src/security/approval/gate.rs
index 56dade16b7..7274bf991c 100644
--- a/crates/openhuman-core/src/security/approval/gate.rs
+++ b/crates/openhuman-core/src/security/approval/gate.rs
@@ -60,6 +60,23 @@ pub enum DecideMiss {
NeverRegistered,
}
+/// A decision refused by the gate before it reached the store.
+#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
+pub enum ApprovalError {
+ /// The request was parked by a different agent than the one deciding it.
+ #[error("approval request {request_id} belongs to another agent")]
+ WrongAgent { request_id: String },
+}
+
+/// The key `thread_to_request` files a parked chat thread under: the thread
+/// id alone for the process's own sessions, else the agent and thread.
+pub(crate) fn thread_route_key(agent_id: Option<&str>, thread_id: &str) -> String {
+ match agent_id {
+ Some(agent) => format!("{agent}\u{1f}{thread_id}"),
+ None => thread_id.to_string(),
+ }
+}
+
/// How long the gate will park a future before timing out and
/// returning `Deny`. 10 minutes matches the default `expires_at`
/// written into the persisted row.
@@ -204,6 +221,7 @@ pub(crate) struct RequestRoute {
pub(crate) client_id: Option<String>,
pub(crate) tool_call_id: Option<String>,
pub(crate) forced: bool,
+ pub(crate) agent_id: Option<String>,
}
/// Coordinator for pending approvals.
@@ -212,8 +230,9 @@ pub struct ApprovalGate {
session_id: String,
ttl: Duration,
waiters: Mutex<HashMap<String, oneshot::Sender<ApprovalDecision>>>,
- /// thread_id → request_id for the approval currently parked on that chat
- /// thread, so the web channel can route a yes/no reply to `approval_decide`.
+ /// [`thread_route_key`] → request_id for the approval currently parked on
+ /// that chat thread, so the web channel can route a yes/no reply to
+ /// `approval_decide`.
/// In-memory only (session-scoped — a parked approval doesn't survive a
/// restart, and the oneshot waiter is in-memory anyway).
thread_to_request: Mutex<HashMap<String, String>>,
@@ -245,7 +264,7 @@ pub struct ApprovalGate {
struct WaiterGuard<'a> {
gate: &'a ApprovalGate,
request_id: String,
- thread_id: Option<String>,
+ thread_key: Option<String>,
armed: bool,
}
@@ -273,9 +292,9 @@ impl Drop for WaiterGuard<'_> {
// an unconditional `remove` would delete the *new* request's routing, so
// the next typed yes/no would fall through as a fresh chat turn instead
// of resolving the live gate (#4774).
- if let Some(thread_id) = &self.thread_id {
+ if let Some(thread_key) = &self.thread_key {
self.gate
- .clear_thread_route_if_owned(thread_id, &self.request_id);
+ .clear_thread_route_if_owned(thread_key, &self.request_id);
}
let decided = store::decide(&self.gate.config, &self.request_id, ApprovalDecision::Deny);
if let Ok(Some(row)) = decided {
@@ -288,6 +307,7 @@ impl Drop for WaiterGuard<'_> {
client_id: route.as_ref().and_then(|r| r.client_id.clone()),
tool_call_id: route.and_then(|r| r.tool_call_id),
resolution: Some("cancelled".to_string()),
+ agent_id: row.agent_id,
});
}
tracing::warn!(
diff --git a/crates/openhuman-core/src/security/approval/gate_intercept.rs b/crates/openhuman-core/src/security/approval/gate_intercept.rs
index 6487be4f4d..b7f35dfb40 100644
--- a/crates/openhuman-core/src/security/approval/gate_intercept.rs
+++ b/crates/openhuman-core/src/security/approval/gate_intercept.rs
@@ -365,6 +365,10 @@ impl ApprovalGate {
let request_id = uuid::Uuid::new_v4().to_string();
let now = chrono::Utc::now();
+ let agent_id = crate::core::runtime::agent_scope::current_agent_id();
+ let thread_key = chat_thread_id
+ .as_deref()
+ .map(|thread_id| thread_route_key(agent_id.as_deref(), thread_id));
// Resolve the clamped park TTL up front so the persisted `expires_at`
// and the actual wait below (see `resolve_park_ttl` further down)
// use the same value — see `Self::resolve_park_ttl` and the
@@ -409,6 +413,7 @@ impl ApprovalGate {
expires_at,
source_context: source_context.clone(),
tool_call_id: tool_call_id.map(str::to_string),
+ agent_id: agent_id.clone(),
};
// Register the waiter BEFORE persisting the row so a fast
@@ -423,10 +428,10 @@ impl ApprovalGate {
}
// 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_id) = chat_thread_id.as_ref() {
+ if let Some(thread_key) = thread_key.as_ref() {
self.thread_to_request
.lock()
- .insert(thread_id.clone(), request_id.clone());
+ .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
@@ -440,11 +445,12 @@ impl ApprovalGate {
client_id: chat_client_id.clone(),
tool_call_id: tool_call_id.map(str::to_string),
forced,
+ agent_id: agent_id.clone(),
},
);
if let Err(err) = store::insert_pending(&self.config, &pending, &self.session_id) {
self.evict_waiter(&request_id);
- self.clear_thread(&chat_thread_id, &request_id);
+ self.clear_thread(&thread_key, &request_id);
self.take_request_route(&request_id);
tracing::error!(
error = %err,
@@ -467,6 +473,7 @@ impl ApprovalGate {
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 {
@@ -478,6 +485,7 @@ impl ApprovalGate {
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
@@ -507,6 +515,7 @@ impl ApprovalGate {
run_id: run_id.clone(),
tool_name: tool_name.to_string(),
summary: action_summary.to_string(),
+ agent_id: agent_id.clone(),
});
// The workspace the flow parked in, so the approval banner is
// dropped by a client that has since switched away rather than
@@ -577,7 +586,7 @@ impl ApprovalGate {
let mut waiter_guard = WaiterGuard {
gate: self,
request_id: request_id.clone(),
- thread_id: chat_thread_id.clone(),
+ thread_key: thread_key.clone(),
armed: true,
};
@@ -601,7 +610,7 @@ impl ApprovalGate {
waiter_guard.disarm();
// The routing mappings are only needed while parked; clear them on
// every exit (decision, channel drop, or timeout).
- self.clear_thread(&chat_thread_id, &request_id);
+ self.clear_thread(&thread_key, &request_id);
outcome
}
}
diff --git a/crates/openhuman-core/src/security/approval/gate_intercept_decision.rs b/crates/openhuman-core/src/security/approval/gate_intercept_decision.rs
index 23a6682e23..737d15cdb7 100644
--- a/crates/openhuman-core/src/security/approval/gate_intercept_decision.rs
+++ b/crates/openhuman-core/src/security/approval/gate_intercept_decision.rs
@@ -65,6 +65,7 @@ impl ApprovalGate {
client_id: route.as_ref().and_then(|r| r.client_id.clone()),
tool_call_id: route.and_then(|r| r.tool_call_id),
resolution: Some("cancelled".to_string()),
+ agent_id: row.agent_id.clone(),
});
}
(
@@ -164,6 +165,7 @@ impl ApprovalGate {
client_id: route.as_ref().and_then(|r| r.client_id.clone()),
tool_call_id: route.and_then(|r| r.tool_call_id),
resolution: Some("expired".to_string()),
+ agent_id: row.agent_id.clone(),
});
}
(
diff --git a/crates/openhuman-core/src/security/approval/gate_state.rs b/crates/openhuman-core/src/security/approval/gate_state.rs
index 344169859a..e6e68028a8 100644
--- a/crates/openhuman-core/src/security/approval/gate_state.rs
+++ b/crates/openhuman-core/src/security/approval/gate_state.rs
@@ -72,11 +72,89 @@ impl ApprovalGate {
client_id: route.as_ref().and_then(|r| r.client_id.clone()),
tool_call_id: route.and_then(|r| r.tool_call_id),
resolution: None,
+ agent_id: row.agent_id.clone(),
});
}
Ok(decided)
}
+ /// [`Self::decide`] on behalf of `agent`: refuses with
+ /// [`ApprovalError::WrongAgent`] when the request was parked by any other
+ /// agent (or by the process itself), so one agent cannot answer another's
+ /// approval.
+ pub fn decide_for_agent(
+ &self,
+ agent: &str,
+ request_id: &str,
+ decision: ApprovalDecision,
+ ) -> anyhow::Result<Option<PendingApproval>> {
+ let owner = match self
+ .request_routes
+ .lock()
+ .get(request_id)
+ .map(|route| route.agent_id.clone())
+ {
+ Some(owner) => Some(owner),
+ None => store::pending_agent(&self.config, request_id)?,
+ };
+ if let Some(owner) = owner {
+ if owner.as_deref() != Some(agent) {
+ tracing::warn!(
+ request_id = %request_id,
+ agent_id = %agent,
+ owner = owner.as_deref().unwrap_or("<process>"),
+ "[approval::gate] decision refused: request belongs to another agent"
+ );
+ return Err(ApprovalError::WrongAgent {
+ request_id: request_id.to_string(),
+ }
+ .into());
+ }
+ }
+ self.decide(request_id, decision)
+ }
+
+ /// 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> {
+ let rows = store::list_pending_for_agent(&self.config, Some(agent))?;
+ let mut denied = 0;
+ for row in rows {
+ let Some(decided) = store::decide(&self.config, &row.request_id, ApprovalDecision::Deny)?
+ else {
+ continue;
+ };
+ denied += 1;
+ if let Some(tx) = self.take_waiter(&decided.request_id) {
+ let _ = tx.send(ApprovalDecision::Deny);
+ }
+ let route = self.take_request_route(&decided.request_id);
+ if let Some(thread_id) = route.as_ref().and_then(|r| r.thread_id.as_deref()) {
+ self.clear_thread_route_if_owned(
+ &thread_route_key(Some(agent), thread_id),
+ &decided.request_id,
+ );
+ }
+ BUS.publish(DomainEvent::ApprovalDecided {
+ request_id: decided.request_id.clone(),
+ tool_name: decided.tool_name.clone(),
+ decision: ApprovalDecision::Deny.as_str().to_string(),
+ thread_id: route.as_ref().and_then(|r| r.thread_id.clone()),
+ client_id: route.as_ref().and_then(|r| r.client_id.clone()),
+ tool_call_id: route.and_then(|r| r.tool_call_id),
+ resolution: Some(resolution.to_string()),
+ agent_id: Some(agent.to_string()),
+ });
+ }
+ tracing::info!(
+ agent_id = %agent,
+ denied,
+ resolution,
+ "[approval::gate] denied every pending request of the agent"
+ );
+ Ok(denied)
+ }
+
/// 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`:
@@ -118,6 +196,15 @@ impl ApprovalGate {
store::list_pending(&self.config)
}
+ /// [`Self::list_pending`] narrowed to `agent`'s rows; `None` lists the
+ /// process's own rows.
+ pub fn list_pending_for_agent(
+ &self,
+ agent: Option<&str>,
+ ) -> anyhow::Result<Vec<PendingApproval>> {
+ store::list_pending_for_agent(&self.config, agent)
+ }
+
/// List recently decided rows for durable audit views.
pub fn list_recent_decisions(
&self,
@@ -213,10 +300,21 @@ impl ApprovalGate {
waiters.remove(request_id);
}
- /// The request_id of the approval currently parked on `thread_id`, if any.
- /// Used by the web channel to route an inbound yes/no reply to a decision.
+ /// The request_id of the approval currently parked on `thread_id` by the
+ /// ambient context's agent, if any. Used by the web channel to route an
+ /// inbound yes/no reply to a decision.
pub fn pending_for_thread(&self, thread_id: &str) -> Option<String> {
- self.thread_to_request.lock().get(thread_id).cloned()
+ let agent = crate::core::runtime::agent_scope::current_agent_id();
+ self.pending_for_agent_thread(agent.as_deref(), thread_id)
+ }
+
+ /// The request_id `agent` (`None`: the process) has parked on
+ /// `thread_id`, if any.
+ pub fn pending_for_agent_thread(&self, agent: Option<&str>, thread_id: &str) -> Option<String> {
+ self.thread_to_request
+ .lock()
+ .get(&thread_route_key(agent, thread_id))
+ .cloned()
}
/// The full pending row parked on `thread_id`, if any.
@@ -264,9 +362,9 @@ impl ApprovalGate {
}
/// Drop the thread → request mapping when it still belongs to this request.
- fn clear_thread(&self, thread_id: &Option<String>, request_id: &str) {
- if let Some(t) = thread_id {
- self.clear_thread_route_if_owned(t, request_id);
+ fn clear_thread(&self, thread_key: &Option<String>, request_id: &str) {
+ if let Some(key) = thread_key {
+ self.clear_thread_route_if_owned(key, request_id);
}
}
@@ -275,10 +373,10 @@ impl ApprovalGate {
/// replacement turn may have already parked a new approval on the same
/// thread and overwritten the entry; clearing unconditionally would delete
/// the *new* request's routing (#4774).
- fn clear_thread_route_if_owned(&self, thread_id: &str, request_id: &str) {
+ fn clear_thread_route_if_owned(&self, thread_key: &str, request_id: &str) {
let mut map = self.thread_to_request.lock();
- if map.get(thread_id).is_some_and(|rid| rid == request_id) {
- map.remove(thread_id);
+ if map.get(thread_key).is_some_and(|rid| rid == request_id) {
+ map.remove(thread_key);
}
}
}
diff --git a/crates/openhuman-core/src/security/approval/mod.rs b/crates/openhuman-core/src/security/approval/mod.rs
index 142017a42c..4e6907ea07 100644
--- a/crates/openhuman-core/src/security/approval/mod.rs
+++ b/crates/openhuman-core/src/security/approval/mod.rs
@@ -21,8 +21,8 @@ pub mod store;
pub mod types;
pub use gate::{
- parse_approval_reply, ApprovalChatContext, ApprovalGate, FlowRunContext, APPROVAL_CHAT_CONTEXT,
- APPROVAL_COPILOT_STREAM_CONTEXT, APPROVAL_FLOW_RUN_CONTEXT,
+ parse_approval_reply, ApprovalChatContext, ApprovalError, ApprovalGate, FlowRunContext,
+ APPROVAL_CHAT_CONTEXT, APPROVAL_COPILOT_STREAM_CONTEXT, APPROVAL_FLOW_RUN_CONTEXT,
};
pub use redact::{redact_args, summarize_action};
pub use schemas::all_controller_schemas as all_approval_controller_schemas;
diff --git a/crates/openhuman-core/src/security/approval/store.rs b/crates/openhuman-core/src/security/approval/store.rs
index 2e3cf4054d..446d1d8006 100644
--- a/crates/openhuman-core/src/security/approval/store.rs
+++ b/crates/openhuman-core/src/security/approval/store.rs
@@ -128,6 +128,10 @@ fn migrate_columns(conn: &Connection) -> Result<()> {
"tool_call_id",
"ALTER TABLE pending_approvals ADD COLUMN tool_call_id TEXT",
),
+ (
+ "agent_id",
+ "ALTER TABLE pending_approvals ADD COLUMN agent_id TEXT",
+ ),
] {
if !have.contains(col) {
// Two cores can open the same workspace during startup (for
@@ -143,6 +147,12 @@ fn migrate_columns(conn: &Connection) -> Result<()> {
tracing::info!(column = col, "[approval::store] migrated v1 schema");
}
}
+ conn.execute(
+ "CREATE INDEX IF NOT EXISTS idx_pending_approvals_agent
+ ON pending_approvals(agent_id, decided_at)",
+ params![],
+ )
+ .context("[approval::store] create agent index")?;
Ok(())
}
@@ -238,8 +248,8 @@ pub fn insert_pending(config: &Config, pending: &PendingApproval, session_id: &s
conn.execute(
"INSERT INTO pending_approvals
(request_id, tool_name, action_summary, args_redacted,
- session_id, created_at, expires_at, source_context, tool_call_id)
- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
+ session_id, created_at, expires_at, source_context, tool_call_id, agent_id)
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
params![
pending.request_id,
pending.tool_name,
@@ -250,6 +260,7 @@ pub fn insert_pending(config: &Config, pending: &PendingApproval, session_id: &s
expires,
source_context,
pending.tool_call_id,
+ pending.agent_id,
],
)
.context("[approval::store] insert pending row")?;
@@ -281,7 +292,7 @@ pub fn list_pending(config: &Config) -> Result<Vec<PendingApproval>> {
let mut stmt = conn
.prepare(
"SELECT request_id, tool_name, action_summary, args_redacted,
- session_id, created_at, expires_at, source_context, tool_call_id
+ session_id, created_at, expires_at, source_context, tool_call_id, agent_id
FROM pending_approvals
WHERE decided_at IS NULL
ORDER BY created_at ASC",
@@ -298,6 +309,44 @@ pub fn list_pending(config: &Config) -> Result<Vec<PendingApproval>> {
})
}
+/// [`list_pending`] narrowed to the rows of `agent` (see
+/// [`PendingApproval::belongs_to`]).
+pub fn list_pending_for_agent(
+ config: &Config,
+ agent: Option<&str>,
+) -> Result<Vec<PendingApproval>> {
+ Ok(list_pending(config)?
+ .into_iter()
+ .filter(|row| row.belongs_to(agent))
+ .collect())
+}
+
+/// The agent that parked the still-undecided `request_id`: `Ok(None)` when no
+/// such row exists, `Ok(Some(None))` for a row the process parked itself.
+pub fn pending_agent(config: &Config, request_id: &str) -> Result<Option<Option<String>>> {
+ with_connection(config, |conn| {
+ let mut stmt = conn
+ .prepare(
+ "SELECT agent_id FROM pending_approvals
+ WHERE request_id = ?1 AND decided_at IS NULL",
+ )
+ .context("[approval::store] prepare pending_agent")?;
+ let mut rows = stmt
+ .query(params![request_id])
+ .context("[approval::store] query pending_agent")?;
+ match rows
+ .next()
+ .context("[approval::store] pending_agent next")?
+ {
+ Some(row) => Ok(Some(
+ row.get::<_, Option<String>>(0)
+ .context("[approval::store] pending_agent decode")?,
+ )),
+ None => Ok(None),
+ }
+ })
+}
+
/// Look up the persisted decision for a request_id without mutating
/// state. Returns `Ok(None)` when the row doesn't exist or hasn't
/// been decided yet. Used to resolve gate-timeout vs decide races
@@ -352,7 +401,7 @@ pub fn decide(
let mut stmt = conn
.prepare(
"SELECT request_id, tool_name, action_summary, args_redacted,
- session_id, created_at, expires_at, source_context, tool_call_id
+ session_id, created_at, expires_at, source_context, tool_call_id, agent_id
FROM pending_approvals WHERE request_id = ?1",
)
.context("[approval::store] prepare select decided")?;
@@ -513,7 +562,7 @@ fn expire_stale_with_now(conn: &Connection, now: DateTime<Utc>) -> Result<Vec<Pe
let mut stmt = conn
.prepare(
"SELECT request_id, tool_name, action_summary, args_redacted,
- session_id, created_at, expires_at, source_context, tool_call_id
+ session_id, created_at, expires_at, source_context, tool_call_id, agent_id
FROM pending_approvals
WHERE decided_at IS NULL
AND expires_at IS NOT NULL
@@ -555,6 +604,7 @@ fn expire_stale_with_now(conn: &Connection, now: DateTime<Utc>) -> Result<Vec<Pe
client_id: None,
tool_call_id: row.tool_call_id.clone(),
resolution: Some("expired".to_string()),
+ agent_id: row.agent_id.clone(),
});
}
Ok(about_to_expire)
@@ -630,6 +680,7 @@ fn row_to_pending(row: &rusqlite::Row<'_>) -> rusqlite::Result<PendingApproval>
// Column 8 (`tool_call_id`) is likewise absent on rows written before
// this field existed — tolerate a missing-column read error as `None`.
let tool_call_id: Option<String> = row.get(8).unwrap_or(None);
+ let agent_id: Option<String> = row.get(9).unwrap_or(None);
// Note: column index 4 (`session_id`) is read on the SELECT but
// intentionally not surfaced — see `PendingApproval` doc-comment.
@@ -642,6 +693,7 @@ fn row_to_pending(row: &rusqlite::Row<'_>) -> rusqlite::Result<PendingApproval>
expires_at: expires_opt.as_deref().map(parse_rfc3339),
source_context,
tool_call_id,
+ agent_id,
})
}
diff --git a/crates/openhuman-core/src/security/approval/store_tests.rs b/crates/openhuman-core/src/security/approval/store_tests.rs
index 8293a64bd4..e9194ccc5c 100644
--- a/crates/openhuman-core/src/security/approval/store_tests.rs
+++ b/crates/openhuman-core/src/security/approval/store_tests.rs
@@ -49,6 +49,7 @@ fn sample_with_expiry(
expires_at,
source_context: None,
tool_call_id: None,
+ agent_id: None,
}
}
diff --git a/crates/openhuman-core/src/security/approval/types.rs b/crates/openhuman-core/src/security/approval/types.rs
index 367617b5be..2bdc77a847 100644
--- a/crates/openhuman-core/src/security/approval/types.rs
+++ b/crates/openhuman-core/src/security/approval/types.rs
@@ -42,6 +42,10 @@ pub struct PendingApproval {
/// workflows) and for rows persisted before this field existed.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tool_call_id: Option<String>,
+ /// The embedded agent whose turn parked this call. `None` for the
+ /// process's own sessions and for rows persisted before this field.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub agent_id: Option<String>,
}
impl PendingApproval {
@@ -63,6 +67,7 @@ impl PendingApproval {
expires_at,
source_context: None,
tool_call_id: None,
+ agent_id: None,
}
}
@@ -74,6 +79,12 @@ impl PendingApproval {
self.source_context = Some(ctx);
self
}
+
+ /// Whether this row is visible to `agent`: `None` sees the process's own
+ /// rows, `Some(id)` sees only that agent's.
+ pub fn belongs_to(&self, agent: Option<&str>) -> bool {
+ self.agent_id.as_deref() == agent
+ }
}
/// Correlation context for a [`PendingApproval`] raised from a source other
diff --git a/crates/openhuman-core/src/security/approval/types_tests.rs b/crates/openhuman-core/src/security/approval/types_tests.rs
index d6192174d2..08f5e26129 100644
--- a/crates/openhuman-core/src/security/approval/types_tests.rs
+++ b/crates/openhuman-core/src/security/approval/types_tests.rs
@@ -142,6 +142,7 @@ fn pending_approval_debug_and_serialize_do_not_carry_session_id() {
expires_at: None,
source_context: None,
tool_call_id: None,
+ agent_id: None,
};
let dbg = format!("{p:?}");
assert!(
diff --git a/crates/openhuman-core/src/web_chat/event_bus.rs b/crates/openhuman-core/src/web_chat/event_bus.rs
index 2560e4684f..0296459795 100644
--- a/crates/openhuman-core/src/web_chat/event_bus.rs
+++ b/crates/openhuman-core/src/web_chat/event_bus.rs
@@ -614,6 +614,7 @@ impl EventHandler<DomainEvent> for ApprovalSurfaceSubscriber {
client_id,
tool_call_id,
expires_at,
+ agent_id: _,
} => match (thread_id, client_id) {
(Some(thread_id), Some(client_id)) => {
log::info!(
@@ -646,6 +647,7 @@ impl EventHandler<DomainEvent> for ApprovalSurfaceSubscriber {
client_id,
tool_call_id,
resolution,
+ agent_id: _,
} => match (thread_id, client_id) {
(Some(thread_id), Some(client_id)) => {
log::info!(
diff --git a/crates/openhuman-core/src/web_chat/event_bus_tests.rs b/crates/openhuman-core/src/web_chat/event_bus_tests.rs
index ee91ac2bdd..93fce50083 100644
--- a/crates/openhuman-core/src/web_chat/event_bus_tests.rs
+++ b/crates/openhuman-core/src/web_chat/event_bus_tests.rs
@@ -443,6 +443,7 @@ async fn approval_surface_bridges_approval_decided_with_resolution() {
client_id: Some("client-decided-1".to_string()),
tool_call_id: Some("call-decided-1".to_string()),
resolution: Some("expired".to_string()),
+ agent_id: None,
});
let ev = find_agent_web_event(&mut web_rx, "approval_decided", "thread-decided-1").await;
@@ -469,6 +470,7 @@ async fn approval_surface_drops_approval_decided_without_chat_routing() {
client_id: None,
tool_call_id: None,
resolution: Some("expired".to_string()),
+ agent_id: None,
});
// A sibling event we know fires, so we don't just race an empty channel.
crate::core::bus::BUS.publish(DomainEvent::ThreadGoalCleared {
diff --git a/crates/openhuman-rpc/src/server/socketio.rs b/crates/openhuman-rpc/src/server/socketio.rs
index f522886418..8bb5ba0ad6 100644
--- a/crates/openhuman-rpc/src/server/socketio.rs
+++ b/crates/openhuman-rpc/src/server/socketio.rs
@@ -997,6 +997,7 @@ pub fn spawn_web_channel_bridge(io: SocketIo) {
run_id,
tool_name,
summary,
+ agent_id: _,
} => {
let payload = serde_json::json!({
"request_id": request_id,