BlueGit

ict rusty-teams

Files

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

runner.rs

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