Merge pull request 'Permissions: --yolo, command-aware allow rules, load allow.json' (#119) from yolo-rules into main
ci / check (push) Canceled after 0s

This commit was merged in pull request #119.
This commit is contained in:
hermes committed 2026-10-02 21:38:15 +00:00
commit da5ff36b51
6 files changed
+148 -36

No files matched your search

+7
View File
@@ -36,6 +36,9 @@ struct Cli {
/// Resume: no value opens the session picker; with a query resumes the best title match. /// Resume: no value opens the session picker; with a query resumes the best title match.
#[arg(short, long, num_args = 0..=1, default_missing_value = "")] #[arg(short, long, num_args = 0..=1, default_missing_value = "")]
resume: Option<String>, resume: Option<String>,
/// Skip permission prompts for bash/write/edit (also `permissions = "yolo"` in config.toml).
#[arg(long)]
yolo: bool,
/// Output mode: text (default for -p), json (NDJSON events on stdout; needs -p), rpc (JSON-RPC on stdio). /// 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)] #[arg(long, value_enum, default_value_t = Mode::Text)]
mode: Mode, mode: Mode,
@@ -79,6 +82,8 @@ struct Config {
explore_model: Option<String>, explore_model: Option<String>,
/// Capture the mouse for wheel scrolling (default true; false = terminal selection works without shift). /// Capture the mouse for wheel scrolling (default true; false = terminal selection works without shift).
mouse: Option<bool>, mouse: Option<bool>,
/// "ask" (default) or "yolo": whether bash/write/edit prompt in the TUI.
permissions: Option<String>,
/// Replaces the built-in system prompt (AGENTS.md etc. are still appended). /// Replaces the built-in system prompt (AGENTS.md etc. are still appended).
system_prompt: Option<String>, system_prompt: Option<String>,
lsp: Option<LspCfg>, lsp: Option<LspCfg>,
@@ -124,6 +129,7 @@ impl Config {
max_tokens: o.max_tokens.or(c.max_tokens), max_tokens: o.max_tokens.or(c.max_tokens),
explore_model: o.explore_model.or(c.explore_model), explore_model: o.explore_model.or(c.explore_model),
mouse: o.mouse.or(c.mouse), mouse: o.mouse.or(c.mouse),
permissions: o.permissions.or(c.permissions),
system_prompt: o.system_prompt.or(c.system_prompt), system_prompt: o.system_prompt.or(c.system_prompt),
lsp: o.lsp.or(c.lsp), lsp: o.lsp.or(c.lsp),
extensions: [c.extensions, o.extensions].concat(), extensions: [c.extensions, o.extensions].concat(),
@@ -616,6 +622,7 @@ async fn main() -> Result<()> {
pricing, pricing,
specs, specs,
open_sessions, open_sessions,
yolo: cli.yolo || cfg.permissions.as_deref() == Some("yolo"),
mcp: mcp mcp: mcp
.servers .servers
.iter() .iter()
+97 -23
View File
@@ -32,25 +32,74 @@ pub type Permit = std::sync::Arc<
+ Sync, + Sync,
>; >;
/// `bash` rules cover a command's first word (`bash:cargo`); file tools are covered as a whole. /// Never remembered as a pattern: "always" stores the exact command only.
// ponytail: first-word granularity; add glob/argument patterns when people want `rm target/*` only. const RISKY: &[&str] = &[
"rm", "sudo", "su", "dd", "mkfs", "chmod", "chown", "curl", "wget", "ssh", "scp", "sh", "bash",
"zsh", "eval", "exec", "xargs", "find", "env", "git",
];
/// Shell syntax that chains or redirects: such commands match no pattern rule and are never
/// remembered, so `cargo test && rm -rf ~` cannot ride on a `cargo test *` rule.
fn compound(cmd: &str) -> bool {
cmd.contains(['\n', ';', '&', '|', '<', '>', '`', '$', '(', ')'])
}
/// Rule for "allow always". Bash: `bash:<command words> *` (first word, plus the subcommand when
/// there is one, e.g. `bash:cargo test *`); risky or compound commands store the exact command, or
/// nothing at all for compound ones (empty rule = the prompt offers no "always").
/// File tools are covered as a whole by the tool name.
// ponytail: patterns are `*` globs on the full command line; add argument-aware rules if needed.
pub fn request(tool: &str, args: &serde_json::Value) -> Request { pub fn request(tool: &str, args: &serde_json::Value) -> Request {
let s = |k: &str| args[k].as_str().unwrap_or_default().to_string(); let s = |k: &str| args[k].as_str().unwrap_or_default().to_string();
if tool == "bash" { if tool != "bash" {
let cmd = s("command"); return Request {
let word = cmd.split_whitespace().next().unwrap_or_default();
Request {
tool: tool.into(),
detail: cmd.clone(),
rule: format!("bash:{word}"),
}
} else {
Request {
tool: tool.into(), tool: tool.into(),
detail: s("path"), detail: s("path"),
rule: tool.into(), rule: tool.into(),
};
}
let cmd = s("command");
let cmd = cmd.trim().to_string();
let words: Vec<&str> = cmd.split_whitespace().collect();
let rule = if compound(&cmd) || words.is_empty() {
String::new()
} else if RISKY.contains(&words[0]) {
format!("bash:{cmd}")
} else if let Some(w) = words.get(1).filter(|w| {
w.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
&& !w.starts_with('-')
}) {
format!("bash:{} {w} *", words[0])
} else {
format!("bash:{} *", words[0])
};
Request {
tool: tool.into(),
detail: cmd,
rule,
}
}
/// `*` matches any run of characters; everything else literally.
fn glob(pat: &str, s: &str) -> bool {
let parts: Vec<&str> = pat.split('*').collect();
if parts.len() == 1 {
return pat == s;
}
let (first, last) = (parts[0], parts[parts.len() - 1]);
if s.len() < first.len() + last.len() || !s.starts_with(first) || !s.ends_with(last) {
return false;
}
let mut at = first.len();
let end = s.len() - last.len();
for m in &parts[1..parts.len() - 1] {
match s[at..end].find(m) {
Some(i) => at += i + m.len(),
None => return false,
} }
} }
true
} }
/// Always-allowed rules, persisted in `<project>/.hx/allow.json`. /// Always-allowed rules, persisted in `<project>/.hx/allow.json`.
@@ -72,11 +121,26 @@ impl Allow {
file: Some(file), file: Some(file),
} }
} }
pub fn has(&self, rule: &str) -> bool {
self.rules.contains(rule) /// Is this request covered by a stored rule? `bash:cargo test *` also covers a bare `cargo test`.
pub fn allows(&self, r: &Request) -> bool {
if r.tool != "bash" {
return self.rules.contains(&r.rule);
}
if compound(&r.detail) {
return false;
}
self.rules
.iter()
.filter_map(|x| x.strip_prefix("bash:"))
.any(|p| glob(p, &r.detail) || p.strip_suffix(" *").is_some_and(|b| b == r.detail))
} }
/// Remember a rule; the file is best effort (the rule holds for this session either way). /// Remember a rule; the file is best effort (the rule holds for this session either way).
pub fn add(&mut self, rule: &str) { pub fn add(&mut self, rule: &str) {
if rule.is_empty() {
return;
}
self.rules.insert(rule.into()); self.rules.insert(rule.into());
if let Some(f) = &self.file { if let Some(f) = &self.file {
let mut v: Vec<_> = self.rules.iter().collect(); let mut v: Vec<_> = self.rules.iter().collect();
@@ -102,23 +166,33 @@ mod tests {
use super::*; use super::*;
use serde_json::json; use serde_json::json;
fn bash(c: &str) -> Request {
request("bash", &json!({ "command": c }))
}
#[test] #[test]
fn rules_from_requests() { fn rules_from_requests() {
let r = request("bash", &json!({"command": "cargo test -q"})); assert_eq!(bash("cargo test -q").rule, "bash:cargo test *");
assert_eq!( assert_eq!(bash("ls -l").rule, "bash:ls *");
(r.rule.as_str(), r.detail.as_str()), assert_eq!(bash("rm -rf target").rule, "bash:rm -rf target");
("bash:cargo", "cargo test -q") assert_eq!(bash("cargo test && rm -rf ~").rule, "");
);
assert_eq!(request("edit", &json!({"path": "a.rs"})).rule, "edit"); assert_eq!(request("edit", &json!({"path": "a.rs"})).rule, "edit");
assert!(gated("bash") && !gated("read")); assert!(gated("bash") && !gated("read"));
} }
#[test] #[test]
fn allow_persists() { fn rules_match_narrowly() {
let d = tempfile::tempdir().unwrap(); let d = tempfile::tempdir().unwrap();
let mut a = Allow::load(d.path()); let mut a = Allow::load(d.path());
assert!(!a.has("bash:ls")); a.add(&bash("cargo test -q").rule);
a.add("bash:ls"); a.add(&bash("rm -rf target").rule);
assert!(Allow::load(d.path()).has("bash:ls")); assert!(a.allows(&bash("cargo test")) && a.allows(&bash("cargo test -p x")));
assert!(!a.allows(&bash("cargo publish")) && !a.allows(&bash("cargo testx")));
assert!(!a.allows(&bash("cargo test && rm -rf ~")) && !a.allows(&bash("cargo test; id")));
assert!(a.allows(&bash("rm -rf target")) && !a.allows(&bash("rm -rf /")));
// persisted
assert!(Allow::load(d.path()).allows(&bash("cargo test -q")));
a.add("");
assert!(!a.allows(&bash("")));
} }
} }
+1 -1
View File
@@ -114,7 +114,7 @@ impl Registry {
.allow .allow
.lock() .lock()
.unwrap_or_else(|e| e.into_inner()) .unwrap_or_else(|e| e.into_inner())
.has(&req.rule); .allows(&req);
if !known { if !known {
let rule = req.rule.clone(); let rule = req.rule.clone();
match ask(req).await { match ask(req).await {
+10 -1
View File
@@ -53,6 +53,8 @@ pub struct Setup {
pub open_sessions: bool, pub open_sessions: bool,
/// Capture the mouse (wheel scrolling); terminal text selection then needs shift-drag. /// Capture the mouse (wheel scrolling); terminal text selection then needs shift-drag.
pub mouse: bool, pub mouse: bool,
/// No permission prompts (`--yolo`).
pub yolo: bool,
/// MCP servers for the side panel: (name, connected). /// MCP servers for the side panel: (name, connected).
pub mcp: Vec<(String, bool)>, pub mcp: Vec<(String, bool)>,
} }
@@ -234,6 +236,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
specs, specs,
open_sessions, open_sessions,
mouse, mouse,
yolo,
mcp, mcp,
} = setup; } = setup;
let (tx, mut rx) = mpsc::unbounded_channel(); let (tx, mut rx) = mpsc::unbounded_channel();
@@ -250,7 +253,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
Box::pin(async move { orx.await.unwrap_or(false) }) Box::pin(async move { orx.await.unwrap_or(false) })
})); }));
} }
{ if !yolo {
let tx = tx.clone(); let tx = tx.clone();
let _ = agent.cx.state.permit.set(std::sync::Arc::new(move |r| { let _ = agent.cx.state.permit.set(std::sync::Arc::new(move |r| {
let (otx, orx) = tokio::sync::oneshot::channel(); let (otx, orx) = tokio::sync::oneshot::channel();
@@ -270,6 +273,12 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
let _ = agent.cx.state.subs.events.set(stx); let _ = agent.cx.state.subs.events.set(stx);
let abort: AbortHandle = agent.abort_handle(); let abort: AbortHandle = agent.abort_handle();
let cwd = agent.cx.cwd.clone(); let cwd = agent.cx.cwd.clone();
*agent
.cx
.state
.allow
.lock()
.unwrap_or_else(|e| e.into_inner()) = hx_core::permit::Allow::load(&cwd);
let mut app = App { let mut app = App {
t: Transcript::default(), t: Transcript::default(),
ed: Editor::default(), ed: Editor::default(),
+32 -10
View File
@@ -18,20 +18,40 @@ impl Prompt {
} }
/// Some = decided. /// Some = decided.
/// Chained commands have no rule: they are asked every time.
fn can_always(&self) -> bool {
!self.req.rule.is_empty()
}
fn opts(&self) -> Vec<(Decision, String)> {
let mut v = vec![(Decision::Once, "[y] allow once".to_string())];
if self.can_always() {
let r = self
.req
.rule
.strip_prefix("bash:")
.unwrap_or(&self.req.rule);
v.push((Decision::Always, format!("[a] allow always: {r}")));
}
v.push((Decision::Deny, "[n] deny".into()));
v
}
pub fn key(&mut self, k: KeyEvent) -> Option<Decision> { pub fn key(&mut self, k: KeyEvent) -> Option<Decision> {
match k.code { match k.code {
KeyCode::Char('y' | 'Y') => Some(Decision::Once), KeyCode::Char('y' | 'Y') => Some(Decision::Once),
KeyCode::Char('a' | 'A') => Some(Decision::Always), KeyCode::Char('a' | 'A') if self.can_always() => Some(Decision::Always),
KeyCode::Char('n' | 'N') | KeyCode::Esc => Some(Decision::Deny), KeyCode::Char('n' | 'N') | KeyCode::Esc => Some(Decision::Deny),
KeyCode::Up | KeyCode::Left => { KeyCode::Up | KeyCode::Left => {
self.sel = (self.sel + 2) % 3; let n = self.opts().len();
self.sel = (self.sel + n - 1) % n;
None None
} }
KeyCode::Down | KeyCode::Right | KeyCode::Tab => { KeyCode::Down | KeyCode::Right | KeyCode::Tab => {
self.sel = (self.sel + 1) % 3; self.sel = (self.sel + 1) % self.opts().len();
None None
} }
KeyCode::Enter => Some([Decision::Once, Decision::Always, Decision::Deny][self.sel]), KeyCode::Enter => Some(self.opts()[self.sel].0),
_ => None, _ => None,
} }
} }
@@ -49,11 +69,7 @@ impl Prompt {
let th = theme::t(); let th = theme::t();
let a = f.area(); let a = f.area();
let w = (a.width * 3 / 5).clamp(44, 100).min(a.width); let w = (a.width * 3 / 5).clamp(44, 100).min(a.width);
let opts = [ let opts: Vec<String> = self.opts().into_iter().map(|o| o.1).collect();
"[y] allow once".to_string(),
format!("[a] allow always: {}", self.req.rule),
"[n] deny".to_string(),
];
let mut lines = vec![ let mut lines = vec![
Line::styled("hx wants to run:", th.dim()), Line::styled("hx wants to run:", th.dim()),
Line::default(), Line::default(),
@@ -102,7 +118,7 @@ mod tests {
Prompt::new(Request { Prompt::new(Request {
tool: "bash".into(), tool: "bash".into(),
detail: "rm -rf x".into(), detail: "rm -rf x".into(),
rule: "bash:rm".into(), rule: "bash:rm -rf x".into(),
}) })
} }
fn k(c: KeyCode) -> KeyEvent { fn k(c: KeyCode) -> KeyEvent {
@@ -117,5 +133,11 @@ mod tests {
let mut q = p(); let mut q = p();
assert_eq!(q.key(k(KeyCode::Down)), None); assert_eq!(q.key(k(KeyCode::Down)), None);
assert_eq!(q.key(k(KeyCode::Enter)), Some(Decision::Always)); assert_eq!(q.key(k(KeyCode::Enter)), Some(Decision::Always));
// chained command: no "always"
let mut c = p();
c.req.rule.clear();
assert_eq!(c.key(k(KeyCode::Char('a'))), None);
c.key(k(KeyCode::Down));
assert_eq!(c.key(k(KeyCode::Enter)), Some(Decision::Deny));
} }
} }
+1 -1
View File
@@ -65,7 +65,7 @@ send(b"make hello.txt"); send(b"\r", 2)
check("permission prompt", "permission") check("permission prompt", "permission")
check("allow always rule", "allow always: write") check("allow always rule", "allow always: write")
send(b"y", 2) send(b"y", 2)
check("second prompt for bash", "allow always: bash:cat") check("second prompt for bash", "allow always: cat *")
send(b"y", 3) send(b"y", 3)
check("tool call shown", "hello.txt") check("tool call shown", "hello.txt")
check("tool outcome", "1 lines") check("tool outcome", "1 lines")