Skip to main content

agent_commander/
result_close.rs

1//! Close a process that lingers after its final result (hive-mind#1280, #3015).
2//!
3//! Claude Code can keep running after it wrote its `result` event: an MCP
4//! server or a background task holds it open. Hive Mind waits a bounded time
5//! (`HIVE_MIND_RESULT_STREAM_CLOSE_MS`) and then stops the process itself. The
6//! stop is the caller's own signal, so the run is still judged by its result.
7
8use crate::background_tasks::track_background_tasks;
9use crate::completion::completion_state;
10use crate::executor::ProcessHandle;
11use crate::streaming::{JsonRecordEvent, JsonRecordScanner};
12use serde_json::Value;
13use std::io;
14use std::time::{Duration, Instant};
15
16/// Default interval between checks of a running process.
17pub const DEFAULT_RESULT_POLL: Duration = Duration::from_millis(100);
18
19/// Read stream events incrementally from a growing stdout buffer.
20#[derive(Debug, Clone, Default)]
21pub struct StdoutMessageReader {
22    scanner: JsonRecordScanner,
23    messages: Vec<Value>,
24    scanned: usize,
25}
26
27impl StdoutMessageReader {
28    pub fn new() -> Self {
29        Self::default()
30    }
31
32    /// Scan the complete lines added since the last call and return every
33    /// event parsed so far. A trailing partial line (or UTF-8 sequence) waits
34    /// for the next call.
35    pub fn read(&mut self, stdout: &str) -> &[Value] {
36        let end = stdout.rfind('\n').map_or(0, |index| index + 1);
37        if end > self.scanned {
38            for event in self.scanner.write(&stdout[self.scanned..end]) {
39                if let JsonRecordEvent::Json { value, .. } = event {
40                    match value {
41                        Value::Array(values) => self.messages.extend(values),
42                        value => self.messages.push(value),
43                    }
44                }
45            }
46            self.scanned = end;
47        }
48        &self.messages
49    }
50}
51
52/// Whether the main thread has ended its turn with a final result.
53pub fn has_final_result(tool: &str, messages: &[Value]) -> bool {
54    matches!(
55        completion_state(tool, messages),
56        Some("completed" | "failed")
57    )
58}
59
60/// How long a process may stay after its final result.
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub struct ResultCloseOptions {
63    /// Time the process may stay after its result once no background task
64    /// runs; `None` waits for it to exit
65    pub close_timeout: Option<Duration>,
66    /// Extra time granted while background tasks still run; `None` leaves
67    /// them to the tool's own ceiling
68    pub background_wait: Option<Duration>,
69    /// Poll interval
70    pub poll: Duration,
71}
72
73impl Default for ResultCloseOptions {
74    fn default() -> Self {
75        Self {
76            close_timeout: None,
77            background_wait: None,
78            poll: DEFAULT_RESULT_POLL,
79        }
80    }
81}
82
83/// Wait for a process to exit, stopping it when it outlives its result.
84///
85/// Returns the exit code and whether the process was stopped after its result.
86pub async fn wait_for_exit_after_result(
87    handle: &mut ProcessHandle,
88    tool: &str,
89    options: ResultCloseOptions,
90) -> io::Result<(i32, bool)> {
91    let Some(close_timeout) = options.close_timeout else {
92        return Ok((handle.wait_for_exit().await?, false));
93    };
94    let mut reader = StdoutMessageReader::new();
95    let mut result_at: Option<Instant> = None;
96    let mut idle_at: Option<Instant> = None;
97    while !handle.try_wait()? {
98        tokio::time::sleep(options.poll).await;
99        if handle.try_wait()? {
100            break;
101        }
102        let messages = reader.read(&handle.peek_stdout());
103        if !has_final_result(tool, messages) {
104            result_at = None;
105            idle_at = None;
106            continue;
107        }
108        let now = Instant::now();
109        let first_result = *result_at.get_or_insert(now);
110        let running = !track_background_tasks(messages).running.is_empty();
111        idle_at = if running {
112            None
113        } else {
114            Some(idle_at.unwrap_or(now))
115        };
116        let idle_expired = idle_at.is_some_and(|at| now - at >= close_timeout);
117        let background_expired = options
118            .background_wait
119            .is_some_and(|wait| now - first_result >= wait + close_timeout);
120        if idle_expired || background_expired {
121            handle.terminate().await?;
122            return Ok((handle.wait_for_exit().await?, true));
123        }
124    }
125    Ok((handle.wait_for_exit().await?, false))
126}