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, Content, Event, EventStream,
6 InvocationContext, Part, ReadonlyContext, Result, Session, State, WorkflowPosition,
7};
8use async_stream::stream;
9use async_trait::async_trait;
10use std::collections::HashMap;
11use std::sync::{Arc, RwLock};
12
13pub const DEFAULT_LOOP_MAX_ITERATIONS: u32 = 1000;
16
17pub struct LoopAgent {
19 name: String,
20 description: String,
21 sub_agents: Vec<Arc<dyn Agent>>,
22 max_iterations: u32,
23 skills_index: Option<Arc<SkillIndex>>,
24 skill_policy: SelectionPolicy,
25 max_skill_chars: usize,
26 before_callbacks: Arc<Vec<BeforeAgentCallback>>,
27 after_callbacks: Arc<Vec<AfterAgentCallback>>,
28}
29
30impl LoopAgent {
31 pub fn new(name: impl Into<String>, sub_agents: Vec<Arc<dyn Agent>>) -> Self {
33 Self {
34 name: name.into(),
35 description: String::new(),
36 sub_agents,
37 max_iterations: DEFAULT_LOOP_MAX_ITERATIONS,
38 skills_index: None,
39 skill_policy: SelectionPolicy::default(),
40 max_skill_chars: 2000,
41 before_callbacks: Arc::new(Vec::new()),
42 after_callbacks: Arc::new(Vec::new()),
43 }
44 }
45
46 pub fn with_description(mut self, desc: impl Into<String>) -> Self {
48 self.description = desc.into();
49 self
50 }
51
52 pub fn with_max_iterations(mut self, max: u32) -> Self {
66 self.max_iterations = max;
67 self
68 }
69
70 #[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 #[cfg(feature = "skills")]
79 pub fn with_auto_skills(self) -> Result<Self> {
80 self.with_skills_from_root(".")
81 }
82
83 #[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 #[cfg(feature = "skills")]
93 pub fn with_skill_policy(mut self, policy: SelectionPolicy) -> Self {
94 self.skill_policy = policy;
95 self
96 }
97
98 #[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 pub fn before_callback(mut self, callback: BeforeAgentCallback) -> Self {
107 if let Some(callbacks) = Arc::get_mut(&mut self.before_callbacks) {
108 callbacks.push(callback);
109 }
110 self
111 }
112
113 pub fn after_callback(mut self, callback: AfterAgentCallback) -> Self {
115 if let Some(callbacks) = Arc::get_mut(&mut self.after_callbacks) {
116 callbacks.push(callback);
117 }
118 self
119 }
120}
121
122struct HistoryTrackingSession {
129 parent_ctx: Arc<dyn InvocationContext>,
130 history: RwLock<TrackedHistory>,
131 streamed_id: RwLock<Option<String>>,
133 state: StateTrackingState,
134}
135
136#[derive(Default)]
139struct TrackedHistory {
140 contents: Vec<Content>,
141 origins: Vec<Option<(String, String)>>,
142}
143
144impl TrackedHistory {
145 fn push(&mut self, content: Content, origin: Option<(String, String)>) {
146 self.contents.push(content);
147 self.origins.push(origin);
148 }
149
150 fn last_from(&self, origin: &(String, String)) -> bool {
152 matches!(self.origins.last(), Some(Some(last)) if last == origin)
153 }
154}
155
156struct StateTrackingState {
157 values: RwLock<HashMap<String, serde_json::Value>>,
158}
159
160impl StateTrackingState {
161 fn new(parent_ctx: &Arc<dyn InvocationContext>) -> Self {
162 Self { values: RwLock::new(parent_ctx.session().state().all()) }
163 }
164
165 fn apply_delta(&self, delta: &HashMap<String, serde_json::Value>) {
166 if delta.is_empty() {
167 return;
168 }
169
170 let mut values = self.values.write().unwrap_or_else(|e| e.into_inner());
171 for (key, value) in delta {
172 values.insert(key.clone(), value.clone());
173 }
174 }
175}
176
177impl State for StateTrackingState {
178 fn get(&self, key: &str) -> Option<serde_json::Value> {
179 self.values.read().unwrap_or_else(|e| e.into_inner()).get(key).cloned()
180 }
181
182 fn set(&mut self, key: String, value: serde_json::Value) {
183 if let Err(msg) = adk_core::validate_state_key(&key) {
184 tracing::warn!(key = %key, "rejecting invalid state key: {msg}");
185 return;
186 }
187 self.values.write().unwrap_or_else(|e| e.into_inner()).insert(key, value);
188 }
189
190 fn all(&self) -> HashMap<String, serde_json::Value> {
191 self.values.read().unwrap_or_else(|e| e.into_inner()).clone()
192 }
193}
194
195impl HistoryTrackingSession {
196 fn new(parent_ctx: Arc<dyn InvocationContext>) -> Self {
197 let mut history = TrackedHistory::default();
198 for content in parent_ctx.session().conversation_history() {
199 history.push(content, None);
200 }
201 Self {
202 history: RwLock::new(history),
203 streamed_id: RwLock::new(None),
204 state: StateTrackingState::new(&parent_ctx),
205 parent_ctx,
206 }
207 }
208
209 fn delegates(&self) -> bool {
211 self.parent_ctx.session().records_invocation_events()
212 }
213
214 fn apply_event(&self, event: &Event) {
215 if let Some(content) = &event.llm_response.content {
216 let origin = (event.author.clone(), event.branch.clone());
217 let mut history = self.history.write().unwrap_or_else(|e| e.into_inner());
222 let mut streamed_id = self.streamed_id.write().unwrap_or_else(|e| e.into_inner());
223 let unplaced;
226 let content = if !event.llm_response.partial
227 && content.parts.iter().any(|part| matches!(part, Part::FunctionResponse { .. }))
228 {
229 unplaced =
230 adk_core::supersede_pending_responses(&mut history.contents, content.clone());
231 match &unplaced {
232 Some(rest) => rest,
233 None => {
234 *streamed_id = None;
235 drop(history);
236 drop(streamed_id);
237 self.state.apply_delta(&event.actions.state_delta);
238 return;
239 }
240 }
241 } else {
242 content
243 };
244 let continues_stream = streamed_id.as_deref() == Some(event.id.as_str());
245 let same_author = history.last_from(&origin);
246
247 if event.llm_response.partial {
248 if continues_stream
251 && same_author
252 && let Some(last) = history.contents.last_mut()
253 && last.role == content.role
254 {
255 merge_parts(last, &content.parts);
256 return;
257 }
258 history.push(content.clone(), Some(origin));
260 *streamed_id = Some(event.id.clone());
261 } else {
262 let content_complete = event
263 .llm_response
264 .provider_metadata
265 .as_ref()
266 .and_then(|metadata| metadata.get("content_complete"))
267 .and_then(serde_json::Value::as_bool)
268 == Some(true);
269 let replaced_stream = continues_stream && content_complete && same_author;
270 *streamed_id = None;
271 if replaced_stream && let Some(last) = history.contents.last_mut() {
272 *last = content.clone();
274 } else if continues_stream
275 && same_author
276 && let Some(last) = history.contents.last_mut()
277 && last.role == content.role
278 {
279 merge_parts(last, &content.parts);
283 } else if !content.parts.is_empty() {
284 history.push(content.clone(), Some(origin));
285 }
286 }
287 }
288 self.state.apply_delta(&event.actions.state_delta);
289 }
290}
291
292fn merge_parts(last: &mut Content, parts: &[Part]) {
294 for part in parts {
295 if let Part::Text { text } = part
296 && let Some(Part::Text { text: existing }) = last.parts.last_mut()
297 {
298 existing.push_str(text);
299 } else {
300 last.parts.push(part.clone());
301 }
302 }
303}
304
305impl Session for HistoryTrackingSession {
306 fn id(&self) -> &str {
307 self.parent_ctx.session().id()
308 }
309
310 fn app_name(&self) -> &str {
311 self.parent_ctx.session().app_name()
312 }
313
314 fn user_id(&self) -> &str {
315 self.parent_ctx.session().user_id()
316 }
317
318 fn state(&self) -> &dyn State {
319 &self.state
320 }
321
322 fn conversation_history(&self) -> Vec<Content> {
323 if self.delegates() {
324 return self.parent_ctx.session().conversation_history();
325 }
326 self.history.read().unwrap_or_else(|e| e.into_inner()).contents.clone()
327 }
328
329 fn conversation_history_for_agent(&self, agent_name: &str) -> Vec<Content> {
330 if self.delegates() {
331 return self.parent_ctx.session().conversation_history_for_agent(agent_name);
332 }
333 self.conversation_history()
334 }
335
336 fn conversation_history_scoped(&self, agent_name: Option<&str>, branch: &str) -> Vec<Content> {
337 if self.delegates() {
338 return self.parent_ctx.session().conversation_history_scoped(agent_name, branch);
339 }
340 self.conversation_history()
341 }
342
343 fn conversation_history_with_context(&self, agent_name: &str, branch: &str) -> Vec<Content> {
344 if self.delegates() {
345 return self.parent_ctx.session().conversation_history_with_context(agent_name, branch);
346 }
347 let history = self.history.read().unwrap_or_else(|e| e.into_inner());
348 let call_ids: std::collections::HashSet<String> = history
349 .contents
350 .iter()
351 .flat_map(|content| content.parts.iter())
352 .filter_map(|part| match part {
353 Part::FunctionCall { id: Some(id), .. } => Some(id.clone()),
354 _ => None,
355 })
356 .collect();
357 history
358 .contents
359 .iter()
360 .zip(&history.origins)
361 .filter_map(|(content, origin)| match origin {
362 Some((_, event_branch))
363 if adk_core::history::is_tool_branch_event(branch, event_branch, &call_ids) =>
364 {
365 None
366 }
367 Some((author, _)) if author != "user" && author != agent_name => {
368 adk_core::history::other_agent_context(author, content)
369 }
370 Some(_) | None => Some(content.clone()),
371 })
372 .collect()
373 }
374
375 fn records_invocation_events(&self) -> bool {
376 self.delegates()
377 }
378
379 fn held_tool_calls(&self, agent_name: &str, branch: &str) -> Vec<adk_core::HeldToolCall> {
380 self.parent_ctx.session().held_tool_calls(agent_name, branch)
381 }
382
383 fn workflow_resume_positions(
384 &self,
385 workflow: &str,
386 branch: &str,
387 ) -> Vec<adk_core::WorkflowPosition> {
388 self.parent_ctx.session().workflow_resume_positions(workflow, branch)
389 }
390
391 fn append_to_history(&self, content: Content) {
392 if self.delegates() {
393 self.parent_ctx.session().append_to_history(content);
394 return;
395 }
396 self.history.write().unwrap_or_else(|e| e.into_inner()).push(content, None);
397 }
398}
399
400#[cfg(test)]
402pub(crate) fn history_tracking_context_for_test(
403 parent: Arc<dyn InvocationContext>,
404) -> Arc<dyn InvocationContext> {
405 Arc::new(HistoryTrackingContext::new(parent))
406}
407
408struct HistoryTrackingContext {
409 parent_ctx: Arc<dyn InvocationContext>,
410 session: HistoryTrackingSession,
411}
412
413impl HistoryTrackingContext {
414 fn new(parent_ctx: Arc<dyn InvocationContext>) -> Self {
415 let session = HistoryTrackingSession::new(parent_ctx.clone());
416 Self { parent_ctx, session }
417 }
418
419 fn apply_event(&self, event: &Event) {
420 self.session.apply_event(event);
421 }
422}
423
424#[async_trait]
425impl adk_core::ReadonlyContext for HistoryTrackingContext {
426 fn invocation_id(&self) -> &str {
427 self.parent_ctx.invocation_id()
428 }
429
430 fn agent_name(&self) -> &str {
431 self.parent_ctx.agent_name()
432 }
433
434 fn user_id(&self) -> &str {
435 self.parent_ctx.user_id()
436 }
437
438 fn app_name(&self) -> &str {
439 self.parent_ctx.app_name()
440 }
441
442 fn session_id(&self) -> &str {
443 self.parent_ctx.session_id()
444 }
445
446 fn branch(&self) -> &str {
447 self.parent_ctx.branch()
448 }
449
450 fn user_content(&self) -> &Content {
451 self.parent_ctx.user_content()
452 }
453
454 fn acting_context(&self) -> adk_core::ActingContext {
455 self.parent_ctx.acting_context()
456 }
457
458 fn is_authenticated(&self) -> bool {
459 self.parent_ctx.is_authenticated()
460 }
461}
462
463#[async_trait]
464impl CallbackContext for HistoryTrackingContext {
465 fn artifacts(&self) -> Option<Arc<dyn adk_core::Artifacts>> {
466 self.parent_ctx.artifacts()
467 }
468
469 fn shared_state(&self) -> Option<Arc<adk_core::SharedState>> {
470 self.parent_ctx.shared_state()
471 }
472}
473
474#[async_trait]
475impl InvocationContext for HistoryTrackingContext {
476 fn agent(&self) -> Arc<dyn Agent> {
477 self.parent_ctx.agent()
478 }
479
480 fn memory(&self) -> Option<Arc<dyn adk_core::Memory>> {
481 self.parent_ctx.memory()
482 }
483
484 fn session(&self) -> &dyn Session {
485 &self.session
486 }
487
488 fn run_config(&self) -> &adk_core::RunConfig {
489 self.parent_ctx.run_config()
490 }
491
492 fn end_invocation(&self) {
493 self.parent_ctx.end_invocation();
494 }
495
496 fn ended(&self) -> bool {
497 self.parent_ctx.ended()
498 }
499
500 fn is_cancelled(&self) -> bool {
501 self.parent_ctx.is_cancelled()
502 }
503
504 fn user_scopes(&self) -> Vec<String> {
505 self.parent_ctx.user_scopes()
506 }
507
508 fn request_metadata(&self) -> HashMap<String, serde_json::Value> {
509 self.parent_ctx.request_metadata()
510 }
511
512 fn authoritative_transfer_targets(&self) -> bool {
513 self.parent_ctx.authoritative_transfer_targets()
514 }
515 fn delegation_depth(&self) -> u32 {
516 self.parent_ctx.delegation_depth()
517 }
518 fn max_delegation_depth(&self) -> Option<u32> {
519 self.parent_ctx.max_delegation_depth()
520 }
521
522 fn orchestration_root_invocation_id(&self) -> &str {
523 self.parent_ctx.orchestration_root_invocation_id()
524 }
525
526 fn orchestration_edge_id(&self) -> Option<&str> {
527 self.parent_ctx.orchestration_edge_id()
528 }
529
530 fn requires_tool_confirmation(&self, tool_name: &str) -> bool {
531 self.parent_ctx.requires_tool_confirmation(tool_name)
532 }
533
534 fn steering_inbox(&self) -> Option<adk_core::SteeringInbox> {
535 self.parent_ctx.steering_inbox()
536 }
537
538 async fn get_secret(&self, name: &str) -> adk_core::Result<Option<String>> {
539 self.parent_ctx.get_secret(name).await
540 }
541
542 async fn get_secret_for(
543 &self,
544 request: &adk_core::SecretRequest,
545 ) -> adk_core::Result<Option<String>> {
546 self.parent_ctx.get_secret_for(request).await
547 }
548}
549
550fn resume_point(
553 positions: &[WorkflowPosition],
554 sub_agents: &[Arc<dyn Agent>],
555 max_iterations: u32,
556) -> Option<(u32, usize)> {
557 positions
558 .iter()
559 .filter(|position| position.iteration < max_iterations)
560 .filter_map(|position| {
561 let index = sub_agents.iter().position(|agent| agent.name() == position.sub_agent)?;
562 Some((position.iteration, index))
563 })
564 .min()
565}
566
567#[async_trait]
568impl Agent for LoopAgent {
569 fn name(&self) -> &str {
570 &self.name
571 }
572
573 fn description(&self) -> &str {
574 &self.description
575 }
576
577 fn profile(&self) -> adk_core::AgentProfile {
578 adk_core::AgentProfile {
579 kind: adk_core::AgentKind::Loop {
580 max_iterations: (self.max_iterations > 0).then_some(self.max_iterations),
581 },
582 ..Default::default()
583 }
584 }
585
586 fn sub_agents(&self) -> &[Arc<dyn Agent>] {
587 &self.sub_agents
588 }
589
590 fn supports_agent_transfer(&self) -> bool {
591 false
595 }
596
597 async fn run(&self, ctx: Arc<dyn InvocationContext>) -> Result<EventStream> {
598 if let Some(refused) = crate::requested_call::refused_by_root(
601 ctx.as_ref(),
602 &self.name,
603 crate::requested_call::RUNS_OTHER_AGENTS,
604 ) {
605 return Ok(refused);
606 }
607 let sub_agents = self.sub_agents.clone();
608 let max_iterations = self.max_iterations;
609 let before_callbacks = self.before_callbacks.clone();
610 let after_callbacks = self.after_callbacks.clone();
611 let agent_name = self.name.clone();
612 let run_ctx = super::skill_context::with_skill_injected_context(
613 ctx,
614 self.skills_index.as_ref(),
615 &self.skill_policy,
616 self.max_skill_chars,
617 );
618 let run_ctx = Arc::new(HistoryTrackingContext::new(run_ctx));
619 let resume_at = resume_point(
620 &run_ctx.session().workflow_resume_positions(&agent_name, run_ctx.branch()),
621 &sub_agents,
622 max_iterations,
623 );
624
625 let s = stream! {
626 use futures::StreamExt;
627
628 for callback in before_callbacks.as_ref() {
630 match callback(run_ctx.clone() as Arc<dyn CallbackContext>).await {
631 Ok(Some(content)) => {
632 let mut early_event = Event::new(run_ctx.invocation_id());
633 early_event.author = agent_name.clone();
634 early_event.llm_response.content = Some(content);
635 yield Ok(early_event);
636
637 for after_cb in after_callbacks.as_ref() {
638 match after_cb(run_ctx.clone() as Arc<dyn CallbackContext>).await {
639 Ok(Some(after_content)) => {
640 let mut after_event = Event::new(run_ctx.invocation_id());
641 after_event.author = agent_name.clone();
642 after_event.llm_response.content = Some(after_content);
643 yield Ok(after_event);
644 return;
645 }
646 Ok(None) => continue,
647 Err(e) => { yield Err(e); return; }
648 }
649 }
650 return;
651 }
652 Ok(None) => continue,
653 Err(e) => { yield Err(e); return; }
654 }
655 }
656
657 let (first_iteration, mut first_index) = resume_at.unwrap_or((0, 0));
662 for iteration in first_iteration..max_iterations {
663 let mut should_exit = false;
664
665 for (index, agent) in sub_agents.iter().enumerate().skip(first_index) {
666 let mut stream = agent.run(run_ctx.clone() as Arc<dyn InvocationContext>).await?;
667 let mut held = false;
668
669 while let Some(result) = stream.next().await {
670 match result {
671 Ok(mut event) => {
672 if event.actions.tool_confirmation.is_some() {
673 held = true;
674 event.actions.workflow_positions.insert(
675 agent_name.clone(),
676 WorkflowPosition::new(iteration, agent.name()),
677 );
678 }
679 run_ctx.apply_event(&event);
680 if event.actions.escalate {
681 should_exit = true;
682 }
683 yield Ok(event);
684 }
685 Err(e) => {
686 yield Err(e);
687 return;
688 }
689 }
690 }
691
692 if held {
695 tracing::info!(
696 agent.name = %agent_name,
697 workflow.iteration = iteration,
698 workflow.sub_agent = %agent.name(),
699 workflow.index = index,
700 "workflow paused on a held tool call"
701 );
702 return;
703 }
704
705 if should_exit {
706 break;
707 }
708 }
709 first_index = 0;
710
711 if should_exit {
712 break;
713 }
714 }
715
716 for callback in after_callbacks.as_ref() {
718 match callback(run_ctx.clone() as Arc<dyn CallbackContext>).await {
719 Ok(Some(content)) => {
720 let mut after_event = Event::new(run_ctx.invocation_id());
721 after_event.author = agent_name.clone();
722 after_event.llm_response.content = Some(content);
723 yield Ok(after_event);
724 break;
725 }
726 Ok(None) => continue,
727 Err(e) => { yield Err(e); return; }
728 }
729 }
730 };
731
732 Ok(Box::pin(s))
733 }
734}