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 super::super::{Tool, ToolContext, NEXT_SUBAGENT_ID};
14use crate::runtime::subagent::{SubagentHandle, SubagentResult, SubagentState, SubagentStatus};
15use crate::{AgentEvent, LlmEvent, Result, RuntimeError, SessionEvent};
16
17pub struct SubagentResumeTool;
18
19fn expired_context_error(handle_id: &str) -> RuntimeError {
20 RuntimeError::Tool(format!(
21 "Subagent '{}' has expired resumable context; call subagent_collect with reconciled=true to reconcile its retained tombstone.",
22 handle_id
23 ))
24}
25
26#[async_trait::async_trait]
27impl Tool for SubagentResumeTool {
28 fn origin(&self) -> crate::tools::ToolOrigin {
29 crate::tools::ToolOrigin::Builtin
30 }
31
32 fn name(&self) -> &str {
33 "subagent_resume"
34 }
35
36 fn description(&self) -> &str {
37 "Resume a finished or timed-out reactive subagent with new instructions. \
38 The previous subagent's conversation state is prepended as context so the \
39 new run has full history. Returns a new handle_id — the original handle \
40 remains readable for comparison. Only works on subagents in \
41 finished/timed_out/failed state."
42 }
43
44 fn parameters(&self) -> Value {
45 json!({
46 "type": "object",
47 "properties": {
48 "handle_id": {
49 "type": "string",
50 "description": "Handle ID of the completed subagent to resume (e.g. \"sa_3\")."
51 },
52 "instructions": {
53 "type": "string",
54 "description": "New task or context to prepend to the resumed subagent. \
55 Injected before the prior conversation history."
56 }
57 },
58 "required": ["handle_id", "instructions"]
59 })
60 }
61
62 async fn execute(&self, params: Value, ctx: ToolContext) -> Result<String> {
63 let prior_handle_id = params["handle_id"]
64 .as_str()
65 .ok_or_else(|| RuntimeError::Tool("Missing 'handle_id' parameter".to_string()))?
66 .to_string();
67
68 let instructions = params["instructions"]
69 .as_str()
70 .ok_or_else(|| RuntimeError::Tool("Missing 'instructions' parameter".to_string()))?
71 .to_string();
72
73 let registry = ctx.capabilities.subagent_registry.as_ref().ok_or_else(|| {
74 RuntimeError::Tool("SubagentRegistry not available on this ToolContext".to_string())
75 })?;
76
77 let (agent_name, model, prior_context, prior_system_prompt, prior_timeout) = {
79 let reg = registry.lock().unwrap();
80 let handle = reg.get(&prior_handle_id).ok_or_else(|| {
81 RuntimeError::Tool(format!(
82 "No subagent found with handle_id '{}'",
83 prior_handle_id
84 ))
85 })?;
86
87 if handle.status() == SubagentStatus::Running {
88 return Err(RuntimeError::Tool(format!(
89 "Subagent '{}' is still running. Call subagent_collect first, \
90 or wait until it finishes.",
91 prior_handle_id
92 )));
93 }
94 if handle.is_tombstone() {
95 return Err(expired_context_error(&prior_handle_id));
96 }
97
98 let prior = {
99 let state = handle.conversation_state();
100 if state.is_empty() {
101 handle.partial_output()
102 } else {
103 serde_json::to_string(&state).unwrap_or_else(|_| handle.partial_output())
104 }
105 };
106
107 (
108 handle.agent_name.clone(),
109 handle.model.clone(),
110 prior,
111 handle.system_prompt.clone(),
112 handle.timeout_secs,
113 )
114 };
115
116 let resumed_task = format!(
121 "{instructions}\n\n\
122 ---\n\
123 [Prior conversation context from handle {prior_handle_id}]\n\
124 {prior_context}"
125 );
126
127 let system_prompt = prior_system_prompt;
129 let timeout_secs = prior_timeout;
130 let label = agent_name.clone();
131 let task_preview: String = resumed_task.chars().take(80).collect();
132 let task_full = resumed_task.clone();
133 let subagent_id = NEXT_SUBAGENT_ID.fetch_add(1, Ordering::Relaxed);
134 let handle_id = format!("sa_{}", subagent_id);
135 let decision = ctx
136 .capabilities
137 .orchestration
138 .as_ref()
139 .ok_or_else(|| RuntimeError::Tool("delegation policy unavailable".into()))?
140 .resolve_and_authorize(&handle_id, Some(&model))
141 .map_err(|error| RuntimeError::Tool(error.to_string()))?;
142 let model = decision.model.as_str().to_owned();
143 let codex_parent_plan = ctx.capabilities.codex_parent_plan.clone();
144 let memory_backend = ctx.capabilities.memory_backend.clone();
145
146 tracing::info!(
147 "subagent_resume: dispatching '{}' (id={}, resumed_from={}) model={}",
148 label,
149 handle_id,
150 prior_handle_id,
151 model
152 );
153
154 let state = Arc::new(RwLock::new(SubagentState::new()));
155
156 let (steer_tx, steer_rx) = mpsc::unbounded_channel::<String>();
157 let (shutdown_tx, shutdown_rx) = oneshot::channel::<()>();
158 let (result_tx, result_rx) = oneshot::channel::<SubagentResult>();
159
160 if let Some(ref tx) = ctx.channels.tx_events {
161 let _ = tx.send(crate::StreamEvent::Agent(AgentEvent::SubagentStart {
162 subagent_id,
163 agent_name: label.clone(),
164 task_preview: task_preview.clone(),
165 }));
166 }
167
168 let state_t = Arc::clone(&state);
169 let task_full_a = task_full.clone();
170 let label_inner = label.clone();
171 let model_inner = model.clone();
172 let tx_events_inner = ctx.channels.tx_events.clone();
173 let start_time = std::time::Instant::now();
174 let parent_queue = ctx.capabilities.event_queue.clone();
175 let handle_id_inner = handle_id.clone();
176 let prior_handle_for_finalizer = prior_handle_id.clone();
177
178 let system_prompt_for_handle = system_prompt.clone();
180 let handle = SubagentHandle::new(
181 handle_id.clone(),
182 subagent_id,
183 label.clone(),
184 task_preview,
185 model.clone(),
186 system_prompt_for_handle,
187 timeout_secs,
188 Arc::clone(&state),
189 Some(steer_tx),
190 Some(shutdown_tx),
191 Some(result_rx),
192 )
193 .with_authorization(&decision);
194 {
195 let mut reg = registry.lock().unwrap();
196 reg.register_with_cancellation(handle, ctx.capabilities.launch_cancel.as_ref());
197 }
198
199 let orchestration = ctx.capabilities.orchestration.as_ref().unwrap();
200 if let Err(error) = orchestration.mark_starting(&handle_id) {
201 orchestration.rollback(&handle_id);
202 return Err(RuntimeError::Tool(error));
203 }
204 let thread_handle = std::thread::spawn(move || {
206 let state_for_finalizer = Arc::clone(&state_t);
208 let label_for_finalizer = label_inner.clone();
209
210 let panic_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
211 let rt = match tokio::runtime::Builder::new_current_thread()
212 .enable_all()
213 .build()
214 {
215 Ok(rt) => rt,
216 Err(_) => {
217 state_t.write().unwrap().status =
218 SubagentStatus::Failed("runtime initialization failed".into());
219 return;
220 }
221 };
222
223 let state_a = Arc::clone(&state_t);
224 let label_a = label_inner.clone();
225 let model_a = model_inner.clone();
226 let tx_events_a = tx_events_inner.clone();
227 let task_for_timeout = task_full_a.clone();
228 let task_for_complete = task_full_a.clone();
229 let task_for_stream = task_full_a;
230
231 let outcome: std::result::Result<SubagentResult, String> = rt.block_on(async move {
232 use futures::StreamExt;
233
234 let mut runtime = match super::spawn_runtime().await {
237 Ok(r) => r,
238 Err(_) => return Err("subagent runtime initialization failed".into()),
239 };
240
241 super::apply_subagent_runtime_policy(&mut runtime, &crate::config::load_config(), memory_backend.as_ref());
246 runtime.set_system_prompt(super::compose_system_prompt(system_prompt, runtime.memory_backend_is_axel()));
247 runtime.set_model(model_a.clone());
248 super::apply_codex_worker_reasoning(&mut runtime, codex_parent_plan.as_ref());
249
250 let cancel = crate::CancellationToken::new();
251 let cancel_inner = cancel.clone();
252 tokio::spawn(async move {
253 let _ = shutdown_rx.await;
254 cancel_inner.cancel();
255 });
256
257 let mut stream = runtime.run_stream_with_messages(
258 vec![std::sync::Arc::new(serde_json::json!({"role": "user", "content": task_for_stream}))],
259 cancel,
260 Some(steer_rx),
261 None,
262 false,
263 ).await;
264
265 let mut tool_count = 0u32;
266 let mut response_baseline = (0usize, 0usize, 0u32);
267 let mut total_input_tokens = 0u64;
268 let mut total_output_tokens = 0u64;
269 let mut total_cache_read = 0u64;
270 let mut total_cache_creation = 0u64;
271 let mut total_cache_5m: Option<u64> = None;
273 let mut total_cache_1h: Option<u64> = None;
274
275 let timeout_fut = tokio::time::sleep(Duration::from_secs(timeout_secs));
276 tokio::pin!(timeout_fut);
277
278 loop {
279 tokio::select! {
280 event = stream.next() => {
281 let Some(event) = event else { break };
282 match event {
283 crate::StreamEvent::Llm(LlmEvent::Thinking(_)) => {
284 if let Some(ref tx) = tx_events_a {
285 let _ = tx.send(crate::StreamEvent::Agent(AgentEvent::SubagentUpdate {
286 subagent_id,
287 agent_name: label_a.clone(),
288 status: "💭 thinking...".to_string(),
289 }));
290 }
291 }
292 crate::StreamEvent::Llm(LlmEvent::ResponseStart) => {
293 let s = state_a.read().unwrap();
294 response_baseline = (s.partial_text.len(), s.tool_log.len(), tool_count);
295 }
296 crate::StreamEvent::Llm(LlmEvent::ResponseReset) => {
297 let mut s = state_a.write().unwrap();
298 s.partial_text.truncate(response_baseline.0);
299 s.tool_log.truncate(response_baseline.1);
300 tool_count = response_baseline.2;
301 }
302 crate::StreamEvent::Llm(LlmEvent::Text(text)) => {
303 state_a.write().unwrap().partial_text.push_str(&text);
304 }
305 crate::StreamEvent::Llm(LlmEvent::ToolUseStart { tool_name: name, .. }) => {
306 tool_count += 1;
307 if let Some(ref tx) = tx_events_a {
308 let _ = tx.send(crate::StreamEvent::Agent(AgentEvent::SubagentUpdate {
309 subagent_id,
310 agent_name: label_a.clone(),
311 status: format!("⚙ {} (tool #{})", name, tool_count),
312 }));
313 }
314 }
315 crate::StreamEvent::Llm(LlmEvent::ToolUse { tool_name, input, .. }) => {
316 let input_str = input.to_string();
317 let input_preview: String = input_str.chars().take(200).collect();
318 state_a.write().unwrap().tool_log
319 .push(format!("[tool_use]: {} — {}", tool_name, input_preview));
320 let detail = match tool_name.as_str() {
321 "bash" => {
322 let cmd = input["command"].as_str().unwrap_or("");
323 let preview: String = cmd.chars().take(60).collect();
324 format!("$ {}", preview)
325 }
326 "read" => format!("reading {}", input["path"].as_str().unwrap_or("?").rsplit('/').next().unwrap_or("?")),
327 "write" => format!("writing {}", input["path"].as_str().unwrap_or("?").rsplit('/').next().unwrap_or("?")),
328 "edit" => format!("editing {}", input["path"].as_str().unwrap_or("?").rsplit('/').next().unwrap_or("?")),
329 "grep" => format!("grep /{}/", input["pattern"].as_str().unwrap_or("?").chars().take(30).collect::<String>()),
330 "find" => format!("find {}", input["pattern"].as_str().unwrap_or("?")),
331 "ls" => format!("ls {}", input["path"].as_str().unwrap_or(".").rsplit('/').next().unwrap_or(".")),
332 other => {
333 if other.starts_with("ext__") {
334 other.splitn(3, "__").last().unwrap_or(other).to_string()
335 } else {
336 other.to_string()
337 }
338 }
339 };
340 if let Some(ref tx) = tx_events_a {
341 let _ = tx.send(crate::StreamEvent::Agent(AgentEvent::SubagentUpdate {
342 subagent_id,
343 agent_name: label_a.clone(),
344 status: detail,
345 }));
346 }
347 }
348 crate::StreamEvent::Llm(LlmEvent::ToolResult { result, .. }) => {
349 let preview: String = result.chars().take(300).collect();
350 state_a.write().unwrap().tool_log
351 .push(format!("[tool_result]: {}", preview));
352 }
353 crate::StreamEvent::Session(SessionEvent::Usage {
354 input_tokens, output_tokens,
355 cache_read_input_tokens, cache_creation_input_tokens,
356 cache_creation_5m, cache_creation_1h,
357 model: _,
358 }) => {
359 total_input_tokens += input_tokens;
360 total_output_tokens += output_tokens;
361 total_cache_read += cache_read_input_tokens;
362 total_cache_creation += cache_creation_input_tokens;
363 crate::core::rpc_dispatch::merge_split(&mut total_cache_5m, cache_creation_5m);
364 crate::core::rpc_dispatch::merge_split(&mut total_cache_1h, cache_creation_1h);
365 }
366 crate::StreamEvent::Session(SessionEvent::Error(e)) => return Err(format!("provider request failed [{}]", e.category_label())),
367 crate::StreamEvent::Session(SessionEvent::Done) => break,
368 _ => {}
369 }
370 }
371 _ = &mut timeout_fut => {
372 let (partial, log) = {
373 let mut s = state_a.write().unwrap();
374 s.status = SubagentStatus::TimedOut;
375 s.conversation_state = vec![
376 serde_json::json!({"role": "user", "content": task_for_timeout.clone()}),
377 serde_json::json!({"role": "assistant", "content": &s.partial_text}),
378 ];
379 (s.partial_text.clone(), s.tool_log.clone())
380 };
381 let mut text = format!("[TIMED OUT after {}s — partial results below]\n\n", timeout_secs);
382 if !log.is_empty() {
383 text.push_str(&log.join("\n"));
384 text.push('\n');
385 }
386 if !partial.is_empty() {
387 text.push_str("\n[partial response]:\n");
388 text.push_str(&partial);
389 }
390 state_a.write().unwrap_or_else(|p| p.into_inner()).partial_text = text.clone();
391 return Ok(SubagentResult {
392 text,
393 model: model_a.clone(),
394 input_tokens: total_input_tokens,
395 output_tokens: total_output_tokens,
396 cache_read: total_cache_read,
397 cache_creation: total_cache_creation,
398 cache_creation_5m: total_cache_5m,
399 cache_creation_1h: total_cache_1h,
400 tool_count,
401 timed_out: true,
402 });
403 }
404 }
405 }
406
407 Ok(SubagentResult {
408 text: state_a.write().unwrap().partial_text.clone(),
409 model: model_a.clone(),
410 input_tokens: total_input_tokens,
411 output_tokens: total_output_tokens,
412 cache_read: total_cache_read,
413 cache_creation: total_cache_creation,
414 cache_creation_5m: total_cache_5m,
415 cache_creation_1h: total_cache_1h,
416 tool_count,
417 timed_out: false,
418 })
419 });
420
421 match outcome {
422 Ok(sa_result) => {
423 {
424 let mut s = state_t.write().unwrap();
425 if matches!(s.status, SubagentStatus::Running) && !s.cancel_requested {
426 s.status = SubagentStatus::Completed;
427 s.conversation_state = vec![
428 serde_json::json!({"role": "user", "content": task_for_complete.clone()}),
429 serde_json::json!({"role": "assistant", "content": sa_result.text.clone()}),
430 ];
431 }
432 }
433 let elapsed = start_time.elapsed().as_secs_f64();
434 let preview: String = sa_result.text.chars().take(120).collect();
435 if let Some(ref tx) = tx_events_inner {
436 let _ = tx.send(crate::StreamEvent::Agent(AgentEvent::SubagentDone {
437 subagent_id,
438 agent_name: label_inner.clone(),
439 result_preview: preview,
440 duration_secs: elapsed,
441 }));
442 }
443 let _ = result_tx.send(sa_result);
444 }
445 Err(e) => {
446 state_t.write().unwrap().status = SubagentStatus::Failed(e.clone());
447 let elapsed = start_time.elapsed().as_secs_f64();
448 if let Some(ref tx) = tx_events_inner {
449 let _ = tx.send(crate::StreamEvent::Agent(AgentEvent::SubagentDone {
450 subagent_id,
451 agent_name: label_inner.clone(),
452 result_preview: format!("ERROR: {}", e),
453 duration_secs: elapsed,
454 }));
455 }
456 }
457 }
458 }));
459
460 if let Err(panic_info) = panic_result {
461 let msg = if let Some(s) = panic_info.downcast_ref::<&str>() {
462 s.to_string()
463 } else if let Some(s) = panic_info.downcast_ref::<String>() {
464 s.clone()
465 } else {
466 "unknown panic".to_string()
467 };
468 tracing::error!("Resumed subagent thread panicked: {}", msg);
469 state_t.write().unwrap_or_else(|p| p.into_inner()).status =
470 SubagentStatus::Failed(format!("panic: {}", msg));
471 }
472
473 super::finalize::finalize_subagent(
477 &state_for_finalizer,
478 parent_queue.as_ref(),
479 &handle_id_inner,
480 subagent_id,
481 &label_for_finalizer,
482 start_time,
483 Some(&prior_handle_for_finalizer),
484 );
485 });
486
487 {
489 let mut reg = registry.lock().unwrap();
490 if let Some(h) = reg.get_mut(&handle_id) {
491 h.set_thread_handle(thread_handle);
492 }
493 }
494 if let Err(error) = orchestration.mark_running(&handle_id) {
495 let mut handle = registry.lock().unwrap().remove(&handle_id);
496 if let Some(handle) = handle.as_mut() {
497 handle.cancel();
498 }
499 if let Some(handle) = handle {
500 let _ = handle.collect().await;
501 }
502 orchestration.rollback(&handle_id);
503 return Err(RuntimeError::Tool(error));
504 }
505
506 Ok(json!({
507 "handle_id": handle_id,
508 "resumed_from": prior_handle_id,
509 "agent_name": label,
510 "status": "running"
511 })
512 .to_string())
513 }
514}
515
516#[cfg(test)]
517mod tests {
518 use super::*;
519 use crate::runtime::subagent::{reap_finished_with_ttl, SubagentRegistry};
520 use crate::tools::test_helpers::create_tool_context;
521 use std::sync::Mutex;
522
523 #[tokio::test]
524 async fn tombstone_resume_reports_expired_context_without_side_effects() {
525 let state = Arc::new(RwLock::new(SubagentState::new()));
526 {
527 let mut state = state.write().unwrap();
528 state.status = SubagentStatus::Completed;
529 state.partial_text = "terminal output".into();
530 state.conversation_state = vec![json!({"role": "assistant", "content": "context"})];
531 state.finished_at = Some(std::time::Instant::now());
532 }
533 let (steer_tx, _steer_rx) = mpsc::unbounded_channel();
534 let (shutdown_tx, _shutdown_rx) = oneshot::channel();
535 let (_result_tx, result_rx) = oneshot::channel();
536 let registry = Arc::new(Mutex::new(SubagentRegistry::new()));
537 registry.lock().unwrap().register(SubagentHandle::new(
538 "sa_expired".into(),
539 1,
540 "test".into(),
541 "task".into(),
542 "anthropic/claude-sonnet-4-6".into(),
543 "system".into(),
544 30,
545 state,
546 Some(steer_tx),
547 Some(shutdown_tx),
548 Some(result_rx),
549 ));
550 let foreground =
551 agent_core::prompt::QualifiedModelId::parse("anthropic/claude-sonnet-4-6").unwrap();
552 let orchestration = Arc::new(
553 crate::orchestration::OrchestrationRuntime::baseline(foreground, 8, 64).unwrap(),
554 );
555 orchestration
556 .authorize("sa_expired", "anthropic/claude-sonnet-4-6")
557 .unwrap();
558 let gate_before = orchestration.completion_gate();
559 reap_finished_with_ttl(®istry, Some(orchestration.as_ref()), Duration::ZERO);
560 assert!(registry
561 .lock()
562 .unwrap()
563 .get("sa_expired")
564 .unwrap()
565 .is_tombstone());
566 let count_before = registry.lock().unwrap().list_active().len();
567
568 let mut ctx = create_tool_context();
569 ctx.capabilities.subagent_registry = Some(registry.clone());
570 ctx.capabilities.orchestration = Some(orchestration.clone());
571 let error = SubagentResumeTool
572 .execute(
573 json!({"handle_id": "sa_expired", "instructions": "continue"}),
574 ctx,
575 )
576 .await
577 .unwrap_err()
578 .to_string();
579 assert!(error.contains("expired resumable context"));
580 assert!(!error.contains("No subagent found"));
581 assert_eq!(registry.lock().unwrap().list_active().len(), count_before);
582 assert_eq!(orchestration.completion_gate(), gate_before);
583 }
584}