use crate::approvals::{Decision, Pending};
use crate::message::Message;
use crate::provider::ChatProvider;
use crate::tools::Approver;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
pub const FAILURES_BEFORE_QUIET: usize = 3;
const ASK_BUDGET: usize = 2_000;
const ARGS_BUDGET: usize = 4_000;
pub type RulingLog = std::sync::Arc<dyn Fn(&Pending, &Decision, Option<&str>) + Send + Sync>;
const SYSTEM: &str = "\
You decide whether an autonomous coding agent may run one tool call, on behalf of a person who is \
asleep or busy. You are given the person's current ask and the single call the agent wants to make.
Answer with exactly one line, in one of these three forms:
allow — the call is an ordinary part of the ask, and a reasonable person who asked for that would \
not want to be woken up for it
deny — the call is destructive, dishonest, or clearly outside what the ask is about, or you cannot \
tell what it does
escalate — the call is consequential enough that a person must decide: anything that deletes or \
overwrites work they did not name, sends data off the machine, touches credentials, spends money, \
or changes the system outside the working directory
`deny` and `escalate` take a reason after a colon, addressed to the agent, in at most one short \
sentence. No other words, no punctuation beyond that, no code fences.
When in doubt, escalate. A wrong `allow` is a call nobody approved; a wrong `escalate` costs one \
glance.";
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Ruling {
Allow,
Deny(String),
Escalate(String),
}
impl Ruling {
pub fn as_str(&self) -> &'static str {
match self {
Ruling::Allow => "allow",
Ruling::Deny(_) => "deny",
Ruling::Escalate(_) => "escalate",
}
}
}
pub fn parse_reply(text: &str) -> Ruling {
let line = text
.lines()
.map(str::trim)
.find(|l| !l.is_empty())
.unwrap_or_default();
let cleaned = line
.trim_start_matches(['"', '\'', '`', '*', '-', ' '])
.trim();
let (word, rest) = match cleaned.split_once([':', '—', '-']) {
Some((word, rest)) => (word.trim(), rest.trim()),
None => (cleaned, ""),
};
match word.to_ascii_lowercase().as_str() {
"allow" | "allowed" | "allow." => Ruling::Allow,
"deny" | "denied" | "deny." => Ruling::Deny(if rest.is_empty() {
"the judge refused this call".to_string()
} else {
rest.to_string()
}),
"escalate" | "escalated" | "escalate." => Ruling::Escalate(if rest.is_empty() {
"the judge passed this call to you".to_string()
} else {
rest.to_string()
}),
_ => Ruling::Escalate(format!(
"the judge did not give one of the three answers ({})",
clip(line, 80)
)),
}
}
fn clip(text: &str, max: usize) -> String {
if text.chars().count() <= max {
return text.to_string();
}
let head: String = text.chars().take(max).collect();
format!("{head}…")
}
pub fn prompt(ask: &str, call: &Pending) -> [Message; 2] {
let mut user = String::from("THE PERSON'S CURRENT ASK:\n");
let trimmed = ask.trim();
if trimmed.is_empty() {
user.push_str("(nothing — this run has no user prompt)");
} else {
user.push_str(&clip(trimmed, ASK_BUDGET));
}
user.push_str("\n\nTHE CALL THE AGENT WANTS TO MAKE:\n");
user.push_str(&format!("tool: {}\n", call.tool));
user.push_str(&format!("what it does: {}\n", call.summary));
let args = call.args.trim();
user.push_str("arguments: ");
if args.is_empty() || args == "{}" {
user.push_str("(none)\n");
} else {
user.push_str(&format!("\n{}\n", clip(args, ARGS_BUDGET)));
}
[Message::system(SYSTEM), Message::user(user)]
}
pub struct Judge<'a> {
aux: &'a std::sync::Arc<dyn ChatProvider>,
ask: &'a str,
timeout: Duration,
inner: &'a dyn Approver,
failures: AtomicUsize,
log: Option<RulingLog>,
}
impl<'a> Judge<'a> {
pub fn new(
aux: &'a std::sync::Arc<dyn ChatProvider>,
ask: &'a str,
timeout: Duration,
inner: &'a dyn Approver,
) -> Self {
Self {
aux,
ask,
timeout,
inner,
failures: AtomicUsize::new(0),
log: None,
}
}
pub fn with_log(mut self, log: RulingLog) -> Self {
self.log = Some(log);
self
}
async fn consult(&self, call: &Pending) -> (Ruling, Option<String>) {
let request = prompt(self.ask, call);
match tokio::time::timeout(self.timeout, self.aux.chat(&request, &[])).await {
Err(_) => (
Ruling::Escalate(format!(
"the judge did not answer within {}s",
self.timeout.as_secs()
)),
None,
),
Ok(Err(e)) => (
Ruling::Escalate(format!("the judge call failed: {e}")),
None,
),
Ok(Ok(answer)) => {
let text = answer.content.as_deref().unwrap_or_default().to_string();
match parse_reply(&text) {
Ruling::Allow => (Ruling::Allow, None),
Ruling::Deny(reason) => (Ruling::Deny(reason), None),
Ruling::Escalate(why) => (Ruling::Escalate(why), None),
}
}
}
}
}
#[async_trait::async_trait]
impl Approver for Judge<'_> {
async fn decide(&self, call: &Pending) -> Decision {
if self.failures.load(Ordering::Relaxed) >= FAILURES_BEFORE_QUIET {
return self.inner.decide(call).await;
}
let (ruling, _) = self.consult(call).await;
let decision = match ruling {
Ruling::Allow => Decision::Allow,
Ruling::Deny(reason) => Decision::Deny(reason),
Ruling::Escalate(why) => {
if why.starts_with("the judge did not") || why.starts_with("the judge call failed")
{
self.failures.fetch_add(1, Ordering::Relaxed);
}
if let Some(log) = &self.log {
log(call, &Decision::Defer, Some(&why));
}
return self.inner.decide(call).await;
}
};
if let Some(log) = &self.log {
log(call, &decision, None);
}
decision
}
}
#[cfg(test)]
mod tests {
use super::*;
fn call() -> Pending {
Pending::new(
"call_1",
"shell",
"run `ls`".to_string(),
r#"{"command":"ls"}"#.into(),
)
}
#[test]
fn the_three_words_are_read_and_nothing_else_is_permission() {
assert_eq!(parse_reply("allow"), Ruling::Allow);
assert_eq!(parse_reply("ALLOW.\n"), Ruling::Allow);
assert_eq!(parse_reply(" allow "), Ruling::Allow);
assert_eq!(
parse_reply("deny: that deletes the repository"),
Ruling::Deny("that deletes the repository".into())
);
assert_eq!(
parse_reply("escalate: it writes outside the working directory"),
Ruling::Escalate("it writes outside the working directory".into())
);
assert!(matches!(parse_reply("sure, go ahead"), Ruling::Escalate(_)));
assert!(matches!(parse_reply(""), Ruling::Escalate(_)));
assert!(matches!(
parse_reply("{\"allow\": true}"),
Ruling::Escalate(_)
));
}
#[test]
fn a_deny_without_a_reason_still_says_why_it_is_a_denial() {
assert_eq!(
parse_reply("deny"),
Ruling::Deny("the judge refused this call".into())
);
assert_eq!(
parse_reply("deny:"),
Ruling::Deny("the judge refused this call".into())
);
}
#[test]
fn the_judge_is_given_the_call_and_the_ask_not_a_transcript() {
let [system, user] = prompt("fix the failing test", &call());
assert!(system.content.as_deref().unwrap().contains("escalate"));
let user = user.content.unwrap();
assert!(user.contains("fix the failing test"));
assert!(user.contains("tool: shell"));
assert!(user.contains("run `ls`"));
assert!(user.contains(r#"{"command":"ls"}"#));
}
#[test]
fn a_pasted_file_is_not_carried_into_the_judge_whole() {
let ask = "x".repeat(10_000);
let [_, user] = prompt(&ask, &call());
let user = user.content.unwrap();
assert!(
user.len() < ASK_BUDGET + 500,
"the ask is clipped: {}",
user.len()
);
assert!(user.ends_with('…') || user.contains('…'));
}
}