Skip to main content

agent_engine/tools/subagent/
start.rs

1//! SubagentStartTool — dispatch a reactive subagent and return a handle_id immediately.
2//!
3//! Unlike the one-shot `subagent` tool, this tool returns *before* the subagent
4//! finishes. The caller gets a `handle_id` they can poll via `subagent_status`,
5//! steer via `subagent_steer`, or block on via `subagent_collect`.
6
7use serde_json::{json, Value};
8use std::sync::atomic::Ordering;
9use std::sync::{Arc, RwLock};
10use tokio::sync::{mpsc, oneshot};
11
12use super::super::{resolve_agent_prompt, Tool, ToolContext, NEXT_SUBAGENT_ID};
13use crate::runtime::subagent::{SubagentHandle, SubagentResult, SubagentState, SubagentStatus};
14use crate::{AgentEvent, Result, RuntimeError};
15
16pub struct SubagentStartTool;
17
18#[async_trait::async_trait]
19impl Tool for SubagentStartTool {
20    fn origin(&self) -> crate::tools::ToolOrigin {
21        crate::tools::ToolOrigin::Builtin
22    }
23
24    fn name(&self) -> &str {
25        "subagent_start"
26    }
27
28    fn description(&self) -> &str {
29        "Dispatch a reactive subagent and return immediately with a handle_id. \
30         The subagent runs in the background and is REACTIVE: when it finishes, a \
31         completion event is pushed into your queue and you are woken with its \
32         status — do NOT sleep, busy-wait, or poll in a loop waiting for it. After \
33         dispatching, end your turn or keep doing other work; on the completion \
34         event call subagent_collect once with reconciled=true. subagent_status is \
35         for an occasional progress peek, and subagent_steer injects guidance \
36         mid-run. Use this for parallel execution or when you want to continue \
37         working while the subagent runs. For simple sequential delegation that \
38         must block, use subagent instead. Provide either an agent name (resolves \
39         from ~/.synaps-cli/agents/<name>.md) or a system_prompt string directly; \
40         give an inline subagent a short name so it is recognisable in the \
41         subagent panel."
42    }
43
44    fn parameters(&self) -> Value {
45        json!({
46            "type": "object",
47            "properties": {
48                "agent": {
49                    "type": "string",
50                    "description": "Agent name — resolves to ~/.synaps-cli/agents/<name>.md. Mutually exclusive with system_prompt."
51                },
52                "system_prompt": {
53                    "type": "string",
54                    "description": "Inline system prompt for the subagent. Use when you don't have a named agent file."
55                },
56                "name": {
57                    "type": "string",
58                    "description": "Short display name for an inline (system_prompt) subagent, e.g. \"gif-recorder\". Shown in the subagent panel and in status/collect output. Letters, digits, - and _ only, max 32. Ignored when agent is set; defaults to \"inline\"."
59                },
60                "task": {
61                    "type": "string",
62                    "description": "The task/prompt to send to the subagent."
63                },
64                "model": {
65                    "type": "string",
66                    "description": "Omit to inherit the session foreground qualified identity. Explicit values must be one of subagent_models' listed exact choices."
67                },
68                "role": {
69                    "type": "string",
70                    "enum": ["planner", "implementer", "tester", "reviewer", "researcher", "debugger"],
71                    "description": "Typed orchestration role."
72                },
73                "write_policy": {
74                    "oneOf": [
75                        {"type": "object", "properties": {"mode": {"const": "read_only"}}, "required": ["mode"]},
76                        {"type": "object", "properties": {"mode": {"const": "isolated_worktree"}}, "required": ["mode"]},
77                        {"type": "object", "properties": {"mode": {"const": "non_overlapping_paths"}, "scopes": {"type": "array", "items": {"type": "string"}}}, "required": ["mode", "scopes"]}
78                    ],
79                    "description": "Declared write isolation and path scopes."
80                },
81                "timeout": {
82                    "type": "integer",
83                    "description": "Wall-clock limit in seconds. Omit for the session default (config `subagent_timeout`); 0 = no limit. A timed-out worker keeps its full conversation: subagent_resume continues it where it stopped."
84                }
85            },
86            "required": ["task"]
87        })
88    }
89
90    async fn execute(&self, params: Value, ctx: ToolContext) -> Result<String> {
91        // ── Parse params ───────────────────────────────────────────────────────
92        let task = params["task"]
93            .as_str()
94            .ok_or_else(|| RuntimeError::Tool("Missing 'task' parameter".to_string()))?
95            .to_string();
96
97        // Treat blank / whitespace / control-char strings as absent.
98        // Some model providers serialize "unset" as "" rather than omitting the field,
99        // and we must not try to resolve "" (or " ", or "\u{0}") as an agent name —
100        // doing so produces a hard "Agent '' not found" error that the model then
101        // retries forever with sentinel values instead of falling back to system_prompt.
102        let is_blank = |s: &String| s.chars().all(|c| c.is_whitespace() || c.is_control());
103        let agent_name = params["agent"]
104            .as_str()
105            .map(|s| s.to_string())
106            .filter(|s| !is_blank(s));
107        let inline_prompt = params["system_prompt"]
108            .as_str()
109            .map(|s| s.to_string())
110            .filter(|s| !is_blank(s));
111        let requested_model = params["model"].as_str();
112        // Validate the registry before authorization, id allocation, or event emission;
113        // the same borrow is reused below when publishing the authorized handle.
114        let registry = ctx.capabilities.subagent_registry.as_ref().ok_or_else(|| {
115            RuntimeError::Tool("subagent_start requires a subagent_registry in ToolContext".into())
116        })?;
117        let system_prompt = match (&agent_name, &inline_prompt) {
118            (Some(name), _) => resolve_agent_prompt(name).map_err(RuntimeError::Tool)?,
119            (None, Some(p)) => p.clone(),
120            (None, None) => {
121                return Err(RuntimeError::Tool(
122                    "Must provide either 'agent' (name) or 'system_prompt' (inline). Got neither."
123                        .to_string(),
124                ));
125            }
126        };
127        let subagent_id = NEXT_SUBAGENT_ID.fetch_add(1, Ordering::Relaxed);
128        let handle_id = format!("sa_{}", subagent_id);
129        let orchestration = ctx
130            .capabilities
131            .orchestration
132            .as_ref()
133            .ok_or_else(|| RuntimeError::Tool("delegation policy unavailable".into()))?;
134        orchestration
135            .reserve_delegation(&handle_id, ctx.capabilities.delegation_parent.as_deref())
136            .map_err(|reason| RuntimeError::Tool(format!("delegation denied: {reason}")))?;
137        let decision = orchestration
138            .resolve_and_authorize(&handle_id, requested_model)
139            .map_err(|error| {
140                orchestration
141                    .release_delegation(&handle_id, ctx.capabilities.delegation_parent.as_deref());
142                RuntimeError::Tool(error.to_string())
143            })?;
144        let model = decision.model.as_str().to_owned();
145        let codex_parent_plan = ctx.capabilities.codex_parent_plan.clone();
146        let memory_backend = ctx.capabilities.memory_backend.clone();
147        let session_allow_all = ctx.capabilities.session_allow_all.clone();
148        let telemetry = ctx.capabilities.telemetry.clone();
149        let timeout_secs = params["timeout"]
150            .as_u64()
151            .unwrap_or(ctx.limits.subagent_timeout);
152
153        let label = super::subagent_label(agent_name.as_deref(), params["name"].as_str());
154        let task_preview: String = task.chars().take(80).collect();
155        let task_full = task.clone();
156
157        tracing::info!(
158            "subagent_start: dispatching '{}' (id={}) model={}",
159            label,
160            handle_id,
161            model
162        );
163
164        // ── Shared state ───────────────────────────────────────────────────────
165        let state = Arc::new(RwLock::new(SubagentState::new()));
166        state.write().unwrap().archive_meta = Some(crate::runtime::subagent::SubagentArchiveMeta {
167            agent_name: label.clone(),
168            model: model.clone(),
169            system_prompt: system_prompt.clone(),
170            timeout_secs,
171        });
172
173        state.write().unwrap().archive_dir = Some(super::archive::process_dir());
174        let initial_messages = vec![Arc::new(
175            serde_json::json!({"role": "user", "content": task.clone()}),
176        )];
177        state.write().unwrap().history = Some(initial_messages.clone());
178
179        // ── Channels ───────────────────────────────────────────────────────────
180        let (steer_tx, steer_rx) = mpsc::unbounded_channel::<String>();
181        let (shutdown_tx, shutdown_rx) = oneshot::channel::<()>();
182        let (result_tx, result_rx) = oneshot::channel::<SubagentResult>();
183
184        // ── Forward SubagentStart event to TUI ─────────────────────────────────
185        if let Some(ref tx) = ctx.channels.tx_events {
186            let _ = tx.send(crate::StreamEvent::Agent(AgentEvent::SubagentStart {
187                subagent_id,
188                agent_name: label.clone(),
189                task_preview: task_preview.clone(),
190            }));
191        }
192
193        // ── Clone state for the spawned thread ─────────────────────────────────
194        let state_t = Arc::clone(&state);
195        let task_full_a = task_full.clone();
196        let label_inner = label.clone();
197        let model_inner = model.clone();
198        let tx_events_inner = ctx.channels.tx_events.clone();
199        let start_time = std::time::Instant::now();
200        let parent_queue = ctx.capabilities.event_queue.clone();
201        let handle_id_inner = handle_id.clone();
202        let child_parent_id = handle_id.clone();
203
204        // ── Build and register handle BEFORE spawning ─────────────────────────
205        // This closes the publish-before-register race: finalize_subagent can
206        // push a completion event the instant the thread exits, but the registry
207        // must already contain the handle so the parent's collect succeeds.
208        let system_prompt_for_handle = system_prompt.clone();
209        let handle = SubagentHandle::new(
210            handle_id.clone(),
211            subagent_id,
212            label.clone(),
213            task_preview,
214            model.clone(),
215            system_prompt_for_handle,
216            timeout_secs,
217            Arc::clone(&state),
218            Some(steer_tx),
219            Some(shutdown_tx),
220            Some(result_rx),
221        )
222        .with_authorization(&decision);
223        {
224            let mut reg = registry.lock().unwrap();
225            reg.register_with_cancellation(handle, ctx.capabilities.launch_cancel.as_ref());
226        }
227
228        let orchestration = ctx.capabilities.orchestration.as_ref().unwrap();
229        let orchestration_for_worker = Arc::clone(orchestration);
230        let parent_for_worker = ctx.capabilities.delegation_parent.clone();
231        if let Err(error) = orchestration.mark_starting(&handle_id) {
232            orchestration.rollback(&handle_id);
233            orchestration
234                .release_delegation(&handle_id, ctx.capabilities.delegation_parent.as_deref());
235            return Err(RuntimeError::Tool(error));
236        }
237
238        // ── Spawn subagent thread (mirrors subagent.rs) ────────────────────────
239        let thread_handle = std::thread::spawn(move || {
240            // Pre-clone for finalizer — catch_unwind moves state_t and label_inner
241            let state_for_finalizer = Arc::clone(&state_t);
242            let label_for_finalizer = label_inner.clone();
243            let orchestration_for_runtime = Arc::clone(&orchestration_for_worker);
244
245            let mut pending_result = None;
246            let panic_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
247                let rt = match tokio::runtime::Builder::new_current_thread()
248                    .enable_all()
249                    .build()
250                {
251                    Ok(rt) => rt,
252                    Err(_) => {
253                        state_t.write().unwrap().status =
254                            SubagentStatus::Failed("runtime initialization failed".into());
255                        return;
256                    }
257                };
258
259                // Clones for the async block — the outer closure still needs the originals.
260                let state_a = Arc::clone(&state_t);
261                let label_a = label_inner.clone();
262                let model_a = model_inner.clone();
263                let tx_events_a = tx_events_inner.clone();
264                let task_for_timeout = task_full_a.clone();
265                let task_for_complete = task_full_a;
266
267                let outcome: std::result::Result<SubagentResult, String> =
268                    rt.block_on(async move {
269                        // Host-built worker (shared client/creds/token cache, cached
270                        // registry) or the legacy fresh runtime — see `spawn_runtime`.
271                        let mut runtime = match super::spawn_runtime().await {
272                            Ok(r) => r,
273                            Err(_) => return Err("subagent runtime initialization failed".into()),
274                        };
275
276                        // Apply subagent spawn policy: worker role, 5m cache TTL, worker
277                        // turn budget. Subagents are short-lived one-shots — paying the 1h
278                        // write premium (~2× input price) on them is unrecoverable waste
279                        // (~$0.23 per 10-spawn fan-out). (#110)
280                        super::apply_subagent_runtime_policy(
281                            &mut runtime,
282                            &crate::config::load_config(),
283                            memory_backend.as_ref(),
284                            session_allow_all.as_ref(),
285                            telemetry.as_ref(),
286                        );
287                        runtime.set_system_prompt(super::compose_system_prompt(
288                            system_prompt,
289                            runtime.memory_backend_is_axel(),
290                        ));
291                        runtime.set_model(model_a.clone());
292                        super::apply_codex_worker_reasoning(
293                            &mut runtime,
294                            codex_parent_plan.as_ref(),
295                        );
296                        runtime
297                            .install_worker_orchestration(Arc::clone(&orchestration_for_runtime));
298                        runtime.set_delegation_parent(Some(child_parent_id.clone()));
299
300                        let cancel = crate::CancellationToken::new();
301                        let cancel_inner = cancel.clone();
302                        tokio::spawn(async move {
303                            let _ = shutdown_rx.await;
304                            cancel_inner.cancel();
305                        });
306
307                        let cancel_on_timeout = cancel.clone();
308                        let stream = runtime.run_stream_with_messages(
309                                initial_messages,
310                                cancel,
311                                Some(steer_rx),
312                                None,
313                                false,
314                            ).await;
315
316                        super::drive::WorkerDrive {
317                            state: Arc::clone(&state_a),
318                            tx_events: tx_events_a.clone(),
319                            subagent_id,
320                            label: label_a.clone(),
321                            model: model_a.clone(),
322                            timeout_secs,
323                            cancel: cancel_on_timeout,
324                            task: task_for_timeout,
325                        }
326                        .run(stream)
327                        .await
328                    });
329
330                match outcome {
331                    Ok(sa_result) => {
332                        // Only overwrite Running → Completed (don't stomp TimedOut or a cancellation).
333                        {
334                            let mut s = state_t.write().unwrap();
335                            if matches!(s.status, SubagentStatus::Running) && !s.cancel_requested {
336                                s.status = SubagentStatus::Completed;
337                                s.conversation_state = vec![
338                                    serde_json::json!({"role": "user", "content": task_for_complete.clone()}),
339                                    serde_json::json!({"role": "assistant", "content": sa_result.text.clone()}),
340                                ];
341                            }
342                        }
343                        pending_result = Some(sa_result);
344                    }
345                    Err(e) => {
346                        state_t.write().unwrap().status = SubagentStatus::Failed(e);
347                    }
348                }
349            }));
350
351            if let Err(panic_info) = panic_result {
352                let msg = if let Some(s) = panic_info.downcast_ref::<&str>() {
353                    s.to_string()
354                } else if let Some(s) = panic_info.downcast_ref::<String>() {
355                    s.clone()
356                } else {
357                    "unknown panic".to_string()
358                };
359                tracing::error!("Subagent thread panicked: {}", msg);
360                state_t.write().unwrap_or_else(|p| p.into_inner()).status =
361                    SubagentStatus::Failed(format!("panic: {}", msg));
362            }
363
364            // ── Terminal finalizer — exactly once, outside catch_unwind ────────
365            // Covers all paths: Ok, Err, timeout, panic, early tokio-build failure.
366            super::finalize::finalize_subagent(
367                &state_for_finalizer,
368                parent_queue.as_ref(),
369                &handle_id_inner,
370                subagent_id,
371                &label_for_finalizer,
372                start_time,
373                None, // start.rs: not a resume
374            );
375            // A cancelled worker publishes no wake, so nothing would ever
376            // prompt a collect: retire it before any terminal publication.
377            super::finalize::retire_if_cancelled(
378                &state_for_finalizer,
379                &orchestration_for_worker,
380                &handle_id_inner,
381            );
382            // All terminal publications follow the recovery/finalization barrier.
383            if let Some(ref tx) = tx_events_inner {
384                let s = state_for_finalizer
385                    .read()
386                    .unwrap_or_else(|p| p.into_inner());
387                let preview = match s.status.failure_reason() {
388                    Some(reason) => format!("ERROR: {reason}"),
389                    None => s.partial_text.chars().take(120).collect(),
390                };
391                let _ = tx.send(crate::StreamEvent::Agent(AgentEvent::SubagentDone {
392                    subagent_id,
393                    agent_name: label_for_finalizer.clone(),
394                    result_preview: preview,
395                    duration_secs: start_time.elapsed().as_secs_f64(),
396                }));
397            }
398            if let Some(result) = pending_result {
399                let _ = result_tx.send(result);
400            }
401            orchestration_for_worker
402                .release_delegation(&handle_id_inner, parent_for_worker.as_deref());
403        });
404
405        // ── Attach the already-persisted handle to the started thread ──────────
406        {
407            let mut reg = registry.lock().unwrap();
408            if let Some(h) = reg.get_mut(&handle_id) {
409                h.set_thread_handle(thread_handle);
410            }
411        }
412        if let Err(error) = ctx
413            .capabilities
414            .orchestration
415            .as_ref()
416            .unwrap()
417            .mark_running(&handle_id)
418        {
419            let thread = {
420                let mut reg = registry.lock().unwrap();
421                if let Some(handle) = reg.get_mut(&handle_id) {
422                    handle.cancel();
423                }
424                reg.remove(&handle_id)
425            };
426            if let Some(handle) = thread {
427                let _ = handle.collect().await;
428            }
429            orchestration.rollback(&handle_id);
430            orchestration
431                .release_delegation(&handle_id, ctx.capabilities.delegation_parent.as_deref());
432            return Err(RuntimeError::Tool(error));
433        }
434        // The thread may have been cancelled and finalized before it was
435        // marked running; its own retire attempt was then too early.
436        super::finalize::retire_if_cancelled(&state, orchestration, &handle_id);
437
438        Ok(json!({
439            "handle_id":  handle_id,
440            "agent_name": label,
441            "status":     "running"
442        })
443        .to_string())
444    }
445}
446
447#[cfg(test)]
448mod tests {
449    use super::*;
450    use crate::tools::test_helpers::create_tool_context;
451    use crate::tools::{SubagentRegistry, Tool};
452    use serde_json::json;
453    use std::sync::{Arc, Mutex};
454
455    // V4: registry=None must return Err immediately, before any thread is spawned.
456    #[tokio::test]
457    async fn test_subagent_start_no_registry_returns_err() {
458        let tool = SubagentStartTool;
459        let ctx = create_tool_context(); // subagent_registry is None by default
460
461        let params = json!({
462            "system_prompt": "You are a test subagent.",
463            "task": "Say ok",
464        });
465
466        let result = tool.execute(params, ctx).await;
467        assert!(
468            result.is_err(),
469            "missing registry must return Err before spawn"
470        );
471        let msg = format!("{:?}", result.unwrap_err());
472        assert!(
473            msg.contains("subagent_registry"),
474            "error must mention subagent_registry: {msg}"
475        );
476    }
477
478    /// These tests launch a real worker thread. Run unpinned, it read the
479    /// developer's real `auth.json` (and could reach the provider), and wrote
480    /// `logs/subagents` and `subagent-history` under the real `~/.synaps-cli`,
481    /// after the test returned. Pin an empty base dir and clear the
482    /// environment's provider credentials/endpoints (`OfflineProviderEnv`), so
483    /// the worker fails at auth, offline; keep both until it has exited.
484    fn join_worker(registry: &Mutex<SubagentRegistry>, handle_id: &str) {
485        let thread = registry
486            .lock()
487            .unwrap()
488            .get_mut(handle_id)
489            .and_then(|h| h.thread_handle.take());
490        if let Some(thread) = thread {
491            let _ = thread.join();
492        }
493    }
494
495    #[tokio::test]
496    #[serial_test::serial(synaps_base_dir)]
497    async fn test_subagent_start_blank_agent_uses_system_prompt() {
498        let _base = crate::test_env::BaseDirGuard::new();
499        let _offline = crate::test_env::OfflineProviderEnv::new();
500        let tool = SubagentStartTool;
501        let mut ctx = create_tool_context();
502        let registry = Arc::new(Mutex::new(SubagentRegistry::new()));
503        ctx.capabilities.subagent_registry = Some(registry.clone());
504
505        let params = json!({
506            "agent": "",
507            "system_prompt": "You are a concise test subagent. Reply with only: ok",
508            "task": "Say ok",
509            "model": "anthropic/claude-sonnet-4-6",
510            "timeout": 1
511        });
512
513        let result = tool.execute(params, ctx).await;
514        assert!(
515            result.is_ok(),
516            "blank agent should not be resolved as ~/.synaps-cli/agents/.md: {result:?}"
517        );
518        let body: serde_json::Value = serde_json::from_str(&result.unwrap()).unwrap();
519        assert_eq!(body["agent_name"], "inline");
520        let handle_id = body["handle_id"].as_str().unwrap_or_default();
521        assert!(handle_id.starts_with("sa_"));
522        join_worker(&registry, handle_id);
523    }
524
525    #[tokio::test]
526    #[serial_test::serial(synaps_base_dir)]
527    async fn test_subagent_start_inline_name_labels_the_handle() {
528        let _base = crate::test_env::BaseDirGuard::new();
529        let _offline = crate::test_env::OfflineProviderEnv::new();
530        let tool = SubagentStartTool;
531        let mut ctx = create_tool_context();
532        let registry = Arc::new(Mutex::new(SubagentRegistry::new()));
533        ctx.capabilities.subagent_registry = Some(registry.clone());
534
535        let params = json!({
536            "system_prompt": "You are a concise test subagent. Reply with only: ok",
537            "name": "gif recorder",
538            "task": "Say ok",
539            "model": "anthropic/claude-sonnet-4-6",
540            "timeout": 1
541        });
542
543        let result = tool.execute(params, ctx).await.expect("dispatch");
544        let body: serde_json::Value = serde_json::from_str(&result).unwrap();
545        assert_eq!(body["agent_name"], "gif-recorder");
546        let handle_id = body["handle_id"].as_str().unwrap();
547        {
548            let reg = registry.lock().unwrap();
549            assert_eq!(
550                reg.get(handle_id).expect("registered").agent_name,
551                "gif-recorder"
552            );
553        }
554        join_worker(&registry, handle_id);
555    }
556}