use std::io::{self, BufRead, BufReader, Read, Write};
use std::os::unix::process::{CommandExt, ExitStatusExt};
use std::path::Path;
use std::process::{Child, Command, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};
use serde_json::Value;
use super::adapter::Agent;
use super::signin;
use super::tree::{self, SIGKILL};
use super::watch::{EXIT_LINE, GRACE};
mod shared;
pub use shared::{Announce, End, Shared, lock};
const LINE_BYTES: usize = 8 * 1024 * 1024;
const DRAIN: Duration = Duration::from_secs(1);
const FALLBACK: Duration = Duration::from_secs(3);
const FILING: Duration = Duration::from_secs(300);
pub struct Turn {
pub shared: Arc<Mutex<Shared>>,
pub before: Result<u64, String>,
pub read_text: usize,
pub read_events: usize,
pub notes: Vec<String>,
stop: Arc<AtomicBool>,
supervisor: Option<JoinHandle<()>>,
}
fn bounded_line(reader: &mut impl BufRead, line: &mut Vec<u8>) -> io::Result<bool> {
line.clear();
let mut seen = false;
loop {
let buffer = reader.fill_buf()?;
if buffer.is_empty() {
return Ok(seen);
}
seen = true;
let (chunk, done) = match buffer.iter().position(|b| *b == b'\n') {
Some(at) => (&buffer[..at], at + 1),
None => (buffer, buffer.len()),
};
if line.len() < LINE_BYTES {
let room = LINE_BYTES - line.len();
line.extend_from_slice(&chunk[..chunk.len().min(room)]);
}
let newline = done > chunk.len();
reader.consume(done);
if newline {
return Ok(true);
}
}
}
impl Turn {
pub fn begin(
agent: Agent,
plan: &Value,
prompt: &str,
dir: &Path,
limit: Duration,
announce: Option<Announce>,
nonce: String,
) -> io::Result<Self> {
let mut command = Command::new(std::env::current_exe()?);
if let Some(home) = super::selection::home() {
command.env(crate::home::HOME_ENV, home);
}
let mut child = command
.arg("harness-watch")
.current_dir(dir)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.process_group(0)
.spawn()?;
let mut message = plan.to_string().into_bytes();
message.push(b'\n');
message.extend_from_slice(prompt.as_bytes());
let shared = Arc::new(Mutex::new(Shared::default()));
let stdout = child.stdout.take().expect("piped");
let stderr = child.stderr.take().expect("piped");
let out = Arc::clone(&shared);
thread::spawn(move || {
let mut announce = announce;
let mut reader = BufReader::new(stdout);
let mut line = Vec::new();
while let Ok(true) = bounded_line(&mut reader, &mut line) {
let events = agent.read(&String::from_utf8_lossy(&line));
let mut shared = lock(&out);
for event in events {
shared.apply(event, &mut announce);
}
}
lock(&out).eof = true;
});
let err = Arc::clone(&shared);
thread::spawn(move || {
let mut stderr = stderr;
let mut chunk = [0u8; 4096];
while let Ok(n) = stderr.read(&mut chunk) {
if n == 0 {
break;
}
let mut shared = lock(&err);
shared.stderr.push(&String::from_utf8_lossy(&chunk[..n]));
began(&mut shared, &nonce);
}
exit_line(&mut lock(&err), &nonce, agent);
});
let stop = Arc::new(AtomicBool::new(false));
let asked = Arc::clone(&stop);
let state = Arc::clone(&shared);
let supervisor = thread::spawn(move || supervise(child, message, &asked, &state, limit));
Ok(Self {
shared,
before: Ok(0),
read_text: 0,
read_events: 0,
notes: Vec::new(),
stop,
supervisor: Some(supervisor),
})
}
pub fn ended(&self) -> bool {
lock(&self.shared).ended()
}
pub fn ask_stop(&self) {
self.stop.store(true, Ordering::SeqCst);
}
pub fn join(&mut self, bound: Duration) -> bool {
let deadline = Instant::now() + bound;
while self
.supervisor
.as_ref()
.is_some_and(|handle| !handle.is_finished())
{
if Instant::now() >= deadline {
return false;
}
thread::sleep(Duration::from_millis(10));
}
if let Some(handle) = self.supervisor.take() {
let _ = handle.join();
}
true
}
pub fn stop_bound() -> Duration {
GRACE + FALLBACK + GRACE + Duration::from_secs(1)
}
}
fn supervise(
mut child: Child,
message: Vec<u8>,
asked: &AtomicBool,
shared: &Mutex<Shared>,
limit: Duration,
) {
let mut control = child.stdin.take();
if let Some(stdin) = control.as_mut() {
let _ = stdin.write_all(&message).and_then(|()| stdin.flush());
}
let group = child.id() as i32;
let deadline = Instant::now() + limit;
let end = loop {
match child.try_wait() {
Ok(Some(status)) if status.signal().is_some() => break End::Lost,
Ok(Some(status)) => break End::Exited(status.code().unwrap_or(1)),
Ok(None) => {}
Err(_) => break End::Lost,
}
let timed_out = Instant::now() >= deadline;
if timed_out || asked.load(Ordering::SeqCst) {
drop(control.take());
terminate(&mut child, group, shared);
break if timed_out {
End::TimedOut
} else {
End::Stopped
};
}
thread::sleep(Duration::from_millis(25));
};
drop(control);
tree::end_group(group, GRACE);
let mut shared = lock(shared);
if shared.end.is_none() {
shared.end = Some(end);
shared.ended_at = Some(Instant::now());
}
}
fn exit_line(shared: &mut Shared, nonce: &str, agent: Agent) {
began(shared, nonce);
let text = shared.stderr.text().to_string();
let marker = format!("{EXIT_LINE} {nonce} ");
let Some(at) = text.rfind(&marker) else {
return;
};
let Ok(code) = text[at + marker.len()..].trim().parse::<i32>() else {
return;
};
let (kept, filed) = super::filing::taken(&text[..at], nonce);
if signin::stderr_said(agent, code, &kept) {
shared.apply(signin::failed_after(agent, &kept), &mut None);
}
shared.filed = filed;
shared.stderr.replace(kept.trim_end());
if shared.end.is_none() {
shared.end = Some(End::Exited(code));
shared.ended_at = Some(Instant::now());
}
}
fn began(shared: &mut Shared, nonce: &str) {
if let Some(kept) = super::filing::began(shared.stderr.text(), nonce) {
shared.filing = true;
shared.stderr.replace(&kept);
}
}
fn terminate(child: &mut Child, group: i32, shared: &Mutex<Shared>) {
let mut deadline = Instant::now() + GRACE + FALLBACK;
let mut filing = false;
while Instant::now() < deadline {
if let Ok(Some(_)) = child.try_wait() {
return;
}
if !filing && lock(shared).filing {
filing = true;
deadline = Instant::now() + FILING;
}
thread::sleep(Duration::from_millis(20));
}
tree::end_group(group, Duration::from_secs(1));
tree::signal(-group, SIGKILL);
let _ = child.wait();
}