use std::fmt;
use tokio::sync::{mpsc, oneshot};
use crate::message::ToolCall;
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum NestedVerdict {
Allow,
Deny { reason: String },
Declined { reason: String },
Unanswered { reason: String },
}
impl NestedVerdict {
pub fn is_allowed(&self) -> bool {
matches!(self, Self::Allow)
}
pub fn reason(&self) -> Option<&str> {
match self {
Self::Allow => None,
Self::Deny { reason } | Self::Declined { reason } | Self::Unanswered { reason } => {
Some(reason)
}
}
}
}
pub(crate) struct NestedAsk {
pub call: ToolCall,
pub reply: oneshot::Sender<NestedVerdict>,
}
#[derive(Clone)]
pub struct NestedCalls {
tx: mpsc::UnboundedSender<NestedAsk>,
}
const RUN_GONE: &str = "the run ended before this call could be checked";
impl NestedCalls {
pub(crate) fn new(tx: mpsc::UnboundedSender<NestedAsk>) -> Self {
Self { tx }
}
pub async fn authorize(&self, call: ToolCall) -> NestedVerdict {
let (reply, answer) = oneshot::channel();
if self.tx.send(NestedAsk { call, reply }).is_err() {
return NestedVerdict::Deny {
reason: RUN_GONE.to_string(),
};
}
answer.await.unwrap_or_else(|_| NestedVerdict::Deny {
reason: RUN_GONE.to_string(),
})
}
}
impl fmt::Debug for NestedCalls {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("NestedCalls").finish_non_exhaustive()
}
}