merry_runtime/agent_loop/
run.rs1use 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
17pub 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 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 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 pub async fn cancel_and_wait(&mut self) {
185 self.loop_token.cancel();
186 self.pending_tool_invocations = None;
187 while self.events.next().await.is_some() {}
191 if let Some(handle) = self.producer_handle.take() {
192 let _ = handle.await;
193 }
194 }
195
196 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 pub async fn next(&mut self) -> Result<Option<AgentRunMessage>, RuntimeError> {
227 self.next_message().await
228 }
229
230 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#[allow(clippy::large_enum_variant)]
254#[derive(Debug, Clone, PartialEq, Eq)]
255#[non_exhaustive]
256pub enum AgentRunMessage {
257 Event(RuntimeEvent),
259 ToolInvocations {
266 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 #[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}