use crate::api_status::auth_refusal_status;
use crate::background_tasks::track_background_tasks;
use crate::completion::completion_state;
use crate::executor::ProcessHandle;
use crate::streaming::{JsonRecordEvent, JsonRecordScanner};
use serde_json::Value;
use std::io;
use std::time::{Duration, Instant};
pub const DEFAULT_RESULT_POLL: Duration = Duration::from_millis(100);
#[derive(Debug, Clone, Default)]
pub struct StdoutMessageReader {
scanner: JsonRecordScanner,
messages: Vec<Value>,
scanned: usize,
}
impl StdoutMessageReader {
pub fn new() -> Self {
Self::default()
}
pub fn read(&mut self, stdout: &str) -> &[Value] {
let end = stdout.rfind('\n').map_or(0, |index| index + 1);
if end > self.scanned {
for event in self.scanner.write(&stdout[self.scanned..end]) {
if let JsonRecordEvent::Json { value, .. } = event {
match value {
Value::Array(values) => self.messages.extend(values),
value => self.messages.push(value),
}
}
}
self.scanned = end;
}
&self.messages
}
}
pub fn has_final_result(tool: &str, messages: &[Value]) -> bool {
matches!(
completion_state(tool, messages),
Some("completed" | "failed")
)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ResultCloseOptions {
pub close_timeout: Option<Duration>,
pub background_wait: Option<Duration>,
pub poll: Duration,
pub fail_fast_on_auth_error: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResultCloseOutcome {
pub exit_code: i32,
pub terminated_after_result: bool,
pub auth_refusal: Option<Value>,
}
impl Default for ResultCloseOptions {
fn default() -> Self {
Self {
close_timeout: None,
background_wait: None,
poll: DEFAULT_RESULT_POLL,
fail_fast_on_auth_error: false,
}
}
}
pub async fn wait_for_exit_after_result(
handle: &mut ProcessHandle,
tool: &str,
options: ResultCloseOptions,
) -> io::Result<(i32, bool)> {
let outcome = watch_process_exit(handle, tool, options).await?;
Ok((outcome.exit_code, outcome.terminated_after_result))
}
pub async fn watch_process_exit(
handle: &mut ProcessHandle,
tool: &str,
options: ResultCloseOptions,
) -> io::Result<ResultCloseOutcome> {
let finish = |exit_code, terminated_after_result, auth_refusal| ResultCloseOutcome {
exit_code,
terminated_after_result,
auth_refusal,
};
if options.close_timeout.is_none() && !options.fail_fast_on_auth_error {
return Ok(finish(handle.wait_for_exit().await?, false, None));
}
let mut reader = StdoutMessageReader::new();
let mut checked = 0;
let mut result_at: Option<Instant> = None;
let mut idle_at: Option<Instant> = None;
while !handle.try_wait()? {
tokio::time::sleep(options.poll).await;
if handle.try_wait()? {
break;
}
let messages = reader.read(&handle.peek_stdout());
if options.fail_fast_on_auth_error {
let refusal = messages[checked..]
.iter()
.find(|event| auth_refusal_status(event).is_some())
.cloned();
checked = messages.len();
if refusal.is_some() {
handle.terminate().await?;
return Ok(finish(handle.wait_for_exit().await?, false, refusal));
}
}
let Some(close_timeout) = options.close_timeout else {
continue;
};
if !has_final_result(tool, messages) {
result_at = None;
idle_at = None;
continue;
}
let now = Instant::now();
let first_result = *result_at.get_or_insert(now);
let running = !track_background_tasks(messages).running.is_empty();
idle_at = if running {
None
} else {
Some(idle_at.unwrap_or(now))
};
let idle_expired = idle_at.is_some_and(|at| now - at >= close_timeout);
let background_expired = options
.background_wait
.is_some_and(|wait| now - first_result >= wait + close_timeout);
if idle_expired || background_expired {
handle.terminate().await?;
return Ok(finish(handle.wait_for_exit().await?, true, None));
}
}
Ok(finish(handle.wait_for_exit().await?, false, None))
}