claux 20260907.0.0

Terminal AI coding assistant with tool execution
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
use anyhow::Result;
use async_trait::async_trait;
#[cfg(windows)]
use process_wrap::tokio::JobObject;
use process_wrap::tokio::{CommandWrap, KillOnDrop};
use serde::Deserialize;
use serde_json::{json, Value};
use std::process::Stdio;
use std::sync::Arc;
use std::time::Duration;
use tokio::io::AsyncReadExt;
use tokio::task::JoinHandle;
use tokio_util::sync::CancellationToken;

use super::{Tool, ToolOutput};
use crate::command_sandbox::CommandSandbox;

const CHILD_POLL_INTERVAL: Duration = Duration::from_millis(10);
const OUTPUT_DRAIN_TIMEOUT: Duration = Duration::from_secs(1);
const CHILD_REAP_TIMEOUT: Duration = Duration::from_secs(1);

pub struct BashTool {
    sandbox: Arc<CommandSandbox>,
}

impl BashTool {
    pub fn new(sandbox: Arc<CommandSandbox>) -> Self {
        Self { sandbox }
    }
}

#[derive(Deserialize)]
struct Params {
    command: String,
    #[serde(default)]
    timeout: Option<u64>,
    #[serde(default)]
    #[serde(rename = "description")]
    _description: Option<String>,
}

#[async_trait]
impl Tool for BashTool {
    fn name(&self) -> &str {
        "Bash"
    }

    fn description(&self) -> &str {
        "Execute a bash command. Use for git, build tools, or other CLI operations."
    }

    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "description": "The bash command to execute"
                },
                "timeout": {
                    "type": "integer",
                    "description": "Timeout in milliseconds (max 600000, default 120000)"
                },
                "description": {
                    "type": "string",
                    "description": "Short description of what the command does"
                }
            },
            "required": ["command"]
        })
    }

    fn is_read_only(&self) -> bool {
        false // conservative default; could be smarter with command analysis
    }

    fn summarize(&self, input: &Value) -> String {
        let cmd = input["command"].as_str().unwrap_or("?");
        // Truncate long commands
        if cmd.len() > 80 {
            format!("{}...", crate::utils::truncate_str(cmd, 77))
        } else {
            cmd.to_string()
        }
    }

    async fn execute(&self, input: Value, cancel: CancellationToken) -> Result<ToolOutput> {
        let params: Params = serde_json::from_value(input)?;

        let timeout_ms = params.timeout.unwrap_or(120_000).min(600_000);
        let timeout = Duration::from_millis(timeout_ms);

        let mut inner = self.sandbox.command(&params.command)?;
        inner.stdout(Stdio::piped()).stderr(Stdio::piped());
        #[cfg(unix)]
        inner.process_group(0);
        let mut command = CommandWrap::from(inner);
        // Commands commonly create descendants (shell pipelines, test runners,
        // build systems). Put the whole tree in one killable unit so cancelling
        // the tool cannot leave grandchildren alive with our pipes still open.
        command.wrap(KillOnDrop);
        #[cfg(windows)]
        command.wrap(JobObject);

        let mut child = match command.spawn() {
            Ok(c) => c,
            Err(e) => {
                return Ok(ToolOutput {
                    content: format!("Failed to execute command: {e}"),
                    is_error: true,
                });
            }
        };
        let process_group = child.id();

        // Take the pipes so we can read them concurrently with wait().
        let mut stdout_pipe = child.stdout().take();
        let mut stderr_pipe = child.stderr().take();

        // Spawn readers so partial output is captured even if we get cancelled
        // or time out mid-stream.
        let mut stdout_task = tokio::spawn(async move {
            let mut buf = Vec::new();
            if let Some(p) = stdout_pipe.as_mut() {
                let _ = p.read_to_end(&mut buf).await;
            }
            buf
        });
        let mut stderr_task = tokio::spawn(async move {
            let mut buf = Vec::new();
            if let Some(p) = stderr_pipe.as_mut() {
                let _ = p.read_to_end(&mut buf).await;
            }
            buf
        });

        let outcome = tokio::select! {
            status = wait_for_parent(&mut child) => Outcome::Finished(status),
            _ = cancel.cancelled() => Outcome::Cancelled,
            _ = tokio::time::sleep(timeout) => Outcome::TimedOut,
        };

        // A shell can exit successfully while a background descendant remains
        // alive and holds stdout/stderr open. Always terminate anything left
        // in the command's process tree before draining output. Persistent
        // services must detach into their own service manager and redirect
        // their streams rather than inheriting a tool invocation's pipes.
        let residual_processes_terminated = terminate_process_tree(&mut child, process_group);

        if !matches!(outcome, Outcome::Finished(_)) {
            let _ = tokio::time::timeout(CHILD_REAP_TIMEOUT, wait_for_parent(&mut child)).await;
        }

        let (stdout, stdout_abandoned) = drain_reader(&mut stdout_task).await;
        let (stderr, stderr_abandoned) = drain_reader(&mut stderr_task).await;
        let output_abandoned = stdout_abandoned || stderr_abandoned;

        let stdout_s = render_output(&stdout, "stdout");
        let stderr_s = render_output(&stderr, "stderr");

        let mut content = String::new();
        if !stdout_s.is_empty() {
            content.push_str(&stdout_s);
        }
        if !stderr_s.is_empty() {
            if !content.is_empty() {
                content.push('\n');
            }
            content.push_str(&stderr_s);
        }

        let mut is_error = match &outcome {
            Outcome::Finished(Ok(status)) => {
                if !status.success() {
                    content.push_str(&format!("\nExit code: {status}"));
                }
                !status.success()
            }
            Outcome::Finished(Err(e)) => {
                if !content.is_empty() {
                    content.push('\n');
                }
                content.push_str(&format!("wait error: {e}"));
                true
            }
            Outcome::Cancelled => {
                if !content.is_empty() {
                    content.push('\n');
                }
                content.push_str("Interrupted by user.");
                true
            }
            Outcome::TimedOut => {
                if !content.is_empty() {
                    content.push('\n');
                }
                content.push_str(&format!("Command timed out after {timeout_ms}ms"));
                true
            }
        };

        if matches!(outcome, Outcome::Finished(Ok(status)) if status.success())
            && residual_processes_terminated
        {
            if !content.is_empty() {
                content.push('\n');
            }
            content.push_str(
                "Background processes were terminated when the command exited. Use a service manager for persistent processes.",
            );
            is_error = true;
        }

        if output_abandoned {
            if !content.is_empty() {
                content.push('\n');
            }
            content.push_str(
                "A detached process kept command output open; Claux stopped waiting for its output.",
            );
            is_error = true;
        }

        if content.len() > 100_000 {
            content.truncate(100_000);
            content.push_str("\n... (output truncated)");
        }

        Ok(ToolOutput { content, is_error })
    }
}

