BlueGit

ict rusty-teams

Files

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

runner.rs

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