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
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
//! Runtime step inputs, execution context, and provider request compilation.
//!
//! Public step types are provider-neutral. Request compilation is internal
//! glue from structured runtime state into `merry-llm` model requests; provider
//! crates render those normalized requests into wire formats.

pub use crate::user_input::StepInput;
use crate::{
    CompiledContext, FinalOutputContract, ProjectRules, PromptProfile, SkillCatalog, TaskAnchor,
    UserImageInput, UserMessageInput, prompt::render_prompt_block, session::TranscriptItemSnapshot,
};
use merry_core::{PendingToolCall, ToolCallResult, ToolCallResultStatus, ToolOutput, ToolSpec};
use merry_llm::{
    GenerationConfig, ModelContent, ModelImage, ModelInputItem, ModelMessage, ModelMessageRole,
    ModelName, ModelReasoning, ModelRequest, ModelToolCall, ModelToolCallId, ModelToolResult,
    ModelToolResultContent, ToolArguments,
};
use tokio_util::sync::CancellationToken;

/// Context shared with runtime step producers.
///
/// The context carries cancellation and provider-neutral generation controls
/// for one step. It does not carry provider conversation state.
#[derive(Debug, Clone)]
pub struct StepContext {
    cancellation_token: CancellationToken,
    generation_config: GenerationConfig,
    final_output_contract: Option<FinalOutputContract>,
}

impl StepContext {
    /// Creates a step context with the provided cancellation token.
    #[must_use]
    pub fn new(cancellation_token: CancellationToken) -> Self {
        Self {
            cancellation_token,
            generation_config: GenerationConfig::default(),
            final_output_contract: None,
        }
    }

    /// Returns the cancellation token for this step.
    ///
    /// Runtime producers check this token at cancellation checkpoints. Dropping
    /// the returned [`crate::RuntimeJournalEventStream`] also cancels the step token.
    #[must_use]
    pub fn cancellation_token(&self) -> &CancellationToken {
        &self.cancellation_token
    }

    /// Sets provider-neutral generation controls for this step.
    ///
    /// Controls are normalized Merry model settings, not provider request
    /// fields.
    #[must_use]
    pub fn with_generation_config(mut self, generation_config: GenerationConfig) -> Self {
        self.generation_config = generation_config;
        self
    }

    /// Adds a runtime-owned final-output contract to this step.
    #[must_use]
    pub fn with_final_output_contract(mut self, contract: FinalOutputContract) -> Self {
        self.final_output_contract = Some(contract);
        self
    }

    /// Returns provider-neutral generation controls for this step.
    #[must_use]
    pub fn generation_config(&self) -> &GenerationConfig {
        &self.generation_config
    }

    pub(crate) fn into_parts(
        self,
    ) -> (
        CancellationToken,
        GenerationConfig,
        Option<FinalOutputContract>,
    ) {
        (
            self.cancellation_token,
            self.generation_config,
            self.final_output_contract,
        )
    }
}

impl Default for StepContext {
    fn default() -> Self {
        Self {
            cancellation_token: CancellationToken::new(),
            generation_config: GenerationConfig::default(),
            final_output_contract: None,
        }
    }
}

/// Ordered dynamic context slots compiled around the session transcript.
///
/// Session-stable slots (`memory_context`, `checkpoint`, `task_anchor`) sit
/// immediately after the immutable prefix and before `transcript`.
/// Turn-volatile slots (`plan_control`, `compiled_context`) sit after
/// `transcript` and before the current user input so todo updates, plan
/// reminders, and per-turn memory activation do not invalidate the cached
/// multi-turn transcript prefix.
pub(crate) struct DynamicContextSlots<'a> {
    pub(crate) memory_context: Option<&'a str>,
    pub(crate) task_anchor: Option<&'a TaskAnchor>,
    pub(crate) plan_control: Option<&'a str>,
    pub(crate) context: &'a CompiledContext,
}