async fn wait_for_parent(
    child: &mut Box<dyn process_wrap::tokio::ChildWrapper>,
) -> std::io::Result<std::process::ExitStatus> {
    loop {
        if let Some(status) = child.try_wait()? {
            return Ok(status);
        }
        tokio::time::sleep(CHILD_POLL_INTERVAL).await;
    }
}

#[cfg(unix)]
fn terminate_process_tree(
    _child: &mut Box<dyn process_wrap::tokio::ChildWrapper>,
    process_group: Option<u32>,
) -> bool {
    use nix::sys::signal::{killpg, Signal};
    use nix::unistd::Pid;

    process_group
        .and_then(|pid| i32::try_from(pid).ok())
        .is_some_and(|pid| killpg(Pid::from_raw(pid), Signal::SIGKILL).is_ok())
}

#[cfg(not(unix))]
fn terminate_process_tree(
    child: &mut Box<dyn process_wrap::tokio::ChildWrapper>,
    _process_group: Option<u32>,
) -> bool {
    child.start_kill().is_ok()
}

async fn drain_reader(task: &mut JoinHandle<Vec<u8>>) -> (Vec<u8>, bool) {
    match tokio::time::timeout(OUTPUT_DRAIN_TIMEOUT, &mut *task).await {
        Ok(Ok(output)) => (output, false),
        Ok(Err(_)) => (Vec::new(), false),
        Err(_) => {
            task.abort();
            (Vec::new(), true)
        }
    }
}

fn render_output(bytes: &[u8], stream: &str) -> String {
    match std::str::from_utf8(bytes) {
        Ok(text) if !bytes.contains(&0) => text.to_string(),
        _ => format!("[binary {stream} suppressed: {} bytes]", bytes.len()),
    }
}

enum Outcome {
    Finished(std::io::Result<std::process::ExitStatus>),
    Cancelled,
    TimedOut,
}

