summaryrefslogtreecommitdiffstats
path: root/src/tools
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--src/tools/mod.rs74
-rw-r--r--src/tools/shell.rs185
2 files changed, 181 insertions, 78 deletions
diff --git a/src/tools/mod.rs b/src/tools/mod.rs
index ddb1004..27840e9 100644
--- a/src/tools/mod.rs
+++ b/src/tools/mod.rs
@@ -24,28 +24,52 @@ pub fn approval(name: &str) -> Approval {
24 } 24 }
25} 25}
26 26
27/// A call with no arguments at all. Every tool here requires at least one, so 27/// True when the call cannot be replayed as a real tool call at all: no name.
28/// this is a placeholder some backends emit next to a real call, not an attempt. 28/// (Named calls with no arguments are kept so the model can be told what went
29/// wrong and retry.)
29pub fn is_placeholder(arguments: &str) -> bool { 30pub fn is_placeholder(arguments: &str) -> bool {
30 let trimmed = arguments.trim(); 31 arguments.trim().is_empty()
31 if trimmed.is_empty() { 32}
32 return true; 33
34/// Returns the keys the model actually sent, quoted and bounded.
35fn received_keys(args: &Value) -> String {
36 let Some(object) = args.as_object() else {
37 return "no arguments".to_string();
38 };
39 if object.is_empty() {
40 return "no arguments".to_string();
33 } 41 }
34 matches!( 42 let mut keys: Vec<String> = object.keys().map(|key| format!("`{key}`")).collect();
35 serde_json::from_str::<Value>(trimmed), 43 keys.sort();
36 Ok(Value::Object(map)) if map.is_empty() 44 if keys.len() > 6 {
37 ) 45 keys.truncate(6);
46 keys.push("…".to_string());
47 }
48 keys.join(", ")
38} 49}
39 50
40/// Rejects a call that cannot possibly run, before a human is asked to approve 51/// Rejects a call that cannot run, before a human is asked to approve it.
41/// it. An empty `cmd` used to mean an approval prompt for `run: `. 52///
53/// The message has to distinguish three different failures: the argument is
54/// empty, the argument is missing because the key is wrong, and the call
55/// arrived with no arguments at all (usually argument loss in transit). They
56/// used to share one message, which pointed callers at the wrong fix.
42pub fn validate(name: &str, args: &Value) -> Result<(), String> { 57pub fn validate(name: &str, args: &Value) -> Result<(), String> {
43 let text = |key: &str| args.get(key).and_then(|value| value.as_str()).unwrap_or(""); 58 let required = |key: &str| match args.get(key).and_then(|value| value.as_str()) {
44 let required = |key: &str| { 59 Some(value) if !value.trim().is_empty() => Ok(()),
45 if text(key).trim().is_empty() { 60 Some(_) => Err(format!("`{key}` is present but empty")),
46 Err(format!("`{key}` is required and must not be empty")) 61 None => {
47 } else { 62 if args.as_object().map(|o| o.is_empty()).unwrap_or(true) {
48 Ok(()) 63 Err(format!(
64 "the call arrived with no arguments at all, so `{key}` is missing. \
65 If you sent one, it was lost in transit — retry the call"
66 ))
67 } else {
68 Err(format!(
69 "missing `{key}`; received {}. The parameter is `{key}`",
70 received_keys(args)
71 ))
72 }
49 } 73 }
50 }; 74 };
51 75
@@ -57,6 +81,7 @@ pub fn validate(name: &str, args: &Value) -> Result<(), String> {
57 required("old") 81 required("old")
58 } 82 }
59 "grep" | "glob" => required("pattern"), 83 "grep" | "glob" => required("pattern"),
84 "" => Err("the tool call arrived without a tool name; it was probably truncated in transit — retry the call".into()),
60 _ => Ok(()), 85 _ => Ok(()),
61 } 86 }
62} 87}
@@ -67,7 +92,14 @@ pub fn run(name: &str, args: &Value, cancel: &std::sync::atomic::AtomicBool) ->
67 "read" => fs::read(args), 92 "read" => fs::read(args),
68 "grep" => fs::grep(args), 93 "grep" => fs::grep(args),
69 "glob" => fs::glob(args), 94 "glob" => fs::glob(args),
70 "bash" => shell::bash(args, std::time::Duration::from_secs(120), cancel), 95 "bash" => {
96 let seconds = args
97 .get("timeout_seconds")
98 .and_then(|value| value.as_u64())
99 .unwrap_or(120)
100 .clamp(1, 600);
101 shell::bash(args, std::time::Duration::from_secs(seconds), cancel)
102 }
71 other => Err(unknown(other)), 103 other => Err(unknown(other)),
72 } 104 }
73} 105}
@@ -139,12 +171,14 @@ pub fn schemas() -> Vec<Value> {
139 "type": "function", 171 "type": "function",
140 "function": { 172 "function": {
141 "name": "bash", 173 "name": "bash",
142 "description": "Run a shell command. Each call is a fresh shell at the working directory, so `cd` does not persist; pass cwd instead. Times out after 120s. Returns combined output and the exit code.", 174 "description": "Run a shell command. Each call is a fresh shell at the working directory, so `cd` does not persist; pass cwd instead. stdout and stderr are reported in separate labelled sections when both produce output. Times out after timeout_seconds (default 120, maximum 600). Large output is truncated head+tail with an explicit marker; raise max_bytes if the match you need is in the middle.",
143 "parameters": { 175 "parameters": {
144 "type": "object", 176 "type": "object",
145 "properties": { 177 "properties": {
146 "cmd": { "type": "string" }, 178 "cmd": { "type": "string" },
147 "cwd": { "type": "string", "description": "working directory (default: project root)" } 179 "cwd": { "type": "string", "description": "working directory (default: project root)" },
180 "timeout_seconds": { "type": "integer", "description": "1-600, default 120" },
181 "max_bytes": { "type": "integer", "description": "per-stream output budget, 1024-16777216, default 81920" }
148 }, 182 },
149 "required": ["cmd"] 183 "required": ["cmd"]
150 } 184 }
diff --git a/src/tools/shell.rs b/src/tools/shell.rs
index 6f095c6..91f2dd9 100644
--- a/src/tools/shell.rs
+++ b/src/tools/shell.rs
@@ -8,11 +8,14 @@ use std::time::{Duration, Instant};
8 8
9use serde_json::Value; 9use serde_json::Value;
10 10
11const HEAD_BYTES: usize = 64 * 1024; 11/// Default budget per stream, split 4:1 between head and tail.
12const TAIL_BYTES: i64 = 16 * 1024; 12const DEFAULT_MAX_BYTES: usize = 80 * 1024;
13/// The child cannot write more than this, so a runaway command cannot fill /tmp 13const MIN_MAX_BYTES: usize = 1024;
14/// and take the machine down with it. 14const MAX_MAX_BYTES: usize = 16 * 1024 * 1024;
15const MAX_OUTPUT_BYTES: u64 = 64 * 1024 * 1024; 15/// The child cannot write more than this per stream, so a runaway command cannot
16/// fill /tmp and take the machine down with it.
17const MAX_FILE_BYTES: u64 = 64 * 1024 * 1024;
18
16static COUNTER: AtomicU64 = AtomicU64::new(0); 19static COUNTER: AtomicU64 = AtomicU64::new(0);
17 20
18pub fn bash( 21pub fn bash(
@@ -25,25 +28,26 @@ pub fn bash(
25 None => return Err("missing required argument `cmd`".into()), 28 None => return Err("missing required argument `cmd`".into()),
26 }; 29 };
27 30
31 let max_bytes = args
32 .get("max_bytes")
33 .and_then(|value| value.as_u64())
34 .unwrap_or(DEFAULT_MAX_BYTES as u64)
35 .clamp(MIN_MAX_BYTES as u64, MAX_MAX_BYTES as u64) as usize;
36 let head_budget = max_bytes * 4 / 5;
37 let tail_budget = max_bytes - head_budget;
38
28 let cwd = resolve_cwd(args.get("cwd").and_then(|v| v.as_str()))?; 39 let cwd = resolve_cwd(args.get("cwd").and_then(|v| v.as_str()))?;
29 if !cwd.is_dir() { 40 if !cwd.is_dir() {
30 return Err(format!("cwd is not a directory: {}", cwd.display())); 41 return Err(format!("cwd is not a directory: {}", cwd.display()));
31 } 42 }
32 43
33 let path = std::env::temp_dir().join(format!( 44 let serial = COUNTER.fetch_add(1, Ordering::Relaxed);
34 "agent686-{}-{}.out", 45 let out_path = temp_path("out", serial);
35 std::process::id(), 46 let err_path = temp_path("err", serial);
36 COUNTER.fetch_add(1, Ordering::Relaxed) 47 let mut out_file = create(&out_path)?;
37 )); 48 let mut err_file = create(&err_path)?;
38 let mut file = std::fs::OpenOptions::new() 49 let stdout = out_file.try_clone().map_err(|e| e.to_string())?;
39 .read(true) 50 let stderr = err_file.try_clone().map_err(|e| e.to_string())?;
40 .write(true)
41 .create(true)
42 .truncate(true)
43 .open(&path)
44 .map_err(|e| format!("{}: {e}", path.display()))?;
45 let stdout = file.try_clone().map_err(|e| e.to_string())?;
46 let stderr = file.try_clone().map_err(|e| e.to_string())?;
47 51
48 let mut command = Command::new("sh"); 52 let mut command = Command::new("sh");
49 command 53 command
@@ -63,8 +67,8 @@ pub fn bash(
63 command.pre_exec(|| { 67 command.pre_exec(|| {
64 // rlim_t is u32 on i686 and u64 on x86-64. 68 // rlim_t is u32 on i686 and u64 on x86-64.
65 let limit = libc::rlimit { 69 let limit = libc::rlimit {
66 rlim_cur: MAX_OUTPUT_BYTES as libc::rlim_t, 70 rlim_cur: MAX_FILE_BYTES as libc::rlim_t,
67 rlim_max: MAX_OUTPUT_BYTES as libc::rlim_t, 71 rlim_max: MAX_FILE_BYTES as libc::rlim_t,
68 }; 72 };
69 if libc::setrlimit(libc::RLIMIT_FSIZE, &limit) != 0 { 73 if libc::setrlimit(libc::RLIMIT_FSIZE, &limit) != 0 {
70 return Err(std::io::Error::last_os_error()); 74 return Err(std::io::Error::last_os_error());
@@ -103,38 +107,97 @@ pub fn bash(
103 // A child that blew the file-size limit was killed by SIGXFSZ. 107 // A child that blew the file-size limit was killed by SIGXFSZ.
104 let over_limit = status.signal() == Some(libc::SIGXFSZ); 108 let over_limit = status.signal() == Some(libc::SIGXFSZ);
105 109
106 let output = read_capped(&mut file).map_err(|e| format!("could not read output: {e}"))?; 110 let (out_text, out_cut) = read_capped(&mut out_file, head_budget, tail_budget)?;
107 drop(file); 111 let (err_text, err_cut) = read_capped(&mut err_file, head_budget, tail_budget)?;
108 let _ = std::fs::remove_file(&path); 112 drop(out_file);
113 drop(err_file);
114 let _ = std::fs::remove_file(&out_path);
115 let _ = std::fs::remove_file(&err_path);
109 116
110 let mut out = output; 117 let marker = if over_limit {
111 if !out.is_empty() && !out.ends_with('\n') { 118 format!(
112 out.push('\n');
113 }
114 if over_limit {
115 out.push_str(&format!(
116 "[output exceeded {} MiB; command killed]", 119 "[output exceeded {} MiB; command killed]",
117 MAX_OUTPUT_BYTES / (1024 * 1024) 120 MAX_FILE_BYTES / (1024 * 1024)
118 )); 121 )
119 } else if aborted { 122 } else if aborted {
120 out.push_str("[aborted by the user]"); 123 "[aborted by the user]".to_string()
121 } else if timed_out { 124 } else if timed_out {
122 out.push_str(&format!( 125 format!("[timed out after {:.1}s; process killed]", timeout.as_secs_f64())
123 "[timed out after {:.1}s; process killed]",
124 timeout.as_secs_f64()
125 ));
126 } else { 126 } else {
127 match status.code() { 127 match status.code() {
128 Some(code) => out.push_str(&format!("[exit {code}]")), 128 Some(code) => format!("[exit {code}]"),
129 None => { 129 None => format!(
130 out.push_str(&format!( 130 "[killed by signal {}]",
131 "[killed by signal {}]", 131 status.signal().unwrap_or_default()
132 status.signal().unwrap_or_default() 132 ),
133 ));
134 }
135 } 133 }
134 };
135
136 Ok(format_result(
137 &out_text, out_cut, &err_text, err_cut, &marker,
138 ))
139}
140
141/// stdout and stderr are kept apart: a program that prints its real error to
142/// stderr used to be indistinguishable from one that printed it to stdout.
143/// Labelling only appears when it carries information.
144fn format_result(
145 stdout: &str,
146 stdout_truncated: bool,
147 stderr: &str,
148 stderr_truncated: bool,
149 marker: &str,
150) -> String {
151 let has_stdout = !stdout.trim().is_empty();
152 let has_stderr = !stderr.trim().is_empty();
153
154 let mut out = String::new();
155 if has_stdout && has_stderr {
156 out.push_str("[stdout]\n");
157 out.push_str(stdout);
158 end_line(&mut out, stdout);
159 out.push_str("[stderr]\n");
160 out.push_str(stderr);
161 end_line(&mut out, stderr);
162 } else if has_stderr {
163 out.push_str("[stderr]\n");
164 out.push_str(stderr);
165 end_line(&mut out, stderr);
166 } else if has_stdout {
167 out.push_str(stdout);
168 end_line(&mut out, stdout);
136 } 169 }
137 Ok(out) 170
171 let truncated = stdout_truncated || stderr_truncated;
172 out.push_str(marker);
173 if truncated {
174 out.push_str(" (output truncated; raise max_bytes or narrow the command)");
175 }
176 out
177}
178
179fn end_line(out: &mut String, text: &str) {
180 if !text.is_empty() && !text.ends_with('\n') {
181 out.push('\n');
182 }
183}
184
185fn temp_path(kind: &str, serial: u64) -> PathBuf {
186 std::env::temp_dir().join(format!(
187 "agent686-{}-{}-{kind}.log",
188 std::process::id(),
189 serial
190 ))
191}
192
193fn create(path: &PathBuf) -> Result<File, String> {
194 std::fs::OpenOptions::new()
195 .read(true)
196 .write(true)
197 .create(true)
198 .truncate(true)
199 .open(path)
200 .map_err(|e| format!("{}: {e}", path.display()))
138} 201}
139 202
140fn resolve_cwd(cwd: Option<&str>) -> Result<PathBuf, String> { 203fn resolve_cwd(cwd: Option<&str>) -> Result<PathBuf, String> {
@@ -152,26 +215,32 @@ fn resolve_cwd(cwd: Option<&str>) -> Result<PathBuf, String> {
152 }) 215 })
153} 216}
154 217
155fn read_capped(file: &mut File) -> Result<String, String> { 218/// Reads at most `head` bytes from the start and `tail` from the end, noting
219/// what was dropped. Returns the text and whether anything was cut.
220fn read_capped(file: &mut File, head: usize, tail: usize) -> Result<(String, bool), String> {
156 let len = file.metadata().map(|m| m.len()).unwrap_or(0); 221 let len = file.metadata().map(|m| m.len()).unwrap_or(0);
157 file.seek(SeekFrom::Start(0)).map_err(|e| e.to_string())?; 222 file.seek(SeekFrom::Start(0)).map_err(|e| e.to_string())?;
158 223
159 let mut out = Vec::new(); 224 let mut bytes = Vec::new();
160 if len <= HEAD_BYTES as u64 { 225 let mut truncated = false;
161 file.read_to_end(&mut out).map_err(|e| e.to_string())?; 226
227 if len <= (head + tail) as u64 {
228 file.read_to_end(&mut bytes).map_err(|e| e.to_string())?;
162 } else { 229 } else {
163 file.take(HEAD_BYTES as u64) 230 truncated = true;
164 .read_to_end(&mut out) 231 file.take(head as u64)
232 .read_to_end(&mut bytes)
165 .map_err(|e| e.to_string())?; 233 .map_err(|e| e.to_string())?;
166 let omitted = len.saturating_sub(HEAD_BYTES as u64 + TAIL_BYTES as u64); 234 let omitted = len.saturating_sub(head as u64 + tail as u64);
167 out.extend_from_slice(format!("\n… {omitted} bytes omitted …\n").as_bytes()); 235 bytes.extend_from_slice(format!("\n… {omitted} bytes omitted …\n").as_bytes());
168 file.seek(SeekFrom::End(-TAIL_BYTES)) 236 file.seek(SeekFrom::End(-(tail as i64)))
169 .map_err(|e| e.to_string())?; 237 .map_err(|e| e.to_string())?;
170 let mut tail = Vec::new(); 238 let mut rest = Vec::new();
171 file.read_to_end(&mut tail).map_err(|e| e.to_string())?; 239 file.read_to_end(&mut rest).map_err(|e| e.to_string())?;
172 out.extend_from_slice(&tail); 240 bytes.extend_from_slice(&rest);
173 } 241 }
174 Ok(String::from_utf8_lossy(&out).into_owned()) 242
243 Ok((String::from_utf8_lossy(&bytes).into_owned(), truncated))
175} 244}
176 245
177/// SIGKILL the whole process group the command created. `child.kill()` would 246/// SIGKILL the whole process group the command created. `child.kill()` would