aboutsummaryrefslogtreecommitdiffstats
path: root/src/tools/shell.rs
diff options
context:
space:
mode:
authorsalmonik <salmonik@tuta.io>2026-11-15 03:11:22 +0100
committersalmonik <salmonik@tuta.io>2026-11-15 03:11:22 +0100
commit343f2a8a6148b8004d6f4d74fb779b4f30c9686a (patch)
tree2ea1ddab346565309da644517c3478d2a9096e55 /src/tools/shell.rs
parentM0: streaming provider, SSE decoder, mock provider, i686 build gate (diff)
downloadagent686-343f2a8a6148b8004d6f4d74fb779b4f30c9686a.tar.gz
agent686-343f2a8a6148b8004d6f4d74fb779b4f30c9686a.zip
M1-M5: sessions, six tools, approvals, prompt, Ctrl-C, target gate
- append-only JSONL sessions with --continue/--session; reasoning stored, stripped on replay - read/write/edit/grep/glob + bash with timeout and capped output - diff-preview approval for the first edit of a session, per-call approval for bash - system prompt frozen per session with AGENTS.md snapshot and change warning - SIGINT aborts the turn, second Ctrl-C exits - glibc gate ignores weak symbols; verified in linux/386 debian:12 - acceptance test (calculator in C) passes on both x86-64 and i386
Diffstat (limited to 'src/tools/shell.rs')
-rw-r--r--src/tools/shell.rs129
1 files changed, 129 insertions, 0 deletions
diff --git a/src/tools/shell.rs b/src/tools/shell.rs
new file mode 100644
index 0000000..9c214fb
--- /dev/null
+++ b/src/tools/shell.rs
@@ -0,0 +1,129 @@
1use std::fs::File;
2use std::io::{Read, Seek, SeekFrom};
3use std::path::PathBuf;
4use std::process::{Command, Stdio};
5use std::sync::atomic::{AtomicU64, Ordering};
6use std::time::{Duration, Instant};
7
8use serde_json::Value;
9
10const HEAD_BYTES: usize = 64 * 1024;
11const TAIL_BYTES: i64 = 16 * 1024;
12static COUNTER: AtomicU64 = AtomicU64::new(0);
13
14pub fn bash(args: &Value, timeout: Duration) -> Result<String, String> {
15 let cmd = match args.get("cmd").and_then(|v| v.as_str()) {
16 Some(cmd) => cmd.to_string(),
17 None => return Err("missing required argument `cmd`".into()),
18 };
19
20 let cwd = resolve_cwd(args.get("cwd").and_then(|v| v.as_str()))?;
21 if !cwd.is_dir() {
22 return Err(format!("cwd is not a directory: {}", cwd.display()));
23 }
24
25 let path = std::env::temp_dir().join(format!(
26 "agent686-{}-{}.out",
27 std::process::id(),
28 COUNTER.fetch_add(1, Ordering::Relaxed)
29 ));
30 let mut file = std::fs::OpenOptions::new()
31 .read(true)
32 .write(true)
33 .create(true)
34 .truncate(true)
35 .open(&path)
36 .map_err(|e| format!("{}: {e}", path.display()))?;
37 let stdout = file.try_clone().map_err(|e| e.to_string())?;
38 let stderr = file.try_clone().map_err(|e| e.to_string())?;
39
40 let mut child = Command::new("sh")
41 .arg("-c")
42 .arg(&cmd)
43 .current_dir(&cwd)
44 .stdin(Stdio::null())
45 .stdout(Stdio::from(stdout))
46 .stderr(Stdio::from(stderr))
47 .spawn()
48 .map_err(|e| format!("failed to start sh: {e}"))?;
49
50 let deadline = Instant::now() + timeout;
51 let mut timed_out = false;
52 let status = loop {
53 match child.try_wait().map_err(|e| e.to_string())? {
54 Some(status) => break status,
55 None => {
56 if Instant::now() >= deadline {
57 let _ = child.kill();
58 timed_out = true;
59 break child.wait().map_err(|e| e.to_string())?;
60 }
61 std::thread::sleep(Duration::from_millis(20));
62 }
63 }
64 };
65
66 let output = read_capped(&mut file).map_err(|e| format!("could not read output: {e}"))?;
67 drop(file);
68 let _ = std::fs::remove_file(&path);
69
70 let mut out = output;
71 if !out.is_empty() && !out.ends_with('\n') {
72 out.push('\n');
73 }
74 if timed_out {
75 out.push_str(&format!(
76 "[timed out after {:.1}s; process killed]",
77 timeout.as_secs_f64()
78 ));
79 } else {
80 match status.code() {
81 Some(code) => out.push_str(&format!("[exit {code}]")),
82 None => {
83 use std::os::unix::process::ExitStatusExt;
84 out.push_str(&format!(
85 "[killed by signal {}]",
86 status.signal().unwrap_or_default()
87 ));
88 }
89 }
90 }
91 Ok(out)
92}
93
94fn resolve_cwd(cwd: Option<&str>) -> Result<PathBuf, String> {
95 let current = std::env::current_dir().map_err(|e| e.to_string())?;
96 Ok(match cwd {
97 Some(dir) => {
98 let path = PathBuf::from(dir);
99 if path.is_absolute() {
100 path
101 } else {
102 current.join(path)
103 }
104 }
105 None => current,
106 })
107}
108
109fn read_capped(file: &mut File) -> Result<String, String> {
110 let len = file.metadata().map(|m| m.len()).unwrap_or(0);
111 file.seek(SeekFrom::Start(0)).map_err(|e| e.to_string())?;
112
113 let mut out = Vec::new();
114 if len <= HEAD_BYTES as u64 {
115 file.read_to_end(&mut out).map_err(|e| e.to_string())?;
116 } else {
117 file.take(HEAD_BYTES as u64)
118 .read_to_end(&mut out)
119 .map_err(|e| e.to_string())?;
120 let omitted = len.saturating_sub(HEAD_BYTES as u64 + TAIL_BYTES as u64);
121 out.extend_from_slice(format!("\n… {omitted} bytes omitted …\n").as_bytes());
122 file.seek(SeekFrom::End(-TAIL_BYTES))
123 .map_err(|e| e.to_string())?;
124 let mut tail = Vec::new();
125 file.read_to_end(&mut tail).map_err(|e| e.to_string())?;
126 out.extend_from_slice(&tail);
127 }
128 Ok(String::from_utf8_lossy(&out).into_owned())
129}