use super::{
agent_tools::Served,
driver::render,
permission::PermissionDecision,
policy::{AcpAgentPolicy, AgentToolCallRef},
};
use crate::cli_runtime::{
agent_event::{render::EventRenderer, AgentEvent},
status_sink::StatusSink,
};
use agent_client_protocol::v1::schema::{
RequestPermissionRequest, SessionUpdate, ToolCallContent, ToolCallId, ToolCallStatus,
};
use std::{collections::HashSet, sync::Mutex};
pub(super) struct Deciders<'p, P> {
policy: &'p Mutex<P>,
served: Option<&'p Served>,
}
impl<'p, P: AcpAgentPolicy> Deciders<'p, P> {
pub(super) fn new(policy: &'p Mutex<P>, served: Option<&'p Served>) -> Self {
Self { policy, served }
}
pub(super) fn policy(&self) -> &'p Mutex<P> {
self.policy
}
fn served_tool<'c>(&self, call: AgentToolCallRef<'c>) -> Option<&'c str> {
let named = self.policy.lock().expect("ACP policy").agent_tool(call);
named.filter(|name| self.served.is_some_and(|served| served.serves(name)))
}
pub(super) fn decide(&self, request: &RequestPermissionRequest) -> PermissionDecision {
if self.served_tool((&request.tool_call).into()).is_some() {
return PermissionDecision::AllowOnce;
}
self.policy
.lock()
.expect("ACP policy")
.decide_permission(request)
}
pub(super) fn show(
&self,
mut update: SessionUpdate,
rejected: &HashSet<ToolCallId>,
renderer: &mut EventRenderer,
sink: &mut StatusSink,
) {
let status = self
.policy
.lock()
.expect("ACP policy")
.status_effects(&update);
for effect in status {
sink.apply_effect(effect);
}
mark_rejected(&mut update, rejected);
let tool = match &update {
SessionUpdate::ToolCall(call) => self.served_tool(call.into()),
_ => None,
};
if let Some(served) = self.served {
served.heard(&update, tool);
}
let event = match update {
SessionUpdate::ToolCall(call) if tool.is_some() => {
AgentEvent::ServedToolCall(Box::new(call))
}
update => AgentEvent::from(update),
};
render(renderer, sink, event);
}
}
pub(super) fn mark_rejected(update: &mut SessionUpdate, rejected: &HashSet<ToolCallId>) {
if let SessionUpdate::ToolCallUpdate(call) = update {
if call.fields.status == Some(ToolCallStatus::Completed)
&& rejected.contains(&call.tool_call_id)
{
call.fields.status = Some(ToolCallStatus::Failed);
call.fields.content = Some(vec![ToolCallContent::from(
"rejected by Rho permission policy",
)]);
}
}
}