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

+259 -35
View File
@@ -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.
@@ -126,6 +143,80 @@ fn resolve(base: &Path, p: &str) -> PathBuf {
}
}
/// Allowlist entry `readonly`: bash commands that only look. Spelled out in code instead of glob patterns because
/// the dangerous part is the flags (`find -exec`, `rg --pre`, `sort -o`, `fd -x`), which a pattern cannot see.
pub const READONLY: &str = "readonly";
const READONLY_CMDS: &[&str] = &[
"ls", "cat", "head", "tail", "wc", "grep", "rg", "fd", "find", "pwd", "echo", "stat", "file",
"du", "df", "which", "tree", "diff", "sort", "cut", "nl", "tr", "jq", "basename", "dirname",
];
const READONLY_GIT: &[&str] = &[
"status",
"diff",
"log",
"show",
"blame",
"ls-files",
"rev-parse",
];
/// Flags that run a program or write a file, per command (`*` = any command).
const RUN_OR_WRITE_FLAGS: &[(&str, &[&str])] = &[
(
"find",
&[
"-exec", "-execdir", "-ok", "-okdir", "-delete", "-fprint", "-fprint0", "-fprintf",
"-fls",
],
),
("fd", &["-x", "-X", "--exec", "--exec-batch"]),
("rg", &["--pre", "--pre-glob"]),
("sort", &["-o", "--output", "--compress-program"]),
("tree", &["-o"]),
(
"git",
&[
"--output",
"--ext-diff",
"--textconv",
"-O",
"--open-files-in-pager",
],
),
];
/// Ok when `cmd` is one simple command from the read-only set without a flag that runs or writes anything.
pub fn readonly_cmd(cmd: &str) -> Result<(), String> {
if !simple(cmd) {
return Err("not a simple command".into());
}
let words: Vec<&str> = cmd.split_whitespace().collect();
let Some(first) = words.first().copied() else {
return Err("empty".into());
};
let ok = if first == "git" {
words.get(1).is_some_and(|s| READONLY_GIT.contains(s))
} else {
READONLY_CMDS.contains(&first)
};
if !ok {
return Err(format!("`{first}` is not a read-only command"));
}
let bad = RUN_OR_WRITE_FLAGS
.iter()
.filter(|(c, _)| *c == first)
.flat_map(|(_, f)| f.iter());
for w in &words[1..] {
let flag = w.split_once('=').map_or(*w, |(f, _)| f);
if bad
.clone()
.any(|f| *f == flag || (f.len() > 2 && f.starts_with("--") && flag == *f))
{
return Err(format!("flag `{flag}` runs or writes"));
}
}
Ok(())
}
fn simple(cmd: &str) -> bool {
!cmd.contains([
'\n', ';', '&', '|', '`', '$', '<', '>', '(', ')', '{', '}', '\\',
@@ -163,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
@@ -175,11 +266,18 @@ impl Policy {
if free {
why = Some("bash".to_string());
} else {
let hit = self.allow.iter().find_map(|a| {
let (tl, pat) = a.split_once(':')?;
(tl.eq_ignore_ascii_case("bash") && simple(cmd) && glob(pat, cmd.trim()))
.then_some(a)
});
let hit = self
.allow
.iter()
.find_map(|a| {
let (tl, pat) = a.split_once(':')?;
(tl.eq_ignore_ascii_case("bash") && simple(cmd) && glob(pat, cmd.trim()))
.then(|| a.clone())
})
.or_else(|| {
let on = self.allow.iter().any(|a| a.eq_ignore_ascii_case(READONLY));
(on && readonly_cmd(cmd).is_ok()).then(|| READONLY.to_string())
});
let Some(hit) = hit else {
return Deny(format!("bash `{}` is not in the allowlist", short(cmd)));
};
@@ -190,11 +288,11 @@ 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"));
}
}
}
why = Some(hit.clone());
why = Some(hit);
}
} else if let Some(path) = ["path", "file_path"]
.iter()
@@ -204,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() {
@@ -269,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(),
@@ -279,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())?;
@@ -328,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}")}),
@@ -337,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)
}
@@ -358,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();
@@ -367,6 +488,7 @@ mod tests {
worktree: d.join("wt").canonicalize().unwrap(),
read_roots: vec![],
audit: d.join("audit"),
soft_continue: false,
}
}
@@ -381,6 +503,7 @@ mod tests {
#[test]
fn entries() {
assert!(check_entry("read").is_ok() && check_entry("bash:cargo *").is_ok());
assert!(check_entry("readonly").is_ok() && check_entry("readonly:x").is_err());
assert!(
check_entry("").is_err()
&& check_entry("read:x").is_err()
@@ -400,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(_)
@@ -424,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",
@@ -435,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")})),
@@ -456,10 +567,123 @@ 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]
fn readonly_entry() {
let p = pol(&["readonly", "read"]);
let b = |c: &str| p.decide("bash", &json!({"command": c}));
for ok in [
"ls",
"ls -la sub",
"cat a.rs",
"rg -n -w compute --hidden -g '!.git' -g '!.hx'",
"rg -n \"Instal\" README.md",
"fd -e rs",
"find . -name '*.rs'",
"git status",
"git diff --stat",
"git log --oneline -5",
"head -n 5 a.txt",
"grep -rn foo .",
"wc -l a.rs",
"diff a b",
"sort a.txt",
"jq . a.json",
"tree -L 2",
] {
assert!(matches!(b(ok), Allow(w) if w == "readonly"), "{ok}");
}
for bad in [
"find . -exec rm {} +",
"find . -delete",
"find . -fprint x",
"fd -x rm",
"fd --exec rm",
"rg --pre ./x foo",
"rg --pre=./x foo",
"sort -o out a",
"sort --output=out a",
"tree -o out",
"git push",
"git commit -m x",
"git branch -D x",
"git diff --output=x",
"git -C .. status",
"git diff --ext-diff",
"rm a",
"cp a b",
"sed -i s/a/b/ a",
"python3 -c 'print(1)'",
"python3 test.py",
"cargo test",
"ls; rm a",
"cat a | sh",
"echo hi > a",
"ls $(id)",
"cat .env",
"cat ~/.ssh/id_rsa",
"cat /etc/passwd",
"ls ..",
"ls /",
"head ../../x",
"",
" ",
] {
assert!(denied(b(bad)), "{bad}");
}
// without the entry the same command is denied; patterns and `readonly` combine
assert!(denied(
pol(&["read"]).decide("bash", &json!({"command": "ls"}))
));
let both = pol(&["readonly", "bash:cargo *"]);
assert!(
matches!(both.decide("bash", &json!({"command": "cargo test"})), Allow(w) if w == "bash:cargo *")
);
assert!(
matches!(both.decide("bash", &json!({"command": "ls"})), Allow(w) if w == "readonly")
);
// readonly does not make write tools available
assert!(denied(p.decide("write", &json!({"path": "a"}))));
}
#[test]
@@ -479,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"),
@@ -496,7 +720,7 @@ mod tests {
"cat .env",
"cat ~/.ssh/id_rsa",
] {
assert!(matches!(f(bad), Deny(_)), "{bad}");
assert!(denied(f(bad)), "{bad}");
}
}
}
+23
View File
@@ -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
View File
@@ -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
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));
+4
View File
@@ -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,
}