Skip to main content

merry_runtime/permission/
channel.rs

1//! Host-facing permission review transport.
2//!
3//! A host (TUI, headless driver, or embedding app) receives one typed
4//! [`PermissionReviewRequest`] per pending review and answers with one
5//! [`PermissionReviewResponse`]. The runtime validates the answer identity
6//! before it can grant anything, so a stale UI response cannot authorize a
7//! later call. Nothing here decides policy: this module only moves a request to
8//! the host and returns the host's answer.
9
10use super::{
11    HostFallbackReason, PermissionActor, PermissionAdmissionContext, PermissionAdmissionDecision,
12    PermissionAdmissionError, PermissionAdmissionFuture, PermissionAdmissionSource,
13    PermissionRequest, validate_optional_reason,
14};
15use thiserror::Error;
16use tokio::sync::{mpsc, oneshot};
17use tokio_util::sync::CancellationToken;
18
19/// A pending host-facing permission review request.
20pub struct PermissionReviewRequest {
21    request: PermissionRequest,
22    host_fallback_reason: Option<HostFallbackReason>,
23    actor: PermissionActor,
24    cancellation_token: CancellationToken,
25    response_sender: Option<oneshot::Sender<PermissionReviewResponse>>,
26}
27
28impl std::fmt::Debug for PermissionReviewRequest {
29    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30        formatter
31            .debug_struct("PermissionReviewRequest")
32            .field("approval_id", &self.approval_id())
33            .field("fingerprint", &self.fingerprint())
34            .field("actor", &self.actor)
35            .field("request", &self.request)
36            .finish_non_exhaustive()
37    }
38}
39
40impl PermissionReviewRequest {
41    /// Returns the request that must be shown to the host.
42    #[must_use]
43    pub fn request(&self) -> &PermissionRequest {
44        &self.request
45    }
46
47    /// Returns the actor identity (main agent or specific subagent) requesting permission.
48    #[must_use]
49    pub const fn actor(&self) -> &PermissionActor {
50        &self.actor
51    }
52
53    /// Returns the stable response correlation id.
54    #[must_use]
55    pub fn approval_id(&self) -> String {
56        self.request.approval_id()
57    }
58
59    /// Returns the exact request fingerprint required in a response.
60    #[must_use]
61    pub fn fingerprint(&self) -> String {
62        self.request.fingerprint()
63    }
64
65    /// Returns why AI review handed this request to the host, when it did.
66    #[must_use]
67    pub const fn host_fallback_reason(&self) -> Option<&HostFallbackReason> {
68        self.host_fallback_reason.as_ref()
69    }
70
71    /// Returns whether the runtime cancelled this pending review.
72    #[must_use]
73    pub fn is_cancelled(&self) -> bool {
74        self.cancellation_token.is_cancelled()
75    }
76
77    /// Resolves this request as an approval.
78    pub fn approve(
79        self,
80        rationale: impl Into<String>,
81    ) -> Result<(), PermissionReviewResponseError> {
82        let approval_id = self.approval_id();
83        let fingerprint = self.fingerprint();
84        self.respond(PermissionReviewResponse::allow(
85            approval_id,
86            fingerprint,
87            rationale,
88        ))
89    }
90
91    /// Resolves this request as a denial.
92    pub fn deny(self, rationale: impl Into<String>) -> Result<(), PermissionReviewResponseError> {
93        let approval_id = self.approval_id();
94        let fingerprint = self.fingerprint();
95        self.respond(PermissionReviewResponse::deny(
96            approval_id,
97            fingerprint,
98            rationale,
99        ))
100    }
101
102    /// Sends a response, including its caller-supplied correlation fields.
103    ///
104    /// The runtime validates both fields before it can grant the request, so a
105    /// stale UI response cannot authorize a later call.
106    pub fn respond(
107        mut self,
108        response: PermissionReviewResponse,
109    ) -> Result<(), PermissionReviewResponseError> {
110        let Some(sender) = self.response_sender.take() else {
111            return Err(PermissionReviewResponseError::AlreadyResolved);
112        };
113        sender
114            .send(response)
115            .map_err(|_| PermissionReviewResponseError::Closed)
116    }
117}
118
119/// Host response for one pending permission review request.
120#[derive(Debug, Clone, PartialEq, Eq)]
121pub struct PermissionReviewResponse {
122    approval_id: String,
123    fingerprint: String,
124    decision: PermissionReviewResponseDecision,
125    rationale: String,
126}
127
128impl PermissionReviewResponse {
129    /// Creates an approval response for an exact request.
130    #[must_use]
131    pub fn allow(
132        approval_id: impl Into<String>,
133        fingerprint: impl Into<String>,
134        rationale: impl Into<String>,
135    ) -> Self {
136        Self {
137            approval_id: approval_id.into(),
138            fingerprint: fingerprint.into(),
139            decision: PermissionReviewResponseDecision::Allow,
140            rationale: rationale.into(),
141        }
142    }
143
144    /// Creates a denial response for an exact request.
145    #[must_use]
146    pub fn deny(
147        approval_id: impl Into<String>,
148        fingerprint: impl Into<String>,
149        rationale: impl Into<String>,
150    ) -> Self {
151        Self {
152            approval_id: approval_id.into(),
153            fingerprint: fingerprint.into(),
154            decision: PermissionReviewResponseDecision::Deny,
155            rationale: rationale.into(),
156        }
157    }
158}
159
160#[derive(Debug, Clone, Copy, PartialEq, Eq)]
161enum PermissionReviewResponseDecision {
162    Allow,
163    Deny,
164}
165
166/// Channel-backed human fallback source.
167#[derive(Debug, Clone)]
168pub struct ChannelPermissionAdmissionSource {
169    sender: mpsc::Sender<PermissionReviewRequest>,
170}
171
172impl ChannelPermissionAdmissionSource {
173    /// Creates a source and its host-facing pending-review receiver.
174    pub fn channel(capacity: usize) -> (Self, mpsc::Receiver<PermissionReviewRequest>) {
175        let (sender, receiver) = mpsc::channel(capacity.max(1));
176        (Self { sender }, receiver)
177    }
178}
179
180impl PermissionAdmissionSource for ChannelPermissionAdmissionSource {
181    fn review<'a>(
182        &'a self,
183        request: PermissionRequest,
184        context: PermissionAdmissionContext,
185    ) -> PermissionAdmissionFuture<'a> {
186        Box::pin(async move {
187            let approval_id = request.approval_id();
188            let fingerprint = request.fingerprint();
189            let (response_sender, response_receiver) = oneshot::channel();
190            let pending = PermissionReviewRequest {
191                request: request.clone(),
192                host_fallback_reason: context.host_fallback_reason().cloned(),
193                actor: context.actor().clone(),
194                cancellation_token: context.cancellation_token().clone(),
195                response_sender: Some(response_sender),
196            };
197            tokio::select! {
198                biased;
199                () = context.cancellation_token().cancelled() => {
200                    Err(PermissionAdmissionError::Cancelled)
201                }
202                result = self.sender.send(pending) => {
203                    result.map_err(|_| PermissionAdmissionError::HumanReviewUnavailable {
204                        message: "human permission review channel is closed".to_owned(),
205                    })?;
206                    let response = tokio::select! {
207                        biased;
208                        () = context.cancellation_token().cancelled() => {
209                            return Err(PermissionAdmissionError::Cancelled);
210                        }
211                        response = response_receiver => response.map_err(|_| {
212                            PermissionAdmissionError::HumanReviewUnavailable {
213                                message: "human permission review response was closed".to_owned(),
214                            }
215                        })?,
216                    };
217                    if response.approval_id != approval_id {
218                        return Err(PermissionAdmissionError::StaleReviewResponse {
219                            expected: approval_id,
220                            actual: response.approval_id,
221                        });
222                    }
223                    if response.fingerprint != fingerprint {
224                        return Err(PermissionAdmissionError::StaleReviewResponse {
225                            expected: fingerprint,
226                            actual: response.fingerprint,
227                        });
228                    }
229                    validate_optional_reason(&response.rationale)?;
230                    let decision = match response.decision {
231                        PermissionReviewResponseDecision::Allow => {
232                            PermissionAdmissionDecision::approved(response.rationale)
233                        }
234                        PermissionReviewResponseDecision::Deny => {
235                            PermissionAdmissionDecision::denied(response.rationale)
236                        }
237                    };
238                    Ok(decision)
239                }
240            }
241        })
242    }
243}
244
245/// Error returned when a host responds to a pending review request.
246#[derive(Debug, Error, Clone, PartialEq, Eq)]
247pub enum PermissionReviewResponseError {
248    /// The pending runtime request was already resolved or cancelled.
249    #[error("permission review request is already resolved")]
250    AlreadyResolved,
251    /// The runtime no longer accepts a response for this request.
252    #[error("permission review response channel is closed")]
253    Closed,
254}