Skip to main content

strands/interventions/
actions.rs

1//! The actions an intervention handler returns.
2
3use std::fmt;
4
5use crate::error::BoxError;
6use crate::hooks::HookOutput;
7use crate::models::is_js_whitespace;
8use crate::types::JsonValue;
9
10crate::callback::callback! {
11    /// Decides whether a human's response approves a [`Confirm`].
12    pub struct Evaluate(Fn(&JsonValue) -> bool);
13}
14
15/// The in-place mutation a [`Transform`] applies to the event.
16pub(crate) type TransformFn<E> = Box<dyn FnOnce(&mut E) -> Result<(), BoxError> + Send>;
17
18/// The default approval test of a [`Confirm`]: `true`, or `"y"`/`"yes"`
19/// (case-insensitive, trimmed of Unicode whitespace other than `U+0085`, plus `U+FEFF`).
20///
21/// ```
22/// use serde_json::json;
23/// use strands::interventions::default_evaluate;
24///
25/// assert!(default_evaluate(&json!(true)));
26/// assert!(default_evaluate(&json!(" YES ")));
27/// assert!(!default_evaluate(&json!("no")));
28/// ```
29#[must_use]
30pub fn default_evaluate(response: &JsonValue) -> bool {
31    match response {
32        JsonValue::Bool(approved) => *approved,
33        JsonValue::String(text) => matches!(text.to_lowercase().trim_matches(is_js_whitespace), "y" | "yes"),
34        _ => false,
35    }
36}
37
38/// Lets the operation continue unchanged (`Proceed`).
39#[derive(Debug, Clone, Default, PartialEq, Eq)]
40#[non_exhaustive]
41pub struct Proceed {
42    /// Debugging metadata; not shown to the model.
43    pub reason: Option<String>,
44}
45
46impl Proceed {
47    /// A proceed without a reason.
48    #[must_use]
49    pub fn new() -> Self {
50        Self::default()
51    }
52
53    /// Sets the debugging reason.
54    #[must_use]
55    pub fn with_reason(mut self, reason: impl Into<String>) -> Self {
56        self.reason = Some(reason.into());
57        self
58    }
59}
60
61/// Blocks the operation (`Deny`): on `Before*` events the cancel message is `DENIED: <reason>`,
62/// which the model sees.
63#[derive(Debug, Clone, PartialEq, Eq)]
64#[non_exhaustive]
65pub struct Deny {
66    /// Why the operation was blocked; shown to the model.
67    pub reason: String,
68}
69
70impl Deny {
71    /// A denial with the reason shown to the model.
72    pub fn new(reason: impl Into<String>) -> Self {
73        Self { reason: reason.into() }
74    }
75}
76
77/// Steers the model with feedback (`Guide`).
78///
79/// On `before_tool_call` and `before_invocation` the event is cancelled with `GUIDANCE: ..`; on
80/// `before_model_call` the feedback is appended as a user message for this call; on
81/// `after_model_call` the response is discarded and the call retried with the feedback appended.
82/// Feedback from several handlers accumulates as `[<handler>] <feedback>` lines.
83#[derive(Debug, Clone, PartialEq, Eq)]
84#[non_exhaustive]
85pub struct Guide {
86    /// The guidance shown to the model.
87    pub feedback: String,
88    /// Debugging metadata; not shown to the model.
89    pub reason: Option<String>,
90}
91
92impl Guide {
93    /// Guidance with the feedback shown to the model.
94    pub fn new(feedback: impl Into<String>) -> Self {
95        Self {
96            feedback: feedback.into(),
97            reason: None,
98        }
99    }
100
101    /// Sets the debugging reason.
102    #[must_use]
103    pub fn with_reason(mut self, reason: impl Into<String>) -> Self {
104        self.reason = Some(reason.into());
105        self
106    }
107}
108
109/// Asks a human to approve the tool call (`Confirm`); only `before_tool_call` supports it.
110///
111/// Without a [`response`](Self::response) the agent stops with an interrupt named after the
112/// handler, whose reason is the prompt, and the answer arrives on resume. With one, the interrupt
113/// is recorded with that answer and the agent never pauses. The answer goes through
114/// [`evaluate`](Self::evaluate) ([`default_evaluate`] when unset); a rejection cancels the call
115/// with `CONFIRMATION_FAILED: <prompt>`.
116#[derive(Clone)]
117#[non_exhaustive]
118pub struct Confirm {
119    /// The question for the human; not shown to the model.
120    pub prompt: String,
121    /// Debugging metadata; not shown to the model.
122    pub reason: Option<String>,
123    /// An answer collected by the handler itself, so the agent does not pause.
124    pub response: Option<JsonValue>,
125    /// The approval test; [`default_evaluate`] when `None`.
126    pub evaluate: Option<Evaluate>,
127}
128
129impl Confirm {
130    /// A confirmation with the default approval test.
131    pub fn new(prompt: impl Into<String>) -> Self {
132        Self {
133            prompt: prompt.into(),
134            reason: None,
135            response: None,
136            evaluate: None,
137        }
138    }
139
140    /// Sets the debugging reason.
141    #[must_use]
142    pub fn with_reason(mut self, reason: impl Into<String>) -> Self {
143        self.reason = Some(reason.into());
144        self
145    }
146
147    /// Supplies the human's answer up front (inline mode).
148    #[must_use]
149    pub fn with_response(mut self, response: impl Into<JsonValue>) -> Self {
150        self.response = Some(response.into());
151        self
152    }
153
154    /// Replaces the approval test.
155    #[must_use]
156    pub fn with_evaluate(mut self, evaluate: impl Fn(&JsonValue) -> bool + Send + Sync + 'static) -> Self {
157        self.evaluate = Some(Evaluate::new(evaluate));
158        self
159    }
160
161    pub(crate) fn approves(&self, response: &JsonValue) -> bool {
162        match &self.evaluate {
163            Some(evaluate) => evaluate(response),
164            None => default_evaluate(response),
165        }
166    }
167}
168
169impl fmt::Debug for Confirm {
170    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
171        f.debug_struct("Confirm")
172            .field("prompt", &self.prompt)
173            .field("reason", &self.reason)
174            .field("response", &self.response)
175            .field("evaluate", &self.evaluate.as_ref().map(|_| ".."))
176            .finish()
177    }
178}
179
180/// Mutates the event in place before execution continues (`Transform`); later handlers see the
181/// change. An error from the mutation is handled by the handler's
182/// [`on_error`](super::InterventionHandler::on_error) policy.
183#[non_exhaustive]
184pub struct Transform<E> {
185    pub(crate) apply: TransformFn<E>,
186    /// Debugging metadata; not shown to the model.
187    pub reason: Option<String>,
188}
189
190impl<E> Transform<E> {
191    /// A transform from a closure returning `()` or a `Result`.
192    pub fn new<R: HookOutput>(apply: impl FnOnce(&mut E) -> R + Send + 'static) -> Self {
193        Self {
194            apply: Box::new(move |event| apply(event).into_hook_result()),
195            reason: None,
196        }
197    }
198
199    /// Sets the debugging reason.
200    #[must_use]
201    pub fn with_reason(mut self, reason: impl Into<String>) -> Self {
202        self.reason = Some(reason.into());
203        self
204    }
205}
206
207impl<E> fmt::Debug for Transform<E> {
208    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
209        f.debug_struct("Transform")
210            .field("reason", &self.reason)
211            .finish_non_exhaustive()
212    }
213}
214
215/// What a handler decides at a lifecycle point (`InterventionAction`), for the event `E` it was
216/// given.
217///
218/// | Action      | before_invocation | before_tool_call | before_model_call | after_tool_call | after_model_call |
219/// |-------------|-------------------|------------------|-------------------|-----------------|------------------|
220/// | `Proceed`   | -                 | -                | -                 | -               | -                |
221/// | `Deny`      | cancel            | cancel           | cancel            | no effect       | no effect        |
222/// | `Guide`     | cancel            | cancel           | inject            | no effect       | inject and retry |
223/// | `Confirm`   | no effect         | confirm          | no effect         | no effect       | no effect        |
224/// | `Transform` | apply             | apply            | apply             | apply           | apply            |
225///
226/// A cancel by `Deny` (or a rejected `Confirm`) skips the remaining handlers; an action with no
227/// effect logs a warning.
228///
229/// ```
230/// use strands::hooks::BeforeToolCallEvent;
231/// use strands::interventions::InterventionAction;
232///
233/// let deny = InterventionAction::<BeforeToolCallEvent>::deny("not authorized");
234/// assert_eq!(deny.action_type(), "deny");
235/// let redact = InterventionAction::transform(|event: &mut BeforeToolCallEvent| {
236///     event.tool_use_mut().input = serde_json::json!({});
237/// });
238/// assert_eq!(redact.action_type(), "transform");
239/// ```
240#[non_exhaustive]
241pub enum InterventionAction<E> {
242    /// Continue unchanged.
243    Proceed(Proceed),
244    /// Block the operation.
245    Deny(Deny),
246    /// Steer the model with feedback.
247    Guide(Guide),
248    /// Ask a human first.
249    Confirm(Confirm),
250    /// Mutate the event.
251    Transform(Transform<E>),
252}
253
254impl<E> InterventionAction<E> {
255    /// Continue unchanged (`proceed`).
256    #[must_use]
257    pub fn proceed() -> Self {
258        Self::Proceed(Proceed::new())
259    }
260
261    /// Block the operation (`deny`); the reason is shown to the model.
262    pub fn deny(reason: impl Into<String>) -> Self {
263        Self::Deny(Deny::new(reason))
264    }
265
266    /// Steer the model (`guide`); the feedback is shown to the model.
267    pub fn guide(feedback: impl Into<String>) -> Self {
268        Self::Guide(Guide::new(feedback))
269    }
270
271    /// Ask a human (`confirm`), with the default approval test and no pre-collected answer. Build
272    /// a [`Confirm`] for the options.
273    pub fn confirm(prompt: impl Into<String>) -> Self {
274        Self::Confirm(Confirm::new(prompt))
275    }
276
277    /// Mutate the event (`transform`), with a closure returning `()` or a `Result`.
278    pub fn transform<R: HookOutput>(apply: impl FnOnce(&mut E) -> R + Send + 'static) -> Self {
279        Self::Transform(Transform::new(apply))
280    }
281
282    /// The action's `type` tag: `proceed`, `deny`, `guide`, `confirm` or `transform`.
283    #[must_use]
284    pub fn action_type(&self) -> &'static str {
285        match self {
286            Self::Proceed(_) => "proceed",
287            Self::Deny(_) => "deny",
288            Self::Guide(_) => "guide",
289            Self::Confirm(_) => "confirm",
290            Self::Transform(_) => "transform",
291        }
292    }
293}
294
295impl<E> fmt::Debug for InterventionAction<E> {
296    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
297        match self {
298            Self::Proceed(action) => action.fmt(f),
299            Self::Deny(action) => action.fmt(f),
300            Self::Guide(action) => action.fmt(f),
301            Self::Confirm(action) => action.fmt(f),
302            Self::Transform(action) => action.fmt(f),
303        }
304    }
305}
306
307impl<E> From<Proceed> for InterventionAction<E> {
308    fn from(action: Proceed) -> Self {
309        Self::Proceed(action)
310    }
311}
312
313impl<E> From<Deny> for InterventionAction<E> {
314    fn from(action: Deny) -> Self {
315        Self::Deny(action)
316    }
317}
318
319impl<E> From<Guide> for InterventionAction<E> {
320    fn from(action: Guide) -> Self {
321        Self::Guide(action)
322    }
323}
324
325impl<E> From<Confirm> for InterventionAction<E> {
326    fn from(action: Confirm) -> Self {
327        Self::Confirm(action)
328    }
329}
330
331impl<E> From<Transform<E>> for InterventionAction<E> {
332    fn from(action: Transform<E>) -> Self {
333        Self::Transform(action)
334    }
335}