use std::collections::BTreeSet;
use std::sync::Arc;
use gadk_agent::{Agent, AgentType, InvocationContext};
use gadk_session::Event;
use crate::tool::utils::{function_calls, function_responses};
pub(crate) fn find_call_event<'a>(events: &'a [Event], call_id: &str) -> Option<&'a Event> {
events.iter().rev().find(|e| {
function_calls(e.response.content.as_ref())
.iter()
.any(|fc| fc.id == call_id)
})
}
pub(crate) fn graph_resume_indexes(ctx: &InvocationContext) -> Option<Vec<usize>> {
if ctx.graph_resume_done() {
return None;
}
let responses = function_responses(ctx.user_content());
if responses.is_empty() {
return None;
}
let events = ctx.session().events();
let agent = ctx.agent();
let mut selected = BTreeSet::new();
let mut in_graph = false;
for response in responses {
let Some(ev) = find_call_event(&events, &response.id) else {
continue;
};
for (i, sub) in agent.sub_agents().iter().enumerate() {
if sub.find_agent(&ev.author).is_none() {
continue;
}
selected.insert(i);
in_graph = in_graph || called_from_graph(sub, &ev.author, false);
}
}
if !in_graph {
return None;
}
Some(selected.into_iter().collect())
}
fn called_from_graph(a: &Arc<dyn Agent>, author: &str, in_graph: bool) -> bool {
let in_graph = in_graph || a.agent_state().agent_type == AgentType::WorkflowAgent;
if a.name() == author {
return in_graph;
}
a.sub_agents()
.iter()
.any(|sub| called_from_graph(sub, author, in_graph))
}