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//!
8//! The same watch stops a run whose API request was refused with 401/403
9//! (`fail_fast_on_auth_error`, issue #69): Claude would retry the refused
10//! credential until the caller's own timeout.
11
12use crate::api_status::auth_refusal_status;
13use crate::background_tasks::track_background_tasks;
14use crate::completion::completion_state;
15use crate::executor::ProcessHandle;
16use crate::streaming::{JsonRecordEvent, JsonRecordScanner};
17use serde_json::Value;
18use std::io;
19use std::time::{Duration, Instant};
20
21/// Default interval between checks of a running process.
22pub const DEFAULT_RESULT_POLL: Duration = Duration::from_millis(100);
23
24/// Read stream events incrementally from a growing stdout buffer.
25#[derive(Debug, Clone, Default)]
26pub struct StdoutMessageReader {
27    scanner: JsonRecordScanner,
28    messages: Vec<Value>,
29    scanned: usize,
30}
31
32impl StdoutMessageReader {
33    pub fn new() -> Self {
34        Self::default()
35    }
36
37    /// Scan the complete lines added since the last call and return every
38    /// event parsed so far. A trailing partial line (or UTF-8 sequence) waits
39    /// for the next call.
40    pub fn read(&mut self, stdout: &str) -> &[Value] {
41        let end = stdout.rfind('\n').map_or(0, |index| index + 1);
42        if end > self.scanned {
43            for event in self.scanner.write(&stdout[self.scanned..end]) {
44                if let JsonRecordEvent::Json { value, .. } = event {
45                    match value {
46                        Value::Array(values) => self.messages.extend(values),
47                        value => self.messages.push(value),
48                    }
49                }
50            }
51            self.scanned = end;
52        }
53        &self.messages
54    }
55}
56
57/// Whether the main thread has ended its turn with a final result.
58pub fn has_final_result(tool: &str, messages: &[Value]) -> bool {
59    matches!(
60        completion_state(tool, messages),
61        Some("completed" | "failed")
62    )
63}
64
65/// How long a process may stay after its final result.
66#[derive(Debug, Clone, Copy, PartialEq, Eq)]
67pub struct ResultCloseOptions {
68    /// Time the process may stay after its result once no background task
69    /// runs; `None` waits for it to exit
70    pub close_timeout: Option<Duration>,
71    /// Extra time granted while background tasks still run; `None` leaves
72    /// them to the tool's own ceiling
73    pub background_wait: Option<Duration>,
74    /// Poll interval
75    pub poll: Duration,
76    /// Stop the process on the first `api_retry` event with status 401/403
77    /// (issue #69)
78    pub fail_fast_on_auth_error: bool,
79}
80
81/// How a watched process ended.
82#[derive(Debug, Clone, PartialEq, Eq)]
83pub struct ResultCloseOutcome {
84    pub exit_code: i32,
85    /// The process was stopped after its final result
86    pub terminated_after_result: bool,
87    /// The `api_retry` event that stopped the process under
88    /// `fail_fast_on_auth_error`
89    pub auth_refusal: Option<Value>,
90}
91
92impl Default for ResultCloseOptions {
93    fn default() -> Self {
94        Self {
95            close_timeout: None,
96            background_wait: None,
97            poll: DEFAULT_RESULT_POLL,
98            fail_fast_on_auth_error: false,
99        }
100    }
101}
102
103/// Wait for a process to exit, stopping it when it outlives its result.
104///
105/// Returns the exit code and whether the process was stopped after its result.
106pub async fn wait_for_exit_after_result(
107    handle: &mut ProcessHandle,
108    tool: &str,
109    options: ResultCloseOptions,
110) -> io::Result<(i32, bool)> {
111    let outcome = watch_process_exit(handle, tool, options).await?;
112    Ok((outcome.exit_code, outcome.terminated_after_result))
113}
114
115/// Wait for a process to exit, stopping it when it outlives its result or,
116/// with `fail_fast_on_auth_error`, when its API request is refused with
117/// 401/403.
118pub async fn watch_process_exit(
119    handle: &mut ProcessHandle,
120    tool: &str,
121    options: ResultCloseOptions,
122) -> io::Result<ResultCloseOutcome> {
123    let finish = |exit_code, terminated_after_result, auth_refusal| ResultCloseOutcome {
124        exit_code,
125        terminated_after_result,
126        auth_refusal,
127    };
128    if options.close_timeout.is_none() && !options.fail_fast_on_auth_error {
129        return Ok(finish(handle.wait_for_exit().await?, false, None));
130    }
131    let mut reader = StdoutMessageReader::new();
132    let mut checked = 0;
133    let mut result_at: Option<Instant> = None;
134    let mut idle_at: Option<Instant> = None;
135    while !handle.try_wait()? {
136        tokio::time::sleep(options.poll).await;
137        if handle.try_wait()? {
138            break;
139        }
140        let messages = reader.read(&handle.peek_stdout());
141        if options.fail_fast_on_auth_error {
142            let refusal = messages[checked..]
143                .iter()
144                .find(|event| auth_refusal_status(event).is_some())
145                .cloned();
146            checked = messages.len();
147            if refusal.is_some() {
148                handle.terminate().await?;
149                return Ok(finish(handle.wait_for_exit().await?, false, refusal));
150            }
151        }
152        let Some(close_timeout) = options.close_timeout else {
153            continue;
154        };
155        if !has_final_result(tool, messages) {
156            result_at = None;
157            idle_at = None;
158            continue;
159        }
160        let now = Instant::now();
161        let first_result = *result_at.get_or_insert(now);
162        let running = !track_background_tasks(messages).running.is_empty();
163        idle_at = if running {
164            None
165        } else {
166            Some(idle_at.unwrap_or(now))
167        };
168        let idle_expired = idle_at.is_some_and(|at| now - at >= close_timeout);
169        let background_expired = options
170            .background_wait
171            .is_some_and(|wait| now - first_result >= wait + close_timeout);
172        if idle_expired || background_expired {
173            handle.terminate().await?;
174            return Ok(finish(handle.wait_for_exit().await?, true, None));
175        }
176    }
177    Ok(finish(handle.wait_for_exit().await?, false, None))
178}