agent_commander/
result_close.rs1use 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
16pub const DEFAULT_RESULT_POLL: Duration = Duration::from_millis(100);
18
19#[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 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
52pub fn has_final_result(tool: &str, messages: &[Value]) -> bool {
54 matches!(
55 completion_state(tool, messages),
56 Some("completed" | "failed")
57 )
58}
59
60#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub struct ResultCloseOptions {
63 pub close_timeout: Option<Duration>,
66 pub background_wait: Option<Duration>,
69 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
83pub 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}