pub(crate) struct StepModelRequestParts<'a> {
    pub(crate) input: &'a StepInput,
    pub(crate) model: &'a ModelName,
    pub(crate) stable_prefix: StablePrefixParts<'a>,
    pub(crate) dynamic_slots: DynamicContextSlots<'a>,
    pub(crate) transcript: &'a [TranscriptItemSnapshot],
    pub(crate) tool_specs: Vec<ToolSpec>,
    pub(crate) generation_config: GenerationConfig,
}

/// Stable prompt material every request for one session starts with.
///
/// The agent loop and model-backed compaction share this prefix byte for byte so
/// a provider can serve the compaction request from the same cached prefix as
/// the session's normal requests. Compaction therefore appends its directive
/// and payload after the prefix instead of replacing it with a second system
/// prompt.
pub(crate) struct StablePrefixParts<'a> {
    pub(crate) prompt_profile: &'a PromptProfile,
    pub(crate) progress_commentary: bool,
    pub(crate) skill_catalog: Option<&'a SkillCatalog>,
    pub(crate) project_rules: Option<&'a ProjectRules>,
}

/// Compiles the ordered stable prefix items for one session.
///
/// The order is part of the provider-visible cache contract: base runtime
/// instructions, optional progress commentary instructions, profile stable
/// blocks, available skill metadata, project rules, then the reasoning-language
/// rule. Callers that append further items must not rewrite or reorder these
/// messages. The language rule stays last so later English policy text does
/// not reopen another thinking language.
pub(crate) fn compile_stable_prefix_items(
    parts: StablePrefixParts<'_>,
) -> Result<Vec<ModelInputItem>, merry_llm::ModelError> {
    let StablePrefixParts {
        prompt_profile,
        progress_commentary,
        skill_catalog,
        project_rules,
    } = parts;
    let mut items = Vec::with_capacity(
        3 + prompt_profile.stable_blocks().len() + usize::from(project_rules.is_some()),
    );

    items.push(ModelInputItem::Message(ModelMessage::new(
        ModelMessageRole::System,
        ModelContent::text(prompt_profile.base_instructions())?,
    )?));

    if progress_commentary {
        items.push(ModelInputItem::Message(ModelMessage::new(
            ModelMessageRole::System,
            ModelContent::text(prompt_profile.progress_commentary_instructions())?,
        )?));
    }

    for block in prompt_profile.stable_blocks() {
        let block_text = block.render();
        items.push(ModelInputItem::Message(ModelMessage::new(
            ModelMessageRole::System,
            ModelContent::text(&block_text)?,
        )?));
    }

    if let Some(skill_metadata_text) =
        skill_catalog.and_then(SkillCatalog::to_stable_prefix_message_text)
    {
        let skill_metadata_text = render_prompt_block("merry_skill_catalog", &skill_metadata_text);
        items.push(ModelInputItem::Message(ModelMessage::new(
            ModelMessageRole::System,
            ModelContent::text(&skill_metadata_text)?,
        )?));
    }

    if let Some(project_rules) = project_rules {
        let project_rules_text = project_rules.to_stable_prefix_message_text();
        let project_rules_text = render_prompt_block("merry_project_rules", &project_rules_text);
        items.push(ModelInputItem::Message(ModelMessage::new(
            ModelMessageRole::System,
            ModelContent::text(&project_rules_text)?,
        )?));
    }

    items.push(ModelInputItem::Message(ModelMessage::new(
        ModelMessageRole::System,
        ModelContent::text(crate::prompt::REASONING_LANGUAGE_INSTRUCTIONS)?,
    )?));

    Ok(items)
}

