1use std::collections::{BTreeMap, HashMap, HashSet};
51use std::sync::{Arc, Mutex};
52
53use adk_core::subagent::{
54 FORK_INVOCATION_PREFIX, RUN_LIMITS_INPUT_KEY, RunLimits, SUBAGENT_FINISHED_CODE,
55 SUBAGENT_INPUT_KEY, notice_header, subagent_not_found, subagent_notice, subagent_refused,
56};
57use adk_core::{
58 AdkError, AdkIdentity, AppName, Content, DurableRunStore, Enqueued, ErrorCategory,
59 ErrorComponent, FollowUp, NewRun, OnConflict, Part, Result, RunBudget, RunFilter, RunRecord,
60 RunState, STEER_NO_ACTIVE_RUN_CODE, SessionId, SteerOutcome, SteerReceipt, SubagentHost,
61 SubagentLaunch, SubagentParent, SubagentRecord, SubagentScope, SubagentStart, SubagentStatus,
62 SubagentTarget, UserId,
63};
64use adk_runner::Runner;
65use adk_session::{CreateRequest, GetRequest, SessionService};
66use async_trait::async_trait;
67use serde_json::{Value, json};
68
69use super::worker::{ParkReason, WorkerHooks};
70
71const STEER_RUN_NOT_READY_CODE: &str = "agent.steer.run_not_ready";
74
75#[derive(Debug, Clone)]
93#[non_exhaustive]
94pub struct SubagentConfig {
95 pub queue: String,
98 pub default_target: Option<String>,
100 pub targets: Vec<SubagentTarget>,
103 pub default_budget: RunBudget,
106 pub max_budget: RunBudget,
108 pub max_depth: u32,
111 pub max_active: usize,
113 pub notice_chars: usize,
115 pub max_attempts: u32,
117 pub reconcile_window: std::time::Duration,
120}
121
122impl Default for SubagentConfig {
123 fn default() -> Self {
124 Self {
125 queue: "default".to_string(),
126 default_target: None,
127 targets: Vec::new(),
128 default_budget: RunBudget::new()
129 .max_model_calls(50)
130 .max_tool_calls(200)
131 .max_wall_time(std::time::Duration::from_secs(30 * 60)),
132 max_budget: RunBudget::new(),
133 max_depth: 2,
134 max_active: 4,
135 notice_chars: 4_000,
136 max_attempts: NewRun::DEFAULT_MAX_ATTEMPTS,
137 reconcile_window: std::time::Duration::from_secs(7 * 24 * 60 * 60),
138 }
139 }
140}
141
142impl SubagentConfig {
143 #[must_use]
145 pub fn with_queue(mut self, queue: impl Into<String>) -> Self {
146 self.queue = queue.into();
147 self
148 }
149
150 #[must_use]
152 pub fn with_default_target(mut self, target: impl Into<String>) -> Self {
153 self.default_target = Some(target.into());
154 self
155 }
156
157 #[must_use]
159 pub fn with_target(mut self, target: SubagentTarget) -> Self {
160 self.targets.push(target);
161 self
162 }
163
164 #[must_use]
166 pub fn with_default_budget(mut self, budget: RunBudget) -> Self {
167 self.default_budget = budget;
168 self
169 }
170
171 #[must_use]
173 pub fn with_max_budget(mut self, budget: RunBudget) -> Self {
174 self.max_budget = budget;
175 self
176 }
177
178 #[must_use]
180 pub fn with_max_depth(mut self, depth: u32) -> Self {
181 self.max_depth = depth;
182 self
183 }
184
185 #[must_use]
187 pub fn with_max_active(mut self, max: usize) -> Self {
188 self.max_active = max;
189 self
190 }
191
192 #[must_use]
194 pub fn with_notice_chars(mut self, chars: usize) -> Self {
195 self.notice_chars = chars;
196 self
197 }
198}
199
200#[async_trait]
204pub trait SubagentBackend: Send + Sync {
205 async fn enqueue_subagent(&self, run: NewRun, launch: &SubagentLaunch) -> Result<RunRecord>;
211
212 async fn enqueue_notice(
219 &self,
220 run: NewRun,
221 child: &RunRecord,
222 launch: &SubagentLaunch,
223 ) -> Result<RunRecord>;
224
225 async fn steer(
232 &self,
233 app_name: &str,
234 user_id: &str,
235 session_id: &str,
236 text: &str,
237 ) -> Result<Option<SteerReceipt>>;
238
239 async fn cancel(&self, run_id: &str) -> Result<()>;
246
247 async fn changed(&self, _record: &SubagentRecord) {}
249}
250
251#[derive(Clone)]
271pub struct RunStoreBackend {
272 runs: Arc<dyn DurableRunStore>,
273 runners: Arc<std::sync::RwLock<Vec<std::sync::Weak<Runner>>>>,
274}
275
276impl std::fmt::Debug for RunStoreBackend {
277 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
278 f.debug_struct("RunStoreBackend").field("runners", &self.runners().len()).finish()
279 }
280}
281
282impl RunStoreBackend {
283 pub fn new(runs: Arc<dyn DurableRunStore>) -> Self {
285 Self { runs, runners: Arc::default() }
286 }
287
288 #[must_use]
290 pub fn with_runner(self, runner: &Arc<Runner>) -> Self {
291 self.add_runner(runner);
292 self
293 }
294
295 pub fn add_runner(&self, runner: &Arc<Runner>) {
297 self.runners.write().unwrap_or_else(|e| e.into_inner()).push(Arc::downgrade(runner));
298 }
299
300 fn runners(&self) -> Vec<Arc<Runner>> {
301 self.runners
302 .read()
303 .unwrap_or_else(|e| e.into_inner())
304 .iter()
305 .filter_map(std::sync::Weak::upgrade)
306 .collect()
307 }
308}
309
310#[async_trait]
311impl SubagentBackend for RunStoreBackend {
312 async fn enqueue_subagent(&self, run: NewRun, _launch: &SubagentLaunch) -> Result<RunRecord> {
313 enqueued(self.runs.enqueue(run).await?)
314 }
315
316 async fn enqueue_notice(
317 &self,
318 run: NewRun,
319 _child: &RunRecord,
320 _launch: &SubagentLaunch,
321 ) -> Result<RunRecord> {
322 enqueued(self.runs.enqueue(run).await?)
323 }
324
325 async fn steer(
326 &self,
327 app_name: &str,
328 user_id: &str,
329 session_id: &str,
330 text: &str,
331 ) -> Result<Option<SteerReceipt>> {
332 let identity = AdkIdentity::new(
333 AppName::try_from(app_name)?,
334 UserId::try_from(user_id)?,
335 SessionId::try_from(session_id)?,
336 );
337 for runner in self.runners().iter().filter(|runner| runner.app_name() == app_name) {
338 match runner.steer(&identity, Content::new("user").with_text(text)).await {
339 Ok(receipt) => return Ok(Some(receipt)),
340 Err(error)
341 if error.code == STEER_NO_ACTIVE_RUN_CODE
342 || error.code == STEER_RUN_NOT_READY_CODE => {}
343 Err(error) => return Err(error),
344 }
345 }
346 Ok(None)
347 }
348
349 async fn cancel(&self, run_id: &str) -> Result<()> {
350 self.runs.request_cancel(run_id).await
351 }
352}
353
354fn enqueued(enqueued: Enqueued) -> Result<RunRecord> {
356 match enqueued {
357 Enqueued::Created(run) | Enqueued::Existing(run) => Ok(run),
358 Enqueued::Rejected { blocking_run_id } => Err(AdkError::new(
359 ErrorComponent::Server,
360 ErrorCategory::Unavailable,
361 "subagent.rejected",
362 format!(
363 "run {blocking_run_id} holds the run's concurrency key; try again once it ends"
364 ),
365 )),
366 }
367}
368
369#[derive(Clone)]
373pub struct DurableSubagents {
374 inner: Arc<Inner>,
375}
376
377#[derive(Clone, Default)]
379pub struct WeakSubagents(std::sync::Weak<Inner>);
380
381impl std::fmt::Debug for WeakSubagents {
382 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
383 f.debug_struct("WeakSubagents").field("alive", &(self.0.strong_count() > 0)).finish()
384 }
385}
386
387impl WeakSubagents {
388 pub fn upgrade(&self) -> Option<DurableSubagents> {
390 self.0.upgrade().map(|inner| DurableSubagents { inner })
391 }
392}
393
394struct Inner {
395 runs: Arc<dyn DurableRunStore>,
396 sessions: Arc<dyn SessionService>,
397 backend: Arc<dyn SubagentBackend>,
398 config: SubagentConfig,
399 cancelled: Mutex<HashSet<String>>,
401}
402
403impl std::fmt::Debug for DurableSubagents {
404 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
405 f.debug_struct("DurableSubagents")
406 .field("config", &self.inner.config)
407 .finish_non_exhaustive()
408 }
409}
410
411impl DurableSubagents {
412 pub fn new(
414 runs: Arc<dyn DurableRunStore>,
415 sessions: Arc<dyn SessionService>,
416 backend: Arc<dyn SubagentBackend>,
417 config: SubagentConfig,
418 ) -> Self {
419 Self {
420 inner: Arc::new(Inner {
421 runs,
422 sessions,
423 backend,
424 config,
425 cancelled: Mutex::new(HashSet::new()),
426 }),
427 }
428 }
429
430 pub fn config(&self) -> &SubagentConfig {
432 &self.inner.config
433 }
434
435 pub fn downgrade(&self) -> WeakSubagents {
438 WeakSubagents(Arc::downgrade(&self.inner))
439 }
440
441 async fn groups(
444 &self,
445 filter: RunFilter,
446 ) -> Result<BTreeMap<String, (SubagentLaunch, Vec<RunRecord>)>> {
447 let mut groups: BTreeMap<String, (SubagentLaunch, Vec<RunRecord>)> = BTreeMap::new();
448 for run in self.inner.runs.list(filter.queue(self.inner.config.queue.as_str())).await? {
449 let Some(launch) = SubagentLaunch::of_run(&run) else { continue };
450 if launch.parent.app_name != run.app_name || launch.parent.user_id != run.user_id {
452 continue;
453 }
454 groups.entry(launch.id.clone()).or_insert_with(|| (launch, Vec::new())).1.push(run);
455 }
456 for (launch, runs) in groups.values_mut() {
457 runs.sort_by(|a, b| a.created_at.cmp(&b.created_at).then(a.run_id.cmp(&b.run_id)));
458 if let Some(first) = runs.first().and_then(SubagentLaunch::of_run) {
460 *launch = first;
461 }
462 }
463 Ok(groups)
464 }
465
466 async fn subagent(
468 &self,
469 scope: &SubagentScope,
470 id: &str,
471 ) -> Result<Option<(SubagentLaunch, Vec<RunRecord>)>> {
472 let filter = RunFilter::default()
473 .app_name(scope.app_name.as_str())
474 .user_id(scope.user_id.as_str())
475 .concurrency_key(format!("subagent:{id}"));
476 Ok(self
477 .groups(filter)
478 .await?
479 .remove(id)
480 .filter(|(launch, _)| scope.contains(&launch.parent)))
481 }
482
483 async fn subagent_any(
485 &self,
486 app_name: &str,
487 user_id: &str,
488 id: &str,
489 ) -> Result<Option<(SubagentLaunch, Vec<RunRecord>)>> {
490 let filter = RunFilter::default()
491 .app_name(app_name)
492 .user_id(user_id)
493 .concurrency_key(format!("subagent:{id}"));
494 Ok(self.groups(filter).await?.remove(id))
495 }
496
497 fn target_for(&self, start: &SubagentStart, parent_target: Option<&str>) -> Result<String> {
499 let config = &self.inner.config;
500 let asked = start.request.target.as_deref().map(str::trim).filter(|t| !t.is_empty());
501 let target =
502 asked.or(config.default_target.as_deref()).or(parent_target).ok_or_else(|| {
503 subagent_refused(
504 "this host has no default sub-agent target and the parent's target is \
505 unknown; name a target",
506 )
507 })?;
508 let allowed = config.targets.iter().any(|known| known.name == target)
509 || config.default_target.as_deref() == Some(target)
510 || (config.targets.is_empty() && parent_target == Some(target));
511 if !allowed {
512 let mut names: Vec<&str> = config.targets.iter().map(|t| t.name.as_str()).collect();
513 names.extend(config.default_target.as_deref());
514 return Err(subagent_refused(format!(
515 "'{target}' is not a sub-agent target of this host; choose one of: {}",
516 if names.is_empty() {
517 "the parent's own agent".to_string()
518 } else {
519 names.join(", ")
520 }
521 )));
522 }
523 Ok(target.to_string())
524 }
525
526 async fn fork(&self, parent: &SubagentParent, session_id: &str) -> Result<()> {
529 let sessions = &self.inner.sessions;
530 let existing = sessions
531 .get(GetRequest {
532 app_name: parent.app_name.clone(),
533 user_id: parent.user_id.clone(),
534 session_id: session_id.to_string(),
535 num_recent_events: None,
536 after: None,
537 })
538 .await;
539 if existing.is_ok() {
541 return Ok(());
542 }
543 let source = sessions
544 .get(GetRequest {
545 app_name: parent.app_name.clone(),
546 user_id: parent.user_id.clone(),
547 session_id: parent.session_id.clone(),
548 num_recent_events: None,
549 after: None,
550 })
551 .await?;
552 let events = source.events().all();
553 let state: HashMap<String, Value> =
554 source.state().all().into_iter().filter(|(key, _)| !key.contains(':')).collect();
555 let answered: HashSet<String> = events
556 .iter()
557 .flat_map(|event| {
558 event
559 .tool_results()
560 .into_iter()
561 .filter_map(|result| result.call_id.map(str::to_string))
562 })
563 .collect();
564 sessions
565 .create(CreateRequest {
566 app_name: parent.app_name.clone(),
567 user_id: parent.user_id.clone(),
568 session_id: Some(session_id.to_string()),
569 state,
570 })
571 .await?;
572 for event in events {
573 if event.llm_response.partial
574 || event
575 .tool_calls()
576 .iter()
577 .any(|call| call.call_id.is_none_or(|id| !answered.contains(id)))
578 {
579 continue;
580 }
581 let mut copy = event.clone();
582 copy.id = uuid::Uuid::new_v4().to_string();
583 copy.invocation_id = format!("{FORK_INVOCATION_PREFIX}{}", event.invocation_id);
584 sessions.append_event(session_id, copy).await?;
585 }
586 Ok(())
587 }
588
589 fn follow_up_run(&self, launch: &SubagentLaunch, first: &RunRecord, text: &str) -> NewRun {
592 let mut input = first.input.clone();
593 if let Some(map) = input.as_object_mut() {
594 map.insert("text".to_string(), Value::String(text.to_string()));
595 }
596 let mut run = NewRun::new(
597 self.inner.config.queue.as_str(),
598 first.app_name.as_str(),
599 first.user_id.as_str(),
600 first.target.as_str(),
601 input,
602 )
603 .with_session_id(launch.session_id())
604 .with_concurrency_key(launch.concurrency_key(), OnConflict::Enqueue)
605 .with_max_attempts(self.inner.config.max_attempts);
606 run.principal.clone_from(&first.principal);
607 run
608 }
609
610 async fn deliver_to_subagent(
612 &self,
613 launch: &SubagentLaunch,
614 runs: &[RunRecord],
615 text: &str,
616 key: Option<String>,
617 ) -> Result<FollowUp> {
618 let (Some(first), Some(latest)) = (runs.first(), runs.last()) else {
619 return Err(subagent_not_found(&launch.id));
620 };
621 if latest.state == RunState::Running
622 && let Some(receipt) = self
623 .inner
624 .backend
625 .steer(&first.app_name, &first.user_id, &launch.session_id(), text)
626 .await?
627 {
628 let steer_id = receipt.steer_id().to_string();
629 let host = self.clone();
630 let launch = launch.clone();
631 let first = first.clone();
632 let text = text.to_string();
633 tokio::spawn(async move {
634 if let Ok(SteerOutcome::Returned(_)) = receipt.outcome().await {
635 let mut run = host.follow_up_run(&launch, &first, &text);
636 run.idempotency_key = key;
637 if let Err(error) = host.inner.backend.enqueue_subagent(run, &launch).await {
638 tracing::warn!(subagent.id = %launch.id, error = %error, "could not queue the follow-up the running turn returned");
639 }
640 }
641 });
642 return Ok(FollowUp::Steered { steer_id, run_id: latest.run_id.clone() });
643 }
644 let mut run = self.follow_up_run(launch, first, text);
645 run.idempotency_key = key;
646 let run = self.inner.backend.enqueue_subagent(run, launch).await?;
647 Ok(FollowUp::Queued { run_id: run.run_id })
648 }
649
650 async fn report(
652 &self,
653 run: &RunRecord,
654 ) -> Option<(SubagentLaunch, Vec<RunRecord>, SubagentRecord)> {
655 let launch = SubagentLaunch::of_run(run)?;
656 if launch.parent.app_name != run.app_name || launch.parent.user_id != run.user_id {
657 tracing::warn!(run.id = %run.run_id, "a run names a sub-agent parent of another user; ignoring it");
658 return None;
659 }
660 let (launch, mut runs) = match self
661 .subagent_any(&run.app_name, &run.user_id, &launch.id)
662 .await
663 {
664 Ok(Some(found)) => found,
665 Ok(None) => (launch, vec![run.clone()]),
666 Err(error) => {
667 tracing::warn!(run.id = %run.run_id, error = %error, "could not read the sub-agent's runs");
668 (launch, vec![run.clone()])
669 }
670 };
671 if let Some(stored) = runs.iter_mut().find(|stored| stored.run_id == run.run_id) {
673 *stored = run.clone();
674 }
675 let latest = runs.iter().position(|stored| stored.run_id == run.run_id)?;
676 let record = SubagentRecord::from_runs(&launch, &runs[..=latest])?;
677 self.inner.backend.changed(&record).await;
678 Some((launch, runs, record))
679 }
680
681 pub async fn run_finished(&self, run: &RunRecord) {
684 if !run.state.is_terminal() {
685 return;
686 }
687 let Some((launch, _, record)) = self.report(run).await else { return };
688 if record.status == SubagentStatus::Cancelled
689 && self.inner.cancelled.lock().unwrap_or_else(|e| e.into_inner()).remove(&launch.id)
690 {
691 return;
692 }
693 if !launch.notify_parent {
694 return;
695 }
696 if let Err(error) = self.tell_parent(&launch, run, &record, true, true).await {
697 tracing::warn!(subagent.id = %launch.id, run.id = %run.run_id, error = %error, "could not tell the parent its sub-agent finished; it is told when the host starts again");
698 }
699 }
700
701 pub async fn run_parked(&self, run: &RunRecord) {
704 let Some((launch, _, record)) = self.report(run).await else { return };
705 if record.status != SubagentStatus::WaitingForHuman || !launch.notify_parent {
706 return;
707 }
708 if let Err(error) = self.tell_parent(&launch, run, &record, false, true).await {
709 tracing::debug!(subagent.id = %launch.id, error = %error, "could not tell the parent its sub-agent waits for a person");
710 }
711 }
712
713 pub async fn run_claimed(&self, run: &RunRecord) {
715 let _ = self.report(run).await;
716 }
717
718 async fn tell_parent(
722 &self,
723 launch: &SubagentLaunch,
724 child: &RunRecord,
725 record: &SubagentRecord,
726 durable: bool,
727 steer: bool,
728 ) -> Result<()> {
729 let notice = subagent_notice(record, self.inner.config.notice_chars);
730 let header = notice_header(&record.id, &record.name, &record.run_id, record.status);
731 let parent = &launch.parent;
732 if durable && self.parent_was_told(parent, &header).await {
733 return Ok(());
734 }
735 let key = format!("subagent:{}:{}:{}", record.id, record.run_id, record.status.as_str());
736 if let Some(parent_id) = &launch.parent_subagent {
737 let Some((parent_launch, runs)) =
738 self.subagent_any(&parent.app_name, &parent.user_id, parent_id).await?
739 else {
740 return Ok(());
741 };
742 if !durable {
743 if steer && runs.last().is_some_and(|run| run.state == RunState::Running) {
744 let _ = self
745 .inner
746 .backend
747 .steer(
748 &parent.app_name,
749 &parent.user_id,
750 &parent_launch.session_id(),
751 ¬ice,
752 )
753 .await?;
754 }
755 return Ok(());
756 }
757 if steer {
758 self.deliver_to_subagent(&parent_launch, &runs, ¬ice, Some(key)).await?;
759 } else if let Some(first) = runs.first() {
760 let mut run = self.follow_up_run(&parent_launch, first, ¬ice);
761 run.idempotency_key = Some(key);
762 self.inner.backend.enqueue_subagent(run, &parent_launch).await?;
763 }
764 return Ok(());
765 }
766 let receipt = if steer {
767 self.inner
768 .backend
769 .steer(&parent.app_name, &parent.user_id, &parent.session_id, ¬ice)
770 .await?
771 } else {
772 None
773 };
774 if let Some(receipt) = receipt {
775 tracing::info!(subagent.id = %record.id, steer.id = receipt.steer_id(), status = %record.status, "told the parent's running turn");
776 if durable {
777 let host = self.clone();
778 let launch = launch.clone();
779 let child = child.clone();
780 tokio::spawn(async move {
781 if let Ok(SteerOutcome::Returned(_)) = receipt.outcome().await
782 && let Err(error) =
783 host.enqueue_parent_turn(&launch, &child, ¬ice, key).await
784 {
785 tracing::warn!(subagent.id = %launch.id, error = %error, "could not wake the parent after its turn ended");
786 }
787 });
788 }
789 return Ok(());
790 }
791 if durable {
792 self.enqueue_parent_turn(launch, child, ¬ice, key).await?;
793 }
794 Ok(())
795 }
796
797 async fn parent_was_told(&self, parent: &SubagentParent, header: &str) -> bool {
799 let Ok(session) = self
800 .inner
801 .sessions
802 .get(GetRequest {
803 app_name: parent.app_name.clone(),
804 user_id: parent.user_id.clone(),
805 session_id: parent.session_id.clone(),
806 num_recent_events: None,
807 after: None,
808 })
809 .await
810 else {
811 return false;
812 };
813 session.events().all().iter().any(|event| {
814 event.author == "user"
815 && event.llm_response.content.as_ref().is_some_and(|content| {
816 content.parts.iter().filter_map(Part::text).any(|text| text.starts_with(header))
817 })
818 })
819 }
820
821 async fn enqueue_parent_turn(
823 &self,
824 launch: &SubagentLaunch,
825 child: &RunRecord,
826 notice: &str,
827 key: String,
828 ) -> Result<()> {
829 let parent = &launch.parent;
830 let Some(target) = parent.target.as_deref() else {
831 tracing::info!(subagent.id = %launch.id, "the parent's target is unknown, so only a turn in flight is told; the parent polls");
832 return Ok(());
833 };
834 let mut run = NewRun::new(
835 self.inner.config.queue.as_str(),
836 parent.app_name.as_str(),
837 parent.user_id.as_str(),
838 target,
839 json!({ "text": notice }),
840 )
841 .with_session_id(parent.session_id.as_str())
842 .with_idempotency_key(key)
843 .with_concurrency_key(format!("subagent-notice:{}", parent.session_id), OnConflict::Enqueue)
846 .with_max_attempts(self.inner.config.max_attempts);
847 if let Some(acting) = &parent.acting {
848 let mut principal = adk_core::ActingContext::new(adk_core::AgentPrincipal::derived(
849 &parent.app_name,
850 target,
851 ));
852 principal.on_behalf_of.clone_from(&acting.on_behalf_of);
853 principal.delegation_chain.clone_from(&acting.delegation_chain);
854 run.principal = Some(principal);
855 }
856 let woken = self.inner.backend.enqueue_notice(run, child, launch).await?;
857 tracing::info!(subagent.id = %launch.id, parent.session = %parent.session_id, run.id = %woken.run_id, "woke the parent with its sub-agent's notice");
858 Ok(())
859 }
860
861 pub async fn reconcile(&self) -> Result<usize> {
872 let groups = self.groups(RunFilter::default()).await?;
873 let since = chrono::Duration::from_std(self.inner.config.reconcile_window)
874 .ok()
875 .and_then(|window| chrono::Utc::now().checked_sub_signed(window))
876 .unwrap_or(chrono::DateTime::<chrono::Utc>::MIN_UTC);
877 let mut looked = 0;
878 for (launch, runs) in groups.values() {
879 if !launch.notify_parent {
880 continue;
881 }
882 for (index, run) in runs.iter().enumerate() {
883 if !matches!(run.state, RunState::Completed | RunState::Failed)
884 || run.updated_at < since
885 {
886 continue;
887 }
888 looked += 1;
889 let Some(record) = SubagentRecord::from_runs(launch, &runs[..=index]) else {
890 continue;
891 };
892 if let Err(error) = self.tell_parent(launch, run, &record, true, false).await {
893 tracing::warn!(subagent.id = %launch.id, run.id = %run.run_id, error = %error, "could not tell the parent on reconcile");
894 }
895 }
896 }
897 Ok(looked)
898 }
899}
900
901#[async_trait]
902impl SubagentHost for DurableSubagents {
903 async fn start(&self, start: SubagentStart) -> Result<SubagentRecord> {
904 let config = &self.inner.config;
905 let mut parent = start.parent.clone();
906 let scope = parent.scope();
907 let parent_run = match &parent.run_id {
909 Some(run_id) => self.inner.runs.get(run_id).await?,
910 None => None,
911 };
912 let parent_launch = parent_run.as_ref().and_then(SubagentLaunch::of_run);
913 if parent.target.is_none() {
914 parent.target = parent_run.as_ref().map(|run| run.target.clone());
915 }
916 let depth = parent_launch.as_ref().map_or(1, |launch| launch.depth + 1);
917 if depth > config.max_depth {
918 return Err(subagent_refused(format!(
919 "a sub-agent at depth {depth} would exceed this host's limit of {}; do the work \
920 in this agent instead",
921 config.max_depth
922 )));
923 }
924 let mine = self
925 .groups(
926 RunFilter::default()
927 .app_name(scope.app_name.as_str())
928 .user_id(scope.user_id.as_str()),
929 )
930 .await?;
931 let mine: Vec<&(SubagentLaunch, Vec<RunRecord>)> =
932 mine.values().filter(|(launch, _)| scope.contains(&launch.parent)).collect();
933 if let Some(key) = &start.idempotency_key
934 && let Some((launch, runs)) =
935 mine.iter().find(|(launch, _)| launch.start_key.as_deref() == Some(key))
936 {
937 return SubagentRecord::from_runs(launch, runs)
938 .ok_or_else(|| subagent_not_found(&launch.id));
939 }
940 let active = mine
941 .iter()
942 .filter(|(_, runs)| runs.last().is_some_and(|run| !run.state.is_terminal()))
943 .count();
944 if active >= config.max_active {
945 return Err(subagent_refused(format!(
946 "this session already has {active} unfinished sub-agents, the most this host \
947 allows ({}); wait for one to finish or cancel one",
948 config.max_active
949 )));
950 }
951 let target = self.target_for(&start, parent.target.as_deref())?;
952 let mut ask = config.default_budget.clone();
954 if let Some(asked) = &start.request.budget {
955 ask.max_model_calls = asked.max_model_calls.or(ask.max_model_calls);
956 ask.max_total_tokens = asked.max_total_tokens.or(ask.max_total_tokens);
957 ask.max_cost_micro_usd = asked.max_cost_micro_usd.or(ask.max_cost_micro_usd);
958 ask.max_wall_time = asked.max_wall_time.or(ask.max_wall_time);
959 ask.max_tool_calls = asked.max_tool_calls.or(ask.max_tool_calls);
960 ask.allow_unpriced_models |= asked.allow_unpriced_models;
961 }
962 let ask = ask.narrowed(&config.max_budget);
963 let budget = match &start.tracker {
964 Some(tracker) => tracker.carve(&ask).map_err(AdkError::from)?,
965 None => ask,
966 };
967 let id = format!("sa-{}", uuid::Uuid::new_v4().simple());
968 let name = start
969 .request
970 .name
971 .clone()
972 .map(|name| name.trim().to_string())
973 .filter(|name| !name.is_empty())
974 .unwrap_or_else(|| id.chars().take(11).collect());
975 let mut launch =
976 SubagentLaunch::new(&id, name, &target, parent.clone(), &start.request.task);
977 launch.mode = start.request.mode;
978 launch.depth = depth;
979 launch.notify_parent = start.request.notify_parent;
980 launch.parent_subagent = parent_launch.map(|launch| launch.id);
981 launch.start_key.clone_from(&start.idempotency_key);
982 if launch.mode == adk_core::SubagentMode::Fork {
983 self.fork(&parent, &launch.session_id()).await?;
984 }
985 let mut limits = RunLimits::new().with_budget(budget);
986 if let Some(tools) = &start.allowed_tools {
987 limits = limits.with_allowed_tools(tools.iter().cloned());
988 }
989 let input = json!({
990 "text": start.request.task,
991 SUBAGENT_INPUT_KEY: launch,
992 RUN_LIMITS_INPUT_KEY: limits,
993 });
994 let mut run = NewRun::new(
995 config.queue.as_str(),
996 parent.app_name.as_str(),
997 parent.user_id.as_str(),
998 target.as_str(),
999 input,
1000 )
1001 .with_session_id(launch.session_id())
1002 .with_concurrency_key(launch.concurrency_key(), OnConflict::Enqueue)
1003 .with_max_attempts(config.max_attempts)
1004 .with_principal(parent.child_acting(&target));
1005 if let Some(key) = &start.idempotency_key {
1006 run = run.with_idempotency_key(format!("subagent:start:{key}"));
1007 }
1008 let record = self.inner.backend.enqueue_subagent(run, &launch).await?;
1009 let launch = SubagentLaunch::of_run(&record).unwrap_or(launch);
1010 let record = SubagentRecord::from_runs(&launch, std::slice::from_ref(&record))
1011 .ok_or_else(|| subagent_not_found(&launch.id))?;
1012 tracing::info!(subagent.id = %record.id, subagent.target = %record.target, subagent.depth = record.depth, run.id = %record.run_id, "sub-agent started");
1013 self.inner.backend.changed(&record).await;
1014 Ok(record)
1015 }
1016
1017 async fn get(&self, scope: &SubagentScope, id: &str) -> Result<Option<SubagentRecord>> {
1018 Ok(self
1019 .subagent(scope, id)
1020 .await?
1021 .and_then(|(launch, runs)| SubagentRecord::from_runs(&launch, &runs)))
1022 }
1023
1024 async fn list(&self, scope: &SubagentScope) -> Result<Vec<SubagentRecord>> {
1025 let filter =
1026 RunFilter::default().app_name(scope.app_name.as_str()).user_id(scope.user_id.as_str());
1027 let mut records: Vec<SubagentRecord> = self
1028 .groups(filter)
1029 .await?
1030 .values()
1031 .filter(|(launch, _)| scope.contains(&launch.parent))
1032 .filter_map(|(launch, runs)| SubagentRecord::from_runs(launch, runs))
1033 .collect();
1034 records.sort_by(|a, b| a.created_at.cmp(&b.created_at).then(a.id.cmp(&b.id)));
1035 Ok(records)
1036 }
1037
1038 async fn send(&self, scope: &SubagentScope, id: &str, message: &str) -> Result<FollowUp> {
1039 if message.trim().is_empty() {
1040 return Err(AdkError::new(
1041 ErrorComponent::Agent,
1042 ErrorCategory::InvalidInput,
1043 adk_core::STEER_INVALID_MESSAGE_CODE,
1044 "the follow-up message is empty; send the text the sub-agent should act on",
1045 ));
1046 }
1047 let Some((launch, runs)) = self.subagent(scope, id).await? else {
1048 return Err(subagent_not_found(id));
1049 };
1050 if runs.last().is_some_and(|run| run.state == RunState::Cancelled) {
1051 return Err(AdkError::new(
1052 ErrorComponent::Agent,
1053 ErrorCategory::InvalidInput,
1054 SUBAGENT_FINISHED_CODE,
1055 format!("sub-agent '{id}' was cancelled and takes no more work; start a new one"),
1056 ));
1057 }
1058 let follow_up = self.deliver_to_subagent(&launch, &runs, message, None).await?;
1059 tracing::info!(subagent.id = %id, follow_up = ?follow_up, "follow-up sent to sub-agent");
1060 Ok(follow_up)
1061 }
1062
1063 async fn cancel(&self, scope: &SubagentScope, id: &str) -> Result<SubagentRecord> {
1064 let Some((launch, runs)) = self.subagent(scope, id).await? else {
1065 return Err(subagent_not_found(id));
1066 };
1067 let unfinished: Vec<&RunRecord> =
1068 runs.iter().filter(|run| !run.state.is_terminal()).collect();
1069 if !unfinished.is_empty() {
1070 self.inner
1071 .cancelled
1072 .lock()
1073 .unwrap_or_else(|e| e.into_inner())
1074 .insert(launch.id.clone());
1075 }
1076 for run in unfinished {
1077 self.inner.backend.cancel(&run.run_id).await?;
1078 }
1079 tracing::info!(subagent.id = %id, "sub-agent cancelled by its parent");
1080 let (launch, runs) = self.subagent(scope, id).await?.unwrap_or((launch, runs));
1081 let record =
1082 SubagentRecord::from_runs(&launch, &runs).ok_or_else(|| subagent_not_found(id))?;
1083 if record.status.is_terminal() {
1085 self.inner.cancelled.lock().unwrap_or_else(|e| e.into_inner()).remove(&launch.id);
1086 self.inner.backend.changed(&record).await;
1087 }
1088 Ok(record)
1089 }
1090
1091 fn targets(&self) -> Vec<SubagentTarget> {
1092 self.inner.config.targets.clone()
1093 }
1094}
1095
1096#[derive(Debug, Clone)]
1112pub struct SubagentHooks {
1113 subagents: DurableSubagents,
1114}
1115
1116impl SubagentHooks {
1117 pub fn new(subagents: DurableSubagents) -> Self {
1119 Self { subagents }
1120 }
1121}
1122
1123#[async_trait]
1124impl WorkerHooks for SubagentHooks {
1125 async fn on_claim(&self, run: &RunRecord) {
1126 if run.input.get(SUBAGENT_INPUT_KEY).is_some() {
1127 self.subagents.run_claimed(run).await;
1128 }
1129 }
1130
1131 async fn on_park(&self, run: &RunRecord, reason: ParkReason) {
1132 if reason == ParkReason::AwaitingApproval && run.input.get(SUBAGENT_INPUT_KEY).is_some() {
1133 self.subagents.run_parked(run).await;
1134 }
1135 }
1136
1137 async fn on_finish(&self, run: &RunRecord) {
1138 if run.input.get(SUBAGENT_INPUT_KEY).is_some() {
1139 self.subagents.run_finished(run).await;
1140 }
1141 }
1142}