Skip to main content

rpi_cli/
approval_gate.rs

1//! Host-integrated approval gate — runtime approval modes for embedded hosts.
2//!
3//! ## Why
4//!
5//! rpi's interactive permissions are extension-owned and read their rules at
6//! session build time; an embedding desktop host needs to switch the policy at
7//! runtime and receive a real approval prompt for the exact tool call. This
8//! module provides the engine half:
9//!
10//! - [`ApprovalMode`] (`AlwaysAsk` / `Write` / `Yolo`) in a process-global
11//!   atomic, settable at runtime by the host;
12//! - a [`ApprovalHandler`] the host installs once — the gate calls it with the
13//!   tool name/args/session id and honors an `Allow`/`Deny` decision;
14//! - [`hook`], a `before_tool_call` hook that composes with the extension hook
15//!   and blocks denied calls with a readable reason.
16//!
17//! When no handler is installed the gate is a no-op: a bare CLI keeps its
18//! existing extension permissions behaviour and is never silently downgraded.
19//!
20//! Classification is intentionally conservative: only an explicit read-only
21//! allowlist is auto-allowed; anything unknown is treated as mutating and asks
22//! under `AlwaysAsk`.
23
24use std::sync::atomic::{AtomicU8, Ordering};
25use std::sync::{Arc, OnceLock};
26
27use async_trait::async_trait;
28use rpi_agent::hooks::BeforeToolCall;
29use rpi_agent::types::{BeforeToolCallContext, BeforeToolCallResult};
30use rpi_harness::agent_harness::WeakAgentHarness;
31use tokio_util::sync::CancellationToken;
32
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub enum ApprovalMode {
35    /// Ask before any mutating tool (read-only tools never ask).
36    AlwaysAsk,
37    /// Auto-approve file writes; ask before commands / unknown tools.
38    Write,
39    /// Auto-approve everything (hard policy gates still apply elsewhere).
40    Yolo,
41}
42
43impl ApprovalMode {
44    pub fn as_wire(self) -> &'static str {
45        match self {
46            ApprovalMode::AlwaysAsk => "always-ask",
47            ApprovalMode::Write => "write",
48            ApprovalMode::Yolo => "yolo",
49        }
50    }
51
52    pub fn parse(value: &str) -> Option<Self> {
53        match value.trim().to_ascii_lowercase().as_str() {
54            "always-ask" | "always_ask" | "ask" | "default" => Some(ApprovalMode::AlwaysAsk),
55            "write" => Some(ApprovalMode::Write),
56            "yolo" | "full" | "full-access" | "full_access" => Some(ApprovalMode::Yolo),
57            _ => None,
58        }
59    }
60
61    fn code(self) -> u8 {
62        match self {
63            ApprovalMode::AlwaysAsk => 0,
64            ApprovalMode::Write => 1,
65            ApprovalMode::Yolo => 2,
66        }
67    }
68
69    fn from_code(code: u8) -> Self {
70        match code {
71            1 => ApprovalMode::Write,
72            2 => ApprovalMode::Yolo,
73            _ => ApprovalMode::AlwaysAsk,
74        }
75    }
76}
77
78static MODE: AtomicU8 = AtomicU8::new(0);
79
80/// Set the process-wide approval mode (host call; takes effect for the very
81/// next tool call, including in-flight turns).
82pub fn set_mode(mode: ApprovalMode) {
83    MODE.store(mode.code(), Ordering::SeqCst);
84}
85
86pub fn mode() -> ApprovalMode {
87    ApprovalMode::from_code(MODE.load(Ordering::SeqCst))
88}
89
90/// One approval question, with just enough context for a human to decide.
91#[derive(Debug, Clone)]
92pub struct ApprovalRequest {
93    pub session_id: String,
94    pub tool: String,
95    pub args: serde_json::Value,
96}
97
98#[derive(Debug, Clone)]
99pub enum ApprovalDecision {
100    Allow,
101    Deny { reason: Option<String> },
102}
103
104/// Host approval door (UI prompt). Must return a decision; an I/O error is
105/// surfaced as a denial with the error text (never fail-open).
106#[async_trait]
107pub trait ApprovalHandler: Send + Sync {
108    async fn request(&self, request: ApprovalRequest) -> ApprovalDecision;
109}
110
111static HANDLER: OnceLock<Arc<dyn ApprovalHandler>> = OnceLock::new();
112
113pub fn set_handler(handler: Arc<dyn ApprovalHandler>) -> bool {
114    HANDLER.set(handler).is_ok()
115}
116
117pub fn handler_installed() -> bool {
118    HANDLER.get().is_some()
119}
120
121/// Read-only tools are always safe; keep this list explicit (unknown = mutating).
122fn read_only_tool(tool: &str) -> bool {
123    matches!(
124        tool,
125        "read" | "ls" | "grep" | "find" | "web_search" | "web_fetch" | "docs" | "todo"
126    )
127}
128
129fn write_tool(tool: &str) -> bool {
130    matches!(
131        tool,
132        "write" | "edit" | "hashline_edit" | "ast_edit" | "apply_patch" | "multi_edit"
133    )
134}
135
136/// Whether this call needs a human decision under `mode`.
137fn needs_approval(mode: ApprovalMode, tool: &str) -> bool {
138    match mode {
139        ApprovalMode::Yolo => false,
140        ApprovalMode::Write => !read_only_tool(tool) && !write_tool(tool),
141        ApprovalMode::AlwaysAsk => !read_only_tool(tool),
142    }
143}
144
145async fn session_id(binding: &OnceLock<WeakAgentHarness>) -> String {
146    let Some(weak) = binding.get() else {
147        return String::new();
148    };
149    let Some(harness) = weak.upgrade() else {
150        return String::new();
151    };
152    harness
153        .session()
154        .get_metadata()
155        .await
156        .map(|metadata| metadata.id)
157        .unwrap_or_default()
158}
159
160/// Evaluate one tool call against the current mode + host handler.
161///
162/// Owned inputs only: the `before_tool_call` future must be `'static`, so the
163/// hook copies the tool name/args before awaiting.
164///
165/// Cancellation is propagated (reviewer blocker #4): once the handler door is
166/// open, a stale UI prompt must not hold the tool turn forever — if `signal`
167/// fires first the call fails **closed** (blocked), never open.
168pub async fn evaluate(
169    binding: &OnceLock<WeakAgentHarness>,
170    tool: &str,
171    args: &serde_json::Value,
172    signal: &CancellationToken,
173) -> Option<BeforeToolCallResult> {
174    if !needs_approval(mode(), tool) {
175        return None;
176    }
177    let Some(handler) = HANDLER.get() else {
178        // Host never installed an approval door: leave behaviour to the
179        // extension permissions path rather than inventing a denial.
180        return None;
181    };
182    let request = ApprovalRequest {
183        session_id: session_id(binding).await,
184        tool: tool.to_owned(),
185        args: args.clone(),
186    };
187    let decision = tokio::select! {
188        biased;
189        _ = signal.cancelled() => {
190            return Some(BeforeToolCallResult {
191                block: true,
192                reason: Some(format!("approval for {tool} cancelled before a decision")),
193                ..Default::default()
194            });
195        }
196        decision = handler.request(request) => decision,
197    };
198    match decision {
199        ApprovalDecision::Allow => None,
200        ApprovalDecision::Deny { reason } => Some(BeforeToolCallResult {
201            block: true,
202            reason: Some(reason.unwrap_or_else(|| format!("User denied {tool}"))),
203            ..Default::default()
204        }),
205    }
206}
207
208/// The `before_tool_call` gate. Compose it **after** any extension hook: an
209/// extension veto still wins, and the host gate sees only calls that would
210/// actually run.
211pub fn hook(binding: Arc<OnceLock<WeakAgentHarness>>) -> BeforeToolCall {
212    Arc::new(
213        move |context: BeforeToolCallContext<'_>, signal: CancellationToken| {
214            let binding = Arc::clone(&binding);
215            let tool = context.tool_call.name.clone();
216            let args = context.args.clone();
217            Box::pin(async move {
218                if signal.is_cancelled() {
219                    return Some(BeforeToolCallResult {
220                        block: true,
221                        reason: Some("tool call cancelled".into()),
222                        ..Default::default()
223                    });
224                }
225                evaluate(&binding, &tool, &args, &signal).await
226            })
227        },
228    )
229}
230
231#[cfg(test)]
232mod tests {
233    use super::*;
234
235    #[test]
236    fn mode_roundtrip() {
237        for mode in [
238            ApprovalMode::AlwaysAsk,
239            ApprovalMode::Write,
240            ApprovalMode::Yolo,
241        ] {
242            assert_eq!(ApprovalMode::parse(mode.as_wire()), Some(mode));
243        }
244        assert_eq!(ApprovalMode::parse("bogus"), None);
245    }
246
247    #[test]
248    fn classification_matches_policy() {
249        assert!(!needs_approval(ApprovalMode::AlwaysAsk, "read"));
250        assert!(needs_approval(ApprovalMode::AlwaysAsk, "bash"));
251        assert!(needs_approval(ApprovalMode::AlwaysAsk, "write"));
252        assert!(!needs_approval(ApprovalMode::Write, "write"));
253        assert!(needs_approval(ApprovalMode::Write, "bash"));
254        assert!(!needs_approval(ApprovalMode::Yolo, "bash"));
255    }
256
257    #[test]
258    fn read_only_and_write_sets_are_explicit() {
259        for tool in ["read", "ls", "grep", "find", "docs"] {
260            assert!(read_only_tool(tool));
261        }
262        for tool in ["write", "edit", "hashline_edit", "ast_edit"] {
263            assert!(write_tool(tool));
264        }
265        assert!(!read_only_tool("bash"));
266        assert!(!write_tool("bash"));
267    }
268
269    struct NeverDecides;
270    #[async_trait]
271    impl ApprovalHandler for NeverDecides {
272        async fn request(&self, _request: ApprovalRequest) -> ApprovalDecision {
273            std::future::pending::<ApprovalDecision>().await
274        }
275    }
276
277    struct AlwaysAllows;
278    #[async_trait]
279    impl ApprovalHandler for AlwaysAllows {
280        async fn request(&self, _request: ApprovalRequest) -> ApprovalDecision {
281            ApprovalDecision::Allow
282        }
283    }
284
285    /// A cancelled tool signal must win over a handler that never answers:
286    /// fail closed instead of holding the tool turn forever (reviewer #4).
287    #[test]
288    fn cancelled_signal_fails_closed_before_a_decision() {
289        if HANDLER.get().is_none() {
290            let _ = set_handler(Arc::new(NeverDecides));
291        }
292        set_mode(ApprovalMode::AlwaysAsk);
293        let token = CancellationToken::new();
294        token.cancel();
295        let binding = OnceLock::new();
296        let outcome =
297            futures::executor::block_on(evaluate(&binding, "bash", &serde_json::json!({}), &token));
298        let blocked = matches!(outcome, Some(result) if result.block);
299        assert!(blocked, "cancelled signal must return a blocking result");
300
301        // And an allowing handler is not consulted once the signal is up.
302        let _ = set_handler(Arc::new(AlwaysAllows));
303        let outcome =
304            futures::executor::block_on(evaluate(&binding, "bash", &serde_json::json!({}), &token));
305        assert!(matches!(outcome, Some(result) if result.block));
306    }
307}