merry-runtime 0.1.4

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
use super::CompactionError;
use crate::{
    checkpoint::CheckpointRef,
    session::{ModelTurnId, ModelTurnStatus},
    token_estimate::{ReasoningTokenAccounting, TokenEstimateScale},
};
use merry_core::{ToolCallId, ToolCallResultStatus};
use serde::Serialize;
use serde_json::Value;
use std::collections::BTreeSet;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct CompactionWindowBudget {
    primary_window_tokens: u64,
    preferred_dynamic_body_tokens: Option<u64>,
    max_dynamic_body_tokens: u64,
    replacement_fixed_dynamic_body_tokens: u64,
    archive_only_fixed_dynamic_body_tokens: u64,
    checkpoint_output_ceiling_tokens: u64,
    token_estimate_scale: TokenEstimateScale,
    reasoning_tokens: ReasoningTokenAccounting,
}

impl CompactionWindowBudget {
    pub(crate) fn new(
        primary_window_tokens: u64,
        max_dynamic_body_tokens: u64,
        replacement_fixed_dynamic_body_tokens: u64,
        archive_only_fixed_dynamic_body_tokens: u64,
        checkpoint_output_ceiling_tokens: u64,
    ) -> Result<Self, CompactionError> {
        for (field, value) in [
            ("primary_window_tokens", primary_window_tokens),
            ("max_dynamic_body_tokens", max_dynamic_body_tokens),
            (
                "checkpoint_output_ceiling_tokens",
                checkpoint_output_ceiling_tokens,
            ),
        ] {
            if value == 0 {
                return Err(CompactionError::InvalidPolicy { field });
            }
        }

        Ok(Self {
            primary_window_tokens,
            preferred_dynamic_body_tokens: None,
            max_dynamic_body_tokens,
            replacement_fixed_dynamic_body_tokens,
            archive_only_fixed_dynamic_body_tokens,
            checkpoint_output_ceiling_tokens,
            token_estimate_scale: TokenEstimateScale::default(),
            reasoning_tokens: ReasoningTokenAccounting::Exclude,
        })
    }

    #[cfg(test)]
    pub(crate) fn unbounded_for_tests(
        checkpoint_output_ceiling_tokens: u64,
    ) -> Result<Self, CompactionError> {
        Self::new(u64::MAX, u64::MAX, 0, 0, checkpoint_output_ceiling_tokens)
    }

    /// Applies the primary request calibration to destination-body estimates only.
    pub(crate) fn with_token_estimate_scale(self, scale: TokenEstimateScale) -> Self {
        Self {
            token_estimate_scale: scale,
            ..self
        }
    }

    /// Controls whether retained assistant reasoning counts toward destination-body tokens.
    pub(crate) fn with_reasoning_tokens(self, reasoning_tokens: ReasoningTokenAccounting) -> Self {
        Self {
            reasoning_tokens,
            ..self
        }
    }

    pub(crate) const fn reasoning_tokens(self) -> ReasoningTokenAccounting {
        self.reasoning_tokens
    }

    /// Converts fixed context, checkpoint, and retained history to calibrated tokens.
    pub(crate) fn estimate_body_tokens(self, base_tokens: u64) -> u64 {
        self.token_estimate_scale.estimate(base_tokens)
    }

    /// Adds a bounded history target to calibrated fixed input and summary ceiling.
    /// The body budget remains authoritative; arithmetic overflow is rejected.
    pub(crate) fn with_retained_history_target(
        self,
        retained_history_tokens: u64,
    ) -> Result<Self, CompactionError> {
        let preferred_tokens = self
            .replacement_fixed_dynamic_body_tokens
            .checked_add(self.checkpoint_output_ceiling_tokens)
            .map(|tokens| self.estimate_body_tokens(tokens))
            .and_then(|tokens| tokens.checked_add(retained_history_tokens))
            .ok_or(CompactionError::BudgetOverflow)?;
        Ok(Self {
            preferred_dynamic_body_tokens: Some(preferred_tokens.min(self.max_dynamic_body_tokens)),
            ..self
        })
    }

