Skip to main content

merry_runtime/permission/
decision.rs

1//! Admission decision, review metadata, actor attribution, and error types.
2
3use super::PermissionRequest;
4use merry_core::{ApprovalScope, CoreError};
5use merry_llm::FinishReason;
6use serde::{Deserialize, Serialize};
7use std::{future::Future, pin::Pin};
8use thiserror::Error;
9use tokio_util::sync::CancellationToken;
10
11/// Result returned by a permission admission gate.
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub enum PermissionAdmissionDecision {
14    /// The requested exact action may run through the configured permissioned runner.
15    Approved(PermissionAdmissionReview),
16    /// The requested action must not run.
17    Denied(PermissionAdmissionReview),
18}
19
20impl PermissionAdmissionDecision {
21    #[must_use]
22    pub fn approved(rationale: impl Into<String>) -> Self {
23        Self::approved_with_scope(ApprovalScope::Once, rationale)
24    }
25
26    #[must_use]
27    pub fn approved_with_scope(scope: ApprovalScope, rationale: impl Into<String>) -> Self {
28        Self::approved_with_scope_and_note(scope, rationale, None)
29    }
30
31    /// Creates a host approval decision with an explicit scope and optional user guidance note.
32    #[must_use]
33    pub fn approved_with_scope_and_note(
34        scope: ApprovalScope,
35        rationale: impl Into<String>,
36        user_note: Option<String>,
37    ) -> Self {
38        Self::Approved(
39            PermissionAdmissionReview::new(
40                PermissionAdmissionReviewSource::Host,
41                PermissionReviewRisk::Unknown,
42                PermissionUserAuthorization::Unknown,
43                rationale,
44            )
45            .with_approval_scope(scope)
46            .with_user_note(user_note),
47        )
48    }
49
50    pub(crate) fn approved_existing_grant() -> Self {
51        Self::Approved(PermissionAdmissionReview::new(
52            PermissionAdmissionReviewSource::ExistingGrant,
53            PermissionReviewRisk::Low,
54            PermissionUserAuthorization::High,
55            "requested capabilities are already authorized by the current process session",
56        ))
57    }
58
59    #[must_use]
60    pub fn denied(rationale: impl Into<String>) -> Self {
61        Self::denied_with_note(rationale, None)
62    }
63
64    /// Creates a host denial decision with an optional user note to guide the agent and reviewer.
65    #[must_use]
66    pub fn denied_with_note(rationale: impl Into<String>, user_note: Option<String>) -> Self {
67        Self::Denied(
68            PermissionAdmissionReview::new(
69                PermissionAdmissionReviewSource::Host,
70                PermissionReviewRisk::Unknown,
71                PermissionUserAuthorization::Unknown,
72                rationale,
73            )
74            .with_user_note(user_note),
75        )
76    }
77
78    pub(crate) fn is_approved(&self) -> bool {
79        matches!(self, Self::Approved(_))
80    }
81
82    pub(crate) fn review(&self) -> &PermissionAdmissionReview {
83        match self {
84            Self::Approved(review) | Self::Denied(review) => review,
85        }
86    }
87
88    pub(crate) fn approval_scope(&self) -> ApprovalScope {
89        match self {
90            Self::Approved(review) => review.approval_scope(),
91            Self::Denied(_) => ApprovalScope::Once,
92        }
93    }
94
95    /// Returns the optional user-supplied note attached to this decision.
96    #[must_use]
97    pub fn user_note(&self) -> Option<&str> {
98        self.review().user_note()
99    }
100}
101
102/// Metadata for one admission decision.
103#[derive(Debug, Clone, PartialEq, Eq)]
104pub struct PermissionAdmissionReview {
105    source: PermissionAdmissionReviewSource,
106    risk: PermissionReviewRisk,
107    user_authorization: PermissionUserAuthorization,
108    rationale: String,
109    approval_scope: ApprovalScope,
110    user_note: Option<String>,
111}
112
113impl PermissionAdmissionReview {
114    pub(super) fn new(
115        source: PermissionAdmissionReviewSource,
116        risk: PermissionReviewRisk,
117        user_authorization: PermissionUserAuthorization,
118        rationale: impl Into<String>,
119    ) -> Self {
120        Self {
121            source,
122            risk,
123            user_authorization,
124            rationale: rationale.into(),
125            approval_scope: ApprovalScope::Once,
126            user_note: None,
127        }
128    }
129
130    #[must_use]
131    pub(crate) const fn with_approval_scope(mut self, scope: ApprovalScope) -> Self {
132        self.approval_scope = scope;
133        self
134    }
135
136    #[must_use]
137    pub(crate) fn with_user_note(mut self, user_note: Option<String>) -> Self {
138        self.user_note = user_note
139            .map(|note| note.trim().to_owned())
140            .filter(|note| !note.is_empty());
141        self
142    }
143
144    /// Returns the requested/effective lifetime scope for this approval.
145    #[must_use]
146    pub const fn approval_scope(&self) -> ApprovalScope {
147        self.approval_scope
148    }
149
150    /// Returns the optional user-authored note supplied during human review.
151    #[must_use]
152    pub fn user_note(&self) -> Option<&str> {
153        self.user_note.as_deref()
154    }
155
156    #[must_use]
157    pub fn rationale(&self) -> &str {
158        &self.rationale
159    }
160
161    /// Returns the source that produced this review metadata.
162    #[must_use]
163    pub const fn source(&self) -> PermissionAdmissionReviewSource {
164        self.source
165    }
166
167    /// Returns the reviewer's risk assessment.
168    #[must_use]
169    pub const fn risk(&self) -> PermissionReviewRisk {
170        self.risk
171    }
172
173    /// Returns the reviewer's user-authorization assessment.
174    #[must_use]
175    pub const fn user_authorization(&self) -> PermissionUserAuthorization {
176        self.user_authorization
177    }
178
179    /// Returns whether a model approval is internally consistent with Merry's
180    /// admission thresholds.
181    ///
182    /// - `Low` and `Medium` risk actions may auto-approve when grounded in the
183    ///   user's current task (`Medium` or `High` authorization).
184    /// - `High` risk clearable actions may auto-approve only under explicit
185    ///   user direction (`High` authorization).
186    /// - `Critical` (hard-deny) and `Unknown` risk actions never auto-approve.
187    pub(super) fn can_auto_approve(&self) -> bool {
188        matches!(
189            (self.risk, self.user_authorization),
190            (
191                PermissionReviewRisk::Low | PermissionReviewRisk::Medium,
192                PermissionUserAuthorization::Medium | PermissionUserAuthorization::High,
193            ) | (
194                PermissionReviewRisk::High,
195                PermissionUserAuthorization::High
196            )
197        )
198    }
199}
200
201#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
202#[serde(rename_all = "snake_case")]
203pub enum PermissionAdmissionReviewSource {
204    Host,
205    Model,
206    ExistingGrant,
207}
208
209#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
210#[serde(rename_all = "snake_case")]
211pub enum PermissionReviewRisk {
212    Low,
213    Medium,
214    High,
215    Critical,
216    Unknown,
217}
218
219impl PermissionReviewRisk {
220    pub(super) fn from_model(value: &str) -> Result<Self, PermissionAdmissionError> {
221        match value {
222            "low" => Ok(Self::Low),
223            "medium" => Ok(Self::Medium),
224            "high" => Ok(Self::High),
225            "critical" => Ok(Self::Critical),
226            "unknown" => Ok(Self::Unknown),
227            actual => Err(PermissionAdmissionError::InvalidReviewOutput {
228                message: format!("risk must be low|medium|high|critical|unknown, got {actual:?}"),
229            }),
230        }
231    }
232
233    #[must_use]
234    pub const fn as_str(self) -> &'static str {
235        match self {
236            Self::Low => "low",
237            Self::Medium => "medium",
238            Self::High => "high",
239            Self::Critical => "critical",
240            Self::Unknown => "unknown",
241        }
242    }
243}
244
245#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
246#[serde(rename_all = "snake_case")]
247pub enum PermissionUserAuthorization {
248    Unknown,
249    Low,
250    Medium,
251    High,
252}
253
254impl PermissionUserAuthorization {
255    pub(super) fn from_model(value: &str) -> Result<Self, PermissionAdmissionError> {
256        match value {
257            "unknown" => Ok(Self::Unknown),
258            "low" => Ok(Self::Low),
259            "medium" => Ok(Self::Medium),
260            "high" => Ok(Self::High),
261            actual => Err(PermissionAdmissionError::InvalidReviewOutput {
262                message: format!(
263                    "user_authorization must be unknown|low|medium|high, got {actual:?}"
264                ),
265            }),
266        }
267    }
268
269    #[must_use]
270    pub const fn as_str(self) -> &'static str {
271        match self {
272            Self::Unknown => "unknown",
273            Self::Low => "low",
274            Self::Medium => "medium",
275            Self::High => "high",
276        }
277    }
278}
279
280/// Boxed admission review future.
281pub type PermissionAdmissionFuture<'a> =
282    Pin<Box<dyn Future<Output = PermissionAdmissionResult> + Send + 'a>>;
283
284/// Admission gate result.
285pub type PermissionAdmissionResult = Result<PermissionAdmissionDecision, PermissionAdmissionError>;
286
287/// Object-safe permission admission boundary.
288pub trait PermissionAdmissionSource: Send + Sync {
289    fn review<'a>(
290        &'a self,
291        request: PermissionRequest,
292        context: PermissionAdmissionContext,
293    ) -> PermissionAdmissionFuture<'a>;
294}
295
296/// Why a permission request reached the host after AI review was attempted.
297///
298/// Under [`super::PermissionReviewMode::ModelThenHostFallback`] the host is
299/// asked only after the AI review step; this records what that step produced so
300/// a host prompt can distinguish an AI denial from AI review being unavailable.
301#[derive(Debug, Clone, PartialEq, Eq)]
302pub enum HostFallbackReason {
303    /// The AI reviewer denied the request, or approved it without enough
304    /// confidence to admit it. The original review metadata is retained.
305    ModelDenied(PermissionAdmissionReview),
306    /// AI review ran but could not produce a decision.
307    ReviewFailed { message: String },
308    /// No approval-review model is configured, so AI review was skipped.
309    ReviewModelUnavailable,
310}
311
312impl HostFallbackReason {
313    /// Returns the AI review behind a [`HostFallbackReason::ModelDenied`].
314    #[must_use]
315    pub const fn model_review(&self) -> Option<&PermissionAdmissionReview> {
316        match self {
317            Self::ModelDenied(review) => Some(review),
318            Self::ReviewFailed { .. } | Self::ReviewModelUnavailable => None,
319        }
320    }
321}
322
323impl std::fmt::Display for HostFallbackReason {
324    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
325        match self {
326            Self::ModelDenied(review) => {
327                write!(formatter, "AI review denied: {}", review.rationale())
328            }
329            Self::ReviewFailed { message } => {
330                write!(formatter, "AI review unavailable: {message}")
331            }
332            Self::ReviewModelUnavailable => {
333                formatter.write_str("AI review unavailable: no approval-review model is configured")
334            }
335        }
336    }
337}
338
339/// Identifies whether a permission review request originated from the main
340/// session or a managed subagent.
341#[derive(Debug, Clone, Default, PartialEq, Eq)]
342pub enum PermissionActor {
343    /// Request originated directly from the primary/main agent session.
344    #[default]
345    MainAgent,
346    /// Request originated from a managed child subagent.
347    Subagent {
348        /// Stable runtime-assigned subagent identifier.
349        agent_id: merry_core::SubagentId,
350        /// Optional human-friendly display name assigned to the child task.
351        display_name: Option<String>,
352        /// Optional resolved role name (e.g. `coder`, `review`, `explore`).
353        role: Option<String>,
354    },
355}
356
357/// Cancellation-aware permission admission context.
358#[derive(Debug, Clone)]
359pub struct PermissionAdmissionContext {
360    cancellation_token: CancellationToken,
361    host_fallback_reason: Option<HostFallbackReason>,
362    actor: PermissionActor,
363}
364
365impl PermissionAdmissionContext {
366    #[must_use]
367    pub fn new(cancellation_token: CancellationToken) -> Self {
368        Self {
369            cancellation_token,
370            host_fallback_reason: None,
371            actor: PermissionActor::MainAgent,
372        }
373    }
374
375    #[must_use]
376    pub fn cancellation_token(&self) -> &CancellationToken {
377        &self.cancellation_token
378    }
379
380    /// Records why AI review handed this request to the host.
381    #[must_use]
382    pub fn with_host_fallback_reason(mut self, reason: HostFallbackReason) -> Self {
383        self.host_fallback_reason = Some(reason);
384        self
385    }
386
387    /// Returns why AI review handed this request to the host, if it did.
388    #[must_use]
389    pub const fn host_fallback_reason(&self) -> Option<&HostFallbackReason> {
390        self.host_fallback_reason.as_ref()
391    }
392
393    /// Attaches the actor identity that originated this permission request.
394    #[must_use]
395    pub fn with_actor(mut self, actor: PermissionActor) -> Self {
396        self.actor = actor;
397        self
398    }
399
400    /// Returns the actor identity that originated this permission request.
401    #[must_use]
402    pub const fn actor(&self) -> &PermissionActor {
403        &self.actor
404    }
405}
406
407/// Errors raised by permission request parsing or admission.
408#[derive(Debug, Error)]
409pub enum PermissionAdmissionError {
410    /// Tool arguments were invalid and should be returned to the model.
411    #[error("invalid permission request arguments: {message}")]
412    InvalidArguments { message: String },
413    /// No reviewer/model was configured for a required permission gate.
414    #[error("permission review is required but no review model is configured")]
415    ReviewModelUnavailable,
416    /// Model-backed review failed before producing a decision.
417    #[error("permission review failed: {message}")]
418    ReviewFailed { message: String },
419    /// Model-backed review returned output that violates the review contract.
420    #[error("permission review output is invalid: {message}")]
421    InvalidReviewOutput { message: String },
422    /// The reviewer ran out of output tokens before it could answer.
423    ///
424    /// This is an output-budget failure rather than a contract violation: the
425    /// reviewer never reached the review contract, so runtime policy may retry
426    /// it with a larger budget or hand the decision to the host instead of
427    /// recording the reviewer as non-compliant.
428    #[error(
429        "permission review ran out of output tokens before answering: reviewer finished with {finish_reason:?} instead of stop"
430    )]
431    ReviewOutputTruncated {
432        /// Finish reason reported by the provider.
433        finish_reason: FinishReason,
434    },
435    /// The optional human fallback could not accept or await a response.
436    #[error("human permission review is unavailable: {message}")]
437    HumanReviewUnavailable { message: String },
438    /// A response did not match the currently pending request identity.
439    #[error("stale permission review response: expected {expected}, got {actual}")]
440    StaleReviewResponse { expected: String, actual: String },
441    /// Permission admission observed cooperative cancellation.
442    #[error("permission admission cancelled")]
443    Cancelled,
444    /// Core protocol value rejected the tool definition.
445    #[error(transparent)]
446    Core {
447        /// Source core validation error.
448        #[from]
449        source: CoreError,
450    },
451}