eclipse-core 0.13.2

Core library for eclipse: providers, tools, sessions, config, runtime
Documentation
//! `#340`: a third approval mode, where the aux route answers allow / deny / escalate.
//!
//! The gate has two settings today and neither reads the call: `ask` puts a card in front of a
//! person, `auto` never does. This is the third, and it is deliberately the narrowest of them: the
//! judge is consulted **only** for a call the registry already marked `ask` and whose tool says it
//! needs approval. A `deny` policy never reaches it — a judge that can override the registry turns
//! the registry into advice — and it can neither widen a policy nor allow a call that was not
//! already going to be asked about.
//!
//! Three answers, and the mapping is the whole design:
//!
//! - `allow` → [`Decision::Allow`], the call runs, no card;
//! - `deny: <reason>` → [`Decision::Deny`], the sentence reaches the model as the tool result;
//! - anything else — `escalate`, an answer in the wrong words, a timeout, a dead route, a body that
//!   does not parse — → the person's own gate, exactly as if the mode were `ask`.
//!
//! **The failure path is the feature.** This is the one call in the system where a timeout must
//! never read as "carry on": the trimmed-turn summary falling back to `Allow` would be a shell
//! command nobody approved. So every doubt escalates, and after [`FAILURES_BEFORE_QUIET`] failures
//! in one turn the judge stops being consulted at all — a turn that makes forty `shell` calls is
//! forty judge calls, and a route that is down should not cost forty timeouts before the person
//! sees the first card.
//!
//! What the judge sees is the call, not the session: the tool name, its arguments, the one-line
//! summary the person would have been shown, and the user's current ask. A judge fed the whole
//! transcript is a second model billing for context and a new place private content goes, to answer
//! a question four fields settle.

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;

/// How many times the judge may fail in one turn before it stops being asked.
///
/// Not a retry count — the provider's own retries are underneath this. This is the point at which
/// "the route is down" stops costing a timeout per gated call for the rest of the turn.
pub const FAILURES_BEFORE_QUIET: usize = 3;

/// How much of the user's ask the judge is given. The ask is context for the call, not the task
/// itself; a pasted file must not become a second prompt.
const ASK_BUDGET: usize = 2_000;
/// How much of the call's arguments the judge is given, for the same reason.
const ARGS_BUDGET: usize = 4_000;

/// Where a ruling goes so a later reader can find it: the store's append-only log, in practice.
/// A named alias because the closure type is otherwise three lines of noise in every signature.
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.";

/// What the model said, once its words have been read.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Ruling {
    Allow,
    Deny(String),
    /// Hand it to the person, with the model's reason if it gave one worth showing.
    Escalate(String),
}

impl Ruling {
    pub fn as_str(&self) -> &'static str {
        match self {
            Ruling::Allow => "allow",
            Ruling::Deny(_) => "deny",
            Ruling::Escalate(_) => "escalate",
        }
    }
}

/// Read the answer.
///
/// Fail-closed in the strongest sense available: the *only* text that produces [`Ruling::Allow`] is
/// a line that starts with `allow`. Everything else is escalate, because an answer this build does
/// not understand is not permission. `deny` keeps its reason, since that sentence is what teaches
/// the model something; a `deny` with no reason still denies.
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}…")
}

/// The two messages the judge is given: its instructions, and the call.
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)]
}

/// The gate's judge: one aux call per call that would otherwise be a card.
///
/// Wraps the person's own approver, so every doubt lands there. It is installed by
/// [`crate::runtime::Agent`] for the duration of one run — `smart` is a mode of the run, not a
/// property of whoever built the gate — and counts its own failures for that run.
pub struct Judge<'a> {
    aux: &'a std::sync::Arc<dyn ChatProvider>,
    /// The user's ask, as context for the call.
    ask: &'a str,
    timeout: Duration,
    /// Where an escalate goes: the person, exactly as they would have been asked anyway.
    inner: &'a dyn Approver,
    /// How many times this judge has failed in this run, against [`FAILURES_BEFORE_QUIET`].
    failures: AtomicUsize,
    /// Somewhere to leave the ruling, so what the model waved through is answerable later.
    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,
        }
    }

    /// Record each ruling where a later reader can find it.
    pub fn with_log(mut self, log: RulingLog) -> Self {
        self.log = Some(log);
        self
    }

    /// Ask, and turn every failure into the person's card.
    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 {
        // A judge that has failed this many times is a route that is down: stop paying a timeout
        // per call and let the person answer, which is what happens without the mode at all.
        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) => {
                // Counted as a failure only when the judge did not actually rule — an explicit
                // `escalate` is a working judge doing its job, and it must not be discouraged.
                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())
        );
        // Fail closed: words this build did not ask for are not permission.
        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('…'));
    }
}