From 8e7c0bb89a4a3310f6f589875f1de16f08dbed90 Mon Sep 17 00:00:00 2001 From: hermes Date: Mon, 12 Oct 2026 16:09:40 +0000 Subject: [PATCH 1/2] Optional sandbox for bash, LSP servers and lens/test runners (bwrap, seatbelt) --- README.md | 11 + crates/hx-cli/src/config.sample.toml | 11 + crates/hx-cli/src/main.rs | 17 + crates/hx-core/src/lib.rs | 1 + crates/hx-core/src/sandbox.rs | 511 +++++++++++++++++++++++++++ crates/hx-lens/src/lsp.rs | 5 +- crates/hx-lens/src/runners.rs | 17 +- crates/hx-lens/src/testrun.rs | 12 +- crates/hx-tools/src/lib.rs | 11 +- tests/all.sh | 1 + tests/sandbox_e2e.sh | 6 + 11 files changed, 586 insertions(+), 17 deletions(-) create mode 100644 crates/hx-core/src/sandbox.rs create mode 100644 tests/sandbox_e2e.sh diff --git a/README.md b/README.md index 0ff6a8d..25c17e1 100644 --- a/README.md +++ b/README.md @@ -55,6 +55,17 @@ max_tokens = 16384 # explore_model = "claude-haiku-4-5" # model for read-only `task` subagents; default: cheapest tier of the provider # system_prompt = "..." # replaces built-in prompt; AGENTS.md still appended +## Sandbox: bash, LSP servers, lens and test runners run under bwrap (Linux) / sandbox-exec (macOS). +## Project dir + /tmp writable, $HOME hidden except `ro`/`rw`, filtered env (no API keys/tokens), no network. +## File tools (read/write/edit) obey the same paths. mode = "on" without a working backend refuses to start. +# [sandbox] +# mode = "off" # off | on (CLI: --sandbox / --no-sandbox) +# backend = "auto" # auto | bwrap | seatbelt +# network = false +# rw = ["~/.cargo/registry", "~/.cargo/git"] # extra writable paths +# ro = ["~/.cargo", "~/.rustup", "~/.local", "~/.nvm", "~/.npm"] # readable parts of $HOME +# env_allow = ["PATH", "HOME", "TERM", "LC_*", "CARGO_*"] # trailing * = prefix + [lsp] mode = "turn_end" # turn_end | agent_end | off disable = ["clangd"] diff --git a/crates/hx-cli/src/config.sample.toml b/crates/hx-cli/src/config.sample.toml index 01131b0..d164c41 100644 --- a/crates/hx-cli/src/config.sample.toml +++ b/crates/hx-cli/src/config.sample.toml @@ -14,6 +14,17 @@ # codemode = false # `codemode` tool: JS scripts that call other tools in a sandbox # system_prompt = "..." # replaces the built-in prompt; AGENTS.md is still appended +## Sandbox: bash, LSP servers, lens and test runners run under bwrap (Linux) / sandbox-exec (macOS). +## Project dir + /tmp writable, $HOME hidden except `ro`/`rw`, filtered env (no API keys/tokens), no network. +## File tools (read/write/edit) obey the same paths. mode = "on" without a working backend refuses to start. +# [sandbox] +# mode = "off" # off | on (CLI: --sandbox / --no-sandbox) +# backend = "auto" # auto | bwrap | seatbelt +# network = false +# rw = ["~/.cargo/registry", "~/.cargo/git"] # extra writable paths +# ro = ["~/.cargo", "~/.rustup", "~/.local", "~/.nvm", "~/.npm"] # readable parts of $HOME +# env_allow = ["PATH", "HOME", "TERM", "LC_*", "CARGO_*"] # trailing * = prefix + ## OpenAI-compatible endpoint (Ollama, vLLM, LM Studio, OpenRouter), used with provider = "custom". # [openai_compat] # base_url = "http://localhost:11434/v1" diff --git a/crates/hx-cli/src/main.rs b/crates/hx-cli/src/main.rs index c9a3793..a6ece04 100644 --- a/crates/hx-cli/src/main.rs +++ b/crates/hx-cli/src/main.rs @@ -39,6 +39,12 @@ struct Cli { /// Skip permission prompts for bash/write/edit (also `permissions = "yolo"` in config.toml). #[arg(long)] yolo: bool, + /// Run bash, LSP servers and lens runners in a sandbox (bwrap / seatbelt). + #[arg(long, conflicts_with = "no_sandbox")] + sandbox: bool, + /// Force the sandbox off (overrides config). + #[arg(long)] + no_sandbox: bool, /// Output mode: text (default for -p), json (NDJSON events on stdout; needs -p), rpc (JSON-RPC on stdio). #[arg(long, value_enum, default_value_t = Mode::Text)] mode: Mode, @@ -129,6 +135,8 @@ struct Config { permissions: Option, /// Replaces the built-in system prompt (AGENTS.md etc. are still appended). system_prompt: Option, + /// confine child processes: mode = "on", backend, network, rw, ro, env_allow + sandbox: Option, lsp: Option, /// subprocess extensions (JSON-RPC over stdio); global and project lists are concatenated extensions: Vec, @@ -177,6 +185,7 @@ impl Config { remember_model: o.remember_model.or(c.remember_model), permissions: o.permissions.or(c.permissions), system_prompt: o.system_prompt.or(c.system_prompt), + sandbox: o.sandbox.or(c.sandbox), lsp: o.lsp.or(c.lsp), extensions: [c.extensions, o.extensions].concat(), }; @@ -574,6 +583,14 @@ async fn main() -> Result<()> { let cwd = std::env::current_dir()?; let cfg = Config::load(&cwd)?; trace("config"); + let mut sb = cfg.sandbox.clone().unwrap_or_default(); + if cli.sandbox { + sb.mode = hx_core::sandbox::Mode::On; + } + if cli.no_sandbox { + sb.mode = hx_core::sandbox::Mode::Off; + } + hx_core::sandbox::init(&sb, &cwd).map_err(anyhow::Error::msg)?; if let Some(oc) = cfg.openai_compat.clone() { let _ = COMPAT.set(oc); } diff --git a/crates/hx-core/src/lib.rs b/crates/hx-core/src/lib.rs index 496195b..0fd8c7a 100644 --- a/crates/hx-core/src/lib.rs +++ b/crates/hx-core/src/lib.rs @@ -11,6 +11,7 @@ mod mask; pub mod memory; pub mod nudge; pub mod permit; +pub mod sandbox; pub mod session; pub mod stats; pub mod subagent; diff --git a/crates/hx-core/src/sandbox.rs b/crates/hx-core/src/sandbox.rs new file mode 100644 index 0000000..336df4d --- /dev/null +++ b/crates/hx-core/src/sandbox.rs @@ -0,0 +1,511 @@ +//! Optional sandbox for child processes (bash, LSP servers, lens runners, test runners). +//! +//! Every sandboxed spawn goes through [`command`], a drop-in for `Command::new`. With the sandbox +//! off it is a plain `Command::new`; on, it returns a command that runs the program under +//! `bwrap` (Linux) or `sandbox-exec` (macOS): filesystem read-only except the project dir and +//! `rw`, `$HOME` hidden except `ro`/`rw`, no network unless `network`, environment filtered. +//! The hx process itself (LLM API, OAuth tokens) stays outside. File tools call [`guard_read`] / +//! [`guard_write`] because they run in-process. +//! +//! ponytail: one policy for all children, no per-call network opt-in; add when a tool needs it. + +use std::ffi::OsStr; +use std::path::{Path, PathBuf}; +use std::sync::OnceLock; + +#[derive(Default, Clone, Copy, PartialEq, Eq, Debug, serde::Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Mode { + #[default] + Off, + On, +} + +#[derive(Default, Clone, Copy, PartialEq, Eq, Debug, serde::Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Backend { + #[default] + Auto, + Bwrap, + Seatbelt, +} + +#[derive(Clone, Debug, serde::Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct Cfg { + /// off (default) | on + pub mode: Mode, + /// auto (default) | bwrap | seatbelt + pub backend: Backend, + /// network for sandboxed children (default false) + pub network: bool, + /// extra writable paths (the project dir is always writable); `~` expands + pub rw: Vec, + /// extra readable paths under `$HOME` (which is otherwise hidden); `~` expands + pub ro: Vec, + /// env vars passed to children; a trailing `*` matches a prefix + pub env_allow: Vec, +} + +impl Default for Cfg { + fn default() -> Self { + let s = |v: &[&str]| v.iter().map(|s| s.to_string()).collect(); + Cfg { + mode: Mode::Off, + backend: Backend::Auto, + network: false, + rw: s(&["~/.cargo/registry", "~/.cargo/git"]), + ro: s(&[ + "~/.cargo", + "~/.rustup", + "~/.local", + "~/.nvm", + "~/.npm", + "~/.pyenv", + "~/.gitconfig", + "~/.config/git", + ]), + env_allow: s(&[ + "PATH", + "HOME", + "USER", + "LOGNAME", + "SHELL", + "TERM", + "LANG", + "LC_*", + "TMPDIR", + "CARGO_*", + "RUST*", + "NIX_*", + "NODE_PATH", + "GOPATH", + "GOROOT", + "VIRTUAL_ENV", + ]), + } + } +} + +#[derive(Debug)] +pub struct Sandbox { + backend: Backend, + network: bool, + home: PathBuf, + cwd: PathBuf, + rw: Vec, + ro: Vec, + env_allow: Vec, +} + +static SANDBOX: OnceLock> = OnceLock::new(); + +/// Call once at startup. Errors (never silently falls back) if `mode = on` and no backend works. +pub fn init(cfg: &Cfg, cwd: &Path) -> Result<(), String> { + let sb = if cfg.mode == Mode::On { + Some(Sandbox::new(cfg, cwd)?) + } else { + None + }; + SANDBOX + .set(sb) + .map_err(|_| "sandbox already initialised".into()) +} + +pub fn active() -> Option<&'static Sandbox> { + SANDBOX.get().and_then(Option::as_ref) +} + +/// Drop-in for `tokio::process::Command::new` that applies the sandbox when it is on. +pub fn command(program: impl AsRef) -> tokio::process::Command { + match active() { + Some(sb) => sb.command(program.as_ref()), + None => tokio::process::Command::new(program), + } +} + +/// Error if the file tools may not read `p`. +pub fn guard_read(p: &Path) -> Result<(), String> { + active().map_or(Ok(()), |sb| sb.guard_read(p)) +} + +/// Error if the file tools may not write `p`. +pub fn guard_write(p: &Path) -> Result<(), String> { + active().map_or(Ok(()), |sb| sb.guard_write(p)) +} + +fn expand(home: &Path, s: &str) -> PathBuf { + match s.strip_prefix("~/") { + Some(r) => home.join(r), + None if s == "~" => home.to_path_buf(), + None => PathBuf::from(s), + } +} + +/// Canonical path of `p`, or of its nearest existing ancestor plus the rest (for new files). +fn canon(p: &Path) -> PathBuf { + // lexical `..`/`.` removal first, so a non-existent prefix cannot hide an escape + let mut norm = PathBuf::new(); + for c in p.components() { + match c { + std::path::Component::ParentDir => { + norm.pop(); + } + std::path::Component::CurDir => {} + c => norm.push(c), + } + } + let p = norm.as_path(); + let mut rest = vec![]; + let mut cur = p; + loop { + if let Ok(c) = cur.canonicalize() { + return rest.iter().rev().fold(c, |a, s| a.join(s)); + } + match (cur.parent(), cur.file_name()) { + (Some(par), Some(n)) => { + rest.push(n.to_owned()); + cur = par; + } + _ => return p.to_path_buf(), + } + } +} + +/// Probe: can this backend run `true` with a read-only root? +fn probe(b: Backend) -> Result<(), String> { + let (bin, args): (&str, Vec) = match b { + Backend::Bwrap => ( + "bwrap", + [ + "--ro-bind", + "/", + "/", + "--dev", + "/dev", + "--unshare-all", + "--", + "true", + ] + .map(String::from) + .into(), + ), + _ => ( + "sandbox-exec", + ["-p", "(version 1)(allow default)", "true"] + .map(String::from) + .into(), + ), + }; + match std::process::Command::new(bin).args(&args).output() { + Ok(o) if o.status.success() => Ok(()), + Ok(o) => Err(format!( + "`{bin}` cannot create a sandbox here: {}", + String::from_utf8_lossy(&o.stderr).trim() + )), + Err(e) => Err(format!("`{bin}` not usable: {e}")), + } +} + +impl Sandbox { + fn new(cfg: &Cfg, cwd: &Path) -> Result { + let backend = match cfg.backend { + Backend::Auto if cfg!(target_os = "macos") => Backend::Seatbelt, + Backend::Auto => Backend::Bwrap, + b => b, + }; + probe(backend).map_err(|e| { + format!("sandbox = on but {e}. Install bubblewrap (Linux), or set sandbox mode = \"off\" / pass --no-sandbox.") + })?; + let home: PathBuf = std::env::var_os("HOME").map(Into::into).unwrap_or_default(); + let paths = |v: &[String]| -> Vec { + v.iter() + .map(|s| expand(&home, s)) + .filter(|p| p.exists()) + .map(|p| canon(&p)) + .collect() + }; + let mut ro = paths(&cfg.ro); + let skills = crate::context::hx_home().join("skills"); + if skills.exists() { + ro.push(canon(&skills)); + } + Ok(Sandbox { + backend, + network: cfg.network, + home: canon(&home), + cwd: canon(cwd), + rw: paths(&cfg.rw), + ro, + env_allow: cfg.env_allow.clone(), + }) + } + + pub fn describe(&self) -> String { + format!( + "{}, network {}", + match self.backend { + Backend::Seatbelt => "seatbelt", + _ => "bwrap", + }, + if self.network { "on" } else { "off" } + ) + } + + fn tmp_dirs() -> Vec { + let mut v = vec![canon(Path::new("/tmp"))]; + v.push(canon(&std::env::temp_dir())); + v.dedup(); + v + } + + fn writable(&self) -> Vec { + let mut v = vec![self.cwd.clone()]; + v.extend(self.rw.iter().cloned()); + v.extend(Self::tmp_dirs()); + v + } + + fn guard_write(&self, p: &Path) -> Result<(), String> { + let c = canon(p); + if self.writable().iter().any(|w| c.starts_with(w)) { + return Ok(()); + } + Err(format!( + "sandbox: {} is outside the writable paths (project dir, /tmp, sandbox.rw)", + p.display() + )) + } + + fn guard_read(&self, p: &Path) -> Result<(), String> { + let c = canon(p); + let hidden = c.starts_with(&self.home); + if !hidden + || self + .writable() + .iter() + .chain(self.ro.iter()) + .any(|w| c.starts_with(w)) + { + return Ok(()); + } + Err(format!( + "sandbox: {} is hidden (under $HOME, not in sandbox.ro/rw)", + p.display() + )) + } + + fn env_ok(&self, k: &str) -> bool { + self.env_allow.iter().any(|a| match a.strip_suffix('*') { + Some(pre) => k.starts_with(pre), + None => a == k, + }) + } + + fn command(&self, program: &OsStr) -> tokio::process::Command { + let (bin, args) = match self.backend { + Backend::Seatbelt => ("sandbox-exec", vec!["-p".into(), self.seatbelt_profile()]), + _ => { + let mut a = self.bwrap_args(); + a.push("--".into()); + ("bwrap", a) + } + }; + let mut c = tokio::process::Command::new(bin); + c.args(&args).arg(program).env_clear(); + for (k, v) in std::env::vars_os() { + if k.to_str().is_some_and(|k| self.env_ok(k)) { + c.env(k, v); + } + } + c + } + + fn bwrap_args(&self) -> Vec { + let s = |p: &Path| p.to_string_lossy().into_owned(); + let mut a: Vec = [ + "--ro-bind", + "/", + "/", + "--dev", + "/dev", + "--proc", + "/proc", + "--unshare-pid", + "--unshare-ipc", + "--unshare-uts", + "--die-with-parent", + "--new-session", + ] + .map(String::from) + .into(); + a.push( + if self.network { + "--share-net" + } else { + "--unshare-net" + } + .into(), + ); + // hide $HOME and /tmp, then bring back what is allowed (later mounts win) + for t in Self::tmp_dirs() { + a.extend(["--tmpfs".into(), s(&t)]); + } + if self.home != Path::new("/") && !self.home.as_os_str().is_empty() { + a.extend(["--tmpfs".into(), s(&self.home)]); + } + for p in &self.ro { + a.extend(["--ro-bind".into(), s(p), s(p)]); + } + for p in self.rw.iter().chain([&self.cwd]) { + a.extend(["--bind".into(), s(p), s(p)]); + } + a + } + + fn seatbelt_profile(&self) -> String { + let q = |p: &Path| { + format!( + "(subpath \"{}\")", + p.to_string_lossy() + .replace('\\', "\\\\") + .replace('"', "\\\"") + ) + }; + let list = |v: &[PathBuf]| v.iter().map(|p| q(p)).collect::>().join(" "); + let mut p = String::from( + "(version 1)\n(deny default)\n(allow process-exec)\n(allow process-fork)\n\ + (allow signal (target self))\n(allow sysctl-read)\n(allow mach-lookup)\n\ + (allow ipc-posix-shm)\n(allow file-read*)\n", + ); + // last matching rule wins: hide $HOME, then re-allow + p += &format!("(deny file-read* {})\n", q(&self.home)); + let w = self.writable(); + let readable: Vec = w.iter().chain(self.ro.iter()).cloned().collect(); + p += &format!("(allow file-read* {})\n", list(&readable)); + p += &format!("(allow file-write* {})\n", list(&w)); + p += "(allow file-write* (literal \"/dev/null\") (literal \"/dev/tty\"))\n"; + if self.network { + p += "(allow network*)\n"; + } + p + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn sb(backend: Backend, network: bool) -> Sandbox { + Sandbox { + backend, + network, + home: "/home/u".into(), + cwd: "/home/u/proj".into(), + rw: vec!["/home/u/.cargo/registry".into()], + ro: vec!["/home/u/.cargo".into()], + env_allow: vec!["PATH".into(), "LC_*".into()], + } + } + + #[test] + fn bwrap_hides_home_then_rebinds() { + let a = sb(Backend::Bwrap, false).bwrap_args().join(" "); + assert!(a.contains("--unshare-net") && !a.contains("--share-net")); + let tmpfs = a.find("--tmpfs /home/u").unwrap(); + let bind = a.find("--bind /home/u/proj /home/u/proj").unwrap(); + assert!( + tmpfs < bind, + "home must be hidden before the project is bound" + ); + assert!( + sb(Backend::Bwrap, true) + .bwrap_args() + .join(" ") + .contains("--share-net") + ); + } + + #[test] + fn seatbelt_profile_rules() { + let p = sb(Backend::Seatbelt, false).seatbelt_profile(); + assert!(p.contains("(deny default)") && !p.contains("network")); + assert!( + p.find("(deny file-read* (subpath \"/home/u\"))").unwrap() + < p.find("(allow file-read* (subpath \"/home/u/proj\"") + .unwrap() + ); + assert!(p.contains("(allow file-write* (subpath \"/home/u/proj\")")); + assert!( + sb(Backend::Seatbelt, true) + .seatbelt_profile() + .contains("(allow network*)") + ); + } + + #[test] + fn guards() { + let s = sb(Backend::Bwrap, false); + assert!(s.guard_write(Path::new("/home/u/proj/new/a.rs")).is_ok()); + assert!(s.guard_write(Path::new("/home/u/.ssh/x")).is_err()); + assert!(s.guard_write(Path::new("/home/u/proj/../.bashrc")).is_err()); + assert!(s.guard_read(Path::new("/home/u/.ssh/id_rsa")).is_err()); + assert!( + s.guard_read(Path::new("/home/u/.cargo/config.toml")) + .is_ok() + ); + assert!(s.guard_read(Path::new("/etc/hosts")).is_ok()); + } + + #[test] + fn env_filter() { + let s = sb(Backend::Bwrap, false); + assert!(s.env_ok("PATH") && s.env_ok("LC_ALL")); + assert!(!s.env_ok("ANTHROPIC_API_KEY") && !s.env_ok("PATHX")); + } + + /// Real confinement; skipped where no backend works (CI without user namespaces). + #[tokio::test] + async fn confines() { + let b = if cfg!(target_os = "macos") { + Backend::Seatbelt + } else { + Backend::Bwrap + }; + let proj = tempfile::tempdir().unwrap(); + let cfg = Cfg { + mode: Mode::On, + backend: b, + rw: vec![], + ro: vec![], + ..Cfg::default() + }; + let Ok(sb) = Sandbox::new(&cfg, proj.path()) else { + eprintln!("skipped: no sandbox backend"); + return; + }; + let home = sb.home.clone(); + let run = |script: String| { + let mut c = sb.command(OsStr::new("sh")); + c.arg("-c").arg(script).current_dir(&sb.cwd); + async move { c.output().await.unwrap() } + }; + assert!( + run("touch ok.txt".into()).await.status.success(), + "project dir writable" + ); + assert!(sb.cwd.join("ok.txt").exists()); + let probe = home.join(".hx-sandbox-probe"); + assert!( + !run(format!("touch {}", probe.display())) + .await + .status + .success() + ); + assert!(!probe.exists(), "HOME must be read-only/hidden"); + // cargo sets CARGO_MANIFEST_DIR for tests; with env_allow = [PATH] it must not leak + assert!(std::env::var_os("CARGO_MANIFEST_DIR").is_some()); + let o = run("echo ${CARGO_MANIFEST_DIR:-unset}".into()).await; + assert_eq!(String::from_utf8_lossy(&o.stdout).trim(), "unset"); + } +} diff --git a/crates/hx-lens/src/lsp.rs b/crates/hx-lens/src/lsp.rs index 6569af8..6c32283 100644 --- a/crates/hx-lens/src/lsp.rs +++ b/crates/hx-lens/src/lsp.rs @@ -1,5 +1,6 @@ //! Minimal LSP JSON-RPC client over stdio. +use hx_core::sandbox::command as sandboxed; use serde_json::{Value, json}; use std::collections::HashMap; use std::path::{Path, PathBuf}; @@ -8,7 +9,7 @@ use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicI64, Ordering}; use std::time::{Duration, Instant}; use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader}; -use tokio::process::{Child, ChildStdin, Command}; +use tokio::process::{Child, ChildStdin}; use tokio::sync::{Mutex, Notify, mpsc, oneshot}; #[derive(Debug, Clone, PartialEq)] @@ -230,7 +231,7 @@ impl Client { root: &Path, init_options: Value, ) -> std::io::Result> { - let mut c = Command::new(&cmd[0]); + let mut c = sandboxed(&cmd[0]); c.args(&cmd[1..]) .current_dir(root) .stdin(Stdio::piped()) diff --git a/crates/hx-lens/src/runners.rs b/crates/hx-lens/src/runners.rs index 4de6ebc..a4fd200 100644 --- a/crates/hx-lens/src/runners.rs +++ b/crates/hx-lens/src/runners.rs @@ -3,6 +3,7 @@ //! All runners report `Finding`s; the dispatcher runs the applicable ones in parallel with a timeout. use crate::manager::which; +use hx_core::sandbox::command as sandboxed; use serde_json::Value; use std::path::{Path, PathBuf}; use std::time::{Duration, Instant}; @@ -204,7 +205,7 @@ pub async fn run(r: &Runner, root: &Path, files: &[PathBuf], timeout: Duration) "eslint" => eslint(root, files, timeout).await, "ast-grep" => ast_grep(root, files, timeout).await, "rustfmt" => exec( - Command::new("rustfmt") + sandboxed("rustfmt") .args(["--edition", "2024"]) .args(files) .current_dir(root), @@ -213,7 +214,7 @@ pub async fn run(r: &Runner, root: &Path, files: &[PathBuf], timeout: Duration) .await .map(|_| vec![]), "ruff-format" => exec( - Command::new("ruff") + sandboxed("ruff") .args(["format", "--quiet"]) .args(files) .current_dir(root), @@ -222,7 +223,7 @@ pub async fn run(r: &Runner, root: &Path, files: &[PathBuf], timeout: Duration) .await .map(|_| vec![]), "biome-format" => exec( - Command::new("biome") + sandboxed("biome") .args(["format", "--write"]) .args(files) .current_dir(root), @@ -248,7 +249,7 @@ pub async fn run(r: &Runner, root: &Path, files: &[PathBuf], timeout: Duration) /// clippy checks the whole crate; `run` filters to changed files. async fn clippy(root: &Path, timeout: Duration) -> Result, String> { let (o, _) = exec( - Command::new("cargo") + sandboxed("cargo") .args([ "clippy", "--quiet", @@ -299,7 +300,7 @@ async fn clippy(root: &Path, timeout: Duration) -> Result, String> async fn ruff(root: &Path, files: &[PathBuf], timeout: Duration) -> Result, String> { let (o, _) = exec( - Command::new("ruff") + sandboxed("ruff") .args(["check", "--output-format=json", "--no-fix", "--quiet"]) .args(files) .current_dir(root), @@ -327,7 +328,7 @@ async fn ruff(root: &Path, files: &[PathBuf], timeout: Duration) -> Result Result, String> { let (o, _) = exec( - Command::new("biome") + sandboxed("biome") .args(["lint", "--reporter=json"]) .args(files) .current_dir(root), @@ -360,7 +361,7 @@ async fn biome(root: &Path, files: &[PathBuf], timeout: Duration) -> Result Result, String> { let (o, _) = exec( - Command::new("eslint") + sandboxed("eslint") .args(["--format", "json"]) .args(files) .current_dir(root), @@ -412,7 +413,7 @@ async fn ast_grep( return Ok(vec![]); } let (o, _) = exec( - Command::new("ast-grep") + sandboxed("ast-grep") .args(["scan", "--json=compact", "--inline-rules"]) .arg(rules.join("\n---\n")) .args(files) diff --git a/crates/hx-lens/src/testrun.rs b/crates/hx-lens/src/testrun.rs index a1e5699..1c48720 100644 --- a/crates/hx-lens/src/testrun.rs +++ b/crates/hx-lens/src/testrun.rs @@ -4,11 +4,11 @@ use crate::manager::which; use crate::runners::marker_root; +use hx_core::sandbox::command as sandboxed; use serde_json::Value; use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::time::Duration; -use tokio::process::Command; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum Adapter { @@ -120,33 +120,33 @@ pub async fn run(r: &Run, timeout: Duration) -> Result { }; let mut cmd = match r.adapter { Adapter::Cargo => { - let mut c = Command::new("cargo"); + let mut c = sandboxed("cargo"); c.args(["test", "--no-fail-fast", "--color", "never"]); c } Adapter::Pytest => { - let mut c = Command::new("pytest"); + let mut c = sandboxed("pytest"); c.args(["-q", "-p", "no:cacheprovider", "--junitxml"]) .arg(&tmp) .args(&r.targets); c } Adapter::Vitest => { - let mut c = Command::new(bin("vitest")); + let mut c = sandboxed(bin("vitest")); c.args(["run", "--reporter=json", "--outputFile"]) .arg(&tmp) .args(&r.targets); c } Adapter::Jest => { - let mut c = Command::new(bin("jest")); + let mut c = sandboxed(bin("jest")); c.args(["--json", "--outputFile"]) .arg(&tmp) .args(&r.targets); c } Adapter::Go => { - let mut c = Command::new("go"); + let mut c = sandboxed("go"); c.args(["test", "-json"]); c.args(r.targets.iter().map(|d| { let rel = d.strip_prefix(&r.root).unwrap_or(d); diff --git a/crates/hx-tools/src/lib.rs b/crates/hx-tools/src/lib.rs index 735a669..223b7ea 100644 --- a/crates/hx-tools/src/lib.rs +++ b/crates/hx-tools/src/lib.rs @@ -87,6 +87,9 @@ impl Tool for Read { } async fn call(&self, a: Value, cx: &ToolCtx) -> ToolResult { let p = resolve(cx, a["path"].as_str().unwrap_or_default()); + if let Err(e) = hx_core::sandbox::guard_read(&p) { + return ToolResult::err(e); + } let bytes = match tokio::fs::read(&p).await { Ok(b) => b, Err(e) => return ToolResult::err(format!("{}: {e}", p.display())), @@ -161,6 +164,9 @@ impl Tool for Write { } async fn call(&self, a: Value, cx: &ToolCtx) -> ToolResult { let p = resolve(cx, a["path"].as_str().unwrap_or_default()); + if let Err(e) = hx_core::sandbox::guard_write(&p) { + return ToolResult::err(e); + } let c = a["content"].as_str().unwrap_or_default(); if p.exists() && !cx.state.is_fresh(&p) { return ToolResult::err(format!( @@ -206,6 +212,9 @@ impl Tool for Edit { } async fn call(&self, a: Value, cx: &ToolCtx) -> ToolResult { let p = resolve(cx, a["path"].as_str().unwrap_or_default()); + if let Err(e) = hx_core::sandbox::guard_write(&p) { + return ToolResult::err(e); + } let (old, new) = ( a["old_string"].as_str().unwrap_or_default(), a["new_string"].as_str().unwrap_or_default(), @@ -333,7 +342,7 @@ impl Tool for Bash { async fn call(&self, a: Value, cx: &ToolCtx) -> ToolResult { let cmd = a["command"].as_str().unwrap_or_default(); let secs = a["timeout"].as_u64().unwrap_or(120).clamp(1, 3600); - let mut c = tokio::process::Command::new("bash"); + let mut c = hx_core::sandbox::command("bash"); c.arg("-c") .arg(format!("exec 2>&1; {cmd}")) .current_dir(&cx.cwd) diff --git a/tests/all.sh b/tests/all.sh index 5de4b6e..b7b7fb9 100755 --- a/tests/all.sh +++ b/tests/all.sh @@ -20,3 +20,4 @@ sh tests/m6_e2e.sh python3 tests/tui_lspinstall.py | grep -q FAIL && { echo "tui lsp install FAIL"; exit 1; } || echo "tui lsp install ok" sh tests/m7_e2e.sh sh tests/m8_e2e.sh +sh tests/sandbox_e2e.sh diff --git a/tests/sandbox_e2e.sh b/tests/sandbox_e2e.sh new file mode 100644 index 0000000..4ba7e43 --- /dev/null +++ b/tests/sandbox_e2e.sh @@ -0,0 +1,6 @@ +#!/bin/sh +# Sandbox: no raw child spawns outside the chokepoint (real confinement is tested in hx-core sandbox::tests::confines). +cd "$(dirname "$0")/.." +bad=$(grep -rn "Command::new" crates/hx-lens/src crates/hx-tools/src --include=*.rs | grep -v "tests\?\.rs\|manager.rs\|cargo\|stty\|\"kill\"") +[ -z "$bad" ] || { echo "sandbox e2e FAIL: raw spawn: $bad"; exit 1; } +echo "sandbox e2e ok" From 1a027512e81e7c7d5618c3be31150bbd3144f785 Mon Sep 17 00:00:00 2001 From: hermes Date: Mon, 12 Oct 2026 21:32:45 +0000 Subject: [PATCH 2/2] agent: retry empty replies once, never store them, then fail visibly --- crates/hx-core/src/agent.rs | 52 +++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/crates/hx-core/src/agent.rs b/crates/hx-core/src/agent.rs index 3b97466..b90e1c2 100644 --- a/crates/hx-core/src/agent.rs +++ b/crates/hx-core/src/agent.rs @@ -72,6 +72,10 @@ pub enum Error { Aborted, #[error("stream ended without Done")] Truncated, + #[error( + "empty reply from the provider (stop: {0:?}), also on retry; try /compact or /model, or lower the effort" + )] + EmptyReply(StopReason), #[error("max turns ({0}) reached")] MaxTurns(u32), } @@ -351,6 +355,7 @@ impl Agent { async fn run_inner(&mut self, prompt: String) -> Result { self.push(Message::user(prompt))?; + let mut empty_retries = 0; for _ in 0..self.max_turns { if self.aborted() { return Err(Error::Aborted); @@ -390,6 +395,25 @@ impl Agent { } let (msg, stop, usage) = done.ok_or(Error::Truncated)?; self.usage.add(&usage); + // no text and no tool call (e.g. output_tokens 0): never store it, it would poison + // the context and every "continue" would hit the same empty reply + let useful = msg.content.iter().any(|b| match b { + ContentBlock::Text { text } => !text.trim().is_empty(), + ContentBlock::ToolUse { .. } => true, + _ => false, + }); + if !useful { + if empty_retries == 0 { + empty_retries += 1; + self.emit(Event::Info(format!( + "empty reply from the provider (stop: {stop:?}); retrying once" + ))) + .await; + continue; + } + return Err(Error::EmptyReply(stop)); + } + empty_retries = 0; let total = (usage.input_tokens + usage.cache_read_tokens + usage.cache_write_tokens @@ -594,6 +618,34 @@ mod tests { } } + #[tokio::test] + async fn empty_reply_retries_once_and_is_not_stored() { + let text = |t: &str| asst(vec![ContentBlock::Text { text: t.into() }]); + let mk = |v| { + let dir = tempfile::tempdir().unwrap(); + let cx = ToolCtx { + cwd: dir.path().into(), + state: Default::default(), + }; + let script = Arc::new(Script(Mutex::new(v), Mutex::new(vec![]))); + let (a, _h) = Agent::new( + script, + Registry::default(), + Session::open(dir.path().join("s.jsonl")).unwrap(), + cx, + ); + (a, dir) + }; + // empty, then text: retried, only the good reply is stored + let (mut a, _d) = mk(vec![asst(vec![]), text("ok")]); + assert_eq!(a.run("p").await.unwrap().text(), "ok"); + assert_eq!(a.session.messages().len(), 2); + // empty twice: error, nothing stored besides the prompt + let (mut a, _d) = mk(vec![asst(vec![]), asst(vec![])]); + assert!(matches!(a.run("p").await, Err(Error::EmptyReply(_)))); + assert_eq!(a.session.messages().len(), 1); + } + #[tokio::test] async fn btw_reads_snapshot_without_touching_session() { let script = Arc::new(Script(