use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Weak};
use crate::runner::agent_node::AgentNodeHandler;
use crate::runner::engine::FlowEngine;
#[derive(Clone, Default)]
pub struct NestedFlowHandlers {
#[cfg_attr(not(feature = "agentic-worker"), allow(dead_code))]
agent: Option<Weak<dyn AgentNodeHandler>>,
}
impl NestedFlowHandlers {
#[must_use]
pub fn with_agent(mut self, handler: &Arc<dyn AgentNodeHandler>) -> Self {
self.agent = Some(Arc::downgrade(handler));
self
}
pub(crate) fn install_on(&self, engine: &mut FlowEngine) {
#[cfg(feature = "agentic-worker")]
if let Some(handler) = self.agent.as_ref().and_then(Weak::upgrade) {
engine.set_agent_node_handler(handler);
}
#[cfg(not(feature = "agentic-worker"))]
let _ = engine;
}
}
pub const NESTED_FLOW_AGENTS_ENV: &str = "GREENTIC_AW_NESTED_FLOW_AGENTS";
#[must_use]
pub(crate) fn nested_flow_agents_enabled_from(get_env: impl Fn(&str) -> Option<String>) -> bool {
match get_env(NESTED_FLOW_AGENTS_ENV) {
Some(value) => !matches!(
value.trim().to_ascii_lowercase().as_str(),
"0" | "false" | "off" | "no"
),
None => true,
}
}
#[must_use]
pub fn nested_flow_agents_enabled() -> bool {
nested_flow_agents_enabled_from(|key| std::env::var(key).ok())
}
#[cfg(feature = "agentic-worker")]
pub(crate) fn for_dispatch(
dispatch: crate::runner::agent_node::DwAgentDispatch,
agent: Option<&Arc<dyn AgentNodeHandler>>,
) -> Option<NestedFlowHandlers> {
match (dispatch, agent) {
(crate::runner::agent_node::DwAgentDispatch::InProcess, Some(handler)) => {
Some(NestedFlowHandlers::default().with_agent(handler))
}
_ => None,
}
}
pub(crate) const MAX_NESTED_FLOW_TOOL_DEPTH: u8 = 3;
pub(crate) const MAX_NESTED_FLOW_AGENT_STEPS: usize = 16;
#[derive(Clone, Default)]
pub(crate) struct AgentStepBudget(Arc<AtomicUsize>);
impl AgentStepBudget {
fn claim(&self) -> bool {
self.0.fetch_add(1, Ordering::SeqCst) < MAX_NESTED_FLOW_AGENT_STEPS
}
}
impl PartialEq for AgentStepBudget {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.0, &other.0)
}
}
impl Eq for AgentStepBudget {}
impl std::fmt::Debug for AgentStepBudget {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "AgentStepBudget({})", self.0.load(Ordering::SeqCst))
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct NestedFlowFrame {
pub(crate) depth: u8,
pub(crate) flow_id: String,
pub(crate) agent_session: Option<String>,
pub(crate) agent_steps: AgentStepBudget,
}
tokio::task_local! {
static FRAME: NestedFlowFrame;
}
fn current_depth() -> u8 {
FRAME.try_with(|frame| frame.depth).unwrap_or(0)
}
fn current_budget() -> AgentStepBudget {
FRAME
.try_with(|frame| frame.agent_steps.clone())
.unwrap_or_default()
}
pub(crate) fn enter(flow_id: &str) -> Result<NestedFlowFrame, String> {
let depth = current_depth();
if depth >= MAX_NESTED_FLOW_TOOL_DEPTH {
return Err(format!(
"flow tool '{flow_id}' refused: flow tools are already nested {depth} deep, \
the limit is {MAX_NESTED_FLOW_TOOL_DEPTH}"
));
}
Ok(NestedFlowFrame {
depth: depth + 1,
flow_id: flow_id.to_string(),
agent_session: nested_agent_session(flow_id),
agent_steps: current_budget(),
})
}
pub(crate) async fn scope<F: std::future::Future>(frame: NestedFlowFrame, fut: F) -> F::Output {
FRAME.scope(frame, fut).await
}
#[cfg_attr(not(feature = "agentic-worker"), allow(dead_code))]
pub(crate) fn agent_session_for(ctx_session: Option<&str>) -> Result<String, String> {
let frame = FRAME.try_with(Clone::clone).ok();
if let Some(frame) = &frame
&& !frame.agent_steps.claim()
{
return Err(format!(
"flow tool '{}' refused: too many nested agent steps under one flow tool call, \
the limit is {MAX_NESTED_FLOW_AGENT_STEPS}",
frame.flow_id
));
}
if let Some(session) = ctx_session.filter(|s| !s.is_empty()) {
return Ok(session.to_string());
}
match frame {
Some(NestedFlowFrame {
agent_session: Some(session),
..
}) => Ok(session),
Some(NestedFlowFrame { flow_id, .. }) => Err(format!(
"flow tool '{flow_id}' refused: the calling agent has no session, so its \
dw.agent has no conversation of its own to run under"
)),
None => Ok(String::new()),
}
}
const MAX_CALL_ID_LEN: usize = 128;
fn sanitise_call_id(call_id: &str) -> String {
call_id
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '-') {
c
} else {
'_'
}
})
.take(MAX_CALL_ID_LEN)
.collect()
}
fn nested_session_from(session: Option<&str>, call_id: &str) -> String {
let call_id = sanitise_call_id(call_id);
match session {
Some(session) => format!("{session}::flowtool::{call_id}"),
None => format!("flowtool::{call_id}"),
}
}
fn nested_agent_session(flow_id: &str) -> Option<String> {
match calling_tool() {
Some((Some(session), call_id)) => Some(nested_session_from(Some(&session), &call_id)),
Some((None, _)) => None,
None => Some(format!("flowtool::{flow_id}::{}", ulid::Ulid::new())),
}
}
#[cfg(feature = "agentic-worker")]
fn calling_tool() -> Option<(Option<String>, String)> {
greentic_aw_runtime::current_tool_call().map(|frame| {
(
frame.session_id().map(str::to_string),
frame.call_id().to_string(),
)
})
}
#[cfg(not(feature = "agentic-worker"))]
fn calling_tool() -> Option<(Option<String>, String)> {
None
}
#[cfg(feature = "agentic-worker")]
fn trusted_caller_block() -> Option<serde_json::Value> {
let frame = greentic_aw_runtime::current_tool_call()?;
serde_json::to_value(frame.caller()).ok()
}
#[cfg(not(feature = "agentic-worker"))]
fn trusted_caller_block() -> Option<serde_json::Value> {
None
}
pub(crate) fn pin_caller(input: &mut serde_json::Value) {
use serde_json::Value;
let pinned = trusted_caller_block()
.filter(|b| b.get("user_verified").and_then(Value::as_bool) == Some(true));
match input {
Value::Object(map) => match pinned {
Some(block) => {
let extensions = map
.entry("extensions")
.or_insert_with(|| Value::Object(Default::default()));
if !extensions.is_object() {
*extensions = Value::Object(Default::default());
}
if let Value::Object(ext) = extensions {
ext.insert(crate::caller_identity::CALLER_EXT_KEY.into(), block);
}
}
None => {
if let Some(Value::Object(ext)) = map.get_mut("extensions") {
ext.remove(crate::caller_identity::CALLER_EXT_KEY);
}
}
},
Value::Null => {
if let Some(block) = pinned {
*input = serde_json::json!({
"extensions": { crate::caller_identity::CALLER_EXT_KEY: block }
});
}
}
_ => {}
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
use super::*;
struct Noop;
#[async_trait::async_trait]
impl AgentNodeHandler for Noop {
async fn execute(
&self,
_: &str,
_: &str,
_: &str,
_: &str,
_: &serde_json::Value,
_: bool,
_: Option<&serde_json::Value>,
) -> anyhow::Result<serde_json::Value> {
Ok(serde_json::Value::Null)
}
}
#[cfg(feature = "agentic-worker")]
#[test]
fn only_in_process_dispatch_lends_the_handler() {
use crate::runner::agent_node::DwAgentDispatch;
let handler: Arc<dyn AgentNodeHandler> = Arc::new(Noop);
assert!(for_dispatch(DwAgentDispatch::InProcess, Some(&handler)).is_some());
assert!(for_dispatch(DwAgentDispatch::Nats, Some(&handler)).is_none());
assert!(for_dispatch(DwAgentDispatch::InProcess, None).is_none());
}
#[test]
fn the_opt_out_reads_only_the_documented_off_values() {
let with = |v: Option<&'static str>| {
nested_flow_agents_enabled_from(move |k| {
assert_eq!(k, NESTED_FLOW_AGENTS_ENV);
v.map(str::to_string)
})
};
assert!(with(None));
assert!(with(Some("1")));
assert!(with(Some("true")));
assert!(with(Some("")));
assert!(with(Some("garbage")));
for off in ["0", "false", "FALSE", "off", "Off", "no", " no "] {
assert!(!with(Some(off)), "{off:?} must disable");
}
}
#[test]
fn a_lent_handler_is_held_weakly() {
let handler: Arc<dyn AgentNodeHandler> = Arc::new(Noop);
let lent = NestedFlowHandlers::default().with_agent(&handler);
assert_eq!(Arc::strong_count(&handler), 1);
assert_eq!(Arc::weak_count(&handler), 1);
drop(handler);
assert!(lent.agent.as_ref().and_then(Weak::upgrade).is_none());
}
fn frame(depth: u8, session: &str) -> NestedFlowFrame {
NestedFlowFrame {
depth,
flow_id: "f".into(),
agent_session: Some(session.into()),
agent_steps: AgentStepBudget::default(),
}
}
#[tokio::test]
async fn the_flow_context_session_wins_over_the_frame() {
let seen = scope(frame(1, "nested"), async {
(
agent_session_for(Some("ctx")),
agent_session_for(Some("")),
agent_session_for(None),
)
})
.await;
assert_eq!(
seen,
(Ok("ctx".into()), Ok("nested".into()), Ok("nested".into()))
);
}
#[tokio::test]
async fn outside_a_flow_tool_the_session_is_unchanged() {
assert_eq!(agent_session_for(None), Ok(String::new()));
assert_eq!(agent_session_for(Some("s")), Ok("s".to_string()));
}
#[tokio::test]
async fn entering_increments_the_depth_and_stops_at_the_limit() {
assert_eq!(enter("f").unwrap().depth, 1);
let inner = scope(frame(2, "x"), async { enter("f") }).await.unwrap();
assert_eq!(inner.depth, 3);
let refused = scope(frame(MAX_NESTED_FLOW_TOOL_DEPTH, "x"), async { enter("f") }).await;
assert!(refused.unwrap_err().contains("nested"));
}
#[tokio::test]
async fn the_limit_refuses_with_a_readable_error() {
let refused = scope(frame(MAX_NESTED_FLOW_TOOL_DEPTH, "x"), async {
enter("loop")
})
.await
.unwrap_err();
assert!(refused.contains("flow tool 'loop' refused"), "{refused}");
assert!(refused.contains("the limit is 3"), "{refused}");
}
#[tokio::test]
async fn a_spawned_task_does_not_inherit_the_depth() {
let (here, spawned) = scope(frame(MAX_NESTED_FLOW_TOOL_DEPTH, "x"), async {
let here = enter("f").is_err();
let spawned = tokio::spawn(async { enter("f").map(|f| f.depth) })
.await
.unwrap();
(here, spawned)
})
.await;
assert!(here, "inside the scope the limit holds");
assert_eq!(spawned, Ok(1), "a spawned task starts again from depth 0");
}
#[test]
fn a_call_id_is_sanitised_to_a_session_safe_token() {
assert_eq!(sanitise_call_id("call_1-a.b"), "call_1-a.b");
assert_eq!(sanitise_call_id("a::b"), "a__b");
assert_eq!(sanitise_call_id("x::flowtool::y"), "x__flowtool__y");
assert_eq!(sanitise_call_id("a b/\u{e9}"), "a_b__");
assert!(!sanitise_call_id("::").contains(':'));
}
#[test]
fn the_session_is_built_from_the_sanitised_id_the_same_way_every_time() {
let a = nested_session_from(Some("s"), "x::flowtool::y");
assert_eq!(a, nested_session_from(Some("s"), "x::flowtool::y"));
assert_eq!(a, "s::flowtool::x__flowtool__y");
assert_eq!(a.matches("::flowtool::").count(), 1);
assert_ne!(a, nested_session_from(Some("s"), "y"));
assert_ne!(
nested_session_from(Some("s"), "a::b"),
nested_session_from(Some("s::flowtool::a"), "b")
);
}
#[test]
fn without_a_tool_call_a_model_written_caller_is_stripped_and_nothing_stamped() {
let mut input = serde_json::json!({
"q": 1,
"extensions": { "caller": { "user_verified": true, "sub": "victim" }, "keep": 1 }
});
pin_caller(&mut input);
assert_eq!(
input,
serde_json::json!({ "q": 1, "extensions": { "keep": 1 } })
);
let mut null = serde_json::Value::Null;
pin_caller(&mut null);
assert!(null.is_null());
}
#[cfg(feature = "agentic-worker")]
#[tokio::test]
async fn inside_a_tool_call_the_whole_block_is_the_frames() {
use greentic_aw_runtime::tool_call_frame::within;
use greentic_aw_runtime::{ToolCallFrame, VerifiedCaller};
let mut input = serde_json::json!({
"extensions": { "caller": { "user_verified": true, "sub": "victim", "role": "root" } }
});
within(ToolCallFrame::new(Some("s"), "c"), async {
pin_caller(&mut input)
})
.await;
assert_eq!(input, serde_json::json!({ "extensions": {} }));
let mut null = serde_json::Value::Null;
within(ToolCallFrame::new(Some("s"), "c"), async {
pin_caller(&mut null)
})
.await;
assert!(null.is_null());
let alice = VerifiedCaller {
user_verified: true,
sub: Some("alice".into()),
..VerifiedCaller::default()
};
let mut input = serde_json::Value::Null;
within(ToolCallFrame::new(None, "c").with_caller(alice), async {
pin_caller(&mut input)
})
.await;
assert_eq!(input["extensions"]["caller"]["sub"], "alice");
let mut input = serde_json::json!({
"extensions": { "caller": { "user_verified": true, "sub": "victim", "role": "root" } }
});
within(
ToolCallFrame::new(Some("s"), "c").with_caller(VerifiedCaller {
user_verified: true,
sub: Some("alice".into()),
..VerifiedCaller::default()
}),
async { pin_caller(&mut input) },
)
.await;
assert_eq!(input["extensions"]["caller"]["sub"], "alice");
assert!(input["extensions"]["caller"].get("role").is_none());
}
#[test]
fn a_long_call_id_is_capped_after_sanitising_the_same_way_every_time() {
let long = format!("{}::{}", "a".repeat(200), "b".repeat(50));
let capped = sanitise_call_id(&long);
assert_eq!(capped.len(), MAX_CALL_ID_LEN);
assert_eq!(capped, "a".repeat(MAX_CALL_ID_LEN));
assert_eq!(capped, sanitise_call_id(&long), "deterministic");
let exact = "x".repeat(MAX_CALL_ID_LEN);
assert_eq!(sanitise_call_id(&exact), exact);
assert_eq!(
nested_session_from(Some("s"), &long),
format!("s::flowtool::{}", "a".repeat(MAX_CALL_ID_LEN))
);
}
#[tokio::test]
async fn the_nested_agent_steps_under_one_outermost_call_are_capped() {
let outer = enter("fan").unwrap();
let seen = scope(outer, async {
(0..=MAX_NESTED_FLOW_AGENT_STEPS)
.map(|_| agent_session_for(None))
.collect::<Vec<_>>()
})
.await;
assert!(
seen[..MAX_NESTED_FLOW_AGENT_STEPS]
.iter()
.all(Result::is_ok),
"the first {MAX_NESTED_FLOW_AGENT_STEPS} run: {seen:?}"
);
let refused = seen[MAX_NESTED_FLOW_AGENT_STEPS].clone().unwrap_err();
assert!(refused.contains("flow tool 'fan' refused"), "{refused}");
assert!(refused.contains("the limit is 16"), "{refused}");
}
#[tokio::test]
async fn deeper_levels_share_the_outermost_calls_step_budget() {
let outer = enter("top").unwrap();
let refused = scope(outer, async {
for _ in 0..10 {
agent_session_for(None).unwrap();
}
let inner = enter("mid").unwrap();
scope(inner, async {
for _ in 0..6 {
agent_session_for(None).unwrap();
}
agent_session_for(None)
})
.await
})
.await;
assert!(refused.unwrap_err().contains("the limit is 16"));
}
#[tokio::test]
async fn a_new_outermost_call_starts_its_own_budget_and_a_short_chain_is_unaffected() {
for _ in 0..2 {
let outer = enter("again").unwrap();
let seen = scope(outer, async {
let inner = enter("next").unwrap();
scope(inner, async {
(0..3).map(|_| agent_session_for(None)).collect::<Vec<_>>()
})
.await
})
.await;
assert!(seen.iter().all(Result::is_ok), "{seen:?}");
}
for _ in 0..=MAX_NESTED_FLOW_AGENT_STEPS {
assert_eq!(agent_session_for(None), Ok(String::new()));
}
}
}