agent_commander/
result_close.rs1use 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
21pub const DEFAULT_RESULT_POLL: Duration = Duration::from_millis(100);
23
24#[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 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
57pub fn has_final_result(tool: &str, messages: &[Value]) -> bool {
59 matches!(
60 completion_state(tool, messages),
61 Some("completed" | "failed")
62 )
63}
64
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
67pub struct ResultCloseOptions {
68 pub close_timeout: Option<Duration>,
71 pub background_wait: Option<Duration>,
74 pub poll: Duration,
76 pub fail_fast_on_auth_error: bool,
79}
80
81#[derive(Debug, Clone, PartialEq, Eq)]
83pub struct ResultCloseOutcome {
84 pub exit_code: i32,
85 pub terminated_after_result: bool,
87 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
103pub 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
115pub 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}