use super::{
AgentLoopBlockedReason, AgentLoopConfig, AgentLoopError, AgentLoopResult, AgentLoopStatus,
AgentRunMessage,
};
use crate::{
FinalOutput, FinalOutputContract, Runtime, RuntimeError, RuntimeJournalEventStream,
StepContext, StepInput,
events::{ActiveStepPermit, RuntimeEventProjector},
subagent::completion_notification_text,
};
use futures_util::StreamExt;
use merry_core::{
ErrorInfo, PendingToolCall, RuntimeJournalEvent, RuntimeJournalPayload, SessionId,
ToolCallResultStatus,
};
use merry_llm::GenerationConfig;
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
pub(crate) fn trace_loop_finish(
session_id: &str,
status: &'static str,
model_turns_run: usize,
diagnostic_code: Option<&str>,
) {
tracing::info!(
event = "runtime.loop.finish",
session_id,
status,
model_turns_run,
diagnostic_code = diagnostic_code.unwrap_or(""),
"runtime loop finish"
);
}
pub(crate) fn trace_loop_error(session_id: &str, model_turns_run: usize, source: &RuntimeError) {
trace_loop_finish(
session_id,
"error",
model_turns_run,
Some(source.diagnostic_code()),
);
}
pub(crate) async fn collect_step_events(
stream: RuntimeJournalEventStream,
) -> Vec<RuntimeJournalEvent> {
stream
.filter(|event| std::future::ready(!event.payload.is_transient()))
.collect()
.await
}
pub(crate) fn build_step_context(
token: CancellationToken,
generation_config: GenerationConfig,
final_output_contract: Option<&FinalOutputContract>,
) -> StepContext {
let mut step_context = StepContext::new(token).with_generation_config(generation_config);
if let Some(contract) = final_output_contract.cloned() {
step_context = step_context.with_final_output_contract(contract);
}
step_context
}
pub(crate) fn final_assistant_output_from_step(events: &[RuntimeJournalEvent]) -> Option<String> {
for event in events.iter().rev() {
let RuntimeJournalPayload::AssistantOutputRecorded { text } = &event.payload else {
continue;
};
return Some(text.clone());
}
None
}
pub(crate) enum FinalOutputStepDecision {
Recorded {
final_output: FinalOutput,
events: Vec<RuntimeJournalEvent>,
},
ValidationFailed {
events: Vec<RuntimeJournalEvent>,
error_message: String,
},
}
pub(crate) async fn evaluate_and_record_final_output_call(
runtime: &Runtime,
contract: Option<&FinalOutputContract>,
call: PendingToolCall,
loop_permit: &ActiveStepPermit,
) -> Result<FinalOutputStepDecision, RuntimeError> {
if let Some(Err(error)) = contract.map(|contract| contract.validate_call(&call)) {
let error_message = error.message();
let events = runtime
.submit_tool_input_validation_failure_with_active_permit(&call, error, loop_permit)
.await?;
return Ok(FinalOutputStepDecision::ValidationFailed {
events,
error_message,
});
}
if let Some(contract) = contract
&& let Err(error_message) = validate_final_output(contract, &call)
{
let events = runtime
.submit_structured_output_failure_with_active_permit(
call.id(),
&error_message,
loop_permit,
)
.await?;
return Ok(FinalOutputStepDecision::ValidationFailed {
events,
error_message,
});
}
let (final_output, events) = runtime.record_final_output_tool_call(call).await?;
Ok(FinalOutputStepDecision::Recorded {
final_output,
events,
})
}
fn validate_final_output(
contract: &FinalOutputContract,
call: &PendingToolCall,
) -> Result<(), String> {
let json = serde_json::to_string(call.arguments().as_object())
.map_err(|source| format!("structured output could not be serialized: {source}"))?;
contract.validate_output(&json)
}
pub(crate) async fn finish_agent_loop_result(
runtime: &Runtime,
status: AgentLoopStatus,
events: Vec<RuntimeJournalEvent>,
model_turns_run: usize,
final_output: Option<String>,
) -> AgentLoopResult {
let session_usage = runtime.usage().await;
AgentLoopResult::new(status, events, model_turns_run, final_output, session_usage)
}
pub(crate) async fn max_model_turns_blocked_result(
runtime: &Runtime,
config: &AgentLoopConfig,
events: Vec<RuntimeJournalEvent>,
model_turns_run: usize,
) -> AgentLoopResult {
finish_agent_loop_result(
runtime,
AgentLoopStatus::Blocked {
reason: AgentLoopBlockedReason::MaxModelTurnsReached {
max_model_turns: config.max_model_turns(),
},
},
events,
model_turns_run,
None,
)
.await
}
pub(crate) async fn preempt_next_input_with_subagent_notification(
runtime: &Runtime,
next_input: &mut Option<StepInput>,
deferred_user_input: &mut Option<StepInput>,
) {
if let Some(notification_input) = take_subagent_notification_input(runtime).await {
if next_input
.as_ref()
.is_some_and(|input| !input.user_messages().is_empty())
{
*deferred_user_input = next_input.take();
} else {
let _ = next_input.take();
}
*next_input = Some(notification_input);
}
}
pub(crate) fn can_retry_structured_output(
config: &AgentLoopConfig,
retries: usize,
model_turns_run: usize,
) -> bool {
retries <= config.structured_output_retry_policy().max_retries()
&& model_turns_run < config.max_model_turns()
}
pub(crate) async fn structured_output_failure_result(
runtime: &Runtime,
events: Vec<RuntimeJournalEvent>,
model_turns_run: usize,
message: String,
) -> AgentLoopResult {
tracing::debug!(
session_id = runtime.session_id().as_str(),
model_turns_run,
error = %message,
"structured output retry policy exhausted"
);
let session_usage = runtime.usage().await;
AgentLoopResult::new(
AgentLoopStatus::Failed {
diagnostic: ErrorInfo::new(
"structured_output_invalid",
"structured final output could not be decoded as the requested type",
)
.expect("static structured output diagnostic is valid"),
},
events,
model_turns_run,
None,
session_usage,
)
}
pub(crate) async fn publish_journal_event(
runtime: &Runtime,
projector: &mut RuntimeEventProjector,
sender: &mpsc::Sender<AgentRunMessage>,
events: &mut Vec<RuntimeJournalEvent>,
event: RuntimeJournalEvent,
) -> Result<(), RuntimeError> {
let retained = (!event.payload.is_transient()).then(|| event.clone());
let projected = projector.project(event, runtime).await?;
if let Some(event) = retained {
events.push(event);
}
if let Some(projected) = projected
&& sender
.send(AgentRunMessage::Event(projected))
.await
.is_err()
{
return Err(RuntimeError::AgentRunClosed {
session_id: runtime.session_id().clone(),
message: "public event receiver closed before the event was delivered",
});
}
Ok(())
}
pub(crate) fn continuation_step_input() -> StepInput {
StepInput::no_new_user_input()
}
pub(crate) async fn take_subagent_notification(runtime: &Runtime) -> Option<(StepInput, String)> {
let statuses = runtime.take_subagent_completion_notifications().await;
if statuses.is_empty() {
return None;
}
let text = completion_notification_text(&statuses);
let input = match StepInput::loop_control_text(&text) {
Ok(input) => input,
Err(error) => {
tracing::warn!(%error, "discarding invalid subagent completion notification");
return None;
}
};
Some((input, text))
}
pub(crate) async fn take_subagent_notification_input(runtime: &Runtime) -> Option<StepInput> {
take_subagent_notification(runtime)
.await
.map(|(input, _)| input)
}
pub(crate) fn agent_loop_cancelled_diagnostic() -> ErrorInfo {
ErrorInfo::new(
"agent_loop_cancelled",
"agent loop cancellation was requested",
)
.expect("static agent loop cancellation diagnostic must be valid")
}
pub(crate) fn agent_loop_stream_error(
session_id: &SessionId,
events: Vec<RuntimeJournalEvent>,
message: &'static str,
) -> AgentLoopError {
AgentLoopError::new(
events,
RuntimeError::AgentRunClosed {
session_id: session_id.clone(),
message,
},
)
}
pub(crate) fn agent_loop_stream_error_with_source(
runtime: &Runtime,
model_turns_run: usize,
events: &[RuntimeJournalEvent],
source: RuntimeError,
) -> AgentLoopError {
trace_loop_error(runtime.session_id().as_str(), model_turns_run, &source);
AgentLoopError::new(events.to_vec(), source)
}
pub(crate) fn tool_execution_cancelled_diagnostic(call_id: &merry_core::ToolCallId) -> ErrorInfo {
ErrorInfo::new(
"tool_execution_cancelled",
&format!("tool call {call_id} execution was cancelled"),
)
.expect("static code and runtime-owned tool call id form a valid diagnostic")
}
pub(crate) fn blocked_reason_code(reason: &AgentLoopBlockedReason) -> &'static str {
match reason {
AgentLoopBlockedReason::MaxModelTurnsReached { .. } => "max_model_turns_reached",
AgentLoopBlockedReason::MultiplePendingToolCalls { .. } => "multiple_pending_tool_calls",
AgentLoopBlockedReason::StepCompletedWithPendingToolCall { .. } => {
"step_completed_with_pending_tool_call"
}
AgentLoopBlockedReason::StepEndedWithoutTerminalEvent => {
"step_ended_without_terminal_event"
}
AgentLoopBlockedReason::FinalOutputToolNotCalled => "final_output_tool_not_called",
AgentLoopBlockedReason::BridgeToolCallRequested { .. } => "bridge_tool_call_requested",
}
}
pub(crate) fn tool_resolution_status(events: &[RuntimeJournalEvent]) -> &'static str {
events
.iter()
.find_map(|event| match &event.payload {
RuntimeJournalPayload::ToolCallResolved { result } => Some(match result.status() {
ToolCallResultStatus::Succeeded => "succeeded",
ToolCallResultStatus::Failed => "failed",
}),
_ => None,
})
.unwrap_or("unresolved")
}
pub(crate) fn tool_resolution_diagnostic_code(events: &[RuntimeJournalEvent]) -> Option<&str> {
events.iter().find_map(|event| match &event.payload {
RuntimeJournalPayload::ToolCallResolved { result } => {
result.diagnostic().map(merry_core::ErrorInfo::code)
}
_ => None,
})
}
pub(crate) fn tool_resolution_is_policy_denied(events: &[RuntimeJournalEvent]) -> bool {
tool_resolution_diagnostic_code(events) == Some("action_policy_denied")
}