summaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorsalmonik <salmonik@tuta.io>2026-11-15 15:38:57 +0100
committersalmonik <salmonik@tuta.io>2026-11-15 15:38:57 +0100
commitc7afd1ea752aeff0310ac7c6b78d091ac360c760 (patch)
tree461f22fc3633ea1ea0e23ccbf330d7a55a92bea8 /src
parent0.4.1 + 0.4.2: abort integrity, stream completeness, tool-call indexing (diff)
downloadagent686-c7afd1ea752aeff0310ac7c6b78d091ac360c760.tar.gz
agent686-c7afd1ea752aeff0310ac7c6b78d091ac360c760.zip
0.4.3: kill process groups, bound bash output, keep the key out of tool env
- setsid-style process group kill on timeout and on Ctrl-C - 64 MiB RLIMIT_FSIZE so a runaway command cannot fill /tmp - OPENCODE_API_KEY removed from child environment - sessions 0600/0700, history 0600 and trimmed
Diffstat (limited to 'src')
-rw-r--r--src/agent.rs19
-rw-r--r--src/doctor.rs15
-rw-r--r--src/line.rs13
-rw-r--r--src/session.rs12
-rw-r--r--src/tools/mod.rs4
-rw-r--r--src/tools/shell.rs67
6 files changed, 116 insertions, 14 deletions
diff --git a/src/agent.rs b/src/agent.rs
index 46da069..9e2a431 100644
--- a/src/agent.rs
+++ b/src/agent.rs
@@ -159,6 +159,7 @@ pub fn run_turn(
159 let mut last: Option<Outcome> = None; 159 let mut last: Option<Outcome> = None;
160 let mut aborted = false; 160 let mut aborted = false;
161 let mut denied = 0usize; 161 let mut denied = 0usize;
162 let mut truncated: Option<String> = None;
162 163
163 loop { 164 loop {
164 if cancel.load(std::sync::atomic::Ordering::Relaxed) { 165 if cancel.load(std::sync::atomic::Ordering::Relaxed) {
@@ -184,6 +185,9 @@ pub fn run_turn(
184 } 185 }
185 } 186 }
186 187
188 if outcome.finish.as_deref() == Some("length") {
189 truncated = Some("the model hit its output limit; the answer is cut off".into());
190 }
187 let assistant = assistant_message(&outcome); 191 let assistant = assistant_message(&outcome);
188 push(session, history, assistant, Some(outcome.reasoning.as_str())); 192 push(session, history, assistant, Some(outcome.reasoning.as_str()));
189 193
@@ -204,7 +208,7 @@ pub fn run_turn(
204 let result = if aborted { 208 let result = if aborted {
205 ToolOutcome::Failed("aborted by the user before this call ran".into()) 209 ToolOutcome::Failed("aborted by the user before this call ran".into())
206 } else { 210 } else {
207 execute(&call, approver) 211 execute(&call, approver, cancel)
208 }; 212 };
209 if result.denied() { 213 if result.denied() {
210 denied += 1; 214 denied += 1;
@@ -226,6 +230,9 @@ pub fn run_turn(
226 if aborted { 230 if aborted {
227 eprintln!("aborted"); 231 eprintln!("aborted");
228 } 232 }
233 if let Some(note) = truncated {
234 eprintln!("agent686: {note}");
235 }
229 if let Some(outcome) = last { 236 if let Some(outcome) = last {
230 ui::status(steps, started.elapsed(), &outcome); 237 ui::status(steps, started.elapsed(), &outcome);
231 } 238 }
@@ -281,12 +288,16 @@ fn repair_tool_results(session: &mut Session, history: &mut Vec<Value>) {
281 } 288 }
282} 289}
283 290
284fn execute(call: &provider::ToolCall, approver: &mut Approver) -> ToolOutcome { 291fn execute(
292 call: &provider::ToolCall,
293 approver: &mut Approver,
294 cancel: &AtomicBool,
295) -> ToolOutcome {
285 let args: Value = serde_json::from_str(&call.arguments).unwrap_or_else(|_| json!({})); 296 let args: Value = serde_json::from_str(&call.arguments).unwrap_or_else(|_| json!({}));
286 ui::tool_line(&call.name, &args); 297 ui::tool_line(&call.name, &args);
287 298
288 match tools::approval(&call.name) { 299 match tools::approval(&call.name) {
289 Approval::Never => match tools::run(&call.name, &args) { 300 Approval::Never => match tools::run(&call.name, &args, cancel) {
290 Ok(output) => ToolOutcome::Ok(output), 301 Ok(output) => ToolOutcome::Ok(output),
291 Err(error) => ToolOutcome::Failed(error), 302 Err(error) => ToolOutcome::Failed(error),
292 }, 303 },
@@ -306,7 +317,7 @@ fn execute(call: &provider::ToolCall, approver: &mut Approver) -> ToolOutcome {
306 Approval::EveryCall => { 317 Approval::EveryCall => {
307 let cmd = args.get("cmd").and_then(|v| v.as_str()).unwrap_or(""); 318 let cmd = args.get("cmd").and_then(|v| v.as_str()).unwrap_or("");
308 if approver.allow_bash(cmd) { 319 if approver.allow_bash(cmd) {
309 match tools::run(&call.name, &args) { 320 match tools::run(&call.name, &args, cancel) {
310 Ok(output) => ToolOutcome::Ok(output), 321 Ok(output) => ToolOutcome::Ok(output),
311 Err(error) => ToolOutcome::Failed(error), 322 Err(error) => ToolOutcome::Failed(error),
312 } 323 }
diff --git a/src/doctor.rs b/src/doctor.rs
index 42d24a8..65fca50 100644
--- a/src/doctor.rs
+++ b/src/doctor.rs
@@ -19,7 +19,20 @@ pub fn run(cfg: &Config) -> i32 {
19 19
20 match config::key_source() { 20 match config::key_source() {
21 KeySource::Env => row(true, "key", "present in OPENCODE_API_KEY"), 21 KeySource::Env => row(true, "key", "present in OPENCODE_API_KEY"),
22 KeySource::File(path) => row(true, "key", &format!("present in {}", path.display())), 22 KeySource::File(path) => {
23 row(true, "key", &format!("present in {}", path.display()));
24 use std::os::unix::fs::PermissionsExt;
25 if let Ok(meta) = std::fs::metadata(&path) {
26 if meta.permissions().mode() & 0o077 != 0 {
27 println!(
28 "{:<13} {:<4} {} is readable by other users; chmod 600 it",
29 "key perms",
30 "WARN",
31 path.display()
32 );
33 }
34 }
35 }
23 KeySource::Missing => { 36 KeySource::Missing => {
24 row( 37 row(
25 false, 38 false,
diff --git a/src/line.rs b/src/line.rs
index 6b93f06..4989734 100644
--- a/src/line.rs
+++ b/src/line.rs
@@ -1,4 +1,5 @@
1use std::io::{self, IsTerminal, Write}; 1use std::io::{self, IsTerminal, Write};
2use std::os::unix::fs::PermissionsExt;
2use std::path::PathBuf; 3use std::path::PathBuf;
3 4
4use crossterm::cursor::{MoveToColumn, MoveUp}; 5use crossterm::cursor::{MoveToColumn, MoveUp};
@@ -324,7 +325,8 @@ fn history_path() -> PathBuf {
324} 325}
325 326
326fn load_history() -> Vec<String> { 327fn load_history() -> Vec<String> {
327 let text = std::fs::read_to_string(history_path()).unwrap_or_default(); 328 let path = history_path();
329 let text = std::fs::read_to_string(&path).unwrap_or_default();
328 let mut lines: Vec<String> = text 330 let mut lines: Vec<String> = text
329 .split('\n') 331 .split('\n')
330 .filter(|line| !line.trim().is_empty() && !line.starts_with('\u{0}')) 332 .filter(|line| !line.trim().is_empty() && !line.starts_with('\u{0}'))
@@ -332,6 +334,11 @@ fn load_history() -> Vec<String> {
332 .collect(); 334 .collect();
333 if lines.len() > HISTORY_LIMIT { 335 if lines.len() > HISTORY_LIMIT {
334 lines.drain(..lines.len() - HISTORY_LIMIT); 336 lines.drain(..lines.len() - HISTORY_LIMIT);
337 // Keep the file from growing without bound, not just the in-memory list.
338 if lines.len() * 2 < text.lines().count() {
339 let body: Vec<String> = lines.iter().map(|line| line.replace('\n', "\u{0}")).collect();
340 let _ = std::fs::write(&path, format!("{}\n", body.join("\n")));
341 }
335 } 342 }
336 lines 343 lines
337} 344}
@@ -341,11 +348,15 @@ fn append_history(line: &str) {
341 if let Some(parent) = path.parent() { 348 if let Some(parent) = path.parent() {
342 let _ = std::fs::create_dir_all(parent); 349 let _ = std::fs::create_dir_all(parent);
343 } 350 }
351 if let Some(parent) = path.parent() {
352 let _ = std::fs::set_permissions(parent, std::fs::Permissions::from_mode(0o700));
353 }
344 if let Ok(mut file) = std::fs::OpenOptions::new() 354 if let Ok(mut file) = std::fs::OpenOptions::new()
345 .create(true) 355 .create(true)
346 .append(true) 356 .append(true)
347 .open(&path) 357 .open(&path)
348 { 358 {
359 let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600));
349 // One record per line, so newlines inside a prompt are escaped. 360 // One record per line, so newlines inside a prompt are escaped.
350 let _ = writeln!(file, "{}", line.replace('\n', "\u{0}")); 361 let _ = writeln!(file, "{}", line.replace('\n', "\u{0}"));
351 } 362 }
diff --git a/src/session.rs b/src/session.rs
index 9f2b699..f27a188 100644
--- a/src/session.rs
+++ b/src/session.rs
@@ -1,6 +1,8 @@
1use std::fs::{File, OpenOptions}; 1use std::fs::{File, OpenOptions};
2use std::hash::{Hash, Hasher}; 2use std::hash::{Hash, Hasher};
3use std::io::{BufRead, BufReader, Read, Write}; 3use std::io::{BufRead, BufReader, Read, Write};
4use std::os::unix::fs::PermissionsExt;
5use std::path::Path;
4use std::path::PathBuf; 6use std::path::PathBuf;
5use std::time::{SystemTime, UNIX_EPOCH}; 7use std::time::{SystemTime, UNIX_EPOCH};
6 8
@@ -41,6 +43,11 @@ pub fn sessions_dir() -> PathBuf {
41 data_root().join("sessions") 43 data_root().join("sessions")
42} 44}
43 45
46/// Sessions contain the whole conversation, so they are for this user only.
47fn restrict(path: &Path, mode: u32) {
48 let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode));
49}
50
44pub struct Session { 51pub struct Session {
45 pub id: String, 52 pub id: String,
46 pub model: String, 53 pub model: String,
@@ -66,12 +73,15 @@ impl Session {
66 pub fn create_as(id: String, model: &str, system: &Value) -> Result<Session, String> { 73 pub fn create_as(id: String, model: &str, system: &Value) -> Result<Session, String> {
67 let dir = sessions_dir(); 74 let dir = sessions_dir();
68 std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?; 75 std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
76 restrict(&data_root(), 0o700);
77 restrict(&dir, 0o700);
69 let path = dir.join(format!("{id}.jsonl")); 78 let path = dir.join(format!("{id}.jsonl"));
70 let mut file = OpenOptions::new() 79 let mut file = OpenOptions::new()
71 .create_new(true) 80 .create_new(true)
72 .append(true) 81 .append(true)
73 .open(&path) 82 .open(&path)
74 .map_err(|e| format!("{}: {e}", path.display()))?; 83 .map_err(|e| format!("{}: {e}", path.display()))?;
84 restrict(&path, 0o600);
75 85
76 let header = json!({ 86 let header = json!({
77 "t": "header", 87 "t": "header",
@@ -141,6 +151,8 @@ impl Session {
141 .append(true) 151 .append(true)
142 .open(&path) 152 .open(&path)
143 .map_err(|e| format!("{}: {e}", path.display()))?; 153 .map_err(|e| format!("{}: {e}", path.display()))?;
154 // Older builds created these 0644.
155 restrict(&path, 0o600);
144 156
145 Ok(( 157 Ok((
146 Session { 158 Session {
diff --git a/src/tools/mod.rs b/src/tools/mod.rs
index 7a1a26d..a8851ab 100644
--- a/src/tools/mod.rs
+++ b/src/tools/mod.rs
@@ -25,12 +25,12 @@ pub fn approval(name: &str) -> Approval {
25} 25}
26 26
27/// Tools that execute immediately. 27/// Tools that execute immediately.
28pub fn run(name: &str, args: &Value) -> Result<String, String> { 28pub fn run(name: &str, args: &Value, cancel: &std::sync::atomic::AtomicBool) -> Result<String, String> {
29 match name { 29 match name {
30 "read" => fs::read(args), 30 "read" => fs::read(args),
31 "grep" => fs::grep(args), 31 "grep" => fs::grep(args),
32 "glob" => fs::glob(args), 32 "glob" => fs::glob(args),
33 "bash" => shell::bash(args, std::time::Duration::from_secs(120)), 33 "bash" => shell::bash(args, std::time::Duration::from_secs(120), cancel),
34 other => Err(unknown(other)), 34 other => Err(unknown(other)),
35 } 35 }
36} 36}
diff --git a/src/tools/shell.rs b/src/tools/shell.rs
index 9c214fb..29d2375 100644
--- a/src/tools/shell.rs
+++ b/src/tools/shell.rs
@@ -1,17 +1,25 @@
1use std::fs::File; 1use std::fs::File;
2use std::io::{Read, Seek, SeekFrom}; 2use std::io::{Read, Seek, SeekFrom};
3use std::os::unix::process::{CommandExt, ExitStatusExt};
3use std::path::PathBuf; 4use std::path::PathBuf;
4use std::process::{Command, Stdio}; 5use std::process::{Command, Stdio};
5use std::sync::atomic::{AtomicU64, Ordering}; 6use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
6use std::time::{Duration, Instant}; 7use std::time::{Duration, Instant};
7 8
8use serde_json::Value; 9use serde_json::Value;
9 10
10const HEAD_BYTES: usize = 64 * 1024; 11const HEAD_BYTES: usize = 64 * 1024;
11const TAIL_BYTES: i64 = 16 * 1024; 12const TAIL_BYTES: i64 = 16 * 1024;
13/// The child cannot write more than this, so a runaway command cannot fill /tmp
14/// and take the machine down with it.
15const MAX_OUTPUT_BYTES: u64 = 64 * 1024 * 1024;
12static COUNTER: AtomicU64 = AtomicU64::new(0); 16static COUNTER: AtomicU64 = AtomicU64::new(0);
13 17
14pub fn bash(args: &Value, timeout: Duration) -> Result<String, String> { 18pub fn bash(
19 args: &Value,
20 timeout: Duration,
21 cancel: &AtomicBool,
22) -> Result<String, String> {
15 let cmd = match args.get("cmd").and_then(|v| v.as_str()) { 23 let cmd = match args.get("cmd").and_then(|v| v.as_str()) {
16 Some(cmd) => cmd.to_string(), 24 Some(cmd) => cmd.to_string(),
17 None => return Err("missing required argument `cmd`".into()), 25 None => return Err("missing required argument `cmd`".into()),
@@ -37,25 +45,53 @@ pub fn bash(args: &Value, timeout: Duration) -> Result<String, String> {
37 let stdout = file.try_clone().map_err(|e| e.to_string())?; 45 let stdout = file.try_clone().map_err(|e| e.to_string())?;
38 let stderr = file.try_clone().map_err(|e| e.to_string())?; 46 let stderr = file.try_clone().map_err(|e| e.to_string())?;
39 47
40 let mut child = Command::new("sh") 48 let mut command = Command::new("sh");
49 command
41 .arg("-c") 50 .arg("-c")
42 .arg(&cmd) 51 .arg(&cmd)
43 .current_dir(&cwd) 52 .current_dir(&cwd)
44 .stdin(Stdio::null()) 53 .stdin(Stdio::null())
45 .stdout(Stdio::from(stdout)) 54 .stdout(Stdio::from(stdout))
46 .stderr(Stdio::from(stderr)) 55 .stderr(Stdio::from(stderr))
56 // The harness owns the key; no build script needs it, and a failing
57 // command that dumps the environment would put it in the transcript.
58 .env_remove("OPENCODE_API_KEY")
59 // Own process group, so the whole tree can be killed and so terminal
60 // Ctrl-C does not race our own handling.
61 .process_group(0);
62 unsafe {
63 command.pre_exec(|| {
64 let limit = libc::rlimit {
65 rlim_cur: MAX_OUTPUT_BYTES,
66 rlim_max: MAX_OUTPUT_BYTES,
67 };
68 if libc::setrlimit(libc::RLIMIT_FSIZE, &limit) != 0 {
69 return Err(std::io::Error::last_os_error());
70 }
71 Ok(())
72 });
73 }
74
75 let mut child = command
47 .spawn() 76 .spawn()
48 .map_err(|e| format!("failed to start sh: {e}"))?; 77 .map_err(|e| format!("failed to start sh: {e}"))?;
78 let group = child.id() as i32;
49 79
50 let deadline = Instant::now() + timeout; 80 let deadline = Instant::now() + timeout;
51 let mut timed_out = false; 81 let mut timed_out = false;
82 let mut aborted = false;
52 let status = loop { 83 let status = loop {
84 if cancel.load(Ordering::Relaxed) {
85 aborted = true;
86 kill_group(group);
87 break child.wait().map_err(|e| e.to_string())?;
88 }
53 match child.try_wait().map_err(|e| e.to_string())? { 89 match child.try_wait().map_err(|e| e.to_string())? {
54 Some(status) => break status, 90 Some(status) => break status,
55 None => { 91 None => {
56 if Instant::now() >= deadline { 92 if Instant::now() >= deadline {
57 let _ = child.kill();
58 timed_out = true; 93 timed_out = true;
94 kill_group(group);
59 break child.wait().map_err(|e| e.to_string())?; 95 break child.wait().map_err(|e| e.to_string())?;
60 } 96 }
61 std::thread::sleep(Duration::from_millis(20)); 97 std::thread::sleep(Duration::from_millis(20));
@@ -63,6 +99,9 @@ pub fn bash(args: &Value, timeout: Duration) -> Result<String, String> {
63 } 99 }
64 }; 100 };
65 101
102 // A child that blew the file-size limit was killed by SIGXFSZ.
103 let over_limit = status.signal() == Some(libc::SIGXFSZ);
104
66 let output = read_capped(&mut file).map_err(|e| format!("could not read output: {e}"))?; 105 let output = read_capped(&mut file).map_err(|e| format!("could not read output: {e}"))?;
67 drop(file); 106 drop(file);
68 let _ = std::fs::remove_file(&path); 107 let _ = std::fs::remove_file(&path);
@@ -71,7 +110,14 @@ pub fn bash(args: &Value, timeout: Duration) -> Result<String, String> {
71 if !out.is_empty() && !out.ends_with('\n') { 110 if !out.is_empty() && !out.ends_with('\n') {
72 out.push('\n'); 111 out.push('\n');
73 } 112 }
74 if timed_out { 113 if over_limit {
114 out.push_str(&format!(
115 "[output exceeded {} MiB; command killed]",
116 MAX_OUTPUT_BYTES / (1024 * 1024)
117 ));
118 } else if aborted {
119 out.push_str("[aborted by the user]");
120 } else if timed_out {
75 out.push_str(&format!( 121 out.push_str(&format!(
76 "[timed out after {:.1}s; process killed]", 122 "[timed out after {:.1}s; process killed]",
77 timeout.as_secs_f64() 123 timeout.as_secs_f64()
@@ -80,7 +126,6 @@ pub fn bash(args: &Value, timeout: Duration) -> Result<String, String> {
80 match status.code() { 126 match status.code() {
81 Some(code) => out.push_str(&format!("[exit {code}]")), 127 Some(code) => out.push_str(&format!("[exit {code}]")),
82 None => { 128 None => {
83 use std::os::unix::process::ExitStatusExt;
84 out.push_str(&format!( 129 out.push_str(&format!(
85 "[killed by signal {}]", 130 "[killed by signal {}]",
86 status.signal().unwrap_or_default() 131 status.signal().unwrap_or_default()
@@ -127,3 +172,13 @@ fn read_capped(file: &mut File) -> Result<String, String> {
127 } 172 }
128 Ok(String::from_utf8_lossy(&out).into_owned()) 173 Ok(String::from_utf8_lossy(&out).into_owned())
129} 174}
175
176/// SIGKILL the whole process group the command created. `child.kill()` would
177/// only reach `sh`, leaving `sh`'s children running on the 2-core box.
178fn kill_group(pid: i32) {
179 if pid > 0 {
180 unsafe {
181 libc::kill(-pid, libc::SIGKILL);
182 }
183 }
184}