1use crate::approvals::{Decision, Pending};
30use crate::message::Message;
31use crate::provider::ChatProvider;
32use crate::tools::Approver;
33use std::sync::atomic::{AtomicUsize, Ordering};
34use std::time::Duration;
35
36pub const FAILURES_BEFORE_QUIET: usize = 3;
41
42const ASK_BUDGET: usize = 2_000;
45const ARGS_BUDGET: usize = 4_000;
47
48pub type RulingLog = std::sync::Arc<dyn Fn(&Pending, &Decision, Option<&str>) + Send + Sync>;
51
52const SYSTEM: &str = "\
53You decide whether an autonomous coding agent may run one tool call, on behalf of a person who is \
54asleep or busy. You are given the person's current ask and the single call the agent wants to make.
55
56Answer with exactly one line, in one of these three forms:
57allow — the call is an ordinary part of the ask, and a reasonable person who asked for that would \
58not want to be woken up for it
59deny — the call is destructive, dishonest, or clearly outside what the ask is about, or you cannot \
60tell what it does
61escalate — the call is consequential enough that a person must decide: anything that deletes or \
62overwrites work they did not name, sends data off the machine, touches credentials, spends money, \
63or changes the system outside the working directory
64
65`deny` and `escalate` take a reason after a colon, addressed to the agent, in at most one short \
66sentence. No other words, no punctuation beyond that, no code fences.
67
68When in doubt, escalate. A wrong `allow` is a call nobody approved; a wrong `escalate` costs one \
69glance.";
70
71#[derive(Debug, Clone, PartialEq, Eq)]
73pub enum Ruling {
74 Allow,
75 Deny(String),
76 Escalate(String),
78}
79
80impl Ruling {
81 pub fn as_str(&self) -> &'static str {
82 match self {
83 Ruling::Allow => "allow",
84 Ruling::Deny(_) => "deny",
85 Ruling::Escalate(_) => "escalate",
86 }
87 }
88}
89
90pub fn parse_reply(text: &str) -> Ruling {
97 let line = text
98 .lines()
99 .map(str::trim)
100 .find(|l| !l.is_empty())
101 .unwrap_or_default();
102 let cleaned = line
103 .trim_start_matches(['"', '\'', '`', '*', '-', ' '])
104 .trim();
105 let (word, rest) = match cleaned.split_once([':', '—']) {
109 Some((word, rest)) => (word.trim(), rest.trim()),
110 None => (cleaned, ""),
111 };
112 let word = word.trim_end_matches('.');
114 match word.to_ascii_lowercase().as_str() {
115 "allow" | "allowed" if rest.is_empty() => Ruling::Allow,
119 "deny" | "denied" => Ruling::Deny(if rest.is_empty() {
120 "the judge refused this call".to_string()
121 } else {
122 rest.to_string()
123 }),
124 "escalate" | "escalated" => Ruling::Escalate(if rest.is_empty() {
125 "the judge passed this call to you".to_string()
126 } else {
127 rest.to_string()
128 }),
129 _ => Ruling::Escalate(format!(
130 "the judge did not give one of the three answers ({})",
131 clip(line, 80)
132 )),
133 }
134}
135
136fn clip(text: &str, max: usize) -> String {
137 if text.chars().count() <= max {
138 return text.to_string();
139 }
140 let head: String = text.chars().take(max).collect();
141 format!("{head}…")
142}
143
144pub fn prompt(ask: &str, call: &Pending) -> [Message; 2] {
146 let mut user = String::from("THE PERSON'S CURRENT ASK:\n");
147 let trimmed = ask.trim();
148 if trimmed.is_empty() {
149 user.push_str("(nothing — this run has no user prompt)");
150 } else {
151 user.push_str(&clip(trimmed, ASK_BUDGET));
152 }
153 user.push_str("\n\nTHE CALL THE AGENT WANTS TO MAKE:\n");
154 user.push_str(&format!("tool: {}\n", call.tool));
155 user.push_str(&format!("what it does: {}\n", call.summary));
156 let args = call.args.trim();
157 user.push_str("arguments: ");
158 if args.is_empty() || args == "{}" {
159 user.push_str("(none)\n");
160 } else {
161 user.push_str(&format!("\n{}\n", clip(args, ARGS_BUDGET)));
162 }
163 [Message::system(SYSTEM), Message::user(user)]
164}
165
166pub struct Judge<'a> {
172 aux: &'a std::sync::Arc<dyn ChatProvider>,
173 ask: &'a str,
175 timeout: Duration,
176 inner: &'a dyn Approver,
178 failures: AtomicUsize,
180 log: Option<RulingLog>,
182}
183
184impl<'a> Judge<'a> {
185 pub fn new(
186 aux: &'a std::sync::Arc<dyn ChatProvider>,
187 ask: &'a str,
188 timeout: Duration,
189 inner: &'a dyn Approver,
190 ) -> Self {
191 Self {
192 aux,
193 ask,
194 timeout,
195 inner,
196 failures: AtomicUsize::new(0),
197 log: None,
198 }
199 }
200
201 pub fn with_log(mut self, log: RulingLog) -> Self {
203 self.log = Some(log);
204 self
205 }
206
207 async fn consult(&self, call: &Pending) -> (Ruling, Option<String>) {
209 let request = prompt(self.ask, call);
210 match tokio::time::timeout(self.timeout, self.aux.chat(&request, &[])).await {
211 Err(_) => (
212 Ruling::Escalate(format!(
213 "the judge did not answer within {}s",
214 self.timeout.as_secs()
215 )),
216 None,
217 ),
218 Ok(Err(e)) => (
219 Ruling::Escalate(format!("the judge call failed: {e}")),
220 None,
221 ),
222 Ok(Ok(answer)) => {
223 let text = answer.content.as_deref().unwrap_or_default().to_string();
224 match parse_reply(&text) {
225 Ruling::Allow => (Ruling::Allow, None),
226 Ruling::Deny(reason) => (Ruling::Deny(reason), None),
227 Ruling::Escalate(why) => (Ruling::Escalate(why), None),
228 }
229 }
230 }
231 }
232}
233
234#[async_trait::async_trait]
235impl Approver for Judge<'_> {
236 async fn decide(&self, call: &Pending) -> Decision {
237 if self.failures.load(Ordering::Relaxed) >= FAILURES_BEFORE_QUIET {
240 return self.inner.decide(call).await;
241 }
242 let (ruling, _) = self.consult(call).await;
243 let decision = match ruling {
244 Ruling::Allow => Decision::Allow,
245 Ruling::Deny(reason) => Decision::Deny(reason),
246 Ruling::Escalate(why) => {
247 if why.starts_with("the judge did not") || why.starts_with("the judge call failed")
250 {
251 self.failures.fetch_add(1, Ordering::Relaxed);
252 }
253 if let Some(log) = &self.log {
254 log(call, &Decision::Defer, Some(&why));
255 }
256 return self.inner.decide(call).await;
257 }
258 };
259 if let Some(log) = &self.log {
260 log(call, &decision, None);
261 }
262 decision
263 }
264}
265
266#[cfg(test)]
267mod tests {
268 use super::*;
269
270 fn call() -> Pending {
271 Pending::new(
272 "call_1",
273 "shell",
274 "run `ls`".to_string(),
275 r#"{"command":"ls"}"#.into(),
276 )
277 }
278
279 #[test]
283 fn a_refusal_that_mentions_allow_is_not_permission() {
284 for text in [
285 "allowed: false",
286 "allow-list check failed — deny",
287 "allow: but it deletes the repository",
288 "allow — read-only, still needs a card",
289 "allowance denied",
290 "allowed by policy, except it is not",
291 ] {
292 let ruling = parse_reply(text);
293 assert!(
294 matches!(ruling, Ruling::Escalate(_)),
295 "{text:?} read as {ruling:?}, and only a bare `allow` is permission"
296 );
297 }
298 for text in ["allow", "Allow.", "ALLOW", " allow "] {
300 assert_eq!(parse_reply(text), Ruling::Allow, "{text:?}");
301 }
302 assert_eq!(
303 parse_reply("deny."),
304 Ruling::Deny("the judge refused this call".into())
305 );
306 }
307
308 #[test]
309 fn the_three_words_are_read_and_nothing_else_is_permission() {
310 assert_eq!(parse_reply("allow"), Ruling::Allow);
311 assert_eq!(parse_reply("ALLOW.\n"), Ruling::Allow);
312 assert_eq!(parse_reply(" allow "), Ruling::Allow);
313 assert_eq!(
314 parse_reply("deny: that deletes the repository"),
315 Ruling::Deny("that deletes the repository".into())
316 );
317 assert_eq!(
318 parse_reply("escalate: it writes outside the working directory"),
319 Ruling::Escalate("it writes outside the working directory".into())
320 );
321 assert!(matches!(parse_reply("sure, go ahead"), Ruling::Escalate(_)));
323 assert!(matches!(parse_reply(""), Ruling::Escalate(_)));
324 assert!(matches!(
325 parse_reply("{\"allow\": true}"),
326 Ruling::Escalate(_)
327 ));
328 }
329
330 #[test]
331 fn a_deny_without_a_reason_still_says_why_it_is_a_denial() {
332 assert_eq!(
333 parse_reply("deny"),
334 Ruling::Deny("the judge refused this call".into())
335 );
336 assert_eq!(
337 parse_reply("deny:"),
338 Ruling::Deny("the judge refused this call".into())
339 );
340 }
341
342 #[test]
343 fn the_judge_is_given_the_call_and_the_ask_not_a_transcript() {
344 let [system, user] = prompt("fix the failing test", &call());
345 assert!(system.content.as_deref().unwrap().contains("escalate"));
346 let user = user.content.unwrap();
347 assert!(user.contains("fix the failing test"));
348 assert!(user.contains("tool: shell"));
349 assert!(user.contains("run `ls`"));
350 assert!(user.contains(r#"{"command":"ls"}"#));
351 }
352
353 #[test]
354 fn a_pasted_file_is_not_carried_into_the_judge_whole() {
355 let ask = "x".repeat(10_000);
356 let [_, user] = prompt(&ask, &call());
357 let user = user.content.unwrap();
358 assert!(
359 user.len() < ASK_BUDGET + 500,
360 "the ask is clipped: {}",
361 user.len()
362 );
363 assert!(user.ends_with('…') || user.contains('…'));
364 }
365}