Skip to main content

strands/vended_interventions/hitl/
mod.rs

1//! Human-in-the-loop approval of tool calls.
2//!
3//! [`HumanInTheLoop`] asks a human before tool calls. By default the agent stops with an
4//! interrupt and the caller resumes it with the answer; give it an [`ask`](HumanInTheLoopConfig::ask)
5//! callback (or [`HumanInTheLoopAsk::Stdio`]) to ask inline instead.
6//!
7//! ```
8//! use strands::Agent;
9//! use strands::testing::MockModel;
10//! use strands::vended_interventions::hitl::{HumanInTheLoop, HumanInTheLoopConfig};
11//!
12//! let hitl = HumanInTheLoop::new(HumanInTheLoopConfig {
13//!     allowed_tools: vec!["read_file".into()],
14//!     ..Default::default()
15//! });
16//! let agent = Agent::builder()
17//!     .model(MockModel::new())
18//!     .interventions([hitl])
19//!     .printer(false)
20//!     .build()?;
21//! # let _ = agent;
22//! # Ok::<(), strands::Error>(())
23//! ```
24
25mod classifier;
26
27use std::collections::HashSet;
28use std::fmt;
29use std::future::Future;
30use std::io::{self, BufRead, Write};
31use std::sync::{Arc, Mutex, PoisonError};
32
33use async_trait::async_trait;
34use futures::future::BoxFuture;
35
36pub use classifier::{ClassifierConfig, ClassifierResult, HumanInTheLoopClassifier, LlmClassifierConfig};
37
38use crate::error::BoxError;
39use crate::hooks::BeforeToolCallEvent;
40use crate::interventions::{
41    Confirm, Evaluate, InterventionAction, InterventionHandler, InterventionResult, default_evaluate,
42};
43use crate::models::is_js_whitespace;
44use crate::state_store::StateStore;
45use crate::types::JsonValue;
46
47/// The app-state key of the tools trusted for the session.
48pub const TRUSTED_TOOLS_KEY: &str = "hitl:trustedTools";
49
50crate::callback::callback! {
51    /// Collects a human's answer inline. The answer is `None` when there is none, which denies the
52    /// call.
53    pub struct AskFn(Fn(String) -> BoxFuture<'static, Result<Option<JsonValue>, BoxError>>);
54}
55
56/// How a [`HumanInTheLoop`] collects answers inline (`ask`).
57#[derive(Clone)]
58#[non_exhaustive]
59pub enum HumanInTheLoopAsk {
60    /// Prompt on the terminal and read a line from stdin (`'stdio'`); concurrent prompts take
61    /// turns.
62    Stdio,
63    /// Ask through your own UI.
64    Callback(AskFn),
65}
66
67impl HumanInTheLoopAsk {
68    /// An inline answer from an async closure.
69    ///
70    /// ```
71    /// use strands::vended_interventions::hitl::HumanInTheLoopAsk;
72    ///
73    /// let ask = HumanInTheLoopAsk::callback(|prompt: String| async move {
74    ///     let _ = prompt;
75    ///     Ok(Some(serde_json::json!("yes")))
76    /// });
77    /// # let _ = ask;
78    /// ```
79    pub fn callback<F, Fut>(ask: F) -> Self
80    where
81        F: Fn(String) -> Fut + Send + Sync + 'static,
82        Fut: Future<Output = Result<Option<JsonValue>, BoxError>> + Send + 'static,
83    {
84        Self::Callback(AskFn::new(move |prompt| Box::pin(ask(prompt))))
85    }
86}
87
88impl fmt::Debug for HumanInTheLoopAsk {
89    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90        match self {
91            Self::Stdio => f.write_str("Stdio"),
92            Self::Callback(_) => f.write_str("Callback(..)"),
93        }
94    }
95}
96
97/// Settings of a [`HumanInTheLoop`] (`HumanInTheLoopConfig`).
98#[derive(Clone, Default, bon::Builder)]
99pub struct HumanInTheLoopConfig {
100    /// Tools that run without approval. `*` allows every tool; a `!` prefix makes a tool always
101    /// require approval, even under `*` or trust. Listed tools skip the classifier.
102    #[builder(default)]
103    pub allowed_tools: Vec<String>,
104    /// Decides which other tool calls need approval. Unset, all of them do.
105    #[builder(into)]
106    pub classifier: Option<ClassifierConfig>,
107    /// A trust answer (`t`/`trust` by default) approves the call and remembers the tool in app
108    /// state for the session. Defaults to `false`. With a classifier, a trusted tool is no longer
109    /// classified.
110    pub enable_trust: Option<bool>,
111    /// Recognizes a trust answer; read only with `enable_trust`. Defaults to `t`/`trust`
112    /// (case-insensitive).
113    #[builder(into)]
114    pub evaluate_trust: Option<Evaluate>,
115    /// Recognizes an approval. Defaults to `true` or `y`/`yes` (case-insensitive).
116    #[builder(into)]
117    pub evaluate: Option<Evaluate>,
118    /// Collects answers inline. Unset, the agent stops with an interrupt and resumes with the
119    /// answer.
120    pub ask: Option<HumanInTheLoopAsk>,
121}
122
123impl fmt::Debug for HumanInTheLoopConfig {
124    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
125        f.debug_struct("HumanInTheLoopConfig")
126            .field("allowed_tools", &self.allowed_tools)
127            .field("classifier", &self.classifier)
128            .field("enable_trust", &self.enable_trust)
129            .field("ask", &self.ask)
130            .finish_non_exhaustive()
131    }
132}
133
134/// What [`HumanInTheLoop::auto`] accepts (`HumanInTheLoopAutoConfig`): how the human is reached and
135/// the calls that skip the decision entirely. The approval strategy is the mode's to choose.
136#[derive(Clone, Debug, Default, bon::Builder)]
137pub struct HumanInTheLoopAutoConfig {
138    /// Tools that run without approval, as in [`HumanInTheLoopConfig::allowed_tools`].
139    #[builder(default)]
140    pub allowed_tools: Vec<String>,
141    /// Collects answers inline, as in [`HumanInTheLoopConfig::ask`].
142    pub ask: Option<HumanInTheLoopAsk>,
143}
144
145impl From<HumanInTheLoopAutoConfig> for HumanInTheLoopConfig {
146    fn from(config: HumanInTheLoopAutoConfig) -> Self {
147        Self {
148            allowed_tools: config.allowed_tools,
149            classifier: Some(ClassifierConfig::llm()),
150            ask: config.ask,
151            ..Self::default()
152        }
153    }
154}
155
156fn is_trust_response(response: &JsonValue) -> bool {
157    match response {
158        JsonValue::String(text) => matches!(text.to_lowercase().trim_matches(is_js_whitespace), "t" | "trust"),
159        _ => false,
160    }
161}
162
163/// App state can be restored from a session, so anything but a list of strings counts as empty.
164fn trusted_tools(app_state: &StateStore) -> Vec<String> {
165    let Some(JsonValue::Array(values)) = app_state.get_value(TRUSTED_TOOLS_KEY) else {
166        return Vec::new();
167    };
168    values
169        .iter()
170        .map(|value| value.as_str().map(str::to_owned))
171        .collect::<Option<Vec<_>>>()
172        .unwrap_or_default()
173}
174
175fn trust_tool(app_state: &StateStore, tool_name: &str) {
176    let mut trusted = trusted_tools(app_state);
177    if trusted.iter().any(|name| name == tool_name) {
178        return;
179    }
180    trusted.push(tool_name.to_owned());
181    if let Err(error) = app_state.set(TRUSTED_TOOLS_KEY, trusted) {
182        tracing::warn!("tool=<{tool_name}>, error=<{error}> | failed to store the trusted tool");
183    }
184}
185
186struct Stdio {
187    options: &'static str,
188    turn: tokio::sync::Mutex<()>,
189}
190
191impl Stdio {
192    async fn ask(&self, prompt: String) -> Result<Option<JsonValue>, BoxError> {
193        let _turn = self.turn.lock().await;
194        let line = format!("{prompt} {}: ", self.options);
195        let answer = tokio::task::spawn_blocking(move || -> io::Result<Option<String>> {
196            let mut stdout = io::stdout().lock();
197            stdout.write_all(line.as_bytes())?;
198            stdout.flush()?;
199            drop(stdout);
200            let mut answer = String::new();
201            let read = io::stdin().lock().read_line(&mut answer)?;
202            Ok((read > 0).then(|| answer.trim_matches(is_js_whitespace).to_owned()))
203        })
204        .await??;
205        Ok(answer.map(JsonValue::String))
206    }
207}
208
209enum Ask {
210    Stdio(Stdio),
211    Callback(AskFn),
212}
213
214impl Ask {
215    async fn ask(&self, prompt: String) -> Result<Option<JsonValue>, BoxError> {
216        match self {
217            Self::Stdio(stdio) => stdio.ask(prompt).await,
218            Self::Callback(ask) => ask(prompt).await,
219        }
220    }
221}
222
223/// Asks a human before tool calls run (`HumanInTheLoop`).
224///
225/// Which calls need approval, first match wins: a `!tool` entry always does; a tool trusted at
226/// runtime (with `enable_trust`) does not; `*` or a listed tool does not; then the classifier
227/// decides; without one, every call does. The prompt is
228/// `Approve "<tool>"[ — <reason>]?\n  Input: <json>`; with interrupts it is the interrupt's
229/// reason, under the interrupt name `strands:human-in-the-loop`.
230pub struct HumanInTheLoop {
231    allowed_tools: HashSet<String>,
232    classifier: Option<Arc<dyn HumanInTheLoopClassifier>>,
233    enable_trust: bool,
234    evaluate_trust: Option<Evaluate>,
235    evaluate: Option<Evaluate>,
236    ask: Option<Ask>,
237    classified_tool_use_ids: Mutex<HashSet<String>>,
238}
239
240impl Default for HumanInTheLoop {
241    fn default() -> Self {
242        Self::new(HumanInTheLoopConfig::default())
243    }
244}
245
246impl fmt::Debug for HumanInTheLoop {
247    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
248        f.debug_struct("HumanInTheLoop")
249            .field("allowed_tools", &self.allowed_tools)
250            .field("enable_trust", &self.enable_trust)
251            .finish_non_exhaustive()
252    }
253}
254
255/// The name of the handler and of the interrupts it raises.
256pub const HUMAN_IN_THE_LOOP_NAME: &str = "strands:human-in-the-loop";
257
258impl HumanInTheLoop {
259    /// Auto mode (`'auto'`): the SDK's current best approval strategy decides which calls need a
260    /// human. Today that is the built-in LLM risk classifier, the same as
261    /// [`ClassifierConfig::llm`]: low-risk calls run on their own and risky ones are escalated.
262    /// What auto mode resolves to may change between releases; pass a full
263    /// [`HumanInTheLoopConfig`] to [`new`](Self::new) to pin the strategy.
264    ///
265    /// ```
266    /// use strands::vended_interventions::hitl::{HumanInTheLoop, HumanInTheLoopAsk, HumanInTheLoopAutoConfig};
267    ///
268    /// let hitl = HumanInTheLoop::auto(HumanInTheLoopAutoConfig {
269    ///     allowed_tools: vec!["read_file".into()],
270    ///     ask: Some(HumanInTheLoopAsk::Stdio),
271    /// });
272    /// # let _ = hitl;
273    /// ```
274    #[must_use]
275    pub fn auto(config: HumanInTheLoopAutoConfig) -> Self {
276        Self::new(config.into())
277    }
278
279    /// A handler with these settings.
280    #[must_use]
281    pub fn new(config: HumanInTheLoopConfig) -> Self {
282        let allowed_tools: HashSet<String> = config.allowed_tools.into_iter().collect();
283        let classifier = config.classifier.map(ClassifierConfig::resolve);
284        if classifier.is_some() && allowed_tools.contains("*") {
285            tracing::warn!(
286                "classifier has no effect when allowedTools contains \"*\" \u{2014} all tools are already allowed"
287            );
288        }
289        let enable_trust = config.enable_trust.unwrap_or(false);
290        let ask = config.ask.map(|ask| match ask {
291            HumanInTheLoopAsk::Stdio => Ask::Stdio(Stdio {
292                options: if enable_trust { "(y/n/t)" } else { "(y/n)" },
293                turn: tokio::sync::Mutex::new(()),
294            }),
295            HumanInTheLoopAsk::Callback(ask) => Ask::Callback(ask),
296        });
297        Self {
298            allowed_tools,
299            classifier,
300            enable_trust,
301            evaluate_trust: config.evaluate_trust,
302            evaluate: config.evaluate,
303            ask,
304            classified_tool_use_ids: Mutex::new(HashSet::new()),
305        }
306    }
307
308    fn is_negated(&self, tool_name: &str) -> bool {
309        self.allowed_tools.contains(&format!("!{tool_name}"))
310    }
311
312    fn is_trust(&self, response: &JsonValue) -> bool {
313        match &self.evaluate_trust {
314            Some(evaluate) => evaluate(response),
315            None => is_trust_response(response),
316        }
317    }
318
319    fn approves(evaluate: Option<&Evaluate>, response: &JsonValue) -> bool {
320        match evaluate {
321            Some(evaluate) => evaluate(response),
322            None => default_evaluate(response),
323        }
324    }
325
326    /// Whether the call needs approval, and why.
327    async fn requires_approval(&self, event: &BeforeToolCallEvent) -> ClassifierResult {
328        let tool_name = event.tool_use().name.as_str();
329        if self.is_negated(tool_name) {
330            return ClassifierResult::new(true);
331        }
332        if self.enable_trust
333            && trusted_tools(event.agent().app_state())
334                .iter()
335                .any(|name| name == tool_name)
336        {
337            return ClassifierResult::new(false);
338        }
339        if self.allowed_tools.contains("*") || self.allowed_tools.contains(tool_name) {
340            return ClassifierResult::new(false);
341        }
342        let Some(classifier) = &self.classifier else {
343            return ClassifierResult::new(true);
344        };
345        let first_time = self
346            .classified_tool_use_ids
347            .lock()
348            .unwrap_or_else(PoisonError::into_inner)
349            .insert(event.tool_use().tool_use_id.clone());
350        if !first_time {
351            return ClassifierResult::new(true);
352        }
353        match classifier.classify(event).await {
354            Ok(result) => result,
355            Err(error) => {
356                tracing::warn!(
357                    "tool=<{tool_name}>, error=<{error}> | classifier failed, defaulting to approval required"
358                );
359                ClassifierResult::new(true)
360            }
361        }
362    }
363
364    /// The confirm action for interrupt/resume mode, whose evaluation also handles trust.
365    fn confirm(&self, event: &BeforeToolCallEvent, prompt: String) -> InterventionAction<BeforeToolCallEvent> {
366        let tool_name = event.tool_use().name.clone();
367        let trust = (!self.is_negated(&tool_name) && self.enable_trust).then(|| self.evaluate_trust.clone());
368        let evaluate = self.evaluate.clone();
369        let app_state = event.agent().app_state().clone();
370        Confirm::new(prompt)
371            .with_evaluate(move |response| {
372                if let Some(evaluate_trust) = &trust {
373                    let trusted = match evaluate_trust {
374                        Some(evaluate_trust) => evaluate_trust(response),
375                        None => is_trust_response(response),
376                    };
377                    if trusted {
378                        trust_tool(&app_state, &tool_name);
379                        return true;
380                    }
381                }
382                Self::approves(evaluate.as_ref(), response)
383            })
384            .into()
385    }
386}
387
388#[async_trait]
389impl InterventionHandler for HumanInTheLoop {
390    fn name(&self) -> &str {
391        HUMAN_IN_THE_LOOP_NAME
392    }
393
394    async fn before_tool_call(&self, event: &mut BeforeToolCallEvent) -> InterventionResult<BeforeToolCallEvent> {
395        let decision = self.requires_approval(event).await;
396        if !decision.requires_human_in_the_loop {
397            return Ok(InterventionAction::proceed());
398        }
399        let tool_name = event.tool_use().name.clone();
400        let reason = decision
401            .reason
402            .map(|reason| format!(" \u{2014} {reason}"))
403            .unwrap_or_default();
404        let input = serde_json::to_string(&event.tool_use().input)?;
405        let prompt = format!("Approve \"{tool_name}\"{reason}?\n  Input: {input}");
406
407        let Some(ask) = &self.ask else {
408            return Ok(self.confirm(event, prompt));
409        };
410        // An inline caller cannot resume an interrupt, so a missing answer fails closed.
411        let Some(response) = ask.ask(prompt).await? else {
412            return Ok(InterventionAction::deny(format!(
413                "Tool \"{tool_name}\" denied: approval callback returned no response."
414            )));
415        };
416        if !self.is_negated(&tool_name) && self.enable_trust && self.is_trust(&response) {
417            trust_tool(event.agent().app_state(), &tool_name);
418            return Ok(InterventionAction::proceed());
419        }
420        if Self::approves(self.evaluate.as_ref(), &response) {
421            return Ok(InterventionAction::proceed());
422        }
423        Ok(InterventionAction::deny(format!(
424            "Tool \"{tool_name}\" denied: the human rejected the call."
425        )))
426    }
427}
428
429#[cfg(test)]
430mod tests;