use std::fmt;
use std::future::Future;
use std::path::Path;
use std::pin::Pin;
use std::sync::Arc;
use aither_core::llm::tool::CallIdentity;
use crate::command::CommandRole;
use crate::script_language::ScriptLanguage;
use crate::shell_syntax::{ShellParseError, ShellScript};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScriptOrigin {
Foreground,
Background,
Run,
}
#[derive(Debug, Clone, Copy)]
pub struct ScriptCheck<'a> {
pub task_id: &'a str,
pub script: &'a str,
pub language: ScriptLanguage,
pub shell: Option<Result<&'a ShellScript, &'a ShellParseError>>,
pub origin: ScriptOrigin,
pub role: CommandRole,
pub working_dir: &'a Path,
pub call: Option<&'a CallIdentity>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScriptOutcome {
NotRun,
Failed,
Exited {
code: i32,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ScriptEnd<'a> {
pub task_id: &'a str,
pub outcome: ScriptOutcome,
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("{text}")]
pub struct PolicyRefusal {
text: String,
unchanged_read: bool,
}
impl PolicyRefusal {
#[must_use]
pub fn new(text: impl Into<String>) -> Self {
Self {
text: text.into(),
unchanged_read: false,
}
}
#[must_use]
pub fn unchanged_read(text: impl Into<String>) -> Self {
Self {
text: text.into(),
unchanged_read: true,
}
}
#[must_use]
pub fn text(&self) -> &str {
&self.text
}
#[must_use]
pub const fn is_unchanged_read(&self) -> bool {
self.unchanged_read
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PolicyDecision {
Allow,
Refuse(PolicyRefusal),
}
pub trait CommandPolicy: Send + Sync + 'static {
type State: Default + Send + Sync + 'static;
fn check(
&self,
script: &ScriptCheck<'_>,
state: &Self::State,
) -> impl Future<Output = PolicyDecision> + Send;
fn ended(&self, end: &ScriptEnd<'_>, state: &Self::State) -> impl Future<Output = ()> + Send {
let _ = (end, state);
std::future::ready(())
}
}
trait CommandPolicyImpl: Send + Sync {
fn bind(self: Arc<Self>) -> Arc<dyn BoundPolicyImpl>;
}
impl<T: CommandPolicy> CommandPolicyImpl for T {
fn bind(self: Arc<Self>) -> Arc<dyn BoundPolicyImpl> {
Arc::new(Bound {
policy: self,
state: T::State::default(),
})
}
}
struct Bound<T: CommandPolicy> {
policy: Arc<T>,
state: T::State,
}
trait BoundPolicyImpl: Send + Sync {
fn check<'a>(
&'a self,
script: &'a ScriptCheck<'a>,
) -> Pin<Box<dyn Future<Output = PolicyDecision> + Send + 'a>>;
fn ended<'a>(&'a self, end: &'a ScriptEnd<'a>)
-> Pin<Box<dyn Future<Output = ()> + Send + 'a>>;
}
impl<T: CommandPolicy> BoundPolicyImpl for Bound<T> {
fn check<'a>(
&'a self,
script: &'a ScriptCheck<'a>,
) -> Pin<Box<dyn Future<Output = PolicyDecision> + Send + 'a>> {
Box::pin(self.policy.check(script, &self.state))
}
fn ended<'a>(
&'a self,
end: &'a ScriptEnd<'a>,
) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>> {
Box::pin(self.policy.ended(end, &self.state))
}
}
#[derive(Clone)]
pub struct AnyCommandPolicy(Arc<dyn CommandPolicyImpl>);
impl AnyCommandPolicy {
#[must_use]
pub fn new(policy: impl CommandPolicy) -> Self {
Self(Arc::new(policy))
}
}
impl fmt::Debug for AnyCommandPolicy {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("AnyCommandPolicy")
}
}
#[derive(Clone, Default)]
pub struct CommandPolicies {
policies: Arc<[AnyCommandPolicy]>,
bound: Arc<[Arc<dyn BoundPolicyImpl>]>,
}
impl CommandPolicies {
pub fn new(policies: Vec<AnyCommandPolicy>) -> Self {
let policies: Arc<[AnyCommandPolicy]> = policies.into();
Self {
bound: Self::bind(&policies),
policies,
}
}
fn bind(policies: &[AnyCommandPolicy]) -> Arc<[Arc<dyn BoundPolicyImpl>]> {
policies
.iter()
.map(|policy| policy.0.clone().bind())
.collect()
}
#[must_use]
pub fn for_agent(&self) -> Self {
Self {
policies: self.policies.clone(),
bound: Self::bind(&self.policies),
}
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.bound.is_empty()
}
pub async fn check(&self, script: &ScriptCheck<'_>) -> Result<(), PolicyRefusal> {
let decisions =
futures::future::join_all(self.bound.iter().map(|policy| policy.check(script))).await;
decisions
.into_iter()
.find_map(|decision| match decision {
PolicyDecision::Allow => None,
PolicyDecision::Refuse(refusal) => Some(refusal),
})
.map_or(Ok(()), Err)
}
pub async fn ended(&self, task_id: &str, outcome: ScriptOutcome) {
if self.is_empty() {
return;
}
let end = ScriptEnd { task_id, outcome };
futures::future::join_all(self.bound.iter().map(|policy| policy.ended(&end))).await;
}
}
impl fmt::Debug for CommandPolicies {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("CommandPolicies")
.field("policies", &self.policies.len())
.finish_non_exhaustive()
}
}
#[cfg(test)]
mod tests {
use std::sync::atomic::{AtomicUsize, Ordering};
use super::*;
struct Quota {
allowed: usize,
}
impl CommandPolicy for Quota {
type State = AtomicUsize;
fn check(
&self,
_script: &ScriptCheck<'_>,
state: &AtomicUsize,
) -> impl Future<Output = PolicyDecision> + Send {
std::future::ready(if state.fetch_add(1, Ordering::SeqCst) < self.allowed {
PolicyDecision::Allow
} else {
PolicyDecision::Refuse(PolicyRefusal::new("over quota"))
})
}
}
struct Never(&'static str);
impl CommandPolicy for Never {
type State = ();
fn check(
&self,
_script: &ScriptCheck<'_>,
(): &(),
) -> impl Future<Output = PolicyDecision> + Send {
std::future::ready(PolicyDecision::Refuse(PolicyRefusal::new(self.0)))
}
}
fn check(task_id: &str) -> ScriptCheck<'_> {
ScriptCheck {
task_id,
script: "true",
language: ScriptLanguage::Shell,
shell: None,
origin: ScriptOrigin::Foreground,
role: CommandRole::Main,
working_dir: Path::new("/"),
call: None,
}
}
#[tokio::test]
async fn each_agent_binds_fresh_state() {
let main = CommandPolicies::new(vec![AnyCommandPolicy::new(Quota { allowed: 1 })]);
let view = main.clone();
let subagent = main.for_agent();
assert_eq!(main.check(&check("a")).await, Ok(()));
assert_eq!(
main.check(&check("b")).await,
Err(PolicyRefusal::new("over quota"))
);
assert!(
view.check(&check("c")).await.is_err(),
"a view of the main agent's registry shares its state"
);
assert_eq!(
subagent.check(&check("d")).await,
Ok(()),
"the subagent's state is its own"
);
}
#[tokio::test]
async fn the_first_refusal_in_registration_order_is_read() {
let policies = CommandPolicies::new(vec![
AnyCommandPolicy::new(Quota { allowed: 1 }),
AnyCommandPolicy::new(Never("first")),
AnyCommandPolicy::new(Never("second")),
]);
assert_eq!(
policies.check(&check("a")).await,
Err(PolicyRefusal::new("first"))
);
assert!(CommandPolicies::default().is_empty());
assert_eq!(CommandPolicies::default().check(&check("b")).await, Ok(()));
}
}