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, validate_optional_user_note,
14};
15use merry_core::ApprovalScope;
16use thiserror::Error;
17use tokio::sync::{mpsc, oneshot};
18use tokio_util::sync::CancellationToken;
19
20/// A pending host-facing permission review request.
21pub struct PermissionReviewRequest {
22    request: PermissionRequest,
23    host_fallback_reason: Option<HostFallbackReason>,
24    actor: PermissionActor,
25    cancellation_token: CancellationToken,
26    response_sender: Option<oneshot::Sender<PermissionReviewResponse>>,
27}
28
29impl std::fmt::Debug for PermissionReviewRequest {
30    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
31        formatter
32            .debug_struct("PermissionReviewRequest")
33            .field("approval_id", &self.approval_id())
34            .field("fingerprint", &self.fingerprint())
35            .field("actor", &self.actor)
36            .field("request", &self.request)
37            .finish_non_exhaustive()
38    }
39}
40
41impl PermissionReviewRequest {
42    /// Returns the request that must be shown to the host.
43    #[must_use]
44    pub fn request(&self) -> &PermissionRequest {
45        &self.request
46    }
47
48    /// Returns the actor identity (main agent or specific subagent) requesting permission.
49    #[must_use]
50    pub const fn actor(&self) -> &PermissionActor {
51        &self.actor
52    }
53
54    /// Returns the stable response correlation id.
55    #[must_use]
56    pub fn approval_id(&self) -> String {
57        self.request.approval_id()
58    }
59
60    /// Returns the exact request fingerprint required in a response.
61    #[must_use]
62    pub fn fingerprint(&self) -> String {
63        self.request.fingerprint()
64    }
65
66    /// Returns why AI review handed this request to the host, when it did.
67    #[must_use]
68    pub const fn host_fallback_reason(&self) -> Option<&HostFallbackReason> {
69        self.host_fallback_reason.as_ref()
70    }
71
72    /// Returns whether the runtime cancelled this pending review.
73    #[must_use]
74    pub fn is_cancelled(&self) -> bool {
75        self.cancellation_token.is_cancelled()
76    }
77
78    /// Resolves this request as a one-shot approval.
79    pub fn approve(
80        self,
81        rationale: impl Into<String>,
82    ) -> Result<(), PermissionReviewResponseError> {
83        self.approve_with_scope(ApprovalScope::Once, rationale)
84    }
85
86    /// Resolves this request as an approval with an explicit lifetime scope.
87    pub fn approve_with_scope(
88        self,
89        scope: ApprovalScope,
90        rationale: impl Into<String>,
91    ) -> Result<(), PermissionReviewResponseError> {
92        self.approve_with_scope_and_note(scope, rationale, None)
93    }
94
95    /// Resolves this request as an approval with an explicit lifetime scope and
96    /// an optional human guidance note for the AI reviewer.
97    pub fn approve_with_scope_and_note(
98        self,
99        scope: ApprovalScope,
100        rationale: impl Into<String>,
101        user_note: Option<String>,
102    ) -> Result<(), PermissionReviewResponseError> {
103        let approval_id = self.approval_id();
104        let fingerprint = self.fingerprint();
105        self.respond(
106            PermissionReviewResponse::allow_with_scope(approval_id, fingerprint, scope, rationale)
107                .with_user_note(user_note),
108        )
109    }
110
111    /// Resolves this request as a denial.
112    pub fn deny(self, rationale: impl Into<String>) -> Result<(), PermissionReviewResponseError> {
113        self.deny_with_note(rationale, None)
114    }
115
116    /// Resolves this request as a denial with an optional human note to guide
117    /// the working model and AI reviewer.
118    pub fn deny_with_note(
119        self,
120        rationale: impl Into<String>,
121        user_note: Option<String>,
122    ) -> Result<(), PermissionReviewResponseError> {
123        let approval_id = self.approval_id();
124        let fingerprint = self.fingerprint();
125        self.respond(
126            PermissionReviewResponse::deny(approval_id, fingerprint, rationale)
127                .with_user_note(user_note),
128        )
129    }
130
131    /// Sends a response, including its caller-supplied correlation fields.
132    ///
133    /// The runtime validates both fields before it can grant the request, so a
134    /// stale UI response cannot authorize a later call.
135    pub fn respond(
136        mut self,
137        response: PermissionReviewResponse,
138    ) -> Result<(), PermissionReviewResponseError> {
139        let Some(sender) = self.response_sender.take() else {
140            return Err(PermissionReviewResponseError::AlreadyResolved);
141        };
142        sender
143            .send(response)
144            .map_err(|_| PermissionReviewResponseError::Closed)
145    }
146}
147
148/// Host response for one pending permission review request.
149#[derive(Debug, Clone, PartialEq, Eq)]
150pub struct PermissionReviewResponse {
151    approval_id: String,
152    fingerprint: String,
153    decision: PermissionReviewResponseDecision,
154    scope: ApprovalScope,
155    rationale: String,
156    user_note: Option<String>,
157}
158
159impl PermissionReviewResponse {
160    /// Creates a one-shot approval response for an exact request.
161    #[must_use]
162    pub fn allow(
163        approval_id: impl Into<String>,
164        fingerprint: impl Into<String>,
165        rationale: impl Into<String>,
166    ) -> Self {
167        Self::allow_with_scope(approval_id, fingerprint, ApprovalScope::Once, rationale)
168    }
169
170    /// Creates an approval response for an exact request with an explicit scope.
171    #[must_use]
172    pub fn allow_with_scope(
173        approval_id: impl Into<String>,
174        fingerprint: impl Into<String>,
175        scope: ApprovalScope,
176        rationale: impl Into<String>,
177    ) -> Self {
178        Self {
179            approval_id: approval_id.into(),
180            fingerprint: fingerprint.into(),
181            decision: PermissionReviewResponseDecision::Allow,
182            scope,
183            rationale: rationale.into(),
184            user_note: None,
185        }
186    }
187
188    /// Creates a denial response for an exact request.
189    #[must_use]
190    pub fn deny(
191        approval_id: impl Into<String>,
192        fingerprint: impl Into<String>,
193        rationale: impl Into<String>,
194    ) -> Self {
195        Self {
196            approval_id: approval_id.into(),
197            fingerprint: fingerprint.into(),
198            decision: PermissionReviewResponseDecision::Deny,
199            scope: ApprovalScope::Once,
200            rationale: rationale.into(),
201            user_note: None,
202        }
203    }
204
205    /// Attaches an optional user-authored note to this review response.
206    ///
207    /// Blank or whitespace-only notes are normalized to `None`.
208    #[must_use]
209    pub fn with_user_note(mut self, user_note: Option<String>) -> Self {
210        self.user_note = user_note
211            .map(|note| note.trim().to_owned())
212            .filter(|note| !note.is_empty());
213        self
214    }
215
216    /// Returns the optional user-authored note attached to this response.
217    #[must_use]
218    pub fn user_note(&self) -> Option<&str> {
219        self.user_note.as_deref()
220    }
221}
222
223#[derive(Debug, Clone, Copy, PartialEq, Eq)]
224enum PermissionReviewResponseDecision {
225    Allow,
226    Deny,
227}
228
229/// Channel-backed human fallback source.
230#[derive(Debug, Clone)]
231pub struct ChannelPermissionAdmissionSource {
232    sender: mpsc::Sender<PermissionReviewRequest>,
233}
234
235impl ChannelPermissionAdmissionSource {
236    /// Creates a source and its host-facing pending-review receiver.
237    pub fn channel(capacity: usize) -> (Self, mpsc::Receiver<PermissionReviewRequest>) {
238        let (sender, receiver) = mpsc::channel(capacity.max(1));
239        (Self { sender }, receiver)
240    }
241}
242
243impl PermissionAdmissionSource for ChannelPermissionAdmissionSource {
244    fn review<'a>(
245        &'a self,
246        request: PermissionRequest,
247        context: PermissionAdmissionContext,
248    ) -> PermissionAdmissionFuture<'a> {
249        Box::pin(async move {
250            let approval_id = request.approval_id();
251            let fingerprint = request.fingerprint();
252            let (response_sender, response_receiver) = oneshot::channel();
253            let pending = PermissionReviewRequest {
254                request: request.clone(),
255                host_fallback_reason: context.host_fallback_reason().cloned(),
256                actor: context.actor().clone(),
257                cancellation_token: context.cancellation_token().clone(),
258                response_sender: Some(response_sender),
259            };
260            tokio::select! {
261                biased;
262                () = context.cancellation_token().cancelled() => {
263                    Err(PermissionAdmissionError::Cancelled)
264                }
265                result = self.sender.send(pending) => {
266                    result.map_err(|_| PermissionAdmissionError::HumanReviewUnavailable {
267                        message: "human permission review channel is closed".to_owned(),
268                    })?;
269                    let response = tokio::select! {
270                        biased;
271                        () = context.cancellation_token().cancelled() => {
272                            return Err(PermissionAdmissionError::Cancelled);
273                        }
274                        response = response_receiver => response.map_err(|_| {
275                            PermissionAdmissionError::HumanReviewUnavailable {
276                                message: "human permission review response was closed".to_owned(),
277                            }
278                        })?,
279                    };
280                    if response.approval_id != approval_id {
281                        return Err(PermissionAdmissionError::StaleReviewResponse {
282                            expected: approval_id,
283                            actual: response.approval_id,
284                        });
285                    }
286                    if response.fingerprint != fingerprint {
287                        return Err(PermissionAdmissionError::StaleReviewResponse {
288                            expected: fingerprint,
289                            actual: response.fingerprint,
290                        });
291                    }
292                    validate_optional_reason(&response.rationale)?;
293                    let user_note = response
294                        .user_note
295                        .map(|note| note.trim().to_owned())
296                        .filter(|note| !note.is_empty());
297                    if let Some(note) = user_note.as_deref() {
298                        validate_optional_user_note(note)?;
299                    }
300                    let decision = match response.decision {
301                        PermissionReviewResponseDecision::Allow => {
302                            PermissionAdmissionDecision::approved_with_scope_and_note(
303                                response.scope,
304                                response.rationale,
305                                user_note,
306                            )
307                        }
308                        PermissionReviewResponseDecision::Deny => {
309                            PermissionAdmissionDecision::denied_with_note(
310                                response.rationale,
311                                user_note,
312                            )
313                        }
314                    };
315                    Ok(decision)
316                }
317            }
318        })
319    }
320}
321
322/// Error returned when a host responds to a pending review request.
323#[derive(Debug, Error, Clone, PartialEq, Eq)]
324pub enum PermissionReviewResponseError {
325    /// The pending runtime request was already resolved or cancelled.
326    #[error("permission review request is already resolved")]
327    AlreadyResolved,
328    /// The runtime no longer accepts a response for this request.
329    #[error("permission review response channel is closed")]
330    Closed,
331}