Skip to main content

strands/agent/
stream.rs

1//! [`AgentStream`]: the agent loop as a stream of event records.
2//!
3//! The loop is an ordinary `async fn` that hands each record to an [`Emitter`] and suspends until
4//! the consumer takes it, so the loop advances only as the stream is polled. Dropping the stream
5//! drops the loop's future; the loop's drop guard then repairs history.
6
7use std::fmt;
8use std::future::Future;
9use std::pin::Pin;
10use std::sync::{Arc, Mutex, PoisonError};
11use std::task::{Context, Poll};
12
13use futures::Stream;
14
15use super::result::AgentResult;
16use crate::error::Result;
17use crate::hooks::AgentStreamEvent;
18
19type Slot = Arc<Mutex<Option<AgentStreamEvent>>>;
20type LoopFuture<'a> = Pin<Box<dyn Future<Output = Result<AgentResult>> + Send + 'a>>;
21
22/// Hands records from the loop to its [`AgentStream`].
23#[derive(Clone, Default)]
24pub(crate) struct Emitter {
25    slot: Slot,
26}
27
28impl Emitter {
29    /// Yields `event` to the consumer; completes once the consumer has taken it.
30    pub(crate) async fn emit(&self, event: AgentStreamEvent) {
31        *self.slot.lock().unwrap_or_else(PoisonError::into_inner) = Some(event);
32        YieldOnce(false).await;
33    }
34}
35
36struct YieldOnce(bool);
37
38impl Future for YieldOnce {
39    type Output = ();
40
41    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
42        if self.0 {
43            return Poll::Ready(());
44        }
45        self.0 = true;
46        cx.waker().wake_by_ref();
47        Poll::Pending
48    }
49}
50
51/// The stream of an agent invocation (`agent.stream()`): event records, ending with
52/// [`AgentStreamEvent::AgentResult`]. An invocation a `BeforeInvocationEvent` hook cancelled ends
53/// without that record; [`into_result`](Self::into_result) returns the result either way.
54///
55/// The loop runs as the stream is polled. It borrows the agent, so the agent cannot be invoked
56/// again until the stream is finished or dropped. Dropping it early cancels the invocation: tool
57/// tasks still running are aborted, history is closed with the cancel message, and the
58/// `AfterInvocationEvent` hooks run at the start of the agent's next call.
59///
60/// An error ends the stream: it is the last item.
61#[must_use = "streams do nothing unless polled"]
62pub struct AgentStream<'a> {
63    future: Option<LoopFuture<'a>>,
64    slot: Slot,
65    result: Option<AgentResult>,
66}
67
68impl<'a> AgentStream<'a> {
69    pub(crate) fn new(emitter: &Emitter, future: impl Future<Output = Result<AgentResult>> + Send + 'a) -> Self {
70        Self {
71            future: Some(Box::pin(future)),
72            slot: emitter.slot.clone(),
73            result: None,
74        }
75    }
76
77    /// Takes the invocation result once the stream has ended.
78    pub(crate) fn take_result(&mut self) -> Option<AgentResult> {
79        self.result.take()
80    }
81
82    /// The invocation's result, once the stream has ended.
83    /// `None` while it is still running and when the invocation failed.
84    ///
85    /// ```
86    /// use futures::StreamExt;
87    /// use strands::Agent;
88    /// use strands::hooks::BeforeInvocationEvent;
89    /// use strands::testing::MockModel;
90    ///
91    /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async {
92    /// let mut agent = Agent::builder().model(MockModel::new()).printer(false).build()?;
93    /// agent.add_hook(|event: &mut BeforeInvocationEvent<'_>| event.set_cancel("closed"));
94    /// let mut stream = agent.stream("Hi");
95    /// while let Some(event) = stream.next().await {
96    ///     event?;
97    /// }
98    /// let result = stream.into_result().expect("the stream ended");
99    /// assert_eq!(result.to_string(), "closed");
100    /// # Ok::<(), strands::Error>(())
101    /// # }).unwrap();
102    /// ```
103    #[must_use]
104    pub fn into_result(mut self) -> Option<AgentResult> {
105        self.result.take()
106    }
107
108    fn take_event(&self) -> Option<AgentStreamEvent> {
109        self.slot.lock().unwrap_or_else(PoisonError::into_inner).take()
110    }
111}
112
113impl Stream for AgentStream<'_> {
114    type Item = Result<AgentStreamEvent>;
115
116    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
117        let Some(future) = self.future.as_mut() else {
118            return Poll::Ready(None);
119        };
120        let polled = future.as_mut().poll(cx);
121        if let Some(event) = self.take_event() {
122            if let Poll::Ready(output) = polled {
123                self.finish(output);
124            }
125            return Poll::Ready(Some(Ok(event)));
126        }
127        match polled {
128            Poll::Pending => Poll::Pending,
129            Poll::Ready(Ok(result)) => {
130                self.future = None;
131                self.result = Some(result);
132                Poll::Ready(None)
133            }
134            Poll::Ready(Err(error)) => {
135                self.future = None;
136                Poll::Ready(Some(Err(error)))
137            }
138        }
139    }
140}
141
142impl AgentStream<'_> {
143    fn finish(&mut self, output: Result<AgentResult>) {
144        self.future = None;
145        if let Ok(result) = output {
146            self.result = Some(result);
147        }
148    }
149}
150
151impl fmt::Debug for AgentStream<'_> {
152    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
153        f.debug_struct("AgentStream")
154            .field("finished", &self.future.is_none())
155            .finish_non_exhaustive()
156    }
157}
158
159/// The stream and emitter mechanics.
160#[cfg(test)]
161mod tests;