strands_harness/
interventions.rs1use std::fmt;
15use std::sync::Arc;
16
17use strands::interventions::InterventionHandler;
18use strands::vended_interventions::hitl::{
19 ClassifierConfig, HumanInTheLoop, HumanInTheLoopAsk, HumanInTheLoopConfig, LlmClassifierConfig,
20};
21
22#[derive(Clone)]
25#[non_exhaustive]
26pub enum InterventionValue {
27 Text(String),
30 Handler(Arc<dyn InterventionHandler>),
32}
33
34impl InterventionValue {
35 pub fn handler(handler: impl InterventionHandler) -> Self {
37 Self::Handler(Arc::new(handler))
38 }
39}
40
41impl fmt::Debug for InterventionValue {
42 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
43 match self {
44 Self::Text(text) => f.debug_tuple("Text").field(text).finish(),
45 Self::Handler(handler) => f.debug_tuple("Handler").field(&handler.name()).finish(),
46 }
47 }
48}
49
50impl From<&str> for InterventionValue {
51 fn from(text: &str) -> Self {
52 Self::Text(text.to_owned())
53 }
54}
55
56impl From<String> for InterventionValue {
57 fn from(text: String) -> Self {
58 Self::Text(text)
59 }
60}
61
62impl From<Arc<dyn InterventionHandler>> for InterventionValue {
63 fn from(handler: Arc<dyn InterventionHandler>) -> Self {
64 Self::Handler(handler)
65 }
66}
67
68impl From<HumanInTheLoop> for InterventionValue {
69 fn from(handler: HumanInTheLoop) -> Self {
70 Self::handler(handler)
71 }
72}
73
74#[derive(Debug, Clone)]
77#[non_exhaustive]
78pub enum InterventionsOption {
79 Value(InterventionValue),
81 List(Vec<InterventionValue>),
83}
84
85impl InterventionsOption {
86 fn values(&self) -> &[InterventionValue] {
87 match self {
88 Self::Value(value) => std::slice::from_ref(value),
89 Self::List(values) => values,
90 }
91 }
92}
93
94impl<T: Into<InterventionValue>> From<T> for InterventionsOption {
95 fn from(value: T) -> Self {
96 Self::Value(value.into())
97 }
98}
99
100impl<T: Into<InterventionValue>> From<Vec<T>> for InterventionsOption {
101 fn from(values: Vec<T>) -> Self {
102 Self::List(values.into_iter().map(Into::into).collect())
103 }
104}
105
106impl<T: Into<InterventionValue>, const N: usize> From<[T; N]> for InterventionsOption {
107 fn from(values: [T; N]) -> Self {
108 Self::List(values.into_iter().map(Into::into).collect())
109 }
110}
111
112pub(crate) fn hitl_config(text: &str, ask: Option<&HumanInTheLoopAsk>) -> Option<HumanInTheLoopConfig> {
115 let classifier = match text.trim() {
116 "off" => return None,
117 "ask" => None,
118 "smart" => Some(ClassifierConfig::llm()),
119 trimmed if trimmed.ends_with(".cedar") => return None,
120 _ => Some(ClassifierConfig::Llm(LlmClassifierConfig {
121 system_prompt: Some(text.to_owned()),
122 ..Default::default()
123 })),
124 };
125 Some(HumanInTheLoopConfig {
126 classifier,
127 ask: ask.cloned(),
128 ..Default::default()
129 })
130}
131
132#[cfg(feature = "cedar")]
133fn cedar_handler(policies: &str) -> strands::Result<Arc<dyn InterventionHandler>> {
134 use strands::vended_interventions::cedar::{CedarAuthorization, CedarAuthorizationConfig};
135
136 let config = CedarAuthorizationConfig {
137 policies: policies.to_owned(),
138 ..Default::default()
139 };
140 Ok(Arc::new(CedarAuthorization::new(config)?))
141}
142
143#[cfg(not(feature = "cedar"))]
144fn cedar_handler(policies: &str) -> strands::Result<Arc<dyn InterventionHandler>> {
145 Err(strands::Error::other(format!(
146 "Cedar policy '{policies}' needs the strands-harness feature \"cedar\"; enable it to use Cedar interventions."
147 )))
148}
149
150fn resolve_one(
151 value: &InterventionValue,
152 ask: Option<&HumanInTheLoopAsk>,
153) -> strands::Result<Option<Arc<dyn InterventionHandler>>> {
154 let text = match value {
155 InterventionValue::Handler(handler) => return Ok(Some(Arc::clone(handler))),
156 InterventionValue::Text(text) => text,
157 };
158 let trimmed = text.trim();
159 if trimmed.ends_with(".cedar") && !matches!(trimmed, "off" | "ask" | "smart") {
160 return cedar_handler(trimmed).map(Some);
161 }
162 Ok(hitl_config(text, ask).map(|config| Arc::new(HumanInTheLoop::new(config)) as Arc<dyn InterventionHandler>))
163}
164
165fn check_handler_collisions(handlers: &[Arc<dyn InterventionHandler>]) -> strands::Result<()> {
167 for (index, handler) in handlers.iter().enumerate() {
168 if handlers[..index].iter().any(|prior| prior.name() == handler.name()) {
169 return Err(strands::Error::other(format!(
170 "Two interventions share the handler name '{}', but an agent registers at most one per name. Layer different kinds (e.g. a Cedar policy plus one human-approval preset), not two of the same kind.",
171 handler.name()
172 )));
173 }
174 }
175 Ok(())
176}
177
178pub(crate) fn resolve_interventions(
181 value: Option<&InterventionsOption>,
182 ask: Option<&HumanInTheLoopAsk>,
183) -> strands::Result<Vec<Arc<dyn InterventionHandler>>> {
184 let Some(value) = value else {
185 return Ok(Vec::new());
186 };
187 let mut handlers = Vec::new();
188 for value in value.values() {
189 handlers.extend(resolve_one(value, ask)?);
190 }
191 check_handler_collisions(&handlers)?;
192 Ok(handlers)
193}
194
195#[cfg(test)]
197mod tests {
198 use super::*;
199
200 fn cedar_file(dir: &std::path::Path) -> String {
201 let path = dir.join("agent.cedar");
202 std::fs::write(&path, "permit(principal, action == Action::\"read\", resource);").unwrap();
203 path.to_string_lossy().into_owned()
204 }
205
206 fn names(handlers: &[Arc<dyn InterventionHandler>]) -> Vec<&str> {
207 handlers.iter().map(|handler| handler.name()).collect()
208 }
209
210 #[test]
211 fn registers_nothing_for_undefined_or_off() {
212 assert!(resolve_interventions(None, None).unwrap().is_empty());
213 assert!(resolve_interventions(Some(&"off".into()), None).unwrap().is_empty());
214 let list = InterventionsOption::List(vec!["off".into()]);
215 assert!(resolve_interventions(Some(&list), None).unwrap().is_empty());
216 }
217
218 #[test]
219 fn converts_lists_and_arrays_of_values() {
220 let texts = |option: InterventionsOption| -> Vec<String> {
221 option
222 .values()
223 .iter()
224 .map(|value| match value {
225 InterventionValue::Text(text) => text.clone(),
226 InterventionValue::Handler(_) => "handler".to_owned(),
227 })
228 .collect()
229 };
230 assert_eq!(texts(vec!["ask", "smart"].into()), ["ask", "smart"]);
231 assert_eq!(texts(["ask".to_owned()].into()), ["ask"]);
232 }
233
234 #[test]
235 fn gates_every_tool_for_ask() {
236 let config = hitl_config("ask", None).unwrap();
237 assert!(config.allowed_tools.is_empty());
238 assert!(config.classifier.is_none());
239 let handlers = resolve_interventions(Some(&"ask".into()), None).unwrap();
240 assert_eq!(names(&handlers), ["strands:human-in-the-loop"]);
241 }
242
243 #[test]
244 fn uses_the_llm_classifier_for_smart() {
245 let config = hitl_config("smart", None).unwrap();
246 assert!(config.allowed_tools.is_empty());
247 assert!(matches!(
248 config.classifier,
249 Some(ClassifierConfig::Llm(LlmClassifierConfig {
250 system_prompt: None,
251 ..
252 }))
253 ));
254 }
255
256 #[test]
257 fn turns_a_natural_language_string_into_the_classifier_prompt() {
258 let policy = "Read-only overall, but writes under ./out are fine";
259 let config = hitl_config(policy, None).unwrap();
260 assert!(config.allowed_tools.is_empty());
261 let Some(ClassifierConfig::Llm(classifier)) = config.classifier else {
262 panic!("expected the LLM classifier");
263 };
264 assert_eq!(classifier.system_prompt.as_deref(), Some(policy));
265 }
266
267 #[cfg(not(feature = "cedar"))]
268 #[test]
269 fn reports_a_clear_error_when_the_optional_cedar_dependency_is_unavailable() {
270 let dir = tempfile::tempdir().unwrap();
271 let path = cedar_file(dir.path());
272 let error = resolve_interventions(Some(&path.as_str().into()), None).err().unwrap();
273 assert!(error.to_string().to_lowercase().contains("cedar"));
274 }
275
276 #[cfg(feature = "cedar")]
277 #[test]
278 fn loads_a_cedar_file_path_as_a_cedar_handler_when_the_dependency_is_installed() {
279 let dir = tempfile::tempdir().unwrap();
280 let path = cedar_file(dir.path());
281 let handlers = resolve_interventions(Some(&path.as_str().into()), None).unwrap();
282 assert_eq!(names(&handlers), ["cedar-authorization"]);
283 }
284
285 #[test]
286 fn does_not_treat_a_non_cedar_file_path_as_cedar() {
287 let dir = tempfile::tempdir().unwrap();
288 let path = dir.path().join("policy.txt");
289 std::fs::write(&path, "be careful").unwrap();
290 let text = path.to_string_lossy().into_owned();
291 assert!(hitl_config(&text, None).is_some());
292 let handlers = resolve_interventions(Some(&text.as_str().into()), None).unwrap();
293 assert_eq!(names(&handlers), ["strands:human-in-the-loop"]);
294 }
295
296 #[test]
297 fn passes_a_handler_instance_through_untouched() {
298 let handler: Arc<dyn InterventionHandler> = Arc::new(HumanInTheLoop::new(HumanInTheLoopConfig {
299 ask: Some(HumanInTheLoopAsk::Stdio),
300 enable_trust: Some(true),
301 ..Default::default()
302 }));
303 let handlers = resolve_interventions(Some(&Arc::clone(&handler).into()), None).unwrap();
304 assert_eq!(handlers.len(), 1);
305 assert!(Arc::ptr_eq(&handlers[0], &handler));
306 }
307
308 #[test]
309 fn throws_when_two_human_approval_handlers_collide() {
310 let both = InterventionsOption::List(vec!["ask".into(), "smart".into()]);
311 let error = resolve_interventions(Some(&both), None).err().unwrap();
312 assert!(error.to_string().contains("at most one"));
313 assert_eq!(
314 error.to_string(),
315 "Two interventions share the handler name 'strands:human-in-the-loop', but an agent registers at most one per name. Layer different kinds (e.g. a Cedar policy plus one human-approval preset), not two of the same kind."
316 );
317 }
318
319 #[test]
320 fn threads_the_ask_mode_into_the_handler() {
321 assert!(hitl_config("ask", None).unwrap().ask.is_none());
322 let stdio = HumanInTheLoopAsk::Stdio;
323 assert!(hitl_config("ask", Some(&stdio)).unwrap().ask.is_some());
324 }
325}