merry-runtime 0.1.1

Structured session, task ledger, context compaction, memory, permission, and tool runtime for Merry.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
//! Runtime-owned permission request and approval review primitives.
//!
//! Permission requests wrap an exact planned action and its minimum capabilities.
//! A process may declare known capabilities before execution; a failed sandboxed
//! action may instead request capabilities discovered from its durable result.
//! Runtime owns admission and executes the exact process action after approval.

use crate::{PathAccess, ProcessActionIntent};
use merry_core::{CoreError, PendingToolCall, ToolName};
use merry_llm::FinishReason;
use serde::{Deserialize, Serialize};
use std::{future::Future, pin::Pin};
use thiserror::Error;
use tokio_util::sync::CancellationToken;

const REQUEST_PERMISSIONS_TOOL_NAME: &str = "request_permissions";
const MAX_PERMISSION_REASON_BYTES: usize = 2048;
const MAX_REVIEW_RULES_PER_CATEGORY: usize = 64;
const MAX_REVIEW_RULE_BYTES: usize = 512;
pub(crate) const MAX_RECORDED_PERMISSION_DECISIONS: usize = 16;
const DEFAULT_PERMISSION_STDOUT_LIMIT_BYTES: usize = 64 * 1024;
const DEFAULT_PERMISSION_STDERR_LIMIT_BYTES: usize = 64 * 1024;
mod channel;
pub(crate) mod environment;
mod input;
mod payload;
mod request_json;
mod review;

pub use channel::{
    ChannelPermissionAdmissionSource, PermissionReviewRequest, PermissionReviewResponse,
    PermissionReviewResponseError,
};
pub(crate) use environment::{PermissionReviewEnvironmentMetadata, probe_environment_metadata};
pub(crate) use input::{
    RequestedCapabilitiesInput, normalize_requested_capabilities, normalize_requested_path,
    permission_reason_schema_for_schemars, permission_request_from_call,
    permission_request_from_process_call, process_cwd_schema_for_schemars,
    requested_capabilities_schema_for_schemars, validate_optional_reason,
};
pub use input::{parse_permission_request, request_permissions_tool};
pub(crate) use payload::{
    permission_blocked_outcome, permission_denied_outcome, permission_invalid_arguments_outcome,
    permission_review_error_outcome,
};
pub(crate) use request_json::permission_request_fingerprint_json;
pub(crate) use review::ModelBackedPermissionAdmissionSource;

/// User-trusted custom rules and environment notes for AI permission review.
///
/// Sourced exclusively from trusted global configuration (never project-local
/// hidden files) so a repository cannot silently relax its own review rules.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct PermissionReviewRules {
    environment: Vec<String>,
    allow: Vec<String>,
    soft_deny: Vec<String>,
    hard_deny: Vec<String>,
}

impl PermissionReviewRules {
    /// Constructs validated reviewer rules from global configuration lists.
    pub fn new(
        environment: Vec<String>,
        allow: Vec<String>,
        soft_deny: Vec<String>,
        hard_deny: Vec<String>,
    ) -> Result<Self, PermissionAdmissionError> {
        Ok(Self {
            environment: validate_review_rule_list("environment", environment)?,
            allow: validate_review_rule_list("allow", allow)?,
            soft_deny: validate_review_rule_list("soft_deny", soft_deny)?,
            hard_deny: validate_review_rule_list("hard_deny", hard_deny)?,
        })
    }

    /// Returns whether all four rule lists are empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.environment.is_empty()
            && self.allow.is_empty()
            && self.soft_deny.is_empty()
            && self.hard_deny.is_empty()
    }

    /// Returns trusted environment context entries.
    #[must_use]
    pub fn environment(&self) -> &[String] {
        &self.environment
    }

    /// Returns custom routine-allow carve-outs (never override hard-deny).
    #[must_use]
    pub fn allow(&self) -> &[String] {
        &self.allow
    }

    /// Returns custom soft-deny rules (clearable by explicit user authorization).
    #[must_use]
    pub fn soft_deny(&self) -> &[String] {
        &self.soft_deny
    }

    /// Returns custom hard-deny rules (critical; never auto-approved).
    #[must_use]
    pub fn hard_deny(&self) -> &[String] {
        &self.hard_deny
    }
}