    /// Returns a stricter copy that uses the preferred body budget, when one exists.
    pub(crate) fn preferred(self) -> Option<Self> {
        self.preferred_dynamic_body_tokens.map(|tokens| Self {
            max_dynamic_body_tokens: tokens,
            preferred_dynamic_body_tokens: None,
            ..self
        })
    }

    pub(crate) const fn primary_window_tokens(self) -> u64 {
        self.primary_window_tokens
    }

    pub(crate) const fn max_dynamic_body_tokens(self) -> u64 {
        self.max_dynamic_body_tokens
    }

    /// Returns the dynamic-body target used after a checkpoint is installed.
    ///
    /// The preferred budget includes the fixed request body, the accepted
    /// checkpoint ceiling, and the bounded raw-history target. It is distinct
    /// from the body budget: the body budget is the largest request that can
    /// still be sent, while this target decides when repeated compaction has
    /// done enough work.
    pub(crate) const fn target_dynamic_body_tokens(self) -> u64 {
        match self.preferred_dynamic_body_tokens {
            Some(tokens) => tokens,
            None => self.max_dynamic_body_tokens,
        }
    }

    pub(crate) const fn replacement_fixed_dynamic_body_tokens(self) -> u64 {
        self.replacement_fixed_dynamic_body_tokens
    }

    pub(crate) const fn archive_only_fixed_dynamic_body_tokens(self) -> u64 {
        self.archive_only_fixed_dynamic_body_tokens
    }

    pub(crate) const fn checkpoint_output_ceiling_tokens(self) -> u64 {
        self.checkpoint_output_ceiling_tokens
    }
}

/// Upper bound on how much covered history one compaction request may read.
///
/// This bounds the compaction *request*, while [`CompactionWindowBudget`] bounds
/// the request the compaction installs. They answer different questions, so the
/// runtime tracks them separately: a replacement that cannot fit the compaction
/// model window lowers this budget, which keeps more turns raw until the request
/// fits.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub(crate) struct CompactionCoverageBudget {
    max_tokens: Option<u64>,
}

impl CompactionCoverageBudget {
    /// Keeps the planner's configured retention without a coverage cap.
    pub(crate) const fn unbounded() -> Self {
        Self { max_tokens: None }
    }

    /// Caps the covered payload at `max_tokens`.
    pub(crate) const fn limited(max_tokens: u64) -> Self {
        Self {
            max_tokens: Some(max_tokens),
        }
    }

    /// Returns the cap, or `None` when coverage is unbounded.
    pub(crate) const fn max_tokens(self) -> Option<u64> {
        self.max_tokens
    }
}

/// How one compaction pass chooses what to cover and what the payload carries.
///
/// The runtime selects this from the request it is about to build, so one value
/// describes the whole reduction instead of several loose flags.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum CompactionShape {
    /// One pass that must land inside the body budget; manual compaction.
    SinglePass,
    /// Cover the largest window one request hosts, repeating until the request fits.
    Rolling,
    /// Last resort when even user/assistant history cannot fit in one request.
    RollingText,
    /// Cover everything before the retained tail once, omitting older tool exchanges.
    OneShot {
        /// Newest covered tool exchanges kept, arguments and result together.
        retained_tool_exchanges: usize,
    },
}

impl CompactionShape {
    /// Returns how strictly this shape requires the retained history to fit.
    pub(crate) const fn retained_fit(self) -> RetainedFit {
        match self {
            Self::SinglePass | Self::OneShot { .. } => RetainedFit::Required,
            Self::Rolling | Self::RollingText => RetainedFit::Deferred,
        }
    }

