use std::fmt;
use std::future::Future;
use std::path::PathBuf;
use std::pin::Pin;
use std::sync::Arc;
use aither_core::llm::tool::{ApprovalRequest, CallIdentity};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use crate::container::ContainerPath;
use crate::interpreter::Interpreter;
use crate::shell_syntax::{ShellParseError, ShellScript};
use crate::terminal::DirectoryResetReason;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScriptOrigin {
Foreground,
Background,
Run,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
#[allow(missing_docs, reason = "the schema's descriptions are the embedder's")]
pub enum SandboxMode {
#[default]
Sandboxed,
Unsandboxed,
}
impl SandboxMode {
#[must_use]
pub const fn description(self) -> &'static str {
match self {
Self::Sandboxed => "sandboxed",
Self::Unsandboxed => "unsandboxed (no sandbox, full access)",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ScriptDir {
Host(PathBuf),
Container {
inside: ContainerPath,
host: PathBuf,
},
Remote {
server: String,
},
}
impl ScriptDir {
#[must_use]
pub fn host(&self) -> Option<&std::path::Path> {
match self {
Self::Host(dir) | Self::Container { host: dir, .. } => Some(dir),
Self::Remote { .. } => None,
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct ScriptCheck<'a> {
pub task_id: &'a str,
pub script: &'a str,
pub interpreter: Interpreter,
pub shell: Option<Result<&'a ShellScript, &'a ShellParseError>>,
pub origin: ScriptOrigin,
pub sandbox: SandboxMode,
pub location: Option<&'a str>,
pub start: &'a ScriptDir,
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 enum Carry {
Moved,
Reset(DirectoryResetReason),
Unchanged,
NotCarried,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ScriptEnd<'a> {
pub task_id: &'a str,
pub outcome: ScriptOutcome,
pub end: &'a ScriptDir,
pub carry: Carry,
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("{text}")]
pub struct ScriptRefusal {
text: String,
}
impl ScriptRefusal {
#[must_use]
pub fn new(text: impl Into<String>) -> Self {
Self { text: text.into() }
}
#[must_use]
pub fn text(&self) -> &str {
&self.text
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ScriptDecision {
Pass,
Allow,
Ask(ApprovalRequest),
Refuse(ScriptRefusal),
}
impl ScriptDecision {
const fn strictness(&self) -> u8 {
match self {
Self::Pass => 0,
Self::Allow => 1,
Self::Ask(_) => 2,
Self::Refuse(_) => 3,
}
}
#[must_use]
pub fn strictest(decisions: impl IntoIterator<Item = Self>) -> Self {
decisions
.into_iter()
.fold(Self::Pass, |strictest, decision| {
if decision.strictness() > strictest.strictness() {
decision
} else {
strictest
}
})
}
}
pub trait ScriptPolicy: Send + Sync + 'static {
type State: Default + Send + Sync + 'static;
fn check(
&self,
script: &ScriptCheck<'_>,
state: &Self::State,
) -> impl Future<Output = ScriptDecision> + Send;
fn ended(&self, end: &ScriptEnd<'_>, state: &Self::State) -> impl Future<Output = ()> + Send {
let _ = (end, state);
std::future::ready(())
}
}
trait ScriptPolicyImpl: Send + Sync {
fn bind(self: Arc<Self>) -> Arc<dyn BoundPolicyImpl>;
}
impl<T: ScriptPolicy> ScriptPolicyImpl for T {
fn bind(self: Arc<Self>) -> Arc<dyn BoundPolicyImpl> {
Arc::new(Bound {
policy: self,
state: T::State::default(),
})
}
}
struct Bound<T: ScriptPolicy> {
policy: Arc<T>,
state: T::State,
}
trait BoundPolicyImpl: Send + Sync {
fn check<'a>(
&'a self,
script: &'a ScriptCheck<'a>,
) -> Pin<Box<dyn Future<Output = ScriptDecision> + Send + 'a>>;
fn ended<'a>(&'a self, end: &'a ScriptEnd<'a>)
-> Pin<Box<dyn Future<Output = ()> + Send + 'a>>;
}
impl<T: ScriptPolicy> BoundPolicyImpl for Bound<T> {
fn check<'a>(
&'a self,
script: &'a ScriptCheck<'a>,
) -> Pin<Box<dyn Future<Output = ScriptDecision> + 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 AnyScriptPolicy(Arc<dyn ScriptPolicyImpl>);
impl AnyScriptPolicy {
#[must_use]
pub fn new(policy: impl ScriptPolicy) -> Self {
Self(Arc::new(policy))
}
}
impl fmt::Debug for AnyScriptPolicy {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("AnyScriptPolicy")
}
}
#[derive(Clone, Default)]
pub struct ScriptPolicies {
policies: Arc<[AnyScriptPolicy]>,
bound: Arc<[Arc<dyn BoundPolicyImpl>]>,
}
impl ScriptPolicies {
#[must_use]
pub fn new(policies: Vec<AnyScriptPolicy>) -> Self {
let policies: Arc<[AnyScriptPolicy]> = policies.into();
Self {
bound: Self::bind(&policies),
policies,
}
}
fn bind(policies: &[AnyScriptPolicy]) -> 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<'_>) -> ScriptDecision {
let decisions =
futures::future::join_all(self.bound.iter().map(|policy| policy.check(script))).await;
ScriptDecision::strictest(decisions)
}
pub async fn ended(
&self,
task_id: &str,
outcome: ScriptOutcome,
end: &ScriptDir,
carry: Carry,
) {
if self.is_empty() {
return;
}
let end = ScriptEnd {
task_id,
outcome,
end,
carry,
};
futures::future::join_all(self.bound.iter().map(|policy| policy.ended(&end))).await;
}
}
impl fmt::Debug for ScriptPolicies {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ScriptPolicies")
.field("policies", &self.policies.len())
.finish_non_exhaustive()
}
}
#[cfg(test)]
mod tests {
use std::sync::atomic::{AtomicUsize, Ordering};
use aither_core::llm::tool::ApprovalKind;
use super::*;
struct Quota {
allowed: usize,
}
impl ScriptPolicy for Quota {
type State = AtomicUsize;
fn check(
&self,
_script: &ScriptCheck<'_>,
state: &AtomicUsize,
) -> impl Future<Output = ScriptDecision> + Send {
std::future::ready(if state.fetch_add(1, Ordering::SeqCst) < self.allowed {
ScriptDecision::Allow
} else {
ScriptDecision::Refuse(ScriptRefusal::new("over quota"))
})
}
}
struct Always(ScriptDecision);
impl ScriptPolicy for Always {
type State = ();
fn check(
&self,
_script: &ScriptCheck<'_>,
(): &(),
) -> impl Future<Output = ScriptDecision> + Send {
std::future::ready(self.0.clone())
}
}
fn refuse(text: &str) -> ScriptDecision {
ScriptDecision::Refuse(ScriptRefusal::new(text))
}
fn ask(subject: &str) -> ScriptDecision {
ScriptDecision::Ask(ApprovalRequest::new(ApprovalKind::new("test"), subject))
}
fn check(task_id: &str) -> ScriptCheck<'_> {
static START: std::sync::LazyLock<ScriptDir> =
std::sync::LazyLock::new(|| ScriptDir::Host(PathBuf::from("/")));
ScriptCheck {
task_id,
script: "true",
interpreter: Interpreter::Shell,
shell: None,
origin: ScriptOrigin::Foreground,
sandbox: SandboxMode::Sandboxed,
location: None,
start: &START,
call: None,
}
}
fn policies(decisions: impl IntoIterator<Item = ScriptDecision>) -> ScriptPolicies {
ScriptPolicies::new(
decisions
.into_iter()
.map(|decision| AnyScriptPolicy::new(Always(decision)))
.collect(),
)
}
#[tokio::test]
async fn each_agent_binds_fresh_state() {
let main = ScriptPolicies::new(vec![AnyScriptPolicy::new(Quota { allowed: 1 })]);
let view = main.clone();
let subagent = main.for_agent();
assert_eq!(main.check(&check("a")).await, ScriptDecision::Allow);
assert_eq!(main.check(&check("b")).await, refuse("over quota"));
assert!(
matches!(view.check(&check("c")).await, ScriptDecision::Refuse(_)),
"a view of the main agent's registry shares its state"
);
assert_eq!(
subagent.check(&check("d")).await,
ScriptDecision::Allow,
"the subagent's state is its own"
);
}
#[tokio::test]
async fn the_strictest_decision_wins() {
let order = [
ScriptDecision::Pass,
ScriptDecision::Allow,
ask("first question"),
refuse("first refusal"),
];
for (weak, strong) in order
.iter()
.enumerate()
.flat_map(|(i, weak)| order[i + 1..].iter().map(move |strong| (weak, strong)))
{
for pair in [[weak, strong], [strong, weak]] {
let policies = policies(pair.into_iter().cloned());
assert_eq!(&policies.check(&check("a")).await, strong);
}
}
assert_eq!(
policies([ScriptDecision::Allow, ScriptDecision::Pass])
.check(&check("b"))
.await,
ScriptDecision::Allow
);
}
#[tokio::test]
async fn the_first_of_equally_strict_decisions_in_registration_order_stands() {
let policies = policies([
ScriptDecision::Allow,
ask("first question"),
ask("second question"),
refuse("first refusal"),
refuse("second refusal"),
]);
assert_eq!(policies.check(&check("a")).await, refuse("first refusal"));
let asking = super::ScriptPolicies::new(vec![
AnyScriptPolicy::new(Always(ask("first question"))),
AnyScriptPolicy::new(Always(ask("second question"))),
]);
assert_eq!(asking.check(&check("b")).await, ask("first question"));
assert!(ScriptPolicies::default().is_empty());
assert_eq!(
ScriptPolicies::default().check(&check("c")).await,
ScriptDecision::Pass
);
}
}