fn validate_review_rule_list(
    category: &str,
    entries: Vec<String>,
) -> Result<Vec<String>, PermissionAdmissionError> {
    if entries.len() > MAX_REVIEW_RULES_PER_CATEGORY {
        return Err(PermissionAdmissionError::InvalidArguments {
            message: format!(
                "permissions.review.{category} may contain at most {MAX_REVIEW_RULES_PER_CATEGORY} entries"
            ),
        });
    }
    let mut normalized = Vec::with_capacity(entries.len());
    for entry in entries {
        let trimmed = entry.trim();
        if trimmed.is_empty() {
            return Err(PermissionAdmissionError::InvalidArguments {
                message: format!("permissions.review.{category} entries must not be blank"),
            });
        }
        if trimmed.len() > MAX_REVIEW_RULE_BYTES {
            return Err(PermissionAdmissionError::InvalidArguments {
                message: format!(
                    "permissions.review.{category} entry exceeds {MAX_REVIEW_RULE_BYTES} bytes"
                ),
            });
        }
        if trimmed.chars().any(char::is_control) {
            return Err(PermissionAdmissionError::InvalidArguments {
                message: format!(
                    "permissions.review.{category} entries must not contain control characters"
                ),
            });
        }
        normalized.push(trimmed.to_owned());
    }
    Ok(normalized)
}

/// Harness-recorded summary of one prior permission review outcome in this session.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct RecordedPermissionDecision {
    source: PermissionAdmissionReviewSource,
    approved: bool,
    tool_name: String,
    command: String,
    requested_json: String,
}

impl RecordedPermissionDecision {
    pub(crate) fn from_request_and_decision(
        request: &PermissionRequest,
        decision: &PermissionAdmissionDecision,
    ) -> Self {
        let PermissionedAction::Process(intent) = request.action();
        Self {
            source: decision.review().source(),
            approved: decision.is_approved(),
            tool_name: request.tool_name().as_str().to_owned(),
            command: crate::shell_command_for_argv(intent.argv()),
            requested_json: request_json::requested_capabilities_json(request.requested())
                .to_string(),
        }
    }

    pub(crate) fn render_json_line(&self) -> String {
        serde_json::json!({
            "source": self.source.as_str(),
            "decision": if self.approved { "approved" } else { "denied" },
            "tool": sanitize_recorded_field(&self.tool_name),
            "command": sanitize_recorded_field(&self.command),
            "requested": sanitize_recorded_field(&self.requested_json),
        })
        .to_string()
    }
}

fn sanitize_recorded_field(text: &str) -> String {
    const MAX_LEN: usize = 320;
    let flattened: String = text
        .chars()
        .map(|ch| {
            if matches!(
                ch,
                '\r' | '\n' | '\u{0085}' | '\u{000B}' | '\u{000C}' | '\u{2028}' | '\u{2029}'
            ) {
                ' '
            } else {
                ch
            }
        })
        .collect();
    crate::compaction::bounded_excerpt(&flattened, MAX_LEN)
}

/// How much runtime should trust the host/runtime owner for permission gates.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RuntimeTrustLevel {
    /// Agentic/coding-agent runtime. Permissioned actions require review.
    Agent,
    /// Trusted SDK or host app runtime. The host may explicitly disable review.
    TrustedSdk,
}

/// Review mode for explicit permission requests.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PermissionReviewMode {
    /// Runtime chooses the conservative default for the trust level.
    DefaultForTrust,
    /// Always route permission requests through a review source.
    Required,
    /// Allow an injected non-model admission source to decide without model review.
    HostDecisionOnly,
    /// Try AI review first, then wait on an injected host source when the AI
    /// review denies the request or cannot produce a decision.
    ModelThenHostFallback,
    /// Explicit SDK/host mode that admits configured registered tools without
    /// an AI or human approval round.
    FullyTrusted,
    /// Deny every permission request and action review without consulting a
    /// reviewer. Actions that need no approval still run.
    DenyAll,
}

impl PermissionReviewMode {
    /// Returns whether the caller explicitly disabled permission review.
    pub(crate) const fn is_fully_trusted(self) -> bool {
        matches!(self, Self::FullyTrusted)
    }

    /// Returns whether every permission request is rejected without review.
    pub(crate) const fn is_deny_all(self) -> bool {
        matches!(self, Self::DenyAll)
    }

