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([':', '—', '-']) {
106 Some((word, rest)) => (word.trim(), rest.trim()),
107 None => (cleaned, ""),
108 };
109 match word.to_ascii_lowercase().as_str() {
110 "allow" | "allowed" | "allow." => Ruling::Allow,
111 "deny" | "denied" | "deny." => Ruling::Deny(if rest.is_empty() {
112 "the judge refused this call".to_string()
113 } else {
114 rest.to_string()
115 }),
116 "escalate" | "escalated" | "escalate." => Ruling::Escalate(if rest.is_empty() {
117 "the judge passed this call to you".to_string()
118 } else {
119 rest.to_string()
120 }),
121 _ => Ruling::Escalate(format!(
122 "the judge did not give one of the three answers ({})",
123 clip(line, 80)
124 )),
125 }
126}
127
128fn clip(text: &str, max: usize) -> String {
129 if text.chars().count() <= max {
130 return text.to_string();
131 }
132 let head: String = text.chars().take(max).collect();
133 format!("{head}…")
134}
135
136pub fn prompt(ask: &str, call: &Pending) -> [Message; 2] {
138 let mut user = String::from("THE PERSON'S CURRENT ASK:\n");
139 let trimmed = ask.trim();
140 if trimmed.is_empty() {
141 user.push_str("(nothing — this run has no user prompt)");
142 } else {
143 user.push_str(&clip(trimmed, ASK_BUDGET));
144 }
145 user.push_str("\n\nTHE CALL THE AGENT WANTS TO MAKE:\n");
146 user.push_str(&format!("tool: {}\n", call.tool));
147 user.push_str(&format!("what it does: {}\n", call.summary));
148 let args = call.args.trim();
149 user.push_str("arguments: ");
150 if args.is_empty() || args == "{}" {
151 user.push_str("(none)\n");
152 } else {
153 user.push_str(&format!("\n{}\n", clip(args, ARGS_BUDGET)));
154 }
155 [Message::system(SYSTEM), Message::user(user)]
156}
157
158pub struct Judge<'a> {
164 aux: &'a std::sync::Arc<dyn ChatProvider>,
165 ask: &'a str,
167 timeout: Duration,
168 inner: &'a dyn Approver,
170 failures: AtomicUsize,
172 log: Option<RulingLog>,
174}
175
176impl<'a> Judge<'a> {
177 pub fn new(
178 aux: &'a std::sync::Arc<dyn ChatProvider>,
179 ask: &'a str,
180 timeout: Duration,
181 inner: &'a dyn Approver,
182 ) -> Self {
183 Self {
184 aux,
185 ask,
186 timeout,
187 inner,
188 failures: AtomicUsize::new(0),
189 log: None,
190 }
191 }
192
193 pub fn with_log(mut self, log: RulingLog) -> Self {
195 self.log = Some(log);
196 self
197 }
198
199 async fn consult(&self, call: &Pending) -> (Ruling, Option<String>) {
201 let request = prompt(self.ask, call);
202 match tokio::time::timeout(self.timeout, self.aux.chat(&request, &[])).await {
203 Err(_) => (
204 Ruling::Escalate(format!(
205 "the judge did not answer within {}s",
206 self.timeout.as_secs()
207 )),
208 None,
209 ),
210 Ok(Err(e)) => (
211 Ruling::Escalate(format!("the judge call failed: {e}")),
212 None,
213 ),
214 Ok(Ok(answer)) => {
215 let text = answer.content.as_deref().unwrap_or_default().to_string();
216 match parse_reply(&text) {
217 Ruling::Allow => (Ruling::Allow, None),
218 Ruling::Deny(reason) => (Ruling::Deny(reason), None),
219 Ruling::Escalate(why) => (Ruling::Escalate(why), None),
220 }
221 }
222 }
223 }
224}
225
226#[async_trait::async_trait]
227impl Approver for Judge<'_> {
228 async fn decide(&self, call: &Pending) -> Decision {
229 if self.failures.load(Ordering::Relaxed) >= FAILURES_BEFORE_QUIET {
232 return self.inner.decide(call).await;
233 }
234 let (ruling, _) = self.consult(call).await;
235 let decision = match ruling {
236 Ruling::Allow => Decision::Allow,
237 Ruling::Deny(reason) => Decision::Deny(reason),
238 Ruling::Escalate(why) => {
239 if why.starts_with("the judge did not") || why.starts_with("the judge call failed")
242 {
243 self.failures.fetch_add(1, Ordering::Relaxed);
244 }
245 if let Some(log) = &self.log {
246 log(call, &Decision::Defer, Some(&why));
247 }
248 return self.inner.decide(call).await;
249 }
250 };
251 if let Some(log) = &self.log {
252 log(call, &decision, None);
253 }
254 decision
255 }
256}
257
258#[cfg(test)]
259mod tests {
260 use super::*;
261
262 fn call() -> Pending {
263 Pending::new(
264 "call_1",
265 "shell",
266 "run `ls`".to_string(),
267 r#"{"command":"ls"}"#.into(),
268 )
269 }
270
271 #[test]
272 fn the_three_words_are_read_and_nothing_else_is_permission() {
273 assert_eq!(parse_reply("allow"), Ruling::Allow);
274 assert_eq!(parse_reply("ALLOW.\n"), Ruling::Allow);
275 assert_eq!(parse_reply(" allow "), Ruling::Allow);
276 assert_eq!(
277 parse_reply("deny: that deletes the repository"),
278 Ruling::Deny("that deletes the repository".into())
279 );
280 assert_eq!(
281 parse_reply("escalate: it writes outside the working directory"),
282 Ruling::Escalate("it writes outside the working directory".into())
283 );
284 assert!(matches!(parse_reply("sure, go ahead"), Ruling::Escalate(_)));
286 assert!(matches!(parse_reply(""), Ruling::Escalate(_)));
287 assert!(matches!(
288 parse_reply("{\"allow\": true}"),
289 Ruling::Escalate(_)
290 ));
291 }
292
293 #[test]
294 fn a_deny_without_a_reason_still_says_why_it_is_a_denial() {
295 assert_eq!(
296 parse_reply("deny"),
297 Ruling::Deny("the judge refused this call".into())
298 );
299 assert_eq!(
300 parse_reply("deny:"),
301 Ruling::Deny("the judge refused this call".into())
302 );
303 }
304
305 #[test]
306 fn the_judge_is_given_the_call_and_the_ask_not_a_transcript() {
307 let [system, user] = prompt("fix the failing test", &call());
308 assert!(system.content.as_deref().unwrap().contains("escalate"));
309 let user = user.content.unwrap();
310 assert!(user.contains("fix the failing test"));
311 assert!(user.contains("tool: shell"));
312 assert!(user.contains("run `ls`"));
313 assert!(user.contains(r#"{"command":"ls"}"#));
314 }
315
316 #[test]
317 fn a_pasted_file_is_not_carried_into_the_judge_whole() {
318 let ask = "x".repeat(10_000);
319 let [_, user] = prompt(&ask, &call());
320 let user = user.content.unwrap();
321 assert!(
322 user.len() < ASK_BUDGET + 500,
323 "the ask is clipped: {}",
324 user.len()
325 );
326 assert!(user.ends_with('…') || user.contains('…'));
327 }
328}