Skip to main content

strands/interventions/
handler.rs

1//! The [`InterventionHandler`] trait.
2
3use std::sync::Arc;
4
5use async_trait::async_trait;
6
7use super::actions::InterventionAction;
8use crate::error::BoxError;
9use crate::hooks::{
10    AfterModelCallEvent, AfterToolCallEvent, BeforeInvocationEvent, BeforeModelCallEvent, BeforeToolCallEvent,
11};
12
13/// What a lifecycle method returns: the action for its event, or an error that the handler's
14/// [`OnError`] policy resolves.
15pub type InterventionResult<E> = Result<InterventionAction<E>, BoxError>;
16
17/// What happens when a handler fails during evaluation (`OnError`).
18///
19/// An interrupt raised by a handler is never a failure: it always stops the agent for human input.
20#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
21#[non_exhaustive]
22pub enum OnError {
23    /// Fail the invocation with the error (the default and safest: a broken policy check blocks
24    /// execution).
25    #[default]
26    Throw,
27    /// Continue as if the handler returned `Proceed`. This is fail-open: a broken handler stops
28    /// enforcing its policy.
29    Proceed,
30    /// Treat the failure as a `Deny` with the reason `Handler threw: <error>` (fail-closed).
31    Deny,
32}
33
34/// A policy evaluated at the agent's lifecycle points (`InterventionHandler`).
35///
36/// Override the methods you care about; the others return `Proceed`. Handlers run in registration
37/// order, after the agent's other hooks on `Before*` events
38/// ([`HookOrder::INTERVENTION_INPUT`](crate::HookOrder::INTERVENTION_INPUT)) and before them on
39/// `After*` events ([`HookOrder::INTERVENTION_OUTPUT`](crate::HookOrder::INTERVENTION_OUTPUT)).
40/// Tool calls made with [`ToolAgent::call_tool`](crate::ToolAgent::call_tool) are gated too.
41/// Methods on events that borrow the agent name the lifetime, as in
42/// `async fn before_model_call<'a>(&self, event: &mut BeforeModelCallEvent<'a>) -> InterventionResult<BeforeModelCallEvent<'a>>`.
43///
44/// ```
45/// use strands::hooks::BeforeToolCallEvent;
46/// use strands::interventions::{InterventionAction, InterventionHandler, InterventionResult};
47///
48/// struct NoShell;
49///
50/// #[strands::async_trait]
51/// impl InterventionHandler for NoShell {
52///     fn name(&self) -> &str {
53///         "no-shell"
54///     }
55///
56///     async fn before_tool_call(&self, event: &mut BeforeToolCallEvent) -> InterventionResult<BeforeToolCallEvent> {
57///         if event.tool_use().name == "shell" {
58///             return Ok(InterventionAction::deny("shell is disabled"));
59///         }
60///         Ok(InterventionAction::proceed())
61///     }
62/// }
63///
64/// let agent = strands::Agent::builder()
65///     .model(strands::testing::MockModel::new())
66///     .interventions([NoShell])
67///     .printer(false)
68///     .build()?;
69/// # let _ = agent;
70/// # Ok::<(), strands::Error>(())
71/// ```
72#[async_trait]
73pub trait InterventionHandler: Send + Sync + 'static {
74    /// The handler's name, unique among an agent's handlers; also the name of the interrupt a
75    /// `Confirm` raises.
76    fn name(&self) -> &str;
77
78    /// What to do when this handler fails. Defaults to [`OnError::Throw`].
79    fn on_error(&self) -> OnError {
80        OnError::Throw
81    }
82
83    /// Evaluates the invocation before it starts.
84    ///
85    /// # Errors
86    ///
87    /// Any error is resolved by [`on_error`](Self::on_error).
88    async fn before_invocation<'a>(
89        &self,
90        _event: &mut BeforeInvocationEvent<'a>,
91    ) -> InterventionResult<BeforeInvocationEvent<'a>> {
92        Ok(InterventionAction::proceed())
93    }
94
95    /// Evaluates a tool call before it runs.
96    ///
97    /// # Errors
98    ///
99    /// Any error is resolved by [`on_error`](Self::on_error).
100    async fn before_tool_call(&self, _event: &mut BeforeToolCallEvent) -> InterventionResult<BeforeToolCallEvent> {
101        Ok(InterventionAction::proceed())
102    }
103
104    /// Evaluates a tool result.
105    ///
106    /// # Errors
107    ///
108    /// Any error is resolved by [`on_error`](Self::on_error).
109    async fn after_tool_call(&self, _event: &mut AfterToolCallEvent) -> InterventionResult<AfterToolCallEvent> {
110        Ok(InterventionAction::proceed())
111    }
112
113    /// Evaluates a model call before it is made.
114    ///
115    /// # Errors
116    ///
117    /// Any error is resolved by [`on_error`](Self::on_error).
118    async fn before_model_call<'a>(
119        &self,
120        _event: &mut BeforeModelCallEvent<'a>,
121    ) -> InterventionResult<BeforeModelCallEvent<'a>> {
122        Ok(InterventionAction::proceed())
123    }
124
125    /// Evaluates a model response.
126    ///
127    /// # Errors
128    ///
129    /// Any error is resolved by [`on_error`](Self::on_error).
130    async fn after_model_call<'a>(
131        &self,
132        _event: &mut AfterModelCallEvent<'a>,
133    ) -> InterventionResult<AfterModelCallEvent<'a>> {
134        Ok(InterventionAction::proceed())
135    }
136}
137
138/// A shared handler is a handler, so `Arc<dyn InterventionHandler>` and `Arc<H>` go wherever
139/// handlers do.
140#[async_trait]
141impl<H: InterventionHandler + ?Sized> InterventionHandler for Arc<H> {
142    fn name(&self) -> &str {
143        (**self).name()
144    }
145
146    fn on_error(&self) -> OnError {
147        (**self).on_error()
148    }
149
150    async fn before_invocation<'a>(
151        &self,
152        event: &mut BeforeInvocationEvent<'a>,
153    ) -> InterventionResult<BeforeInvocationEvent<'a>> {
154        (**self).before_invocation(event).await
155    }
156
157    async fn before_tool_call(&self, event: &mut BeforeToolCallEvent) -> InterventionResult<BeforeToolCallEvent> {
158        (**self).before_tool_call(event).await
159    }
160
161    async fn after_tool_call(&self, event: &mut AfterToolCallEvent) -> InterventionResult<AfterToolCallEvent> {
162        (**self).after_tool_call(event).await
163    }
164
165    async fn before_model_call<'a>(
166        &self,
167        event: &mut BeforeModelCallEvent<'a>,
168    ) -> InterventionResult<BeforeModelCallEvent<'a>> {
169        (**self).before_model_call(event).await
170    }
171
172    async fn after_model_call<'a>(
173        &self,
174        event: &mut AfterModelCallEvent<'a>,
175    ) -> InterventionResult<AfterModelCallEvent<'a>> {
176        (**self).after_model_call(event).await
177    }
178}