    pub(crate) fn requires_model_review(self, trust_level: RuntimeTrustLevel) -> bool {
        match self {
            Self::DefaultForTrust => trust_level == RuntimeTrustLevel::Agent,
            Self::Required => true,
            Self::HostDecisionOnly => false,
            Self::ModelThenHostFallback => true,
            Self::FullyTrusted | Self::DenyAll => false,
        }
    }
}

/// Extra capability requested for a permissioned action.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RequestedCapability {
    /// Allow network access in the selected permissioned backend/profile.
    Network,
    /// Allow filesystem access to one path in the selected backend/profile.
    Path(RequestedPathCapability),
    /// Allow one explicitly configured host integration in the selected
    /// permissioned backend/profile.
    HostIntegration(HostIntegration),
}

/// Host integration and supporting client files exposed to inner process actions.
/// Trusted global configuration is the capability ceiling and preauthorizes the
/// inner action sandbox; an integration the configuration did not enable can
/// still be requested for one permissioned action when the backend supports it
/// and its endpoint is visible.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum HostIntegration {
    /// The user's SSH authentication agent socket and read-only known-hosts files.
    SshAgent,
    /// The user's D-Bus session bus socket, commonly used by keyring clients.
    SessionBus,
    /// The native GnuPG agent and read-only public-key client integration, separate from SSH.
    GpgAgent,
}

impl HostIntegration {
    /// Returns the stable model/configuration name for this integration.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::SshAgent => "ssh-agent",
            Self::SessionBus => "dbus",
            Self::GpgAgent => "gpg-agent",
        }
    }
}

/// Requested filesystem capability for one path.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RequestedPathCapability {
    path: String,
    access: PathAccess,
}

impl RequestedPathCapability {
    pub fn new(path: String, access: PathAccess) -> Result<Self, PermissionAdmissionError> {
        let path = normalize_requested_path(&path)?;
        Ok(Self { path, access })
    }

    #[must_use]
    pub fn path(&self) -> &str {
        &self.path
    }

    #[must_use]
    pub const fn access(&self) -> PathAccess {
        self.access
    }
}

/// Exact action covered by a permission request.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PermissionedAction {
    /// Execute one validated process intent.
    Process(ProcessActionIntent),
}

impl PermissionedAction {
    #[must_use]
    pub fn kind(&self) -> &'static str {
        match self {
            Self::Process(_) => "process",
        }
    }

    #[must_use]
    pub fn summary(&self) -> &str {
        match self {
            Self::Process(intent) => intent.summary(),
        }
    }
}

/// Runtime-owned normalized permission request.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PermissionRequest {
    tool_call_id: merry_core::ToolCallId,
    tool_name: ToolName,
    reason: Option<String>,
    requested: Vec<RequestedCapability>,
    action: PermissionedAction,
    review_context: Vec<PermissionReviewContextEntry>,
    review_only: bool,
}

impl PermissionRequest {
    pub(crate) fn new(
        call: &PendingToolCall,
        reason: Option<String>,
        requested: Vec<RequestedCapability>,
        action: PermissionedAction,
        review_context: Vec<PermissionReviewContextEntry>,
    ) -> Result<Self, PermissionAdmissionError> {
        if requested.is_empty() {
            return Err(PermissionAdmissionError::InvalidArguments {
                message: "request_permissions requires at least one requested capability"
                    .to_owned(),
            });
        }
        if let Some(reason) = reason.as_deref() {
            validate_optional_reason(reason)?;
        }

        let requested = normalize_requested_capabilities(requested)?;

        Ok(Self {
            tool_call_id: call.id().clone(),
            tool_name: call.name().clone(),
            reason,
            requested,
            action,
            review_context,
            review_only: false,
        })
    }

    /// Creates a review-only request for a high-risk action.
    ///
    /// Unlike a capability request, this does not grant or retain any
    /// capability. It reuses the same admission source to review the exact
    /// action before a separately configured runner executes it.
    pub(crate) fn for_action_review(
        call: &PendingToolCall,
        reason: impl Into<String>,
        action: PermissionedAction,
        review_context: Vec<PermissionReviewContextEntry>,
    ) -> Self {
        Self {
            tool_call_id: call.id().clone(),
            tool_name: call.name().clone(),
            reason: Some(reason.into()),
            requested: Vec::new(),
            action,
            review_context,
            review_only: true,
        }
    }

