Skip to main content

gadk_engine/agents/
sequential_agent.rs

1// Copyright 2026 Chris Olson
2// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! A sequential agent: runs its sub-agents once each, in the order they are listed.
17
18use std::any::Any;
19use std::collections::HashSet;
20use std::sync::Arc;
21
22use async_trait::async_trait;
23use futures::StreamExt;
24use gadk_agent::{
25    Agent, AgentConfig, AgentError, AgentState, AgentType, Context, ContextDelta, EventStream,
26    InvocationContext, LiveAgent, LiveRequest, LiveSession, Tool, ToolError,
27};
28use schemars::JsonSchema;
29use serde::{Deserialize, Serialize};
30
31use crate::agents::graph_resume::graph_resume_indexes;
32use crate::llm::state::reveal;
33use crate::runner::wrap;
34use crate::tool::{FunctionTool, FunctionToolConfig};
35
36/// The configuration of a sequential agent.
37#[derive(Clone, Default)]
38pub struct SequentialAgentConfig {
39    /// Basic agent setup; `run` must be `None`.
40    pub agent: AgentConfig,
41}
42
43/// An agent that runs its sub-agents once, in the order they are listed. Use it when execution
44/// must happen in a fixed, strict order.
45pub fn new(cfg: SequentialAgentConfig) -> Result<Arc<dyn Agent>, AgentError> {
46    if cfg.agent.run.is_some() {
47        return Err(AgentError::Config(
48            "SequentialAgent doesn't allow custom Run implementations".into(),
49        ));
50    }
51    let mut agent_cfg = cfg.agent.clone();
52    agent_cfg.run = Some(Arc::new(run));
53    gadk_agent::new_with_state(
54        agent_cfg,
55        AgentState {
56            agent_type: AgentType::SequentialAgent,
57            config: Some(Arc::new(cfg)),
58            on_before_agent_callback_event: None,
59            // The returned agent supports live runs.
60            live: Some(Arc::new(SequentialLive)),
61        },
62    )
63    .map_err(|e| AgentError::Config(format!("failed to create base agent: {e}")))
64}
65
66/// Runs the sub-agents in order.
67fn run(ctx: InvocationContext) -> EventStream {
68    Box::pin(async_stream::stream! {
69        let mut subs: Vec<Arc<dyn Agent>> = ctx.agent().sub_agents().to_vec();
70        // Resuming a nested graph workflow starts from the sub-agent holding the lowest-indexed
71        // caller.
72        if let Some(&first) = graph_resume_indexes(&ctx).as_ref().and_then(|ix| ix.first()) {
73            subs.drain(..first);
74        }
75        for sub in subs {
76            let mut s = sub.run(ctx.clone());
77            while let Some(item) = s.next().await {
78                // A failed sub-agent ends the sequence, as in adk-python: later sub-agents would
79                // run without the output they depend on.
80                let failed = item.is_err();
81                yield item;
82                if failed {
83                    return;
84                }
85            }
86        }
87    })
88}
89
90/// Name of the `task_completed` tool.
91const TASK_COMPLETED_NAME: &str = "task_completed";
92/// Description of the `task_completed` tool.
93const TASK_COMPLETED_DESCRIPTION: &str =
94    "Signals that the agent has successfully completed the user's question or task.";
95/// Instruction suffix appended once to each LLM agent the `task_completed` tool is injected into.
96pub(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.";
97
98// The arguments of `task_completed`: none. A plain comment: a doc comment would become the
99// schema's `description`, which an empty-object schema should not have.
100#[derive(Deserialize, JsonSchema)]
101struct TaskCompletedArgs {}
102
103// The result of `task_completed`: `{"result": "<text>"}`.
104#[derive(Serialize, JsonSchema)]
105struct TaskCompletedResults {
106    result: String,
107}
108
109/// Builds the `task_completed` function tool, which the model calls to hand over to the next
110/// sub-agent.
111fn task_completed_tool() -> Result<Arc<dyn Tool>, ToolError> {
112    FunctionTool::new(
113        FunctionToolConfig::new(TASK_COMPLETED_NAME, TASK_COMPLETED_DESCRIPTION),
114        |_ctx: Context, _args: TaskCompletedArgs| async move {
115            Ok::<_, ToolError>(TaskCompletedResults {
116                result: "Task completion signaled.".into(),
117            })
118        },
119    )
120}
121
122/// Each LLM agent gets the tool and the suffix exactly once, through its `live_injection` latch
123/// (a caller-provided `task_completed` is left untouched); live-capable composites with children
124/// are recursed into; anything else is left alone. `visited` is keyed by the agent's `Arc`
125/// address.
126fn inject_sub_agents(
127    agents: &[Arc<dyn Agent>],
128    tool: &Arc<dyn Tool>,
129    visited: &mut HashSet<usize>,
130) {
131    for sub in agents {
132        if !visited.insert(Arc::as_ptr(sub).cast::<()>() as usize) {
133            continue;
134        }
135        if let Some(state) = reveal(&**sub) {
136            // Live callers must observe the completed injection before using the shared tool
137            // list and instruction: do_once blocks concurrent callers until it finishes.
138            state.live_injection.do_once(|| {
139                let has_completion_tool = state
140                    .tools
141                    .read()
142                    .iter()
143                    .any(|t| t.name() == TASK_COMPLETED_NAME);
144                if has_completion_tool {
145                    return;
146                }
147                state.tools.write().push(Arc::clone(tool));
148                state
149                    .instruction_suffix
150                    .write()
151                    .push_str(TASK_COMPLETED_INSTRUCTION_SUFFIX);
152            });
153        } else if sub.as_live().is_some() && !sub.sub_agents().is_empty() {
154            inject_sub_agents(sub.sub_agents(), tool, visited);
155        }
156    }
157}
158
159/// The live session of a sequential agent: forwards `send` to the active sub-agent's session.
160///
161/// `close()` closes only the active sub-session; it does not stop the sequence. Once that
162/// sub-agent's stream ends, the next sub-agent starts, but `send` keeps refusing with
163/// "session is closed" because the closed flag stays set. To end the whole run, drop the event
164/// stream.
165#[derive(Default)]
166pub(crate) struct SequentialLiveSession {
167    /// (active sub-session, closed).
168    state: parking_lot::Mutex<(Option<Arc<dyn LiveSession>>, bool)>,
169}
170
171impl SequentialLiveSession {
172    /// Records the sub-agent session that `send` forwards to.
173    fn set_active(&self, sess: Arc<dyn LiveSession>) {
174        self.state.lock().0 = Some(sess);
175    }
176}
177
178#[async_trait]
179impl LiveSession for SequentialLiveSession {
180    /// Forwards the request to the active sub-session. The lock is released before the forwarded
181    /// send is awaited.
182    async fn send(&self, req: LiveRequest) -> Result<(), AgentError> {
183        let active = {
184            let g = self.state.lock();
185            if g.1 {
186                return Err(AgentError::other("session is closed"));
187            }
188            match &g.0 {
189                Some(s) => Arc::clone(s),
190                None => return Err(AgentError::other("no active sub-agent live session")),
191            }
192        };
193        active.send(req).await
194    }
195
196    /// Marks the session closed and closes the active sub-session.
197    async fn close(&self) -> Result<(), AgentError> {
198        let active = {
199            let mut g = self.state.lock();
200            g.1 = true;
201            g.0.clone()
202        };
203        match active {
204            Some(s) => s.close().await,
205            None => Ok(()),
206        }
207    }
208
209    fn as_any(&self) -> &dyn Any {
210        self
211    }
212}
213
214/// Closes a sub-session: inline through [`CloseOnDrop::close`], or, when the consumer drops the
215/// stream mid-sub-agent, from a spawned task.
216struct CloseOnDrop(Option<Arc<dyn LiveSession>>);
217
218impl CloseOnDrop {
219    async fn close(mut self) {
220        if let Some(s) = self.0.take()
221            && let Err(e) = s.close().await
222        {
223            tracing::warn!("error closing sub-session: {e}");
224        }
225    }
226}
227
228impl Drop for CloseOnDrop {
229    fn drop(&mut self) {
230        let Some(s) = self.0.take() else {
231            return;
232        };
233        if let Ok(h) = tokio::runtime::Handle::try_current() {
234            h.spawn(async move {
235                if let Err(e) = s.close().await {
236                    tracing::warn!("error closing sub-session: {e}");
237                }
238            });
239        }
240    }
241}
242
243/// The live entry point of a sequential agent, installed as `AgentState.live` by [`new`].
244/// Stateless: it reads the sub-agents from `ctx.agent()`.
245pub(crate) struct SequentialLive;
246
247#[async_trait]
248impl LiveAgent for SequentialLive {
249    /// Runs the sub-agents' live sessions in turn.
250    ///
251    /// Before any sub-agent runs, every LLM sub-agent (recursing into live-capable composites
252    /// with children) is given the `task_completed` tool and an instruction suffix telling the
253    /// model to call it. This injection is permanent: it changes that agent's later non-live runs
254    /// too, and it happens at most once per agent (a panicking injection is retried by the next
255    /// caller).
256    ///
257    /// The returned stream runs each sub-agent's live session in turn; the returned session
258    /// forwards `send` to the active one. A sub-agent that is not live-capable ends the stream
259    /// with `sub-agent <name> does not support Live Run` when its turn comes, after the earlier
260    /// sub-agents have run (the check is lazy, per sub-agent). A sub-agent's error is
261    /// forwarded and ends the sequence, closing that sub-agent's live session, as in Run.
262    async fn run_live(
263        &self,
264        ctx: InvocationContext,
265    ) -> Result<(Arc<dyn LiveSession>, EventStream), AgentError> {
266        let sub_agents: Vec<Arc<dyn Agent>> = ctx.agent().sub_agents().to_vec();
267        if sub_agents.is_empty() {
268            return Err(AgentError::other("sequential agent has no sub-agents"));
269        }
270        let tool =
271            task_completed_tool().map_err(|e| wrap("failed to create task_completed tool", e))?;
272        inject_sub_agents(&sub_agents, &tool, &mut HashSet::new());
273
274        let seq_sess = Arc::new(SequentialLiveSession::default());
275        let stream = sequential_live_stream(ctx, sub_agents, Arc::clone(&seq_sess));
276        Ok((seq_sess, stream))
277    }
278}
279
280/// The event stream of a sequential live run: runs each sub-agent's live session in turn and
281/// records it as the active one.
282fn sequential_live_stream(
283    ctx: InvocationContext,
284    sub_agents: Vec<Arc<dyn Agent>>,
285    seq_sess: Arc<SequentialLiveSession>,
286) -> EventStream {
287    Box::pin(async_stream::stream! {
288        for sub in sub_agents {
289            let Some(live) = sub.as_live() else {
290                yield Err(AgentError::other(format!(
291                    "sub-agent {} does not support Live Run",
292                    sub.name()
293                )));
294                return;
295            };
296            let sub_ctx = ctx.with_delta(ContextDelta {
297                agent: Some(Arc::clone(&sub)),
298                ..Default::default()
299            });
300            let (sub_sess, mut inner) = match live.run_live(sub_ctx).await {
301                Ok(v) => v,
302                Err(e) => {
303                    yield Err(wrap(format!("sub-agent {} live run failed", sub.name()), e));
304                    return;
305                }
306            };
307            seq_sess.set_active(Arc::clone(&sub_sess));
308            // Dropping the stream here closes the sub-session from a spawned task.
309            let guard = CloseOnDrop(Some(sub_sess));
310            while let Some(item) = inner.next().await {
311                // A failed sub-agent ends the sequence, as in Run: its live session is closed and
312                // no later sub-agent starts.
313                let failed = item.is_err();
314                yield item;
315                if failed {
316                    guard.close().await;
317                    return;
318                }
319            }
320            guard.close().await;
321        }
322    })
323}