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    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
18/// Runtime-owned single-consumer protocol for one agent run.
19///
20/// [`Self::next_message`] is the only output path. It yields durable runtime
21/// events, explicit host-owned tool batches, and subscribed host-bridged hook
22/// invocations from the same ordered channel.
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    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    /// Submits a complete batch of host-executed tool outcomes.
85    ///
86    /// The host may prepare results concurrently, then submit the complete set
87    /// in any order. The batch itself does not grant parallel-execution safety;
88    /// the runtime validates the complete set and records it in pending-call
89    /// order before starting the next model turn. Correctable validation errors
90    /// keep the batch pending; a non-correctable recording error is converted
91    /// into a failed tool result so the model loop can still recover.
92    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    /// Submits a typed decision for the active host-bridged hook invocation.
153    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    /// Reports a fail-closed host hook error for the active hook invocation.
162    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    /// Returns the collected loop result once the run has completed.
213    ///
214    /// Unconsumed events are drained. An unresolved host-tool batch or hook
215    /// invocation is reported as an error and cancellation is requested.
216    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    /// Cancels the loop producer and waits until its task has stopped.
266    ///
267    /// This is the output-boundary cancellation path: once a consumer cannot
268    /// accept another event, callers must stop provider/tool work before
269    /// settling and persisting the runtime state.
270    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        // A producer may be waiting for capacity while publishing a durable
275        // event. Drain the bounded channel so cancellation can reach the
276        // runtime checkpoint instead of relying on task abortion.
277        while self.events.next().await.is_some() {}
278        if let Some(handle) = self.producer_handle.take() {
279            let _ = handle.await;
280        }
281    }
282
283    /// Returns the next runtime-owned run message.
284    ///
285    /// SDK host adapters use this to execute bridge tool calls and subscribed
286    /// host hooks without exposing bridge handoff as a public [`RuntimeEvent`].
287    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    /// Returns the next runtime-owned run message.
322    ///
323    /// This Rust convenience alias has the same message-first semantics as
324    /// [`Self::next_message`]; it never filters host-tool handoffs.
325    pub async fn next(&mut self) -> Result<Option<AgentRunMessage>, RuntimeError> {
326        self.next_message().await
327    }
328
329    /// Requests cancellation without waiting for the producer task to stop.
330    ///
331    /// This is intended for synchronous cleanup guards that cannot await, such
332    /// as a facade tool-invocation lease being dropped before it is resolved.
333    /// Callers that own an async lifecycle should prefer [`Self::cancel_and_wait`]
334    /// so producer completion and the terminal result are observed explicitly.
335    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/// Message emitted by an [`AgentRun`].
352// Keep the public event inline to avoid an allocation for every streamed event.
353#[allow(clippy::large_enum_variant)]
354#[derive(Debug, Clone, PartialEq, Eq)]
355#[non_exhaustive]
356pub enum AgentRunMessage {
357    /// Public SDK/UI event.
358    Event(RuntimeEvent),
359    /// Ordered host-owned tool calls from one runtime execution wave.
360    ///
361    /// Runtime-owned calls from the same model response are executed internally
362    /// and are not emitted here. A single host call is represented as a
363    /// one-call batch; calls are never combined across model responses or
364    /// separate run reads.
365    ToolInvocations {
366        /// Runtime-owned batch ID and host-owned calls in provider/model order.
367        /// Every call must be resolved before the run can request the next
368        /// runtime execution wave or model response.
369        batch: PendingToolCallBatch,
370    },
371    /// Subscribed host-bridged lifecycle hook awaiting a typed decision.
372    ///
373    /// Emitted only when the host explicitly subscribed to this hook point
374    /// (and matching tool name, for tool hooks).
375    HookInvocation {
376        /// Pending hook invocation payload and identifier.
377        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    /// Borrows the runtime-owned tool batch when this message carries a host
391    /// invocation handoff.
392    #[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    /// Borrows the hook invocation when this message carries a bridged hook request.
401    #[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}