diff options
| -rw-r--r-- | CHANGELOG.md | 17 | ||||
| -rw-r--r-- | Cargo.lock | 2 | ||||
| -rw-r--r-- | Cargo.toml | 2 | ||||
| -rw-r--r-- | src/agent.rs | 19 | ||||
| -rw-r--r-- | src/doctor.rs | 15 | ||||
| -rw-r--r-- | src/line.rs | 13 | ||||
| -rw-r--r-- | src/session.rs | 12 | ||||
| -rw-r--r-- | src/tools/mod.rs | 4 | ||||
| -rw-r--r-- | src/tools/shell.rs | 67 | ||||
| -rw-r--r-- | tests/sessions.rs | 6 | ||||
| -rw-r--r-- | tests/tools.rs | 106 |
11 files changed, 225 insertions, 38 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md index 9867621..79acd31 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md | |||
| @@ -7,6 +7,23 @@ break the interface, **PATCH** for bug fixes. | |||
| 7 | file, and the tool schemas the model sees. Anything a script or a resumed session | 7 | file, and the tool schemas the model sees. Anything a script or a resumed session |
| 8 | could depend on counts as API. | 8 | could depend on counts as API. |
| 9 | 9 | ||
| 10 | ## 0.4.3 | ||
| 11 | |||
| 12 | ### Fixed | ||
| 13 | - `bash` timeouts killed only the direct `sh`, leaving `make`, `cargo` or `sleep` | ||
| 14 | running on the 2-core box. The command now runs in its own process group and | ||
| 15 | the whole group is killed on timeout or on Ctrl-C. | ||
| 16 | - `bash` output was unbounded on disk while being truncated on read; the child now | ||
| 17 | has a 64 MiB file-size limit and reports when it hit it. | ||
| 18 | - A long-running command can now be stopped with Ctrl-C instead of waiting out | ||
| 19 | the 120 s timeout. | ||
| 20 | - `OPENCODE_API_KEY` was inherited by every command, so a failing build that | ||
| 21 | dumped the environment would put the key in the transcript and send it back to | ||
| 22 | the provider. It is removed from the child environment. | ||
| 23 | - Session files are created `0600` and their directories `0700`; older `0644` | ||
| 24 | files are tightened on open. History is `0600` and its file is trimmed. | ||
| 25 | - `--doctor` warns when the key file is readable by other users. | ||
| 26 | |||
| 10 | ## 0.4.2 | 27 | ## 0.4.2 |
| 11 | 28 | ||
| 12 | ### Fixed | 29 | ### Fixed |
| @@ -10,7 +10,7 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" | |||
| 10 | 10 | ||
| 11 | [[package]] | 11 | [[package]] |
| 12 | name = "agent686" | 12 | name = "agent686" |
| 13 | version = "0.4.0" | 13 | version = "0.4.2" |
| 14 | dependencies = [ | 14 | dependencies = [ |
| 15 | "crossterm", | 15 | "crossterm", |
| 16 | "libc", | 16 | "libc", |
| @@ -1,6 +1,6 @@ | |||
| 1 | [package] | 1 | [package] |
| 2 | name = "agent686" | 2 | name = "agent686" |
| 3 | version = "0.4.2" | 3 | version = "0.4.3" |
| 4 | edition = "2021" | 4 | edition = "2021" |
| 5 | description = "A small coding agent for a 32-bit Debian box" | 5 | description = "A small coding agent for a 32-bit Debian box" |
| 6 | publish = false | 6 | publish = false |
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 | ||
| 284 | fn execute(call: &provider::ToolCall, approver: &mut Approver) -> ToolOutcome { | 291 | fn 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 @@ | |||
| 1 | use std::io::{self, IsTerminal, Write}; | 1 | use std::io::{self, IsTerminal, Write}; |
| 2 | use std::os::unix::fs::PermissionsExt; | ||
| 2 | use std::path::PathBuf; | 3 | use std::path::PathBuf; |
| 3 | 4 | ||
| 4 | use crossterm::cursor::{MoveToColumn, MoveUp}; | 5 | use crossterm::cursor::{MoveToColumn, MoveUp}; |
| @@ -324,7 +325,8 @@ fn history_path() -> PathBuf { | |||
| 324 | } | 325 | } |
| 325 | 326 | ||
| 326 | fn load_history() -> Vec<String> { | 327 | fn 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 @@ | |||
| 1 | use std::fs::{File, OpenOptions}; | 1 | use std::fs::{File, OpenOptions}; |
| 2 | use std::hash::{Hash, Hasher}; | 2 | use std::hash::{Hash, Hasher}; |
| 3 | use std::io::{BufRead, BufReader, Read, Write}; | 3 | use std::io::{BufRead, BufReader, Read, Write}; |
| 4 | use std::os::unix::fs::PermissionsExt; | ||
| 5 | use std::path::Path; | ||
| 4 | use std::path::PathBuf; | 6 | use std::path::PathBuf; |
| 5 | use std::time::{SystemTime, UNIX_EPOCH}; | 7 | use 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. | ||
| 47 | fn restrict(path: &Path, mode: u32) { | ||
| 48 | let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode)); | ||
| 49 | } | ||
| 50 | |||
| 44 | pub struct Session { | 51 | pub 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. |
| 28 | pub fn run(name: &str, args: &Value) -> Result<String, String> { | 28 | pub 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 @@ | |||
| 1 | use std::fs::File; | 1 | use std::fs::File; |
| 2 | use std::io::{Read, Seek, SeekFrom}; | 2 | use std::io::{Read, Seek, SeekFrom}; |
| 3 | use std::os::unix::process::{CommandExt, ExitStatusExt}; | ||
| 3 | use std::path::PathBuf; | 4 | use std::path::PathBuf; |
| 4 | use std::process::{Command, Stdio}; | 5 | use std::process::{Command, Stdio}; |
| 5 | use std::sync::atomic::{AtomicU64, Ordering}; | 6 | use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; |
| 6 | use std::time::{Duration, Instant}; | 7 | use std::time::{Duration, Instant}; |
| 7 | 8 | ||
| 8 | use serde_json::Value; | 9 | use serde_json::Value; |
| 9 | 10 | ||
| 10 | const HEAD_BYTES: usize = 64 * 1024; | 11 | const HEAD_BYTES: usize = 64 * 1024; |
| 11 | const TAIL_BYTES: i64 = 16 * 1024; | 12 | const 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. | ||
| 15 | const MAX_OUTPUT_BYTES: u64 = 64 * 1024 * 1024; | ||
| 12 | static COUNTER: AtomicU64 = AtomicU64::new(0); | 16 | static COUNTER: AtomicU64 = AtomicU64::new(0); |
| 13 | 17 | ||
| 14 | pub fn bash(args: &Value, timeout: Duration) -> Result<String, String> { | 18 | pub 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. | ||
| 178 | fn kill_group(pid: i32) { | ||
| 179 | if pid > 0 { | ||
| 180 | unsafe { | ||
| 181 | libc::kill(-pid, libc::SIGKILL); | ||
| 182 | } | ||
| 183 | } | ||
| 184 | } | ||
diff --git a/tests/sessions.rs b/tests/sessions.rs index 8d17fc5..b445242 100644 --- a/tests/sessions.rs +++ b/tests/sessions.rs | |||
| @@ -35,6 +35,12 @@ fn sessions_create_list_and_replay() { | |||
| 35 | ) | 35 | ) |
| 36 | .unwrap(); | 36 | .unwrap(); |
| 37 | 37 | ||
| 38 | { | ||
| 39 | use std::os::unix::fs::PermissionsExt; | ||
| 40 | let mode = fs::metadata(alpha.path()).unwrap().permissions().mode() & 0o777; | ||
| 41 | assert_eq!(mode, 0o600, "sessions must not be group/world readable"); | ||
| 42 | } | ||
| 43 | |||
| 38 | assert!(session::exists("alpha")); | 44 | assert!(session::exists("alpha")); |
| 39 | assert!(!session::exists("nope")); | 45 | assert!(!session::exists("nope")); |
| 40 | 46 | ||
diff --git a/tests/tools.rs b/tests/tools.rs index 8463d8d..c30128e 100644 --- a/tests/tools.rs +++ b/tests/tools.rs | |||
| @@ -5,6 +5,11 @@ use std::time::Duration; | |||
| 5 | use serde_json::json; | 5 | use serde_json::json; |
| 6 | 6 | ||
| 7 | use agent686::tools::{self, shell}; | 7 | use agent686::tools::{self, shell}; |
| 8 | use std::sync::atomic::AtomicBool; | ||
| 9 | |||
| 10 | fn run(name: &str, args: &serde_json::Value) -> Result<String, String> { | ||
| 11 | tools::run(name, args, &AtomicBool::new(false)) | ||
| 12 | } | ||
| 8 | 13 | ||
| 9 | fn temp_dir(tag: &str) -> PathBuf { | 14 | fn temp_dir(tag: &str) -> PathBuf { |
| 10 | let dir = std::env::temp_dir().join(format!("agent686-test-{tag}-{}", std::process::id())); | 15 | let dir = std::env::temp_dir().join(format!("agent686-test-{tag}-{}", std::process::id())); |
| @@ -73,7 +78,7 @@ fn read_numbers_lines_and_reports_truncation() { | |||
| 73 | let path = dir.join("f.txt"); | 78 | let path = dir.join("f.txt"); |
| 74 | fs::write(&path, "one\ntwo\nthree\nfour\n").unwrap(); | 79 | fs::write(&path, "one\ntwo\nthree\nfour\n").unwrap(); |
| 75 | 80 | ||
| 76 | let text = tools::run("read", &json!({ "path": path, "limit": 2 })).unwrap(); | 81 | let text = run("read", &json!({ "path": path, "limit": 2 })).unwrap(); |
| 77 | assert!(text.contains(" 1\tone"), "{text}"); | 82 | assert!(text.contains(" 1\tone"), "{text}"); |
| 78 | assert!(text.contains(" 2\ttwo"), "{text}"); | 83 | assert!(text.contains(" 2\ttwo"), "{text}"); |
| 79 | assert!(text.contains("continue with offset=3"), "{text}"); | 84 | assert!(text.contains("continue with offset=3"), "{text}"); |
| @@ -86,10 +91,10 @@ fn grep_finds_lines_and_honours_case() { | |||
| 86 | let path = dir.join("f.txt"); | 91 | let path = dir.join("f.txt"); |
| 87 | fs::write(&path, "alpha\nbeta\nALPHA\n").unwrap(); | 92 | fs::write(&path, "alpha\nbeta\nALPHA\n").unwrap(); |
| 88 | 93 | ||
| 89 | let text = tools::run("grep", &json!({ "pattern": "alpha", "path": dir })).unwrap(); | 94 | let text = run("grep", &json!({ "pattern": "alpha", "path": dir })).unwrap(); |
| 90 | assert_eq!(text.lines().count(), 1, "{text}"); | 95 | assert_eq!(text.lines().count(), 1, "{text}"); |
| 91 | 96 | ||
| 92 | let text = tools::run( | 97 | let text = run( |
| 93 | "grep", | 98 | "grep", |
| 94 | &json!({ "pattern": "alpha", "path": dir, "ignore_case": true }), | 99 | &json!({ "pattern": "alpha", "path": dir, "ignore_case": true }), |
| 95 | ) | 100 | ) |
| @@ -106,30 +111,30 @@ fn glob_supports_double_star_and_bare_names() { | |||
| 106 | fs::write(dir.join("sub/deep/c.rs"), "").unwrap(); | 111 | fs::write(dir.join("sub/deep/c.rs"), "").unwrap(); |
| 107 | fs::write(dir.join("sub/note.txt"), "").unwrap(); | 112 | fs::write(dir.join("sub/note.txt"), "").unwrap(); |
| 108 | 113 | ||
| 109 | let text = tools::run("glob", &json!({ "pattern": "**/*.rs", "path": dir })).unwrap(); | 114 | let text = run("glob", &json!({ "pattern": "**/*.rs", "path": dir })).unwrap(); |
| 110 | assert_eq!(text.lines().count(), 3, "{text}"); | 115 | assert_eq!(text.lines().count(), 3, "{text}"); |
| 111 | 116 | ||
| 112 | let text = tools::run("glob", &json!({ "pattern": "*.rs", "path": dir })).unwrap(); | 117 | let text = run("glob", &json!({ "pattern": "*.rs", "path": dir })).unwrap(); |
| 113 | assert_eq!(text.lines().count(), 3, "{text}"); | 118 | assert_eq!(text.lines().count(), 3, "{text}"); |
| 114 | 119 | ||
| 115 | let text = tools::run("glob", &json!({ "pattern": "sub/*.rs", "path": dir })).unwrap(); | 120 | let text = run("glob", &json!({ "pattern": "sub/*.rs", "path": dir })).unwrap(); |
| 116 | assert_eq!(text.lines().count(), 1, "{text}"); | 121 | assert_eq!(text.lines().count(), 1, "{text}"); |
| 117 | assert!(text.contains("b.rs"), "{text}"); | 122 | assert!(text.contains("b.rs"), "{text}"); |
| 118 | } | 123 | } |
| 119 | 124 | ||
| 120 | #[test] | 125 | #[test] |
| 121 | fn bash_reports_exit_code_and_times_out() { | 126 | fn bash_reports_exit_code_and_times_out() { |
| 122 | let text = tools::run("bash", &json!({ "cmd": "echo hi; exit 3" })).unwrap(); | 127 | let text = run("bash", &json!({ "cmd": "echo hi; exit 3" })).unwrap(); |
| 123 | assert!(text.contains("hi"), "{text}"); | 128 | assert!(text.contains("hi"), "{text}"); |
| 124 | assert!(text.contains("[exit 3]"), "{text}"); | 129 | assert!(text.contains("[exit 3]"), "{text}"); |
| 125 | 130 | ||
| 126 | let text = shell::bash(&json!({ "cmd": "sleep 5" }), Duration::from_millis(150)).unwrap(); | 131 | let text = shell::bash(&json!({ "cmd": "sleep 5" }), Duration::from_millis(150), &AtomicBool::new(false)).unwrap(); |
| 127 | assert!(text.contains("timed out after"), "{text}"); | 132 | assert!(text.contains("timed out after"), "{text}"); |
| 128 | } | 133 | } |
| 129 | 134 | ||
| 130 | #[test] | 135 | #[test] |
| 131 | fn bash_rejects_a_missing_cwd() { | 136 | fn bash_rejects_a_missing_cwd() { |
| 132 | let error = tools::run("bash", &json!({ "cmd": "true", "cwd": "/nonexistent-dir-xyz" })) | 137 | let error = run("bash", &json!({ "cmd": "true", "cwd": "/nonexistent-dir-xyz" })) |
| 133 | .err() | 138 | .err() |
| 134 | .expect("missing cwd must fail"); | 139 | .expect("missing cwd must fail"); |
| 135 | assert!(error.contains("cwd is not a directory"), "{error}"); | 140 | assert!(error.contains("cwd is not a directory"), "{error}"); |
| @@ -137,7 +142,7 @@ fn bash_rejects_a_missing_cwd() { | |||
| 137 | 142 | ||
| 138 | #[test] | 143 | #[test] |
| 139 | fn unknown_tool_is_an_error_not_a_panic() { | 144 | fn unknown_tool_is_an_error_not_a_panic() { |
| 140 | let error = tools::run("teleport", &json!({})).err().unwrap(); | 145 | let error = run("teleport", &json!({})).err().unwrap(); |
| 141 | assert!(error.contains("unknown tool"), "{error}"); | 146 | assert!(error.contains("unknown tool"), "{error}"); |
| 142 | } | 147 | } |
| 143 | 148 | ||
| @@ -151,7 +156,7 @@ fn read_streams_large_files_and_reports_the_next_offset() { | |||
| 151 | } | 156 | } |
| 152 | fs::write(&path, body).unwrap(); | 157 | fs::write(&path, body).unwrap(); |
| 153 | 158 | ||
| 154 | let text = tools::run("read", &json!({ "path": path, "offset": 990, "limit": 5 })).unwrap(); | 159 | let text = run("read", &json!({ "path": path, "offset": 990, "limit": 5 })).unwrap(); |
| 155 | assert!(text.contains(" 990\tline 990"), "{text}"); | 160 | assert!(text.contains(" 990\tline 990"), "{text}"); |
| 156 | assert!(text.contains(" 994\tline 994"), "{text}"); | 161 | assert!(text.contains(" 994\tline 994"), "{text}"); |
| 157 | assert!(!text.contains("line 995"), "{text}"); | 162 | assert!(!text.contains("line 995"), "{text}"); |
| @@ -164,7 +169,7 @@ fn read_clips_a_single_enormous_line() { | |||
| 164 | let path = dir.join("one-line.txt"); | 169 | let path = dir.join("one-line.txt"); |
| 165 | fs::write(&path, "x".repeat(5 * 1024 * 1024)).unwrap(); | 170 | fs::write(&path, "x".repeat(5 * 1024 * 1024)).unwrap(); |
| 166 | 171 | ||
| 167 | let text = tools::run("read", &json!({ "path": path })).unwrap(); | 172 | let text = run("read", &json!({ "path": path })).unwrap(); |
| 168 | assert!(text.starts_with(" 1\tx"), "{text}"); | 173 | assert!(text.starts_with(" 1\tx"), "{text}"); |
| 169 | assert!(text.contains("line truncated"), "{text}"); | 174 | assert!(text.contains("line truncated"), "{text}"); |
| 170 | // Bounded by the per-line cap, not by the file size. | 175 | // Bounded by the per-line cap, not by the file size. |
| @@ -176,7 +181,7 @@ fn read_reports_an_offset_past_the_end() { | |||
| 176 | let dir = temp_dir("read-eof"); | 181 | let dir = temp_dir("read-eof"); |
| 177 | let path = dir.join("short.txt"); | 182 | let path = dir.join("short.txt"); |
| 178 | fs::write(&path, "only\n").unwrap(); | 183 | fs::write(&path, "only\n").unwrap(); |
| 179 | let text = tools::run("read", &json!({ "path": path, "offset": 9 })).unwrap(); | 184 | let text = run("read", &json!({ "path": path, "offset": 9 })).unwrap(); |
| 180 | assert!(text.contains("fewer than 9 lines"), "{text}"); | 185 | assert!(text.contains("fewer than 9 lines"), "{text}"); |
| 181 | } | 186 | } |
| 182 | 187 | ||
| @@ -185,10 +190,10 @@ fn read_refuses_binaries_and_directories() { | |||
| 185 | let dir = temp_dir("read-binary"); | 190 | let dir = temp_dir("read-binary"); |
| 186 | let binary = dir.join("blob.bin"); | 191 | let binary = dir.join("blob.bin"); |
| 187 | fs::write(&binary, [0u8, 1, 2, 3, 0, 9]).unwrap(); | 192 | fs::write(&binary, [0u8, 1, 2, 3, 0, 9]).unwrap(); |
| 188 | let error = tools::run("read", &json!({ "path": binary })).err().unwrap(); | 193 | let error = run("read", &json!({ "path": binary })).err().unwrap(); |
| 189 | assert!(error.contains("binary"), "{error}"); | 194 | assert!(error.contains("binary"), "{error}"); |
| 190 | 195 | ||
| 191 | let error = tools::run("read", &json!({ "path": dir })).err().unwrap(); | 196 | let error = run("read", &json!({ "path": dir })).err().unwrap(); |
| 192 | assert!(error.contains("is a directory"), "{error}"); | 197 | assert!(error.contains("is a directory"), "{error}"); |
| 193 | } | 198 | } |
| 194 | 199 | ||
| @@ -197,7 +202,7 @@ fn read_handles_a_missing_trailing_newline() { | |||
| 197 | let dir = temp_dir("read-no-newline"); | 202 | let dir = temp_dir("read-no-newline"); |
| 198 | let path = dir.join("f.txt"); | 203 | let path = dir.join("f.txt"); |
| 199 | fs::write(&path, "one\ntwo").unwrap(); | 204 | fs::write(&path, "one\ntwo").unwrap(); |
| 200 | let text = tools::run("read", &json!({ "path": path })).unwrap(); | 205 | let text = run("read", &json!({ "path": path })).unwrap(); |
| 201 | assert!(text.contains(" 2\ttwo"), "{text}"); | 206 | assert!(text.contains(" 2\ttwo"), "{text}"); |
| 202 | assert!(!text.contains("continue with offset"), "{text}"); | 207 | assert!(!text.contains("continue with offset"), "{text}"); |
| 203 | } | 208 | } |
| @@ -211,13 +216,13 @@ fn grep_uses_regular_expressions_by_default() { | |||
| 211 | ) | 216 | ) |
| 212 | .unwrap(); | 217 | .unwrap(); |
| 213 | 218 | ||
| 214 | let text = tools::run("grep", &json!({ "pattern": r"fn\s+main", "path": dir })).unwrap(); | 219 | let text = run("grep", &json!({ "pattern": r"fn\s+main", "path": dir })).unwrap(); |
| 215 | assert_eq!(text.lines().count(), 1, "{text}"); | 220 | assert_eq!(text.lines().count(), 1, "{text}"); |
| 216 | 221 | ||
| 217 | let text = tools::run("grep", &json!({ "pattern": r"fn\s+\w+", "path": dir })).unwrap(); | 222 | let text = run("grep", &json!({ "pattern": r"fn\s+\w+", "path": dir })).unwrap(); |
| 218 | assert_eq!(text.lines().count(), 2, "{text}"); | 223 | assert_eq!(text.lines().count(), 2, "{text}"); |
| 219 | 224 | ||
| 220 | let text = tools::run( | 225 | let text = run( |
| 221 | "grep", | 226 | "grep", |
| 222 | &json!({ "pattern": r"FN\s+MAIN", "path": dir, "ignore_case": true }), | 227 | &json!({ "pattern": r"FN\s+MAIN", "path": dir, "ignore_case": true }), |
| 223 | ) | 228 | ) |
| @@ -231,11 +236,11 @@ fn grep_fixed_matches_literally_and_bad_patterns_explain_themselves() { | |||
| 231 | fs::write(dir.join("f.txt"), "cost is a+b\nand ab\n").unwrap(); | 236 | fs::write(dir.join("f.txt"), "cost is a+b\nand ab\n").unwrap(); |
| 232 | 237 | ||
| 233 | // As a regex, `a+b` matches the "ab" on line 2, not the literal "a+b". | 238 | // As a regex, `a+b` matches the "ab" on line 2, not the literal "a+b". |
| 234 | let text = tools::run("grep", &json!({ "pattern": "a+b", "path": dir })).unwrap(); | 239 | let text = run("grep", &json!({ "pattern": "a+b", "path": dir })).unwrap(); |
| 235 | assert_eq!(text.lines().count(), 1, "{text}"); | 240 | assert_eq!(text.lines().count(), 1, "{text}"); |
| 236 | assert!(text.contains("and ab"), "{text}"); | 241 | assert!(text.contains("and ab"), "{text}"); |
| 237 | 242 | ||
| 238 | let text = tools::run( | 243 | let text = run( |
| 239 | "grep", | 244 | "grep", |
| 240 | &json!({ "pattern": "a+b", "path": dir, "fixed": true }), | 245 | &json!({ "pattern": "a+b", "path": dir, "fixed": true }), |
| 241 | ) | 246 | ) |
| @@ -243,9 +248,66 @@ fn grep_fixed_matches_literally_and_bad_patterns_explain_themselves() { | |||
| 243 | assert_eq!(text.lines().count(), 1, "{text}"); | 248 | assert_eq!(text.lines().count(), 1, "{text}"); |
| 244 | assert!(text.contains("cost is a+b"), "{text}"); | 249 | assert!(text.contains("cost is a+b"), "{text}"); |
| 245 | 250 | ||
| 246 | let error = tools::run("grep", &json!({ "pattern": "(", "path": dir })) | 251 | let error = run("grep", &json!({ "pattern": "(", "path": dir })) |
| 247 | .err() | 252 | .err() |
| 248 | .expect("invalid regex must fail"); | 253 | .expect("invalid regex must fail"); |
| 249 | assert!(error.contains("invalid regex"), "{error}"); | 254 | assert!(error.contains("invalid regex"), "{error}"); |
| 250 | assert!(error.contains("fixed"), "{error}"); | 255 | assert!(error.contains("fixed"), "{error}"); |
| 251 | } | 256 | } |
| 257 | |||
| 258 | fn running(pid: i32) -> bool { | ||
| 259 | // A zombie has already exited; anything but Z means still alive. | ||
| 260 | match fs::read_to_string(format!("/proc/{pid}/stat")) { | ||
| 261 | Ok(stat) => stat | ||
| 262 | .rsplit(')') | ||
| 263 | .next() | ||
| 264 | .and_then(|rest| rest.split_whitespace().next()) | ||
| 265 | .map(|state| state != "Z") | ||
| 266 | .unwrap_or(false), | ||
| 267 | Err(_) => false, | ||
| 268 | } | ||
| 269 | } | ||
| 270 | |||
| 271 | #[test] | ||
| 272 | fn bash_timeout_kills_the_whole_process_group() { | ||
| 273 | let dir = temp_dir("bash-group"); | ||
| 274 | let pidfile = dir.join("pid"); | ||
| 275 | let cmd = format!("sleep 30 & echo $! > {}; wait", pidfile.display()); | ||
| 276 | |||
| 277 | let text = shell::bash( | ||
| 278 | &json!({ "cmd": cmd }), | ||
| 279 | Duration::from_millis(300), | ||
| 280 | &AtomicBool::new(false), | ||
| 281 | ) | ||
| 282 | .unwrap(); | ||
| 283 | assert!(text.contains("timed out"), "{text}"); | ||
| 284 | |||
| 285 | std::thread::sleep(Duration::from_millis(300)); | ||
| 286 | let pid: i32 = fs::read_to_string(&pidfile).unwrap().trim().parse().unwrap(); | ||
| 287 | assert!(!running(pid), "grandchild {pid} survived the timeout"); | ||
| 288 | } | ||
| 289 | |||
| 290 | #[test] | ||
| 291 | fn bash_stops_promptly_when_the_turn_is_cancelled() { | ||
| 292 | let started = std::time::Instant::now(); | ||
| 293 | let text = shell::bash( | ||
| 294 | &json!({ "cmd": "sleep 30" }), | ||
| 295 | Duration::from_secs(20), | ||
| 296 | &AtomicBool::new(true), | ||
| 297 | ) | ||
| 298 | .unwrap(); | ||
| 299 | assert!(text.contains("aborted by the user"), "{text}"); | ||
| 300 | assert!(started.elapsed() < Duration::from_secs(2)); | ||
| 301 | } | ||
| 302 | |||
| 303 | #[test] | ||
| 304 | fn bash_does_not_inherit_the_api_key() { | ||
| 305 | std::env::set_var("OPENCODE_API_KEY", "do-not-leak-me"); | ||
| 306 | let text = run( | ||
| 307 | "bash", | ||
| 308 | &json!({ "cmd": "env | grep -c '^OPENCODE_API_KEY=' || true" }), | ||
| 309 | ) | ||
| 310 | .unwrap(); | ||
| 311 | std::env::remove_var("OPENCODE_API_KEY"); | ||
| 312 | assert!(text.contains('0'), "the key was visible to the child: {text}"); | ||
| 313 | } | ||
