BlueGit

ict rusty-teams

Files

rusty-teams / crates / agents / src / runner.rs

runner.rs

runner.rs 7.3 KiB Download Raw
1use std::collections::VecDeque;
2use std::process::Stdio;
3use std::sync::{Arc, Mutex};
4
5use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
6use tokio::process::Command;
7use tokio::sync::{mpsc, oneshot};
8
9use crate::invocation::{Invocation, RunPlan};
10use crate::parse::{OutputParser, RunEvent};
11use crate::profile::OutputFormat;
12
13const STDERR_TAIL_LINES: usize = 20;
14const PROBE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
15
16#[derive(Clone, Debug, PartialEq, Eq)]
17pub enum RunUpdate {
18 Event(RunEvent),
19 Stderr(String),
20}
21
22#[derive(Clone, Debug, PartialEq, Eq)]
23pub enum RunStatus {
24 Completed {
25 final_text: String,
26 },
27 Failed {
28 message: String,
29 stderr_tail: Vec<String>,
30 },
31 Stopped,
32}
33
34#[derive(Clone, Debug, PartialEq, Eq)]
35pub struct RunOutcome {
36 pub status: RunStatus,
37 pub exit_code: Option<i32>,
38}
39
40fn command_for(invocation: &Invocation) -> Command {
41 let mut command = Command::new(&invocation.program);
42 command.args(&invocation.args);
43 if let Some(cwd) = &invocation.cwd {
44 command.current_dir(cwd);
45 }
46 command.kill_on_drop(true);
47 #[cfg(windows)]
48 command.creation_flags(0x0800_0000);
49 command
50}
51
52fn failed(message: String, stderr_tail: Vec<String>, exit_code: Option<i32>) -> RunOutcome {
53 RunOutcome {
54 status: RunStatus::Failed {
55 message,
56 stderr_tail,
57 },
58 exit_code,
59 }
60}
61
62async fn run_stop_invocation(invocation: &Invocation) {
63 let mut command = command_for(invocation);
64 command
65 .stdin(Stdio::null())
66 .stdout(Stdio::null())
67 .stderr(Stdio::null());
68 if let Ok(mut child) = command.spawn() {
69 let _ = child.wait().await;
70 }
71}
72
73fn snapshot(tail: &Mutex<VecDeque<String>>) -> Vec<String> {
74 tail.lock()
75 .map(|lines| lines.iter().cloned().collect())
76 .unwrap_or_default()
77}
78
79pub async fn run(
80 plan: RunPlan,
81 format: OutputFormat,
82 events: mpsc::UnboundedSender<RunUpdate>,
83 stop: oneshot::Receiver<()>,
84) -> RunOutcome {
85 let cleanup = plan.cleanup.clone();
86 let outcome = run_plan(plan, format, events, stop).await;
87 for path in cleanup {
88 let _ = std::fs::remove_file(path);
89 }
90 outcome
91}
92
93async fn run_plan(
94 plan: RunPlan,
95 format: OutputFormat,
96 events: mpsc::UnboundedSender<RunUpdate>,
97 mut stop: oneshot::Receiver<()>,
98) -> RunOutcome {
99 let mut command = command_for(&plan.run);
100 command
101 .stdin(Stdio::piped())
102 .stdout(Stdio::piped())
103 .stderr(Stdio::piped());
104 let mut child = match command.spawn() {
105 Ok(child) => child,
106 Err(error) => {
107 return failed(
108 format!("cannot start {}: {error}", plan.run.program),
109 Vec::new(),
110 None,
111 );
112 }
113 };
114 let (Some(stdin), Some(stdout), Some(stderr)) =
115 (child.stdin.take(), child.stdout.take(), child.stderr.take())
116 else {
117 return failed(
118 "cannot attach to the process pipes".to_string(),
119 Vec::new(),
120 None,
121 );
122 };
123
124 let prompt = plan.run.stdin.clone();
125 let stdin_task = tokio::spawn(async move {
126 let mut stdin = stdin;
127 if let Some(prompt) = prompt {
128 let _ = stdin.write_all(prompt.as_bytes()).await;
129 }
130 let _ = stdin.shutdown().await;
131 });
132
133 let stderr_tail = Arc::new(Mutex::new(VecDeque::new()));
134 let stderr_task = {
135 let stderr_tail = Arc::clone(&stderr_tail);
136 let events = events.clone();
137 tokio::spawn(async move {
138 let mut lines = BufReader::new(stderr).lines();
139 while let Ok(Some(line)) = lines.next_line().await {
140 if let Ok(mut tail) = stderr_tail.lock() {
141 if tail.len() == STDERR_TAIL_LINES {
142 tail.pop_front();
143 }
144 tail.push_back(line.clone());
145 }
146 let _ = events.send(RunUpdate::Stderr(line));
147 }
148 })
149 };
150
151 let mut parser = OutputParser::new(format);
152 let mut final_text: Option<String> = None;
153 let mut failure_message: Option<String> = None;
154 let mut stdout_lines = BufReader::new(stdout).lines();
155 let mut stop_armed = true;
156
157 let mut handle_events = |parsed: Vec<RunEvent>| {
158 for event in parsed {
159 match &event {
160 RunEvent::Final(text) => final_text = Some(text.clone()),
161 RunEvent::Failed(message) => failure_message = Some(message.clone()),
162 _ => {}
163 }
164 let _ = events.send(RunUpdate::Event(event));
165 }
166 };
167
168 loop {
169 tokio::select! {
170 stop_result = &mut stop, if stop_armed => {
171 if stop_result.is_ok() {
172 let _ = child.kill().await;
173 if let Some(stop_invocation) = &plan.stop {
174 run_stop_invocation(stop_invocation).await;
175 }
176 stdin_task.abort();
177 stderr_task.abort();
178 return RunOutcome { status: RunStatus::Stopped, exit_code: None };
179 }
180 stop_armed = false;
181 }
182 line = stdout_lines.next_line() => match line {
183 Ok(Some(line)) => handle_events(parser.feed(&line)),
184 _ => break,
185 }
186 }
187 }
188 handle_events(parser.finish());
189
190 let exit_code = child.wait().await.ok().and_then(|status| status.code());
191 let _ = stdin_task.await;
192 let _ = stderr_task.await;
193 let tail = snapshot(&stderr_tail);
194
195 match (exit_code, final_text) {
196 (Some(0), Some(final_text)) => RunOutcome {
197 status: RunStatus::Completed { final_text },
198 exit_code,
199 },
200 _ => {
201 let message = failure_message
202 .or_else(|| tail.last().cloned())
203 .unwrap_or_else(|| match exit_code {
204 Some(code) => format!("exited with code {code}"),
205 None => "exited without a result".to_string(),
206 });
207 failed(message, tail, exit_code)
208 }
209 }
210}
211
212fn first_line(bytes: &[u8]) -> Option<String> {
213 String::from_utf8_lossy(bytes)
214 .lines()
215 .map(str::trim)
216 .find(|line| !line.is_empty())
217 .map(str::to_string)
218}
219
220pub async fn probe(invocation: &Invocation) -> Result<String, String> {
221 let mut command = command_for(invocation);
222 command
223 .stdin(Stdio::null())
224 .stdout(Stdio::piped())
225 .stderr(Stdio::piped());
226 let child = command
227 .spawn()
228 .map_err(|error| format!("cannot start {}: {error}", invocation.program))?;
229 let output = tokio::time::timeout(PROBE_TIMEOUT, child.wait_with_output())
230 .await
231 .map_err(|_| "no answer within 10 seconds".to_string())?
232 .map_err(|error| error.to_string())?;
233 if output.status.success() {
234 return Ok(first_line(&output.stdout)
235 .or_else(|| first_line(&output.stderr))
236 .unwrap_or_default());
237 }
238 Err(first_line(&output.stderr)
239 .or_else(|| first_line(&output.stdout))
240 .unwrap_or_else(|| match output.status.code() {
241 Some(code) => format!("exited with code {code}"),
242 None => "exited without a result".to_string(),
243 }))
244}