Allowlist: readonly entry, on_deny = continue, tokens of stopped runs (#20)

This commit was merged in pull request #20.
This commit is contained in:
hermes committed 2026-11-14 12:54:15 +00:00
1 parent 9ce4756fad
commit 39a2e74742
11 files changed
+487 -89

No files matched your search

+71 -27
View File
@@ -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));