    #[must_use]
    pub fn tool_call_id(&self) -> &merry_core::ToolCallId {
        &self.tool_call_id
    }

    #[must_use]
    pub fn tool_name(&self) -> &ToolName {
        &self.tool_name
    }

    #[must_use]
    pub fn reason(&self) -> Option<&str> {
        self.reason.as_deref()
    }

    #[must_use]
    pub fn requested(&self) -> &[RequestedCapability] {
        &self.requested
    }

    /// Returns whether this request asks for network capability.
    #[must_use]
    pub fn requests_network(&self) -> bool {
        self.requested
            .iter()
            .any(|capability| matches!(capability, RequestedCapability::Network))
    }

    /// Returns whether this request reviews an action without granting a
    /// capability.
    #[must_use]
    pub fn is_action_review(&self) -> bool {
        self.review_only
    }

    #[must_use]
    pub fn action(&self) -> &PermissionedAction {
        &self.action
    }

    #[must_use]
    pub(crate) fn review_context(&self) -> &[PermissionReviewContextEntry] {
        &self.review_context
    }

    /// Returns the stable fingerprint for the exact action and capability set.
    #[must_use]
    pub fn fingerprint(&self) -> String {
        crate::process::stable_process_input_fingerprint(
            permission_request_fingerprint_json(self)
                .to_string()
                .as_bytes(),
        )
    }

    /// Returns the stable identifier used to correlate a host response.
    #[must_use]
    pub fn approval_id(&self) -> String {
        format!("{}:{}", self.tool_call_id(), self.fingerprint())
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct PermissionReviewContextEntry {
    role: &'static str,
    text: String,
}

impl PermissionReviewContextEntry {
    pub(crate) fn new(role: &'static str, text: String) -> Self {
        Self { role, text }
    }

    fn role(&self) -> &'static str {
        self.role
    }

    fn text(&self) -> &str {
        &self.text
    }
}

/// Result returned by a permission admission gate.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PermissionAdmissionDecision {
    /// The requested exact action may run through the configured permissioned runner.
    Approved(PermissionAdmissionReview),
    /// The requested action must not run.
    Denied(PermissionAdmissionReview),
}

impl PermissionAdmissionDecision {
    #[must_use]
    pub fn approved(rationale: impl Into<String>) -> Self {
        Self::Approved(PermissionAdmissionReview::new(
            PermissionAdmissionReviewSource::Host,
            PermissionReviewRisk::Unknown,
            PermissionUserAuthorization::Unknown,
            rationale,
        ))
    }

    pub(crate) fn approved_existing_grant() -> Self {
        Self::Approved(PermissionAdmissionReview::new(
            PermissionAdmissionReviewSource::ExistingGrant,
            PermissionReviewRisk::Low,
            PermissionUserAuthorization::High,
            "requested capabilities are already authorized by the current process session",
        ))
    }

    #[must_use]
    pub fn denied(rationale: impl Into<String>) -> Self {
        Self::Denied(PermissionAdmissionReview::new(
            PermissionAdmissionReviewSource::Host,
            PermissionReviewRisk::Unknown,
            PermissionUserAuthorization::Unknown,
            rationale,
        ))
    }

    pub(crate) fn is_approved(&self) -> bool {
        matches!(self, Self::Approved(_))
    }

    pub(crate) fn review(&self) -> &PermissionAdmissionReview {
        match self {
            Self::Approved(review) | Self::Denied(review) => review,
        }
    }
}

/// Metadata for one admission decision.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PermissionAdmissionReview {
    source: PermissionAdmissionReviewSource,
    risk: PermissionReviewRisk,
    user_authorization: PermissionUserAuthorization,
    rationale: String,
}

impl PermissionAdmissionReview {
    fn new(
        source: PermissionAdmissionReviewSource,
        risk: PermissionReviewRisk,
        user_authorization: PermissionUserAuthorization,
        rationale: impl Into<String>,
    ) -> Self {
        Self {
            source,
            risk,
            user_authorization,
            rationale: rationale.into(),
        }
    }

    #[must_use]
    pub fn rationale(&self) -> &str {
        &self.rationale
    }

    /// Returns the source that produced this review metadata.
    #[must_use]
    pub const fn source(&self) -> PermissionAdmissionReviewSource {
        self.source
    }