fn append_leading_dynamic_slots(
    messages: &mut Vec<ModelInputItem>,
    slots: &DynamicContextSlots<'_>,
) -> Result<(), merry_llm::ModelError> {
    let checkpoint_snapshot = slots.context.checkpoint_snapshot();
    messages.reserve(
        usize::from(slots.memory_context.is_some())
            + usize::from(!checkpoint_snapshot.is_empty())
            + usize::from(slots.task_anchor.is_some()),
    );

    if let Some(memory_context) = slots.memory_context.filter(|text| !text.is_empty()) {
        let memory_text = render_prompt_block("merry_memory_context", memory_context);
        messages.push(ModelInputItem::Message(ModelMessage::new(
            ModelMessageRole::System,
            ModelContent::text(&memory_text)?,
        )?));
    }

    if !checkpoint_snapshot.is_empty() {
        let checkpoint_text = render_prompt_block("merry_checkpoint", &checkpoint_snapshot);
        messages.push(ModelInputItem::Message(ModelMessage::new(
            ModelMessageRole::System,
            ModelContent::text(&checkpoint_text)?,
        )?));
    }

    if let Some(task_anchor) = slots.task_anchor {
        let task_anchor_text = task_anchor.to_dynamic_control_message_text();
        let task_anchor_text = render_prompt_block("merry_task_anchor", &task_anchor_text);
        messages.push(ModelInputItem::Message(ModelMessage::new(
            ModelMessageRole::System,
            ModelContent::text(&task_anchor_text)?,
        )?));
    }

    Ok(())
}

fn append_turn_dynamic_slots(
    messages: &mut Vec<ModelInputItem>,
    slots: &DynamicContextSlots<'_>,
) -> Result<(), merry_llm::ModelError> {
    let context_body_snapshot = slots.context.body_snapshot();
    messages.reserve(
        usize::from(slots.plan_control.is_some()) + usize::from(!context_body_snapshot.is_empty()),
    );

    if let Some(plan_control) = slots.plan_control {
        messages.push(ModelInputItem::Message(ModelMessage::new(
            ModelMessageRole::System,
            ModelContent::text(plan_control)?,
        )?));
    }

    if !context_body_snapshot.is_empty() {
        let context_text = render_prompt_block("merry_compiled_context", &context_body_snapshot);
        messages.push(ModelInputItem::Message(ModelMessage::new(
            ModelMessageRole::System,
            ModelContent::text(&context_text)?,
        )?));
    }

    Ok(())
}

pub(crate) fn compile_step_model_request(
    parts: StepModelRequestParts<'_>,
) -> Result<ModelRequest, merry_llm::ModelError> {
    let StepModelRequestParts {
        input,
        model,
        stable_prefix,
        dynamic_slots,
        transcript,
        tool_specs,
        generation_config,
    } = parts;

    // Keep provider prompt projection allowlisted and cache-ordered:
    // 1. immutable session stable prefix
    // 2. session/checkpoint-scoped dynamic slots (memory_context, checkpoint, task_anchor)
    // 3. prior ordered transcript (preserved byte-identical across turns)
    // 4. turn-volatile dynamic slots (plan_control, compiled_context)
    // 5. current user or loop-control input
    let mut messages = compile_stable_prefix_items(stable_prefix)?;
    let stable_prefix_message_count = messages.len();
    append_leading_dynamic_slots(&mut messages, &dynamic_slots)?;
    messages.reserve(transcript.len() + input.user_messages_for_request().len());

    for item in transcript {
        messages.push(model_input_from_transcript_snapshot(item)?);
    }

    append_turn_dynamic_slots(&mut messages, &dynamic_slots)?;

    for message in input.user_messages_for_request() {
        messages.push(ModelInputItem::Message(ModelMessage::new(
            ModelMessageRole::User,
            message.model_content()?,
        )?));
    }

    ModelRequest::new_with_input_and_stable_prefix(
        model.clone(),
        messages,
        tool_specs,
        generation_config,
        stable_prefix_message_count,
    )
}

