merry_runtime/agent_loop/
run.rs1use super::{AgentLoopError, AgentLoopResult, agent_loop_stream_error};
4use crate::{
5 HookDecision, HookInvocation, HookInvocationId, RuntimeError, ToolExecutionOutcome,
6 bridge::{BridgeToolResultCommand, BridgeToolResultPayload},
7 hooks::bridge::HookDecisionCommand,
8};
9use futures_util::StreamExt;
10use merry_core::{PendingToolCallBatch, RuntimeEvent, SessionId, ToolCallBatchId, ToolCallId};
11use std::sync::{
12 Arc,
13 atomic::{AtomicU64, Ordering},
14};
15use tokio::sync::{mpsc, oneshot};
16use tokio_stream::wrappers::ReceiverStream;
17
18pub 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 hook_sender: mpsc::Sender<HookDecisionCommand>,
34 pending_hook_invocation: Option<HookInvocation>,
35 hook_resolution_epoch: Arc<AtomicU64>,
36 observed_hook_resolution_epoch: u64,
37}
38
39impl AgentRun {
40 #[allow(clippy::too_many_arguments)]
41 pub(crate) fn new(
42 session_id: SessionId,
43 events: ReceiverStream<AgentRunMessage>,
44 loop_token: tokio_util::sync::CancellationToken,
45 producer_handle: tokio::task::JoinHandle<()>,
46 result_receiver: oneshot::Receiver<Result<AgentLoopResult, AgentLoopError>>,
47 bridge_sender: mpsc::Sender<BridgeToolResultCommand>,
48 bridge_resolution_epoch: Arc<AtomicU64>,
49 hook_sender: mpsc::Sender<HookDecisionCommand>,
50 hook_resolution_epoch: Arc<AtomicU64>,
51 ) -> Self {
52 let observed_bridge_resolution_epoch = bridge_resolution_epoch.load(Ordering::Acquire);
53 let observed_hook_resolution_epoch = hook_resolution_epoch.load(Ordering::Acquire);
54 Self {
55 session_id,
56 events,
57 loop_token,
58 producer_handle: Some(producer_handle),
59 result_receiver: Some(result_receiver),
60 bridge_sender,
61 pending_tool_invocations: None,
62 bridge_resolution_epoch,
63 observed_bridge_resolution_epoch,
64 hook_sender,
65 pending_hook_invocation: None,
66 hook_resolution_epoch,
67 observed_hook_resolution_epoch,
68 }
69 }
70
71 fn synchronize_bridge_resolution(&mut self) {
72 let epoch = self.bridge_resolution_epoch.load(Ordering::Acquire);
73 if epoch != self.observed_bridge_resolution_epoch {
74 self.pending_tool_invocations = None;
75 self.observed_bridge_resolution_epoch = epoch;
76 }
77 let hook_epoch = self.hook_resolution_epoch.load(Ordering::Acquire);
78 if hook_epoch != self.observed_hook_resolution_epoch {
79 self.pending_hook_invocation = None;
80 self.observed_hook_resolution_epoch = hook_epoch;
81 }
82 }
83
84 pub async fn submit_bridge_tool_outcomes(
93 &mut self,
94 batch_id: &ToolCallBatchId,
95 outcomes: Vec<(ToolCallId, ToolExecutionOutcome)>,
96 ) -> Result<(), RuntimeError> {
97 let Some(expected_batch) = self.pending_tool_invocations.as_ref() else {
98 return Err(RuntimeError::NoPendingAgentRunToolInvocations {
99 session_id: self.session_id.clone(),
100 });
101 };
102 if expected_batch.id() != batch_id {
103 return Err(RuntimeError::BridgeToolResultBatchIdMismatch {
104 session_id: self.session_id.clone(),
105 expected_batch_id: expected_batch.id().clone(),
106 received_batch_id: batch_id.clone(),
107 });
108 }
109 if outcomes.is_empty() {
110 return Err(RuntimeError::BridgeToolResultBatchEmpty {
111 session_id: self.session_id.clone(),
112 });
113 }
114 let result = self
115 .submit_bridge_command(BridgeToolResultPayload::Outcomes {
116 batch_id: batch_id.clone(),
117 outcomes,
118 })
119 .await;
120 match &result {
121 Ok(()) => self.pending_tool_invocations = None,
122 Err(error) if error.is_retryable_bridge_tool_result() => {}
123 Err(_) => self.pending_tool_invocations = None,
124 }
125 result
126 }
127
128 async fn submit_bridge_command(
129 &self,
130 payload: BridgeToolResultPayload,
131 ) -> Result<(), RuntimeError> {
132 let (ack_sender, ack_receiver) = oneshot::channel();
133 let command = BridgeToolResultCommand {
134 payload,
135 ack_sender,
136 };
137 self.bridge_sender
138 .send(command)
139 .await
140 .map_err(|_| RuntimeError::AgentRunClosed {
141 session_id: self.session_id.clone(),
142 message: "agent run closed before accepting the bridge tool result",
143 })?;
144 ack_receiver
145 .await
146 .map_err(|_| RuntimeError::AgentRunClosed {
147 session_id: self.session_id.clone(),
148 message: "agent run closed before acknowledging the bridge tool result",
149 })?
150 }
151
152 pub async fn submit_hook_decision(
154 &mut self,
155 invocation_id: &HookInvocationId,
156 decision: HookDecision,
157 ) -> Result<(), RuntimeError> {
158 self.submit_hook_outcome(invocation_id, Ok(decision)).await
159 }
160
161 pub async fn fail_hook_invocation(
163 &mut self,
164 invocation_id: &HookInvocationId,
165 message: String,
166 ) -> Result<(), RuntimeError> {
167 self.submit_hook_outcome(invocation_id, Err(message)).await
168 }
169
170 async fn submit_hook_outcome(
171 &mut self,
172 invocation_id: &HookInvocationId,
173 outcome: Result<HookDecision, String>,
174 ) -> Result<(), RuntimeError> {
175 self.synchronize_bridge_resolution();
176 let Some(expected) = self.pending_hook_invocation.as_ref() else {
177 return Err(RuntimeError::NoPendingAgentRunHookInvocation {
178 session_id: self.session_id.clone(),
179 });
180 };
181 if expected.id() != invocation_id {
182 return Err(RuntimeError::HookInvocationIdMismatch {
183 session_id: self.session_id.clone(),
184 expected_invocation_id: expected.id().clone(),
185 received_invocation_id: invocation_id.clone(),
186 });
187 }
188 let (ack_sender, ack_receiver) = oneshot::channel();
189 self.hook_sender
190 .send(HookDecisionCommand {
191 invocation_id: invocation_id.clone(),
192 outcome,
193 ack_sender,
194 })
195 .await
196 .map_err(|_| RuntimeError::AgentRunClosed {
197 session_id: self.session_id.clone(),
198 message: "agent run closed before accepting the hook decision",
199 })?;
200 let result = ack_receiver
201 .await
202 .map_err(|_| RuntimeError::AgentRunClosed {
203 session_id: self.session_id.clone(),
204 message: "agent run closed before acknowledging the hook decision",
205 })?;
206 if result.is_ok() {
207 self.pending_hook_invocation = None;
208 }
209 result
210 }
211
212 pub async fn result(&mut self) -> Result<AgentLoopResult, AgentLoopError> {
217 loop {
218 match self.next_message().await {
219 Ok(Some(AgentRunMessage::Event(_))) => {}
220 Ok(Some(AgentRunMessage::ToolInvocations { batch: _ })) => {
221 self.request_cancel();
222 self.pending_tool_invocations = None;
223 return Err(agent_loop_stream_error(
224 &self.session_id,
225 Vec::new(),
226 "agent run result requested before the host tool batch was resolved",
227 ));
228 }
229 Ok(Some(AgentRunMessage::HookInvocation { .. })) => {
230 self.request_cancel();
231 self.pending_hook_invocation = None;
232 return Err(agent_loop_stream_error(
233 &self.session_id,
234 Vec::new(),
235 "agent run result requested before the hook invocation was resolved",
236 ));
237 }
238 Ok(None) => break,
239 Err(source) => {
240 self.request_cancel();
241 self.pending_tool_invocations = None;
242 self.pending_hook_invocation = None;
243 return Err(AgentLoopError::new(Vec::new(), source));
244 }
245 }
246 }
247
248 let Some(result_receiver) = self.result_receiver.take() else {
249 return Err(agent_loop_stream_error(
250 &self.session_id,
251 Vec::new(),
252 "agent loop stream result was already consumed",
253 ));
254 };
255 match result_receiver.await {
256 Ok(result) => result,
257 Err(_) => Err(agent_loop_stream_error(
258 &self.session_id,
259 Vec::new(),
260 "agent loop stream producer stopped before returning a result",
261 )),
262 }
263 }
264
265 pub async fn cancel_and_wait(&mut self) {
271 self.loop_token.cancel();
272 self.pending_tool_invocations = None;
273 self.pending_hook_invocation = None;
274 while self.events.next().await.is_some() {}
278 if let Some(handle) = self.producer_handle.take() {
279 let _ = handle.await;
280 }
281 }
282
283 pub async fn next_message(&mut self) -> Result<Option<AgentRunMessage>, RuntimeError> {
288 self.synchronize_bridge_resolution();
289 if let Some(batch) = self.pending_tool_invocations.as_ref() {
290 return Err(RuntimeError::AgentRunToolInvocationsPending {
291 session_id: self.session_id.clone(),
292 batch_id: batch.id().clone(),
293 });
294 }
295 if let Some(invocation) = self.pending_hook_invocation.as_ref() {
296 return Err(RuntimeError::AgentRunHookInvocationPending {
297 session_id: self.session_id.clone(),
298 invocation_id: invocation.id().clone(),
299 });
300 }
301 let Some(message) = self.events.next().await else {
302 return Ok(None);
303 };
304 match &message {
305 AgentRunMessage::ToolInvocations { batch } => {
306 if batch.calls().is_empty() {
307 return Err(RuntimeError::BridgeToolResultBatchEmpty {
308 session_id: self.session_id.clone(),
309 });
310 }
311 self.pending_tool_invocations = Some(batch.clone());
312 }
313 AgentRunMessage::HookInvocation { invocation } => {
314 self.pending_hook_invocation = Some(invocation.clone());
315 }
316 AgentRunMessage::Event(_) => {}
317 }
318 Ok(Some(message))
319 }
320
321 pub async fn next(&mut self) -> Result<Option<AgentRunMessage>, RuntimeError> {
326 self.next_message().await
327 }
328
329 pub fn request_cancel(&mut self) {
336 self.loop_token.cancel();
337 self.pending_tool_invocations = None;
338 self.pending_hook_invocation = None;
339 }
340}
341
342impl Drop for AgentRun {
343 fn drop(&mut self) {
344 self.loop_token.cancel();
345 if let Some(handle) = self.producer_handle.take() {
346 handle.abort();
347 }
348 }
349}
350
351#[allow(clippy::large_enum_variant)]
354#[derive(Debug, Clone, PartialEq, Eq)]
355#[non_exhaustive]
356pub enum AgentRunMessage {
357 Event(RuntimeEvent),
359 ToolInvocations {
366 batch: PendingToolCallBatch,
370 },
371 HookInvocation {
376 invocation: HookInvocation,
378 },
379}
380
381impl AgentRunMessage {
382 #[must_use]
383 pub fn as_event(&self) -> Option<&RuntimeEvent> {
384 match self {
385 Self::Event(event) => Some(event),
386 Self::ToolInvocations { .. } | Self::HookInvocation { .. } => None,
387 }
388 }
389
390 #[must_use]
393 pub fn as_tool_invocations(&self) -> Option<&PendingToolCallBatch> {
394 match self {
395 Self::ToolInvocations { batch } => Some(batch),
396 Self::Event(_) | Self::HookInvocation { .. } => None,
397 }
398 }
399
400 #[must_use]
402 pub fn as_hook_invocation(&self) -> Option<&HookInvocation> {
403 match self {
404 Self::HookInvocation { invocation } => Some(invocation),
405 Self::Event(_) | Self::ToolInvocations { .. } => None,
406 }
407 }
408}