    /// Returns the reviewer's risk assessment.
    #[must_use]
    pub const fn risk(&self) -> PermissionReviewRisk {
        self.risk
    }

    /// Returns the reviewer's user-authorization assessment.
    #[must_use]
    pub const fn user_authorization(&self) -> PermissionUserAuthorization {
        self.user_authorization
    }

    /// Returns whether a model approval is internally consistent with Merry's
    /// admission thresholds.
    ///
    /// - `Low` and `Medium` risk actions may auto-approve when grounded in the
    ///   user's current task (`Medium` or `High` authorization).
    /// - `High` risk clearable actions may auto-approve only under explicit
    ///   user direction (`High` authorization).
    /// - `Critical` (hard-deny) and `Unknown` risk actions never auto-approve.
    fn can_auto_approve(&self) -> bool {
        matches!(
            (self.risk, self.user_authorization),
            (
                PermissionReviewRisk::Low | PermissionReviewRisk::Medium,
                PermissionUserAuthorization::Medium | PermissionUserAuthorization::High,
            ) | (
                PermissionReviewRisk::High,
                PermissionUserAuthorization::High
            )
        )
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PermissionAdmissionReviewSource {
    Host,
    Model,
    ExistingGrant,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PermissionReviewRisk {
    Low,
    Medium,
    High,
    Critical,
    Unknown,
}

impl PermissionReviewRisk {
    fn from_model(value: &str) -> Result<Self, PermissionAdmissionError> {
        match value {
            "low" => Ok(Self::Low),
            "medium" => Ok(Self::Medium),
            "high" => Ok(Self::High),
            "critical" => Ok(Self::Critical),
            "unknown" => Ok(Self::Unknown),
            actual => Err(PermissionAdmissionError::InvalidReviewOutput {
                message: format!("risk must be low|medium|high|critical|unknown, got {actual:?}"),
            }),
        }
    }

    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Low => "low",
            Self::Medium => "medium",
            Self::High => "high",
            Self::Critical => "critical",
            Self::Unknown => "unknown",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PermissionUserAuthorization {
    Unknown,
    Low,
    Medium,
    High,
}

impl PermissionUserAuthorization {
    fn from_model(value: &str) -> Result<Self, PermissionAdmissionError> {
        match value {
            "unknown" => Ok(Self::Unknown),
            "low" => Ok(Self::Low),
            "medium" => Ok(Self::Medium),
            "high" => Ok(Self::High),
            actual => Err(PermissionAdmissionError::InvalidReviewOutput {
                message: format!(
                    "user_authorization must be unknown|low|medium|high, got {actual:?}"
                ),
            }),
        }
    }

    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Unknown => "unknown",
            Self::Low => "low",
            Self::Medium => "medium",
            Self::High => "high",
        }
    }
}

/// Boxed admission review future.
pub type PermissionAdmissionFuture<'a> =
    Pin<Box<dyn Future<Output = PermissionAdmissionResult> + Send + 'a>>;

/// Admission gate result.
pub type PermissionAdmissionResult = Result<PermissionAdmissionDecision, PermissionAdmissionError>;

/// Object-safe permission admission boundary.
pub trait PermissionAdmissionSource: Send + Sync {
    fn review<'a>(
        &'a self,
        request: PermissionRequest,
        context: PermissionAdmissionContext,
    ) -> PermissionAdmissionFuture<'a>;
}

/// Why a permission request reached the host after AI review was attempted.
///
/// Under [`PermissionReviewMode::ModelThenHostFallback`] the host is asked
/// only after the AI review step; this records what that step produced so a
/// host prompt can distinguish an AI denial from AI review being unavailable.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HostFallbackReason {
    /// The AI reviewer denied the request, or approved it without enough
    /// confidence to admit it. The original review metadata is retained.
    ModelDenied(PermissionAdmissionReview),
    /// AI review ran but could not produce a decision.
    ReviewFailed { message: String },
    /// No approval-review model is configured, so AI review was skipped.
    ReviewModelUnavailable,
}

impl HostFallbackReason {
    /// Returns the AI review behind a [`HostFallbackReason::ModelDenied`].
    #[must_use]
    pub const fn model_review(&self) -> Option<&PermissionAdmissionReview> {
        match self {
            Self::ModelDenied(review) => Some(review),
            Self::ReviewFailed { .. } | Self::ReviewModelUnavailable => None,
        }
    }
}

