1use std::sync::atomic::{AtomicUsize, Ordering};
17use std::sync::{Arc, Weak};
18
19use crate::runner::agent_node::AgentNodeHandler;
20use crate::runner::engine::FlowEngine;
21
22#[derive(Clone, Default)]
26pub struct NestedFlowHandlers {
27 #[cfg_attr(not(feature = "agentic-worker"), allow(dead_code))]
28 agent: Option<Weak<dyn AgentNodeHandler>>,
29}
30
31impl NestedFlowHandlers {
32 #[must_use]
34 pub fn with_agent(mut self, handler: &Arc<dyn AgentNodeHandler>) -> Self {
35 self.agent = Some(Arc::downgrade(handler));
36 self
37 }
38
39 pub(crate) fn install_on(&self, engine: &mut FlowEngine) {
41 #[cfg(feature = "agentic-worker")]
42 if let Some(handler) = self.agent.as_ref().and_then(Weak::upgrade) {
43 engine.set_agent_node_handler(handler);
44 }
45 #[cfg(not(feature = "agentic-worker"))]
46 let _ = engine;
47 }
48}
49
50pub const NESTED_FLOW_AGENTS_ENV: &str = "GREENTIC_AW_NESTED_FLOW_AGENTS";
56
57#[must_use]
59pub(crate) fn nested_flow_agents_enabled_from(get_env: impl Fn(&str) -> Option<String>) -> bool {
60 match get_env(NESTED_FLOW_AGENTS_ENV) {
61 Some(value) => !matches!(
62 value.trim().to_ascii_lowercase().as_str(),
63 "0" | "false" | "off" | "no"
64 ),
65 None => true,
66 }
67}
68
69#[must_use]
72pub fn nested_flow_agents_enabled() -> bool {
73 nested_flow_agents_enabled_from(|key| std::env::var(key).ok())
74}
75
76#[cfg(feature = "agentic-worker")]
81pub(crate) fn for_dispatch(
82 dispatch: crate::runner::agent_node::DwAgentDispatch,
83 agent: Option<&Arc<dyn AgentNodeHandler>>,
84) -> Option<NestedFlowHandlers> {
85 match (dispatch, agent) {
86 (crate::runner::agent_node::DwAgentDispatch::InProcess, Some(handler)) => {
87 Some(NestedFlowHandlers::default().with_agent(handler))
88 }
89 _ => None,
90 }
91}
92
93pub(crate) const MAX_NESTED_FLOW_TOOL_DEPTH: u8 = 3;
99
100pub(crate) const MAX_NESTED_FLOW_AGENT_STEPS: usize = 16;
106
107#[derive(Clone, Default)]
110pub(crate) struct AgentStepBudget(Arc<AtomicUsize>);
111
112impl AgentStepBudget {
113 fn claim(&self) -> bool {
116 self.0.fetch_add(1, Ordering::SeqCst) < MAX_NESTED_FLOW_AGENT_STEPS
117 }
118}
119
120impl PartialEq for AgentStepBudget {
121 fn eq(&self, other: &Self) -> bool {
122 Arc::ptr_eq(&self.0, &other.0)
123 }
124}
125
126impl Eq for AgentStepBudget {}
127
128impl std::fmt::Debug for AgentStepBudget {
129 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
130 write!(f, "AgentStepBudget({})", self.0.load(Ordering::SeqCst))
131 }
132}
133
134#[derive(Clone, Debug, PartialEq, Eq)]
136pub(crate) struct NestedFlowFrame {
137 pub(crate) depth: u8,
139 pub(crate) flow_id: String,
141 pub(crate) agent_session: Option<String>,
145 pub(crate) agent_steps: AgentStepBudget,
147}
148
149tokio::task_local! {
150 static FRAME: NestedFlowFrame;
151}
152
153fn current_depth() -> u8 {
154 FRAME.try_with(|frame| frame.depth).unwrap_or(0)
155}
156
157fn current_budget() -> AgentStepBudget {
159 FRAME
160 .try_with(|frame| frame.agent_steps.clone())
161 .unwrap_or_default()
162}
163
164pub(crate) fn enter(flow_id: &str) -> Result<NestedFlowFrame, String> {
174 let depth = current_depth();
175 if depth >= MAX_NESTED_FLOW_TOOL_DEPTH {
176 return Err(format!(
177 "flow tool '{flow_id}' refused: flow tools are already nested {depth} deep, \
178 the limit is {MAX_NESTED_FLOW_TOOL_DEPTH}"
179 ));
180 }
181 Ok(NestedFlowFrame {
182 depth: depth + 1,
183 flow_id: flow_id.to_string(),
184 agent_session: nested_agent_session(flow_id),
185 agent_steps: current_budget(),
186 })
187}
188
189pub(crate) async fn scope<F: std::future::Future>(frame: NestedFlowFrame, fut: F) -> F::Output {
191 FRAME.scope(frame, fut).await
192}
193
194#[cfg_attr(not(feature = "agentic-worker"), allow(dead_code))]
205pub(crate) fn agent_session_for(ctx_session: Option<&str>) -> Result<String, String> {
206 let frame = FRAME.try_with(Clone::clone).ok();
207 if let Some(frame) = &frame
208 && !frame.agent_steps.claim()
209 {
210 return Err(format!(
211 "flow tool '{}' refused: too many nested agent steps under one flow tool call, \
212 the limit is {MAX_NESTED_FLOW_AGENT_STEPS}",
213 frame.flow_id
214 ));
215 }
216 if let Some(session) = ctx_session.filter(|s| !s.is_empty()) {
217 return Ok(session.to_string());
218 }
219 match frame {
220 Some(NestedFlowFrame {
221 agent_session: Some(session),
222 ..
223 }) => Ok(session),
224 Some(NestedFlowFrame { flow_id, .. }) => Err(format!(
225 "flow tool '{flow_id}' refused: the calling agent has no session, so its \
226 dw.agent has no conversation of its own to run under"
227 )),
228 None => Ok(String::new()),
229 }
230}
231
232const MAX_CALL_ID_LEN: usize = 128;
234
235fn sanitise_call_id(call_id: &str) -> String {
242 call_id
243 .chars()
244 .map(|c| {
245 if c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '-') {
246 c
247 } else {
248 '_'
249 }
250 })
251 .take(MAX_CALL_ID_LEN)
252 .collect()
253}
254
255fn nested_session_from(session: Option<&str>, call_id: &str) -> String {
258 let call_id = sanitise_call_id(call_id);
259 match session {
260 Some(session) => format!("{session}::flowtool::{call_id}"),
261 None => format!("flowtool::{call_id}"),
262 }
263}
264
265fn nested_agent_session(flow_id: &str) -> Option<String> {
271 match calling_tool() {
272 Some((Some(session), call_id)) => Some(nested_session_from(Some(&session), &call_id)),
273 Some((None, _)) => None,
274 None => Some(format!("flowtool::{flow_id}::{}", ulid::Ulid::new())),
275 }
276}
277
278#[cfg(feature = "agentic-worker")]
279fn calling_tool() -> Option<(Option<String>, String)> {
280 greentic_aw_runtime::current_tool_call().map(|frame| {
281 (
282 frame.session_id().map(str::to_string),
283 frame.call_id().to_string(),
284 )
285 })
286}
287
288#[cfg(not(feature = "agentic-worker"))]
289fn calling_tool() -> Option<(Option<String>, String)> {
290 None
291}
292
293#[cfg(feature = "agentic-worker")]
298fn trusted_caller_block() -> Option<serde_json::Value> {
299 let frame = greentic_aw_runtime::current_tool_call()?;
300 serde_json::to_value(frame.caller()).ok()
301}
302
303#[cfg(not(feature = "agentic-worker"))]
304fn trusted_caller_block() -> Option<serde_json::Value> {
305 None
306}
307
308pub(crate) fn pin_caller(input: &mut serde_json::Value) {
323 use serde_json::Value;
324 let pinned = trusted_caller_block()
325 .filter(|b| b.get("user_verified").and_then(Value::as_bool) == Some(true));
326 match input {
327 Value::Object(map) => match pinned {
328 Some(block) => {
329 let extensions = map
330 .entry("extensions")
331 .or_insert_with(|| Value::Object(Default::default()));
332 if !extensions.is_object() {
333 *extensions = Value::Object(Default::default());
334 }
335 if let Value::Object(ext) = extensions {
336 ext.insert(crate::caller_identity::CALLER_EXT_KEY.into(), block);
337 }
338 }
339 None => {
340 if let Some(Value::Object(ext)) = map.get_mut("extensions") {
341 ext.remove(crate::caller_identity::CALLER_EXT_KEY);
342 }
343 }
344 },
345 Value::Null => {
348 if let Some(block) = pinned {
349 *input = serde_json::json!({
350 "extensions": { crate::caller_identity::CALLER_EXT_KEY: block }
351 });
352 }
353 }
354 _ => {}
355 }
356}
357
358#[cfg(test)]
359#[allow(clippy::unwrap_used, clippy::expect_used)]
360mod tests {
361 use super::*;
362
363 struct Noop;
364 #[async_trait::async_trait]
365 impl AgentNodeHandler for Noop {
366 async fn execute(
367 &self,
368 _: &str,
369 _: &str,
370 _: &str,
371 _: &str,
372 _: &serde_json::Value,
373 _: bool,
374 _: Option<&serde_json::Value>,
375 ) -> anyhow::Result<serde_json::Value> {
376 Ok(serde_json::Value::Null)
377 }
378 }
379
380 #[cfg(feature = "agentic-worker")]
381 #[test]
382 fn only_in_process_dispatch_lends_the_handler() {
383 use crate::runner::agent_node::DwAgentDispatch;
384 let handler: Arc<dyn AgentNodeHandler> = Arc::new(Noop);
385 assert!(for_dispatch(DwAgentDispatch::InProcess, Some(&handler)).is_some());
386 assert!(for_dispatch(DwAgentDispatch::Nats, Some(&handler)).is_none());
387 assert!(for_dispatch(DwAgentDispatch::InProcess, None).is_none());
388 }
389
390 #[test]
391 fn the_opt_out_reads_only_the_documented_off_values() {
392 let with = |v: Option<&'static str>| {
393 nested_flow_agents_enabled_from(move |k| {
394 assert_eq!(k, NESTED_FLOW_AGENTS_ENV);
395 v.map(str::to_string)
396 })
397 };
398 assert!(with(None));
399 assert!(with(Some("1")));
400 assert!(with(Some("true")));
401 assert!(with(Some("")));
402 assert!(with(Some("garbage")));
403 for off in ["0", "false", "FALSE", "off", "Off", "no", " no "] {
404 assert!(!with(Some(off)), "{off:?} must disable");
405 }
406 }
407
408 #[test]
410 fn a_lent_handler_is_held_weakly() {
411 let handler: Arc<dyn AgentNodeHandler> = Arc::new(Noop);
412 let lent = NestedFlowHandlers::default().with_agent(&handler);
413 assert_eq!(Arc::strong_count(&handler), 1);
414 assert_eq!(Arc::weak_count(&handler), 1);
415 drop(handler);
416 assert!(lent.agent.as_ref().and_then(Weak::upgrade).is_none());
417 }
418
419 fn frame(depth: u8, session: &str) -> NestedFlowFrame {
420 NestedFlowFrame {
421 depth,
422 flow_id: "f".into(),
423 agent_session: Some(session.into()),
424 agent_steps: AgentStepBudget::default(),
425 }
426 }
427
428 #[tokio::test]
429 async fn the_flow_context_session_wins_over_the_frame() {
430 let seen = scope(frame(1, "nested"), async {
431 (
432 agent_session_for(Some("ctx")),
433 agent_session_for(Some("")),
434 agent_session_for(None),
435 )
436 })
437 .await;
438 assert_eq!(
439 seen,
440 (Ok("ctx".into()), Ok("nested".into()), Ok("nested".into()))
441 );
442 }
443
444 #[tokio::test]
445 async fn outside_a_flow_tool_the_session_is_unchanged() {
446 assert_eq!(agent_session_for(None), Ok(String::new()));
447 assert_eq!(agent_session_for(Some("s")), Ok("s".to_string()));
448 }
449
450 #[tokio::test]
451 async fn entering_increments_the_depth_and_stops_at_the_limit() {
452 assert_eq!(enter("f").unwrap().depth, 1);
453 let inner = scope(frame(2, "x"), async { enter("f") }).await.unwrap();
454 assert_eq!(inner.depth, 3);
455 let refused = scope(frame(MAX_NESTED_FLOW_TOOL_DEPTH, "x"), async { enter("f") }).await;
456 assert!(refused.unwrap_err().contains("nested"));
457 }
458
459 #[tokio::test]
460 async fn the_limit_refuses_with_a_readable_error() {
461 let refused = scope(frame(MAX_NESTED_FLOW_TOOL_DEPTH, "x"), async {
462 enter("loop")
463 })
464 .await
465 .unwrap_err();
466 assert!(refused.contains("flow tool 'loop' refused"), "{refused}");
467 assert!(refused.contains("the limit is 3"), "{refused}");
468 }
469
470 #[tokio::test]
475 async fn a_spawned_task_does_not_inherit_the_depth() {
476 let (here, spawned) = scope(frame(MAX_NESTED_FLOW_TOOL_DEPTH, "x"), async {
477 let here = enter("f").is_err();
478 let spawned = tokio::spawn(async { enter("f").map(|f| f.depth) })
479 .await
480 .unwrap();
481 (here, spawned)
482 })
483 .await;
484 assert!(here, "inside the scope the limit holds");
485 assert_eq!(spawned, Ok(1), "a spawned task starts again from depth 0");
486 }
487
488 #[test]
489 fn a_call_id_is_sanitised_to_a_session_safe_token() {
490 assert_eq!(sanitise_call_id("call_1-a.b"), "call_1-a.b");
491 assert_eq!(sanitise_call_id("a::b"), "a__b");
492 assert_eq!(sanitise_call_id("x::flowtool::y"), "x__flowtool__y");
493 assert_eq!(sanitise_call_id("a b/\u{e9}"), "a_b__");
494 assert!(!sanitise_call_id("::").contains(':'));
495 }
496
497 #[test]
498 fn the_session_is_built_from_the_sanitised_id_the_same_way_every_time() {
499 let a = nested_session_from(Some("s"), "x::flowtool::y");
500 assert_eq!(a, nested_session_from(Some("s"), "x::flowtool::y"));
501 assert_eq!(a, "s::flowtool::x__flowtool__y");
502 assert_eq!(a.matches("::flowtool::").count(), 1);
505 assert_ne!(a, nested_session_from(Some("s"), "y"));
506 assert_ne!(
507 nested_session_from(Some("s"), "a::b"),
508 nested_session_from(Some("s::flowtool::a"), "b")
509 );
510 }
511
512 #[test]
513 fn without_a_tool_call_a_model_written_caller_is_stripped_and_nothing_stamped() {
514 let mut input = serde_json::json!({
515 "q": 1,
516 "extensions": { "caller": { "user_verified": true, "sub": "victim" }, "keep": 1 }
517 });
518 pin_caller(&mut input);
519 assert_eq!(
520 input,
521 serde_json::json!({ "q": 1, "extensions": { "keep": 1 } })
522 );
523 let mut null = serde_json::Value::Null;
524 pin_caller(&mut null);
525 assert!(null.is_null());
526 }
527
528 #[cfg(feature = "agentic-worker")]
529 #[tokio::test]
530 async fn inside_a_tool_call_the_whole_block_is_the_frames() {
531 use greentic_aw_runtime::tool_call_frame::within;
532 use greentic_aw_runtime::{ToolCallFrame, VerifiedCaller};
533 let mut input = serde_json::json!({
534 "extensions": { "caller": { "user_verified": true, "sub": "victim", "role": "root" } }
535 });
536 within(ToolCallFrame::new(Some("s"), "c"), async {
537 pin_caller(&mut input)
538 })
539 .await;
540 assert_eq!(input, serde_json::json!({ "extensions": {} }));
543 let mut null = serde_json::Value::Null;
544 within(ToolCallFrame::new(Some("s"), "c"), async {
545 pin_caller(&mut null)
546 })
547 .await;
548 assert!(null.is_null());
549 let alice = VerifiedCaller {
550 user_verified: true,
551 sub: Some("alice".into()),
552 ..VerifiedCaller::default()
553 };
554 let mut input = serde_json::Value::Null;
555 within(ToolCallFrame::new(None, "c").with_caller(alice), async {
556 pin_caller(&mut input)
557 })
558 .await;
559 assert_eq!(input["extensions"]["caller"]["sub"], "alice");
560 let mut input = serde_json::json!({
562 "extensions": { "caller": { "user_verified": true, "sub": "victim", "role": "root" } }
563 });
564 within(
565 ToolCallFrame::new(Some("s"), "c").with_caller(VerifiedCaller {
566 user_verified: true,
567 sub: Some("alice".into()),
568 ..VerifiedCaller::default()
569 }),
570 async { pin_caller(&mut input) },
571 )
572 .await;
573 assert_eq!(input["extensions"]["caller"]["sub"], "alice");
574 assert!(input["extensions"]["caller"].get("role").is_none());
575 }
576
577 #[test]
578 fn a_long_call_id_is_capped_after_sanitising_the_same_way_every_time() {
579 let long = format!("{}::{}", "a".repeat(200), "b".repeat(50));
580 let capped = sanitise_call_id(&long);
581 assert_eq!(capped.len(), MAX_CALL_ID_LEN);
582 assert_eq!(capped, "a".repeat(MAX_CALL_ID_LEN));
583 assert_eq!(capped, sanitise_call_id(&long), "deterministic");
584 let exact = "x".repeat(MAX_CALL_ID_LEN);
585 assert_eq!(sanitise_call_id(&exact), exact);
586 assert_eq!(
587 nested_session_from(Some("s"), &long),
588 format!("s::flowtool::{}", "a".repeat(MAX_CALL_ID_LEN))
589 );
590 }
591
592 #[tokio::test]
593 async fn the_nested_agent_steps_under_one_outermost_call_are_capped() {
594 let outer = enter("fan").unwrap();
595 let seen = scope(outer, async {
596 (0..=MAX_NESTED_FLOW_AGENT_STEPS)
597 .map(|_| agent_session_for(None))
598 .collect::<Vec<_>>()
599 })
600 .await;
601 assert!(
602 seen[..MAX_NESTED_FLOW_AGENT_STEPS]
603 .iter()
604 .all(Result::is_ok),
605 "the first {MAX_NESTED_FLOW_AGENT_STEPS} run: {seen:?}"
606 );
607 let refused = seen[MAX_NESTED_FLOW_AGENT_STEPS].clone().unwrap_err();
608 assert!(refused.contains("flow tool 'fan' refused"), "{refused}");
609 assert!(refused.contains("the limit is 16"), "{refused}");
610 }
611
612 #[tokio::test]
613 async fn deeper_levels_share_the_outermost_calls_step_budget() {
614 let outer = enter("top").unwrap();
615 let refused = scope(outer, async {
616 for _ in 0..10 {
617 agent_session_for(None).unwrap();
618 }
619 let inner = enter("mid").unwrap();
620 scope(inner, async {
621 for _ in 0..6 {
622 agent_session_for(None).unwrap();
623 }
624 agent_session_for(None)
625 })
626 .await
627 })
628 .await;
629 assert!(refused.unwrap_err().contains("the limit is 16"));
630 }
631
632 #[tokio::test]
633 async fn a_new_outermost_call_starts_its_own_budget_and_a_short_chain_is_unaffected() {
634 for _ in 0..2 {
635 let outer = enter("again").unwrap();
636 let seen = scope(outer, async {
637 let inner = enter("next").unwrap();
638 scope(inner, async {
639 (0..3).map(|_| agent_session_for(None)).collect::<Vec<_>>()
640 })
641 .await
642 })
643 .await;
644 assert!(seen.iter().all(Result::is_ok), "{seen:?}");
645 }
646 for _ in 0..=MAX_NESTED_FLOW_AGENT_STEPS {
648 assert_eq!(agent_session_for(None), Ok(String::new()));
649 }
650 }
651}