1use 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#[derive(Debug, Clone, PartialEq, Eq)]
13pub enum PermissionAdmissionDecision {
14 Approved(PermissionAdmissionReview),
16 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 #[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 #[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 #[must_use]
97 pub fn user_note(&self) -> Option<&str> {
98 self.review().user_note()
99 }
100}
101
102#[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 #[must_use]
146 pub const fn approval_scope(&self) -> ApprovalScope {
147 self.approval_scope
148 }
149
150 #[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 #[must_use]
163 pub const fn source(&self) -> PermissionAdmissionReviewSource {
164 self.source
165 }
166
167 #[must_use]
169 pub const fn risk(&self) -> PermissionReviewRisk {
170 self.risk
171 }
172
173 #[must_use]
175 pub const fn user_authorization(&self) -> PermissionUserAuthorization {
176 self.user_authorization
177 }
178
179 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
280pub type PermissionAdmissionFuture<'a> =
282 Pin<Box<dyn Future<Output = PermissionAdmissionResult> + Send + 'a>>;
283
284pub type PermissionAdmissionResult = Result<PermissionAdmissionDecision, PermissionAdmissionError>;
286
287pub trait PermissionAdmissionSource: Send + Sync {
289 fn review<'a>(
290 &'a self,
291 request: PermissionRequest,
292 context: PermissionAdmissionContext,
293 ) -> PermissionAdmissionFuture<'a>;
294}
295
296#[derive(Debug, Clone, PartialEq, Eq)]
302pub enum HostFallbackReason {
303 ModelDenied(PermissionAdmissionReview),
306 ReviewFailed { message: String },
308 ReviewModelUnavailable,
310}
311
312impl HostFallbackReason {
313 #[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#[derive(Debug, Clone, Default, PartialEq, Eq)]
342pub enum PermissionActor {
343 #[default]
345 MainAgent,
346 Subagent {
348 agent_id: merry_core::SubagentId,
350 display_name: Option<String>,
352 role: Option<String>,
354 },
355}
356
357#[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 #[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 #[must_use]
389 pub const fn host_fallback_reason(&self) -> Option<&HostFallbackReason> {
390 self.host_fallback_reason.as_ref()
391 }
392
393 #[must_use]
395 pub fn with_actor(mut self, actor: PermissionActor) -> Self {
396 self.actor = actor;
397 self
398 }
399
400 #[must_use]
402 pub const fn actor(&self) -> &PermissionActor {
403 &self.actor
404 }
405}
406
407#[derive(Debug, Error)]
409pub enum PermissionAdmissionError {
410 #[error("invalid permission request arguments: {message}")]
412 InvalidArguments { message: String },
413 #[error("permission review is required but no review model is configured")]
415 ReviewModelUnavailable,
416 #[error("permission review failed: {message}")]
418 ReviewFailed { message: String },
419 #[error("permission review output is invalid: {message}")]
421 InvalidReviewOutput { message: String },
422 #[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: FinishReason,
434 },
435 #[error("human permission review is unavailable: {message}")]
437 HumanReviewUnavailable { message: String },
438 #[error("stale permission review response: expected {expected}, got {actual}")]
440 StaleReviewResponse { expected: String, actual: String },
441 #[error("permission admission cancelled")]
443 Cancelled,
444 #[error(transparent)]
446 Core {
447 #[from]
449 source: CoreError,
450 },
451}