1use 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#[derive(Clone, Default)]
24pub(crate) struct Emitter {
25 slot: Slot,
26}
27
28impl Emitter {
29 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#[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 pub(crate) fn take_result(&mut self) -> Option<AgentResult> {
79 self.result.take()
80 }
81
82 #[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#[cfg(test)]
161mod tests;