fn model_input_from_transcript_snapshot(
    snapshot: &TranscriptItemSnapshot,
) -> Result<ModelInputItem, merry_llm::ModelError> {
    match snapshot {
        TranscriptItemSnapshot::UserMessage { text, images, .. } => {
            let message = UserMessageInput::new(text, images.clone())
                .map_err(|error| merry_llm::ModelError::invalid_request(error.to_string()))?;
            Ok(ModelInputItem::Message(ModelMessage::new(
                ModelMessageRole::User,
                message.model_content()?,
            )?))
        }
        TranscriptItemSnapshot::AssistantText { text } => Ok(ModelInputItem::Message(
            ModelMessage::new(ModelMessageRole::Assistant, ModelContent::text(text)?)?,
        )),
        TranscriptItemSnapshot::AssistantReasoning { text } => {
            Ok(ModelInputItem::Reasoning(ModelReasoning::new(text)?))
        }
        TranscriptItemSnapshot::ToolCall { call } => Ok(ModelInputItem::ToolCall(
            model_tool_call_from_pending(call)?,
        )),
        TranscriptItemSnapshot::ToolResult {
            call_id,
            result,
            output,
            images,
        } => {
            debug_assert_eq!(call_id, result.call_id());
            Ok(ModelInputItem::ToolResult(model_tool_result_from_result(
                result, output, images,
            )?))
        }
    }
}

fn model_tool_call_from_pending(
    call: &PendingToolCall,
) -> Result<ModelToolCall, merry_llm::ModelError> {
    Ok(ModelToolCall::new(
        ModelToolCallId::new(call.id().as_str())?,
        call.name().clone(),
        ToolArguments::new(call.arguments().as_object().clone()),
    ))
}

fn model_tool_result_from_result(
    result: &ToolCallResult,
    output: &ToolOutput,
    images: &[UserImageInput],
) -> Result<ModelToolResult, merry_llm::ModelError> {
    let call_id = ModelToolCallId::new(result.call_id().as_str())?;
    let content = model_tool_result_content(output)?;
    let model_images = images
        .iter()
        .map(|input| {
            ModelImage::png(
                input.label(),
                input.shared_png_bytes(),
                input.width(),
                input.height(),
            )
        })
        .collect::<Result<Vec<_>, _>>()?;

    let model_result = match result.status() {
        ToolCallResultStatus::Succeeded => ModelToolResult::new(
            call_id,
            ToolCallResultStatus::Succeeded,
            content,
            result.diagnostic().cloned(),
        )?,
        ToolCallResultStatus::Failed => ModelToolResult::new(
            call_id,
            ToolCallResultStatus::Failed,
            content,
            result.diagnostic().cloned(),
        )?,
    };
    Ok(model_result.with_images(model_images))
}

fn model_tool_result_content(
    output: &ToolOutput,
) -> Result<ModelToolResultContent, merry_llm::ModelError> {
    match output {
        ToolOutput::Text { text } => ModelToolResultContent::text(text),
        ToolOutput::Json { json } => ModelToolResultContent::json(json),
    }
}

#[cfg(test)]
mod tests {
    use super::{StepContext, StepInput};
    use crate::prompt::DEFAULT_RUNTIME_BASE_INSTRUCTIONS;
    use crate::{RuntimeError, UserImageInput, UserMessageInput};
    use merry_llm::{GenerationConfig, ModelContentPart};
    use std::sync::Arc;
    use tokio_util::sync::CancellationToken;

    #[test]
    fn default_runtime_base_instructions_define_general_agent_contract() {
        let instructions = DEFAULT_RUNTIME_BASE_INSTRUCTIONS;
        for required in [
            "You are Merry, a software engineering agent",
            "Use the user's current input language",
            "visible reasoning while a turn is thinking",
            "merry_reasoning_language",
            "Interpret the request before acting:",
            "Work from evidence.",
            "Choose the right scope.",
            "Do not stop after a fixed number of attempts.",
            "Tool declarations describe direct callable interfaces",
            "Verify claims in proportion to risk.",
            "Say that something is done, fixed, or tested only when tool output shows it.",
            "ask the user to confirm unless they already approved that action",
            "Fix the cause of a problem.",
            "without contrast framing",
            "Finish with the outcome that matters to the user",
            "most likely reading",
            "Ending the turn stops all work",
            "is data",
            "path:line",
            "request them together in one response",
        ] {
            assert!(
                instructions.contains(required),
                "base prompt must contain {required:?}"
            );
        }
        for forbidden in [
            "OpenAI",
            "Anthropic",
            "GPT-",
            "roughly 120",
            "roughly 250",
            "merry_outer_sandbox:",
        ] {
            assert!(
                !instructions.contains(forbidden),
                "base prompt must not contain {forbidden:?}"
            );
        }
    }

