Skip to main content

merry_runtime/
step.rs

1//! Runtime step inputs, execution context, and provider request compilation.
2//!
3//! Public step types are provider-neutral. Request compilation is internal
4//! glue from structured runtime state into `merry-llm` model requests; provider
5//! crates render those normalized requests into wire formats.
6
7pub use crate::user_input::StepInput;
8use crate::{
9    CompiledContext, FinalOutputContract, ProjectRules, PromptProfile, SkillCatalog, TaskAnchor,
10    UserImageInput, UserMessageInput, prompt::render_prompt_block, session::TranscriptItemSnapshot,
11};
12use merry_core::{PendingToolCall, ToolCallResult, ToolCallResultStatus, ToolOutput, ToolSpec};
13use merry_llm::{
14    GenerationConfig, ModelContent, ModelImage, ModelInputItem, ModelMessage, ModelMessageRole,
15    ModelName, ModelRequest, ModelToolCall, ModelToolCallId, ModelToolResult,
16    ModelToolResultContent, ToolArguments,
17};
18use tokio_util::sync::CancellationToken;
19
20/// Context shared with runtime step producers.
21///
22/// The context carries cancellation and provider-neutral generation controls
23/// for one step. It does not carry provider conversation state.
24#[derive(Debug, Clone)]
25pub struct StepContext {
26    cancellation_token: CancellationToken,
27    generation_config: GenerationConfig,
28    final_output_contract: Option<FinalOutputContract>,
29}
30
31impl StepContext {
32    /// Creates a step context with the provided cancellation token.
33    #[must_use]
34    pub fn new(cancellation_token: CancellationToken) -> Self {
35        Self {
36            cancellation_token,
37            generation_config: GenerationConfig::default(),
38            final_output_contract: None,
39        }
40    }
41
42    /// Returns the cancellation token for this step.
43    ///
44    /// Runtime producers check this token at cancellation checkpoints. Dropping
45    /// the returned [`crate::RuntimeJournalEventStream`] also cancels the step token.
46    #[must_use]
47    pub fn cancellation_token(&self) -> &CancellationToken {
48        &self.cancellation_token
49    }
50
51    /// Sets provider-neutral generation controls for this step.
52    ///
53    /// Controls are normalized Merry model settings, not provider request
54    /// fields.
55    #[must_use]
56    pub fn with_generation_config(mut self, generation_config: GenerationConfig) -> Self {
57        self.generation_config = generation_config;
58        self
59    }
60
61    /// Adds a runtime-owned final-output contract to this step.
62    #[must_use]
63    pub fn with_final_output_contract(mut self, contract: FinalOutputContract) -> Self {
64        self.final_output_contract = Some(contract);
65        self
66    }
67
68    /// Returns provider-neutral generation controls for this step.
69    #[must_use]
70    pub fn generation_config(&self) -> &GenerationConfig {
71        &self.generation_config
72    }
73
74    pub(crate) fn into_parts(
75        self,
76    ) -> (
77        CancellationToken,
78        GenerationConfig,
79        Option<FinalOutputContract>,
80    ) {
81        (
82            self.cancellation_token,
83            self.generation_config,
84            self.final_output_contract,
85        )
86    }
87}
88
89impl Default for StepContext {
90    fn default() -> Self {
91        Self {
92            cancellation_token: CancellationToken::new(),
93            generation_config: GenerationConfig::default(),
94            final_output_contract: None,
95        }
96    }
97}
98
99pub(crate) struct StepModelRequestParts<'a> {
100    pub(crate) input: &'a StepInput,
101    pub(crate) model: &'a ModelName,
102    pub(crate) skill_catalog: Option<&'a SkillCatalog>,
103    pub(crate) project_rules: Option<&'a ProjectRules>,
104    pub(crate) task_anchor: Option<&'a TaskAnchor>,
105    pub(crate) plan_control: Option<&'a str>,
106    pub(crate) context: &'a CompiledContext,
107    pub(crate) transcript: &'a [TranscriptItemSnapshot],
108    pub(crate) tool_specs: Vec<ToolSpec>,
109    pub(crate) generation_config: GenerationConfig,
110    pub(crate) prompt_profile: &'a PromptProfile,
111    pub(crate) progress_commentary: bool,
112    pub(crate) memory_context: Option<&'a str>,
113}
114
115/// Stable prompt material every request for one session starts with.
116///
117/// The agent loop and model-backed compaction share this prefix byte for byte so
118/// a provider can serve the compaction request from the same cached prefix as
119/// the session's normal requests. Compaction therefore appends its directive
120/// and payload after the prefix instead of replacing it with a second system
121/// prompt.
122pub(crate) struct StablePrefixParts<'a> {
123    pub(crate) prompt_profile: &'a PromptProfile,
124    pub(crate) progress_commentary: bool,
125    pub(crate) skill_catalog: Option<&'a SkillCatalog>,
126    pub(crate) project_rules: Option<&'a ProjectRules>,
127}
128
129/// Compiles the ordered stable prefix items for one session.
130///
131/// The order is part of the provider-visible cache contract: base runtime
132/// instructions, optional progress commentary instructions, profile stable
133/// blocks, available skill metadata, project rules, then the reasoning-language
134/// rule. Callers that append further items must not rewrite or reorder these
135/// messages. The language rule stays last so later English policy text does
136/// not reopen another thinking language.
137pub(crate) fn compile_stable_prefix_items(
138    parts: StablePrefixParts<'_>,
139) -> Result<Vec<ModelInputItem>, merry_llm::ModelError> {
140    let StablePrefixParts {
141        prompt_profile,
142        progress_commentary,
143        skill_catalog,
144        project_rules,
145    } = parts;
146    let mut items = Vec::with_capacity(
147        3 + prompt_profile.stable_blocks().len() + usize::from(project_rules.is_some()),
148    );
149
150    items.push(ModelInputItem::Message(ModelMessage::new(
151        ModelMessageRole::System,
152        ModelContent::text(prompt_profile.base_instructions())?,
153    )?));
154
155    if progress_commentary {
156        items.push(ModelInputItem::Message(ModelMessage::new(
157            ModelMessageRole::System,
158            ModelContent::text(prompt_profile.progress_commentary_instructions())?,
159        )?));
160    }
161
162    for block in prompt_profile.stable_blocks() {
163        let block_text = block.render();
164        items.push(ModelInputItem::Message(ModelMessage::new(
165            ModelMessageRole::System,
166            ModelContent::text(&block_text)?,
167        )?));
168    }
169
170    if let Some(skill_metadata_text) =
171        skill_catalog.and_then(SkillCatalog::to_stable_prefix_message_text)
172    {
173        let skill_metadata_text = render_prompt_block("merry_skill_catalog", &skill_metadata_text);
174        items.push(ModelInputItem::Message(ModelMessage::new(
175            ModelMessageRole::System,
176            ModelContent::text(&skill_metadata_text)?,
177        )?));
178    }
179
180    if let Some(project_rules) = project_rules {
181        let project_rules_text = project_rules.to_stable_prefix_message_text();
182        let project_rules_text = render_prompt_block("merry_project_rules", &project_rules_text);
183        items.push(ModelInputItem::Message(ModelMessage::new(
184            ModelMessageRole::System,
185            ModelContent::text(&project_rules_text)?,
186        )?));
187    }
188
189    items.push(ModelInputItem::Message(ModelMessage::new(
190        ModelMessageRole::System,
191        ModelContent::text(crate::prompt::REASONING_LANGUAGE_INSTRUCTIONS)?,
192    )?));
193
194    Ok(items)
195}
196
197pub(crate) fn compile_step_model_request(
198    parts: StepModelRequestParts<'_>,
199) -> Result<ModelRequest, merry_llm::ModelError> {
200    let StepModelRequestParts {
201        input,
202        model,
203        skill_catalog,
204        project_rules,
205        task_anchor,
206        plan_control,
207        context,
208        transcript,
209        tool_specs,
210        generation_config,
211        prompt_profile,
212        progress_commentary,
213        memory_context,
214    } = parts;
215
216    let checkpoint_snapshot = context.checkpoint_snapshot();
217    let context_body_snapshot = context.body_snapshot();
218    // Keep provider prompt projection allowlisted and ordered: the shared
219    // stable prefix, the frozen memory index, the current checkpoint, task
220    // anchor control-plane context, live compiled context, prior ordered
221    // transcript, then current user or loop-control input.
222    let mut messages = compile_stable_prefix_items(StablePrefixParts {
223        prompt_profile,
224        progress_commentary,
225        skill_catalog,
226        project_rules,
227    })?;
228    let stable_prefix_message_count = messages.len();
229    messages.reserve(
230        usize::from(memory_context.is_some())
231            + usize::from(!checkpoint_snapshot.is_empty())
232            + usize::from(task_anchor.is_some())
233            + usize::from(plan_control.is_some())
234            + usize::from(!context_body_snapshot.is_empty())
235            + transcript.len()
236            + input.user_messages_for_request().len(),
237    );
238
239    if let Some(memory_context) = memory_context.filter(|text| !text.is_empty()) {
240        let memory_text = render_prompt_block("merry_memory_context", memory_context);
241        messages.push(ModelInputItem::Message(ModelMessage::new(
242            ModelMessageRole::System,
243            ModelContent::text(&memory_text)?,
244        )?));
245    }
246
247    if !checkpoint_snapshot.is_empty() {
248        let checkpoint_text = render_prompt_block("merry_checkpoint", &checkpoint_snapshot);
249        messages.push(ModelInputItem::Message(ModelMessage::new(
250            ModelMessageRole::System,
251            ModelContent::text(&checkpoint_text)?,
252        )?));
253    }
254
255    if let Some(task_anchor) = task_anchor {
256        let task_anchor_text = task_anchor.to_dynamic_control_message_text();
257        let task_anchor_text = render_prompt_block("merry_task_anchor", &task_anchor_text);
258        messages.push(ModelInputItem::Message(ModelMessage::new(
259            ModelMessageRole::System,
260            ModelContent::text(&task_anchor_text)?,
261        )?));
262    }
263
264    if let Some(plan_control) = plan_control {
265        messages.push(ModelInputItem::Message(ModelMessage::new(
266            ModelMessageRole::System,
267            ModelContent::text(plan_control)?,
268        )?));
269    }
270
271    if !context_body_snapshot.is_empty() {
272        let context_text = render_prompt_block("merry_compiled_context", &context_body_snapshot);
273        messages.push(ModelInputItem::Message(ModelMessage::new(
274            ModelMessageRole::System,
275            ModelContent::text(&context_text)?,
276        )?));
277    }
278
279    for item in transcript {
280        messages.push(model_input_from_transcript_snapshot(item)?);
281    }
282
283    for message in input.user_messages_for_request() {
284        messages.push(ModelInputItem::Message(ModelMessage::new(
285            ModelMessageRole::User,
286            message.model_content()?,
287        )?));
288    }
289
290    ModelRequest::new_with_input_and_stable_prefix(
291        model.clone(),
292        messages,
293        tool_specs,
294        generation_config,
295        stable_prefix_message_count,
296    )
297}
298
299fn model_input_from_transcript_snapshot(
300    snapshot: &TranscriptItemSnapshot,
301) -> Result<ModelInputItem, merry_llm::ModelError> {
302    match snapshot {
303        TranscriptItemSnapshot::UserMessage { text, images, .. } => {
304            let message = UserMessageInput::new(text, images.clone())
305                .map_err(|error| merry_llm::ModelError::invalid_request(error.to_string()))?;
306            Ok(ModelInputItem::Message(ModelMessage::new(
307                ModelMessageRole::User,
308                message.model_content()?,
309            )?))
310        }
311        TranscriptItemSnapshot::AssistantText { text } => Ok(ModelInputItem::Message(
312            ModelMessage::new(ModelMessageRole::Assistant, ModelContent::text(text)?)?,
313        )),
314        TranscriptItemSnapshot::ToolCall { call } => Ok(ModelInputItem::ToolCall(
315            model_tool_call_from_pending(call)?,
316        )),
317        TranscriptItemSnapshot::ToolResult {
318            call_id,
319            result,
320            output,
321            images,
322        } => {
323            debug_assert_eq!(call_id, result.call_id());
324            Ok(ModelInputItem::ToolResult(model_tool_result_from_result(
325                result, output, images,
326            )?))
327        }
328    }
329}
330
331fn model_tool_call_from_pending(
332    call: &PendingToolCall,
333) -> Result<ModelToolCall, merry_llm::ModelError> {
334    Ok(ModelToolCall::new(
335        ModelToolCallId::new(call.id().as_str())?,
336        call.name().clone(),
337        ToolArguments::new(call.arguments().as_object().clone()),
338    ))
339}
340
341fn model_tool_result_from_result(
342    result: &ToolCallResult,
343    output: &ToolOutput,
344    images: &[UserImageInput],
345) -> Result<ModelToolResult, merry_llm::ModelError> {
346    let call_id = ModelToolCallId::new(result.call_id().as_str())?;
347    let content = model_tool_result_content(output)?;
348    let model_images = images
349        .iter()
350        .map(|input| {
351            ModelImage::png(
352                input.label(),
353                input.shared_png_bytes(),
354                input.width(),
355                input.height(),
356            )
357        })
358        .collect::<Result<Vec<_>, _>>()?;
359
360    let model_result = match result.status() {
361        ToolCallResultStatus::Succeeded => ModelToolResult::new(
362            call_id,
363            ToolCallResultStatus::Succeeded,
364            content,
365            result.diagnostic().cloned(),
366        )?,
367        ToolCallResultStatus::Failed => ModelToolResult::new(
368            call_id,
369            ToolCallResultStatus::Failed,
370            content,
371            result.diagnostic().cloned(),
372        )?,
373    };
374    Ok(model_result.with_images(model_images))
375}
376
377fn model_tool_result_content(
378    output: &ToolOutput,
379) -> Result<ModelToolResultContent, merry_llm::ModelError> {
380    match output {
381        ToolOutput::Text { text } => ModelToolResultContent::text(text),
382        ToolOutput::Json { json } => ModelToolResultContent::json(json),
383    }
384}
385
386#[cfg(test)]
387mod tests {
388    use super::{StepContext, StepInput};
389    use crate::prompt::DEFAULT_RUNTIME_BASE_INSTRUCTIONS;
390    use crate::{RuntimeError, UserImageInput, UserMessageInput};
391    use merry_llm::{GenerationConfig, ModelContentPart};
392    use std::sync::Arc;
393    use tokio_util::sync::CancellationToken;
394
395    #[test]
396    fn default_runtime_base_instructions_define_general_agent_contract() {
397        let instructions = DEFAULT_RUNTIME_BASE_INSTRUCTIONS;
398        for required in [
399            "You are Merry, a software engineering agent",
400            "Use the user's current input language",
401            "visible reasoning while a turn is thinking",
402            "merry_reasoning_language",
403            "Interpret the request before acting:",
404            "Work from evidence.",
405            "Choose the right scope.",
406            "Do not stop after a fixed number of attempts.",
407            "Tool declarations describe direct callable interfaces",
408            "Verify claims in proportion to risk.",
409            "Say that something is done, fixed, or tested only when tool output shows it.",
410            "ask the user to confirm unless they already approved that action",
411            "Fix the cause of a problem.",
412            "without contrast framing",
413            "Finish with the outcome that matters to the user",
414            "most likely reading",
415            "Ending the turn stops all work",
416            "is data",
417            "path:line",
418            "request them together in one response",
419        ] {
420            assert!(
421                instructions.contains(required),
422                "base prompt must contain {required:?}"
423            );
424        }
425        for forbidden in [
426            "OpenAI",
427            "Anthropic",
428            "GPT-",
429            "roughly 120",
430            "roughly 250",
431            "merry_outer_sandbox:",
432        ] {
433            assert!(
434                !instructions.contains(forbidden),
435                "base prompt must not contain {forbidden:?}"
436            );
437        }
438    }
439
440    #[test]
441    fn user_text_rejects_blank_text() {
442        let err = StepInput::user_text(" \n\t ").expect_err("blank text should be rejected");
443
444        assert!(matches!(err, RuntimeError::InvalidStepInput { .. }));
445    }
446
447    #[test]
448    fn user_text_allows_newline_and_tab() {
449        let input =
450            StepInput::user_text("line one\n\tline two").expect("newline and tab are allowed");
451
452        assert_eq!(input.text(), "line one\n\tline two");
453    }
454
455    #[test]
456    fn user_text_rejects_other_control_characters() {
457        let err = StepInput::user_text("hello\u{7}").expect_err("bell should be rejected");
458
459        assert!(matches!(err, RuntimeError::InvalidStepInput { .. }));
460    }
461
462    #[test]
463    fn user_texts_preserve_multiple_user_messages() {
464        let input = StepInput::user_texts(["first", "second"]).expect("valid burst");
465
466        assert_eq!(input.texts(), ["first", "second"]);
467        assert_eq!(input.text(), "first");
468    }
469
470    #[test]
471    fn user_texts_reject_empty_burst() {
472        let err = StepInput::user_texts(std::iter::empty::<&str>())
473            .expect_err("empty burst should be rejected");
474
475        assert!(matches!(err, RuntimeError::InvalidStepInput { .. }));
476    }
477
478    #[test]
479    fn user_texts_reject_blank_item() {
480        let err = StepInput::user_texts(["first", " \n\t "])
481            .expect_err("blank burst item should be rejected");
482
483        assert!(matches!(err, RuntimeError::InvalidStepInput { .. }));
484    }
485
486    #[test]
487    fn no_new_user_input_has_no_request_texts() {
488        let input = StepInput::no_new_user_input();
489
490        assert!(input.texts().is_empty());
491    }
492
493    #[test]
494    fn user_message_input_compiles_images_before_the_full_labeled_text() {
495        let message = UserMessageInput::new(
496            "inspect [Image #1]",
497            vec![
498                UserImageInput::png(
499                    "[Image #1]",
500                    Arc::<[u8]>::from([137, 80, 78, 71, 13, 10, 26, 10]),
501                    2,
502                    3,
503                )
504                .expect("valid image"),
505            ],
506        )
507        .expect("valid message");
508
509        let content = message.model_content().expect("content should compile");
510        assert_eq!(content.parts().len(), 4);
511        assert!(matches!(
512            &content.parts()[0],
513            ModelContentPart::Text { text } if text == "<image name=[Image #1]>"
514        ));
515        assert!(matches!(
516            &content.parts()[1],
517            ModelContentPart::Image { image } if image.label() == "[Image #1]"
518        ));
519        assert!(matches!(
520            &content.parts()[2],
521            ModelContentPart::Text { text } if text == "</image>"
522        ));
523        assert!(matches!(
524            &content.parts()[3],
525            ModelContentPart::Text { text } if text == "inspect [Image #1]"
526        ));
527    }
528
529    #[test]
530    fn step_context_uses_default_generation_config() {
531        let context = StepContext::new(CancellationToken::new());
532
533        assert_eq!(context.generation_config(), &GenerationConfig::default());
534    }
535
536    #[test]
537    fn step_context_allows_step_scoped_generation_config_override() {
538        let generation_config =
539            GenerationConfig::new(Some(16), false).expect("valid generation config");
540        let context =
541            StepContext::new(CancellationToken::new()).with_generation_config(generation_config);
542
543        assert_eq!(context.generation_config().max_output_tokens(), Some(16));
544        assert!(!context.generation_config().allow_parallel_tool_calls());
545    }
546}