Skip to main content

synaps_cli/tools/subagent/
resume.rs

1//! SubagentResumeTool — restart a finished or timed-out subagent with new instructions.
2//!
3//! Takes the completed conversation state stored in the prior `SubagentHandle`,
4//! prepends new instructions, and dispatches a fresh subagent via the same flow as
5//! `subagent_start`. The caller gets a new `handle_id` for the continuation run.
6
7use 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, NEXT_SUBAGENT_ID};
15use crate::runtime::subagent::{SubagentHandle, SubagentResult, SubagentStatus, SubagentState};
16
17pub struct SubagentResumeTool;
18
19#[async_trait::async_trait]
20impl Tool for SubagentResumeTool {
21    fn name(&self) -> &str { "subagent_resume" }
22
23    fn description(&self) -> &str {
24        "Resume a finished or timed-out reactive subagent with new instructions. \
25         The previous subagent's conversation state is prepended as context so the \
26         new run has full history. Returns a new handle_id — the original handle \
27         remains readable for comparison. Only works on subagents in \
28         finished/timed_out/failed state."
29    }
30
31    fn parameters(&self) -> Value {
32        json!({
33            "type": "object",
34            "properties": {
35                "handle_id": {
36                    "type": "string",
37                    "description": "Handle ID of the completed subagent to resume (e.g. \"sa_3\")."
38                },
39                "instructions": {
40                    "type": "string",
41                    "description": "New task or context to prepend to the resumed subagent. \
42                                    Injected before the prior conversation history."
43                }
44            },
45            "required": ["handle_id", "instructions"]
46        })
47    }
48
49    async fn execute(&self, params: Value, ctx: ToolContext) -> Result<String> {
50        let prior_handle_id = params["handle_id"].as_str()
51            .ok_or_else(|| RuntimeError::Tool("Missing 'handle_id' parameter".to_string()))?
52            .to_string();
53
54        let instructions = params["instructions"].as_str()
55            .ok_or_else(|| RuntimeError::Tool("Missing 'instructions' parameter".to_string()))?
56            .to_string();
57
58        let registry = ctx.capabilities.subagent_registry.as_ref()
59            .ok_or_else(|| RuntimeError::Tool(
60                "SubagentRegistry not available on this ToolContext".to_string()
61            ))?;
62
63        // Extract prior state under the lock, release immediately.
64        let (agent_name, model, prior_context, prior_system_prompt, prior_timeout) = {
65            let reg = registry.lock().unwrap();
66            let handle = reg.get(&prior_handle_id)
67                .ok_or_else(|| RuntimeError::Tool(
68                    format!("No subagent found with handle_id '{}'", prior_handle_id)
69                ))?;
70
71            if handle.status() == SubagentStatus::Running {
72                return Err(RuntimeError::Tool(format!(
73                    "Subagent '{}' is still running. Call subagent_collect first, \
74                     or wait until it finishes.",
75                    prior_handle_id
76                )));
77            }
78
79            let prior = {
80                let state = handle.conversation_state();
81                if state.is_empty() {
82                    handle.partial_output()
83                } else {
84                    serde_json::to_string(&state).unwrap_or_else(|_| handle.partial_output())
85                }
86            };
87
88            (handle.agent_name.clone(), handle.model.clone(), prior, handle.system_prompt.clone(), handle.timeout_secs)
89        };
90
91        // ── Build resumed task: new instructions → separator → prior context.
92        let resumed_task = format!(
93            "{instructions}\n\n\
94             ---\n\
95             [Prior conversation context from handle {prior_handle_id}]\n\
96             {prior_context}"
97        );
98
99        // Restore the original system prompt and timeout from the prior handle
100        let system_prompt = prior_system_prompt;
101        let timeout_secs = prior_timeout;
102        let label = agent_name.clone();
103        let task_preview: String = resumed_task.chars().take(80).collect();
104        let task_full = resumed_task.clone();
105        let subagent_id = NEXT_SUBAGENT_ID.fetch_add(1, Ordering::Relaxed);
106        let handle_id = format!("sa_{}", subagent_id);
107
108        tracing::info!(
109            "subagent_resume: dispatching '{}' (id={}, resumed_from={}) model={}",
110            label, handle_id, prior_handle_id, model
111        );
112
113        let state = Arc::new(RwLock::new(SubagentState::new()));
114
115        let (steer_tx, steer_rx) = mpsc::unbounded_channel::<String>();
116        let (shutdown_tx, shutdown_rx) = oneshot::channel::<()>();
117        let (result_tx, result_rx) = oneshot::channel::<SubagentResult>();
118
119        if let Some(ref tx) = ctx.channels.tx_events {
120            let _ = tx.send(crate::StreamEvent::Agent(AgentEvent::SubagentStart {
121                subagent_id,
122                agent_name: label.clone(),
123                task_preview: task_preview.clone(),
124            }));
125        }
126
127        let state_t         = Arc::clone(&state);
128        let task_full_a     = task_full.clone();
129        let label_inner     = label.clone();
130        let model_inner     = model.clone();
131        let tx_events_inner = ctx.channels.tx_events.clone();
132        let start_time      = std::time::Instant::now();
133
134        let system_prompt_for_handle = system_prompt.clone();
135        let thread_handle = std::thread::spawn(move || {
136            let panic_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
137                let rt = match tokio::runtime::Builder::new_current_thread()
138                    .enable_all()
139                    .build()
140                {
141                    Ok(rt) => rt,
142                    Err(e) => {
143                        state_t.write().unwrap().status =
144                            SubagentStatus::Failed(format!("tokio runtime: {}", e));
145                        return;
146                    }
147                };
148
149                let state_a           = Arc::clone(&state_t);
150                let label_a           = label_inner.clone();
151                let model_a           = model_inner.clone();
152                let tx_events_a       = tx_events_inner.clone();
153                let task_for_timeout  = task_full_a.clone();
154                let task_for_complete = task_full_a.clone();
155                let task_for_stream   = task_full_a;
156
157                let outcome: std::result::Result<SubagentResult, String> = rt.block_on(async move {
158                    use futures::StreamExt;
159
160                    let mut runtime = match crate::Runtime::new().await {
161                        Ok(r) => r,
162                        Err(e) => return Err(format!("Failed to create subagent runtime: {}", e)),
163                    };
164
165                    runtime.set_system_prompt(system_prompt);
166                    runtime.set_model(model_a.clone());
167                    runtime.set_tools(crate::ToolRegistry::without_subagent());
168
169                    let cancel = crate::CancellationToken::new();
170                    let cancel_inner = cancel.clone();
171                    tokio::spawn(async move {
172                        let _ = shutdown_rx.await;
173                        cancel_inner.cancel();
174                    });
175
176                    let mut stream = runtime.run_stream_with_messages(
177                        vec![serde_json::json!({"role": "user", "content": task_for_stream})],
178                        cancel,
179                        Some(steer_rx),
180                        None,
181                    ).await;
182
183                    let mut tool_count = 0u32;
184                    let mut total_input_tokens = 0u64;
185                    let mut total_output_tokens = 0u64;
186                    let mut total_cache_read = 0u64;
187                    let mut total_cache_creation = 0u64;
188
189                    let timeout_fut = tokio::time::sleep(Duration::from_secs(timeout_secs));
190                    tokio::pin!(timeout_fut);
191
192                    loop {
193                        tokio::select! {
194                            event = stream.next() => {
195                                let Some(event) = event else { break };
196                                match event {
197                                    crate::StreamEvent::Llm(LlmEvent::Thinking(_)) => {
198                                        if let Some(ref tx) = tx_events_a {
199                                            let _ = tx.send(crate::StreamEvent::Agent(AgentEvent::SubagentUpdate {
200                                                subagent_id,
201                                                agent_name: label_a.clone(),
202                                                status: "💭 thinking...".to_string(),
203                                            }));
204                                        }
205                                    }
206                                    crate::StreamEvent::Llm(LlmEvent::Text(text)) => {
207                                        state_a.write().unwrap().partial_text.push_str(&text);
208                                    }
209                                    crate::StreamEvent::Llm(LlmEvent::ToolUseStart { tool_name: name, .. }) => {
210                                        tool_count += 1;
211                                        if let Some(ref tx) = tx_events_a {
212                                            let _ = tx.send(crate::StreamEvent::Agent(AgentEvent::SubagentUpdate {
213                                                subagent_id,
214                                                agent_name: label_a.clone(),
215                                                status: format!("⚙ {} (tool #{})", name, tool_count),
216                                            }));
217                                        }
218                                    }
219                                    crate::StreamEvent::Llm(LlmEvent::ToolUse { tool_name, input, .. }) => {
220                                        let input_str = input.to_string();
221                                        let input_preview: String = input_str.chars().take(200).collect();
222                                        state_a.write().unwrap().tool_log
223                                            .push(format!("[tool_use]: {} — {}", tool_name, input_preview));
224                                        let detail = match tool_name.as_str() {
225                                            "bash" => {
226                                                let cmd = input["command"].as_str().unwrap_or("");
227                                                let preview: String = cmd.chars().take(60).collect();
228                                                format!("$ {}", preview)
229                                            }
230                                            "read"  => format!("reading {}", input["path"].as_str().unwrap_or("?").rsplit('/').next().unwrap_or("?")),
231                                            "write" => format!("writing {}", input["path"].as_str().unwrap_or("?").rsplit('/').next().unwrap_or("?")),
232                                            "edit"  => format!("editing {}", input["path"].as_str().unwrap_or("?").rsplit('/').next().unwrap_or("?")),
233                                            "grep"  => format!("grep /{}/", input["pattern"].as_str().unwrap_or("?").chars().take(30).collect::<String>()),
234                                            "find"  => format!("find {}", input["pattern"].as_str().unwrap_or("?")),
235                                            "ls"    => format!("ls {}", input["path"].as_str().unwrap_or(".").rsplit('/').next().unwrap_or(".")),
236                                            other   => {
237                                                if other.starts_with("ext__") {
238                                                    other.splitn(3, "__").last().unwrap_or(other).to_string()
239                                                } else {
240                                                    other.to_string()
241                                                }
242                                            }
243                                        };
244                                        if let Some(ref tx) = tx_events_a {
245                                            let _ = tx.send(crate::StreamEvent::Agent(AgentEvent::SubagentUpdate {
246                                                subagent_id,
247                                                agent_name: label_a.clone(),
248                                                status: detail,
249                                            }));
250                                        }
251                                    }
252                                    crate::StreamEvent::Llm(LlmEvent::ToolResult { result, .. }) => {
253                                        let preview: String = result.chars().take(300).collect();
254                                        state_a.write().unwrap().tool_log
255                                            .push(format!("[tool_result]: {}", preview));
256                                    }
257                                    crate::StreamEvent::Session(SessionEvent::Usage {
258                                        input_tokens, output_tokens,
259                                        cache_read_input_tokens, cache_creation_input_tokens,
260                                        model: _,
261                                    }) => {
262                                        total_input_tokens    += input_tokens;
263                                        total_output_tokens   += output_tokens;
264                                        total_cache_read      += cache_read_input_tokens;
265                                        total_cache_creation  += cache_creation_input_tokens;
266                                    }
267                                    crate::StreamEvent::Session(SessionEvent::Error(e)) => return Err(e),
268                                    crate::StreamEvent::Session(SessionEvent::Done) => break,
269                                    _ => {}
270                                }
271                            }
272                            _ = &mut timeout_fut => {
273                                let (partial, log) = {
274                                    let mut s = state_a.write().unwrap();
275                                    s.status = SubagentStatus::TimedOut;
276                                    s.conversation_state = vec![
277                                        serde_json::json!({"role": "user", "content": task_for_timeout.clone()}),
278                                        serde_json::json!({"role": "assistant", "content": &s.partial_text}),
279                                    ];
280                                    (s.partial_text.clone(), s.tool_log.clone())
281                                };
282                                let mut text = format!("[TIMED OUT after {}s — partial results below]\n\n", timeout_secs);
283                                if !log.is_empty() {
284                                    text.push_str(&log.join("\n"));
285                                    text.push('\n');
286                                }
287                                if !partial.is_empty() {
288                                    text.push_str("\n[partial response]:\n");
289                                    text.push_str(&partial);
290                                }
291                                return Ok(SubagentResult {
292                                    text,
293                                    model: model_a.clone(),
294                                    input_tokens: total_input_tokens,
295                                    output_tokens: total_output_tokens,
296                                    cache_read: total_cache_read,
297                                    cache_creation: total_cache_creation,
298                                    tool_count,
299                                });
300                            }
301                        }
302                    }
303
304                    Ok(SubagentResult {
305                        text: state_a.write().unwrap().partial_text.clone(),
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                        tool_count,
312                    })
313                });
314
315                match outcome {
316                    Ok(sa_result) => {
317                        {
318                            let mut s = state_t.write().unwrap();
319                            if matches!(s.status, SubagentStatus::Running) {
320                                s.status = SubagentStatus::Completed;
321                                s.conversation_state = vec![
322                                    serde_json::json!({"role": "user", "content": task_for_complete.clone()}),
323                                    serde_json::json!({"role": "assistant", "content": sa_result.text.clone()}),
324                                ];
325                            }
326                        }
327                        let elapsed = start_time.elapsed().as_secs_f64();
328                        let preview: String = sa_result.text.chars().take(120).collect();
329                        if let Some(ref tx) = tx_events_inner {
330                            let _ = tx.send(crate::StreamEvent::Agent(AgentEvent::SubagentDone {
331                                subagent_id,
332                                agent_name: label_inner.clone(),
333                                result_preview: preview,
334                                duration_secs: elapsed,
335                            }));
336                        }
337                        let _ = result_tx.send(sa_result);
338                    }
339                    Err(e) => {
340                        state_t.write().unwrap().status = SubagentStatus::Failed(e.clone());
341                        let elapsed = start_time.elapsed().as_secs_f64();
342                        if let Some(ref tx) = tx_events_inner {
343                            let _ = tx.send(crate::StreamEvent::Agent(AgentEvent::SubagentDone {
344                                subagent_id,
345                                agent_name: label_inner.clone(),
346                                result_preview: format!("ERROR: {}", e),
347                                duration_secs: elapsed,
348                            }));
349                        }
350                    }
351                }
352            }));
353
354            if let Err(panic_info) = panic_result {
355                let msg = if let Some(s) = panic_info.downcast_ref::<&str>() {
356                    s.to_string()
357                } else if let Some(s) = panic_info.downcast_ref::<String>() {
358                    s.clone()
359                } else {
360                    "unknown panic".to_string()
361                };
362                tracing::error!("Resumed subagent thread panicked: {}", msg);
363                state_t.write().unwrap().status = SubagentStatus::Failed(format!("panic: {}", msg));
364            }
365        });
366
367        let handle = SubagentHandle::new(
368            handle_id.clone(),
369            label.clone(),
370            task_preview,
371            model,
372            system_prompt_for_handle,
373            timeout_secs,
374            state,
375            Some(steer_tx),
376            Some(shutdown_tx),
377            Some(result_rx),
378        );
379
380        {
381            let mut reg = registry.lock().unwrap();
382            reg.register(handle);
383            if let Some(h) = reg.get_mut(&handle_id) {
384                h.set_thread_handle(thread_handle);
385            }
386        }
387
388        Ok(json!({
389            "handle_id":    handle_id,
390            "resumed_from": prior_handle_id,
391            "agent_name":   label,
392            "status":       "running"
393        }).to_string())
394    }
395}