Skip to main content

merry_runtime/
permission.rs

1//! Runtime-owned permission request and approval review primitives.
2//!
3//! Permission requests wrap an exact planned action and its minimum capabilities.
4//! A process may declare known capabilities before execution; a failed sandboxed
5//! action may instead request capabilities discovered from its durable result.
6//! Runtime owns admission and executes the exact process action after approval.
7
8use crate::{PathAccess, ProcessActionIntent};
9use merry_core::{CoreError, PendingToolCall, ToolName};
10use merry_llm::FinishReason;
11use serde::{Deserialize, Serialize};
12use std::{future::Future, pin::Pin};
13use thiserror::Error;
14use tokio_util::sync::CancellationToken;
15
16const REQUEST_PERMISSIONS_TOOL_NAME: &str = "request_permissions";
17const MAX_PERMISSION_REASON_BYTES: usize = 2048;
18const MAX_REVIEW_RULES_PER_CATEGORY: usize = 64;
19const MAX_REVIEW_RULE_BYTES: usize = 512;
20pub(crate) const MAX_RECORDED_PERMISSION_DECISIONS: usize = 16;
21const DEFAULT_PERMISSION_STDOUT_LIMIT_BYTES: usize = 64 * 1024;
22const DEFAULT_PERMISSION_STDERR_LIMIT_BYTES: usize = 64 * 1024;
23mod channel;
24pub(crate) mod environment;
25mod input;
26mod payload;
27mod request_json;
28mod review;
29
30pub use channel::{
31    ChannelPermissionAdmissionSource, PermissionReviewRequest, PermissionReviewResponse,
32    PermissionReviewResponseError,
33};
34pub(crate) use environment::{PermissionReviewEnvironmentMetadata, probe_environment_metadata};
35pub(crate) use input::{
36    RequestedCapabilitiesInput, normalize_requested_capabilities, normalize_requested_path,
37    permission_reason_schema_for_schemars, permission_request_from_call,
38    permission_request_from_process_call, process_cwd_schema_for_schemars,
39    requested_capabilities_schema_for_schemars, validate_optional_reason,
40};
41pub use input::{parse_permission_request, request_permissions_tool};
42pub(crate) use payload::{
43    permission_blocked_outcome, permission_denied_outcome, permission_invalid_arguments_outcome,
44    permission_review_error_outcome,
45};
46pub(crate) use request_json::permission_request_fingerprint_json;
47pub(crate) use review::ModelBackedPermissionAdmissionSource;
48
49/// User-trusted custom rules and environment notes for AI permission review.
50///
51/// Sourced exclusively from trusted global configuration (never project-local
52/// hidden files) so a repository cannot silently relax its own review rules.
53#[derive(Debug, Clone, Default, PartialEq, Eq)]
54pub struct PermissionReviewRules {
55    environment: Vec<String>,
56    allow: Vec<String>,
57    soft_deny: Vec<String>,
58    hard_deny: Vec<String>,
59}
60
61impl PermissionReviewRules {
62    /// Constructs validated reviewer rules from global configuration lists.
63    pub fn new(
64        environment: Vec<String>,
65        allow: Vec<String>,
66        soft_deny: Vec<String>,
67        hard_deny: Vec<String>,
68    ) -> Result<Self, PermissionAdmissionError> {
69        Ok(Self {
70            environment: validate_review_rule_list("environment", environment)?,
71            allow: validate_review_rule_list("allow", allow)?,
72            soft_deny: validate_review_rule_list("soft_deny", soft_deny)?,
73            hard_deny: validate_review_rule_list("hard_deny", hard_deny)?,
74        })
75    }
76
77    /// Returns whether all four rule lists are empty.
78    #[must_use]
79    pub fn is_empty(&self) -> bool {
80        self.environment.is_empty()
81            && self.allow.is_empty()
82            && self.soft_deny.is_empty()
83            && self.hard_deny.is_empty()
84    }
85
86    /// Returns trusted environment context entries.
87    #[must_use]
88    pub fn environment(&self) -> &[String] {
89        &self.environment
90    }
91
92    /// Returns custom routine-allow carve-outs (never override hard-deny).
93    #[must_use]
94    pub fn allow(&self) -> &[String] {
95        &self.allow
96    }
97
98    /// Returns custom soft-deny rules (clearable by explicit user authorization).
99    #[must_use]
100    pub fn soft_deny(&self) -> &[String] {
101        &self.soft_deny
102    }
103
104    /// Returns custom hard-deny rules (critical; never auto-approved).
105    #[must_use]
106    pub fn hard_deny(&self) -> &[String] {
107        &self.hard_deny
108    }
109}
110
111fn validate_review_rule_list(
112    category: &str,
113    entries: Vec<String>,
114) -> Result<Vec<String>, PermissionAdmissionError> {
115    if entries.len() > MAX_REVIEW_RULES_PER_CATEGORY {
116        return Err(PermissionAdmissionError::InvalidArguments {
117            message: format!(
118                "permissions.review.{category} may contain at most {MAX_REVIEW_RULES_PER_CATEGORY} entries"
119            ),
120        });
121    }
122    let mut normalized = Vec::with_capacity(entries.len());
123    for entry in entries {
124        let trimmed = entry.trim();
125        if trimmed.is_empty() {
126            return Err(PermissionAdmissionError::InvalidArguments {
127                message: format!("permissions.review.{category} entries must not be blank"),
128            });
129        }
130        if trimmed.len() > MAX_REVIEW_RULE_BYTES {
131            return Err(PermissionAdmissionError::InvalidArguments {
132                message: format!(
133                    "permissions.review.{category} entry exceeds {MAX_REVIEW_RULE_BYTES} bytes"
134                ),
135            });
136        }
137        if trimmed.chars().any(char::is_control) {
138            return Err(PermissionAdmissionError::InvalidArguments {
139                message: format!(
140                    "permissions.review.{category} entries must not contain control characters"
141                ),
142            });
143        }
144        normalized.push(trimmed.to_owned());
145    }
146    Ok(normalized)
147}
148
149/// Harness-recorded summary of one prior permission review outcome in this session.
150#[derive(Debug, Clone, PartialEq, Eq)]
151pub(crate) struct RecordedPermissionDecision {
152    source: PermissionAdmissionReviewSource,
153    approved: bool,
154    tool_name: String,
155    command: String,
156    requested_json: String,
157}
158
159impl RecordedPermissionDecision {
160    pub(crate) fn from_request_and_decision(
161        request: &PermissionRequest,
162        decision: &PermissionAdmissionDecision,
163    ) -> Self {
164        let PermissionedAction::Process(intent) = request.action();
165        Self {
166            source: decision.review().source(),
167            approved: decision.is_approved(),
168            tool_name: request.tool_name().as_str().to_owned(),
169            command: crate::shell_command_for_argv(intent.argv()),
170            requested_json: request_json::requested_capabilities_json(request.requested())
171                .to_string(),
172        }
173    }
174
175    pub(crate) fn render_json_line(&self) -> String {
176        serde_json::json!({
177            "source": self.source.as_str(),
178            "decision": if self.approved { "approved" } else { "denied" },
179            "tool": sanitize_recorded_field(&self.tool_name),
180            "command": sanitize_recorded_field(&self.command),
181            "requested": sanitize_recorded_field(&self.requested_json),
182        })
183        .to_string()
184    }
185}
186
187fn sanitize_recorded_field(text: &str) -> String {
188    const MAX_LEN: usize = 320;
189    let flattened: String = text
190        .chars()
191        .map(|ch| {
192            if matches!(
193                ch,
194                '\r' | '\n' | '\u{0085}' | '\u{000B}' | '\u{000C}' | '\u{2028}' | '\u{2029}'
195            ) {
196                ' '
197            } else {
198                ch
199            }
200        })
201        .collect();
202    crate::compaction::bounded_excerpt(&flattened, MAX_LEN)
203}
204
205/// How much runtime should trust the host/runtime owner for permission gates.
206#[derive(Debug, Clone, Copy, PartialEq, Eq)]
207pub enum RuntimeTrustLevel {
208    /// Agentic/coding-agent runtime. Permissioned actions require review.
209    Agent,
210    /// Trusted SDK or host app runtime. The host may explicitly disable review.
211    TrustedSdk,
212}
213
214/// Review mode for explicit permission requests.
215#[derive(Debug, Clone, Copy, PartialEq, Eq)]
216pub enum PermissionReviewMode {
217    /// Runtime chooses the conservative default for the trust level.
218    DefaultForTrust,
219    /// Always route permission requests through a review source.
220    Required,
221    /// Allow an injected non-model admission source to decide without model review.
222    HostDecisionOnly,
223    /// Try AI review first, then wait on an injected host source when the AI
224    /// review denies the request or cannot produce a decision.
225    ModelThenHostFallback,
226    /// Explicit SDK/host mode that admits configured registered tools without
227    /// an AI or human approval round.
228    FullyTrusted,
229    /// Deny every permission request and action review without consulting a
230    /// reviewer. Actions that need no approval still run.
231    DenyAll,
232}
233
234impl PermissionReviewMode {
235    /// Returns whether the caller explicitly disabled permission review.
236    pub(crate) const fn is_fully_trusted(self) -> bool {
237        matches!(self, Self::FullyTrusted)
238    }
239
240    /// Returns whether every permission request is rejected without review.
241    pub(crate) const fn is_deny_all(self) -> bool {
242        matches!(self, Self::DenyAll)
243    }
244
245    pub(crate) fn requires_model_review(self, trust_level: RuntimeTrustLevel) -> bool {
246        match self {
247            Self::DefaultForTrust => trust_level == RuntimeTrustLevel::Agent,
248            Self::Required => true,
249            Self::HostDecisionOnly => false,
250            Self::ModelThenHostFallback => true,
251            Self::FullyTrusted | Self::DenyAll => false,
252        }
253    }
254}
255
256/// Extra capability requested for a permissioned action.
257#[derive(Debug, Clone, PartialEq, Eq)]
258pub enum RequestedCapability {
259    /// Allow network access in the selected permissioned backend/profile.
260    Network,
261    /// Allow filesystem access to one path in the selected backend/profile.
262    Path(RequestedPathCapability),
263    /// Allow one explicitly configured host integration in the selected
264    /// permissioned backend/profile.
265    HostIntegration(HostIntegration),
266}
267
268/// Host integration and supporting client files exposed to inner process actions.
269/// Trusted global configuration is the capability ceiling and preauthorizes the
270/// inner action sandbox; an integration the configuration did not enable can
271/// still be requested for one permissioned action when the backend supports it
272/// and its endpoint is visible.
273#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
274pub enum HostIntegration {
275    /// The user's SSH authentication agent socket and read-only known-hosts files.
276    SshAgent,
277    /// The user's D-Bus session bus socket, commonly used by keyring clients.
278    SessionBus,
279    /// The native GnuPG agent and read-only public-key client integration, separate from SSH.
280    GpgAgent,
281}
282
283impl HostIntegration {
284    /// Returns the stable model/configuration name for this integration.
285    #[must_use]
286    pub const fn as_str(self) -> &'static str {
287        match self {
288            Self::SshAgent => "ssh-agent",
289            Self::SessionBus => "dbus",
290            Self::GpgAgent => "gpg-agent",
291        }
292    }
293}
294
295/// Requested filesystem capability for one path.
296#[derive(Debug, Clone, PartialEq, Eq)]
297pub struct RequestedPathCapability {
298    path: String,
299    access: PathAccess,
300}
301
302impl RequestedPathCapability {
303    pub fn new(path: String, access: PathAccess) -> Result<Self, PermissionAdmissionError> {
304        let path = normalize_requested_path(&path)?;
305        Ok(Self { path, access })
306    }
307
308    #[must_use]
309    pub fn path(&self) -> &str {
310        &self.path
311    }
312
313    #[must_use]
314    pub const fn access(&self) -> PathAccess {
315        self.access
316    }
317}
318
319/// Exact action covered by a permission request.
320#[derive(Debug, Clone, PartialEq, Eq)]
321pub enum PermissionedAction {
322    /// Execute one validated process intent.
323    Process(ProcessActionIntent),
324}
325
326impl PermissionedAction {
327    #[must_use]
328    pub fn kind(&self) -> &'static str {
329        match self {
330            Self::Process(_) => "process",
331        }
332    }
333
334    #[must_use]
335    pub fn summary(&self) -> &str {
336        match self {
337            Self::Process(intent) => intent.summary(),
338        }
339    }
340}
341
342/// Runtime-owned normalized permission request.
343#[derive(Debug, Clone, PartialEq, Eq)]
344pub struct PermissionRequest {
345    tool_call_id: merry_core::ToolCallId,
346    tool_name: ToolName,
347    reason: Option<String>,
348    requested: Vec<RequestedCapability>,
349    action: PermissionedAction,
350    review_context: Vec<PermissionReviewContextEntry>,
351    review_only: bool,
352}
353
354impl PermissionRequest {
355    pub(crate) fn new(
356        call: &PendingToolCall,
357        reason: Option<String>,
358        requested: Vec<RequestedCapability>,
359        action: PermissionedAction,
360        review_context: Vec<PermissionReviewContextEntry>,
361    ) -> Result<Self, PermissionAdmissionError> {
362        if requested.is_empty() {
363            return Err(PermissionAdmissionError::InvalidArguments {
364                message: "request_permissions requires at least one requested capability"
365                    .to_owned(),
366            });
367        }
368        if let Some(reason) = reason.as_deref() {
369            validate_optional_reason(reason)?;
370        }
371
372        let requested = normalize_requested_capabilities(requested)?;
373
374        Ok(Self {
375            tool_call_id: call.id().clone(),
376            tool_name: call.name().clone(),
377            reason,
378            requested,
379            action,
380            review_context,
381            review_only: false,
382        })
383    }
384
385    /// Creates a review-only request for a high-risk action.
386    ///
387    /// Unlike a capability request, this does not grant or retain any
388    /// capability. It reuses the same admission source to review the exact
389    /// action before a separately configured runner executes it.
390    pub(crate) fn for_action_review(
391        call: &PendingToolCall,
392        reason: impl Into<String>,
393        action: PermissionedAction,
394        review_context: Vec<PermissionReviewContextEntry>,
395    ) -> Self {
396        Self {
397            tool_call_id: call.id().clone(),
398            tool_name: call.name().clone(),
399            reason: Some(reason.into()),
400            requested: Vec::new(),
401            action,
402            review_context,
403            review_only: true,
404        }
405    }
406
407    #[must_use]
408    pub fn tool_call_id(&self) -> &merry_core::ToolCallId {
409        &self.tool_call_id
410    }
411
412    #[must_use]
413    pub fn tool_name(&self) -> &ToolName {
414        &self.tool_name
415    }
416
417    #[must_use]
418    pub fn reason(&self) -> Option<&str> {
419        self.reason.as_deref()
420    }
421
422    #[must_use]
423    pub fn requested(&self) -> &[RequestedCapability] {
424        &self.requested
425    }
426
427    /// Returns whether this request asks for network capability.
428    #[must_use]
429    pub fn requests_network(&self) -> bool {
430        self.requested
431            .iter()
432            .any(|capability| matches!(capability, RequestedCapability::Network))
433    }
434
435    /// Returns whether this request reviews an action without granting a
436    /// capability.
437    #[must_use]
438    pub fn is_action_review(&self) -> bool {
439        self.review_only
440    }
441
442    #[must_use]
443    pub fn action(&self) -> &PermissionedAction {
444        &self.action
445    }
446
447    #[must_use]
448    pub(crate) fn review_context(&self) -> &[PermissionReviewContextEntry] {
449        &self.review_context
450    }
451
452    /// Returns the stable fingerprint for the exact action and capability set.
453    #[must_use]
454    pub fn fingerprint(&self) -> String {
455        crate::process::stable_process_input_fingerprint(
456            permission_request_fingerprint_json(self)
457                .to_string()
458                .as_bytes(),
459        )
460    }
461
462    /// Returns the stable identifier used to correlate a host response.
463    #[must_use]
464    pub fn approval_id(&self) -> String {
465        format!("{}:{}", self.tool_call_id(), self.fingerprint())
466    }
467}
468
469#[derive(Debug, Clone, PartialEq, Eq)]
470pub(crate) struct PermissionReviewContextEntry {
471    role: &'static str,
472    text: String,
473}
474
475impl PermissionReviewContextEntry {
476    pub(crate) fn new(role: &'static str, text: String) -> Self {
477        Self { role, text }
478    }
479
480    fn role(&self) -> &'static str {
481        self.role
482    }
483
484    fn text(&self) -> &str {
485        &self.text
486    }
487}
488
489/// Result returned by a permission admission gate.
490#[derive(Debug, Clone, PartialEq, Eq)]
491pub enum PermissionAdmissionDecision {
492    /// The requested exact action may run through the configured permissioned runner.
493    Approved(PermissionAdmissionReview),
494    /// The requested action must not run.
495    Denied(PermissionAdmissionReview),
496}
497
498impl PermissionAdmissionDecision {
499    #[must_use]
500    pub fn approved(rationale: impl Into<String>) -> Self {
501        Self::Approved(PermissionAdmissionReview::new(
502            PermissionAdmissionReviewSource::Host,
503            PermissionReviewRisk::Unknown,
504            PermissionUserAuthorization::Unknown,
505            rationale,
506        ))
507    }
508
509    pub(crate) fn approved_existing_grant() -> Self {
510        Self::Approved(PermissionAdmissionReview::new(
511            PermissionAdmissionReviewSource::ExistingGrant,
512            PermissionReviewRisk::Low,
513            PermissionUserAuthorization::High,
514            "requested capabilities are already authorized by the current process session",
515        ))
516    }
517
518    #[must_use]
519    pub fn denied(rationale: impl Into<String>) -> Self {
520        Self::Denied(PermissionAdmissionReview::new(
521            PermissionAdmissionReviewSource::Host,
522            PermissionReviewRisk::Unknown,
523            PermissionUserAuthorization::Unknown,
524            rationale,
525        ))
526    }
527
528    pub(crate) fn is_approved(&self) -> bool {
529        matches!(self, Self::Approved(_))
530    }
531
532    pub(crate) fn review(&self) -> &PermissionAdmissionReview {
533        match self {
534            Self::Approved(review) | Self::Denied(review) => review,
535        }
536    }
537}
538
539/// Metadata for one admission decision.
540#[derive(Debug, Clone, PartialEq, Eq)]
541pub struct PermissionAdmissionReview {
542    source: PermissionAdmissionReviewSource,
543    risk: PermissionReviewRisk,
544    user_authorization: PermissionUserAuthorization,
545    rationale: String,
546}
547
548impl PermissionAdmissionReview {
549    fn new(
550        source: PermissionAdmissionReviewSource,
551        risk: PermissionReviewRisk,
552        user_authorization: PermissionUserAuthorization,
553        rationale: impl Into<String>,
554    ) -> Self {
555        Self {
556            source,
557            risk,
558            user_authorization,
559            rationale: rationale.into(),
560        }
561    }
562
563    #[must_use]
564    pub fn rationale(&self) -> &str {
565        &self.rationale
566    }
567
568    /// Returns the source that produced this review metadata.
569    #[must_use]
570    pub const fn source(&self) -> PermissionAdmissionReviewSource {
571        self.source
572    }
573
574    /// Returns the reviewer's risk assessment.
575    #[must_use]
576    pub const fn risk(&self) -> PermissionReviewRisk {
577        self.risk
578    }
579
580    /// Returns the reviewer's user-authorization assessment.
581    #[must_use]
582    pub const fn user_authorization(&self) -> PermissionUserAuthorization {
583        self.user_authorization
584    }
585
586    /// Returns whether a model approval is internally consistent with Merry's
587    /// admission thresholds.
588    ///
589    /// - `Low` and `Medium` risk actions may auto-approve when grounded in the
590    ///   user's current task (`Medium` or `High` authorization).
591    /// - `High` risk clearable actions may auto-approve only under explicit
592    ///   user direction (`High` authorization).
593    /// - `Critical` (hard-deny) and `Unknown` risk actions never auto-approve.
594    fn can_auto_approve(&self) -> bool {
595        matches!(
596            (self.risk, self.user_authorization),
597            (
598                PermissionReviewRisk::Low | PermissionReviewRisk::Medium,
599                PermissionUserAuthorization::Medium | PermissionUserAuthorization::High,
600            ) | (
601                PermissionReviewRisk::High,
602                PermissionUserAuthorization::High
603            )
604        )
605    }
606}
607
608#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
609#[serde(rename_all = "snake_case")]
610pub enum PermissionAdmissionReviewSource {
611    Host,
612    Model,
613    ExistingGrant,
614}
615
616#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
617#[serde(rename_all = "snake_case")]
618pub enum PermissionReviewRisk {
619    Low,
620    Medium,
621    High,
622    Critical,
623    Unknown,
624}
625
626impl PermissionReviewRisk {
627    fn from_model(value: &str) -> Result<Self, PermissionAdmissionError> {
628        match value {
629            "low" => Ok(Self::Low),
630            "medium" => Ok(Self::Medium),
631            "high" => Ok(Self::High),
632            "critical" => Ok(Self::Critical),
633            "unknown" => Ok(Self::Unknown),
634            actual => Err(PermissionAdmissionError::InvalidReviewOutput {
635                message: format!("risk must be low|medium|high|critical|unknown, got {actual:?}"),
636            }),
637        }
638    }
639
640    #[must_use]
641    pub const fn as_str(self) -> &'static str {
642        match self {
643            Self::Low => "low",
644            Self::Medium => "medium",
645            Self::High => "high",
646            Self::Critical => "critical",
647            Self::Unknown => "unknown",
648        }
649    }
650}
651
652#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
653#[serde(rename_all = "snake_case")]
654pub enum PermissionUserAuthorization {
655    Unknown,
656    Low,
657    Medium,
658    High,
659}
660
661impl PermissionUserAuthorization {
662    fn from_model(value: &str) -> Result<Self, PermissionAdmissionError> {
663        match value {
664            "unknown" => Ok(Self::Unknown),
665            "low" => Ok(Self::Low),
666            "medium" => Ok(Self::Medium),
667            "high" => Ok(Self::High),
668            actual => Err(PermissionAdmissionError::InvalidReviewOutput {
669                message: format!(
670                    "user_authorization must be unknown|low|medium|high, got {actual:?}"
671                ),
672            }),
673        }
674    }
675
676    #[must_use]
677    pub const fn as_str(self) -> &'static str {
678        match self {
679            Self::Unknown => "unknown",
680            Self::Low => "low",
681            Self::Medium => "medium",
682            Self::High => "high",
683        }
684    }
685}
686
687/// Boxed admission review future.
688pub type PermissionAdmissionFuture<'a> =
689    Pin<Box<dyn Future<Output = PermissionAdmissionResult> + Send + 'a>>;
690
691/// Admission gate result.
692pub type PermissionAdmissionResult = Result<PermissionAdmissionDecision, PermissionAdmissionError>;
693
694/// Object-safe permission admission boundary.
695pub trait PermissionAdmissionSource: Send + Sync {
696    fn review<'a>(
697        &'a self,
698        request: PermissionRequest,
699        context: PermissionAdmissionContext,
700    ) -> PermissionAdmissionFuture<'a>;
701}
702
703/// Why a permission request reached the host after AI review was attempted.
704///
705/// Under [`PermissionReviewMode::ModelThenHostFallback`] the host is asked
706/// only after the AI review step; this records what that step produced so a
707/// host prompt can distinguish an AI denial from AI review being unavailable.
708#[derive(Debug, Clone, PartialEq, Eq)]
709pub enum HostFallbackReason {
710    /// The AI reviewer denied the request, or approved it without enough
711    /// confidence to admit it. The original review metadata is retained.
712    ModelDenied(PermissionAdmissionReview),
713    /// AI review ran but could not produce a decision.
714    ReviewFailed { message: String },
715    /// No approval-review model is configured, so AI review was skipped.
716    ReviewModelUnavailable,
717}
718
719impl HostFallbackReason {
720    /// Returns the AI review behind a [`HostFallbackReason::ModelDenied`].
721    #[must_use]
722    pub const fn model_review(&self) -> Option<&PermissionAdmissionReview> {
723        match self {
724            Self::ModelDenied(review) => Some(review),
725            Self::ReviewFailed { .. } | Self::ReviewModelUnavailable => None,
726        }
727    }
728}
729
730impl std::fmt::Display for HostFallbackReason {
731    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
732        match self {
733            Self::ModelDenied(review) => {
734                write!(formatter, "AI review denied: {}", review.rationale())
735            }
736            Self::ReviewFailed { message } => {
737                write!(formatter, "AI review unavailable: {message}")
738            }
739            Self::ReviewModelUnavailable => {
740                formatter.write_str("AI review unavailable: no approval-review model is configured")
741            }
742        }
743    }
744}
745
746/// Identifies whether a permission review request originated from the main
747/// session or a managed subagent.
748#[derive(Debug, Clone, Default, PartialEq, Eq)]
749pub enum PermissionActor {
750    /// Request originated directly from the primary/main agent session.
751    #[default]
752    MainAgent,
753    /// Request originated from a managed child subagent.
754    Subagent {
755        /// Stable runtime-assigned subagent identifier.
756        agent_id: merry_core::SubagentId,
757        /// Optional human-friendly display name assigned to the child task.
758        display_name: Option<String>,
759        /// Optional resolved role name (e.g. `coder`, `review`, `explore`).
760        role: Option<String>,
761    },
762}
763
764/// Cancellation-aware permission admission context.
765#[derive(Debug, Clone)]
766pub struct PermissionAdmissionContext {
767    cancellation_token: CancellationToken,
768    host_fallback_reason: Option<HostFallbackReason>,
769    actor: PermissionActor,
770}
771
772impl PermissionAdmissionContext {
773    #[must_use]
774    pub fn new(cancellation_token: CancellationToken) -> Self {
775        Self {
776            cancellation_token,
777            host_fallback_reason: None,
778            actor: PermissionActor::MainAgent,
779        }
780    }
781
782    #[must_use]
783    pub fn cancellation_token(&self) -> &CancellationToken {
784        &self.cancellation_token
785    }
786
787    /// Records why AI review handed this request to the host.
788    #[must_use]
789    pub fn with_host_fallback_reason(mut self, reason: HostFallbackReason) -> Self {
790        self.host_fallback_reason = Some(reason);
791        self
792    }
793
794    /// Returns why AI review handed this request to the host, if it did.
795    #[must_use]
796    pub const fn host_fallback_reason(&self) -> Option<&HostFallbackReason> {
797        self.host_fallback_reason.as_ref()
798    }
799
800    /// Attaches the actor identity that originated this permission request.
801    #[must_use]
802    pub fn with_actor(mut self, actor: PermissionActor) -> Self {
803        self.actor = actor;
804        self
805    }
806
807    /// Returns the actor identity that originated this permission request.
808    #[must_use]
809    pub const fn actor(&self) -> &PermissionActor {
810        &self.actor
811    }
812}
813
814/// Errors raised by permission request parsing or admission.
815#[derive(Debug, Error)]
816pub enum PermissionAdmissionError {
817    /// Tool arguments were invalid and should be returned to the model.
818    #[error("invalid permission request arguments: {message}")]
819    InvalidArguments { message: String },
820    /// No reviewer/model was configured for a required permission gate.
821    #[error("permission review is required but no review model is configured")]
822    ReviewModelUnavailable,
823    /// Model-backed review failed before producing a decision.
824    #[error("permission review failed: {message}")]
825    ReviewFailed { message: String },
826    /// Model-backed review returned output that violates the review contract.
827    #[error("permission review output is invalid: {message}")]
828    InvalidReviewOutput { message: String },
829    /// The reviewer ran out of output tokens before it could answer.
830    ///
831    /// This is an output-budget failure rather than a contract violation: the
832    /// reviewer never reached the review contract, so runtime policy may retry
833    /// it with a larger budget or hand the decision to the host instead of
834    /// recording the reviewer as non-compliant.
835    #[error(
836        "permission review ran out of output tokens before answering: reviewer finished with {finish_reason:?} instead of stop"
837    )]
838    ReviewOutputTruncated {
839        /// Finish reason reported by the provider.
840        finish_reason: FinishReason,
841    },
842    /// The optional human fallback could not accept or await a response.
843    #[error("human permission review is unavailable: {message}")]
844    HumanReviewUnavailable { message: String },
845    /// A response did not match the currently pending request identity.
846    #[error("stale permission review response: expected {expected}, got {actual}")]
847    StaleReviewResponse { expected: String, actual: String },
848    /// Permission admission observed cooperative cancellation.
849    #[error("permission admission cancelled")]
850    Cancelled,
851    /// Core protocol value rejected the tool definition.
852    #[error(transparent)]
853    Core {
854        /// Source core validation error.
855        #[from]
856        source: CoreError,
857    },
858}
859
860#[cfg(test)]
861mod tests;