    /// Returns how many covered tool exchanges stay at full length.
    ///
    /// `None` keeps every covered tool exchange at full length.
    pub(crate) const fn retained_tool_exchanges(self) -> Option<usize> {
        match self {
            Self::OneShot {
                retained_tool_exchanges,
            } => Some(retained_tool_exchanges),
            Self::RollingText => Some(0),
            Self::SinglePass | Self::Rolling => None,
        }
    }
}

/// How strictly one compaction pass must leave the retained history inside the body budget.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum RetainedFit {
    /// The pass must land under the budget, or report that no window fits.
    ///
    /// Manual compaction uses this: a caller asked for one reduction and needs to
    /// know whether one happened.
    Required,
    /// The pass may land above the budget because the runtime runs another pass.
    ///
    /// Rolling compaction uses this. Each pass covers as much history as the
    /// compaction window can host, and the caller repeats while the recompiled
    /// request still crosses the body budget. Without it, a window that shrank below
    /// the retained history could never reduce anything: every candidate would fail
    /// the budget check before anything could be installed, which is why shrinking
    /// the context window reported that no compaction window fit.
    Deferred,
}

pub(crate) fn retained_turn_fallbacks(configured: usize, available_completed: usize) -> Vec<usize> {
    (1..=configured.min(available_completed)).rev().collect()
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct CompactionWindowFingerprint(u64);

impl CompactionWindowFingerprint {
    pub(crate) const fn new(value: u64) -> Self {
        Self(value)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct CompactionWindowPlan {
    covered_turn_ids: Vec<ModelTurnId>,
    retained_turn_ids: Vec<ModelTurnId>,
    archived_tool_call_ids: BTreeSet<ToolCallId>,
    new_boundary: Option<ModelTurnId>,
    fingerprint: CompactionWindowFingerprint,
}

impl CompactionWindowPlan {
    pub(crate) fn new(
        covered_turn_ids: Vec<ModelTurnId>,
        retained_turn_ids: Vec<ModelTurnId>,
        archived_tool_call_ids: BTreeSet<ToolCallId>,
        new_boundary: Option<ModelTurnId>,
        fingerprint: CompactionWindowFingerprint,
    ) -> Self {
        Self {
            covered_turn_ids,
            retained_turn_ids,
            archived_tool_call_ids,
            new_boundary,
            fingerprint,
        }
    }

    pub(crate) fn covered_turn_ids(&self) -> &[ModelTurnId] {
        &self.covered_turn_ids
    }

    pub(crate) fn retained_turn_ids(&self) -> &[ModelTurnId] {
        &self.retained_turn_ids
    }

    pub(crate) fn archived_tool_call_ids(&self) -> &BTreeSet<ToolCallId> {
        &self.archived_tool_call_ids
    }

    pub(crate) const fn new_boundary(&self) -> Option<ModelTurnId> {
        self.new_boundary
    }

    pub(crate) const fn fingerprint(&self) -> CompactionWindowFingerprint {
        self.fingerprint
    }

    #[cfg(test)]
    pub(crate) fn covered_turn_ids_u64(&self) -> Vec<u64> {
        self.covered_turn_ids
            .iter()
            .map(|turn_id| turn_id.as_u64())
            .collect()
    }

    #[cfg(test)]
    pub(crate) fn retained_turn_ids_u64(&self) -> Vec<u64> {
        self.retained_turn_ids
            .iter()
            .map(|turn_id| turn_id.as_u64())
            .collect()
    }

    #[cfg(test)]
    pub(crate) fn archived_tool_call_ids_for_tests(&self) -> Vec<ToolCallId> {
        self.archived_tool_call_ids.iter().cloned().collect()
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ArchiveOnlyCompactionInput {
    window_plan: CompactionWindowPlan,
    archived_refs: Vec<CheckpointRef>,
}

impl ArchiveOnlyCompactionInput {
    pub(crate) fn new(
        window_plan: CompactionWindowPlan,
        archived_refs: Vec<CheckpointRef>,
    ) -> Self {
        Self {
            window_plan,
            archived_refs,
        }
    }

    pub(crate) fn window_plan(&self) -> &CompactionWindowPlan {
        &self.window_plan
    }

    pub(crate) fn archived_refs(&self) -> &[CheckpointRef] {
        &self.archived_refs
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub(crate) struct CitationCompactionModelTurn {
    turn_id: u64,
    status: CitationCompactionTurnStatus,
    items: Vec<CitationCompactionTurnItem>,
}

impl CitationCompactionModelTurn {
    pub(crate) fn new(
        turn_id: ModelTurnId,
        status: ModelTurnStatus,
        items: Vec<CitationCompactionTurnItem>,
    ) -> Result<Self, CompactionError> {
        let status = match status {
            ModelTurnStatus::Completed => CitationCompactionTurnStatus::Completed,
            ModelTurnStatus::Aborted => CitationCompactionTurnStatus::Aborted,
            ModelTurnStatus::InProgress | ModelTurnStatus::AwaitingToolResults => {
                return Err(CompactionError::StaleWindow);
            }
        };
        Ok(Self {
            turn_id: turn_id.as_u64(),
            status,
            items,
        })
    }

    pub(crate) fn tool_exchange_count(&self) -> usize {
        self.items
            .iter()
            .filter(|item| matches!(item, CitationCompactionTurnItem::ToolExchange { .. }))
            .count()
    }

    pub(crate) fn render_markdown(&self) -> String {
        let mut lines = vec![format!("## Turn {} ({:?})", self.turn_id, self.status)];
        for item in &self.items {
            lines.push(item.render_markdown());
        }
        lines.join("\n\n")
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
enum CitationCompactionTurnStatus {
    Completed,
    Aborted,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "role", rename_all = "snake_case")]
pub(crate) enum CitationCompactionTurnItem {
    User {
        history_id: u64,
        ref_id: String,
        text: String,
    },
    Assistant {
        history_id: u64,
        ref_id: String,
        text: String,
    },
    ToolExchange {
        history_id: u64,
        ref_id: String,
        call_id: String,
        name: String,
        arguments: Value,
        result: CitationCompactionToolResult,
    },
}

impl CitationCompactionTurnItem {
    pub(crate) fn user(history_id: u64, ref_id: String, text: String) -> Self {
        Self::User {
            history_id,
            ref_id,
            text,
        }
    }

    pub(crate) fn assistant(history_id: u64, ref_id: String, text: String) -> Self {
        Self::Assistant {
            history_id,
            ref_id,
            text,
        }
    }

    fn render_markdown(&self) -> String {
        match self {
            Self::User { text, .. } => format!("### User\n\n{text}"),
            Self::Assistant { text, .. } => format!("### Assistant\n\n{text}"),
            Self::ToolExchange {
                name,
                call_id,
                arguments,
                result,
                ..
            } => format!(
                "### Tool {name} ({call_id})\n\nArguments:\n{arguments}\n\nResult ({}):\n{}",
                result.status, result.content
            ),
        }
    }

    pub(crate) fn tool_exchange(
        history_id: u64,
        ref_id: String,
        call_id: &ToolCallId,
        name: String,
        arguments: Value,
        result: CitationCompactionToolResult,
    ) -> Self {
        Self::ToolExchange {
            history_id,
            ref_id,
            call_id: call_id.as_str().to_owned(),
            name,
            arguments,
            result,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub(crate) struct CitationCompactionToolResult {
    status: &'static str,
    content_kind: &'static str,
    content: String,
}

impl CitationCompactionToolResult {
    pub(crate) fn new(
        status: ToolCallResultStatus,
        content_kind: &'static str,
        content: String,
    ) -> Self {
        Self {
            status: tool_call_result_status_label(status),
            content_kind,
            content,
        }
    }
}

fn tool_call_result_status_label(status: ToolCallResultStatus) -> &'static str {
    match status {
        ToolCallResultStatus::Succeeded => "succeeded",
        ToolCallResultStatus::Failed => "failed",
    }
}