1use 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
33pub const SUBAGENT_LABEL: &str = "subagent";
35
36pub const SUBAGENT_NAME_LABEL: &str = "subagent.name";
38
39pub const SUBAGENT_NOTICE_SOURCE: &str = "subagent";
42
43pub(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 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#[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 pub fn new() -> Self {
150 Self::default()
151 }
152
153 #[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 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}