1use 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
49const LIST_RESULT_CHARS: usize = 600;
52
53#[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 pub fn new(host: Arc<dyn SubagentHost>) -> Self {
81 Self { host }
82 }
83
84 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
138pub struct StartSubagentTool {
140 host: Arc<dyn SubagentHost>,
141 description: String,
142}
143
144impl StartSubagentTool {
145 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
237pub 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
289pub 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
332pub 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}