BlueGit

ict rusty-teams

Files

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

runner.rs

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