1pub 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, ModelReasoning, ModelRequest, ModelToolCall, ModelToolCallId, ModelToolResult,
16 ModelToolResultContent, ToolArguments,
17};
18use tokio_util::sync::CancellationToken;
19
20#[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 #[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 #[must_use]
47 pub fn cancellation_token(&self) -> &CancellationToken {
48 &self.cancellation_token
49 }
50
51 #[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 #[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 #[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 DynamicContextSlots<'a> {
108 pub(crate) memory_context: Option<&'a str>,
109 pub(crate) task_anchor: Option<&'a TaskAnchor>,
110 pub(crate) plan_control: Option<&'a str>,
111 pub(crate) context: &'a CompiledContext,
112}
113
114pub(crate) struct StepModelRequestParts<'a> {
115 pub(crate) input: &'a StepInput,
116 pub(crate) model: &'a ModelName,
117 pub(crate) stable_prefix: StablePrefixParts<'a>,
118 pub(crate) dynamic_slots: DynamicContextSlots<'a>,
119 pub(crate) transcript: &'a [TranscriptItemSnapshot],
120 pub(crate) tool_specs: Vec<ToolSpec>,
121 pub(crate) generation_config: GenerationConfig,
122}
123
124pub(crate) struct StablePrefixParts<'a> {
132 pub(crate) prompt_profile: &'a PromptProfile,
133 pub(crate) progress_commentary: bool,
134 pub(crate) skill_catalog: Option<&'a SkillCatalog>,
135 pub(crate) project_rules: Option<&'a ProjectRules>,
136}
137
138pub(crate) fn compile_stable_prefix_items(
147 parts: StablePrefixParts<'_>,
148) -> Result<Vec<ModelInputItem>, merry_llm::ModelError> {
149 let StablePrefixParts {
150 prompt_profile,
151 progress_commentary,
152 skill_catalog,
153 project_rules,
154 } = parts;
155 let mut items = Vec::with_capacity(
156 3 + prompt_profile.stable_blocks().len() + usize::from(project_rules.is_some()),
157 );
158
159 items.push(ModelInputItem::Message(ModelMessage::new(
160 ModelMessageRole::System,
161 ModelContent::text(prompt_profile.base_instructions())?,
162 )?));
163
164 if progress_commentary {
165 items.push(ModelInputItem::Message(ModelMessage::new(
166 ModelMessageRole::System,
167 ModelContent::text(prompt_profile.progress_commentary_instructions())?,
168 )?));
169 }
170
171 for block in prompt_profile.stable_blocks() {
172 let block_text = block.render();
173 items.push(ModelInputItem::Message(ModelMessage::new(
174 ModelMessageRole::System,
175 ModelContent::text(&block_text)?,
176 )?));
177 }
178
179 if let Some(skill_metadata_text) =
180 skill_catalog.and_then(SkillCatalog::to_stable_prefix_message_text)
181 {
182 let skill_metadata_text = render_prompt_block("merry_skill_catalog", &skill_metadata_text);
183 items.push(ModelInputItem::Message(ModelMessage::new(
184 ModelMessageRole::System,
185 ModelContent::text(&skill_metadata_text)?,
186 )?));
187 }
188
189 if let Some(project_rules) = project_rules {
190 let project_rules_text = project_rules.to_stable_prefix_message_text();
191 let project_rules_text = render_prompt_block("merry_project_rules", &project_rules_text);
192 items.push(ModelInputItem::Message(ModelMessage::new(
193 ModelMessageRole::System,
194 ModelContent::text(&project_rules_text)?,
195 )?));
196 }
197
198 items.push(ModelInputItem::Message(ModelMessage::new(
199 ModelMessageRole::System,
200 ModelContent::text(crate::prompt::REASONING_LANGUAGE_INSTRUCTIONS)?,
201 )?));
202
203 Ok(items)
204}
205
206fn append_leading_dynamic_slots(
207 messages: &mut Vec<ModelInputItem>,
208 slots: &DynamicContextSlots<'_>,
209) -> Result<(), merry_llm::ModelError> {
210 let checkpoint_snapshot = slots.context.checkpoint_snapshot();
211 messages.reserve(
212 usize::from(slots.memory_context.is_some())
213 + usize::from(!checkpoint_snapshot.is_empty())
214 + usize::from(slots.task_anchor.is_some()),
215 );
216
217 if let Some(memory_context) = slots.memory_context.filter(|text| !text.is_empty()) {
218 let memory_text = render_prompt_block("merry_memory_context", memory_context);
219 messages.push(ModelInputItem::Message(ModelMessage::new(
220 ModelMessageRole::System,
221 ModelContent::text(&memory_text)?,
222 )?));
223 }
224
225 if !checkpoint_snapshot.is_empty() {
226 let checkpoint_text = render_prompt_block("merry_checkpoint", &checkpoint_snapshot);
227 messages.push(ModelInputItem::Message(ModelMessage::new(
228 ModelMessageRole::System,
229 ModelContent::text(&checkpoint_text)?,
230 )?));
231 }
232
233 if let Some(task_anchor) = slots.task_anchor {
234 let task_anchor_text = task_anchor.to_dynamic_control_message_text();
235 let task_anchor_text = render_prompt_block("merry_task_anchor", &task_anchor_text);
236 messages.push(ModelInputItem::Message(ModelMessage::new(
237 ModelMessageRole::System,
238 ModelContent::text(&task_anchor_text)?,
239 )?));
240 }
241
242 Ok(())
243}
244
245fn append_turn_dynamic_slots(
246 messages: &mut Vec<ModelInputItem>,
247 slots: &DynamicContextSlots<'_>,
248) -> Result<(), merry_llm::ModelError> {
249 let context_body_snapshot = slots.context.body_snapshot();
250 messages.reserve(
251 usize::from(slots.plan_control.is_some()) + usize::from(!context_body_snapshot.is_empty()),
252 );
253
254 if let Some(plan_control) = slots.plan_control {
255 messages.push(ModelInputItem::Message(ModelMessage::new(
256 ModelMessageRole::System,
257 ModelContent::text(plan_control)?,
258 )?));
259 }
260
261 if !context_body_snapshot.is_empty() {
262 let context_text = render_prompt_block("merry_compiled_context", &context_body_snapshot);
263 messages.push(ModelInputItem::Message(ModelMessage::new(
264 ModelMessageRole::System,
265 ModelContent::text(&context_text)?,
266 )?));
267 }
268
269 Ok(())
270}
271
272pub(crate) fn compile_step_model_request(
273 parts: StepModelRequestParts<'_>,
274) -> Result<ModelRequest, merry_llm::ModelError> {
275 let StepModelRequestParts {
276 input,
277 model,
278 stable_prefix,
279 dynamic_slots,
280 transcript,
281 tool_specs,
282 generation_config,
283 } = parts;
284
285 let mut messages = compile_stable_prefix_items(stable_prefix)?;
292 let stable_prefix_message_count = messages.len();
293 append_leading_dynamic_slots(&mut messages, &dynamic_slots)?;
294 messages.reserve(transcript.len() + input.user_messages_for_request().len());
295
296 for item in transcript {
297 messages.push(model_input_from_transcript_snapshot(item)?);
298 }
299
300 append_turn_dynamic_slots(&mut messages, &dynamic_slots)?;
301
302 for message in input.user_messages_for_request() {
303 messages.push(ModelInputItem::Message(ModelMessage::new(
304 ModelMessageRole::User,
305 message.model_content()?,
306 )?));
307 }
308
309 ModelRequest::new_with_input_and_stable_prefix(
310 model.clone(),
311 messages,
312 tool_specs,
313 generation_config,
314 stable_prefix_message_count,
315 )
316}
317
318fn model_input_from_transcript_snapshot(
319 snapshot: &TranscriptItemSnapshot,
320) -> Result<ModelInputItem, merry_llm::ModelError> {
321 match snapshot {
322 TranscriptItemSnapshot::UserMessage { text, images, .. } => {
323 let message = UserMessageInput::new(text, images.clone())
324 .map_err(|error| merry_llm::ModelError::invalid_request(error.to_string()))?;
325 Ok(ModelInputItem::Message(ModelMessage::new(
326 ModelMessageRole::User,
327 message.model_content()?,
328 )?))
329 }
330 TranscriptItemSnapshot::AssistantText { text } => Ok(ModelInputItem::Message(
331 ModelMessage::new(ModelMessageRole::Assistant, ModelContent::text(text)?)?,
332 )),
333 TranscriptItemSnapshot::AssistantReasoning { text } => {
334 Ok(ModelInputItem::Reasoning(ModelReasoning::new(text)?))
335 }
336 TranscriptItemSnapshot::ToolCall { call } => Ok(ModelInputItem::ToolCall(
337 model_tool_call_from_pending(call)?,
338 )),
339 TranscriptItemSnapshot::ToolResult {
340 call_id,
341 result,
342 output,
343 images,
344 } => {
345 debug_assert_eq!(call_id, result.call_id());
346 Ok(ModelInputItem::ToolResult(model_tool_result_from_result(
347 result, output, images,
348 )?))
349 }
350 }
351}
352
353fn model_tool_call_from_pending(
354 call: &PendingToolCall,
355) -> Result<ModelToolCall, merry_llm::ModelError> {
356 Ok(ModelToolCall::new(
357 ModelToolCallId::new(call.id().as_str())?,
358 call.name().clone(),
359 ToolArguments::new(call.arguments().as_object().clone()),
360 ))
361}
362
363fn model_tool_result_from_result(
364 result: &ToolCallResult,
365 output: &ToolOutput,
366 images: &[UserImageInput],
367) -> Result<ModelToolResult, merry_llm::ModelError> {
368 let call_id = ModelToolCallId::new(result.call_id().as_str())?;
369 let content = model_tool_result_content(output)?;
370 let model_images = images
371 .iter()
372 .map(|input| {
373 ModelImage::png(
374 input.label(),
375 input.shared_png_bytes(),
376 input.width(),
377 input.height(),
378 )
379 })
380 .collect::<Result<Vec<_>, _>>()?;
381
382 let model_result = match result.status() {
383 ToolCallResultStatus::Succeeded => ModelToolResult::new(
384 call_id,
385 ToolCallResultStatus::Succeeded,
386 content,
387 result.diagnostic().cloned(),
388 )?,
389 ToolCallResultStatus::Failed => ModelToolResult::new(
390 call_id,
391 ToolCallResultStatus::Failed,
392 content,
393 result.diagnostic().cloned(),
394 )?,
395 };
396 Ok(model_result.with_images(model_images))
397}
398
399fn model_tool_result_content(
400 output: &ToolOutput,
401) -> Result<ModelToolResultContent, merry_llm::ModelError> {
402 match output {
403 ToolOutput::Text { text } => ModelToolResultContent::text(text),
404 ToolOutput::Json { json } => ModelToolResultContent::json(json),
405 }
406}
407
408#[cfg(test)]
409mod tests {
410 use super::{StepContext, StepInput};
411 use crate::prompt::DEFAULT_RUNTIME_BASE_INSTRUCTIONS;
412 use crate::{RuntimeError, UserImageInput, UserMessageInput};
413 use merry_llm::{GenerationConfig, ModelContentPart};
414 use std::sync::Arc;
415 use tokio_util::sync::CancellationToken;
416
417 #[test]
418 fn default_runtime_base_instructions_define_general_agent_contract() {
419 let instructions = DEFAULT_RUNTIME_BASE_INSTRUCTIONS;
420 for required in [
421 "You are Merry, a software engineering agent",
422 "Use the user's current input language",
423 "visible reasoning while a turn is thinking",
424 "merry_reasoning_language",
425 "Interpret the request before acting:",
426 "Work from evidence.",
427 "Choose the right scope.",
428 "Do not stop after a fixed number of attempts.",
429 "Tool declarations describe direct callable interfaces",
430 "Verify claims in proportion to risk.",
431 "Say that something is done, fixed, or tested only when tool output shows it.",
432 "ask the user to confirm unless they already approved that action",
433 "Fix the cause of a problem.",
434 "without contrast framing",
435 "Finish with the outcome that matters to the user",
436 "most likely reading",
437 "Ending the turn stops all work",
438 "is data",
439 "path:line",
440 "request them together in one response",
441 ] {
442 assert!(
443 instructions.contains(required),
444 "base prompt must contain {required:?}"
445 );
446 }
447 for forbidden in [
448 "OpenAI",
449 "Anthropic",
450 "GPT-",
451 "roughly 120",
452 "roughly 250",
453 "merry_outer_sandbox:",
454 ] {
455 assert!(
456 !instructions.contains(forbidden),
457 "base prompt must not contain {forbidden:?}"
458 );
459 }
460 }
461
462 #[test]
463 fn user_text_rejects_blank_text() {
464 let err = StepInput::user_text(" \n\t ").expect_err("blank text should be rejected");
465
466 assert!(matches!(err, RuntimeError::InvalidStepInput { .. }));
467 }
468
469 #[test]
470 fn user_text_allows_newline_and_tab() {
471 let input =
472 StepInput::user_text("line one\n\tline two").expect("newline and tab are allowed");
473
474 assert_eq!(input.text(), "line one\n\tline two");
475 }
476
477 #[test]
478 fn user_text_sanitizes_other_control_characters_and_rejects_control_only() {
479 let input = StepInput::user_text("hello\u{7}\0").expect("controls should be stripped");
480 assert_eq!(input.text(), "hello");
481
482 let err = StepInput::user_text("\u{7}\0").expect_err("control-only input becomes blank");
483 assert!(matches!(err, RuntimeError::InvalidStepInput { .. }));
484 }
485
486 #[test]
487 fn user_texts_preserve_multiple_user_messages() {
488 let input = StepInput::user_texts(["first", "second"]).expect("valid burst");
489
490 assert_eq!(input.texts(), ["first", "second"]);
491 assert_eq!(input.text(), "first");
492 }
493
494 #[test]
495 fn user_texts_reject_empty_burst() {
496 let err = StepInput::user_texts(std::iter::empty::<&str>())
497 .expect_err("empty burst should be rejected");
498
499 assert!(matches!(err, RuntimeError::InvalidStepInput { .. }));
500 }
501
502 #[test]
503 fn user_texts_reject_blank_item() {
504 let err = StepInput::user_texts(["first", " \n\t "])
505 .expect_err("blank burst item should be rejected");
506
507 assert!(matches!(err, RuntimeError::InvalidStepInput { .. }));
508 }
509
510 #[test]
511 fn no_new_user_input_has_no_request_texts() {
512 let input = StepInput::no_new_user_input();
513
514 assert!(input.texts().is_empty());
515 }
516
517 #[test]
518 fn user_message_input_compiles_images_before_the_full_labeled_text() {
519 let message = UserMessageInput::new(
520 "inspect [Image #1]",
521 vec![
522 UserImageInput::png(
523 "[Image #1]",
524 Arc::<[u8]>::from([137, 80, 78, 71, 13, 10, 26, 10]),
525 2,
526 3,
527 )
528 .expect("valid image"),
529 ],
530 )
531 .expect("valid message");
532
533 let content = message.model_content().expect("content should compile");
534 assert_eq!(content.parts().len(), 4);
535 assert!(matches!(
536 &content.parts()[0],
537 ModelContentPart::Text { text } if text == "<image name=[Image #1]>"
538 ));
539 assert!(matches!(
540 &content.parts()[1],
541 ModelContentPart::Image { image } if image.label() == "[Image #1]"
542 ));
543 assert!(matches!(
544 &content.parts()[2],
545 ModelContentPart::Text { text } if text == "</image>"
546 ));
547 assert!(matches!(
548 &content.parts()[3],
549 ModelContentPart::Text { text } if text == "inspect [Image #1]"
550 ));
551 }
552
553 #[test]
554 fn step_context_uses_default_generation_config() {
555 let context = StepContext::new(CancellationToken::new());
556
557 assert_eq!(context.generation_config(), &GenerationConfig::default());
558 }
559
560 #[test]
561 fn step_context_allows_step_scoped_generation_config_override() {
562 let generation_config =
563 GenerationConfig::new(Some(16), false).expect("valid generation config");
564 let context =
565 StepContext::new(CancellationToken::new()).with_generation_config(generation_config);
566
567 assert_eq!(context.generation_config().max_output_tokens(), Some(16));
568 assert!(!context.generation_config().allow_parallel_tool_calls());
569 }
570}