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    /// A lifecycle hook intentionally stopped the turn cleanly.
112    StoppedByHook {
113        /// Hook point that requested stopping the turn.
114        hook_point: crate::HookPoint,
115        /// Actionable human-readable reason returned by the hook.
116        reason: String,
117    },
118}
119
120/// Reasons a loop can stop without final model completion.
121#[non_exhaustive]
122#[derive(Debug, Clone, PartialEq, Eq)]
123pub enum AgentLoopBlockedReason {
124    /// The configured model-turn budget has been reached.
125    MaxModelTurnsReached { max_model_turns: usize },
126    /// Legacy blocked status retained for compatibility with older loop results.
127    ///
128    /// Current runtime-owned loops execute supported pending batches directly.
129    MultiplePendingToolCalls { pending_count: usize },
130    /// A step emitted both completion and pending tool-call state.
131    StepCompletedWithPendingToolCall { pending_count: usize },
132    /// A step stream ended without a completion, failure, cancellation, or
133    /// pending tool-call event.
134    StepEndedWithoutTerminalEvent,
135    /// The loop required the final-output tool but the model completed with text.
136    FinalOutputToolNotCalled,
137    /// A pending tool call must be executed by an external bridge runner.
138    BridgeToolCallRequested {
139        /// Bridge tool call id.
140        call_id: ToolCallId,
141        /// Bridge tool name.
142        tool_name: ToolName,
143    },
144}
145
146/// Runtime method error returned while an agent loop was running.
147///
148/// Runtime failed/cancelled events are represented as [`AgentLoopStatus`].
149/// This error is reserved for facade-method failures such as step admission,
150/// unknown calls, executor infrastructure failure, or an interrupted stream.
151/// Cooperative tool cancellation is represented as
152/// [`AgentLoopStatus::Cancelled`]. The already-observed runtime events are
153/// preserved for callers.
154#[derive(Debug, Error)]
155#[error("agent loop stopped on runtime method error: {source}")]
156pub struct AgentLoopError {
157    events: Vec<RuntimeJournalEvent>,
158    #[source]
159    source: Box<RuntimeError>,
160}
161
162impl AgentLoopError {
163    pub(crate) fn new(events: Vec<RuntimeJournalEvent>, source: RuntimeError) -> Self {
164        Self {
165            events,
166            source: Box::new(source),
167        }
168    }
169
170    /// Retained evidence before the method error, excluding live deltas and rate samples.
171    #[must_use]
172    pub fn events(&self) -> &[RuntimeJournalEvent] {
173        &self.events
174    }
175
176    /// Underlying runtime method error.
177    #[must_use]
178    pub fn runtime_error(&self) -> &RuntimeError {
179        &self.source
180    }
181
182    /// Consumes the error into its preserved events and runtime error.
183    #[must_use]
184    pub fn into_parts(self) -> (Vec<RuntimeJournalEvent>, RuntimeError) {
185        (self.events, *self.source)
186    }
187}