Skip to main content

merry_runtime/agent_loop/
run.rs

1//! Single-consumer stream handle for a runtime-owned agent loop.
2
3use super::{AgentLoopError, AgentLoopResult, agent_loop_stream_error};
4use crate::{
5    RuntimeError, ToolExecutionOutcome,
6    bridge::{BridgeToolResultCommand, BridgeToolResultPayload},
7};
8use futures_util::StreamExt;
9use merry_core::{PendingToolCallBatch, RuntimeEvent, SessionId, ToolCallBatchId, ToolCallId};
10use std::sync::{
11    Arc,
12    atomic::{AtomicU64, Ordering},
13};
14use tokio::sync::{mpsc, oneshot};
15use tokio_stream::wrappers::ReceiverStream;
16
17/// Runtime-owned single-consumer protocol for one agent run.
18///
19/// [`Self::next_message`] is the only output path. It yields durable runtime
20/// events and explicit host-owned tool batches from the same ordered channel,
21/// so a consumer cannot accidentally skip a tool handoff by using an
22/// event-only stream. Runtime state owns the active batch and its lifecycle.
23pub struct AgentRun {
24    session_id: SessionId,
25    events: ReceiverStream<AgentRunMessage>,
26    loop_token: tokio_util::sync::CancellationToken,
27    producer_handle: Option<tokio::task::JoinHandle<()>>,
28    result_receiver: Option<oneshot::Receiver<Result<AgentLoopResult, AgentLoopError>>>,
29    bridge_sender: mpsc::Sender<BridgeToolResultCommand>,
30    pending_tool_invocations: Option<PendingToolCallBatch>,
31    bridge_resolution_epoch: Arc<AtomicU64>,
32    observed_bridge_resolution_epoch: u64,
33}
34
35impl AgentRun {
36    pub(crate) fn new(
37        session_id: SessionId,
38        events: ReceiverStream<AgentRunMessage>,
39        loop_token: tokio_util::sync::CancellationToken,
40        producer_handle: tokio::task::JoinHandle<()>,
41        result_receiver: oneshot::Receiver<Result<AgentLoopResult, AgentLoopError>>,
42        bridge_sender: mpsc::Sender<BridgeToolResultCommand>,
43        bridge_resolution_epoch: Arc<AtomicU64>,
44    ) -> Self {
45        let observed_bridge_resolution_epoch = bridge_resolution_epoch.load(Ordering::Acquire);
46        Self {
47            session_id,
48            events,
49            loop_token,
50            producer_handle: Some(producer_handle),
51            result_receiver: Some(result_receiver),
52            bridge_sender,
53            pending_tool_invocations: None,
54            bridge_resolution_epoch,
55            observed_bridge_resolution_epoch,
56        }
57    }
58
59    fn synchronize_bridge_resolution(&mut self) {
60        let epoch = self.bridge_resolution_epoch.load(Ordering::Acquire);
61        if epoch != self.observed_bridge_resolution_epoch {
62            self.pending_tool_invocations = None;
63            self.observed_bridge_resolution_epoch = epoch;
64        }
65    }
66
67    /// Submits a complete batch of host-executed tool outcomes.
68    ///
69    /// The host may prepare results concurrently, then submit the complete set
70    /// in any order. The batch itself does not grant parallel-execution safety;
71    /// the runtime validates the complete set and records it in pending-call
72    /// order before starting the next model turn. Correctable validation errors
73    /// keep the batch pending; a non-correctable recording error is converted
74    /// into a failed tool result so the model loop can still recover.
75    pub async fn submit_bridge_tool_outcomes(
76        &mut self,
77        batch_id: &ToolCallBatchId,
78        outcomes: Vec<(ToolCallId, ToolExecutionOutcome)>,
79    ) -> Result<(), RuntimeError> {
80        let Some(expected_batch) = self.pending_tool_invocations.as_ref() else {
81            return Err(RuntimeError::NoPendingAgentRunToolInvocations {
82                session_id: self.session_id.clone(),
83            });
84        };
85        if expected_batch.id() != batch_id {
86            return Err(RuntimeError::BridgeToolResultBatchIdMismatch {
87                session_id: self.session_id.clone(),
88                expected_batch_id: expected_batch.id().clone(),
89                received_batch_id: batch_id.clone(),
90            });
91        }
92        if outcomes.is_empty() {
93            return Err(RuntimeError::BridgeToolResultBatchEmpty {
94                session_id: self.session_id.clone(),
95            });
96        }
97        let result = self
98            .submit_bridge_command(BridgeToolResultPayload::Outcomes {
99                batch_id: batch_id.clone(),
100                outcomes,
101            })
102            .await;
103        match &result {
104            Ok(()) => self.pending_tool_invocations = None,
105            Err(error) if error.is_retryable_bridge_tool_result() => {}
106            Err(_) => self.pending_tool_invocations = None,
107        }
108        result
109    }
110
111    async fn submit_bridge_command(
112        &self,
113        payload: BridgeToolResultPayload,
114    ) -> Result<(), RuntimeError> {
115        let (ack_sender, ack_receiver) = oneshot::channel();
116        let command = BridgeToolResultCommand {
117            payload,
118            ack_sender,
119        };
120        self.bridge_sender
121            .send(command)
122            .await
123            .map_err(|_| RuntimeError::AgentRunClosed {
124                session_id: self.session_id.clone(),
125                message: "agent run closed before accepting the bridge tool result",
126            })?;
127        ack_receiver
128            .await
129            .map_err(|_| RuntimeError::AgentRunClosed {
130                session_id: self.session_id.clone(),
131                message: "agent run closed before acknowledging the bridge tool result",
132            })?
133    }
134
135    /// Returns the collected loop result once the run has completed.
136    ///
137    /// Unconsumed events are drained. An unresolved host-tool batch is reported
138    /// as an error and cancellation is requested so the producer cannot remain
139    /// blocked waiting for a result that the caller has abandoned.
140    pub async fn result(&mut self) -> Result<AgentLoopResult, AgentLoopError> {
141        loop {
142            match self.next_message().await {
143                Ok(Some(AgentRunMessage::Event(_))) => {}
144                Ok(Some(AgentRunMessage::ToolInvocations { batch: _ })) => {
145                    self.request_cancel();
146                    self.pending_tool_invocations = None;
147                    return Err(agent_loop_stream_error(
148                        &self.session_id,
149                        Vec::new(),
150                        "agent run result requested before the host tool batch was resolved",
151                    ));
152                }
153                Ok(None) => break,
154                Err(source) => {
155                    self.request_cancel();
156                    self.pending_tool_invocations = None;
157                    return Err(AgentLoopError::new(Vec::new(), source));
158                }
159            }
160        }
161
162        let Some(result_receiver) = self.result_receiver.take() else {
163            return Err(agent_loop_stream_error(
164                &self.session_id,
165                Vec::new(),
166                "agent loop stream result was already consumed",
167            ));
168        };
169        match result_receiver.await {
170            Ok(result) => result,
171            Err(_) => Err(agent_loop_stream_error(
172                &self.session_id,
173                Vec::new(),
174                "agent loop stream producer stopped before returning a result",
175            )),
176        }
177    }
178
179    /// Cancels the loop producer and waits until its task has stopped.
180    ///
181    /// This is the output-boundary cancellation path: once a consumer cannot
182    /// accept another event, callers must stop provider/tool work before
183    /// settling and persisting the runtime state.
184    pub async fn cancel_and_wait(&mut self) {
185        self.loop_token.cancel();
186        self.pending_tool_invocations = None;
187        // A producer may be waiting for capacity while publishing a durable
188        // event. Drain the bounded channel so cancellation can reach the
189        // runtime checkpoint instead of relying on task abortion.
190        while self.events.next().await.is_some() {}
191        if let Some(handle) = self.producer_handle.take() {
192            let _ = handle.await;
193        }
194    }
195
196    /// Returns the next runtime-owned run message.
197    ///
198    /// SDK host adapters use this to execute bridge tool calls without
199    /// exposing bridge handoff as a public [`RuntimeEvent`].
200    pub async fn next_message(&mut self) -> Result<Option<AgentRunMessage>, RuntimeError> {
201        self.synchronize_bridge_resolution();
202        if let Some(batch) = self.pending_tool_invocations.as_ref() {
203            return Err(RuntimeError::AgentRunToolInvocationsPending {
204                session_id: self.session_id.clone(),
205                batch_id: batch.id().clone(),
206            });
207        }
208        let Some(message) = self.events.next().await else {
209            return Ok(None);
210        };
211        if let AgentRunMessage::ToolInvocations { batch } = &message {
212            if batch.calls().is_empty() {
213                return Err(RuntimeError::BridgeToolResultBatchEmpty {
214                    session_id: self.session_id.clone(),
215                });
216            }
217            self.pending_tool_invocations = Some(batch.clone());
218        }
219        Ok(Some(message))
220    }
221
222    /// Returns the next runtime-owned run message.
223    ///
224    /// This Rust convenience alias has the same message-first semantics as
225    /// [`Self::next_message`]; it never filters host-tool handoffs.
226    pub async fn next(&mut self) -> Result<Option<AgentRunMessage>, RuntimeError> {
227        self.next_message().await
228    }
229
230    /// Requests cancellation without waiting for the producer task to stop.
231    ///
232    /// This is intended for synchronous cleanup guards that cannot await, such
233    /// as a facade tool-invocation lease being dropped before it is resolved.
234    /// Callers that own an async lifecycle should prefer [`Self::cancel_and_wait`]
235    /// so producer completion and the terminal result are observed explicitly.
236    pub fn request_cancel(&mut self) {
237        self.loop_token.cancel();
238        self.pending_tool_invocations = None;
239    }
240}
241
242impl Drop for AgentRun {
243    fn drop(&mut self) {
244        self.loop_token.cancel();
245        if let Some(handle) = self.producer_handle.take() {
246            handle.abort();
247        }
248    }
249}
250
251/// Message emitted by an [`AgentRun`].
252// Keep the public event inline to avoid an allocation for every streamed event.
253#[allow(clippy::large_enum_variant)]
254#[derive(Debug, Clone, PartialEq, Eq)]
255#[non_exhaustive]
256pub enum AgentRunMessage {
257    /// Public SDK/UI event.
258    Event(RuntimeEvent),
259    /// Ordered host-owned tool calls from one runtime execution wave.
260    ///
261    /// Runtime-owned calls from the same model response are executed internally
262    /// and are not emitted here. A single host call is represented as a
263    /// one-call batch; calls are never combined across model responses or
264    /// separate run reads.
265    ToolInvocations {
266        /// Runtime-owned batch ID and host-owned calls in provider/model order.
267        /// Every call must be resolved before the run can request the next
268        /// runtime execution wave or model response.
269        batch: PendingToolCallBatch,
270    },
271}
272
273impl AgentRunMessage {
274    #[must_use]
275    pub fn as_event(&self) -> Option<&RuntimeEvent> {
276        match self {
277            Self::Event(event) => Some(event),
278            Self::ToolInvocations { .. } => None,
279        }
280    }
281
282    /// Borrows the runtime-owned tool batch when this message carries a host
283    /// invocation handoff.
284    #[must_use]
285    pub fn as_tool_invocations(&self) -> Option<&PendingToolCallBatch> {
286        match self {
287            Self::ToolInvocations { batch } => Some(batch),
288            Self::Event(_) => None,
289        }
290    }
291}