Skip to main content

adk_server/background/
subagents.rs

1//! Background sub-agents as durable runs: [`DurableSubagents`], the
2//! [`SubagentHost`] over any [`DurableRunStore`] and the [`DurableWorker`](super::DurableWorker) that claims its
3//! queue.
4//!
5//! A sub-agent is a run of its target in a session of its own, `subagent-<id>`; every run
6//! of it carries the [`SubagentLaunch`] under `subagent`, and the budget slice and the
7//! parent's tools under `runLimits`, which the worker applies (see
8//! [Run limits](super::worker#run-limits)). Its runs share the concurrency key
9//! `subagent:<id>`, so a follow-up runs after the run before it.
10//!
11//! | Operation | What happens |
12//! |---|---|
13//! | `start` | Checks depth, running sub-agents and target; carves the budget slice from the parent's run; forks the parent's session when asked; enqueues the first run through the [`SubagentBackend`] |
14//! | `send` | Steers the sub-agent's running turn; queues a follow-up run when none runs here, or when the turn ends without taking the message |
15//! | `cancel` | Cancels every unfinished run of it; its parent is not told |
16//! | A run finishes ([`DurableSubagents::run_finished`]) | The backend reports the status; the parent is told, by steering its running turn or by a new run of its session keyed `subagent:<id>:<run>:<status>`, so it is told once |
17//! | A run parks on a held call ([`DurableSubagents::run_parked`]) | The backend reports `waitingForHuman`; a parent turn in flight is told |
18//! | Start ([`DurableSubagents::reconcile`]) | Tells every parent about finished runs it was not told about, after a crash |
19//!
20//! [`SubagentHooks`] wires the last three into a plain [`DurableWorker`](super::DurableWorker); `adk-kernel` calls
21//! them from its own worker hooks.
22//!
23//! # Example
24//!
25//! ```rust,no_run
26//! use std::sync::Arc;
27//! use adk_core::{InMemoryRunStore, RunBudget};
28//! use adk_server::background::{
29//!     DurableSubagents, DurableWorker, RunStoreBackend, SubagentConfig, SubagentHooks,
30//! };
31//!
32//! # fn example(runner: Arc<adk_runner::Runner>) -> adk_core::Result<()> {
33//! let runs = Arc::new(InMemoryRunStore::new());
34//! let backend = RunStoreBackend::new(runs.clone()).with_runner(&runner);
35//! let subagents = DurableSubagents::new(
36//!     runs.clone(),
37//!     runner.session_service().clone(),
38//!     Arc::new(backend),
39//!     SubagentConfig::default().with_default_budget(RunBudget::new().max_model_calls(20)),
40//! );
41//! let worker = DurableWorker::new(runs)
42//!     .with_agent("assistant", runner)
43//!     .with_hooks(Arc::new(SubagentHooks::new(subagents.clone())))
44//!     .spawn();
45//! # let _ = worker;
46//! # Ok(())
47//! # }
48//! ```
49
50use 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
71/// The code `Runner::steer` answers a run that has not built its context yet, or has
72/// finished, with.
73const STEER_RUN_NOT_READY_CODE: &str = "agent.steer.run_not_ready";
74
75/// How a [`DurableSubagents`] host runs sub-agents.
76///
77/// # Example
78///
79/// ```rust
80/// use std::time::Duration;
81/// use adk_core::RunBudget;
82/// use adk_core::subagent::SubagentTarget;
83/// use adk_server::background::SubagentConfig;
84///
85/// let config = SubagentConfig::default()
86///     .with_queue("background")
87///     .with_target(SubagentTarget::new("researcher", "Reads sources and cites them"))
88///     .with_max_depth(1)
89///     .with_default_budget(RunBudget::new().max_model_calls(10).max_wall_time(Duration::from_secs(600)));
90/// assert_eq!(config.max_active, 4);
91/// ```
92#[derive(Debug, Clone)]
93#[non_exhaustive]
94pub struct SubagentConfig {
95    /// The queue sub-agent runs and parent notices go to; a worker must claim it.
96    /// Defaults to `default`.
97    pub queue: String,
98    /// The target a start that names none runs; the parent's own target when `None`.
99    pub default_target: Option<String>,
100    /// The targets a parent may name. Empty allows only the default target, or the
101    /// parent's own.
102    pub targets: Vec<SubagentTarget>,
103    /// The budget a start that asks for none gets, before it is carved from the parent's.
104    /// Defaults to 50 model calls, 200 tool calls and 30 minutes per attempt.
105    pub default_budget: RunBudget,
106    /// The largest budget a start may ask for: every ask is narrowed by it.
107    pub max_budget: RunBudget,
108    /// How deep a chain of sub-agents may go: 1 lets only top-level agents start them.
109    /// Defaults to 2.
110    pub max_depth: u32,
111    /// How many unfinished sub-agents one parent session may have. Defaults to 4.
112    pub max_active: usize,
113    /// The most characters of a sub-agent's answer a notice carries. Defaults to 4,000.
114    pub notice_chars: usize,
115    /// The attempts each run may take, counting recoveries. Defaults to 3.
116    pub max_attempts: u32,
117    /// How far back [`DurableSubagents::reconcile`] looks for finished runs whose parent
118    /// may not have been told. Defaults to 7 days.
119    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    /// Sets the queue.
144    #[must_use]
145    pub fn with_queue(mut self, queue: impl Into<String>) -> Self {
146        self.queue = queue.into();
147        self
148    }
149
150    /// Sets the target a start that names none runs.
151    #[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    /// Adds a target a parent may name.
158    #[must_use]
159    pub fn with_target(mut self, target: SubagentTarget) -> Self {
160        self.targets.push(target);
161        self
162    }
163
164    /// Sets the budget a start that asks for none gets.
165    #[must_use]
166    pub fn with_default_budget(mut self, budget: RunBudget) -> Self {
167        self.default_budget = budget;
168        self
169    }
170
171    /// Sets the largest budget a start may ask for.
172    #[must_use]
173    pub fn with_max_budget(mut self, budget: RunBudget) -> Self {
174        self.max_budget = budget;
175        self
176    }
177
178    /// Sets how deep a chain of sub-agents may go.
179    #[must_use]
180    pub fn with_max_depth(mut self, depth: u32) -> Self {
181        self.max_depth = depth;
182        self
183    }
184
185    /// Sets how many unfinished sub-agents one parent session may have.
186    #[must_use]
187    pub fn with_max_active(mut self, max: usize) -> Self {
188        self.max_active = max;
189        self
190    }
191
192    /// Sets the most characters of an answer a notice carries.
193    #[must_use]
194    pub fn with_notice_chars(mut self, chars: usize) -> Self {
195        self.notice_chars = chars;
196        self
197    }
198}
199
200/// Where a [`DurableSubagents`] host enqueues, steers and cancels runs, and reports status:
201/// straight to the run store and the runners ([`RunStoreBackend`]), or through a kernel's
202/// process table, which records each sub-agent as a process (`adk-kernel`).
203#[async_trait]
204pub trait SubagentBackend: Send + Sync {
205    /// Enqueues a run of sub-agent `launch`: its first, or a follow-up.
206    ///
207    /// # Errors
208    ///
209    /// The store's error, or the backend's refusal (a freeze, a quota).
210    async fn enqueue_subagent(&self, run: NewRun, launch: &SubagentLaunch) -> Result<RunRecord>;
211
212    /// Enqueues the run of the parent's session that tells it about `child`, a run of
213    /// sub-agent `launch`.
214    ///
215    /// # Errors
216    ///
217    /// The store's error, or the backend's refusal.
218    async fn enqueue_notice(
219        &self,
220        run: NewRun,
221        child: &RunRecord,
222        launch: &SubagentLaunch,
223    ) -> Result<RunRecord>;
224
225    /// Queues `text` on the steering inbox of the turn of session `session_id` that runs
226    /// here, or `None` when none does.
227    ///
228    /// # Errors
229    ///
230    /// The steering path's error: an input guardrail or plugin refused the message.
231    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    /// Cancels run `run_id`: at once when it is queued or parked, at its next checkpoint
240    /// when it runs.
241    ///
242    /// # Errors
243    ///
244    /// The store's error.
245    async fn cancel(&self, run_id: &str) -> Result<()>;
246
247    /// Reports that a sub-agent's status changed. The default does nothing.
248    async fn changed(&self, _record: &SubagentRecord) {}
249}
250
251/// The [`SubagentBackend`] of a host without a kernel: runs go straight to the run store,
252/// and steering to the runners it was given.
253///
254/// It holds its runners weakly and clones share them, so a runner whose agent carries the
255/// sub-agent tools can be added after the host it reaches is built
256/// ([`add_runner`](Self::add_runner)).
257///
258/// # Example
259///
260/// ```rust
261/// use std::sync::Arc;
262/// use adk_core::InMemoryRunStore;
263/// use adk_server::background::RunStoreBackend;
264///
265/// let backend = RunStoreBackend::new(Arc::new(InMemoryRunStore::new()));
266/// // Build the host over `Arc::new(backend.clone())`, the agents over the host, then:
267/// // backend.add_runner(&runner);
268/// # let _ = backend;
269/// ```
270#[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    /// A backend over `runs` that steers no turn.
284    pub fn new(runs: Arc<dyn DurableRunStore>) -> Self {
285        Self { runs, runners: Arc::default() }
286    }
287
288    /// Steers the turns `runner` runs: the parents' and the sub-agents'.
289    #[must_use]
290    pub fn with_runner(self, runner: &Arc<Runner>) -> Self {
291        self.add_runner(runner);
292        self
293    }
294
295    /// Steers the turns `runner` runs, from now on; every clone of this backend sees it.
296    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
354/// The record of a created or existing run; a rejected one is an error.
355fn 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/// Background sub-agents as durable runs (see the [module docs](self)).
370///
371/// Cheap to clone: clones share one host.
372#[derive(Clone)]
373pub struct DurableSubagents {
374    inner: Arc<Inner>,
375}
376
377/// A [`DurableSubagents`] host that is not kept alive, from [`DurableSubagents::downgrade`].
378#[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    /// The host, while it lives.
389    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    /// Sub-agents their parent cancelled: their cancellation tells the parent nothing.
400    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    /// A host whose sub-agents run on `runs`, in sessions of `sessions`, through `backend`.
413    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    /// The host's configuration.
431    pub fn config(&self) -> &SubagentConfig {
432        &self.inner.config
433    }
434
435    /// A handle on this host that does not keep it alive, for a tool built before the
436    /// host's owner — a kernel — exists.
437    pub fn downgrade(&self) -> WeakSubagents {
438        WeakSubagents(Arc::downgrade(&self.inner))
439    }
440
441    /// The runs of `app_name`'s `user_id` on the host's queue that belong to a sub-agent,
442    /// grouped by sub-agent id, each group oldest first.
443    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            // A launch is a claim in the run's input: it counts only for its own user.
451            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            // The first run's launch is the sub-agent's.
459            if let Some(first) = runs.first().and_then(SubagentLaunch::of_run) {
460                *launch = first;
461            }
462        }
463        Ok(groups)
464    }
465
466    /// The runs of sub-agent `id` with its launch, when a parent in `scope` started it.
467    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    /// The sub-agent `id` of any parent, for the host itself.
484    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    /// The target a start runs, after the host's rules.
498    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    /// Copies the parent's session into the sub-agent's: its state, and its events but the
527    /// ones holding calls still waiting for a response, each under a `fork-` invocation id.
528    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        // A replayed start finds the fork it already made.
540        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    /// A follow-up run of sub-agent `launch` with `text` as its user turn: the first run's
590    /// input with the text replaced, so it keeps the slice and the ceiling.
591    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    /// Queues `text` for sub-agent `launch`: on its running turn's inbox, or as its next run.
611    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    /// Reports a status change of the sub-agent `run` belongs to and returns its record.
651    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        // The store may not show the write the hook reports yet.
672        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    /// Tells sub-agent `run`'s parent that the run finished, when it should be told; call
682    /// it after the store recorded the run's outcome. [`SubagentHooks::on_finish`] does.
683    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    /// Reports a sub-agent `run` parked, and tells a parent turn in flight that it waits
702    /// for a person. [`SubagentHooks::on_park`] calls it.
703    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    /// Reports sub-agent `run` started running. [`SubagentHooks::on_claim`] calls it.
714    pub async fn run_claimed(&self, run: &RunRecord) {
715        let _ = self.report(run).await;
716    }
717
718    /// Tells the parent of `launch` about `record`: by steering its turn in flight, else,
719    /// when `durable`, by a run of its session (a follow-up when the parent is itself a
720    /// sub-agent), keyed so it is told once.
721    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                            &notice,
752                        )
753                        .await?;
754                }
755                return Ok(());
756            }
757            if steer {
758                self.deliver_to_subagent(&parent_launch, &runs, &notice, Some(key)).await?;
759            } else if let Some(first) = runs.first() {
760                let mut run = self.follow_up_run(&parent_launch, first, &notice);
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, &notice)
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, &notice, 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, &notice, key).await?;
793        }
794        Ok(())
795    }
796
797    /// Whether the parent's session already holds the notice that starts with `header`.
798    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    /// Enqueues the parent's turn that receives `notice`.
822    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        // Notices for one session run one at a time, so two sub-agents finishing together
844        // never run two turns of the parent's session at once.
845        .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    /// Tells every parent about finished runs of its sub-agents it was not told about: a
862    /// host that stopped between a run's end and the notice — a crash, `kill -9` — catches
863    /// up here. It looks at runs that finished within
864    /// [`SubagentConfig::reconcile_window`], leaves cancelled runs out, and tells a parent by
865    /// a keyed run of its session only, never by steering a turn, so a notice already
866    /// queued is not delivered twice. Returns how many finished runs it looked at.
867    ///
868    /// # Errors
869    ///
870    /// The store's error.
871    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        // The parent's own run says how deep it is and which target its session runs.
908        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        // The limits a start asks for replace the default's; the rest keep the default's.
953        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        // A queued or parked run is cancelled at once and no worker reports it.
1084        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/// The [`WorkerHooks`] that report a plain [`DurableWorker`](super::DurableWorker)'s
1097/// sub-agent runs to a [`DurableSubagents`] host: claims, parks on held calls, and
1098/// finished runs, whose parents it tells.
1099///
1100/// # Example
1101///
1102/// ```rust,no_run
1103/// use std::sync::Arc;
1104/// use adk_server::background::{DurableSubagents, DurableWorker, SubagentHooks};
1105///
1106/// # fn example(worker: DurableWorker, subagents: DurableSubagents) {
1107/// let worker = worker.with_hooks(Arc::new(SubagentHooks::new(subagents)));
1108/// # let _ = worker;
1109/// # }
1110/// ```
1111#[derive(Debug, Clone)]
1112pub struct SubagentHooks {
1113    subagents: DurableSubagents,
1114}
1115
1116impl SubagentHooks {
1117    /// Hooks reporting to `subagents`.
1118    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}