Skip to main content

agent_commander/
background_tasks.rs

1//! Claude Code background tasks and print-mode turns (hive-mind#2301, #3015).
2//!
3//! After the main thread goes idle, `claude -p` waits for background tasks
4//! (Agent, or Bash with `run_in_background`) up to
5//! `CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS`, then writes
6//! "Background tasks still running after 600s; terminating" to stderr and
7//! stops every task. The `result` event still says `success`, but the work is
8//! unfinished, so the run is incomplete and should be resumed.
9
10use regex::Regex;
11use serde::{Deserialize, Serialize};
12use serde_json::Value;
13use std::sync::LazyLock;
14
15/// Claude's announcement that it stopped background tasks at its ceiling.
16pub static PRINT_BG_CEILING_PATTERN: LazyLock<Regex> = LazyLock::new(|| {
17    Regex::new(r"Background tasks still running after (\d+)s; terminating").expect("valid pattern")
18});
19
20const TERMINAL_TASK_STATUSES: &[&str] = &[
21    "completed",
22    "failed",
23    "killed",
24    "stopped",
25    "cancelled",
26    "error",
27];
28
29/// A background task that has not reported an end.
30#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
31pub struct BackgroundTask {
32    pub id: String,
33    #[serde(rename = "type")]
34    pub task_type: Option<String>,
35    pub description: Option<String>,
36}
37
38/// A background task stopped while the main thread was idle.
39#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
40#[serde(rename_all = "camelCase")]
41pub struct StoppedBackgroundTask {
42    pub id: String,
43    pub summary: Option<String>,
44    pub output_file: Option<String>,
45}
46
47/// Background tasks and print-mode turn state over a message list.
48#[derive(Debug, Clone, Default, PartialEq, Eq)]
49pub struct BackgroundTaskState {
50    /// Tasks that never reported an end
51    pub running: Vec<BackgroundTask>,
52    /// Tasks stopped while the main thread was idle; a stop the model asked
53    /// for itself is followed by a main-thread reply, which clears the list
54    pub stopped_tasks: Vec<StoppedBackgroundTask>,
55    /// Last main-thread `result` event
56    pub result_event: Option<Value>,
57    pub result_count: usize,
58    /// Whether the main thread is inside a turn (no result since its last reply)
59    pub turn_open: bool,
60}
61
62/// Whether a print-mode turn ended with background work unfinished.
63#[derive(Debug, Clone, Default, PartialEq, Eq)]
64pub struct BackgroundTaskAssessment {
65    pub running_background_tasks: Vec<BackgroundTask>,
66    pub background_tasks_stopped: u64,
67    pub stopped_background_tasks: Vec<StoppedBackgroundTask>,
68    pub print_wait_ceiling_seconds: Option<u64>,
69    pub incomplete: bool,
70    pub cause: Option<String>,
71}
72
73fn is_main_thread(event: &Value) -> bool {
74    event
75        .get("parent_tool_use_id")
76        .and_then(Value::as_str)
77        .is_none_or(str::is_empty)
78}
79
80fn text(value: &Value, key: &str) -> Option<String> {
81    value
82        .get(key)
83        .and_then(Value::as_str)
84        .filter(|text| !text.is_empty())
85        .map(String::from)
86}
87
88#[derive(Default)]
89struct Tracker {
90    tasks: Vec<BackgroundTask>,
91    descriptions: Vec<(String, String)>,
92    stopped: Vec<StoppedBackgroundTask>,
93}
94
95impl Tracker {
96    fn description(&self, id: &str) -> Option<String> {
97        self.descriptions
98            .iter()
99            .find(|(task, _)| task == id)
100            .map(|(_, description)| description.clone())
101    }
102
103    fn add(&mut self, id: &str, task_type: Option<String>, description: Option<String>) {
104        let known = self.description(id);
105        if let Some(task) = self.tasks.iter_mut().find(|task| task.id == id) {
106            task.task_type = task_type.or_else(|| task.task_type.take());
107            task.description = description.or_else(|| task.description.take()).or(known);
108        } else {
109            self.tasks.push(BackgroundTask {
110                id: id.to_string(),
111                task_type,
112                description: description.or(known),
113            });
114        }
115    }
116
117    fn remove(&mut self, id: &str) {
118        self.tasks.retain(|task| task.id != id);
119    }
120
121    fn apply(&mut self, event: &Value) {
122        let id = text(event, "task_id");
123        match event.get("subtype").and_then(Value::as_str) {
124            Some("task_started") => {
125                if let Some(id) = id {
126                    if let Some(description) = text(event, "description") {
127                        self.descriptions.push((id.clone(), description));
128                    }
129                    if event["is_backgrounded"] == true {
130                        self.add(&id, text(event, "task_type"), text(event, "description"));
131                    }
132                }
133            }
134            Some("background_tasks_changed") => {
135                if let Some(tasks) = event.get("tasks").and_then(Value::as_array) {
136                    self.tasks.clear();
137                    for task in tasks {
138                        if let Some(task_id) = text(task, "task_id") {
139                            self.add(&task_id, text(task, "task_type"), text(task, "description"));
140                        }
141                    }
142                }
143            }
144            Some("task_updated") => {
145                if let Some(id) = id {
146                    let patch = &event["patch"];
147                    let status = patch.get("status").and_then(Value::as_str);
148                    if status.is_some_and(|status| TERMINAL_TASK_STATUSES.contains(&status)) {
149                        self.remove(&id);
150                    } else if patch["is_backgrounded"] == true {
151                        self.add(&id, None, None);
152                    }
153                }
154            }
155            Some("task_notification") => {
156                if let Some(id) = &id {
157                    self.remove(id);
158                }
159                if event["status"] == "stopped" {
160                    let stopped_id = id
161                        .or_else(|| text(event, "tool_use_id"))
162                        .unwrap_or_else(|| format!("stopped-{}", self.stopped.len() + 1));
163                    let entry = StoppedBackgroundTask {
164                        id: stopped_id.clone(),
165                        summary: text(event, "summary"),
166                        output_file: text(event, "output_file"),
167                    };
168                    if let Some(existing) =
169                        self.stopped.iter_mut().find(|task| task.id == stopped_id)
170                    {
171                        *existing = entry;
172                    } else {
173                        self.stopped.push(entry);
174                    }
175                }
176            }
177            _ => {}
178        }
179    }
180}
181
182/// Follow background tasks and the print-mode turn over a message list.
183///
184/// `background_tasks_changed` carries the authoritative list; `task_started`,
185/// `task_updated` and `task_notification` keep it right for CLI versions that
186/// do not send it.
187pub fn track_background_tasks(messages: &[Value]) -> BackgroundTaskState {
188    let mut tracker = Tracker::default();
189    let mut result_event = None;
190    let mut result_count = 0;
191    let mut turn_open = true;
192    for event in messages {
193        match event.get("type").and_then(Value::as_str) {
194            Some("assistant") if is_main_thread(event) => {
195                turn_open = true;
196                tracker.stopped.clear();
197            }
198            Some("result") if is_main_thread(event) => {
199                result_event = Some(event.clone());
200                result_count += 1;
201                turn_open = false;
202            }
203            Some("system") => tracker.apply(event),
204            _ => {}
205        }
206    }
207    BackgroundTaskState {
208        running: tracker.tasks,
209        stopped_tasks: tracker.stopped,
210        result_event,
211        result_count,
212        turn_open,
213    }
214}
215
216/// Read the print-mode wait ceiling (seconds) from Claude's stderr announcement.
217pub fn print_wait_ceiling_seconds(text: &str) -> Option<u64> {
218    PRINT_BG_CEILING_PATTERN
219        .captures(text)
220        .and_then(|captures| captures[1].parse().ok())
221}
222
223/// Decide whether a print-mode turn ended with background work unfinished.
224///
225/// `terminated_after_result` says the caller stopped the process after its
226/// result, while tasks may still have been running.
227pub fn assess_background_tasks(
228    messages: &[Value],
229    output: &str,
230    terminated_after_result: bool,
231) -> BackgroundTaskAssessment {
232    let state = track_background_tasks(messages);
233    let ceiling = print_wait_ceiling_seconds(output);
234    let system_killed = state
235        .result_event
236        .as_ref()
237        .and_then(|result| result.pointer("/subagent_stats/killed/system"))
238        .and_then(Value::as_u64)
239        .unwrap_or(0);
240    let cancelled_by_caller = if terminated_after_result {
241        state.running.len() as u64
242    } else {
243        0
244    };
245    let background_tasks_stopped = system_killed
246        .max(state.stopped_tasks.len() as u64)
247        .max(cancelled_by_caller)
248        .max(u64::from(ceiling.is_some()));
249    let incomplete = !state.turn_open
250        && state
251            .result_event
252            .as_ref()
253            .is_some_and(|result| result["subtype"] == "success" && result["is_error"] != true)
254        && background_tasks_stopped > 0;
255    let cause = incomplete.then(|| match ceiling {
256        Some(seconds) => format!(
257            "Claude Code stopped background tasks after its {seconds}s print-mode wait ceiling (CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS)"
258        ),
259        None if cancelled_by_caller > 0 => {
260            "The process was stopped after its result while background tasks were still running"
261                .to_string()
262        }
263        None => "Claude Code stopped background tasks when print mode exited".to_string(),
264    });
265    BackgroundTaskAssessment {
266        running_background_tasks: state.running,
267        background_tasks_stopped,
268        stopped_background_tasks: state.stopped_tasks,
269        print_wait_ceiling_seconds: ceiling,
270        incomplete,
271        cause,
272    }
273}
274
275/// Whether a model id names a real model; `<synthetic>` does not.
276pub fn is_real_model_id(model_id: &str) -> bool {
277    let id = model_id.trim();
278    !id.is_empty() && !(id.starts_with('<') && id.ends_with('>'))
279}
280
281/// Model ids a tool reports about itself (hive-mind#2840).
282///
283/// Returns main-thread models first, in order of first observation, then
284/// models only seen from subagents, and the main-thread model observed last.
285/// The ids come from `system/init` and assistant `message.model`, so they
286/// survive a crash or a kill before the `result` event.
287pub fn extract_observed_models(messages: &[Value]) -> (Vec<String>, Option<String>) {
288    let mut main = Vec::new();
289    let mut subagent = Vec::new();
290    let mut observed_model = None;
291    for event in messages {
292        let id = match (
293            event.get("type").and_then(Value::as_str),
294            event.get("subtype").and_then(Value::as_str),
295        ) {
296            (Some("system"), Some("init")) => event.get("model"),
297            (Some("assistant"), _) => event.pointer("/message/model"),
298            _ => None,
299        }
300        .and_then(Value::as_str)
301        .filter(|id| is_real_model_id(id))
302        .map(|id| id.trim().to_string());
303        let Some(id) = id else {
304            continue;
305        };
306        if is_main_thread(event) {
307            observed_model = Some(id.clone());
308            main.push(id);
309        } else {
310            subagent.push(id);
311        }
312    }
313    let mut observed = Vec::new();
314    for id in main.into_iter().chain(subagent) {
315        if !observed.contains(&id) {
316            observed.push(id);
317        }
318    }
319    (observed, observed_model)
320}