Skip to main content

aither_core/llm/tool/
approval.rs

1//! Asking the embedder whether an action may go ahead.
2//!
3//! A tool that is about to do something its embedder must approve first,
4//! such as running a command outside the sandbox, builds an
5//! [`ApprovalRequest`] and awaits [`ToolContext::approve`](super::ToolContext::approve).
6//! The request reaches the [`Approver`] the dispatcher attached with
7//! [`ToolContext::with_approver`](super::ToolContext::with_approver), so the
8//! tool needs no agent loop: a host that builds a [`ToolContext`](super::ToolContext)
9//! itself attaches its own approver the same way the loop does.
10//!
11//! ```
12//! use aither_core::llm::{
13//!     Approval, ApprovalKind, ApprovalRequest, Approver, ApproverFailure, AnyApprover,
14//!     ToolContext,
15//! };
16//!
17//! struct DenyAll;
18//!
19//! impl Approver for DenyAll {
20//!     async fn approve(&self, request: ApprovalRequest) -> Result<Approval, ApproverFailure> {
21//!         Ok(Approval::Denied {
22//!             reason: format!("`{}` is not allowed here", request.subject()),
23//!         })
24//!     }
25//! }
26//!
27//! # tokio_test::block_on(async {
28//! let cx = ToolContext::new().with_approver(AnyApprover::new(DenyAll));
29//! let request = ApprovalRequest::new(ApprovalKind::new("unsandboxed"), "rm -rf target");
30//! let approval = cx.approve(request).await.unwrap();
31//! assert!(!approval.is_approved());
32//! # });
33//! ```
34
35use alloc::borrow::Cow;
36use alloc::boxed::Box;
37use alloc::string::String;
38use alloc::sync::Arc;
39use core::fmt::{self, Debug, Display};
40use core::future::Future;
41use core::pin::Pin;
42
43use super::CallIdentity;
44
45/// What kind of action a request asks about, named by whoever builds the
46/// request.
47///
48/// An approver groups and remembers decisions by it: May records its
49/// approvals per escalation mode (sandboxed, unsafe, SSH, publish), the
50/// Claude Agent SDK hands `canUseTool` the tool name, and an ACP permission
51/// request carries the tool call's kind.
52#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
53#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
54#[cfg_attr(feature = "serde", serde(transparent))]
55pub struct ApprovalKind(Cow<'static, str>);
56
57impl ApprovalKind {
58    /// A kind with the given name.
59    #[must_use]
60    pub fn new(name: impl Into<Cow<'static, str>>) -> Self {
61        Self(name.into())
62    }
63
64    /// The kind's name.
65    #[must_use]
66    pub fn as_str(&self) -> &str {
67        &self.0
68    }
69}
70
71impl Display for ApprovalKind {
72    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73        f.write_str(&self.0)
74    }
75}
76
77/// One action awaiting approval.
78#[derive(Debug, Clone, PartialEq, Eq)]
79pub struct ApprovalRequest {
80    kind: ApprovalKind,
81    subject: String,
82    reason: Option<String>,
83    call: Option<CallIdentity>,
84}
85
86impl ApprovalRequest {
87    /// A request to approve `subject`, an action of `kind`.
88    ///
89    /// `subject` is exactly what would go ahead, as the person deciding
90    /// should see it: the script to run, the text to publish, a tool call's
91    /// arguments.
92    #[must_use]
93    pub fn new(kind: ApprovalKind, subject: impl Into<String>) -> Self {
94        Self {
95            kind,
96            subject: subject.into(),
97            reason: None,
98            call: None,
99        }
100    }
101
102    /// Says why the action needs approval, such as the rule that stopped it
103    /// (the `decisionReason` the Claude Agent SDK hands `canUseTool`).
104    #[must_use]
105    pub fn with_reason(mut self, reason: impl Into<String>) -> Self {
106        self.reason = Some(reason.into());
107        self
108    }
109
110    /// Attributes the request to the tool call that raised it.
111    ///
112    /// [`ToolContext::approve`](super::ToolContext::approve) attaches its
113    /// call's identity itself; this is for a request raised outside a tool
114    /// call's context, such as one the agent loop raises before the call
115    /// runs.
116    #[must_use]
117    pub fn with_call(mut self, call: CallIdentity) -> Self {
118        self.call = Some(call);
119        self
120    }
121
122    /// The kind of action asked about.
123    #[must_use]
124    pub const fn kind(&self) -> &ApprovalKind {
125        &self.kind
126    }
127
128    /// The action that would go ahead.
129    #[must_use]
130    pub fn subject(&self) -> &str {
131        &self.subject
132    }
133
134    /// Why the action needs approval, when the requester said.
135    #[must_use]
136    pub fn reason(&self) -> Option<&str> {
137        self.reason.as_deref()
138    }
139
140    /// The tool call, and through it the agent, that raised the request.
141    ///
142    /// An approver attributes the request by it, so a subagent's request can
143    /// be put to the person differently from the main agent's (May labels
144    /// each request with its agent, the Claude Agent SDK passes `toolUseID`
145    /// and `agentID`). `None` for a request raised outside any call, such as
146    /// a host running a command with no agent loop.
147    #[must_use]
148    pub const fn call(&self) -> Option<&CallIdentity> {
149        self.call.as_ref()
150    }
151}
152
153/// An approver's answer.
154#[derive(Debug, Clone, PartialEq, Eq)]
155pub enum Approval {
156    /// The action may go ahead.
157    Approved,
158    /// The action must not go ahead.
159    Denied {
160        /// Why, worded for the model, which reads it in place of the action's
161        /// result.
162        reason: String,
163    },
164}
165
166impl Approval {
167    /// Whether the action may go ahead.
168    #[must_use]
169    pub const fn is_approved(&self) -> bool {
170        matches!(self, Self::Approved)
171    }
172}
173
174/// Decides approval requests for an embedder.
175///
176/// It may answer at once from a policy or a remembered decision, or wait for
177/// a person. Dropping the returned future abandons the request: that is how
178/// a cancelled call withdraws its question.
179pub trait Approver: Send + Sync + 'static {
180    /// The answer to `request`.
181    ///
182    /// # Errors
183    ///
184    /// [`ApproverFailure`] when the approver could not decide, such as when
185    /// the store it records requests in fails. A failure is not a denial:
186    /// the caller sees it as [`ApprovalError::Failed`].
187    fn approve(
188        &self,
189        request: ApprovalRequest,
190    ) -> impl Future<Output = Result<Approval, ApproverFailure>> + Send;
191}
192
193/// An [`Approver`] that could not decide, carrying its own error as the
194/// [source](core::error::Error::source).
195#[derive(Debug, thiserror::Error)]
196#[error("the approver could not decide")]
197pub struct ApproverFailure(#[source] Box<dyn core::error::Error + Send + Sync + 'static>);
198
199impl ApproverFailure {
200    /// A failure caused by `error`.
201    #[must_use]
202    pub fn new(error: impl core::error::Error + Send + Sync + 'static) -> Self {
203        Self(Box::new(error))
204    }
205}
206
207type ApproveFuture<'a> =
208    Pin<Box<dyn Future<Output = Result<Approval, ApproverFailure>> + Send + 'a>>;
209
210/// Object-safe twin of [`Approver`], so [`AnyApprover`] can hold any approver.
211trait ApproverImpl: Send + Sync {
212    fn approve(&self, request: ApprovalRequest) -> ApproveFuture<'_>;
213}
214
215impl<A: Approver> ApproverImpl for A {
216    fn approve(&self, request: ApprovalRequest) -> ApproveFuture<'_> {
217        Box::pin(Approver::approve(self, request))
218    }
219}
220
221/// Any [`Approver`], shared: every call a dispatcher runs carries a clone of
222/// the same approver.
223#[derive(Clone)]
224pub struct AnyApprover(Arc<dyn ApproverImpl>);
225
226impl AnyApprover {
227    /// Wraps `approver`.
228    #[must_use]
229    pub fn new(approver: impl Approver) -> Self {
230        Self(Arc::new(approver))
231    }
232}
233
234impl Approver for AnyApprover {
235    fn approve(
236        &self,
237        request: ApprovalRequest,
238    ) -> impl Future<Output = Result<Approval, ApproverFailure>> + Send {
239        self.0.approve(request)
240    }
241}
242
243impl Debug for AnyApprover {
244    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
245        f.debug_struct("AnyApprover").finish_non_exhaustive()
246    }
247}
248
249/// Why [`ToolContext::approve`](super::ToolContext::approve) produced no
250/// answer.
251#[derive(Debug, thiserror::Error)]
252pub enum ApprovalError {
253    /// The call's dispatcher attached no approver, so nobody can approve the
254    /// action; it must not go ahead.
255    #[error(
256        "approval for `{kind}` was requested, but this tool call's context has no approver \
257         (its dispatcher did not call `ToolContext::with_approver`)"
258    )]
259    NoApprover {
260        /// The kind of the request nobody could answer.
261        kind: ApprovalKind,
262    },
263    /// The approver could not decide; the action must not go ahead.
264    #[error("the approver failed on the request for `{kind}`")]
265    Failed {
266        /// The kind of the request the approver failed on.
267        kind: ApprovalKind,
268        /// What went wrong.
269        #[source]
270        failure: ApproverFailure,
271    },
272    /// The call was cancelled before the approver answered.
273    #[error("the tool call was cancelled while waiting for approval")]
274    Cancelled,
275}