#[cfg(test)]
mod tests {
    use super::*;

    fn token() -> CancellationToken {
        CancellationToken::new()
    }

    fn tool() -> BashTool {
        BashTool::new(Arc::new(CommandSandbox::unrestricted_for_tests()))
    }

    #[tokio::test]
    async fn bash_echo() {
        let tool = tool();
        let result = tool
            .execute(json!({"command": "echo hello"}), token())
            .await
            .unwrap();
        assert!(!result.is_error);
        assert!(result.content.trim().contains("hello"));
    }

    #[tokio::test]
    async fn bash_exit_code() {
        let tool = tool();
        let result = tool
            .execute(json!({"command": "exit 1"}), token())
            .await
            .unwrap();
        assert!(result.is_error);
        assert!(result.content.contains("Exit code"));
    }

    #[tokio::test]
    async fn bash_captures_stderr() {
        let tool = tool();
        let result = tool
            .execute(json!({"command": "echo err >&2"}), token())
            .await
            .unwrap();
        assert!(result.content.contains("err"));
    }

    #[test]
    fn preserves_utf8_output() {
        assert_eq!(render_output("héllo\n".as_bytes(), "stdout"), "héllo\n");
    }

    #[test]
    fn suppresses_invalid_utf8_output() {
        assert_eq!(
            render_output(&[0xff, 0xfe, 0xfd], "stdout"),
            "[binary stdout suppressed: 3 bytes]"
        );
    }

    #[test]
    fn suppresses_nul_containing_output() {
        assert_eq!(
            render_output(b"text\0more", "stderr"),
            "[binary stderr suppressed: 9 bytes]"
        );
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn binary_stdout_does_not_hide_text_stderr() {
        let result = tool()
            .execute(
                json!({"command": "printf '\\377'; printf 'warning' >&2"}),
                token(),
            )
            .await
            .unwrap();

        assert!(!result.is_error);
        assert_eq!(
            result.content,
            "[binary stdout suppressed: 1 bytes]\nwarning"
        );
        assert!(!result.content.contains('\u{fffd}'));
    }

    #[tokio::test]
    async fn bash_timeout() {
        let tool = tool();
        let result = tool
            .execute(json!({"command": "sleep 10", "timeout": 100}), token())
            .await
            .unwrap();
        assert!(result.is_error);
        assert!(result.content.contains("timed out"));
    }

    #[tokio::test]
    async fn bash_cancellation() {
        let tool = tool();
        let cancel = CancellationToken::new();
        let cancel_clone = cancel.clone();
        tokio::spawn(async move {
            tokio::time::sleep(Duration::from_millis(100)).await;
            cancel_clone.cancel();
        });
        let start = std::time::Instant::now();
        let result = tool
            .execute(
                json!({
                    "command": "trap '' HUP; sleep 30 & wait",
                    "timeout": 60000
                }),
                cancel,
            )
            .await
            .unwrap();
        assert!(
            start.elapsed() < Duration::from_secs(3),
            "cancellation should kill the entire process tree (took {:?})",
            start.elapsed()
        );
        assert!(result.is_error);
        assert!(result.content.contains("Interrupted"));
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn background_process_cannot_hold_a_completed_command_open() {
        let start = std::time::Instant::now();
        let result = tool()
            .execute(
                json!({
                    "command": "nohup sleep 30 >/dev/null 2>&1 & printf ready",
                    "timeout": 60000
                }),
                token(),
            )
            .await
            .unwrap();

        assert!(
            start.elapsed() < Duration::from_secs(3),
            "background descendants must not hold the tool open (took {:?})",
            start.elapsed()
        );
        assert!(result.is_error);
        assert!(result.content.contains("ready"));
        assert!(result
            .content
            .contains("Background processes were terminated"));
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn detached_process_cannot_hold_output_capture_open() {
        let start = std::time::Instant::now();
        let result = tool()
            .execute(
                json!({
                    "command": "setsid sh -c 'sleep 2' & printf ready",
                    "timeout": 60000
                }),
                token(),
            )
            .await
            .unwrap();

        assert!(
            start.elapsed() < Duration::from_secs(3),
            "escaped descendants must not hold the tool open (took {:?})",
            start.elapsed()
        );
        assert!(result.is_error);
        assert!(result.content.contains("stopped waiting"));
    }
}