strands/vended_interventions/hitl/
mod.rs1mod 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
47pub const TRUSTED_TOOLS_KEY: &str = "hitl:trustedTools";
49
50crate::callback::callback! {
51 pub struct AskFn(Fn(String) -> BoxFuture<'static, Result<Option<JsonValue>, BoxError>>);
54}
55
56#[derive(Clone)]
58#[non_exhaustive]
59pub enum HumanInTheLoopAsk {
60 Stdio,
63 Callback(AskFn),
65}
66
67impl HumanInTheLoopAsk {
68 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#[derive(Clone, Default, bon::Builder)]
99pub struct HumanInTheLoopConfig {
100 #[builder(default)]
103 pub allowed_tools: Vec<String>,
104 #[builder(into)]
106 pub classifier: Option<ClassifierConfig>,
107 pub enable_trust: Option<bool>,
111 #[builder(into)]
114 pub evaluate_trust: Option<Evaluate>,
115 #[builder(into)]
117 pub evaluate: Option<Evaluate>,
118 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#[derive(Clone, Debug, Default, bon::Builder)]
137pub struct HumanInTheLoopAutoConfig {
138 #[builder(default)]
140 pub allowed_tools: Vec<String>,
141 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
163fn 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
223pub 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
255pub const HUMAN_IN_THE_LOOP_NAME: &str = "strands:human-in-the-loop";
257
258impl HumanInTheLoop {
259 #[must_use]
275 pub fn auto(config: HumanInTheLoopAutoConfig) -> Self {
276 Self::new(config.into())
277 }
278
279 #[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 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 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 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;