1use serde_json::{json, Value};
8use std::sync::atomic::Ordering;
9use std::sync::{Arc, RwLock};
10use std::time::Duration;
11use tokio::sync::{mpsc, oneshot};
12
13use crate::{Result, RuntimeError, LlmEvent, SessionEvent, AgentEvent};
14use super::super::{Tool, ToolContext, resolve_agent_prompt, NEXT_SUBAGENT_ID};
15use crate::runtime::subagent::{SubagentHandle, SubagentResult, SubagentStatus, SubagentState};
16
17pub struct SubagentStartTool;
18
19#[async_trait::async_trait]
20impl Tool for SubagentStartTool {
21 fn name(&self) -> &str { "subagent_start" }
22
23 fn description(&self) -> &str {
24 "Dispatch a reactive subagent and return immediately with a handle_id. \
25 The subagent runs in the background — use subagent_status to poll, \
26 subagent_steer to inject guidance mid-run, and subagent_collect to poll for the result (non-blocking — call \
27 repeatedly until done). Use this for parallel execution or when you \
28 want to continue working while the subagent runs. For simple sequential \
29 delegation, use subagent instead. Provide either an agent name (resolves \
30 from ~/.synaps-cli/agents/<name>.md) or a system_prompt string directly."
31 }
32
33 fn parameters(&self) -> Value {
34 json!({
35 "type": "object",
36 "properties": {
37 "agent": {
38 "type": "string",
39 "description": "Agent name — resolves to ~/.synaps-cli/agents/<name>.md. Mutually exclusive with system_prompt."
40 },
41 "system_prompt": {
42 "type": "string",
43 "description": "Inline system prompt for the subagent. Use when you don't have a named agent file."
44 },
45 "task": {
46 "type": "string",
47 "description": "The task/prompt to send to the subagent."
48 },
49 "model": {
50 "type": "string",
51 "description": "Model override (default: claude-sonnet-4-6). Use claude-opus-4-7 for complex tasks."
52 },
53 "timeout": {
54 "type": "integer",
55 "description": "Timeout in seconds (default: 300). Increase for long-running tasks."
56 }
57 },
58 "required": ["task"]
59 })
60 }
61
62 async fn execute(&self, params: Value, ctx: ToolContext) -> Result<String> {
63 let task = params["task"].as_str()
65 .ok_or_else(|| RuntimeError::Tool("Missing 'task' parameter".to_string()))?
66 .to_string();
67
68 let is_blank = |s: &String| s.chars().all(|c| c.is_whitespace() || c.is_control());
74 let agent_name = params["agent"]
75 .as_str()
76 .map(|s| s.to_string())
77 .filter(|s| !is_blank(s));
78 let inline_prompt = params["system_prompt"]
79 .as_str()
80 .map(|s| s.to_string())
81 .filter(|s| !is_blank(s));
82 let model_override = params["model"].as_str().map(|s| s.to_string());
83 let timeout_secs = params["timeout"].as_u64().unwrap_or(ctx.limits.subagent_timeout);
84
85 let system_prompt = match (&agent_name, &inline_prompt) {
86 (Some(name), _) => resolve_agent_prompt(name).map_err(RuntimeError::Tool)?,
87 (None, Some(p)) => p.clone(),
88 (None, None) => {
89 return Err(RuntimeError::Tool(
90 "Must provide either 'agent' (name) or 'system_prompt' (inline). Got neither.".to_string()
91 ));
92 }
93 };
94
95 let label = agent_name.as_deref().unwrap_or("inline").to_string();
96 let model = model_override.unwrap_or_else(|| crate::models::default_model().to_string());
97 let task_preview: String = task.chars().take(80).collect();
98 let task_full = task.clone();
99 let subagent_id = NEXT_SUBAGENT_ID.fetch_add(1, Ordering::Relaxed);
100 let handle_id = format!("sa_{}", subagent_id);
101
102 tracing::info!("subagent_start: dispatching '{}' (id={}) model={}", label, handle_id, model);
103
104 let state = Arc::new(RwLock::new(SubagentState::new()));
106
107 let (steer_tx, steer_rx) = mpsc::unbounded_channel::<String>();
109 let (shutdown_tx, shutdown_rx) = oneshot::channel::<()>();
110 let (result_tx, result_rx) = oneshot::channel::<SubagentResult>();
111
112 if let Some(ref tx) = ctx.channels.tx_events {
114 let _ = tx.send(crate::StreamEvent::Agent(AgentEvent::SubagentStart {
115 subagent_id,
116 agent_name: label.clone(),
117 task_preview: task_preview.clone(),
118 }));
119 }
120
121 let state_t = Arc::clone(&state);
123 let task_full_a = task_full.clone();
124 let label_inner = label.clone();
125 let model_inner = model.clone();
126 let tx_events_inner = ctx.channels.tx_events.clone();
127 let start_time = std::time::Instant::now();
128
129 let system_prompt_for_handle = system_prompt.clone();
131 let thread_handle = std::thread::spawn(move || {
132 let panic_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
133 let rt = match tokio::runtime::Builder::new_current_thread()
134 .enable_all()
135 .build()
136 {
137 Ok(rt) => rt,
138 Err(e) => {
139 state_t.write().unwrap().status =
140 SubagentStatus::Failed(format!("tokio runtime: {}", e));
141 return;
142 }
143 };
144
145 let state_a = Arc::clone(&state_t);
147 let label_a = label_inner.clone();
148 let model_a = model_inner.clone();
149 let tx_events_a = tx_events_inner.clone();
150 let task_for_timeout = task_full_a.clone();
151 let task_for_complete = task_full_a;
152
153 let outcome: std::result::Result<SubagentResult, String> = rt.block_on(async move {
154 use futures::StreamExt;
155
156 let mut runtime = match crate::Runtime::new().await {
157 Ok(r) => r,
158 Err(e) => return Err(format!("Failed to create subagent runtime: {}", e)),
159 };
160
161 super::apply_subagent_runtime_policy(&mut runtime, &crate::config::load_config());
166 runtime.set_system_prompt(system_prompt);
167 runtime.set_model(model_a.clone());
168 let tools = if let Some(ext_mgr) = crate::runtime::openai::extension_manager_for_routing() {
169 let mgr = ext_mgr.read().await;
170 if let Some(shared) = mgr.tools_shared() {
171 let extension_tools = shared.read().await;
172 crate::ToolRegistry::without_subagent_with_extensions(&extension_tools)
173 } else {
174 crate::ToolRegistry::without_subagent()
175 }
176 } else {
177 crate::ToolRegistry::without_subagent()
178 };
179 runtime.set_tools(tools);
180
181 let cancel = crate::CancellationToken::new();
182 let cancel_inner = cancel.clone();
183 tokio::spawn(async move {
184 let _ = shutdown_rx.await;
185 cancel_inner.cancel();
186 });
187
188 let mut stream = runtime.run_stream_with_messages(vec![serde_json::json!({"role": "user", "content": task})], cancel, Some(steer_rx), None, false).await;
189
190 let mut tool_count = 0u32;
191 let mut total_input_tokens = 0u64;
192 let mut total_output_tokens = 0u64;
193 let mut total_cache_read = 0u64;
194 let mut total_cache_creation = 0u64;
195 let mut total_cache_5m: Option<u64> = None;
197 let mut total_cache_1h: Option<u64> = None;
198
199 let timeout_fut = tokio::time::sleep(Duration::from_secs(timeout_secs));
200 tokio::pin!(timeout_fut);
201
202 loop {
203 tokio::select! {
204 event = stream.next() => {
205 let Some(event) = event else { break };
206 match event {
207 crate::StreamEvent::Llm(LlmEvent::Thinking(_)) => {
208 if let Some(ref tx) = tx_events_a {
209 let _ = tx.send(crate::StreamEvent::Agent(AgentEvent::SubagentUpdate {
210 subagent_id,
211 agent_name: label_a.clone(),
212 status: "💭 thinking...".to_string(),
213 }));
214 }
215 }
216 crate::StreamEvent::Llm(LlmEvent::Text(text)) => {
217 state_a.write().unwrap().partial_text.push_str(&text);
218 }
219 crate::StreamEvent::Llm(LlmEvent::ToolUseStart { tool_name: name, .. }) => {
220 tool_count += 1;
221 if let Some(ref tx) = tx_events_a {
222 let _ = tx.send(crate::StreamEvent::Agent(AgentEvent::SubagentUpdate {
223 subagent_id,
224 agent_name: label_a.clone(),
225 status: format!("⚙ {} (tool #{})", name, tool_count),
226 }));
227 }
228 }
229 crate::StreamEvent::Llm(LlmEvent::ToolUse { tool_name, input, .. }) => {
230 let input_str = input.to_string();
231 let input_preview: String = input_str.chars().take(200).collect();
232 state_a.write().unwrap().tool_log
233 .push(format!("[tool_use]: {} — {}", tool_name, input_preview));
234 let detail = match tool_name.as_str() {
235 "bash" => {
236 let cmd = input["command"].as_str().unwrap_or("");
237 let preview: String = cmd.chars().take(60).collect();
238 format!("$ {}", preview)
239 }
240 "read" => format!("reading {}", input["path"].as_str().unwrap_or("?").rsplit('/').next().unwrap_or("?")),
241 "write" => format!("writing {}", input["path"].as_str().unwrap_or("?").rsplit('/').next().unwrap_or("?")),
242 "edit" => format!("editing {}", input["path"].as_str().unwrap_or("?").rsplit('/').next().unwrap_or("?")),
243 "grep" => format!("grep /{}/", input["pattern"].as_str().unwrap_or("?").chars().take(30).collect::<String>()),
244 "find" => format!("find {}", input["pattern"].as_str().unwrap_or("?")),
245 "ls" => format!("ls {}", input["path"].as_str().unwrap_or(".").rsplit('/').next().unwrap_or(".")),
246 other => {
247 if other.starts_with("ext__") {
248 other.splitn(3, "__").last().unwrap_or(other).to_string()
249 } else {
250 other.to_string()
251 }
252 }
253 };
254 if let Some(ref tx) = tx_events_a {
255 let _ = tx.send(crate::StreamEvent::Agent(AgentEvent::SubagentUpdate {
256 subagent_id,
257 agent_name: label_a.clone(),
258 status: detail,
259 }));
260 }
261 }
262 crate::StreamEvent::Llm(LlmEvent::ToolResult { result, .. }) => {
263 let preview: String = result.chars().take(300).collect();
264 state_a.write().unwrap().tool_log
265 .push(format!("[tool_result]: {}", preview));
266 }
267 crate::StreamEvent::Session(SessionEvent::Usage {
268 input_tokens, output_tokens,
269 cache_read_input_tokens, cache_creation_input_tokens,
270 cache_creation_5m, cache_creation_1h,
271 model: _,
272 }) => {
273 total_input_tokens += input_tokens;
274 total_output_tokens += output_tokens;
275 total_cache_read += cache_read_input_tokens;
276 total_cache_creation += cache_creation_input_tokens;
277 crate::core::rpc_dispatch::merge_split(&mut total_cache_5m, cache_creation_5m);
278 crate::core::rpc_dispatch::merge_split(&mut total_cache_1h, cache_creation_1h);
279 }
280 crate::StreamEvent::Session(SessionEvent::Error(e)) => return Err(e),
281 crate::StreamEvent::Session(SessionEvent::Done) => break,
282 _ => {}
283 }
284 }
285 _ = &mut timeout_fut => {
286 let (partial, log) = {
287 let mut s = state_a.write().unwrap();
288 s.status = SubagentStatus::TimedOut;
289 s.conversation_state = vec![
290 serde_json::json!({"role": "user", "content": task_for_timeout.clone()}),
291 serde_json::json!({"role": "assistant", "content": &s.partial_text}),
292 ];
293 (s.partial_text.clone(), s.tool_log.clone())
294 };
295 let mut text = format!("[TIMED OUT after {}s — partial results below]\n\n", timeout_secs);
296 if !log.is_empty() {
297 text.push_str(&log.join("\n"));
298 text.push('\n');
299 }
300 if !partial.is_empty() {
301 text.push_str("\n[partial response]:\n");
302 text.push_str(&partial);
303 }
304 return Ok(SubagentResult {
305 text,
306 model: model_a.clone(),
307 input_tokens: total_input_tokens,
308 output_tokens: total_output_tokens,
309 cache_read: total_cache_read,
310 cache_creation: total_cache_creation,
311 cache_creation_5m: total_cache_5m,
312 cache_creation_1h: total_cache_1h,
313 tool_count,
314 });
315 }
316 }
317 }
318
319 Ok(SubagentResult {
320 text: state_a.write().unwrap().partial_text.clone(),
321 model: model_a.clone(),
322 input_tokens: total_input_tokens,
323 output_tokens: total_output_tokens,
324 cache_read: total_cache_read,
325 cache_creation: total_cache_creation,
326 cache_creation_5m: total_cache_5m,
327 cache_creation_1h: total_cache_1h,
328 tool_count,
329 })
330 });
331
332 match outcome {
333 Ok(sa_result) => {
334 {
336 let mut s = state_t.write().unwrap();
337 if matches!(s.status, SubagentStatus::Running) {
338 s.status = SubagentStatus::Completed;
339 s.conversation_state = vec![
340 serde_json::json!({"role": "user", "content": task_for_complete.clone()}),
341 serde_json::json!({"role": "assistant", "content": sa_result.text.clone()}),
342 ];
343 }
344 }
345 let elapsed = start_time.elapsed().as_secs_f64();
346 let preview: String = sa_result.text.chars().take(120).collect();
347 if let Some(ref tx) = tx_events_inner {
348 let _ = tx.send(crate::StreamEvent::Agent(AgentEvent::SubagentDone {
349 subagent_id,
350 agent_name: label_inner.clone(),
351 result_preview: preview,
352 duration_secs: elapsed,
353 }));
354 }
355 let _ = result_tx.send(sa_result);
356 }
357 Err(e) => {
358 state_t.write().unwrap().status = SubagentStatus::Failed(e.clone());
359 let elapsed = start_time.elapsed().as_secs_f64();
360 if let Some(ref tx) = tx_events_inner {
361 let _ = tx.send(crate::StreamEvent::Agent(AgentEvent::SubagentDone {
362 subagent_id,
363 agent_name: label_inner.clone(),
364 result_preview: format!("ERROR: {}", e),
365 duration_secs: elapsed,
366 }));
367 }
368 }
370 }
371 }));
372
373 if let Err(panic_info) = panic_result {
374 let msg = if let Some(s) = panic_info.downcast_ref::<&str>() {
375 s.to_string()
376 } else if let Some(s) = panic_info.downcast_ref::<String>() {
377 s.clone()
378 } else {
379 "unknown panic".to_string()
380 };
381 tracing::error!("Subagent thread panicked: {}", msg);
382 state_t.write().unwrap().status = SubagentStatus::Failed(format!("panic: {}", msg));
383 }
384 });
385
386 let handle = SubagentHandle::new(
388 handle_id.clone(),
389 label.clone(),
390 task_preview,
391 model,
392 system_prompt_for_handle,
393 timeout_secs,
394 state,
395 Some(steer_tx),
396 Some(shutdown_tx),
397 Some(result_rx),
398 );
399
400 if let Some(registry) = &ctx.capabilities.subagent_registry {
401 let mut reg = registry.lock().unwrap();
402 reg.register(handle);
403 if let Some(h) = reg.get_mut(&handle_id) {
404 h.set_thread_handle(thread_handle);
405 }
406 } else {
407 return Err(RuntimeError::Tool(
408 "subagent_start requires a subagent_registry in ToolContext".to_string()
409 ));
410 }
411
412 Ok(json!({
413 "handle_id": handle_id,
414 "agent_name": label,
415 "status": "running"
416 }).to_string())
417 }
418}
419
420#[cfg(test)]
421mod tests {
422 use super::*;
423 use crate::tools::test_helpers::create_tool_context;
424 use crate::tools::{SubagentRegistry, Tool};
425 use serde_json::json;
426 use std::sync::{Arc, Mutex};
427
428 #[tokio::test]
429 async fn test_subagent_start_blank_agent_uses_system_prompt() {
430 let tool = SubagentStartTool;
431 let mut ctx = create_tool_context();
432 ctx.capabilities.subagent_registry = Some(Arc::new(Mutex::new(SubagentRegistry::new())));
433
434 let params = json!({
435 "agent": "",
436 "system_prompt": "You are a concise test subagent. Reply with only: ok",
437 "task": "Say ok",
438 "model": "claude-sonnet-4-6",
439 "timeout": 1
440 });
441
442 let result = tool.execute(params, ctx).await;
443 assert!(result.is_ok(), "blank agent should not be resolved as ~/.synaps-cli/agents/.md: {result:?}");
444 let body: serde_json::Value = serde_json::from_str(&result.unwrap()).unwrap();
445 assert_eq!(body["agent_name"], "inline");
446 assert!(body["handle_id"].as_str().unwrap_or_default().starts_with("sa_"));
447 }
448}