Skip to main content

adk_kernel/
subagents.rs

1//! Background sub-agents as kernel processes.
2//!
3//! [`KernelBuilder::subagents`](crate::KernelBuilder::subagents) turns them on: the kernel
4//! hosts a [`DurableSubagents`] whose runs are processes of its `background` queue, and
5//! [`Kernel::subagents`](crate::Kernel::subagents) returns it.
6//!
7//! | Concern | In a kernel |
8//! |---|---|
9//! | A sub-agent's run | A process of kind [`ProcessKind::Subagent`], spawned through the process table: a freeze refuses it, its partition's quotas and spend cap admit it, `ps` and `top` list it with its parent |
10//! | The run that tells the parent | A process of kind `triggered:subagent` whose parent is the sub-agent's run |
11//! | Steering | [`Kernel::steer`](crate::Kernel::steer) on the replica that runs the turn |
12//! | Cancel | [`ProcessTable::kill`](crate::ProcessTable::kill) |
13//! | Status | [`KernelEvent::Subagent`] on the bus at every change; a `WebhookSink` filtered to [`EventKind::Subagent`](crate::EventKind::Subagent) delivers each as a signed webhook |
14//! | Restart | [`Kernel::start`](crate::Kernel::start) runs [`DurableSubagents::reconcile`], so a parent is told about a sub-agent that finished while the kernel was killed |
15//!
16//! A tool built before the kernel reaches it through a [`SubagentHandle`], bound by
17//! [`KernelBuilder::subagent_handle`](crate::KernelBuilder::subagent_handle).
18
19use std::sync::{Arc, OnceLock, RwLock, Weak};
20
21use adk_core::{
22    FollowUp, NewRun, Result, RunRecord, SteerReceipt, SubagentHost, SubagentLaunch,
23    SubagentRecord, SubagentScope, SubagentStart, SubagentTarget,
24};
25use adk_server::background::{DurableSubagents, SubagentBackend, WeakSubagents};
26use async_trait::async_trait;
27
28use crate::bus::KernelEvent;
29use crate::kernel::{Kernel, KernelInner};
30use crate::process::{ProcessKind, ProcessSpec, ProcessTable};
31use crate::supervise::Supervision;
32
33/// The label of a sub-agent's processes that holds its id.
34pub const SUBAGENT_LABEL: &str = "subagent";
35
36/// The label of a sub-agent's processes that holds its name.
37pub const SUBAGENT_NAME_LABEL: &str = "subagent.name";
38
39/// The source of the processes that tell a parent about its sub-agent:
40/// `triggered:subagent`.
41pub const SUBAGENT_NOTICE_SOURCE: &str = "subagent";
42
43/// The kernel's [`SubagentBackend`]: the process table, the kernel's steering and its bus.
44pub(crate) struct KernelSubagentBackend {
45    pub(crate) processes: ProcessTable,
46    pub(crate) sup: Arc<Supervision>,
47    pub(crate) kernel: OnceLock<Weak<KernelInner>>,
48}
49
50impl KernelSubagentBackend {
51    fn spec(launch: &SubagentLaunch, kind: ProcessKind) -> ProcessSpec {
52        let spec = ProcessSpec::new(kind)
53            .with_label(SUBAGENT_LABEL, launch.id.clone())
54            .with_label(SUBAGENT_NAME_LABEL, launch.name.clone());
55        match &launch.parent.run_id {
56            Some(parent) => spec.with_parent(parent.clone()),
57            None => spec,
58        }
59    }
60}
61
62#[async_trait]
63impl SubagentBackend for KernelSubagentBackend {
64    async fn enqueue_subagent(&self, run: NewRun, launch: &SubagentLaunch) -> Result<RunRecord> {
65        let spec = Self::spec(launch, ProcessKind::Subagent);
66        Ok(self.processes.spawn(run, spec).await?.run)
67    }
68
69    async fn enqueue_notice(
70        &self,
71        run: NewRun,
72        child: &RunRecord,
73        launch: &SubagentLaunch,
74    ) -> Result<RunRecord> {
75        let spec =
76            ProcessSpec::new(ProcessKind::Triggered { source: SUBAGENT_NOTICE_SOURCE.to_string() })
77                .with_parent(child.run_id.clone())
78                .with_label(SUBAGENT_LABEL, launch.id.clone());
79        Ok(self.processes.spawn(run, spec).await?.run)
80    }
81
82    async fn steer(
83        &self,
84        app_name: &str,
85        user_id: &str,
86        session_id: &str,
87        text: &str,
88    ) -> Result<Option<SteerReceipt>> {
89        if app_name != self.sup.app_name {
90            return Ok(None);
91        }
92        let Some(kernel) = self.kernel.get().and_then(Weak::upgrade).map(Kernel::from_inner) else {
93            return Ok(None);
94        };
95        Ok(kernel.steer(user_id, session_id, text).await?.map(|steering| steering.receipt))
96    }
97
98    async fn cancel(&self, run_id: &str) -> Result<()> {
99        match self.processes.kill(run_id, "cancelled by the agent that started it").await {
100            Ok(()) => Ok(()),
101            // Finished meanwhile: nothing to cancel.
102            Err(crate::KernelError::InvalidState { .. }) => Ok(()),
103            Err(error) => Err(error.into()),
104        }
105    }
106
107    async fn changed(&self, record: &SubagentRecord) {
108        self.sup.publish(KernelEvent::Subagent {
109            pid: record.run_id.clone(),
110            id: record.id.clone(),
111            name: record.name.clone(),
112            parent: record.parent.run_id.clone(),
113            status: record.status,
114        });
115    }
116}
117
118/// A handle on a kernel's sub-agent host that does not keep the kernel alive, bound when
119/// the kernel is built with it: an agent's sub-agent tools exist before the kernel that
120/// hosts the agent. Until bound, and after the kernel is gone, every operation fails with
121/// `subagent.unavailable`.
122///
123/// # Example
124///
125/// ```rust
126/// use std::sync::Arc;
127/// use adk_agent::subagents::SubagentTools;
128/// use adk_kernel::SubagentHandle;
129///
130/// let handle = SubagentHandle::new();
131/// let tools = SubagentTools::new(Arc::new(handle.clone())).tools();
132/// assert_eq!(tools.len(), 4);
133/// // `Kernel::builder().subagents(SubagentConfig::default()).subagent_handle(handle)` binds it.
134/// ```
135#[derive(Clone, Default)]
136pub struct SubagentHandle {
137    slot: Arc<RwLock<WeakSubagents>>,
138    targets: Arc<RwLock<Vec<SubagentTarget>>>,
139}
140
141impl std::fmt::Debug for SubagentHandle {
142    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
143        f.debug_struct("SubagentHandle").field("bound", &self.get().is_some()).finish()
144    }
145}
146
147impl SubagentHandle {
148    /// An unbound handle.
149    pub fn new() -> Self {
150        Self::default()
151    }
152
153    /// Names the targets the bound host will run, so a `start_subagent` tool built before
154    /// the kernel describes them to the model; binding replaces them with the host's.
155    #[must_use]
156    pub fn with_targets(self, targets: impl IntoIterator<Item = SubagentTarget>) -> Self {
157        *self.targets.write().unwrap_or_else(|e| e.into_inner()) = targets.into_iter().collect();
158        self
159    }
160
161    /// The host of the kernel last built with this handle, while that kernel lives.
162    pub fn get(&self) -> Option<DurableSubagents> {
163        self.slot.read().unwrap_or_else(|e| e.into_inner()).upgrade()
164    }
165
166    pub(crate) fn bind(&self, host: &DurableSubagents) {
167        *self.slot.write().unwrap_or_else(|e| e.into_inner()) = host.downgrade();
168        *self.targets.write().unwrap_or_else(|e| e.into_inner()) = host.targets();
169    }
170
171    fn host(&self) -> Result<DurableSubagents> {
172        self.get().ok_or_else(|| {
173            adk_core::AdkError::new(
174                adk_core::ErrorComponent::Agent,
175                adk_core::ErrorCategory::Unavailable,
176                "subagent.unavailable",
177                "background sub-agents need the agent to run in a kernel built with \
178                 KernelBuilder::subagents and this handle; none is running",
179            )
180        })
181    }
182}
183
184#[async_trait]
185impl SubagentHost for SubagentHandle {
186    async fn start(&self, start: SubagentStart) -> Result<SubagentRecord> {
187        self.host()?.start(start).await
188    }
189
190    async fn get(&self, scope: &SubagentScope, id: &str) -> Result<Option<SubagentRecord>> {
191        SubagentHost::get(&self.host()?, scope, id).await
192    }
193
194    async fn list(&self, scope: &SubagentScope) -> Result<Vec<SubagentRecord>> {
195        self.host()?.list(scope).await
196    }
197
198    async fn send(&self, scope: &SubagentScope, id: &str, message: &str) -> Result<FollowUp> {
199        self.host()?.send(scope, id, message).await
200    }
201
202    async fn cancel(&self, scope: &SubagentScope, id: &str) -> Result<SubagentRecord> {
203        self.host()?.cancel(scope, id).await
204    }
205
206    fn targets(&self) -> Vec<SubagentTarget> {
207        self.get()
208            .map(|host| host.targets())
209            .unwrap_or_else(|| self.targets.read().unwrap_or_else(|e| e.into_inner()).clone())
210    }
211}