From b1ca582d6b2ab5a19206a2ba709332b74224da44 Mon Sep 17 00:00:00 2001 From: Johannes Kresner Date: Tue, 17 Nov 2026 16:43:41 +0100 Subject: [PATCH] fix: orchestrated runs honour yolo/auto and work inside the sandbox - serve --acp applies --yolo / --auto (or `permissions` in config.toml) like the TUI; before, every edit and command went to the orchestrator. - claude no longer asks to run outside the sandbox. With the sandbox on it stays confined; only a stored `claude:unsandboxed` rule or --no-claude-sandbox lets it out, and yolo never does. - The sandbox reads the files the global git config includes and may stat $HOME and the directories above allowed paths and includeIf gitdir paths (metadata only). git died on both before. - hx mcp-serve logs a failed start to $TMPDIR/hx-mcp-serve.log; claude hides its stderr and only reports "mcp__hx__approve not found". Co-Authored-By: Claude Opus 5.5 --- crates/hx-cli/src/main.rs | 178 +++++++++++++++++++--------------- crates/hx-core/src/permit.rs | 10 ++ crates/hx-core/src/sandbox.rs | 113 +++++++++++++++++++++ 3 files changed, 223 insertions(+), 78 deletions(-) diff --git a/crates/hx-cli/src/main.rs b/crates/hx-cli/src/main.rs index 4f1ff57..5d7e6e5 100644 --- a/crates/hx-cli/src/main.rs +++ b/crates/hx-cli/src/main.rs @@ -264,44 +264,91 @@ impl Config { } } -/// Tool context for the claude sandbox question (set once the agent exists). +/// Tool context of the agent, for the stored "run claude outside the sandbox" rule. static CLAUDE_CX: std::sync::OnceLock = std::sync::OnceLock::new(); -/// Answer to "run claude outside the sandbox?" for this process. -static CLAUDE_OUTSIDE: std::sync::Mutex> = std::sync::Mutex::new(None); const OUTSIDE_RULE: &str = "claude:unsandboxed"; -/// Allowed to leave the sandbox? A stored rule says yes; else the TUI asks (once per run, "always" -/// is stored in `.hx/allow.json`); without a prompt hook (`-p`) the answer is no. -async fn claude_outside() -> bool { - if let Some(v) = *CLAUDE_OUTSIDE.lock().unwrap_or_else(|e| e.into_inner()) { - return v; - } - let ok = match CLAUDE_CX.get() { - Some(cx) if cx.state.permit.get().is_some() => { - hx_core::tool::gate( - cx, - hx_core::permit::Request { - tool: "claude".into(), - detail: "run claude outside the sandbox (its tools then run unconfined)".into(), - rule: OUTSIDE_RULE.into(), - }, - ) - .await - } - Some(cx) => cx - .state +/// Leave the sandbox only on an explicit, stored rule (`claude:unsandboxed` in `.hx/allow.json`). Never +/// asked and never implied by yolo: yolo is only safe because claude's tools stay confined. +fn claude_outside() -> bool { + CLAUDE_CX.get().is_some_and(|cx| { + cx.state .allow .lock() .unwrap_or_else(|e| e.into_inner()) - .allows(&hx_core::permit::Request { - tool: "claude".into(), - detail: String::new(), - rule: OUTSIDE_RULE.into(), - }), - None => false, + .has_rule(OUTSIDE_RULE) + }) +} + +/// `hx mcp-serve`: lens/LSP, hx's MCP servers and (with a permission socket) `approve` for claude. +async fn mcp_serve() -> Result<()> { + let cwd = std::env::current_dir()?; + let mgr = Arc::new(hx_lens::manager::Manager::new( + cwd.clone(), + hx_lens::manager::default_servers(), + )); + let mut reg = hx_core::tool::Registry::default(); + reg.add(hx_lens::LspTool::new(mgr.clone())); + let cx = ToolCtx { + cwd: cwd.clone(), + state: Default::default(), }; - *CLAUDE_OUTSIDE.lock().unwrap_or_else(|e| e.into_inner()) = Some(ok); - ok + let sock = std::env::var_os(hx_core::approve::ENV); + if let Some(p) = &sock { + reg.add(hx_core::approve::Approve(p.into())); + // tools run by codemode ask hx for permission like any other + let _ = cx + .state + .permit + .set(hx_core::approve::remote_permit(p.into())); + } + // claude keeps its own tools; hx's MCP servers are added directly, or only through `codemode` + let cfg = Config::load(&cwd)?; + let mut servers = + hx_mcp::config::load(&context::hx_home(), &cwd).map_err(anyhow::Error::msg)?; + // a server entry that is hx itself would spawn mcp-serve recursively + servers.retain(|_, s| !s.args.iter().any(|a| a == "mcp-serve")); + let hub = Arc::new(hx_mcp::Hub::start(servers).await); + if std::env::var_os("HX_CODEMODE").is_some() { + let mut all = hx_tools::registry(); + hx_tools::web::register(&mut all, web_search(&cfg)); + hub.register(&mut all); + all.add(hx_lens::LspTool::new(mgr.clone())); + reg.add(hx_tools::codemode::Codemode::new(&all)); + } else { + hub.register(&mut reg); + } + hx_mcp::serve::serve( + reg, + cx, + tokio::io::BufReader::new(tokio::io::stdin()), + tokio::io::stdout(), + ) + .await?; + mgr.shutdown().await; + Ok(()) +} + +/// Appends a line to `$TMPDIR/hx-mcp-serve.log` (writable inside the sandbox too); best effort. +fn mcp_serve_log(line: &str) { + use std::io::Write; + let p = std::env::temp_dir().join("hx-mcp-serve.log"); + if let Ok(mut f) = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(p) + { + let cwd = std::env::current_dir().unwrap_or_default(); + let t = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_secs()); + let _ = writeln!( + f, + "{t} pid {} cwd {}: {line}", + std::process::id(), + cwd.display() + ); + } } /// What `claude` (and its `hx mcp-serve` child) need inside the sandbox: its binary and config, @@ -354,11 +401,11 @@ fn claude_extra(bin: &str) -> hx_core::sandbox::Extra { } } -/// The `claude` command: sandboxed when the sandbox is on, unless the user let it out. +/// The `claude` command: sandboxed when the sandbox is on, unless claude's sandbox is off or a rule lets it out. async fn claude_command(bin: String) -> tokio::process::Command { if hx_core::sandbox::active().is_none() || !hx_core::sandbox::claude_sandboxed() - || claude_outside().await + || claude_outside() { return tokio::process::Command::new(bin); } @@ -817,51 +864,13 @@ async fn main() -> Result<()> { return Ok(()); } Some(Cmd::McpServe) => { - let cwd = std::env::current_dir()?; - let mgr = Arc::new(hx_lens::manager::Manager::new( - cwd.clone(), - hx_lens::manager::default_servers(), - )); - let mut reg = hx_core::tool::Registry::default(); - reg.add(hx_lens::LspTool::new(mgr.clone())); - let cx = ToolCtx { - cwd: cwd.clone(), - state: Default::default(), - }; - let sock = std::env::var_os(hx_core::approve::ENV); - if let Some(p) = &sock { - reg.add(hx_core::approve::Approve(p.into())); - // tools run by codemode ask hx for permission like any other - let _ = cx - .state - .permit - .set(hx_core::approve::remote_permit(p.into())); + // claude starts this and hides its stderr: a failed start shows up only as + // "mcp__hx__approve not found", so the reason goes to a log file as well + let r = mcp_serve().await; + if let Err(e) = &r { + mcp_serve_log(&format!("mcp-serve failed: {e:#}")); } - // claude keeps its own tools; hx's MCP servers are added directly, or only through `codemode` - let cfg = Config::load(&cwd)?; - let mut servers = - hx_mcp::config::load(&context::hx_home(), &cwd).map_err(anyhow::Error::msg)?; - // a server entry that is hx itself would spawn mcp-serve recursively - servers.retain(|_, s| !s.args.iter().any(|a| a == "mcp-serve")); - let hub = Arc::new(hx_mcp::Hub::start(servers).await); - if std::env::var_os("HX_CODEMODE").is_some() { - let mut all = hx_tools::registry(); - hx_tools::web::register(&mut all, web_search(&cfg)); - hub.register(&mut all); - all.add(hx_lens::LspTool::new(mgr.clone())); - reg.add(hx_tools::codemode::Codemode::new(&all)); - } else { - hub.register(&mut reg); - } - hx_mcp::serve::serve( - reg, - cx, - tokio::io::BufReader::new(tokio::io::stdin()), - tokio::io::stdout(), - ) - .await?; - mgr.shutdown().await; - return Ok(()); + return r; } None => {} } @@ -1185,7 +1194,20 @@ async fn main() -> Result<()> { }); } if let Some(id) = acp_id { - // no TUI, no prompts: every permission question goes to the orchestrator + // no TUI, no prompts: every permission question goes to the orchestrator, except what + // --yolo / --auto (or `permissions` in config.toml) settle here, the same as in the TUI + { + let yolo = cli.yolo || cfg.permissions.as_deref() == Some("yolo"); + let auto = cli.auto || cfg.permissions.as_deref() == Some("auto"); + let mut a = agent + .cx + .state + .allow + .lock() + .unwrap_or_else(|e| e.into_inner()); + a.set_yolo(yolo); + a.set_auto(auto && !yolo); + } let opts = acp::Opts { session: id, cwd: cwd.clone(), diff --git a/crates/hx-core/src/permit.rs b/crates/hx-core/src/permit.rs index 03bd2a4..0c91ebb 100644 --- a/crates/hx-core/src/permit.rs +++ b/crates/hx-core/src/permit.rs @@ -397,6 +397,16 @@ impl Allow { self.yolo } + /// Allow everything (not persisted). + pub fn set_yolo(&mut self, on: bool) { + self.yolo = on; + } + + /// A stored rule (`.hx/allow.json` or "always" this session), ignoring yolo and edit grants. + pub fn has_rule(&self, rule: &str) -> bool { + self.rules.contains(rule) + } + /// Toggle: allow everything (not persisted); returns the new state. pub fn toggle_yolo(&mut self) -> bool { self.yolo = !self.yolo; diff --git a/crates/hx-core/src/sandbox.rs b/crates/hx-core/src/sandbox.rs index 7bf5d86..b50e4a3 100644 --- a/crates/hx-core/src/sandbox.rs +++ b/crates/hx-core/src/sandbox.rs @@ -91,6 +91,60 @@ impl Default for Cfg { } } +/// Paths named by `path =` in `[include]` / `[includeIf ...]` sections of the global git config, followed +/// into the included files (a few levels), and the `gitdir:` directories of `includeIf` (git resolves +/// them on every start). `~/` expands; relative paths are relative to the including file. +fn git_includes(home: &Path) -> (Vec, Vec) { + let mut todo = vec![home.join(".gitconfig"), home.join(".config/git/config")]; + let mut found: Vec = vec![]; + let mut dirs: Vec = vec![]; + let mut depth = 0; + while !todo.is_empty() && depth < 5 { + depth += 1; + let mut next = vec![]; + for f in todo { + let Ok(text) = std::fs::read_to_string(&f) else { + continue; + }; + let mut include = false; + for line in text.lines().map(str::trim) { + if let Some(sec) = line.strip_prefix('[') { + let sec = sec.trim_start(); + include = sec.to_ascii_lowercase().starts_with("include"); + // [includeIf "gitdir:~/w/"] or "gitdir/i:..." + if let Some(d) = sec + .split_once('"') + .and_then(|(_, r)| r.split_once(':')) + .filter(|(k, _)| k.starts_with("gitdir")) + .and_then(|(_, v)| v.split('"').next()) + .and_then(|v| v.strip_prefix("~/")) + { + dirs.push(home.join(d.trim_end_matches("**").trim_end_matches('/'))); + } + continue; + } + let Some((k, v)) = line.split_once('=') else { + continue; + }; + if !include || !k.trim().eq_ignore_ascii_case("path") { + continue; + } + let v = v.trim().trim_matches('"'); + let p = match v.strip_prefix("~/") { + Some(r) => home.join(r), + None => f.parent().unwrap_or(Path::new("/")).join(v), + }; + if !found.contains(&p) { + found.push(p.clone()); + next.push(p); + } + } + } + todo = next; + } + (found, dirs) +} + #[derive(Debug, Clone)] pub struct Sandbox { backend: Backend, @@ -99,6 +153,8 @@ pub struct Sandbox { cwd: PathBuf, rw: Vec, ro: Vec, + /// paths under `$HOME` whose metadata (not content) may be read, e.g. `includeIf "gitdir:~/w"` + meta: Vec, env_allow: Vec, } @@ -273,6 +329,9 @@ impl Sandbox { .collect() }; let mut ro = paths(&cfg.ro); + // files the global git config includes (`[include] path = ...`): without them git fails to start + let (inc, meta) = git_includes(&home); + ro.extend(inc.into_iter().filter(|p| p.exists()).map(|p| canon(&p))); let skills = crate::context::hx_home().join("skills"); if skills.exists() { ro.push(canon(&skills)); @@ -284,6 +343,7 @@ impl Sandbox { cwd: canon(cwd), rw: paths(&cfg.rw), ro, + meta, env_allow: cfg.env_allow.clone(), }) } @@ -442,6 +502,28 @@ impl Sandbox { let w = self.writable(); let readable: Vec = w.iter().chain(self.ro.iter()).cloned().collect(); p += &format!("(allow file-read* {})\n", list(&readable)); + // stat of $HOME and the directories above each allowed path (git resolves paths component by + // component and dies on EPERM); `literal` = these directories only, not what is inside + let mut dirs: Vec<&Path> = readable + .iter() + .chain(&self.meta) + .flat_map(|p| p.ancestors()) + .filter(|a| a.starts_with(&self.home)) + .collect(); + dirs.sort(); + dirs.dedup(); + let lit = |p: &Path| { + format!( + "(literal \"{}\")", + p.to_string_lossy() + .replace('\\', "\\\\") + .replace('"', "\\\"") + ) + }; + p += &format!( + "(allow file-read-metadata {})\n", + dirs.iter().map(|d| lit(d)).collect::>().join(" ") + ); p += &format!("(allow file-write* {})\n", list(&w)); p += "(allow file-write* (literal \"/dev/null\") (literal \"/dev/tty\"))\n"; if self.network { @@ -455,6 +537,33 @@ impl Sandbox { mod tests { use super::*; + #[test] + fn git_includes_follow_include_sections() { + let home = std::env::temp_dir().join(format!("hx-gitinc-{}", std::process::id())); + std::fs::create_dir_all(home.join(".config/delta")).unwrap(); + std::fs::write( + home.join(".gitconfig"), + "[user]\n path = /not/an/include\n[include]\n path = ~/.config/delta/theme.gitconfig\n[includeIf \"gitdir:~/w/\"]\n path = \"work.gitconfig\"\n", + ) + .unwrap(); + std::fs::write( + home.join(".config/delta/theme.gitconfig"), + "[include]\npath = nested\n", + ) + .unwrap(); + let (got, dirs) = git_includes(&home); + let _ = std::fs::remove_dir_all(&home); + assert_eq!(dirs, [home.join("w")]); + assert_eq!( + got, + [ + home.join(".config/delta/theme.gitconfig"), + home.join("work.gitconfig"), + home.join(".config/delta/nested"), + ] + ); + } + fn sb(backend: Backend, network: bool) -> Sandbox { Sandbox { backend, @@ -463,6 +572,7 @@ mod tests { cwd: "/home/u/proj".into(), rw: vec!["/home/u/.cargo/registry".into()], ro: vec!["/home/u/.cargo".into()], + meta: vec!["/home/u/w/x".into()], env_allow: vec!["PATH".into(), "LC_*".into()], } } @@ -495,6 +605,9 @@ mod tests { .unwrap() ); assert!(p.contains("(allow file-write* (subpath \"/home/u/proj\")")); + assert!(p.contains( + "(allow file-read-metadata (literal \"/home/u\") (literal \"/home/u/.cargo\") (literal \"/home/u/.cargo/registry\") (literal \"/home/u/proj\") (literal \"/home/u/w\") (literal \"/home/u/w/x\"))" + )); assert!( sb(Backend::Seatbelt, true) .seatbelt_profile()