Skip to main content

adk_agent/
subagents.rs

1//! The tools that let a model run background sub-agents through a
2//! [`SubagentHost`].
3//!
4//! | Tool | Effect | Does |
5//! |---|---|---|
6//! | `start_subagent` | non-idempotent | Starts a sub-agent and returns at once; the parent keeps working |
7//! | `subagent_status` | read-only | One sub-agent's record with its full answer, or every sub-agent this session started |
8//! | `message_subagent` | non-idempotent | Sends a follow-up: steers its running turn, or queues its next run |
9//! | `cancel_subagent` | idempotent | Cancels it |
10//!
11//! Each call goes through the governed tool path like any other: the run's tool policy,
12//! confirmation and audit apply, and a policy can require approval for `start_subagent`.
13//! The start carves the sub-agent's budget from the calling run's
14//! ([`BudgetTracker::carve`](adk_core::BudgetTracker::carve)), limits it to the caller's
15//! tools, and is keyed by the call's idempotency key, so a call replayed after a crash
16//! starts nothing twice. Every tool answers only for sub-agents of the caller's session.
17//!
18//! # Example
19//!
20//! ```rust,no_run
21//! use std::sync::Arc;
22//! use adk_agent::LlmAgentBuilder;
23//! use adk_agent::subagents::SubagentTools;
24//! use adk_core::SubagentHost;
25//!
26//! # fn example(model: Arc<dyn adk_core::Llm>, host: Arc<dyn SubagentHost>) -> adk_core::Result<()> {
27//! let mut builder = LlmAgentBuilder::new("lead")
28//!     .instruction("Delegate long research to background sub-agents and keep working.")
29//!     .model(model);
30//! for tool in SubagentTools::new(host).tools() {
31//!     builder = builder.tool(tool);
32//! }
33//! let lead = builder.build()?;
34//! # let _ = lead;
35//! # Ok(())
36//! # }
37//! ```
38
39use std::sync::Arc;
40
41use adk_core::subagent::{SubagentRecord, SubagentScope, SubagentStart};
42use adk_core::{
43    AdkError, ErrorCategory, ErrorComponent, Result, RunBudget, SubagentHost, SubagentMode,
44    SubagentRequest, Tool, ToolContext, ToolEffect,
45};
46use async_trait::async_trait;
47use serde_json::{Value, json};
48
49/// The most characters of each answer `subagent_status` lists for several sub-agents; one
50/// sub-agent's record carries its whole answer.
51const LIST_RESULT_CHARS: usize = 600;
52
53/// The four sub-agent tools over one host.
54///
55/// # Example
56///
57/// ```rust,no_run
58/// use std::sync::Arc;
59/// use adk_agent::subagents::SubagentTools;
60///
61/// # fn example(host: Arc<dyn adk_core::SubagentHost>) {
62/// let tools = SubagentTools::new(host).tools();
63/// let names: Vec<&str> = tools.iter().map(|tool| tool.name()).collect();
64/// assert_eq!(names, ["start_subagent", "subagent_status", "message_subagent", "cancel_subagent"]);
65/// # }
66/// ```
67#[derive(Clone)]
68pub struct SubagentTools {
69    host: Arc<dyn SubagentHost>,
70}
71
72impl std::fmt::Debug for SubagentTools {
73    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
74        f.debug_struct("SubagentTools").finish_non_exhaustive()
75    }
76}
77
78impl SubagentTools {
79    /// The tools over `host`.
80    pub fn new(host: Arc<dyn SubagentHost>) -> Self {
81        Self { host }
82    }
83
84    /// `start_subagent`, `subagent_status`, `message_subagent` and `cancel_subagent`.
85    pub fn tools(&self) -> Vec<Arc<dyn Tool>> {
86        vec![
87            Arc::new(StartSubagentTool::new(Arc::clone(&self.host))),
88            Arc::new(SubagentStatusTool { host: Arc::clone(&self.host) }),
89            Arc::new(MessageSubagentTool { host: Arc::clone(&self.host) }),
90            Arc::new(CancelSubagentTool { host: Arc::clone(&self.host) }),
91        ]
92    }
93}
94
95fn invalid(message: impl Into<String>) -> AdkError {
96    AdkError::new(
97        ErrorComponent::Tool,
98        ErrorCategory::InvalidInput,
99        "subagent.invalid_args",
100        message,
101    )
102}
103
104fn required<'a>(args: &'a Value, key: &str) -> Result<&'a str> {
105    args.get(key)
106        .and_then(Value::as_str)
107        .map(str::trim)
108        .filter(|value| !value.is_empty())
109        .ok_or_else(|| invalid(format!("`{key}` is required and must be a non-empty string")))
110}
111
112fn record_json(record: &SubagentRecord, result_chars: Option<usize>) -> Value {
113    let mut value = json!({
114        "id": record.id,
115        "name": record.name,
116        "agent": record.target,
117        "status": record.status.as_str(),
118        "mode": record.mode.as_str(),
119        "runs": record.runs,
120        "task": record.task,
121        "startedAt": record.created_at,
122        "updatedAt": record.updated_at,
123    });
124    if let Some(result) = &record.result {
125        value["result"] = match result_chars {
126            Some(max) if result.chars().count() > max => {
127                Value::String(format!("{}…", result.chars().take(max).collect::<String>()))
128            }
129            _ => Value::String(result.clone()),
130        };
131    }
132    if let Some(error) = &record.error {
133        value["error"] = Value::String(error.clone());
134    }
135    value
136}
137
138/// `start_subagent`: starts a sub-agent in the background.
139pub struct StartSubagentTool {
140    host: Arc<dyn SubagentHost>,
141    description: String,
142}
143
144impl StartSubagentTool {
145    /// The tool over `host`, describing the host's targets to the model.
146    pub fn new(host: Arc<dyn SubagentHost>) -> Self {
147        let mut description = "Starts a sub-agent that works on a task in the background and \
148            returns at once with its id, so you keep working. You are told when it finishes — \
149            in this turn if it is still running, otherwise in a new turn — and you can check it \
150            with subagent_status, send it a follow-up with message_subagent, or stop it with \
151            cancel_subagent. Give it a complete, self-contained task. Use mode `fork` to give it \
152            a copy of this conversation, `fresh` (the default) to give it only the task."
153            .to_string();
154        let targets = host.targets();
155        if !targets.is_empty() {
156            description.push_str(" Agents you can start (`agent`):");
157            for target in targets {
158                description.push_str(&format!(" `{}` — {};", target.name, target.description));
159            }
160        }
161        Self { host, description }
162    }
163}
164
165#[async_trait]
166impl Tool for StartSubagentTool {
167    fn name(&self) -> &str {
168        "start_subagent"
169    }
170
171    fn description(&self) -> &str {
172        &self.description
173    }
174
175    fn parameters_schema(&self) -> Option<Value> {
176        Some(json!({
177            "type": "object",
178            "properties": {
179                "task": { "type": "string", "description": "What the sub-agent is to do, complete and self-contained." },
180                "name": { "type": "string", "description": "A short name to refer to it by." },
181                "agent": { "type": "string", "description": "The agent to start; this host's default when omitted." },
182                "mode": { "type": "string", "enum": ["fresh", "fork"], "description": "`fork` copies this conversation into its session; `fresh` gives it only the task." },
183                "maxModelCalls": { "type": "integer", "minimum": 1, "description": "Most model calls it may make; taken out of your own budget." },
184                "maxToolCalls": { "type": "integer", "minimum": 1, "description": "Most tool calls it may make." },
185                "maxCostUsd": { "type": "number", "exclusiveMinimum": 0, "description": "Most it may spend, in US dollars." },
186                "notify": { "type": "boolean", "description": "Whether you are told when it finishes. Defaults to true." }
187            },
188            "required": ["task"]
189        }))
190    }
191
192    fn effect(&self) -> ToolEffect {
193        ToolEffect::NonIdempotent
194    }
195
196    async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
197        let mut request = SubagentRequest::new(required(&args, "task")?);
198        if let Some(name) = args.get("name").and_then(Value::as_str) {
199            request = request.with_name(name);
200        }
201        if let Some(agent) =
202            args.get("agent").and_then(Value::as_str).filter(|a| !a.trim().is_empty())
203        {
204            request = request.with_target(agent.trim());
205        }
206        request = request.with_mode(match args.get("mode").and_then(Value::as_str) {
207            None | Some("fresh") => SubagentMode::Fresh,
208            Some("fork") => SubagentMode::Fork,
209            Some(other) => {
210                return Err(invalid(format!("`mode` is `fresh` or `fork`, not `{other}`")));
211            }
212        });
213        let mut budget = None;
214        if let Some(calls) = args.get("maxModelCalls").and_then(Value::as_u64) {
215            budget = Some(budget.unwrap_or_else(RunBudget::new).max_model_calls(calls));
216        }
217        if let Some(calls) = args.get("maxToolCalls").and_then(Value::as_u64) {
218            budget = Some(budget.unwrap_or_else(RunBudget::new).max_tool_calls(calls));
219        }
220        if let Some(usd) = args.get("maxCostUsd").and_then(Value::as_f64) {
221            budget = Some(budget.unwrap_or_else(RunBudget::new).max_cost_usd(usd));
222        }
223        if let Some(budget) = budget {
224            request = request.with_budget(budget);
225        }
226        if args.get("notify").and_then(Value::as_bool) == Some(false) {
227            request = request.without_notification();
228        }
229        let start = SubagentStart::from_tool_context(ctx.as_ref(), request);
230        let record = self.host.start(start).await?;
231        let mut value = record_json(&record, None);
232        value["budget"] = serde_json::to_value(&record.budget).unwrap_or(Value::Null);
233        Ok(value)
234    }
235}
236
237/// `subagent_status`: one sub-agent's record, or every sub-agent of this session.
238pub struct SubagentStatusTool {
239    host: Arc<dyn SubagentHost>,
240}
241
242#[async_trait]
243impl Tool for SubagentStatusTool {
244    fn name(&self) -> &str {
245        "subagent_status"
246    }
247
248    fn description(&self) -> &str {
249        "Reports on the sub-agents this conversation started: with `id`, one sub-agent and its \
250         full answer; without, every one with its status (queued, running, waitingForHuman, \
251         parked, completed, failed, cancelled) and the start of its answer."
252    }
253
254    fn parameters_schema(&self) -> Option<Value> {
255        Some(json!({
256            "type": "object",
257            "properties": { "id": { "type": "string", "description": "The sub-agent's id." } }
258        }))
259    }
260
261    fn is_read_only(&self) -> bool {
262        true
263    }
264
265    fn is_concurrency_safe(&self) -> bool {
266        true
267    }
268
269    async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
270        let scope = SubagentScope::from_tool_context(ctx.as_ref());
271        match args.get("id").and_then(Value::as_str).filter(|id| !id.trim().is_empty()) {
272            Some(id) => match self.host.get(&scope, id.trim()).await? {
273                Some(record) => Ok(record_json(&record, None)),
274                None => Err(adk_core::subagent::subagent_not_found(id)),
275            },
276            None => {
277                let records = self.host.list(&scope).await?;
278                Ok(json!({
279                    "subagents": records
280                        .iter()
281                        .map(|record| record_json(record, Some(LIST_RESULT_CHARS)))
282                        .collect::<Vec<_>>()
283                }))
284            }
285        }
286    }
287}
288
289/// `message_subagent`: a follow-up message to a sub-agent.
290pub struct MessageSubagentTool {
291    host: Arc<dyn SubagentHost>,
292}
293
294#[async_trait]
295impl Tool for MessageSubagentTool {
296    fn name(&self) -> &str {
297        "message_subagent"
298    }
299
300    fn description(&self) -> &str {
301        "Sends a follow-up message to a sub-agent this conversation started. A running \
302         sub-agent reads it at its next step; otherwise it is queued as its next turn, which \
303         also continues a finished sub-agent with its earlier work in context."
304    }
305
306    fn parameters_schema(&self) -> Option<Value> {
307        Some(json!({
308            "type": "object",
309            "properties": {
310                "id": { "type": "string", "description": "The sub-agent's id." },
311                "message": { "type": "string", "description": "What to tell it." }
312            },
313            "required": ["id", "message"]
314        }))
315    }
316
317    fn effect(&self) -> ToolEffect {
318        ToolEffect::NonIdempotent
319    }
320
321    async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
322        let scope = SubagentScope::from_tool_context(ctx.as_ref());
323        let id = required(&args, "id")?;
324        let message = required(&args, "message")?;
325        let follow_up = self.host.send(&scope, id, message).await?;
326        let mut value = serde_json::to_value(&follow_up).unwrap_or(Value::Null);
327        value["id"] = Value::String(id.to_string());
328        Ok(value)
329    }
330}
331
332/// `cancel_subagent`: cancels a sub-agent.
333pub struct CancelSubagentTool {
334    host: Arc<dyn SubagentHost>,
335}
336
337#[async_trait]
338impl Tool for CancelSubagentTool {
339    fn name(&self) -> &str {
340        "cancel_subagent"
341    }
342
343    fn description(&self) -> &str {
344        "Cancels a sub-agent this conversation started. A waiting one stops at once, a running \
345         one at its next step. You are not told about a cancellation you asked for."
346    }
347
348    fn parameters_schema(&self) -> Option<Value> {
349        Some(json!({
350            "type": "object",
351            "properties": { "id": { "type": "string", "description": "The sub-agent's id." } },
352            "required": ["id"]
353        }))
354    }
355
356    fn effect(&self) -> ToolEffect {
357        ToolEffect::Idempotent
358    }
359
360    async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
361        let scope = SubagentScope::from_tool_context(ctx.as_ref());
362        let record = self.host.cancel(&scope, required(&args, "id")?).await?;
363        Ok(record_json(&record, Some(LIST_RESULT_CHARS)))
364    }
365}