Skip to main content

ag_ui/client/transport/
mod.rs

1//! Getting events from somewhere.
2//!
3//! Everything else in this crate is synchronous. This is the one layer that
4//! talks to the outside world, and the only place `async` appears — which is
5//! what lets the rest of the crate run under any executor, or none.
6//!
7//! [`Transport`] is deliberately small: one method that takes a
8//! [`RunAgentInput`] and hands back the run's stream as the transport has it,
9//! a [`TransportStream`]. That is wire JSON for anything that reads bytes, and
10//! typed events for a source that never had a wire. The client reads either
11//! through the same compatibility boundary. Implementations shipped here:
12//!
13//! - [`sse`] — the `text/event-stream` decoder every HTTP transport needs.
14#![cfg_attr(
15    feature = "http",
16    doc = "- [`http`] *(feature `http`)* — [`HttpTransport`], backed by `reqwest`."
17)]
18#![cfg_attr(
19    not(feature = "http"),
20    doc = "- `http` *(feature `http`, off in this build)* — `HttpTransport`, backed by `reqwest`."
21)]
22//! - [`replay`] — [`ReplayTransport`], which serves a scripted list of events
23//!   and records what was sent to it. Tests use it; so does the doc example.
24//!
25//! A wasm frontend, an in-process agent, a websocket, a recorded fixture: each
26//! is an `impl Transport`, and nothing above this module changes.
27
28pub mod replay;
29pub mod sse;
30
31#[cfg(feature = "http")]
32pub mod http;
33
34use std::future::Future;
35use std::pin::Pin;
36use std::sync::Arc;
37
38use crate::{Event, RunAgentInput};
39use futures_core::Stream;
40use futures_util::StreamExt;
41use serde_json::Value;
42
43use crate::client::enforce::{self, CheckedStream};
44use crate::client::error::{Error, Result};
45
46pub use replay::ReplayTransport;
47pub use sse::{SseDecoder, SseFrame, decode_events, decode_raw_events};
48
49#[cfg(feature = "http")]
50pub use http::{HttpTransport, HttpTransportBuilder};
51
52/// A boxed stream of typed events, after the compatibility boundary.
53///
54/// `Send` everywhere except wasm, where the browser APIs a transport would be
55/// built on are single-threaded and not `Send` at all. Requiring it there would
56/// make the wasm case — the reason this crate abstracts the transport in the
57/// first place — impossible to satisfy.
58#[cfg(not(target_family = "wasm"))]
59pub type EventStream = Pin<Box<dyn Stream<Item = Result<Event>> + Send>>;
60
61/// A boxed stream of typed events, after the compatibility boundary.
62#[cfg(target_family = "wasm")]
63pub type EventStream = Pin<Box<dyn Stream<Item = Result<Event>>>>;
64
65/// A boxed stream of wire JSON, before the compatibility boundary.
66#[cfg(not(target_family = "wasm"))]
67pub type RawEventStream = Pin<Box<dyn Stream<Item = Result<Value>> + Send>>;
68
69/// A boxed stream of wire JSON, before the compatibility boundary.
70#[cfg(target_family = "wasm")]
71pub type RawEventStream = Pin<Box<dyn Stream<Item = Result<Value>>>>;
72
73/// The future [`Transport::run`] returns: connecting, before any event arrives.
74#[cfg(not(target_family = "wasm"))]
75pub type TransportFuture = Pin<Box<dyn Future<Output = Result<TransportStream>> + Send>>;
76
77/// The future [`Transport::run`] returns: connecting, before any event arrives.
78#[cfg(target_family = "wasm")]
79pub type TransportFuture = Pin<Box<dyn Future<Output = Result<TransportStream>>>>;
80
81/// One run's events as a transport has them, before the client reads them.
82///
83/// A transport builds one of two forms and the client does the rest:
84///
85/// - [`json`](Self::json) — wire JSON, exactly as received. The client runs it
86///   through the compatibility boundary: schema enforcement, the optional-null
87///   registry and the translation of retired events. This is the form for
88///   anything that reads bytes.
89/// - [`typed`](Self::typed) — events built as [`Event`] in this process. They
90///   are delivered as given, with no serialize, schema walk and deserialize
91///   per event.
92///
93/// Either way the boundary's warnings reach a
94/// [`Thread`](crate::client::Thread) as
95/// [`Update::Warning`](crate::client::Update::Warning).
96pub struct TransportStream(Source);
97
98enum Source {
99    Json(RawEventStream),
100    Typed(EventStream),
101}
102
103impl std::fmt::Debug for TransportStream {
104    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
105        f.write_str(match self.0 {
106            Source::Json(_) => "TransportStream::json(..)",
107            Source::Typed(_) => "TransportStream::typed(..)",
108        })
109    }
110}
111
112impl TransportStream {
113    /// Wire JSON, one value per event, with unknown fields left in.
114    ///
115    /// An item that is an error ends the run. [`decode_raw_events`] produces
116    /// this stream from the chunks of a `text/event-stream` body.
117    ///
118    /// ```
119    /// use ag_ui::RunAgentInput;
120    /// use ag_ui::client::transport::{Transport, TransportFuture, TransportStream};
121    /// use futures_util::stream;
122    /// use serde_json::{Value, json};
123    ///
124    /// /// A socket, a queue, a file: anything that yields JSON values.
125    /// struct Frames(Vec<Value>);
126    ///
127    /// impl Transport for Frames {
128    ///     fn run(&self, _input: RunAgentInput) -> TransportFuture {
129    ///         let frames = stream::iter(self.0.clone().into_iter().map(Ok));
130    ///         Box::pin(async move { Ok(TransportStream::json(frames)) })
131    ///     }
132    /// }
133    /// # let _ = Frames(vec![json!({"type": "RUN_STARTED", "threadId": "t", "runId": "r"})]);
134    /// ```
135    #[cfg(not(target_family = "wasm"))]
136    pub fn json(raw: impl Stream<Item = Result<Value>> + Send + 'static) -> Self {
137        Self(Source::Json(Box::pin(raw)))
138    }
139
140    /// Wire JSON, one value per event, with unknown fields left in.
141    #[cfg(target_family = "wasm")]
142    pub fn json(raw: impl Stream<Item = Result<Value>> + 'static) -> Self {
143        Self(Source::Json(Box::pin(raw)))
144    }
145
146    /// Events that were built as [`Event`] in this process and never
147    /// serialized, such as the stream of an agent hosted in the same program.
148    ///
149    /// They are delivered as given: nothing is checked against the schema and
150    /// nothing is removed, because an [`Event`] holds nothing this version
151    /// does not know. What 1.0 retired is still translated as its wire form
152    /// would be, so a consumer sees one contract whichever form fed it: a
153    /// `THINKING_*` event, and a `binary` content part in a message snapshot,
154    /// an input echo or a tool result. A newer declared protocol version is
155    /// still reported. Call [`enforced`](Self::enforced) to have every event
156    /// checked instead.
157    ///
158    #[cfg_attr(feature = "server", doc = "```")]
159    #[cfg_attr(not(feature = "server"), doc = "```ignore")]
160    /// use std::sync::Arc;
161    ///
162    /// use ag_ui::client::transport::{Transport, TransportFuture, TransportStream};
163    /// use ag_ui::client::{RunEnd, Thread};
164    /// use ag_ui::server::{Agent, RunContext};
165    /// use ag_ui::{RunAgentInput, RunOutcome};
166    /// use futures_util::StreamExt;
167    ///
168    /// struct Greeter;
169    ///
170    /// impl Agent for Greeter {
171    ///     type State = ();
172    ///     async fn run(&self, ctx: &mut RunContext<()>) -> ag_ui::server::Result<RunOutcome> {
173    ///         ctx.say("hello")?;
174    ///         Ok(RunOutcome::Success)
175    ///     }
176    /// }
177    ///
178    /// /// An agent in the same process: no wire, so no JSON.
179    /// struct InProcess(Arc<Greeter>);
180    ///
181    /// impl Transport for InProcess {
182    ///     fn run(&self, input: RunAgentInput) -> TransportFuture {
183    ///         let events = ag_ui::server::run(Arc::clone(&self.0), input).map(Ok);
184    ///         Box::pin(async move { Ok(TransportStream::typed(events)) })
185    ///     }
186    /// }
187    ///
188    /// # let rt = tokio::runtime::Builder::new_current_thread().build().unwrap();
189    /// # rt.block_on(async {
190    /// let mut thread = Thread::new(InProcess(Arc::new(Greeter)), "thread-1");
191    /// let report = thread.send("hi").unwrap().collect_report().await;
192    /// assert_eq!(report.end, RunEnd::Success { result: None });
193    /// # });
194    /// ```
195    #[cfg(not(target_family = "wasm"))]
196    pub fn typed(events: impl Stream<Item = Result<Event>> + Send + 'static) -> Self {
197        Self(Source::Typed(Box::pin(events)))
198    }
199
200    /// Events that were built as [`Event`] in this process and never
201    /// serialized.
202    #[cfg(target_family = "wasm")]
203    pub fn typed(events: impl Stream<Item = Result<Event>> + 'static) -> Self {
204        Self(Source::Typed(Box::pin(events)))
205    }
206
207    /// Has typed events read the way a peer's are: each is serialized and goes
208    /// through the whole compatibility boundary. Wire JSON is left as it is.
209    ///
210    /// For a typed source that stands in for a remote agent, where the test is
211    /// what a client makes of the bytes. [`ReplayTransport`] does this.
212    #[must_use]
213    pub fn enforced(self) -> Self {
214        Self(Source::Json(self.into_json()))
215    }
216
217    /// The run as wire JSON, before the boundary: what a proxy or a recorder
218    /// forwards. Typed events are serialized.
219    pub fn into_json(self) -> RawEventStream {
220        match self.0 {
221            Source::Json(raw) => raw,
222            Source::Typed(events) => Box::pin(events.map(|event| {
223                event.and_then(|event| {
224                    serde_json::to_value(event).map_err(|error| Error::Protocol(error.to_string()))
225                })
226            })),
227        }
228    }
229
230    /// The run as typed events, after the boundary, handing each of its
231    /// warnings to `on_warning`. See [`enforce_events`] for what a warning is.
232    pub fn into_events<F>(self, on_warning: F) -> impl Stream<Item = Result<Event>>
233    where
234        F: FnMut(String),
235    {
236        enforce::unchecked(self.into_checked(), on_warning)
237    }
238
239    /// The run after the boundary, with its warnings left in the stream.
240    pub(crate) fn into_checked(self) -> CheckedStream {
241        match self.0 {
242            Source::Json(raw) => Box::pin(enforce::checked(raw)),
243            Source::Typed(events) => Box::pin(enforce::typed(events)),
244        }
245    }
246}
247
248/// Somewhere an agent's events come from.
249///
250/// One method. A transport does not decode, check or translate anything: it
251/// connects and returns the stream in the form it has it, and the client
252/// applies the compatibility boundary. See [`TransportStream`] for the two
253/// forms.
254///
255/// # Why the future is `'static`
256///
257/// A transport is usually held inside a [`Thread`](crate::client::Thread), which
258/// mutates its own state as events arrive. If the returned future borrowed the
259/// transport, that borrow would live as long as the run and the thread could
260/// not touch itself while streaming. So `run` clones what it needs —
261/// `reqwest::Client` is explicitly designed for exactly that — and the future
262/// stands alone.
263pub trait Transport {
264    /// Starts a run and connects to its stream.
265    ///
266    /// Failing to connect is an error from the future; failing mid-stream is an
267    /// error item in the stream.
268    fn run(&self, input: RunAgentInput) -> TransportFuture;
269}
270
271impl<T: Transport + ?Sized> Transport for &T {
272    fn run(&self, input: RunAgentInput) -> TransportFuture {
273        (**self).run(input)
274    }
275}
276
277impl<T: Transport + ?Sized> Transport for Box<T> {
278    fn run(&self, input: RunAgentInput) -> TransportFuture {
279        (**self).run(input)
280    }
281}
282
283impl<T: Transport + ?Sized> Transport for Arc<T> {
284    fn run(&self, input: RunAgentInput) -> TransportFuture {
285        (**self).run(input)
286    }
287}
288
289/// Runs raw wire events through the compatibility and enforcement boundary
290/// every transport shares, handing each of its warnings to `on_warning`.
291///
292/// This is the boundary a [`Thread`](crate::client::Thread) applies to
293/// [`TransportStream::json`], for code that reads wire JSON without one.
294///
295/// A warning says what the boundary removed or translated on the way: an
296/// unrecognised field, enum member or event, a retired `THINKING_*` event, a
297/// deprecated optional `null`, a newer declared protocol version. It arrives
298/// before the event it concerns, and a text already handed on in the same run
299/// is not handed on again. [`decode_events`] and
300/// [`RemoteAgent::run_events`](crate::client::RemoteAgent::run_events) apply
301/// the same boundary and discard them; a [`Thread`](crate::client::Thread)
302/// yields them as [`Update::Warning`](crate::client::Update::Warning). Nothing
303/// in this crate prints them.
304///
305/// ```
306/// use ag_ui::client::transport::{decode_raw_events, enforce_events};
307/// use futures_util::{StreamExt, stream};
308///
309/// # futures_util::FutureExt::now_or_never(async {
310/// let body = "data: {\"type\":\"RUN_STARTED\",\"threadId\":\"t\",\"runId\":\"r\",\"extra\":1}\n\n";
311/// let chunks = stream::iter([Ok::<_, std::io::Error>(body.as_bytes())]);
312/// let mut warnings = Vec::new();
313/// let events: Vec<_> = enforce_events(decode_raw_events(chunks), |warning| warnings.push(warning))
314///     .collect()
315///     .await;
316/// assert!(events[0].is_ok());
317/// assert_eq!(warnings, ["unrecognised property at /extra"]);
318/// # }).unwrap();
319/// ```
320pub fn enforce_events<S, F>(raw: S, on_warning: F) -> impl Stream<Item = Result<Event>>
321where
322    S: Stream<Item = Result<Value>>,
323    F: FnMut(String),
324{
325    enforce::events(raw, on_warning)
326}