merry-runtime 0.1.3

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
//! Admission decision, review metadata, actor attribution, and error types.

use super::PermissionRequest;
use merry_core::{ApprovalScope, CoreError};
use merry_llm::FinishReason;
use serde::{Deserialize, Serialize};
use std::{future::Future, pin::Pin};
use thiserror::Error;
use tokio_util::sync::CancellationToken;

/// 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_with_scope(ApprovalScope::Once, rationale)
    }

    #[must_use]
    pub fn approved_with_scope(scope: ApprovalScope, rationale: impl Into<String>) -> Self {
        Self::approved_with_scope_and_note(scope, rationale, None)
    }

    /// Creates a host approval decision with an explicit scope and optional user guidance note.
    #[must_use]
    pub fn approved_with_scope_and_note(
        scope: ApprovalScope,
        rationale: impl Into<String>,
        user_note: Option<String>,
    ) -> Self {
        Self::Approved(
            PermissionAdmissionReview::new(
                PermissionAdmissionReviewSource::Host,
                PermissionReviewRisk::Unknown,
                PermissionUserAuthorization::Unknown,
                rationale,
            )
            .with_approval_scope(scope)
            .with_user_note(user_note),
        )
    }

    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_with_note(rationale, None)
    }

    /// Creates a host denial decision with an optional user note to guide the agent and reviewer.
    #[must_use]
    pub fn denied_with_note(rationale: impl Into<String>, user_note: Option<String>) -> Self {
        Self::Denied(
            PermissionAdmissionReview::new(
                PermissionAdmissionReviewSource::Host,
                PermissionReviewRisk::Unknown,
                PermissionUserAuthorization::Unknown,
                rationale,
            )
            .with_user_note(user_note),
        )
    }

    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,
        }
    }

    pub(crate) fn approval_scope(&self) -> ApprovalScope {
        match self {
            Self::Approved(review) => review.approval_scope(),
            Self::Denied(_) => ApprovalScope::Once,
        }
    }

    /// Returns the optional user-supplied note attached to this decision.
    #[must_use]
    pub fn user_note(&self) -> Option<&str> {
        self.review().user_note()
    }
}

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

impl PermissionAdmissionReview {
    pub(super) fn new(
        source: PermissionAdmissionReviewSource,
        risk: PermissionReviewRisk,
        user_authorization: PermissionUserAuthorization,
        rationale: impl Into<String>,
    ) -> Self {
        Self {
            source,
            risk,
            user_authorization,
            rationale: rationale.into(),
            approval_scope: ApprovalScope::Once,
            user_note: None,
        }
    }

    #[must_use]
    pub(crate) const fn with_approval_scope(mut self, scope: ApprovalScope) -> Self {
        self.approval_scope = scope;
        self
    }

    #[must_use]
    pub(crate) fn with_user_note(mut self, user_note: Option<String>) -> Self {
        self.user_note = user_note
            .map(|note| note.trim().to_owned())
            .filter(|note| !note.is_empty());
        self
    }

    /// Returns the requested/effective lifetime scope for this approval.
    #[must_use]
    pub const fn approval_scope(&self) -> ApprovalScope {
        self.approval_scope
    }

    /// Returns the optional user-authored note supplied during human review.
    #[must_use]
    pub fn user_note(&self) -> Option<&str> {
        self.user_note.as_deref()
    }

    #[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.
    pub(super) 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 {
    pub(super) 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 {
    pub(super) 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 [`super::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,
    },
}