use std::sync::Arc;
use futures::StreamExt;
use gadk_agent::{
Agent, AgentConfig, AgentError, AgentState, AgentType, EventStream, InvocationContext,
};
use crate::agents::graph_resume::graph_resume_indexes;
#[derive(Clone, Default)]
pub struct LoopAgentConfig {
pub agent: AgentConfig,
pub max_iterations: u32,
}
pub fn new(cfg: LoopAgentConfig) -> Result<Arc<dyn Agent>, AgentError> {
if cfg.agent.run.is_some() {
return Err(AgentError::Config(
"LoopAgent doesn't allow custom Run implementations".into(),
));
}
let max = cfg.max_iterations;
let mut agent_cfg = cfg.agent.clone();
agent_cfg.run = Some(Arc::new(move |ctx: InvocationContext| run(ctx, max)));
gadk_agent::new_with_state(
agent_cfg,
AgentState {
agent_type: AgentType::LoopAgent,
config: Some(Arc::new(cfg)),
on_before_agent_callback_event: None,
live: None,
},
)
.map_err(|e| AgentError::Config(format!("failed to create base agent: {e}")))
}
fn run(ctx: InvocationContext, max_iterations: u32) -> EventStream {
Box::pin(async_stream::stream! {
let subs: Vec<Arc<dyn Agent>> = ctx.agent().sub_agents().to_vec();
if subs.is_empty() {
return;
}
let mut pass_subs: &[Arc<dyn Agent>] = &subs;
if let Some(&first) = graph_resume_indexes(&ctx).as_ref().and_then(|ix| ix.first()) {
pass_subs = &subs[first..];
}
let mut pass_ctx = ctx.clone();
let mut count = max_iterations;
loop {
if ctx.cancellation_token().is_cancelled() {
yield Err(AgentError::Cancelled);
return;
}
tokio::task::yield_now().await;
let mut should_exit = false;
for sub in pass_subs {
let mut s = sub.run(pass_ctx.clone());
while let Some(item) = s.next().await {
match item {
Err(e) => {
yield Err(e);
return;
}
Ok(ev) => {
let escalate = ev.actions.escalate;
yield Ok(ev);
if escalate {
should_exit = true;
}
}
}
}
if should_exit {
return;
}
}
pass_subs = &subs;
pass_ctx = ctx.with_graph_resume_done();
if count > 0 {
count -= 1;
if count == 0 {
return;
}
}
}
})
}