1use std::fmt;
24use std::future::Future;
25use std::path::PathBuf;
26use std::pin::Pin;
27use std::sync::Arc;
28
29use aither_core::llm::tool::{ApprovalRequest, CallIdentity};
30use schemars::JsonSchema;
31use serde::{Deserialize, Serialize};
32
33use crate::container::ContainerPath;
34use crate::interpreter::Interpreter;
35use crate::shell_syntax::{ShellParseError, ShellScript};
36use crate::terminal::DirectoryResetReason;
37
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub enum ScriptOrigin {
41 Foreground,
43 Background,
45 Run,
48}
49
50#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
53#[serde(rename_all = "snake_case")]
54#[allow(missing_docs, reason = "the schema's descriptions are the embedder's")]
55pub enum SandboxMode {
56 #[default]
58 Sandboxed,
59 Unsandboxed,
61}
62
63impl SandboxMode {
64 #[must_use]
66 pub const fn description(self) -> &'static str {
67 match self {
68 Self::Sandboxed => "sandboxed",
69 Self::Unsandboxed => "unsandboxed (no sandbox, full access)",
70 }
71 }
72}
73
74#[derive(Debug, Clone, PartialEq, Eq)]
77pub enum ScriptDir {
78 Host(PathBuf),
80 Container {
82 inside: ContainerPath,
84 host: PathBuf,
87 },
88 Remote {
91 server: String,
93 },
94}
95
96impl ScriptDir {
97 #[must_use]
100 pub fn host(&self) -> Option<&std::path::Path> {
101 match self {
102 Self::Host(dir) | Self::Container { host: dir, .. } => Some(dir),
103 Self::Remote { .. } => None,
104 }
105 }
106}
107
108#[derive(Debug, Clone, Copy)]
111pub struct ScriptCheck<'a> {
112 pub task_id: &'a str,
115 pub script: &'a str,
117 pub interpreter: Interpreter,
119 pub shell: Option<Result<&'a ShellScript, &'a ShellParseError>>,
122 pub origin: ScriptOrigin,
124 pub sandbox: SandboxMode,
126 pub location: Option<&'a str>,
129 pub start: &'a ScriptDir,
135 pub call: Option<&'a CallIdentity>,
138}
139
140#[derive(Debug, Clone, Copy, PartialEq, Eq)]
142pub enum ScriptOutcome {
143 NotRun,
146 Failed,
148 Exited {
150 code: i32,
152 },
153}
154
155#[derive(Debug, Clone, Copy, PartialEq, Eq)]
158pub enum Carry {
159 Moved,
162 Reset(DirectoryResetReason),
165 Unchanged,
167 NotCarried,
170}
171
172#[derive(Debug, Clone, Copy, PartialEq, Eq)]
174pub struct ScriptEnd<'a> {
175 pub task_id: &'a str,
177 pub outcome: ScriptOutcome,
179 pub end: &'a ScriptDir,
184 pub carry: Carry,
186}
187
188#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
194#[error("{text}")]
195pub struct ScriptRefusal {
196 text: String,
197}
198
199impl ScriptRefusal {
200 #[must_use]
202 pub fn new(text: impl Into<String>) -> Self {
203 Self { text: text.into() }
204 }
205
206 #[must_use]
208 pub fn text(&self) -> &str {
209 &self.text
210 }
211}
212
213#[derive(Debug, Clone, PartialEq, Eq)]
223pub enum ScriptDecision {
224 Pass,
226 Allow,
229 Ask(ApprovalRequest),
231 Refuse(ScriptRefusal),
233}
234
235impl ScriptDecision {
236 const fn strictness(&self) -> u8 {
237 match self {
238 Self::Pass => 0,
239 Self::Allow => 1,
240 Self::Ask(_) => 2,
241 Self::Refuse(_) => 3,
242 }
243 }
244
245 #[must_use]
249 pub fn strictest(decisions: impl IntoIterator<Item = Self>) -> Self {
250 decisions
251 .into_iter()
252 .fold(Self::Pass, |strictest, decision| {
253 if decision.strictness() > strictest.strictness() {
254 decision
255 } else {
256 strictest
257 }
258 })
259 }
260}
261
262pub trait ScriptPolicy: Send + Sync + 'static {
274 type State: Default + Send + Sync + 'static;
276
277 fn check(
279 &self,
280 script: &ScriptCheck<'_>,
281 state: &Self::State,
282 ) -> impl Future<Output = ScriptDecision> + Send;
283
284 fn ended(&self, end: &ScriptEnd<'_>, state: &Self::State) -> impl Future<Output = ()> + Send {
290 let _ = (end, state);
291 std::future::ready(())
292 }
293}
294
295trait ScriptPolicyImpl: Send + Sync {
298 fn bind(self: Arc<Self>) -> Arc<dyn BoundPolicyImpl>;
299}
300
301impl<T: ScriptPolicy> ScriptPolicyImpl for T {
302 fn bind(self: Arc<Self>) -> Arc<dyn BoundPolicyImpl> {
303 Arc::new(Bound {
304 policy: self,
305 state: T::State::default(),
306 })
307 }
308}
309
310struct Bound<T: ScriptPolicy> {
312 policy: Arc<T>,
313 state: T::State,
314}
315
316trait BoundPolicyImpl: Send + Sync {
317 fn check<'a>(
318 &'a self,
319 script: &'a ScriptCheck<'a>,
320 ) -> Pin<Box<dyn Future<Output = ScriptDecision> + Send + 'a>>;
321
322 fn ended<'a>(&'a self, end: &'a ScriptEnd<'a>)
323 -> Pin<Box<dyn Future<Output = ()> + Send + 'a>>;
324}
325
326impl<T: ScriptPolicy> BoundPolicyImpl for Bound<T> {
327 fn check<'a>(
328 &'a self,
329 script: &'a ScriptCheck<'a>,
330 ) -> Pin<Box<dyn Future<Output = ScriptDecision> + Send + 'a>> {
331 Box::pin(self.policy.check(script, &self.state))
332 }
333
334 fn ended<'a>(
335 &'a self,
336 end: &'a ScriptEnd<'a>,
337 ) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>> {
338 Box::pin(self.policy.ended(end, &self.state))
339 }
340}
341
342#[derive(Clone)]
344pub struct AnyScriptPolicy(Arc<dyn ScriptPolicyImpl>);
345
346impl AnyScriptPolicy {
347 #[must_use]
349 pub fn new(policy: impl ScriptPolicy) -> Self {
350 Self(Arc::new(policy))
351 }
352}
353
354impl fmt::Debug for AnyScriptPolicy {
355 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
356 f.write_str("AnyScriptPolicy")
357 }
358}
359
360#[derive(Clone, Default)]
363pub struct ScriptPolicies {
364 policies: Arc<[AnyScriptPolicy]>,
365 bound: Arc<[Arc<dyn BoundPolicyImpl>]>,
366}
367
368impl ScriptPolicies {
369 #[must_use]
371 pub fn new(policies: Vec<AnyScriptPolicy>) -> Self {
372 let policies: Arc<[AnyScriptPolicy]> = policies.into();
373 Self {
374 bound: Self::bind(&policies),
375 policies,
376 }
377 }
378
379 fn bind(policies: &[AnyScriptPolicy]) -> Arc<[Arc<dyn BoundPolicyImpl>]> {
380 policies
381 .iter()
382 .map(|policy| policy.0.clone().bind())
383 .collect()
384 }
385
386 #[must_use]
388 pub fn for_agent(&self) -> Self {
389 Self {
390 policies: self.policies.clone(),
391 bound: Self::bind(&self.policies),
392 }
393 }
394
395 #[must_use]
397 pub fn is_empty(&self) -> bool {
398 self.bound.is_empty()
399 }
400
401 pub async fn check(&self, script: &ScriptCheck<'_>) -> ScriptDecision {
404 let decisions =
405 futures::future::join_all(self.bound.iter().map(|policy| policy.check(script))).await;
406 ScriptDecision::strictest(decisions)
407 }
408
409 pub async fn ended(
412 &self,
413 task_id: &str,
414 outcome: ScriptOutcome,
415 end: &ScriptDir,
416 carry: Carry,
417 ) {
418 if self.is_empty() {
419 return;
420 }
421 let end = ScriptEnd {
422 task_id,
423 outcome,
424 end,
425 carry,
426 };
427 futures::future::join_all(self.bound.iter().map(|policy| policy.ended(&end))).await;
428 }
429}
430
431impl fmt::Debug for ScriptPolicies {
432 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
433 f.debug_struct("ScriptPolicies")
434 .field("policies", &self.policies.len())
435 .finish_non_exhaustive()
436 }
437}
438
439#[cfg(test)]
440mod tests {
441 use std::sync::atomic::{AtomicUsize, Ordering};
442
443 use aither_core::llm::tool::ApprovalKind;
444
445 use super::*;
446
447 struct Quota {
449 allowed: usize,
450 }
451
452 impl ScriptPolicy for Quota {
453 type State = AtomicUsize;
454
455 fn check(
456 &self,
457 _script: &ScriptCheck<'_>,
458 state: &AtomicUsize,
459 ) -> impl Future<Output = ScriptDecision> + Send {
460 std::future::ready(if state.fetch_add(1, Ordering::SeqCst) < self.allowed {
461 ScriptDecision::Allow
462 } else {
463 ScriptDecision::Refuse(ScriptRefusal::new("over quota"))
464 })
465 }
466 }
467
468 struct Always(ScriptDecision);
470
471 impl ScriptPolicy for Always {
472 type State = ();
473
474 fn check(
475 &self,
476 _script: &ScriptCheck<'_>,
477 (): &(),
478 ) -> impl Future<Output = ScriptDecision> + Send {
479 std::future::ready(self.0.clone())
480 }
481 }
482
483 fn refuse(text: &str) -> ScriptDecision {
484 ScriptDecision::Refuse(ScriptRefusal::new(text))
485 }
486
487 fn ask(subject: &str) -> ScriptDecision {
488 ScriptDecision::Ask(ApprovalRequest::new(ApprovalKind::new("test"), subject))
489 }
490
491 fn check(task_id: &str) -> ScriptCheck<'_> {
492 static START: std::sync::LazyLock<ScriptDir> =
493 std::sync::LazyLock::new(|| ScriptDir::Host(PathBuf::from("/")));
494 ScriptCheck {
495 task_id,
496 script: "true",
497 interpreter: Interpreter::Shell,
498 shell: None,
499 origin: ScriptOrigin::Foreground,
500 sandbox: SandboxMode::Sandboxed,
501 location: None,
502 start: &START,
503 call: None,
504 }
505 }
506
507 fn policies(decisions: impl IntoIterator<Item = ScriptDecision>) -> ScriptPolicies {
508 ScriptPolicies::new(
509 decisions
510 .into_iter()
511 .map(|decision| AnyScriptPolicy::new(Always(decision)))
512 .collect(),
513 )
514 }
515
516 #[tokio::test]
517 async fn each_agent_binds_fresh_state() {
518 let main = ScriptPolicies::new(vec![AnyScriptPolicy::new(Quota { allowed: 1 })]);
519 let view = main.clone();
520 let subagent = main.for_agent();
521 assert_eq!(main.check(&check("a")).await, ScriptDecision::Allow);
522 assert_eq!(main.check(&check("b")).await, refuse("over quota"));
523 assert!(
524 matches!(view.check(&check("c")).await, ScriptDecision::Refuse(_)),
525 "a view of the main agent's registry shares its state"
526 );
527 assert_eq!(
528 subagent.check(&check("d")).await,
529 ScriptDecision::Allow,
530 "the subagent's state is its own"
531 );
532 }
533
534 #[tokio::test]
535 async fn the_strictest_decision_wins() {
536 let order = [
537 ScriptDecision::Pass,
538 ScriptDecision::Allow,
539 ask("first question"),
540 refuse("first refusal"),
541 ];
542 for (weak, strong) in order
544 .iter()
545 .enumerate()
546 .flat_map(|(i, weak)| order[i + 1..].iter().map(move |strong| (weak, strong)))
547 {
548 for pair in [[weak, strong], [strong, weak]] {
549 let policies = policies(pair.into_iter().cloned());
550 assert_eq!(&policies.check(&check("a")).await, strong);
551 }
552 }
553 assert_eq!(
554 policies([ScriptDecision::Allow, ScriptDecision::Pass])
555 .check(&check("b"))
556 .await,
557 ScriptDecision::Allow
558 );
559 }
560
561 #[tokio::test]
562 async fn the_first_of_equally_strict_decisions_in_registration_order_stands() {
563 let policies = policies([
564 ScriptDecision::Allow,
565 ask("first question"),
566 ask("second question"),
567 refuse("first refusal"),
568 refuse("second refusal"),
569 ]);
570 assert_eq!(policies.check(&check("a")).await, refuse("first refusal"));
571 let asking = super::ScriptPolicies::new(vec![
572 AnyScriptPolicy::new(Always(ask("first question"))),
573 AnyScriptPolicy::new(Always(ask("second question"))),
574 ]);
575 assert_eq!(asking.check(&check("b")).await, ask("first question"));
576 assert!(ScriptPolicies::default().is_empty());
577 assert_eq!(
578 ScriptPolicies::default().check(&check("c")).await,
579 ScriptDecision::Pass
580 );
581 }
582}