Skip to main content

ag_ui/server/emit/
mod.rs

1//! Typestate handles that make protocol misuse a compile error.
2//!
3//! Every streaming construct in AG-UI is bracketed: `TEXT_MESSAGE_START` …
4//! `TEXT_MESSAGE_END`, `TOOL_CALL_START` … `TOOL_CALL_END`, `STEP_STARTED` …
5//! `STEP_FINISHED`. Handing an agent three raw `emit` calls per construct means
6//! trusting it to close what it opened, in order, on every path including the
7//! early return. This module hands out RAII handles instead:
8//!
9//! - creating a handle emits the opening event;
10//! - the handle borrows the [`RunContext`](crate::server::RunContext) mutably, so a
11//!   second overlapping handle is a **borrow-check error**, not a runtime
12//!   protocol violation;
13//! - `Drop` emits the terminator, so forgetting `end()` — or returning `Err`
14//!   through a `?` halfway through a message — still produces a well-formed
15//!   stream.
16//!
17//! ```compile_fail,E0499
18//! use ag_ui::server::RunContext;
19//!
20//! fn interleave(ctx: &mut RunContext<()>) {
21//!     let mut first = ctx.assistant_message().unwrap();
22//!     // error[E0499]: cannot borrow `*ctx` as mutable more than once at a time
23//!     let mut second = ctx.assistant_message().unwrap();
24//!     first.delta("a").unwrap();
25//!     second.delta("b").unwrap();
26//! }
27//! ```
28//!
29//! # Why the emit path is synchronous
30//!
31//! `Drop` cannot be async, so a handle cannot `await` while emitting its
32//! terminator. `msg.delta(text)?` therefore does not take `.await`: emitters
33//! push into a channel and the transport drains it. A configured
34//! [`Runner::event_buffer_capacity`](crate::server::Runner::event_buffer_capacity)
35//! rejects overflow with a terminal error instead of waiting. An earlier draft
36//! copied `await`-ing emitters from the TypeScript and .NET SDKs; it cannot
37//! coexist with the `Drop` guarantee.
38//!
39//! # The escape hatch
40//!
41//! [`StepGuard`] dereferences to the run context — a step is a scope, and
42//! everything else nests inside it. The three streaming handles deliberately do
43//! not, because that is exactly what would let a second message open inside the
44//! first. They expose [`emit`](MessageHandle::emit) instead, for the unordered
45//! events (state, activity, custom) that may legally interleave with a message.
46//!
47//! # What an open handle can still reach
48//!
49//! A handle borrows two *fields* of the run context — the event sink and the
50//! state — rather than the context itself. So the state is reachable through
51//! the handle ([`state`](ToolCallHandle::state),
52//! [`state_mut`](ToolCallHandle::state_mut),
53//! [`publish_state`](ToolCallHandle::publish_state)) and a tool call can do its
54//! work between its arguments and its result: `STATE_*` is unordered, so a
55//! publish inside the brackets is a legal stream.
56//!
57//! Widening reach, not weakening the rule. The context stays exclusively
58//! borrowed for as long as the handle lives, so a second block is still a
59//! borrow-check error — including from inside an open call:
60//!
61//! ```compile_fail,E0499
62//! use ag_ui::server::RunContext;
63//!
64//! fn narrate(ctx: &mut RunContext<()>) {
65//!     let mut call = ctx.tool_call("search").unwrap();
66//!     // error[E0499]: cannot borrow `*ctx` as mutable more than once at a time
67//!     let mut message = ctx.assistant_message().unwrap();
68//!     call.args("{}").unwrap();
69//! }
70//! ```
71//!
72//! # What has no handle, and why that is the answer
73//!
74//! Two things an agent may legitimately put on the wire are
75//! [`RunContext::emit`](crate::server::RunContext::emit) territory, and the escape
76//! hatch is the supported path for both rather than a gap waiting for an API.
77//!
78//! The `*_CHUNK` family is unbracketed by definition: a chunk carries its own
79//! id and needs no start and no end, which is the point — it exists for
80//! provider adapters that cannot know a message ended until the next one
81//! begins. There is nothing for an RAII handle to close, and wrapping one
82//! around a self-contained event would only add a way to get it wrong.
83//!
84//! Interleaved parallel tool calls are the other. Two open [`ToolCallHandle`]s
85//! at once is a borrow-check error *by design*, so a provider streaming
86//! `args(a) args(b) args(a) end(a) end(b)` cannot be mirrored handle-for-call.
87//! Either accumulate each call and emit it whole once its arguments are
88//! complete — what `e2e/src/llm.rs` does, and the only mapping that cannot
89//! splice two calls' arguments into each other — or emit the interleaving
90//! yourself. The verifier keys everything by id, so it accepts the interleaved
91//! stream; what it will not let you do is close a call you never opened.
92//!
93//! # Subagents
94//!
95//! [`SubagentHandle`] is a scope in the sense [`StepGuard`] is: it dereferences
96//! to the run context, and everything opened through it — messages, tool
97//! calls, reasoning, steps, nested subagents — comes out carrying its
98//! `subagentRunId`. The attribution lives in the event sink rather than in
99//! the handles, which is why a [`MessageHandle`] opened inside a subagent
100//! needs no idea that it was: the sink tags every attributable event that
101//! arrives untagged while a scope is open, and leaves an event the agent
102//! tagged explicitly alone.
103//!
104//! That last clause is the concurrent case. Subagents that stream at once are
105//! the parallel-tool-call situation again: two open handles is a borrow-check
106//! error by design, so build each subagent's events with
107//! [`Event::with_subagent_run_id`] and [`emit`](crate::server::RunContext::emit)
108//! them interleaved, bracketed by [`Event::subagent_started`] and
109//! [`Event::subagent_finished_success`]. The verifier keys every entity by id
110//! and remembers who opened it, so the interleaving is accepted; what it will
111//! not let you do is continue one subagent's message under another's tag.
112//! Attribute every chunk when several subagents stream at once — a chunk
113//! that names neither a message nor a subagent can only be resolved when one
114//! stream is open.
115
116mod message;
117mod reasoning;
118mod step;
119mod subagent;
120mod tool;
121
122use std::collections::BTreeSet;
123use std::num::NonZeroUsize;
124
125use crate::{Event, RunErrorEvent, SubagentRunId};
126use futures_channel::mpsc::{UnboundedReceiver, UnboundedSender};
127use futures_core::Stream;
128use futures_util::StreamExt as _;
129
130use crate::server::cancel::CancellationToken;
131use crate::server::error::{Error, Result, Rule, VerificationError};
132use crate::server::transform::TransformerChain;
133use crate::server::verify::Verifier;
134
135pub use message::MessageHandle;
136pub use reasoning::ReasoningHandle;
137pub use step::StepGuard;
138pub use subagent::SubagentHandle;
139pub use tool::ToolCallHandle;
140
141/// The write end of a run's event stream: transformers, then verification,
142/// then the channel.
143///
144/// Not public: the only way to reach one is through a
145/// [`RunContext`](crate::server::RunContext) or a handle, which is what keeps the
146/// ordering guarantees intact.
147pub(crate) struct EventSink {
148    tx: UnboundedSender<Event>,
149    chain: TransformerChain,
150    verifier: Verifier,
151    cancel: CancellationToken,
152    /// Whether a terminal event has gone out. Tracked here as well as in the
153    /// verifier so that turning the `verify` feature off cannot make the driver
154    /// emit a second `RUN_FINISHED`.
155    terminated: bool,
156    /// The subagent scope in force: every attributable event emitted untagged
157    /// while it is set goes out carrying it. See [`SubagentHandle`].
158    attribution: Option<SubagentRunId>,
159    /// Producer lifecycles survive output filtering and the optional verifier.
160    active_subagents: BTreeSet<SubagentRunId>,
161    event_buffer_capacity: Option<NonZeroUsize>,
162    overflowed: bool,
163}
164
165impl std::fmt::Debug for EventSink {
166    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
167        f.debug_struct("EventSink")
168            .field("transformers", &self.chain.len())
169            .field("cancelled", &self.cancel.is_cancelled())
170            .field("attribution", &self.attribution)
171            .finish()
172    }
173}
174
175impl EventSink {
176    pub(crate) fn new(
177        tx: UnboundedSender<Event>,
178        chain: TransformerChain,
179        cancel: CancellationToken,
180    ) -> Self {
181        Self {
182            tx,
183            chain,
184            verifier: Verifier::new(),
185            cancel,
186            terminated: false,
187            attribution: None,
188            active_subagents: BTreeSet::new(),
189            event_buffer_capacity: None,
190            overflowed: false,
191        }
192    }
193
194    pub(crate) fn with_event_buffer_capacity(mut self, capacity: Option<NonZeroUsize>) -> Self {
195        self.event_buffer_capacity = capacity;
196        self
197    }
198
199    /// Emits one event, unless the run was cancelled.
200    ///
201    /// Failing every emit after cancellation is what makes cancellation work
202    /// without any cooperation from the agent: the next `?` unwinds the run.
203    pub(crate) fn emit(&mut self, event: Event) -> Result<()> {
204        if self.cancel.is_cancelled() {
205            return Err(Error::Cancelled);
206        }
207        self.emit_forced(event)
208    }
209
210    /// Emits one event even after cancellation — used by the run driver for
211    /// `RUN_FINISHED` and `RUN_ERROR`, which must go out regardless.
212    pub(crate) fn emit_forced(&mut self, mut event: Event) -> Result<()> {
213        if self.overflowed {
214            return Err(Error::EventBufferFull {
215                capacity: self
216                    .event_buffer_capacity
217                    .expect("overflow requires a limit")
218                    .get(),
219            });
220        }
221        if matches!(event, Event::RunFinished(_)) {
222            if let Some(id) = self.active_subagents.first() {
223                return Err(VerificationError::new(
224                    event.event_type(),
225                    Rule::OpenAtFinish,
226                    format!("subagent '{id}' requires an explicit finish, fail or suspend"),
227                )
228                .into());
229            }
230        }
231        let lifecycle = match &event {
232            Event::SubagentStarted(started) => Some((started.subagent_run_id.clone(), true)),
233            Event::SubagentFinished(finished) => Some((finished.subagent_run_id.clone(), false)),
234            Event::SubagentError(error) => Some((error.subagent_run_id.clone(), false)),
235            _ => None,
236        };
237        // Attribution is applied before the transformers, so a transformer
238        // sees the same tagged stream a consumer would. An event the agent
239        // tagged itself keeps its tag: that is how a hand-interleaved
240        // concurrent stream is written.
241        if let Some(id) = &self.attribution {
242            if event.event_type().is_attributable() && event.subagent_run_id().is_none() {
243                event.set_subagent_run_id(id.clone());
244            }
245        }
246        if self.chain.is_empty() {
247            self.send(event)?;
248        } else {
249            for event in self.chain.transform(event) {
250                self.send(event)?;
251            }
252        }
253        if let Some((id, opened)) = lifecycle {
254            if opened {
255                self.active_subagents.insert(id);
256            } else {
257                self.active_subagents.remove(&id);
258            }
259        }
260        Ok(())
261    }
262
263    /// The subagent scope in force, if any.
264    pub(crate) fn attribution(&self) -> Option<&SubagentRunId> {
265        self.attribution.as_ref()
266    }
267
268    /// Replaces the subagent scope and returns the previous one, so a nested
269    /// scope can restore it on close.
270    pub(crate) fn set_attribution(
271        &mut self,
272        attribution: Option<SubagentRunId>,
273    ) -> Option<SubagentRunId> {
274        std::mem::replace(&mut self.attribution, attribution)
275    }
276
277    fn send(&mut self, event: Event) -> Result<()> {
278        if self.tx.is_closed() {
279            return Err(Error::Disconnected);
280        }
281        if let Some(capacity) = self.event_buffer_capacity {
282            if self.tx.len() >= capacity.get() {
283                let error = Error::EventBufferFull {
284                    capacity: capacity.get(),
285                };
286                let terminal =
287                    Event::from(RunErrorEvent::new(error.to_string()).with_code(error.code()));
288                self.verifier.observe(&terminal)?;
289                self.tx
290                    .unbounded_send(terminal)
291                    .map_err(|_| Error::Disconnected)?;
292                self.terminated = true;
293                self.overflowed = true;
294                self.tx.close_channel();
295                return Err(error);
296            }
297        }
298        self.verifier.observe(&event)?;
299        self.terminated |= matches!(event, Event::RunFinished(_) | Event::RunError(_));
300        self.tx
301            .unbounded_send(event)
302            .map_err(|_| Error::Disconnected)
303    }
304
305    /// Whether a terminal event has already gone out.
306    pub(crate) fn is_terminated(&self) -> bool {
307        self.terminated
308    }
309
310    pub(crate) fn cancel_token(&self) -> &CancellationToken {
311        &self.cancel
312    }
313}
314
315/// The read end of a run's event stream.
316///
317/// Yielded by [`RunContext::new`](crate::server::RunContext::new) for agents under
318/// test. Transports get a [`Stream`] from
319/// [`Runner::run`](crate::server::Runner::run) instead.
320#[derive(Debug)]
321pub struct EventReceiver {
322    rx: UnboundedReceiver<Event>,
323}
324
325impl EventReceiver {
326    pub(crate) fn new(rx: UnboundedReceiver<Event>) -> Self {
327        Self { rx }
328    }
329
330    /// Takes every event emitted so far without waiting.
331    ///
332    /// The emit path is synchronous, so after calling an agent's code
333    /// everything it emitted is already queued. That makes this the whole
334    /// assertion story for a unit test:
335    ///
336    /// ```
337    /// # use ag_ui::{Event, RunAgentInput, TextMessageRole};
338    /// # use ag_ui::server::RunContext;
339    /// let (mut ctx, mut events) = RunContext::<()>::new(RunAgentInput::new("t", "r"))?;
340    /// ctx.say("hello")?;
341    /// assert_eq!(events.drain(), vec![
342    ///     Event::text_message_start("r-msg-1", TextMessageRole::Assistant),
343    ///     Event::text_message_content("r-msg-1", "hello"),
344    ///     Event::text_message_end("r-msg-1"),
345    /// ]);
346    /// # Ok::<(), ag_ui::server::Error>(())
347    /// ```
348    pub fn drain(&mut self) -> Vec<Event> {
349        let mut events = Vec::new();
350        while let Ok(event) = self.rx.try_recv() {
351            events.push(event);
352        }
353        events
354    }
355
356    /// Closes the channel, so the next emit fails with
357    /// [`Error::Disconnected`].
358    ///
359    /// [`Error::Disconnected`]: crate::server::Error::Disconnected
360    pub fn close(&mut self) {
361        self.rx.close();
362    }
363}
364
365impl Stream for EventReceiver {
366    type Item = Event;
367
368    fn poll_next(
369        mut self: std::pin::Pin<&mut Self>,
370        cx: &mut std::task::Context<'_>,
371    ) -> std::task::Poll<Option<Event>> {
372        self.rx.poll_next_unpin(cx)
373    }
374}