Merge pull request 'fix: orchestrated runs honour yolo/auto and work inside the sandbox' (#194) from fix/acp-sandbox-permissions into main
Reviewed-on: #194
This commit was merged in pull request #194.
This commit is contained in:
commit
437f8ec501
3 files changed
+223
-78
No files matched your search
+100
-78
@@ -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<ToolCtx> = std::sync::OnceLock::new();
|
static CLAUDE_CX: std::sync::OnceLock<ToolCtx> = std::sync::OnceLock::new();
|
||||||
/// Answer to "run claude outside the sandbox?" for this process.
|
|
||||||
static CLAUDE_OUTSIDE: std::sync::Mutex<Option<bool>> = std::sync::Mutex::new(None);
|
|
||||||
const OUTSIDE_RULE: &str = "claude:unsandboxed";
|
const OUTSIDE_RULE: &str = "claude:unsandboxed";
|
||||||
|
|
||||||
/// Allowed to leave the sandbox? A stored rule says yes; else the TUI asks (once per run, "always"
|
/// Leave the sandbox only on an explicit, stored rule (`claude:unsandboxed` in `.hx/allow.json`). Never
|
||||||
/// is stored in `.hx/allow.json`); without a prompt hook (`-p`) the answer is no.
|
/// asked and never implied by yolo: yolo is only safe because claude's tools stay confined.
|
||||||
async fn claude_outside() -> bool {
|
fn claude_outside() -> bool {
|
||||||
if let Some(v) = *CLAUDE_OUTSIDE.lock().unwrap_or_else(|e| e.into_inner()) {
|
CLAUDE_CX.get().is_some_and(|cx| {
|
||||||
return v;
|
cx.state
|
||||||
}
|
|
||||||
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
|
|
||||||
.allow
|
.allow
|
||||||
.lock()
|
.lock()
|
||||||
.unwrap_or_else(|e| e.into_inner())
|
.unwrap_or_else(|e| e.into_inner())
|
||||||
.allows(&hx_core::permit::Request {
|
.has_rule(OUTSIDE_RULE)
|
||||||
tool: "claude".into(),
|
})
|
||||||
detail: String::new(),
|
}
|
||||||
rule: OUTSIDE_RULE.into(),
|
|
||||||
}),
|
/// `hx mcp-serve`: lens/LSP, hx's MCP servers and (with a permission socket) `approve` for claude.
|
||||||
None => false,
|
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);
|
let sock = std::env::var_os(hx_core::approve::ENV);
|
||||||
ok
|
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,
|
/// 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 {
|
async fn claude_command(bin: String) -> tokio::process::Command {
|
||||||
if hx_core::sandbox::active().is_none()
|
if hx_core::sandbox::active().is_none()
|
||||||
|| !hx_core::sandbox::claude_sandboxed()
|
|| !hx_core::sandbox::claude_sandboxed()
|
||||||
|| claude_outside().await
|
|| claude_outside()
|
||||||
{
|
{
|
||||||
return tokio::process::Command::new(bin);
|
return tokio::process::Command::new(bin);
|
||||||
}
|
}
|
||||||
@@ -817,51 +864,13 @@ async fn main() -> Result<()> {
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
Some(Cmd::McpServe) => {
|
Some(Cmd::McpServe) => {
|
||||||
let cwd = std::env::current_dir()?;
|
// claude starts this and hides its stderr: a failed start shows up only as
|
||||||
let mgr = Arc::new(hx_lens::manager::Manager::new(
|
// "mcp__hx__approve not found", so the reason goes to a log file as well
|
||||||
cwd.clone(),
|
let r = mcp_serve().await;
|
||||||
hx_lens::manager::default_servers(),
|
if let Err(e) = &r {
|
||||||
));
|
mcp_serve_log(&format!("mcp-serve failed: {e:#}"));
|
||||||
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 keeps its own tools; hx's MCP servers are added directly, or only through `codemode`
|
return r;
|
||||||
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(());
|
|
||||||
}
|
}
|
||||||
None => {}
|
None => {}
|
||||||
}
|
}
|
||||||
@@ -1185,7 +1194,20 @@ async fn main() -> Result<()> {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
if let Some(id) = acp_id {
|
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 {
|
let opts = acp::Opts {
|
||||||
session: id,
|
session: id,
|
||||||
cwd: cwd.clone(),
|
cwd: cwd.clone(),
|
||||||
|
|||||||
@@ -397,6 +397,16 @@ impl Allow {
|
|||||||
self.yolo
|
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.
|
/// Toggle: allow everything (not persisted); returns the new state.
|
||||||
pub fn toggle_yolo(&mut self) -> bool {
|
pub fn toggle_yolo(&mut self) -> bool {
|
||||||
self.yolo = !self.yolo;
|
self.yolo = !self.yolo;
|
||||||
|
|||||||
@@ -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<PathBuf>, Vec<PathBuf>) {
|
||||||
|
let mut todo = vec![home.join(".gitconfig"), home.join(".config/git/config")];
|
||||||
|
let mut found: Vec<PathBuf> = vec![];
|
||||||
|
let mut dirs: Vec<PathBuf> = 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)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct Sandbox {
|
pub struct Sandbox {
|
||||||
backend: Backend,
|
backend: Backend,
|
||||||
@@ -99,6 +153,8 @@ pub struct Sandbox {
|
|||||||
cwd: PathBuf,
|
cwd: PathBuf,
|
||||||
rw: Vec<PathBuf>,
|
rw: Vec<PathBuf>,
|
||||||
ro: Vec<PathBuf>,
|
ro: Vec<PathBuf>,
|
||||||
|
/// paths under `$HOME` whose metadata (not content) may be read, e.g. `includeIf "gitdir:~/w"`
|
||||||
|
meta: Vec<PathBuf>,
|
||||||
env_allow: Vec<String>,
|
env_allow: Vec<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -273,6 +329,9 @@ impl Sandbox {
|
|||||||
.collect()
|
.collect()
|
||||||
};
|
};
|
||||||
let mut ro = paths(&cfg.ro);
|
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");
|
let skills = crate::context::hx_home().join("skills");
|
||||||
if skills.exists() {
|
if skills.exists() {
|
||||||
ro.push(canon(&skills));
|
ro.push(canon(&skills));
|
||||||
@@ -284,6 +343,7 @@ impl Sandbox {
|
|||||||
cwd: canon(cwd),
|
cwd: canon(cwd),
|
||||||
rw: paths(&cfg.rw),
|
rw: paths(&cfg.rw),
|
||||||
ro,
|
ro,
|
||||||
|
meta,
|
||||||
env_allow: cfg.env_allow.clone(),
|
env_allow: cfg.env_allow.clone(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -442,6 +502,28 @@ impl Sandbox {
|
|||||||
let w = self.writable();
|
let w = self.writable();
|
||||||
let readable: Vec<PathBuf> = w.iter().chain(self.ro.iter()).cloned().collect();
|
let readable: Vec<PathBuf> = w.iter().chain(self.ro.iter()).cloned().collect();
|
||||||
p += &format!("(allow file-read* {})\n", list(&readable));
|
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::<Vec<_>>().join(" ")
|
||||||
|
);
|
||||||
p += &format!("(allow file-write* {})\n", list(&w));
|
p += &format!("(allow file-write* {})\n", list(&w));
|
||||||
p += "(allow file-write* (literal \"/dev/null\") (literal \"/dev/tty\"))\n";
|
p += "(allow file-write* (literal \"/dev/null\") (literal \"/dev/tty\"))\n";
|
||||||
if self.network {
|
if self.network {
|
||||||
@@ -455,6 +537,33 @@ impl Sandbox {
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
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 {
|
fn sb(backend: Backend, network: bool) -> Sandbox {
|
||||||
Sandbox {
|
Sandbox {
|
||||||
backend,
|
backend,
|
||||||
@@ -463,6 +572,7 @@ mod tests {
|
|||||||
cwd: "/home/u/proj".into(),
|
cwd: "/home/u/proj".into(),
|
||||||
rw: vec!["/home/u/.cargo/registry".into()],
|
rw: vec!["/home/u/.cargo/registry".into()],
|
||||||
ro: vec!["/home/u/.cargo".into()],
|
ro: vec!["/home/u/.cargo".into()],
|
||||||
|
meta: vec!["/home/u/w/x".into()],
|
||||||
env_allow: vec!["PATH".into(), "LC_*".into()],
|
env_allow: vec!["PATH".into(), "LC_*".into()],
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -495,6 +605,9 @@ mod tests {
|
|||||||
.unwrap()
|
.unwrap()
|
||||||
);
|
);
|
||||||
assert!(p.contains("(allow file-write* (subpath \"/home/u/proj\")"));
|
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!(
|
assert!(
|
||||||
sb(Backend::Seatbelt, true)
|
sb(Backend::Seatbelt, true)
|
||||||
.seatbelt_profile()
|
.seatbelt_profile()
|
||||||
|
|||||||
Reference in new issue
Block a user