1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
//! CLI executor for running prompts through backends.
//!
//! Executes prompts via CLI tools with real-time streaming output.
//! Supports optional execution timeout with graceful SIGTERM termination.
use crate::cli_backend::CliBackend;
#[cfg(test)]
use crate::cli_backend::{OutputFormat, PromptMode};
use nix::sys::signal::{Signal, kill};
use nix::unistd::Pid;
use std::io::Write;
use std::process::Stdio;
use std::time::Duration;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::process::Command;
use tracing::{debug, warn};
/// Result of a CLI execution.
#[derive(Debug)]
pub struct ExecutionResult {
/// The full output from the CLI.
pub output: String,
/// Whether the execution succeeded (exit code 0).
pub success: bool,
/// The exit code.
pub exit_code: Option<i32>,
/// Whether the execution was terminated due to timeout.
pub timed_out: bool,
}
/// Executor for running prompts through CLI backends.
#[derive(Debug)]
pub struct CliExecutor {
backend: CliBackend,
}
impl CliExecutor {
/// Creates a new executor with the given backend.
pub fn new(backend: CliBackend) -> Self {
Self { backend }
}
/// Executes a prompt and streams output to the provided writer.
///
/// Output is streamed line-by-line to the writer while being accumulated
/// for the return value. If `timeout` is provided and the execution exceeds
/// it, the process receives SIGTERM and the result indicates timeout.
///
/// When `verbose` is true, stderr output is also written to the output writer
/// with a `[stderr]` prefix. When false, stderr is captured but not displayed.
pub async fn execute<W: Write + Send>(
&self,
prompt: &str,
mut output_writer: W,
timeout: Option<Duration>,
verbose: bool,
) -> std::io::Result<ExecutionResult> {
// Note: _temp_file is kept alive for the duration of this function scope.
// For large prompts (>7000 chars), Claude reads from the temp file.
let (cmd, args, stdin_input, _temp_file) = self.backend.build_command(prompt, false);
let mut command = Command::new(&cmd);
command.args(&args);
command.stdout(Stdio::piped());
command.stderr(Stdio::piped());
// Set working directory to current directory (mirrors PTY executor behavior)
let cwd = std::env::current_dir()?;
command.current_dir(&cwd);
debug!(
command = %cmd,
args = ?args,
cwd = ?cwd,
"Spawning CLI command"
);
if stdin_input.is_some() {
command.stdin(Stdio::piped());
}
let mut child = command.spawn()?;
// Write to stdin if needed
if let Some(input) = stdin_input
&& let Some(mut stdin) = child.stdin.take()
{
stdin.write_all(input.as_bytes()).await?;
drop(stdin); // Close stdin to signal EOF
}
let mut timed_out = false;
// Take both stdout and stderr handles upfront to read concurrently
// This prevents deadlock when stderr fills its buffer before stdout produces output
let stdout_handle = child.stdout.take();
let stderr_handle = child.stderr.take();
// Wrap the streaming in a timeout if configured
// Read stdout and stderr CONCURRENTLY to avoid pipe buffer deadlock
let stream_result = async {
// Create futures for reading both streams
let stdout_future = async {
let mut lines_out = Vec::new();
if let Some(stdout) = stdout_handle {
let reader = BufReader::new(stdout);
let mut lines = reader.lines();
while let Some(line) = lines.next_line().await? {
lines_out.push(line);
}
}
Ok::<_, std::io::Error>(lines_out)
};
let stderr_future = async {
let mut lines_out = Vec::new();
if let Some(stderr) = stderr_handle {
let reader = BufReader::new(stderr);
let mut lines = reader.lines();
while let Some(line) = lines.next_line().await? {
lines_out.push(line);
}
}
Ok::<_, std::io::Error>(lines_out)
};
// Read both streams concurrently to prevent deadlock
let (stdout_lines, stderr_lines) = tokio::try_join!(stdout_future, stderr_future)?;
// Write stdout lines first (main output)
for line in &stdout_lines {
writeln!(output_writer, "{line}")?;
}
// Write stderr lines (prefixed) only in verbose mode
if verbose {
for line in &stderr_lines {
writeln!(output_writer, "[stderr] {line}")?;
}
}
output_writer.flush()?;
// Build accumulated output (stdout first, then stderr)
let mut accumulated = String::new();
for line in stdout_lines {
accumulated.push_str(&line);
accumulated.push('\n');
}
for line in stderr_lines {
accumulated.push_str("[stderr] ");
accumulated.push_str(&line);
accumulated.push('\n');
}
Ok::<_, std::io::Error>(accumulated)
};
let accumulated_output = match timeout {
Some(duration) => {
debug!(timeout_secs = duration.as_secs(), "Executing with timeout");
match tokio::time::timeout(duration, stream_result).await {
Ok(result) => result?,
Err(_) => {
// Timeout elapsed - send SIGTERM to the child process
warn!(
timeout_secs = duration.as_secs(),
"Execution timeout reached, sending SIGTERM"
);
timed_out = true;
Self::terminate_child(&mut child)?;
String::new() // Return empty output on timeout
}
}
}
None => stream_result.await?,
};
let status = child.wait().await?;
Ok(ExecutionResult {
output: accumulated_output,
success: status.success() && !timed_out,
exit_code: status.code(),
timed_out,
})
}
/// Terminates the child process with SIGTERM.
fn terminate_child(child: &mut tokio::process::Child) -> std::io::Result<()> {
if let Some(pid) = child.id() {
#[allow(clippy::cast_possible_wrap)]
let pid = Pid::from_raw(pid as i32);
debug!(%pid, "Sending SIGTERM to child process");
let _ = kill(pid, Signal::SIGTERM);
}
Ok(())
}
/// Executes a prompt without streaming (captures all output).
///
/// Uses no timeout by default. For timed execution, use `execute_capture_with_timeout`.
pub async fn execute_capture(&self, prompt: &str) -> std::io::Result<ExecutionResult> {
self.execute_capture_with_timeout(prompt, None).await
}
/// Executes a prompt without streaming, with optional timeout.
pub async fn execute_capture_with_timeout(
&self,
prompt: &str,
timeout: Option<Duration>,
) -> std::io::Result<ExecutionResult> {
// Use a sink that discards output for non-streaming execution
// verbose=false since output is being discarded anyway
let sink = std::io::sink();
self.execute(prompt, sink, timeout, false).await
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn test_execute_echo() {
// Use echo as a simple test backend
let backend = CliBackend {
command: "echo".to_string(),
args: vec![],
prompt_mode: PromptMode::Arg,
prompt_flag: None,
output_format: OutputFormat::Text,
};
let executor = CliExecutor::new(backend);
let mut output = Vec::new();
let result = executor
.execute("hello world", &mut output, None, true)
.await
.unwrap();
assert!(result.success);
assert!(!result.timed_out);
assert!(result.output.contains("hello world"));
}
#[tokio::test]
async fn test_execute_stdin() {
// Use cat to test stdin mode
let backend = CliBackend {
command: "cat".to_string(),
args: vec![],
prompt_mode: PromptMode::Stdin,
prompt_flag: None,
output_format: OutputFormat::Text,
};
let executor = CliExecutor::new(backend);
let result = executor.execute_capture("stdin test").await.unwrap();
assert!(result.success);
assert!(result.output.contains("stdin test"));
}
#[tokio::test]
async fn test_execute_failure() {
let backend = CliBackend {
command: "false".to_string(), // Always exits with code 1
args: vec![],
prompt_mode: PromptMode::Arg,
prompt_flag: None,
output_format: OutputFormat::Text,
};
let executor = CliExecutor::new(backend);
let result = executor.execute_capture("").await.unwrap();
assert!(!result.success);
assert!(!result.timed_out);
assert_eq!(result.exit_code, Some(1));
}
#[tokio::test]
async fn test_execute_timeout() {
// Use sleep to test timeout behavior
// The sleep command ignores stdin, so we use PromptMode::Stdin
// to avoid appending the prompt as an argument
let backend = CliBackend {
command: "sleep".to_string(),
args: vec!["10".to_string()], // Sleep for 10 seconds
prompt_mode: PromptMode::Stdin, // Use stdin mode so prompt doesn't interfere
prompt_flag: None,
output_format: OutputFormat::Text,
};
let executor = CliExecutor::new(backend);
// Execute with a 100ms timeout - should trigger timeout
let timeout = Some(Duration::from_millis(100));
let result = executor
.execute_capture_with_timeout("", timeout)
.await
.unwrap();
assert!(result.timed_out, "Expected execution to time out");
assert!(
!result.success,
"Timed out execution should not be successful"
);
}
#[tokio::test]
async fn test_execute_no_timeout_when_fast() {
// Use echo which completes immediately
let backend = CliBackend {
command: "echo".to_string(),
args: vec![],
prompt_mode: PromptMode::Arg,
prompt_flag: None,
output_format: OutputFormat::Text,
};
let executor = CliExecutor::new(backend);
// Execute with a generous timeout - should complete before timeout
let timeout = Some(Duration::from_secs(10));
let result = executor
.execute_capture_with_timeout("fast", timeout)
.await
.unwrap();
assert!(!result.timed_out, "Fast command should not time out");
assert!(result.success);
assert!(result.output.contains("fast"));
}
}