use std::any::Any;
use std::collections::HashSet;
use std::sync::Arc;
use async_trait::async_trait;
use futures::StreamExt;
use gadk_agent::{
Agent, AgentConfig, AgentError, AgentState, AgentType, Context, ContextDelta, EventStream,
InvocationContext, LiveAgent, LiveRequest, LiveSession, Tool, ToolError,
};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use crate::agents::graph_resume::graph_resume_indexes;
use crate::llm::state::reveal;
use crate::runner::wrap;
use crate::tool::{FunctionTool, FunctionToolConfig};
#[derive(Clone, Default)]
pub struct SequentialAgentConfig {
pub agent: AgentConfig,
}
pub fn new(cfg: SequentialAgentConfig) -> Result<Arc<dyn Agent>, AgentError> {
if cfg.agent.run.is_some() {
return Err(AgentError::Config(
"SequentialAgent doesn't allow custom Run implementations".into(),
));
}
let mut agent_cfg = cfg.agent.clone();
agent_cfg.run = Some(Arc::new(run));
gadk_agent::new_with_state(
agent_cfg,
AgentState {
agent_type: AgentType::SequentialAgent,
config: Some(Arc::new(cfg)),
on_before_agent_callback_event: None,
live: Some(Arc::new(SequentialLive)),
},
)
.map_err(|e| AgentError::Config(format!("failed to create base agent: {e}")))
}
fn run(ctx: InvocationContext) -> EventStream {
Box::pin(async_stream::stream! {
let mut subs: Vec<Arc<dyn Agent>> = ctx.agent().sub_agents().to_vec();
if let Some(&first) = graph_resume_indexes(&ctx).as_ref().and_then(|ix| ix.first()) {
subs.drain(..first);
}
for sub in subs {
let mut s = sub.run(ctx.clone());
while let Some(item) = s.next().await {
let failed = item.is_err();
yield item;
if failed {
return;
}
}
}
})
}
const TASK_COMPLETED_NAME: &str = "task_completed";
const TASK_COMPLETED_DESCRIPTION: &str =
"Signals that the agent has successfully completed the user's question or task.";
pub(crate) const TASK_COMPLETED_INSTRUCTION_SUFFIX: &str = "\nIf you finished the user's request according to its description, call the task_completed function to exit so the next agents can take over. When calling this function, do not generate any text other than the function call.";
#[derive(Deserialize, JsonSchema)]
struct TaskCompletedArgs {}
#[derive(Serialize, JsonSchema)]
struct TaskCompletedResults {
result: String,
}
fn task_completed_tool() -> Result<Arc<dyn Tool>, ToolError> {
FunctionTool::new(
FunctionToolConfig::new(TASK_COMPLETED_NAME, TASK_COMPLETED_DESCRIPTION),
|_ctx: Context, _args: TaskCompletedArgs| async move {
Ok::<_, ToolError>(TaskCompletedResults {
result: "Task completion signaled.".into(),
})
},
)
}
fn inject_sub_agents(
agents: &[Arc<dyn Agent>],
tool: &Arc<dyn Tool>,
visited: &mut HashSet<usize>,
) {
for sub in agents {
if !visited.insert(Arc::as_ptr(sub).cast::<()>() as usize) {
continue;
}
if let Some(state) = reveal(&**sub) {
state.live_injection.do_once(|| {
let has_completion_tool = state
.tools
.read()
.iter()
.any(|t| t.name() == TASK_COMPLETED_NAME);
if has_completion_tool {
return;
}
state.tools.write().push(Arc::clone(tool));
state
.instruction_suffix
.write()
.push_str(TASK_COMPLETED_INSTRUCTION_SUFFIX);
});
} else if sub.as_live().is_some() && !sub.sub_agents().is_empty() {
inject_sub_agents(sub.sub_agents(), tool, visited);
}
}
}
#[derive(Default)]
pub(crate) struct SequentialLiveSession {
state: parking_lot::Mutex<(Option<Arc<dyn LiveSession>>, bool)>,
}
impl SequentialLiveSession {
fn set_active(&self, sess: Arc<dyn LiveSession>) {
self.state.lock().0 = Some(sess);
}
}
#[async_trait]
impl LiveSession for SequentialLiveSession {
async fn send(&self, req: LiveRequest) -> Result<(), AgentError> {
let active = {
let g = self.state.lock();
if g.1 {
return Err(AgentError::other("session is closed"));
}
match &g.0 {
Some(s) => Arc::clone(s),
None => return Err(AgentError::other("no active sub-agent live session")),
}
};
active.send(req).await
}
async fn close(&self) -> Result<(), AgentError> {
let active = {
let mut g = self.state.lock();
g.1 = true;
g.0.clone()
};
match active {
Some(s) => s.close().await,
None => Ok(()),
}
}
fn as_any(&self) -> &dyn Any {
self
}
}
struct CloseOnDrop(Option<Arc<dyn LiveSession>>);
impl CloseOnDrop {
async fn close(mut self) {
if let Some(s) = self.0.take()
&& let Err(e) = s.close().await
{
tracing::warn!("error closing sub-session: {e}");
}
}
}
impl Drop for CloseOnDrop {
fn drop(&mut self) {
let Some(s) = self.0.take() else {
return;
};
if let Ok(h) = tokio::runtime::Handle::try_current() {
h.spawn(async move {
if let Err(e) = s.close().await {
tracing::warn!("error closing sub-session: {e}");
}
});
}
}
}
pub(crate) struct SequentialLive;
#[async_trait]
impl LiveAgent for SequentialLive {
async fn run_live(
&self,
ctx: InvocationContext,
) -> Result<(Arc<dyn LiveSession>, EventStream), AgentError> {
let sub_agents: Vec<Arc<dyn Agent>> = ctx.agent().sub_agents().to_vec();
if sub_agents.is_empty() {
return Err(AgentError::other("sequential agent has no sub-agents"));
}
let tool =
task_completed_tool().map_err(|e| wrap("failed to create task_completed tool", e))?;
inject_sub_agents(&sub_agents, &tool, &mut HashSet::new());
let seq_sess = Arc::new(SequentialLiveSession::default());
let stream = sequential_live_stream(ctx, sub_agents, Arc::clone(&seq_sess));
Ok((seq_sess, stream))
}
}
fn sequential_live_stream(
ctx: InvocationContext,
sub_agents: Vec<Arc<dyn Agent>>,
seq_sess: Arc<SequentialLiveSession>,
) -> EventStream {
Box::pin(async_stream::stream! {
for sub in sub_agents {
let Some(live) = sub.as_live() else {
yield Err(AgentError::other(format!(
"sub-agent {} does not support Live Run",
sub.name()
)));
return;
};
let sub_ctx = ctx.with_delta(ContextDelta {
agent: Some(Arc::clone(&sub)),
..Default::default()
});
let (sub_sess, mut inner) = match live.run_live(sub_ctx).await {
Ok(v) => v,
Err(e) => {
yield Err(wrap(format!("sub-agent {} RunLive failed", sub.name()), e));
return;
}
};
seq_sess.set_active(Arc::clone(&sub_sess));
let guard = CloseOnDrop(Some(sub_sess));
while let Some(item) = inner.next().await {
let failed = item.is_err();
yield item;
if failed {
guard.close().await;
return;
}
}
guard.close().await;
}
})
}