Skip to main content

arabica_runtime/
control.rs

1//! Per-run control supplied by the host: cooperative cancellation and the tool
2//! permission gate.
3//!
4//! A host cannot cancel a run by sending `run.cancel` while the run executes:
5//! Session Management holds one borrow for the whole `message.send`, so the
6//! Command would only be processed after the run ended. Control therefore
7//! travels with the run as a shared handle the host can signal at any time.
8
9use std::collections::BTreeMap;
10use std::sync::Arc;
11
12use arabica_model::ToolCallItem;
13use arabica_protocol::{RunId, ToolPermissionOutcome, ToolPermissionScope, ToolPermissionSource};
14use tokio::sync::{mpsc, oneshot, watch};
15
16/// A cancellation signal for one run, shared between the host and Runtime.
17///
18/// Cloning shares the signal. Cancelling is idempotent and never blocks, so a
19/// host may call it from a notification handler that must not wait on the run.
20#[derive(Clone, Debug)]
21pub struct RunCancellation(Arc<watch::Sender<bool>>);
22
23impl RunCancellation {
24    pub fn new() -> Self {
25        let (sender, _) = watch::channel(false);
26        Self(Arc::new(sender))
27    }
28
29    pub fn cancel(&self) {
30        self.0.send_replace(true);
31    }
32
33    pub fn is_cancelled(&self) -> bool {
34        *self.0.borrow()
35    }
36
37    /// Resolve once the run is cancelled; immediately if it already is.
38    pub async fn cancelled(&self) {
39        let mut receiver = self.0.subscribe();
40        // The sender lives as long as any clone of this handle, including
41        // `self`, so the channel cannot close while this future is polled.
42        let _ = receiver.wait_for(|cancelled| *cancelled).await;
43    }
44}
45
46impl Default for RunCancellation {
47    fn default() -> Self {
48        Self::new()
49    }
50}
51
52/// What the gate does with a call to one tool.
53#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
54pub enum ToolPermissionRule {
55    /// Run without asking and without recording a decision.
56    Allow,
57    /// Ask the host's approver first. The default, because a gate that is
58    /// configured but silent should fail safe.
59    #[default]
60    Ask,
61    /// Refuse without asking.
62    Deny,
63}
64
65/// Which rule applies to each tool, keyed by tool name.
66///
67/// Rules are keyed by name, never by the runner's interaction classifier:
68/// that classifier is a memory-retention heuristic, and `cat notes | sh`
69/// classifies as inspection while executing arbitrary code.
70#[derive(Clone, Debug, Default, Eq, PartialEq)]
71pub struct ToolPermissionPolicy {
72    pub default: ToolPermissionRule,
73    pub by_tool: BTreeMap<String, ToolPermissionRule>,
74    /// First matching argument rule takes precedence over the tool and default rules.
75    pub argument_rules: Vec<ToolArgumentPermissionRule>,
76}
77
78#[derive(Clone, Debug, Eq, PartialEq)]
79pub struct ToolArgumentPermissionRule {
80    pub tool: String,
81    /// Dot-separated object path, or `*` to match the serialized arguments.
82    pub parameter: String,
83    pub pattern: String,
84    pub rule: ToolPermissionRule,
85}
86
87impl ToolPermissionPolicy {
88    pub fn rule_for(&self, tool: &str, arguments: &serde_json::Value) -> ToolPermissionRule {
89        for rule in &self.argument_rules {
90            if rule.tool != tool {
91                continue;
92            }
93            let Some(value) = argument_value(arguments, &rule.parameter) else {
94                continue;
95            };
96            if crate::cached_regex_is_match(&rule.pattern, &value) {
97                return rule.rule;
98            }
99        }
100        self.by_tool.get(tool).copied().unwrap_or(self.default)
101    }
102}
103
104fn argument_value(arguments: &serde_json::Value, parameter: &str) -> Option<String> {
105    let value = if parameter == "*" {
106        arguments
107    } else {
108        parameter.split('.').try_fold(arguments, |value, segment| {
109            value
110                .as_object()
111                .and_then(|object| object.get(segment))
112                .or_else(|| {
113                    segment
114                        .parse::<usize>()
115                        .ok()
116                        .and_then(|index| value.get(index))
117                })
118        })?
119    };
120    match value {
121        serde_json::Value::String(value) => Some(value.clone()),
122        _ => Some(value.to_string()),
123    }
124}
125
126/// A decision about one call.
127#[derive(Clone, Copy, Debug, Eq, PartialEq)]
128pub struct PermissionDecision {
129    pub outcome: ToolPermissionOutcome,
130    pub scope: ToolPermissionScope,
131    pub source: ToolPermissionSource,
132}
133
134impl PermissionDecision {
135    /// A person allowed this call only.
136    pub const fn allow_once() -> Self {
137        Self {
138            outcome: ToolPermissionOutcome::Allowed,
139            scope: ToolPermissionScope::Once,
140            source: ToolPermissionSource::User,
141        }
142    }
143
144    /// A person allowed this tool for the rest of the Session.
145    pub const fn allow_for_session() -> Self {
146        Self {
147            outcome: ToolPermissionOutcome::Allowed,
148            scope: ToolPermissionScope::Session,
149            source: ToolPermissionSource::User,
150        }
151    }
152
153    /// A person refused this call.
154    pub const fn deny_once() -> Self {
155        Self {
156            outcome: ToolPermissionOutcome::Denied,
157            scope: ToolPermissionScope::Once,
158            source: ToolPermissionSource::User,
159        }
160    }
161
162    /// The turn was cancelled while the decision was pending.
163    pub const fn cancelled() -> Self {
164        Self {
165            outcome: ToolPermissionOutcome::Cancelled,
166            scope: ToolPermissionScope::Once,
167            source: ToolPermissionSource::User,
168        }
169    }
170
171    pub(crate) const fn approver_unavailable() -> Self {
172        Self {
173            outcome: ToolPermissionOutcome::Denied,
174            scope: ToolPermissionScope::Once,
175            source: ToolPermissionSource::ApproverUnavailable,
176        }
177    }
178}
179
180/// One call awaiting a decision, sent to the host's approver.
181///
182/// The host answers on `reply`. Dropping `reply` without answering counts as an
183/// unavailable approver, so the gate fails closed.
184#[derive(Debug)]
185pub struct PermissionRequest {
186    pub run_id: RunId,
187    pub call: ToolCallItem,
188    pub reply: oneshot::Sender<PermissionDecision>,
189}
190
191/// The permission gate a host attaches to a run.
192#[derive(Clone, Debug, Default)]
193pub struct ToolPermissionGate {
194    pub policy: ToolPermissionPolicy,
195    /// Where `Ask` decisions go. Absent means nobody can be asked, and every
196    /// `Ask` is denied as `approver_unavailable`.
197    pub approver: Option<mpsc::UnboundedSender<PermissionRequest>>,
198}
199
200/// Everything a host may attach to one run.
201///
202/// The default attaches nothing, and a run executed with it emits exactly the
203/// Events it emitted before control existed. Recorded benchmark campaigns
204/// depend on that.
205#[derive(Clone, Debug, Default)]
206pub struct RunControl {
207    pub cancellation: Option<RunCancellation>,
208    /// Absent means no gate at all: every call runs, and no permission Event
209    /// is recorded.
210    pub permissions: Option<ToolPermissionGate>,
211}
212
213impl RunControl {
214    pub fn is_cancelled(&self) -> bool {
215        self.cancellation
216            .as_ref()
217            .is_some_and(RunCancellation::is_cancelled)
218    }
219}