    #[test]
    fn user_text_rejects_blank_text() {
        let err = StepInput::user_text(" \n\t ").expect_err("blank text should be rejected");

        assert!(matches!(err, RuntimeError::InvalidStepInput { .. }));
    }

    #[test]
    fn user_text_allows_newline_and_tab() {
        let input =
            StepInput::user_text("line one\n\tline two").expect("newline and tab are allowed");

        assert_eq!(input.text(), "line one\n\tline two");
    }

    #[test]
    fn user_text_sanitizes_other_control_characters_and_rejects_control_only() {
        let input = StepInput::user_text("hello\u{7}\0").expect("controls should be stripped");
        assert_eq!(input.text(), "hello");

        let err = StepInput::user_text("\u{7}\0").expect_err("control-only input becomes blank");
        assert!(matches!(err, RuntimeError::InvalidStepInput { .. }));
    }

    #[test]
    fn user_texts_preserve_multiple_user_messages() {
        let input = StepInput::user_texts(["first", "second"]).expect("valid burst");

        assert_eq!(input.texts(), ["first", "second"]);
        assert_eq!(input.text(), "first");
    }

    #[test]
    fn user_texts_reject_empty_burst() {
        let err = StepInput::user_texts(std::iter::empty::<&str>())
            .expect_err("empty burst should be rejected");

        assert!(matches!(err, RuntimeError::InvalidStepInput { .. }));
    }

    #[test]
    fn user_texts_reject_blank_item() {
        let err = StepInput::user_texts(["first", " \n\t "])
            .expect_err("blank burst item should be rejected");

        assert!(matches!(err, RuntimeError::InvalidStepInput { .. }));
    }

    #[test]
    fn no_new_user_input_has_no_request_texts() {
        let input = StepInput::no_new_user_input();

        assert!(input.texts().is_empty());
    }

    #[test]
    fn user_message_input_compiles_images_before_the_full_labeled_text() {
        let message = UserMessageInput::new(
            "inspect [Image #1]",
            vec![
                UserImageInput::png(
                    "[Image #1]",
                    Arc::<[u8]>::from([137, 80, 78, 71, 13, 10, 26, 10]),
                    2,
                    3,
                )
                .expect("valid image"),
            ],
        )
        .expect("valid message");

        let content = message.model_content().expect("content should compile");
        assert_eq!(content.parts().len(), 4);
        assert!(matches!(
            &content.parts()[0],
            ModelContentPart::Text { text } if text == "<image name=[Image #1]>"
        ));
        assert!(matches!(
            &content.parts()[1],
            ModelContentPart::Image { image } if image.label() == "[Image #1]"
        ));
        assert!(matches!(
            &content.parts()[2],
            ModelContentPart::Text { text } if text == "</image>"
        ));
        assert!(matches!(
            &content.parts()[3],
            ModelContentPart::Text { text } if text == "inspect [Image #1]"
        ));
    }

    #[test]
    fn step_context_uses_default_generation_config() {
        let context = StepContext::new(CancellationToken::new());

        assert_eq!(context.generation_config(), &GenerationConfig::default());
    }

    #[test]
    fn step_context_allows_step_scoped_generation_config_override() {
        let generation_config =
            GenerationConfig::new(Some(16), false).expect("valid generation config");
        let context =
            StepContext::new(CancellationToken::new()).with_generation_config(generation_config);

        assert_eq!(context.generation_config().max_output_tokens(), Some(16));
        assert!(!context.generation_config().allow_parallel_tool_calls());
    }
}