on_deny=continue (soft vs hard denies), denies counter, tokens of stopped runs
This commit is contained in:
1 parent
e668eb1b0d
commit
8c76da90e8
11 files changed
+310
-87
No files matched your search
@@ -31,6 +31,7 @@ max_retries = 2
|
||||
workers = 2
|
||||
account = "work-claude" # profiles on one login share quota pause and max_concurrent
|
||||
allow = ["read", "write", "edit", "readonly", "bash:cargo *"]
|
||||
on_deny = "continue" # soft denies go back to the agent instead of ending the run
|
||||
[budget]
|
||||
wall_secs = 1800 # per attempt
|
||||
max_turns = 40 # whole run
|
||||
|
||||
@@ -30,6 +30,11 @@ sandbox = true # hx --sandbox (bwrap); required for yolo = tru
|
||||
`.ssh`, `.aws`, `auth.json`, `*.pem`, `*.key`, ...), file tools outside the worktree (reads may also use
|
||||
`read_roots`), writes to `.git` and `.hx`.
|
||||
- A denied call ends the run as `needs-human` with `reason = "policy: ..."`; the branch keeps what was done so far.
|
||||
- `on_deny = "continue"` (default `"stop"`): a call that is merely **not in the allowlist** is answered to the agent
|
||||
(`orch-guard-soft: ... Use another way`), the tool does not run and the run goes on; the gate decides in the end.
|
||||
**Hard** denies always stop the run: credential-looking paths, paths outside the worktree, `git push`, writes to
|
||||
`.git`/`.hx`. Every deny is audited (`decision: deny`, `hard: true|false`) and counted (`denies` in the run state,
|
||||
telemetry and the `denies` column of `orch report`).
|
||||
|
||||
Enforced twice: `orch guard` runs inside hx as an extension (installed as the worktree's `.hx/config.toml`, removed
|
||||
after each attempt, rewritten before the next) and blocks the call before it executes. orch also checks every
|
||||
|
||||
+97
-34
@@ -20,6 +20,8 @@ use std::path::{Component, Path, PathBuf};
|
||||
|
||||
pub const MARK: &str = "# orch-guard (generated, do not edit)";
|
||||
pub const PREFIX: &str = "orch-guard:";
|
||||
/// Block reason of a soft deny under `on_deny = "continue"`: the run goes on, orch only counts it.
|
||||
pub const SOFT_PREFIX: &str = "orch-guard-soft:";
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug)]
|
||||
pub struct Policy {
|
||||
@@ -29,12 +31,27 @@ pub struct Policy {
|
||||
pub worktree: PathBuf,
|
||||
pub read_roots: Vec<PathBuf>,
|
||||
pub audit: PathBuf,
|
||||
/// `on_deny = "continue"`: soft denies are answered to the agent instead of ending the run.
|
||||
#[serde(default)]
|
||||
pub soft_continue: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum Decision {
|
||||
Allow(String),
|
||||
/// Not in the allowlist: with `on_deny = "continue"` the agent gets the reason and works on.
|
||||
Deny(String),
|
||||
/// Never negotiable: credentials, outside the worktree, `git push`, `.git`/`.hx`. Ends the run.
|
||||
Hard(String),
|
||||
}
|
||||
|
||||
impl Decision {
|
||||
pub fn deny_reason(&self) -> Option<&str> {
|
||||
match self {
|
||||
Decision::Deny(w) | Decision::Hard(w) => Some(w),
|
||||
Decision::Allow(_) => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `*` matches any run of characters (including none); everything else is literal.
|
||||
@@ -237,10 +254,10 @@ impl Policy {
|
||||
s("command")
|
||||
};
|
||||
if mentions_git_push(cmd) {
|
||||
return Deny("git push is done by the sink, not the agent".into());
|
||||
return Hard("git push is done by the sink, not the agent".into());
|
||||
}
|
||||
if cmd.split_whitespace().any(secret) {
|
||||
return Deny("command touches a secret-looking path".into());
|
||||
return Hard("command touches a secret-looking path".into());
|
||||
}
|
||||
let free = self
|
||||
.allow
|
||||
@@ -271,7 +288,7 @@ impl Policy {
|
||||
let ok = !w.starts_with('~')
|
||||
&& self.inside(&resolve(&self.worktree, w), &self.roots());
|
||||
if !ok {
|
||||
return Deny(format!("path `{w}` is outside the worktree"));
|
||||
return Hard(format!("path `{w}` is outside the worktree"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -285,21 +302,21 @@ impl Policy {
|
||||
let write = matches!(t.as_str(), "write" | "edit");
|
||||
let r = resolve(&self.worktree, path);
|
||||
if secret(&r.to_string_lossy()) {
|
||||
return Deny(format!("`{path}` looks like a credential file"));
|
||||
return Hard(format!("`{path}` looks like a credential file"));
|
||||
}
|
||||
if write {
|
||||
let rel = r.strip_prefix(&self.worktree);
|
||||
if rel.is_err() {
|
||||
return Deny(format!("write outside the worktree: `{path}`"));
|
||||
return Hard(format!("write outside the worktree: `{path}`"));
|
||||
}
|
||||
if rel.is_ok_and(|x| {
|
||||
x.components()
|
||||
.any(|c| matches!(c.as_os_str().to_str(), Some(".git" | ".hx")))
|
||||
}) {
|
||||
return Deny(format!("`{path}` is guard/git metadata"));
|
||||
return Hard(format!("`{path}` is guard/git metadata"));
|
||||
}
|
||||
} else if !self.inside(&r, &self.roots()) {
|
||||
return Deny(format!("read outside the worktree: `{path}`"));
|
||||
return Hard(format!("read outside the worktree: `{path}`"));
|
||||
}
|
||||
}
|
||||
if why.is_none() {
|
||||
@@ -350,7 +367,13 @@ fn policy_path(run: &str) -> PathBuf {
|
||||
|
||||
/// Writes the policy and the worktree's `.hx/config.toml` that starts the guard. Rewritten before every
|
||||
/// attempt, so an agent that edited it is healed. Refuses to touch a config that is not ours.
|
||||
pub fn install(run: &str, wt: &Path, allow: &[String], read_roots: &[PathBuf]) -> Result<Policy> {
|
||||
pub fn install(
|
||||
run: &str,
|
||||
wt: &Path,
|
||||
allow: &[String],
|
||||
read_roots: &[PathBuf],
|
||||
soft_continue: bool,
|
||||
) -> Result<Policy> {
|
||||
let pol = Policy {
|
||||
run: run.into(),
|
||||
allow: allow.to_vec(),
|
||||
@@ -360,6 +383,7 @@ pub fn install(run: &str, wt: &Path, allow: &[String], read_roots: &[PathBuf]) -
|
||||
.map(|r| resolve(Path::new("/"), &r.to_string_lossy()))
|
||||
.collect(),
|
||||
audit: audit_path(),
|
||||
soft_continue,
|
||||
};
|
||||
let pp = policy_path(run);
|
||||
std::fs::create_dir_all(pp.parent().unwrap())?;
|
||||
@@ -409,6 +433,16 @@ pub fn guard(policy_file: &Path) -> Result<()> {
|
||||
let (act, why, extra) = match &d {
|
||||
Decision::Allow(w) => ("allow", w.clone(), json!({"action": "continue"})),
|
||||
Decision::Deny(w) => (
|
||||
"deny",
|
||||
w.clone(),
|
||||
// soft: the agent reads the reason and picks another way (orch does not kill the run)
|
||||
json!({"action": "block", "reason": if pol.soft_continue {
|
||||
format!("{SOFT_PREFIX} {w}. Use another way (allowed: read-only commands, project tests).")
|
||||
} else {
|
||||
format!("{PREFIX} {w}")
|
||||
}}),
|
||||
),
|
||||
Decision::Hard(w) => (
|
||||
"deny",
|
||||
w.clone(),
|
||||
json!({"action": "block", "reason": format!("{PREFIX} {w}")}),
|
||||
@@ -418,7 +452,8 @@ pub fn guard(policy_file: &Path) -> Result<()> {
|
||||
&pol.audit,
|
||||
&pol.run,
|
||||
"tool",
|
||||
json!({"tool": tool, "decision": act, "why": why, "args": e["args"]}),
|
||||
json!({"tool": tool, "decision": act, "why": why, "args": e["args"],
|
||||
"hard": matches!(d, Decision::Hard(_))}),
|
||||
);
|
||||
Ok(extra)
|
||||
}
|
||||
@@ -439,6 +474,11 @@ mod tests {
|
||||
use super::*;
|
||||
use Decision::*;
|
||||
|
||||
/// Denied, soft or hard.
|
||||
fn denied(d: Decision) -> bool {
|
||||
d.deny_reason().is_some()
|
||||
}
|
||||
|
||||
fn pol(allow: &[&str]) -> Policy {
|
||||
let d = std::env::temp_dir().join(format!("orch-pol-{}", std::process::id()));
|
||||
std::fs::create_dir_all(d.join("wt/sub")).unwrap();
|
||||
@@ -448,6 +488,7 @@ mod tests {
|
||||
worktree: d.join("wt").canonicalize().unwrap(),
|
||||
read_roots: vec![],
|
||||
audit: d.join("audit"),
|
||||
soft_continue: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -482,13 +523,10 @@ mod tests {
|
||||
Allow(_)
|
||||
));
|
||||
assert!(
|
||||
matches!(p.decide("write", &json!({"path": "a.rs"})), Deny(_)),
|
||||
denied(p.decide("write", &json!({"path": "a.rs"}))),
|
||||
"not in allowlist"
|
||||
);
|
||||
assert!(matches!(
|
||||
p.decide("bash", &json!({"command": "ls"})),
|
||||
Deny(_)
|
||||
));
|
||||
assert!(denied(p.decide("bash", &json!({"command": "ls"}))));
|
||||
assert!(matches!(
|
||||
pol(&["*"]).decide("anything", &json!({})),
|
||||
Allow(_)
|
||||
@@ -506,10 +544,7 @@ mod tests {
|
||||
".env",
|
||||
"sub/auth.json",
|
||||
] {
|
||||
assert!(
|
||||
matches!(p.decide("write", &json!({"path": bad})), Deny(_)),
|
||||
"{bad}"
|
||||
);
|
||||
assert!(denied(p.decide("write", &json!({"path": bad}))), "{bad}");
|
||||
}
|
||||
for bad in [
|
||||
"/etc/passwd",
|
||||
@@ -517,20 +552,14 @@ mod tests {
|
||||
"/home/other/.hx/auth.json",
|
||||
".ssh/id_rsa",
|
||||
] {
|
||||
assert!(
|
||||
matches!(p.decide("read", &json!({"path": bad})), Deny(_)),
|
||||
"{bad}"
|
||||
);
|
||||
assert!(denied(p.decide("read", &json!({"path": bad}))), "{bad}");
|
||||
}
|
||||
for bad in [
|
||||
".git/hooks/pre-commit",
|
||||
".hx/config.toml",
|
||||
"sub/../.hx/config.toml",
|
||||
] {
|
||||
assert!(
|
||||
matches!(p.decide("edit", &json!({"path": bad})), Deny(_)),
|
||||
"{bad}"
|
||||
);
|
||||
assert!(denied(p.decide("edit", &json!({"path": bad}))), "{bad}");
|
||||
}
|
||||
assert!(matches!(
|
||||
p.decide("read", &json!({"path": format!("{w}/a")})),
|
||||
@@ -538,10 +567,45 @@ mod tests {
|
||||
));
|
||||
// symlink out of the worktree is resolved
|
||||
std::os::unix::fs::symlink("/etc", p.worktree.join("lnk")).ok();
|
||||
assert!(denied(p.decide("read", &json!({"path": "lnk/passwd"}))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hard_and_soft_denies() {
|
||||
let p = pol(&["read", "bash:cargo *"]);
|
||||
let d = |t: &str, a: Value| p.decide(t, &a);
|
||||
// soft: simply not allowed, the agent may try something else
|
||||
assert!(matches!(d("bash", json!({"command": "ls"})), Deny(_)));
|
||||
assert!(matches!(
|
||||
p.decide("read", &json!({"path": "lnk/passwd"})),
|
||||
d("bash", json!({"command": "python3 -c 'print(1)'"})),
|
||||
Deny(_)
|
||||
));
|
||||
assert!(matches!(d("write", json!({"path": "a.rs"})), Deny(_)));
|
||||
assert!(matches!(d("Foo", json!({})), Deny(_)));
|
||||
// hard: never negotiable
|
||||
assert!(matches!(d("read", json!({"path": ".env"})), Hard(_)));
|
||||
assert!(matches!(d("read", json!({"path": "/etc/passwd"})), Hard(_)));
|
||||
assert!(matches!(
|
||||
d("bash", json!({"command": "git push origin main"})),
|
||||
Hard(_)
|
||||
));
|
||||
assert!(matches!(d("bash", json!({"command": "cat .env"})), Hard(_)));
|
||||
assert!(matches!(
|
||||
d("bash", json!({"command": "cargo run ../../x"})),
|
||||
Hard(_)
|
||||
));
|
||||
let w = pol(&["*"]);
|
||||
assert!(matches!(
|
||||
w.decide("edit", &json!({"path": ".hx/config.toml"})),
|
||||
Hard(_)
|
||||
));
|
||||
assert!(matches!(
|
||||
w.decide("write", &json!({"path": "../x"})),
|
||||
Hard(_)
|
||||
));
|
||||
assert!(
|
||||
Deny("x".into()).deny_reason().is_some() && Allow("x".into()).deny_reason().is_none()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -605,12 +669,11 @@ mod tests {
|
||||
"",
|
||||
" ",
|
||||
] {
|
||||
assert!(matches!(b(bad), Deny(_)), "{bad}");
|
||||
assert!(denied(b(bad)), "{bad}");
|
||||
}
|
||||
// without the entry the same command is denied; patterns and `readonly` combine
|
||||
assert!(matches!(
|
||||
pol(&["read"]).decide("bash", &json!({"command": "ls"})),
|
||||
Deny(_)
|
||||
assert!(denied(
|
||||
pol(&["read"]).decide("bash", &json!({"command": "ls"}))
|
||||
));
|
||||
let both = pol(&["readonly", "bash:cargo *"]);
|
||||
assert!(
|
||||
@@ -620,7 +683,7 @@ mod tests {
|
||||
matches!(both.decide("bash", &json!({"command": "ls"})), Allow(w) if w == "readonly")
|
||||
);
|
||||
// readonly does not make write tools available
|
||||
assert!(matches!(p.decide("write", &json!({"path": "a"})), Deny(_)));
|
||||
assert!(denied(p.decide("write", &json!({"path": "a"}))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -640,7 +703,7 @@ mod tests {
|
||||
"cargo run ../../x",
|
||||
"cargo run ~/x",
|
||||
] {
|
||||
assert!(matches!(b(bad), Deny(_)), "{bad}");
|
||||
assert!(denied(b(bad)), "{bad}");
|
||||
}
|
||||
assert!(matches!(
|
||||
b("cargo build --manifest-path=sub/Cargo.toml"),
|
||||
@@ -657,7 +720,7 @@ mod tests {
|
||||
"cat .env",
|
||||
"cat ~/.ssh/id_rsa",
|
||||
] {
|
||||
assert!(matches!(f(bad), Deny(_)), "{bad}");
|
||||
assert!(denied(f(bad)), "{bad}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,14 @@ pub struct Budget {
|
||||
pub max_tokens: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum OnDeny {
|
||||
#[default]
|
||||
Stop,
|
||||
Continue,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug, Clone)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Profile {
|
||||
@@ -38,6 +46,11 @@ pub struct Profile {
|
||||
/// Present = enforced by `orch guard` inside hx and re-checked on the event stream; a denied call ends
|
||||
/// the run as needs-human.
|
||||
pub allow: Option<Vec<String>>,
|
||||
/// What a denied tool call does: `stop` (default) ends the run as needs-human; `continue` answers the agent with
|
||||
/// the reason so it can pick another way. Credentials, paths outside the worktree, `git push` and `.git`/`.hx`
|
||||
/// always stop. Every deny is audited and counted (`denies` in the run and in telemetry).
|
||||
#[serde(default)]
|
||||
pub on_deny: OnDeny,
|
||||
/// Extra directories the agent may read besides the worktree.
|
||||
#[serde(default)]
|
||||
pub read_roots: Vec<PathBuf>,
|
||||
@@ -135,6 +148,16 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn on_deny_parses() {
|
||||
assert_eq!(Profile::parse("").unwrap().on_deny, OnDeny::Stop);
|
||||
assert_eq!(
|
||||
Profile::parse("on_deny = \"continue\"").unwrap().on_deny,
|
||||
OnDeny::Continue
|
||||
);
|
||||
assert!(Profile::parse("on_deny = \"ignore\"").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn allowlist_validated() {
|
||||
assert!(Profile::parse("allow = [\"read\", \"bash:cargo *\"]").is_ok());
|
||||
|
||||
+11
-2
@@ -31,6 +31,9 @@ pub struct Rec {
|
||||
pub cache_read_tokens: u64,
|
||||
#[serde(default)]
|
||||
pub cache_write_tokens: u64,
|
||||
/// Tool calls the allowlist denied in this run.
|
||||
#[serde(default)]
|
||||
pub denies: u32,
|
||||
pub seconds: u64,
|
||||
}
|
||||
|
||||
@@ -115,6 +118,7 @@ pub fn rec(r: &crate::state::Run, hx_version: &str, mode: &str) -> Rec {
|
||||
output_tokens: r.output_tokens,
|
||||
cache_read_tokens: r.cache_read_tokens,
|
||||
cache_write_tokens: r.cache_write_tokens,
|
||||
denies: r.denies,
|
||||
seconds: r
|
||||
.ended
|
||||
.unwrap_or_else(crate::state::now)
|
||||
@@ -192,6 +196,7 @@ pub struct Agg {
|
||||
pub retries: u64,
|
||||
pub tokens: u64,
|
||||
pub tokens_done: u64,
|
||||
pub denies: u64,
|
||||
pub cache_read: u64,
|
||||
pub input_all: u64,
|
||||
pub secs: Vec<u64>,
|
||||
@@ -212,6 +217,7 @@ impl Agg {
|
||||
}
|
||||
_ => self.failed += 1,
|
||||
}
|
||||
self.denies += u64::from(r.denies);
|
||||
self.cache_read += r.cache_read_tokens;
|
||||
self.input_all += r.input_all();
|
||||
self.retries += u64::from(r.attempts.saturating_sub(1));
|
||||
@@ -259,7 +265,7 @@ fn pct(v: Option<f64>) -> String {
|
||||
|
||||
pub fn report(recs: &[Rec]) -> String {
|
||||
let mut out = format!(
|
||||
"{:<14} {:<22} {:<10} {:>5} {:>5} {:>5} {:>6} {:>6} {:>6} {:>8} {:>9} {:>6} {:>6}\n",
|
||||
"{:<14} {:<22} {:<10} {:>5} {:>5} {:>5} {:>6} {:>6} {:>6} {:>8} {:>9} {:>6} {:>6} {:>6}\n",
|
||||
"profile",
|
||||
"hx-version",
|
||||
"mode",
|
||||
@@ -272,11 +278,12 @@ pub fn report(recs: &[Rec]) -> String {
|
||||
"tok/run",
|
||||
"tok/done",
|
||||
"cache",
|
||||
"denies",
|
||||
"med-s"
|
||||
);
|
||||
let mut line = |a: &str, b: &str, m: &str, g: &Agg| {
|
||||
out.push_str(&format!(
|
||||
"{:<14} {:<22} {:<10} {:>5} {:>5} {:>5} {:>6} {:>6} {:>6} {:>8} {:>9} {:>6} {:>6}\n",
|
||||
"{:<14} {:<22} {:<10} {:>5} {:>5} {:>5} {:>6} {:>6} {:>6} {:>8} {:>9} {:>6} {:>6} {:>6}\n",
|
||||
a,
|
||||
b,
|
||||
m,
|
||||
@@ -289,6 +296,7 @@ pub fn report(recs: &[Rec]) -> String {
|
||||
n(g.tok_per_run()),
|
||||
n(g.tok_per_done()),
|
||||
pct(g.cache_pct()),
|
||||
g.denies,
|
||||
n(g.median_secs())
|
||||
));
|
||||
};
|
||||
@@ -483,6 +491,7 @@ mod tests {
|
||||
output_tokens: 0,
|
||||
cache_read_tokens: 0,
|
||||
cache_write_tokens: 0,
|
||||
denies: 0,
|
||||
seconds: secs,
|
||||
}
|
||||
}
|
||||
|
||||
+71
-27
@@ -3,7 +3,7 @@
|
||||
use crate::adapter::Task;
|
||||
use crate::lock;
|
||||
use crate::policy::{self, Decision, Policy};
|
||||
use crate::profile::Profile;
|
||||
use crate::profile::{OnDeny, Profile};
|
||||
use crate::state::{Run, Status, gate_log_path, kill_group, log_path, now};
|
||||
use anyhow::{Context, Result, bail};
|
||||
use serde_json::Value;
|
||||
@@ -71,6 +71,7 @@ pub fn new_run(task: &Task, repo: &Path, profile: &str) -> Result<Run> {
|
||||
attempts: 0,
|
||||
turns: 0,
|
||||
spent_tokens: 0,
|
||||
denies: 0,
|
||||
published: None,
|
||||
quota_until: None,
|
||||
})
|
||||
@@ -100,16 +101,15 @@ pub fn hx_env(vars: impl Iterator<Item = (String, String)>, p: &Profile) -> Vec<
|
||||
|
||||
/// All tokens of one hx usage object. hx reports `input_tokens` as the uncached part only, so cached input
|
||||
/// (`cache_read_tokens`, `cache_write_tokens`) has to be added or the count is off by orders of magnitude.
|
||||
const USAGE_KEYS: [&str; 4] = [
|
||||
"input_tokens",
|
||||
"output_tokens",
|
||||
"cache_read_tokens",
|
||||
"cache_write_tokens",
|
||||
];
|
||||
|
||||
fn usage_total(u: &Value) -> u64 {
|
||||
[
|
||||
"input_tokens",
|
||||
"output_tokens",
|
||||
"cache_read_tokens",
|
||||
"cache_write_tokens",
|
||||
]
|
||||
.iter()
|
||||
.map(|k| u[*k].as_u64().unwrap_or(0))
|
||||
.sum()
|
||||
USAGE_KEYS.iter().map(|k| u[*k].as_u64().unwrap_or(0)).sum()
|
||||
}
|
||||
|
||||
/// The line hx' claude_cli provider writes into the text stream for every tool claude runs: `\n[claude Bash: ls]\n`.
|
||||
@@ -183,11 +183,15 @@ pub fn execute(r: &mut Run, p: &Profile, task: &Task) -> Result<()> {
|
||||
r.save()?;
|
||||
writeln!(log, "\n--- attempt {}", r.attempts)?;
|
||||
// rewritten before every attempt: an agent that tampered with it is healed
|
||||
let pol = match p
|
||||
.allow
|
||||
.as_ref()
|
||||
.map(|a| policy::install(&r.id, &r.worktree, a, &p.read_roots))
|
||||
{
|
||||
let pol = match p.allow.as_ref().map(|a| {
|
||||
policy::install(
|
||||
&r.id,
|
||||
&r.worktree,
|
||||
a,
|
||||
&p.read_roots,
|
||||
p.on_deny == OnDeny::Continue,
|
||||
)
|
||||
}) {
|
||||
Some(Err(e)) => return fail(r, format!("setup: {e:#}")),
|
||||
Some(Ok(pol)) => Some(pol),
|
||||
None => None,
|
||||
@@ -309,9 +313,13 @@ fn run_hx(
|
||||
|
||||
let deadline = Instant::now() + Duration::from_secs(p.wall_secs());
|
||||
let mut done = None::<Value>;
|
||||
// usage per component from the stream `done` events of THIS attempt: the final `done` line never comes when
|
||||
// the run is stopped (guard, budget, timeout), and those runs would otherwise report 0 tokens
|
||||
let mut seen = [0u64; 4];
|
||||
// claude_cli: claude runs the tools; hx prints a `[claude TOOL: ...]` line per tool use and (hx#182) reports
|
||||
// each one as a tool_call event so the guard can decide. Fewer events than lines = something ran unseen.
|
||||
let (mut claude_lines, mut calls) = (0u32, 0u32);
|
||||
let mut seen_ids = std::collections::HashSet::<String>::new();
|
||||
let mut killed = None;
|
||||
loop {
|
||||
let left = deadline.saturating_duration_since(Instant::now());
|
||||
@@ -339,27 +347,54 @@ fn run_hx(
|
||||
}
|
||||
Some("tool_call") if pol.is_some() => {
|
||||
calls += 1;
|
||||
seen_ids.insert(ev["id"].as_str().unwrap_or_default().to_string());
|
||||
// second line of defence: hx treats a dead or slow guard as "continue"
|
||||
let name = ev["name"].as_str().unwrap_or_default();
|
||||
if let Decision::Deny(why) = pol.unwrap().decide(name, &ev["args"]) {
|
||||
// the guard may not have logged yet (we read the event first): log it here too
|
||||
policy::audit(
|
||||
&policy::audit_path(),
|
||||
&r.id,
|
||||
"tool",
|
||||
serde_json::json!({"tool": name, "decision": "deny", "why": why, "args": ev["args"], "by": "orch"}),
|
||||
);
|
||||
killed = Some(format!("policy: {why}"));
|
||||
let d = pol.unwrap().decide(name, &ev["args"]);
|
||||
// soft denies under on_deny=continue are answered by the guard (the tool never runs);
|
||||
// everything else is a reason to stop the run
|
||||
let stop = match &d {
|
||||
Decision::Hard(_) => true,
|
||||
Decision::Deny(_) => p.on_deny == OnDeny::Stop,
|
||||
Decision::Allow(_) => false,
|
||||
};
|
||||
if let Some(why) = d.deny_reason() {
|
||||
r.denies += 1;
|
||||
if stop {
|
||||
// the guard may not have logged yet (we read the event first): log it here too
|
||||
policy::audit(
|
||||
&policy::audit_path(),
|
||||
&r.id,
|
||||
"tool",
|
||||
serde_json::json!({"tool": name, "decision": "deny", "why": why, "args": ev["args"], "by": "orch"}),
|
||||
);
|
||||
killed = Some(format!("policy: {why}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
Some("tool_result")
|
||||
if pol.is_some()
|
||||
&& ev["is_error"] == true
|
||||
&& ev["content"].to_string().contains(policy::PREFIX) =>
|
||||
&& (ev["content"].to_string().contains(policy::PREFIX)
|
||||
|| ev["content"].to_string().contains(policy::SOFT_PREFIX)) =>
|
||||
{
|
||||
let c = ev["content"].as_str().unwrap_or_default();
|
||||
let why = c.split_once(policy::PREFIX).map_or(c, |(_, w)| w.trim());
|
||||
killed = Some(format!("policy: {why}"));
|
||||
if c.contains(policy::SOFT_PREFIX) {
|
||||
// soft deny answered to the agent (on_deny = continue): the guard saw the call even
|
||||
// though no tool_call line reached this stream; count it, keep the run going
|
||||
if !seen_ids.contains(ev["id"].as_str().unwrap_or_default()) {
|
||||
calls += 1;
|
||||
r.denies += 1;
|
||||
}
|
||||
} else {
|
||||
// hard (or `stop`-mode) deny: counted unless the tool_call event of the same id was
|
||||
// already evaluated by the stream check above
|
||||
if !seen_ids.contains(ev["id"].as_str().unwrap_or_default()) {
|
||||
r.denies += 1;
|
||||
}
|
||||
let why = c.split_once(policy::PREFIX).map_or(c, |(_, w)| w.trim());
|
||||
killed = Some(format!("policy: {why}"));
|
||||
}
|
||||
}
|
||||
Some("stream") if ev["event"]["type"] == "quota" => {
|
||||
let full: Vec<&Value> = ev["event"]["windows"]
|
||||
@@ -377,6 +412,9 @@ fn run_hx(
|
||||
}
|
||||
Some("stream") if ev["event"]["type"] == "done" => {
|
||||
let u = &ev["event"]["usage"];
|
||||
for (s, k) in seen.iter_mut().zip(USAGE_KEYS) {
|
||||
*s += u[k].as_u64().unwrap_or(0);
|
||||
}
|
||||
r.spent_tokens += usage_total(u);
|
||||
if p.budget.max_tokens.is_some_and(|m| r.spent_tokens > m) {
|
||||
killed = Some("budget:tokens".to_string());
|
||||
@@ -411,6 +449,12 @@ fn run_hx(
|
||||
r.cache_read_tokens = f("cache_read_tokens");
|
||||
r.cache_write_tokens = f("cache_write_tokens");
|
||||
r.session = d["session"].as_str().map(String::from);
|
||||
} else {
|
||||
// killed before the final `done`: keep what the stream reported (a lower bound, never less than before)
|
||||
r.input_tokens = r.input_tokens.max(seen[0]);
|
||||
r.output_tokens = r.output_tokens.max(seen[1]);
|
||||
r.cache_read_tokens = r.cache_read_tokens.max(seen[2]);
|
||||
r.cache_write_tokens = r.cache_write_tokens.max(seen[3]);
|
||||
}
|
||||
if let Some(k) = killed {
|
||||
return Ok(Some(k));
|
||||
|
||||
@@ -68,6 +68,9 @@ pub struct Run {
|
||||
pub turns: u64,
|
||||
#[serde(default)]
|
||||
pub spent_tokens: u64,
|
||||
/// Tool calls the policy denied (soft denies that the agent got to answer, plus the one that stopped the run).
|
||||
#[serde(default)]
|
||||
pub denies: u32,
|
||||
/// Sink result (PR URL, branch note) once published.
|
||||
#[serde(default)]
|
||||
pub published: Option<String>,
|
||||
@@ -187,6 +190,7 @@ mod tests {
|
||||
attempts: 0,
|
||||
turns: 0,
|
||||
spent_tokens: 0,
|
||||
denies: 0,
|
||||
published: None,
|
||||
quota_until: None,
|
||||
}
|
||||
|
||||
@@ -257,6 +257,36 @@ for name, call in [("ro-exec", "CALL bash find . -exec rm {} +"), ("ro-rm", "CAL
|
||||
("ro-secret", "CALL bash cat .env"), ("ro-out", "CALL bash ls /etc")]:
|
||||
check(run(name, "ro", env=senv, body=call), "needs-human", "policy:")
|
||||
|
||||
# --- on_deny = "continue": soft denies are answered, the run goes on; hard denies still stop it ---
|
||||
profile("soft", f'home = "{work_home}"\nallow = ["readonly", "write"]\non_deny = "continue"\n')
|
||||
# the agent tries a forbidden command, gets the reason, then does the allowed thing
|
||||
s = check(run("soft-ok", "soft", env=senv, body="CALL bash python3 -c 'print(1)'\nCALL bash ls\nCALL write a.txt"), "done")
|
||||
calls = git_show(s["branch"], "calls.txt")
|
||||
assert "RAN ls" in calls and "WROTE a.txt" in calls and "python3" not in calls, calls # the denied call never ran
|
||||
assert s["denies"] == 1, s
|
||||
assert not (tmp / "state/worktrees" / s["id"] / ".hx").exists()
|
||||
# the soft reason reaches the agent and says to use another way
|
||||
rows = [json.loads(l) for l in subprocess.run([orch, "audit", s["id"]], env=env, capture_output=True, text=True).stdout.splitlines()]
|
||||
assert [r["detail"]["decision"] for r in rows if r["ev"] == "tool"] == ["deny", "allow", "allow"], rows
|
||||
assert "orch-guard-soft:" in (tmp / "state/runs" / (s["id"] + ".log")).read_text()
|
||||
# hard denies stop the run even with on_deny = continue
|
||||
s = check(run("soft-hard", "soft", env=senv, body=f"CALL bash python3 -c 'x'\nCALL read {private}/auth.json\nCALL write b.txt"), "needs-human", "policy:")
|
||||
assert s["denies"] == 2 and "WROTE b.txt" not in git_show(s["branch"], "calls.txt"), s # stopped at the credential read
|
||||
assert "PRIVATE-TOKEN-123" not in git_show(s["branch"], "calls.txt")
|
||||
for name, call in [("soft-push", "CALL bash git push origin main"), ("soft-meta", "CALL write .hx/config.toml"), ("soft-out", "CALL bash ls /etc")]:
|
||||
check(run(name, "soft", env=senv, body=call), "needs-human", "policy:")
|
||||
# default stop: the first soft deny ends the run (unchanged)
|
||||
s = check(run("stop-default", "ro", env=senv, body="CALL bash python3 -c 'print(1)'\nCALL write a.txt"), "needs-human", "policy:")
|
||||
assert s["denies"] == 1 and "a.txt" not in git_show(s["branch"], "calls.txt"), s
|
||||
# direct provider only emits the tool_call: soft deny with the stream check alone (NOGUARD) must not kill the run
|
||||
check(run("soft-noguard", "soft", env=senv, body="NOGUARD\nCALL bash python3 -c 'print(1)'\nCALL write a.txt"), "done")
|
||||
|
||||
# --- tokens of a run that is stopped before hx prints its final `done` line are kept ---
|
||||
tel_now = [json.loads(l) for l in (tmp / "state/telemetry.jsonl").read_text().splitlines() if l.strip()]
|
||||
stopped = next(r for r in reversed(tel_now) if r["task"] == "stop-default")
|
||||
assert stopped["status"] == "needs-human" and stopped["input_tokens"] == 100 and stopped["cache_read_tokens"] == 1000, stopped
|
||||
assert stopped["denies"] == 1, stopped
|
||||
|
||||
# the guard process alone (no orch kill racing it): block / continue over the extension protocol
|
||||
gwt = tmp / "gwt"
|
||||
gwt.mkdir()
|
||||
|
||||
+45
-23
@@ -10,37 +10,59 @@ if "--version" in sys.argv:
|
||||
open(os.environ.get("FAKE_CLAUDE_LOG", "/dev/null"), "a").write(json.dumps(sys.argv[1:]) + "\n")
|
||||
out = lambda o: print(json.dumps(o), flush=True)
|
||||
out({"type": "system", "subtype": "init", "session_id": "S1"})
|
||||
if os.environ.get("FAKE_CLAUDE_READ"):
|
||||
# like claude with --permission-prompt-tool: ask hx first, run the tool only when allowed
|
||||
import subprocess
|
||||
target = os.environ["FAKE_CLAUDE_READ"]
|
||||
answer = {"behavior": "allow"}
|
||||
if "--permission-prompt-tool" in sys.argv and not os.environ.get("FAKE_CLAUDE_NOASK"):
|
||||
import subprocess
|
||||
|
||||
_bridge = {}
|
||||
|
||||
|
||||
def ask(tool, inp, tid):
|
||||
"""Ask hx whether `tool` may run (like claude with --permission-prompt-tool); returns the answer dict."""
|
||||
if "--permission-prompt-tool" not in sys.argv or os.environ.get("FAKE_CLAUDE_NOASK"):
|
||||
return {"behavior": "allow"}
|
||||
if not _bridge:
|
||||
cfg = json.loads(sys.argv[sys.argv.index("--mcp-config") + 1])["mcpServers"]["hx"]
|
||||
pr = subprocess.Popen([cfg["command"], *cfg["args"]], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True,
|
||||
env={**os.environ, **cfg["env"]})
|
||||
_bridge["p"] = subprocess.Popen([cfg["command"], *cfg["args"]], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
||||
text=True, env={**os.environ, **cfg["env"]})
|
||||
_bridge["n"] = 0
|
||||
send("initialize", {})
|
||||
_bridge["p"].stdout.readline()
|
||||
send("tools/call", {"name": "approve", "arguments": {"tool_name": tool, "input": inp, "tool_use_id": tid}})
|
||||
return json.loads(json.loads(_bridge["p"].stdout.readline())["result"]["content"][0]["text"])
|
||||
|
||||
def rpc(i, m, p):
|
||||
pr.stdin.write(json.dumps({"jsonrpc": "2.0", "id": i, "method": m, "params": p}) + "\n")
|
||||
pr.stdin.flush() # (a lambda `write(..) or flush()` never reaches flush: write returns a truthy count)
|
||||
|
||||
rpc(1, "initialize", {})
|
||||
pr.stdout.readline()
|
||||
rpc(2, "tools/call", {"name": "approve", "arguments": {"tool_name": "Read", "input": {"file_path": target}, "tool_use_id": "t1"}})
|
||||
answer = json.loads(json.loads(pr.stdout.readline())["result"]["content"][0]["text"])
|
||||
pr.stdin.close()
|
||||
out({"type": "assistant", "session_id": "S1", "message": {"content": [
|
||||
{"type": "tool_use", "id": "t1", "name": "Read", "input": {"file_path": target}}]}})
|
||||
def send(method, params):
|
||||
_bridge["n"] = _bridge.get("n", 0) + 1
|
||||
_bridge["p"].stdin.write(json.dumps({"jsonrpc": "2.0", "id": _bridge["n"], "method": method, "params": params}) + "\n")
|
||||
_bridge["p"].stdin.flush() # (a lambda `write(..) or flush()` never reaches flush: write returns a truthy count)
|
||||
|
||||
|
||||
def tool(tid, name, inp, run):
|
||||
"""One tool use: ask, announce, run only when allowed, report the result."""
|
||||
answer = ask(name, inp, tid)
|
||||
out({"type": "assistant", "session_id": "S1", "message": {"content": [{"type": "tool_use", "id": tid, "name": name, "input": inp}]}})
|
||||
if answer["behavior"] == "allow":
|
||||
res, err = run(), False
|
||||
else:
|
||||
res, err = "deny: " + answer.get("message", ""), True
|
||||
out({"type": "user", "session_id": "S1", "message": {"content": [
|
||||
{"type": "tool_result", "tool_use_id": tid, "content": res, "is_error": err}]}})
|
||||
return not err
|
||||
|
||||
|
||||
if os.environ.get("FAKE_CLAUDE_BASH"): # first a Bash call (may be denied softly), then a Read of $FAKE_CLAUDE_READ
|
||||
cmd = os.environ["FAKE_CLAUDE_BASH"]
|
||||
tool("b1", "Bash", {"command": cmd}, lambda: subprocess.run(cmd, shell=True, capture_output=True, text=True).stdout)
|
||||
elif os.environ.get("FAKE_CLAUDE_READ"):
|
||||
target = os.environ["FAKE_CLAUDE_READ"]
|
||||
|
||||
def read():
|
||||
try:
|
||||
seen = open(target).read()
|
||||
except OSError as e:
|
||||
seen = "ERR " + str(e)
|
||||
open("claude-read.txt", "w").write(seen)
|
||||
res, err = seen, False
|
||||
else:
|
||||
res, err = "deny: " + answer.get("message", ""), True
|
||||
out({"type": "user", "session_id": "S1", "message": {"content": [
|
||||
{"type": "tool_result", "tool_use_id": "t1", "content": res, "is_error": err}]}})
|
||||
return seen
|
||||
|
||||
tool("t1", "Read", {"file_path": target}, read)
|
||||
out({"type": "stream_event", "session_id": "S1", "event": {"type": "content_block_delta", "delta": {"type": "text_delta", "text": "done"}}})
|
||||
out({"type": "result", "session_id": "S1", "is_error": False, "result": "done", "usage": {"input_tokens": 3, "output_tokens": 4}})
|
||||
@@ -18,6 +18,9 @@ def guard(name, args):
|
||||
ext.stdout.readline()
|
||||
ext.stdin.write(json.dumps({"jsonrpc": "2.0", "id": 2, "method": "event", "params": {"event": {"type": "tool_call", "name": name, "args": args}}}) + "\n"); ext.stdin.flush()
|
||||
return json.loads(ext.stdout.readline())["result"]
|
||||
if "CALL " in body: # a model turn that ends in tool calls is one request: its usage is streamed right away
|
||||
e({"type": "turn_start"})
|
||||
e({"type": "stream", "event": {"type": "done", "usage": {"input_tokens": 100, "output_tokens": 50, "cache_read_tokens": 1000, "cache_write_tokens": 10}}})
|
||||
for n, l in enumerate(x for x in body.splitlines() if x.startswith("CALL ")):
|
||||
_, name, arg = l.split(" ", 2)
|
||||
args = {"command": arg} if name == "bash" else {"path": arg}
|
||||
|
||||
+20
-1
@@ -55,7 +55,7 @@ try:
|
||||
shutil.copy(root / "tests/fake_claude.py", tmp / "claude")
|
||||
os.chmod(tmp / "claude", 0o755)
|
||||
(home / ".hx/config.toml").write_text("claude_cli = []\n") # the profile's own home turns the provider on
|
||||
cenv = '["HX_BASE_URL", "HX_CLAUDE_BIN", "FAKE_CLAUDE_READ", "FAKE_CLAUDE_LOG", "FAKE_CLAUDE_NOASK"]'
|
||||
cenv = '["HX_BASE_URL", "HX_CLAUDE_BIN", "FAKE_CLAUDE_READ", "FAKE_CLAUDE_LOG", "FAKE_CLAUDE_NOASK", "FAKE_CLAUDE_BASH"]'
|
||||
(cfg / "guarded.toml").write_text(f'hx = "{hx}"\nhome = "{home}"\nenv = {cenv}\nallow = ["write"]\n')
|
||||
(cfg / "open.toml").write_text(f'hx = "{hx}"\nhome = "{home}"\nenv = {cenv}\n')
|
||||
cenv_vars = {**env, "HX_CLAUDE_BIN": str(tmp / "claude"), "FAKE_CLAUDE_READ": str(secret), "FAKE_CLAUDE_LOG": str(tmp / "argv.log")}
|
||||
@@ -100,6 +100,25 @@ try:
|
||||
|
||||
assert dead_run("") == "PRIVATE-TOKEN-123", "control: a dead guard without extensions-only lets the read through"
|
||||
assert dead_run('permissions = "extensions-only"\n') is None, "extensions-only must deny when the guard is dead"
|
||||
# on_deny = "continue" against the real hx bridge: a soft deny is answered to claude (tool does not run) and the run
|
||||
# goes on; the fake claude then asks for a second tool, which is allowed
|
||||
(cfg / "soft.toml").write_text(f'hx = "{hx}"\nhome = "{home}"\nenv = {cenv}\nallow = ["read"]\non_deny = "continue"\n')
|
||||
cenv_vars["FAKE_CLAUDE_BASH"] = "ls"
|
||||
st, seen, p = go("soft", "soft1")
|
||||
del cenv_vars["FAKE_CLAUDE_BASH"]
|
||||
assert st["status"] == "done" and st["denies"] == 1, (st, p.stdout, p.stderr)
|
||||
# the denied `ls` never ran; the same command is allowed once the profile has `readonly`
|
||||
(cfg / "soft2.toml").write_text(f'hx = "{hx}"\nhome = "{home}"\nenv = {cenv}\nallow = ["readonly"]\non_deny = "continue"\n')
|
||||
cenv_vars["FAKE_CLAUDE_BASH"] = "ls"
|
||||
st, seen, p = go("soft2", "soft2")
|
||||
del cenv_vars["FAKE_CLAUDE_BASH"]
|
||||
assert st["status"] == "done" and st["denies"] == 0, (st, p.stdout, p.stderr)
|
||||
# default on_deny (stop): the same soft deny ends the run
|
||||
(cfg / "stop.toml").write_text(f'hx = "{hx}"\nhome = "{home}"\nenv = {cenv}\nallow = ["read"]\n')
|
||||
cenv_vars["FAKE_CLAUDE_BASH"] = "ls"
|
||||
st, seen, p = go("stop", "stop1")
|
||||
del cenv_vars["FAKE_CLAUDE_BASH"]
|
||||
assert st["status"] == "needs-human" and st["reason"].startswith("policy:") and st["denies"] >= 1, (st, p.stdout, p.stderr)
|
||||
# claude that never asks hx (flags ignored): hx still reports the tool via claude's tool result, so orch's own
|
||||
# stream check sees it. The tool ran already (after the fact), but the run is not called clean.
|
||||
cenv_vars["FAKE_CLAUDE_NOASK"] = "1"
|
||||
|
||||
Reference in new issue
Block a user