impl std::fmt::Display for HostFallbackReason {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::ModelDenied(review) => {
                write!(formatter, "AI review denied: {}", review.rationale())
            }
            Self::ReviewFailed { message } => {
                write!(formatter, "AI review unavailable: {message}")
            }
            Self::ReviewModelUnavailable => {
                formatter.write_str("AI review unavailable: no approval-review model is configured")
            }
        }
    }
}

/// Identifies whether a permission review request originated from the main
/// session or a managed subagent.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum PermissionActor {
    /// Request originated directly from the primary/main agent session.
    #[default]
    MainAgent,
    /// Request originated from a managed child subagent.
    Subagent {
        /// Stable runtime-assigned subagent identifier.
        agent_id: merry_core::SubagentId,
        /// Optional human-friendly display name assigned to the child task.
        display_name: Option<String>,
        /// Optional resolved role name (e.g. `coder`, `review`, `explore`).
        role: Option<String>,
    },
}

/// Cancellation-aware permission admission context.
#[derive(Debug, Clone)]
pub struct PermissionAdmissionContext {
    cancellation_token: CancellationToken,
    host_fallback_reason: Option<HostFallbackReason>,
    actor: PermissionActor,
}

impl PermissionAdmissionContext {
    #[must_use]
    pub fn new(cancellation_token: CancellationToken) -> Self {
        Self {
            cancellation_token,
            host_fallback_reason: None,
            actor: PermissionActor::MainAgent,
        }
    }

    #[must_use]
    pub fn cancellation_token(&self) -> &CancellationToken {
        &self.cancellation_token
    }

    /// Records why AI review handed this request to the host.
    #[must_use]
    pub fn with_host_fallback_reason(mut self, reason: HostFallbackReason) -> Self {
        self.host_fallback_reason = Some(reason);
        self
    }

    /// Returns why AI review handed this request to the host, if it did.
    #[must_use]
    pub const fn host_fallback_reason(&self) -> Option<&HostFallbackReason> {
        self.host_fallback_reason.as_ref()
    }

    /// Attaches the actor identity that originated this permission request.
    #[must_use]
    pub fn with_actor(mut self, actor: PermissionActor) -> Self {
        self.actor = actor;
        self
    }

    /// Returns the actor identity that originated this permission request.
    #[must_use]
    pub const fn actor(&self) -> &PermissionActor {
        &self.actor
    }
}

/// Errors raised by permission request parsing or admission.
#[derive(Debug, Error)]
pub enum PermissionAdmissionError {
    /// Tool arguments were invalid and should be returned to the model.
    #[error("invalid permission request arguments: {message}")]
    InvalidArguments { message: String },
    /// No reviewer/model was configured for a required permission gate.
    #[error("permission review is required but no review model is configured")]
    ReviewModelUnavailable,
    /// Model-backed review failed before producing a decision.
    #[error("permission review failed: {message}")]
    ReviewFailed { message: String },
    /// Model-backed review returned output that violates the review contract.
    #[error("permission review output is invalid: {message}")]
    InvalidReviewOutput { message: String },
    /// The reviewer ran out of output tokens before it could answer.
    ///
    /// This is an output-budget failure rather than a contract violation: the
    /// reviewer never reached the review contract, so runtime policy may retry
    /// it with a larger budget or hand the decision to the host instead of
    /// recording the reviewer as non-compliant.
    #[error(
        "permission review ran out of output tokens before answering: reviewer finished with {finish_reason:?} instead of stop"
    )]
    ReviewOutputTruncated {
        /// Finish reason reported by the provider.
        finish_reason: FinishReason,
    },
    /// The optional human fallback could not accept or await a response.
    #[error("human permission review is unavailable: {message}")]
    HumanReviewUnavailable { message: String },
    /// A response did not match the currently pending request identity.
    #[error("stale permission review response: expected {expected}, got {actual}")]
    StaleReviewResponse { expected: String, actual: String },
    /// Permission admission observed cooperative cancellation.
    #[error("permission admission cancelled")]
    Cancelled,
    /// Core protocol value rejected the tool definition.
    #[error(transparent)]
    Core {
        /// Source core validation error.
        #[from]
        source: CoreError,
    },
}

#[cfg(test)]
mod tests;