Skip to main content

merry_runtime/agent_loop/
types.rs

1//! Results and control states for the runtime-owned agent loop.
2
3use crate::{FinalOutput, RuntimeError};
4use merry_core::{ErrorInfo, RuntimeJournalEvent, SessionUsage, ToolCallId, ToolName};
5use thiserror::Error;
6
7/// Result of a completed or policy-blocked agent loop run.
8#[derive(Debug, Clone, PartialEq, Eq)]
9pub struct AgentLoopResult {
10    status: AgentLoopStatus,
11    events: Vec<RuntimeJournalEvent>,
12    model_turns_run: usize,
13    final_output: Option<String>,
14    final_output_json: Option<FinalOutput>,
15    session_usage: Option<SessionUsage>,
16}
17
18impl AgentLoopResult {
19    pub(crate) fn new(
20        status: AgentLoopStatus,
21        events: Vec<RuntimeJournalEvent>,
22        model_turns_run: usize,
23        final_output: Option<String>,
24        session_usage: Option<SessionUsage>,
25    ) -> Self {
26        Self::new_with_final_output_json(
27            status,
28            events,
29            model_turns_run,
30            final_output,
31            None,
32            session_usage,
33        )
34    }
35
36    pub(crate) fn new_with_final_output_json(
37        status: AgentLoopStatus,
38        events: Vec<RuntimeJournalEvent>,
39        model_turns_run: usize,
40        final_output: Option<String>,
41        final_output_json: Option<FinalOutput>,
42        session_usage: Option<SessionUsage>,
43    ) -> Self {
44        Self {
45            status,
46            events,
47            model_turns_run,
48            final_output,
49            final_output_json,
50            session_usage,
51        }
52    }
53
54    /// Final loop status.
55    #[must_use]
56    pub fn status(&self) -> &AgentLoopStatus {
57        &self.status
58    }
59
60    /// Retained execution evidence in emission order, excluding live text deltas and rate samples.
61    #[must_use]
62    pub fn events(&self) -> &[RuntimeJournalEvent] {
63        &self.events
64    }
65
66    /// Number of model turns started by the loop.
67    #[must_use]
68    pub fn model_turns_run(&self) -> usize {
69        self.model_turns_run
70    }
71
72    /// Explicit final text returned by the model at loop completion, when present.
73    #[must_use]
74    pub fn final_output(&self) -> Option<&str> {
75        self.final_output.as_deref()
76    }
77
78    /// Structured JSON final output recorded by the runtime final-output tool.
79    #[must_use]
80    pub fn final_output_json(&self) -> Option<&FinalOutput> {
81        self.final_output_json.as_ref()
82    }
83
84    /// Latest session usage snapshot when this loop result was produced.
85    #[must_use]
86    pub fn session_usage(&self) -> Option<&SessionUsage> {
87        self.session_usage.as_ref()
88    }
89
90    /// Consumes the result and returns retained evidence, excluding transient observations.
91    #[must_use]
92    pub fn into_events(self) -> Vec<RuntimeJournalEvent> {
93        self.events
94    }
95}
96
97/// Terminal or blocked status for an agent loop run.
98#[non_exhaustive]
99#[derive(Debug, Clone, PartialEq, Eq)]
100pub enum AgentLoopStatus {
101    /// The provider returned a final completed step.
102    Completed,
103    /// The runtime emitted a failed event. This is distinct from a method error
104    /// returned by [`crate::Runtime::step`] or [`crate::Runtime::execute_tool_call`].
105    Failed { diagnostic: ErrorInfo },
106    /// The runtime emitted a cancelled event, or loop-owned tool execution was
107    /// cancelled before producing a durable result.
108    Cancelled { diagnostic: ErrorInfo },
109    /// The loop stopped because MVP loop policy cannot safely continue.
110    Blocked { reason: AgentLoopBlockedReason },
111}
112
113/// Reasons a loop can stop without final model completion.
114#[non_exhaustive]
115#[derive(Debug, Clone, PartialEq, Eq)]
116pub enum AgentLoopBlockedReason {
117    /// The configured model-turn budget has been reached.
118    MaxModelTurnsReached { max_model_turns: usize },
119    /// Legacy blocked status retained for compatibility with older loop results.
120    ///
121    /// Current runtime-owned loops execute supported pending batches directly.
122    MultiplePendingToolCalls { pending_count: usize },
123    /// A step emitted both completion and pending tool-call state.
124    StepCompletedWithPendingToolCall { pending_count: usize },
125    /// A step stream ended without a completion, failure, cancellation, or
126    /// pending tool-call event.
127    StepEndedWithoutTerminalEvent,
128    /// The loop required the final-output tool but the model completed with text.
129    FinalOutputToolNotCalled,
130    /// A pending tool call must be executed by an external bridge runner.
131    BridgeToolCallRequested {
132        /// Bridge tool call id.
133        call_id: ToolCallId,
134        /// Bridge tool name.
135        tool_name: ToolName,
136    },
137}
138
139/// Runtime method error returned while an agent loop was running.
140///
141/// Runtime failed/cancelled events are represented as [`AgentLoopStatus`].
142/// This error is reserved for facade-method failures such as step admission,
143/// unknown calls, executor infrastructure failure, or an interrupted stream.
144/// Cooperative tool cancellation is represented as
145/// [`AgentLoopStatus::Cancelled`]. The already-observed runtime events are
146/// preserved for callers.
147#[derive(Debug, Error)]
148#[error("agent loop stopped on runtime method error: {source}")]
149pub struct AgentLoopError {
150    events: Vec<RuntimeJournalEvent>,
151    #[source]
152    source: Box<RuntimeError>,
153}
154
155impl AgentLoopError {
156    pub(crate) fn new(events: Vec<RuntimeJournalEvent>, source: RuntimeError) -> Self {
157        Self {
158            events,
159            source: Box::new(source),
160        }
161    }
162
163    /// Retained evidence before the method error, excluding live deltas and rate samples.
164    #[must_use]
165    pub fn events(&self) -> &[RuntimeJournalEvent] {
166        &self.events
167    }
168
169    /// Underlying runtime method error.
170    #[must_use]
171    pub fn runtime_error(&self) -> &RuntimeError {
172        &self.source
173    }
174
175    /// Consumes the error into its preserved events and runtime error.
176    #[must_use]
177    pub fn into_parts(self) -> (Vec<RuntimeJournalEvent>, RuntimeError) {
178        (self.events, *self.source)
179    }
180}