adk_agent/workflow/parallel_agent.rs
1#[cfg(feature = "skills")]
2use crate::skill_shim::load_skill_index;
3use crate::skill_shim::{SelectionPolicy, SkillIndex};
4use adk_core::{
5 AfterAgentCallback, Agent, BeforeAgentCallback, CallbackContext, Event, EventStream,
6 InvocationContext, Result, SharedState, WorkflowPosition,
7};
8use async_stream::stream;
9use async_trait::async_trait;
10use std::sync::Arc;
11
12use super::branch_context::{BranchContext, derive_sub_branch};
13use super::shared_state_context::SharedStateContext;
14
15/// Parallel agent executes sub-agents concurrently.
16///
17/// Each sub-agent runs on its own branch. When one of them escalates
18/// ([`EventActions::escalate`](adk_core::EventActions)), the others are stopped where they are
19/// and the escalation reaches the enclosing workflow, so a `LoopAgent` around the fan-out ends.
20pub struct ParallelAgent {
21 name: String,
22 description: String,
23 sub_agents: Vec<Arc<dyn Agent>>,
24 skills_index: Option<Arc<SkillIndex>>,
25 skill_policy: SelectionPolicy,
26 max_skill_chars: usize,
27 before_callbacks: Arc<Vec<BeforeAgentCallback>>,
28 after_callbacks: Arc<Vec<AfterAgentCallback>>,
29 shared_state_enabled: bool,
30}
31
32impl ParallelAgent {
33 /// Create a new parallel agent with the given name and sub-agents.
34 pub fn new(name: impl Into<String>, sub_agents: Vec<Arc<dyn Agent>>) -> Self {
35 Self {
36 name: name.into(),
37 description: String::new(),
38 sub_agents,
39 skills_index: None,
40 skill_policy: SelectionPolicy::default(),
41 max_skill_chars: 2000,
42 before_callbacks: Arc::new(Vec::new()),
43 after_callbacks: Arc::new(Vec::new()),
44 shared_state_enabled: false,
45 }
46 }
47
48 /// Set the agent description.
49 pub fn with_description(mut self, desc: impl Into<String>) -> Self {
50 self.description = desc.into();
51 self
52 }
53
54 /// Add a before-agent callback.
55 pub fn before_callback(mut self, callback: BeforeAgentCallback) -> Self {
56 if let Some(callbacks) = Arc::get_mut(&mut self.before_callbacks) {
57 callbacks.push(callback);
58 }
59 self
60 }
61
62 /// Add an after-agent callback.
63 pub fn after_callback(mut self, callback: AfterAgentCallback) -> Self {
64 if let Some(callbacks) = Arc::get_mut(&mut self.after_callbacks) {
65 callbacks.push(callback);
66 }
67 self
68 }
69
70 /// Set a preloaded skills index for this agent.
71 #[cfg(feature = "skills")]
72 pub fn with_skills(mut self, index: SkillIndex) -> Self {
73 self.skills_index = Some(Arc::new(index));
74 self
75 }
76
77 /// Auto-load skills from `.skills/` in the current working directory.
78 #[cfg(feature = "skills")]
79 pub fn with_auto_skills(self) -> Result<Self> {
80 self.with_skills_from_root(".")
81 }
82
83 /// Auto-load skills from `.skills/` under a custom root directory.
84 #[cfg(feature = "skills")]
85 pub fn with_skills_from_root(mut self, root: impl AsRef<std::path::Path>) -> Result<Self> {
86 let index = load_skill_index(root).map_err(|e| adk_core::AdkError::agent(e.to_string()))?;
87 self.skills_index = Some(Arc::new(index));
88 Ok(self)
89 }
90
91 /// Customize skill selection behavior.
92 #[cfg(feature = "skills")]
93 pub fn with_skill_policy(mut self, policy: SelectionPolicy) -> Self {
94 self.skill_policy = policy;
95 self
96 }
97
98 /// Limit injected skill content length.
99 #[cfg(feature = "skills")]
100 pub fn with_skill_budget(mut self, max_chars: usize) -> Self {
101 self.max_skill_chars = max_chars;
102 self
103 }
104
105 /// Enables shared state coordination for sub-agents.
106 ///
107 /// When enabled, a fresh `SharedState` instance is created for each
108 /// `run()` invocation and injected into each sub-agent's context.
109 /// Sub-agents can then use `ctx.shared_state()` to access the store.
110 pub fn with_shared_state(mut self) -> Self {
111 self.shared_state_enabled = true;
112 self
113 }
114}
115
116#[async_trait]
117impl Agent for ParallelAgent {
118 fn name(&self) -> &str {
119 &self.name
120 }
121
122 fn description(&self) -> &str {
123 &self.description
124 }
125
126 fn profile(&self) -> adk_core::AgentProfile {
127 adk_core::AgentProfile { kind: adk_core::AgentKind::Parallel, ..Default::default() }
128 }
129
130 fn sub_agents(&self) -> &[Arc<dyn Agent>] {
131 &self.sub_agents
132 }
133
134 fn supports_agent_transfer(&self) -> bool {
135 // Deterministic workflow agent: on cross-turn resumption the runner
136 // must restart from this root so every sub-agent runs again, rather
137 // than resuming a single sub-agent that responded last.
138 false
139 }
140
141 async fn run(&self, ctx: Arc<dyn InvocationContext>) -> Result<EventStream> {
142 // A call a person asked for needs an agent that holds it for their decision itself
143 // (spec 3.3 §7.4 rule 5).
144 if let Some(refused) = crate::requested_call::refused_by_root(
145 ctx.as_ref(),
146 &self.name,
147 crate::requested_call::RUNS_OTHER_AGENTS,
148 ) {
149 return Ok(refused);
150 }
151 let sub_agents = self.sub_agents.clone();
152 let run_ctx = super::skill_context::with_skill_injected_context(
153 ctx,
154 self.skills_index.as_ref(),
155 &self.skill_policy,
156 self.max_skill_chars,
157 );
158 let before_callbacks = self.before_callbacks.clone();
159 let after_callbacks = self.after_callbacks.clone();
160 let agent_name = self.name.clone();
161 let invocation_id = run_ctx.invocation_id().to_string();
162 let shared_state_enabled = self.shared_state_enabled;
163 // A run that resumes a hold runs only the sub-agents still holding calls; the
164 // siblings that finished in the run that held them do not run again.
165 let resuming: Vec<String> = run_ctx
166 .session()
167 .workflow_resume_positions(&agent_name, run_ctx.branch())
168 .into_iter()
169 .map(|position| position.sub_agent)
170 .filter(|name| sub_agents.iter().any(|agent| agent.name() == name))
171 .collect();
172 let names: Vec<String> = sub_agents.iter().map(|agent| agent.name().to_string()).collect();
173
174 let s = stream! {
175 use futures::stream::{StreamExt, select_all};
176
177 for callback in before_callbacks.as_ref() {
178 match callback(run_ctx.clone() as Arc<dyn CallbackContext>).await {
179 Ok(Some(content)) => {
180 let mut early_event = Event::new(&invocation_id);
181 early_event.author = agent_name.clone();
182 early_event.llm_response.content = Some(content);
183 yield Ok(early_event);
184
185 for after_callback in after_callbacks.as_ref() {
186 match after_callback(run_ctx.clone() as Arc<dyn CallbackContext>).await {
187 Ok(Some(after_content)) => {
188 let mut after_event = Event::new(&invocation_id);
189 after_event.author = agent_name.clone();
190 after_event.llm_response.content = Some(after_content);
191 yield Ok(after_event);
192 return;
193 }
194 Ok(None) => continue,
195 Err(e) => {
196 yield Err(e);
197 return;
198 }
199 }
200 }
201 return;
202 }
203 Ok(None) => continue,
204 Err(e) => {
205 yield Err(e);
206 return;
207 }
208 }
209 }
210
211
212 // Create shared state if enabled (fresh per run)
213 let shared = if shared_state_enabled {
214 Some(Arc::new(SharedState::new()))
215 } else {
216 None
217 };
218
219 // Each sub-agent gets its own stream that resolves `run()` and drains
220 // the resulting events. Merging these with `select_all` polls every
221 // sub-agent concurrently, which is what makes this agent parallel:
222 // `Agent::run` only *builds* an `EventStream`, so awaiting the run
223 // futures together is not enough — the streams themselves have to be
224 // polled together. Draining one stream to completion before touching
225 // the next made nominally parallel branches run one at a time.
226 //
227 // Polling from a single task also gives the backpressure the ADK
228 // Python and Go implementations arrange explicitly (a resume signal
229 // and an ack channel respectively): a sub-agent cannot run ahead
230 // while an already-produced event is still being consumed upstream,
231 // so the runner's per-event persistence stays in step with execution.
232 //
233 // Dropping the merged stream drops every sub-agent stream with it, so
234 // a consumer that stops early tears down in-flight sub-agents instead
235 // of leaving them running.
236 let mut merged = {
237 // Item is (sub-agent index, event result). The index lets a failure
238 // be attributed to the branch that produced it.
239 type BranchStream =
240 std::pin::Pin<Box<dyn futures::Stream<Item = (usize, Result<Event>)> + Send>>;
241 let mut per_agent: Vec<BranchStream> = Vec::with_capacity(sub_agents.len());
242
243 for (index, agent) in sub_agents.into_iter().enumerate() {
244 if !resuming.is_empty() && !resuming.iter().any(|name| name == agent.name()) {
245 continue;
246 }
247 let base: Arc<dyn InvocationContext> = if let Some(ref shared) = shared {
248 Arc::new(SharedStateContext::new(run_ctx.clone(), shared.clone()))
249 } else {
250 run_ctx.clone()
251 };
252
253 // Each sub-agent runs on its own branch, so a history read
254 // scoped by branch excludes what its siblings produced while
255 // still seeing the conversation that led to the fan-out. The
256 // shape mirrors ADK Python (`{parent}.{agent}.{sub_agent}`)
257 // and ADK Go.
258 let branch = derive_sub_branch(
259 base.branch(),
260 &format!("{agent_name}.{}", agent.name()),
261 );
262 let ctx: Arc<dyn InvocationContext> =
263 Arc::new(BranchContext::new(base, branch.clone()));
264
265 per_agent.push(Box::pin(stream! {
266 match agent.run(ctx).await {
267 Ok(mut events) => {
268 while let Some(event_result) = events.next().await {
269 let failed = event_result.is_err();
270 // Record which branch produced the event so a
271 // later branch-scoped history read can exclude
272 // it from siblings. A nested workflow may have
273 // already stamped a deeper branch; leave it.
274 let event_result = event_result.map(|mut event| {
275 if event.branch.is_empty() {
276 event.branch = branch.clone();
277 }
278 event
279 });
280 yield (index, event_result);
281 if failed {
282 // Abandon this branch, leave the others running.
283 break;
284 }
285 }
286 }
287 Err(e) => yield (index, Err(e)),
288 }
289 }));
290 }
291
292 select_all(per_agent)
293 };
294
295 // Errors are collected with their sub-agent index so the reported
296 // error stays deterministic. With branches running concurrently,
297 // "whichever failed first" would be a race; the lowest index matches
298 // the declared sub-agent order this agent was constructed with.
299 let mut failures: Vec<(usize, adk_core::AdkError)> = Vec::new();
300 let mut held = false;
301
302 while let Some((index, event_result)) = merged.next().await {
303 match event_result {
304 Ok(mut event) => {
305 if event.actions.tool_confirmation.is_some() {
306 held = true;
307 event.actions.workflow_positions.insert(
308 agent_name.clone(),
309 WorkflowPosition::new(0, names[index].clone()),
310 );
311 }
312 let escalates = event.actions.escalate;
313 yield Ok(event);
314 if escalates {
315 tracing::info!(
316 agent.name = %agent_name,
317 sub_agent.name = %names[index],
318 "a branch escalated; stopping the other branches"
319 );
320 break;
321 }
322 }
323 Err(e) => failures.push((index, e)),
324 }
325 }
326 // An escalation ends the fan-out: the branches still running stop where they are.
327 drop(merged);
328
329 // After all agents complete, propagate the first error if any
330 if let Some((_, e)) = failures.into_iter().min_by_key(|(index, _)| *index) {
331 yield Err(e);
332 return;
333 }
334
335 // A held call pauses the workflow once every branch has finished; the next run
336 // resumes the branches that hold calls, and the after-agent callbacks wait for it.
337 if held {
338 tracing::info!(agent.name = %agent_name, "workflow paused on a held tool call");
339 return;
340 }
341
342 for callback in after_callbacks.as_ref() {
343 match callback(run_ctx.clone() as Arc<dyn CallbackContext>).await {
344 Ok(Some(content)) => {
345 let mut after_event = Event::new(&invocation_id);
346 after_event.author = agent_name.clone();
347 after_event.llm_response.content = Some(content);
348 yield Ok(after_event);
349 break;
350 }
351 Ok(None) => continue,
352 Err(e) => {
353 yield Err(e);
354 return;
355 }
356 }
357 }
358 };
359
360 Ok(Box::pin(s))
361 }
362}