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. That includes the `?` a cancelled run unwinds through: a
16//! terminator still goes out after cancellation, when nothing else does.
17//!
18//! ```compile_fail,E0499
19//! use ag_ui::server::RunContext;
20//!
21//! fn interleave(ctx: &mut RunContext<()>) {
22//! let mut first = ctx.assistant_message().unwrap();
23//! // error[E0499]: cannot borrow `*ctx` as mutable more than once at a time
24//! let mut second = ctx.assistant_message().unwrap();
25//! first.delta("a").unwrap();
26//! second.delta("b").unwrap();
27//! }
28//! ```
29//!
30//! # Why the emit path is synchronous
31//!
32//! `Drop` cannot be async, so a handle cannot `await` while emitting its
33//! terminator. `msg.delta(text)?` therefore does not take `.await`: emitters
34//! push into a channel and the transport drains it. A configured
35//! [`Runner::event_buffer_capacity`](crate::server::Runner::event_buffer_capacity)
36//! rejects overflow with a terminal error instead of waiting. An earlier draft
37//! copied `await`-ing emitters from the TypeScript and .NET SDKs; it cannot
38//! coexist with the `Drop` guarantee.
39//!
40//! # The escape hatch
41//!
42//! [`StepGuard`] dereferences to the run context — a step is a scope, and
43//! everything else nests inside it. The three streaming handles deliberately do
44//! not, because that is exactly what would let a second message open inside the
45//! first. They expose [`emit`](MessageHandle::emit) instead, for the unordered
46//! events (state, activity, custom) that may legally interleave with a message.
47//!
48//! # What an open handle can still reach
49//!
50//! A handle borrows two *fields* of the run context — the event sink and the
51//! state — rather than the context itself. So the state is reachable through
52//! the handle ([`state`](ToolCallHandle::state),
53//! [`state_mut`](ToolCallHandle::state_mut),
54//! [`publish_state`](ToolCallHandle::publish_state)) and a tool call can do its
55//! work between its arguments and its result: `STATE_*` is unordered, so a
56//! publish inside the brackets is a legal stream.
57//!
58//! Widening reach, not weakening the rule. The context stays exclusively
59//! borrowed for as long as the handle lives, so a second block is still a
60//! borrow-check error — including from inside an open call:
61//!
62//! ```compile_fail,E0499
63//! use ag_ui::server::RunContext;
64//!
65//! fn narrate(ctx: &mut RunContext<()>) {
66//! let mut call = ctx.tool_call("search").unwrap();
67//! // error[E0499]: cannot borrow `*ctx` as mutable more than once at a time
68//! let mut message = ctx.assistant_message().unwrap();
69//! call.args("{}").unwrap();
70//! }
71//! ```
72//!
73//! # What has no handle, and why that is the answer
74//!
75//! Two things an agent may legitimately put on the wire are
76//! [`RunContext::emit`](crate::server::RunContext::emit) territory, and the escape
77//! hatch is the supported path for both rather than a gap waiting for an API.
78//!
79//! The `*_CHUNK` family is unbracketed by definition: a chunk carries its own
80//! id and needs no start and no end, which is the point — it exists for
81//! provider adapters that cannot know a message ended until the next one
82//! begins. There is nothing for an RAII handle to close, and wrapping one
83//! around a self-contained event would only add a way to get it wrong.
84//!
85//! Interleaved parallel tool calls are the other. Two open [`ToolCallHandle`]s
86//! at once is a borrow-check error *by design*, so a provider streaming
87//! `args(a) args(b) args(a) end(a) end(b)` cannot be mirrored handle-for-call.
88//! Either accumulate each call and emit it whole once its arguments are
89//! complete — the only mapping that cannot
90//! splice two calls' arguments into each other — or emit the interleaving
91//! yourself. The verifier keys everything by id, so it accepts the interleaved
92//! stream; what it will not let you do is close a call you never opened.
93//!
94//! # Subagents
95//!
96//! [`SubagentHandle`] is a scope in the sense [`StepGuard`] is: it dereferences
97//! to the run context, and everything opened through it — messages, tool
98//! calls, reasoning, steps, nested subagents — comes out carrying its
99//! `subagentRunId`. The attribution lives in the event sink rather than in
100//! the handles, which is why a [`MessageHandle`] opened inside a subagent
101//! needs no idea that it was: the sink tags every attributable event that
102//! arrives untagged while a scope is open, and leaves an event the agent
103//! tagged explicitly alone.
104//!
105//! That last clause is the concurrent case. Subagents that stream at once are
106//! the parallel-tool-call situation again: two open handles is a borrow-check
107//! error by design, so build each subagent's events with
108//! [`Event::with_subagent_run_id`] and [`emit`](crate::server::RunContext::emit)
109//! them interleaved, bracketed by [`Event::subagent_started`] and
110//! [`Event::subagent_finished_success`]. The verifier keys every entity by id
111//! and remembers who opened it, so the interleaving is accepted; what it will
112//! not let you do is continue one subagent's message under another's tag.
113//! Attribute every chunk when several subagents stream at once — a chunk
114//! that names neither a message nor a subagent can only be resolved when one
115//! stream is open.
116
117/// The run's state as an open handle reaches it: `state`, `state_mut` and
118/// `publish_state`, the same on [`MessageHandle`], [`ReasoningHandle`] and
119/// [`ToolCallHandle`], written once.
120///
121/// Each handle holds the event sink and the state as two fields, so these
122/// reach nothing the handle does not already hold. The handle's own words
123/// come first, as the doc of the `impl` block, then where its publish lands.
124macro_rules! state_access {
125 ($(#[$about:meta])* $handle:ident, published $place:literal) => {
126 $(#[$about])*
127 impl<S: $crate::server::agent::AgentState> $handle<'_, S> {
128 /// The typed state, as of the last publish.
129 pub fn state(&self) -> &S {
130 self.state.get()
131 }
132
133 /// The typed state, mutably. Nothing is emitted until you call
134 /// [`publish_state`](Self::publish_state).
135 pub fn state_mut(&mut self) -> &mut S {
136 self.state.get_mut()
137 }
138
139 /// Publishes whatever [`state_mut`](Self::state_mut) left behind, as a
140 /// `STATE_SNAPSHOT` or a `STATE_DELTA`
141 #[doc = concat!($place, ".")]
142 ///
143 /// A no-op when nothing changed since the last publish.
144 pub fn publish_state(&mut self) -> $crate::server::error::Result<()> {
145 self.state.publish(self.sink)
146 }
147 }
148 };
149}
150
151mod message;
152mod reasoning;
153mod step;
154mod subagent;
155mod tool;
156
157use std::num::NonZeroUsize;
158
159use crate::{
160 Event, Message, MessageId, RunErrorEvent, RunId, StepName, SubagentErrorEvent, SubagentRunId,
161 ToolCallId,
162};
163use futures_channel::mpsc::{UnboundedReceiver, UnboundedSender};
164use futures_core::Stream;
165use futures_util::StreamExt as _;
166
167use crate::server::cancel::CancellationToken;
168use crate::server::context::Minted;
169use crate::server::error::{Error, Result, Rule, VerificationError};
170use crate::server::state::StateManager;
171use crate::server::transform::{StreamTransformer, TransformerChain};
172use crate::server::verify::Verifier;
173
174pub use message::MessageHandle;
175pub use reasoning::ReasoningHandle;
176pub use step::StepGuard;
177pub use subagent::SubagentHandle;
178pub use tool::ToolCallHandle;
179
180/// The write end of a run's event stream: transformers, then verification,
181/// then the channel.
182///
183/// Not public: the only way to reach one is through a
184/// [`RunContext`](crate::server::RunContext) or a handle, which is what keeps the
185/// ordering guarantees intact.
186pub(crate) struct EventSink {
187 pub(super) minted: Minted,
188 tx: UnboundedSender<Event>,
189 chain: TransformerChain,
190 verifier: Verifier,
191 /// The state actually queued after all transformers, not the state the
192 /// producer tried to publish before a transformer rewrote it.
193 state_manager: StateManager,
194 cancel: CancellationToken,
195 /// Whether a terminal event has gone out. Tracked here as well as in the
196 /// verifier so that turning the `verify` feature off cannot put anything
197 /// on the wire after it — a second `RUN_FINISHED` included.
198 terminated: bool,
199 /// The subagent scope in force: every attributable event emitted untagged
200 /// while it is set goes out carrying it. See [`SubagentHandle`].
201 attribution: Option<SubagentRunId>,
202 /// What is open with no handle of this driver to close it, in the order
203 /// it was opened, so a cancelled run closes the innermost first. Kept
204 /// here and not read off the verifier: it has to hold with the `verify`
205 /// feature off, and a subagent's lifecycle has to survive a transformer
206 /// that drops it from the output.
207 unclosed: Vec<Unclosed>,
208 event_buffer_capacity: Option<NonZeroUsize>,
209 overflowed: bool,
210}
211
212impl std::fmt::Debug for EventSink {
213 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
214 f.debug_struct("EventSink")
215 .field("transformers", &self.chain.len())
216 .field("cancelled", &self.cancel.is_cancelled())
217 .field("attribution", &self.attribution)
218 .finish()
219 }
220}
221
222impl EventSink {
223 pub(crate) fn new(
224 run_id: RunId,
225 tx: UnboundedSender<Event>,
226 chain: TransformerChain,
227 cancel: CancellationToken,
228 ) -> Self {
229 Self {
230 minted: Minted::new(run_id),
231 tx,
232 chain,
233 verifier: Verifier::new(),
234 state_manager: StateManager::new(),
235 cancel,
236 terminated: false,
237 attribution: None,
238 unclosed: Vec::new(),
239 event_buffer_capacity: None,
240 overflowed: false,
241 }
242 }
243
244 pub(crate) fn with_event_buffer_capacity(mut self, capacity: Option<NonZeroUsize>) -> Self {
245 self.event_buffer_capacity = capacity;
246 self
247 }
248
249 /// Tells the verifier and the transformers the conversation the run
250 /// continues — the request's `messages` — before its first event.
251 ///
252 /// History the consumer already holds is not streamed again, and the
253 /// `RUN_STARTED` echo that could carry it is optional. Without this a
254 /// resumed run answering a call the interrupted run opened would read as
255 /// a result for a call that never started.
256 pub(crate) fn seed(&mut self, history: &[Message]) {
257 self.minted.note_history(history);
258 self.verifier.seed(history);
259 StreamTransformer::seed(&mut self.chain, history);
260 }
261
262 /// For a sink with no run driver behind it, which would have emitted
263 /// `RUN_STARTED`: lets the verifier take the agent's first event.
264 pub(crate) fn assume_run_started(&mut self) {
265 self.verifier.assume_opened();
266 }
267
268 /// Shows the transformers the events a run has already sent, for a sink
269 /// that continues the run. They are the output of an earlier chain, not
270 /// events to transform: see [`StreamTransformer::replay`].
271 pub(crate) fn show_sent(&mut self, sent: &[Event]) {
272 StreamTransformer::replay(&mut self.chain, sent);
273 }
274
275 /// Records an event that was already sent, without sending it again:
276 /// for a sink that continues a run. The event is one an earlier driver
277 /// of the run sent, or one of a run before it on the same stream.
278 ///
279 /// Everything [`send`](Self::send) remembers about an event it queues is
280 /// remembered here: the verifier's ordering state, the state the client
281 /// holds, whether the run ended. What the earlier driver left open is
282 /// read off the same events, which is what a consumer saw: the subagents
283 /// that are active, and every message, tool call, reasoning block,
284 /// reasoning message and step that has a start and no end. An entity a
285 /// `*_CHUNK` event opened is not among them. It has no end event, and
286 /// the run's terminal event ends its chunk stream.
287 ///
288 /// The transformers are not fed the event. What was sent is their
289 /// output, which [`show_sent`](Self::show_sent) lets them learn from.
290 pub(crate) fn replay(&mut self, event: &Event) -> Result<()> {
291 let next_state = self.state_after(event)?;
292 self.verifier.observe(event)?;
293 self.minted.note(event);
294 self.terminated |= matches!(event, Event::RunFinished(_) | Event::RunError(_));
295 if let Some(state) = next_state {
296 self.state_manager.set_published(state);
297 }
298 match event {
299 // What was sent may hold the runs that came before the one being
300 // continued. Each starts with nothing open; the state a client
301 // holds carries over.
302 Event::RunStarted(_) => {
303 self.terminated = false;
304 self.unclosed.clear();
305 }
306 Event::SubagentStarted(started) => self.open_subagent(&started.subagent_run_id),
307 Event::SubagentFinished(finished) => self.close_subagent(&finished.subagent_run_id),
308 Event::SubagentError(error) => self.close_subagent(&error.subagent_run_id),
309 _ => match Unclosed::opened_by(event) {
310 Some(opened) => self.unclosed.push(opened),
311 None => self.unclosed.retain(|open| !open.closed_by(event)),
312 },
313 }
314 Ok(())
315 }
316
317 fn open_subagent(&mut self, id: &SubagentRunId) {
318 let active = Unclosed::Subagent(id.clone());
319 if !self.unclosed.contains(&active) {
320 self.unclosed.push(active);
321 }
322 }
323
324 fn close_subagent(&mut self, id: &SubagentRunId) {
325 self.unclosed
326 .retain(|open| !matches!(open, Unclosed::Subagent(active) if active == id));
327 }
328
329 /// The state a consumer holds once it has applied `event`: `None` for an
330 /// event that leaves it alone, `Some(None)` for one that leaves it
331 /// unknown.
332 fn state_after(&self, event: &Event) -> Result<Option<Option<serde_json::Value>>> {
333 Ok(match event {
334 Event::StateSnapshot(snapshot) => Some(Some(snapshot.snapshot.clone())),
335 Event::StateDelta(delta) => Some(self.state_manager.after_delta(&delta.delta)?),
336 _ => None,
337 })
338 }
339
340 /// Emits one event, unless the run was cancelled.
341 ///
342 /// Failing every emit after cancellation is what makes cancellation work
343 /// without any cooperation from the agent: the next `?` unwinds the run.
344 /// Terminators go through [`emit_forced`](Self::emit_forced) instead, so
345 /// the unwinding still closes everything the run had open.
346 pub(crate) fn emit(&mut self, event: Event) -> Result<()> {
347 if self.cancel.is_cancelled() {
348 return Err(Error::Cancelled);
349 }
350 self.emit_forced(event)
351 }
352
353 /// Publishes a typed state relative to the events the client will see.
354 /// A transformer may drop, insert, or rewrite state events, so the sink's
355 /// own send path is the only place that advances this baseline.
356 pub(crate) fn publish_state(&mut self, next: serde_json::Value) -> Result<()> {
357 match self.state_manager.decide(&next)?.into_event() {
358 Some(event) => self.emit(event),
359 None => Ok(()),
360 }
361 }
362
363 /// Emits one event even after cancellation — used for terminators: the
364 /// run driver's `RUN_FINISHED` and `RUN_ERROR`, and the event each handle
365 /// closes with. AG-UI 1.0 requires a cancelled run to close what it opened
366 /// before the `RUN_FINISHED` that cancels it, so these must go out
367 /// regardless.
368 pub(crate) fn emit_forced(&mut self, mut event: Event) -> Result<()> {
369 if self.overflowed {
370 return Err(Error::EventBufferFull {
371 capacity: self
372 .event_buffer_capacity
373 .expect("overflow requires a limit")
374 .get(),
375 });
376 }
377 let lifecycle = match &event {
378 Event::SubagentStarted(started) => Some((started.subagent_run_id.clone(), true)),
379 Event::SubagentFinished(finished) => Some((finished.subagent_run_id.clone(), false)),
380 Event::SubagentError(error) => Some((error.subagent_run_id.clone(), false)),
381 _ => None,
382 };
383 // Attribution is applied before the transformers, so a transformer
384 // sees the same tagged stream a consumer would. An event the agent
385 // tagged itself keeps its tag: that is how a hand-interleaved
386 // concurrent stream is written.
387 if let Some(id) = &self.attribution {
388 if event.event_type().is_attributable() && event.subagent_run_id().is_none() {
389 event.set_subagent_run_id(id.clone());
390 }
391 }
392 if self.chain.is_empty() {
393 self.send(event)?;
394 } else {
395 // A caller-selected ID stays reserved even when a transformer renames it.
396 self.minted.note(&event);
397 for event in self.chain.transform(event) {
398 self.send(event)?;
399 }
400 }
401 if let Some((id, opened)) = lifecycle {
402 if opened {
403 self.open_subagent(&id);
404 } else {
405 self.close_subagent(&id);
406 }
407 }
408 Ok(())
409 }
410
411 /// Closes what is open with no handle to close it, innermost first: a
412 /// subagent with `SUBAGENT_ERROR` naming `error`, and what an earlier
413 /// driver of the run left open with its end event, under the subagent
414 /// that opened it.
415 ///
416 /// For the run driver when a run is cancelled. A dropped
417 /// [`SubagentHandle`] does not invent an ending, and the schema has no
418 /// cancelled outcome for a subagent; an error carrying the cancellation's
419 /// code is the one ending that neither claims success nor claims the
420 /// invocation is waiting. An entity inherited from an earlier driver has
421 /// no handle here at all, and the agent's own end event for it fails
422 /// once the run is cancelled, like any other emit.
423 ///
424 /// Stops at the first event that cannot be sent: whatever is left open
425 /// then makes `RUN_FINISHED` fail, and the driver reports that instead.
426 pub(crate) fn close_unclosed(&mut self, error: &Error) {
427 for open in self.unclosed.clone().into_iter().rev() {
428 if self.emit_forced(open.closing(error)).is_err() {
429 return;
430 }
431 }
432 }
433
434 /// The subagent scope in force, if any.
435 pub(crate) fn attribution(&self) -> Option<&SubagentRunId> {
436 self.attribution.as_ref()
437 }
438
439 /// Replaces the subagent scope and returns the previous one, so a nested
440 /// scope can restore it on close.
441 pub(crate) fn set_attribution(
442 &mut self,
443 attribution: Option<SubagentRunId>,
444 ) -> Option<SubagentRunId> {
445 std::mem::replace(&mut self.attribution, attribution)
446 }
447
448 /// Queues a post-transformation event. The driver also uses this for its
449 /// last-resort error if a transformer suppressed the terminal event.
450 pub(super) fn send(&mut self, event: Event) -> Result<()> {
451 if self.tx.is_closed() {
452 return Err(Error::Disconnected);
453 }
454 // The verifier says the same when it is compiled in. This check is
455 // here so that leaving it out cannot put events past the end of a run
456 // on the wire.
457 if self.terminated {
458 return Err(VerificationError::new(
459 event.event_type(),
460 Rule::RunEnded,
461 "the run already ended",
462 )
463 .into());
464 }
465 if let Event::RunFinished(finished) = &event {
466 if let Some(open) = self.unclosed.first() {
467 return Err(VerificationError::new(
468 event.event_type(),
469 Rule::OpenAtFinish,
470 open.still_open(),
471 )
472 .into());
473 }
474 // The ordering verifier also checks outcomes, but a hosting
475 // transport must emit a valid terminal with that feature off.
476 if let Some(reason) = finished
477 .outcome
478 .as_ref()
479 .and_then(crate::RunOutcome::interrupt_error)
480 {
481 return Err(VerificationError::new(
482 event.event_type(),
483 Rule::InvalidOutcome,
484 reason,
485 )
486 .into());
487 }
488 }
489 if event.event_type().as_str().starts_with("THINKING_") {
490 return Err(crate::Error::Protocol(
491 "THINKING_* events are retired in AG-UI 1.0; emit REASONING_* events".into(),
492 )
493 .into());
494 }
495 if let Some(capacity) = self.event_buffer_capacity {
496 if self.tx.len() >= capacity.get() {
497 let error = Error::EventBufferFull {
498 capacity: capacity.get(),
499 };
500 let terminal =
501 Event::from(RunErrorEvent::new(error.to_string()).with_code(error.code()));
502 self.verifier.observe(&terminal)?;
503 self.tx
504 .unbounded_send(terminal)
505 .map_err(|_| Error::Disconnected)?;
506 self.terminated = true;
507 self.overflowed = true;
508 self.tx.close_channel();
509 return Err(error);
510 }
511 }
512 let next_state = self.state_after(&event)?;
513 self.verifier.observe(&event)?;
514 self.minted.note(&event);
515 self.terminated |= matches!(event, Event::RunFinished(_) | Event::RunError(_));
516 // What an earlier driver left open is closed by whoever sends its
517 // end: the agent, naming its id, or the driver for a cancelled run.
518 if !self.unclosed.is_empty() {
519 self.unclosed.retain(|open| !open.closed_by(&event));
520 }
521 self.tx
522 .unbounded_send(event)
523 .map_err(|_| Error::Disconnected)?;
524 if let Some(state) = next_state {
525 self.state_manager.set_published(state);
526 }
527 Ok(())
528 }
529
530 /// Whether a terminal event has already gone out.
531 pub(crate) fn is_terminated(&self) -> bool {
532 self.terminated
533 }
534
535 pub(crate) fn cancel_token(&self) -> &CancellationToken {
536 &self.cancel
537 }
538}
539
540/// Something a run has open that no handle of its driver will close.
541///
542/// A subagent that is active: a dropped [`SubagentHandle`] invents no ending
543/// for it. And, in a sink that continues a run, what the earlier driver left
544/// open, each with the subagent that opened it: the handle that would have
545/// closed it went with that driver.
546#[derive(Clone, Debug, PartialEq, Eq)]
547enum Unclosed {
548 Subagent(SubagentRunId),
549 Message(MessageId, Option<SubagentRunId>),
550 ToolCall(ToolCallId, Option<SubagentRunId>),
551 ReasoningMessage(MessageId, Option<SubagentRunId>),
552 ReasoningBlock(MessageId, Option<SubagentRunId>),
553 Step(StepName, Option<SubagentRunId>),
554}
555
556impl Unclosed {
557 /// What an event that was already sent opened, when it is something an
558 /// end event closes. A subagent is not: its lifecycle is followed apart.
559 fn opened_by(event: &Event) -> Option<Self> {
560 Some(match event {
561 Event::TextMessageStart(e) => {
562 Self::Message(e.message_id.clone(), e.subagent_run_id.clone())
563 }
564 Event::ToolCallStart(e) => {
565 Self::ToolCall(e.tool_call_id.clone(), e.subagent_run_id.clone())
566 }
567 Event::ReasoningMessageStart(e) => {
568 Self::ReasoningMessage(e.message_id.clone(), e.subagent_run_id.clone())
569 }
570 Event::ReasoningStart(e) => {
571 Self::ReasoningBlock(e.message_id.clone(), e.subagent_run_id.clone())
572 }
573 Event::StepStarted(e) => Self::Step(e.step_name.clone(), e.subagent_run_id.clone()),
574 _ => return None,
575 })
576 }
577
578 /// Whether `event` is the end event of this.
579 fn closed_by(&self, event: &Event) -> bool {
580 match (self, event) {
581 (Self::Message(id, _), Event::TextMessageEnd(e)) => id == &e.message_id,
582 (Self::ToolCall(id, _), Event::ToolCallEnd(e)) => id == &e.tool_call_id,
583 (Self::ReasoningMessage(id, _), Event::ReasoningMessageEnd(e)) => id == &e.message_id,
584 (Self::ReasoningBlock(id, _), Event::ReasoningEnd(e)) => id == &e.message_id,
585 // A step is its owner's: a subagent and its parent may each run
586 // one of the same name.
587 (Self::Step(name, owner), Event::StepFinished(e)) => {
588 name == &e.step_name && owner == &e.subagent_run_id
589 }
590 _ => false,
591 }
592 }
593
594 /// The event that closes it in a run that stops because of `error`.
595 fn closing(&self, error: &Error) -> Event {
596 let (mut end, owner) = match self {
597 Self::Subagent(id) => {
598 let stopped = SubagentErrorEvent::new(id.clone(), error.to_string());
599 return stopped.with_code(error.code()).into();
600 }
601 Self::Message(id, owner) => (Event::text_message_end(id.clone()), owner),
602 Self::ToolCall(id, owner) => (Event::tool_call_end(id.clone()), owner),
603 Self::ReasoningMessage(id, owner) => (Event::reasoning_message_end(id.clone()), owner),
604 Self::ReasoningBlock(id, owner) => (Event::reasoning_end(id.clone()), owner),
605 Self::Step(name, owner) => (Event::step_finished(name.clone()), owner),
606 };
607 if let Some(owner) = owner {
608 end.set_subagent_run_id(owner.clone());
609 }
610 end
611 }
612
613 /// What a `RUN_FINISHED` that is refused because of it says.
614 fn still_open(&self) -> String {
615 match self {
616 Self::Subagent(id) => {
617 format!("subagent '{id}' requires an explicit finish, fail or suspend")
618 }
619 Self::Message(id, _) => format!("message {:?} is still open", id.as_str()),
620 Self::ToolCall(id, _) => format!("tool call {:?} is still open", id.as_str()),
621 Self::ReasoningMessage(id, _) => {
622 format!("reasoning message {:?} is still open", id.as_str())
623 }
624 Self::ReasoningBlock(id, _) => {
625 format!("reasoning block {:?} is still open", id.as_str())
626 }
627 Self::Step(name, None) => format!("step {:?} is still open", name.as_str()),
628 Self::Step(name, Some(owner)) => format!(
629 "step {:?} is still open under subagent {:?}",
630 name.as_str(),
631 owner.as_str()
632 ),
633 }
634 }
635}
636
637/// The read end of a run's event stream.
638///
639/// Yielded by [`RunContext::new`](crate::server::RunContext::new) for agents under
640/// test, and by [`Runner::into_parts`](crate::server::Runner::into_parts) and
641/// [`Runner::continue_run`](crate::server::Runner::continue_run) for a run
642/// that is driven apart from whoever reads it. Transports that answer one
643/// request get a [`Stream`] from [`Runner::run`](crate::server::Runner::run)
644/// instead.
645///
646/// It is a [`Stream`] of the run's events, and it ends when the driver has
647/// finished or dropped, or when a bounded queue overflowed.
648#[derive(Debug)]
649pub struct EventReceiver {
650 rx: UnboundedReceiver<Event>,
651}
652
653impl EventReceiver {
654 pub(crate) fn new(rx: UnboundedReceiver<Event>) -> Self {
655 Self { rx }
656 }
657
658 /// Takes every event emitted so far without waiting.
659 ///
660 /// The emit path is synchronous, so after calling an agent's code
661 /// everything it emitted is already queued. That makes this the whole
662 /// assertion story for a unit test:
663 ///
664 /// ```
665 /// # use ag_ui::{Event, RunAgentInput, TextMessageRole};
666 /// # use ag_ui::server::RunContext;
667 /// let (mut ctx, mut events) = RunContext::<()>::new(RunAgentInput::new("t", "r"))?;
668 /// ctx.say("hello")?;
669 /// assert_eq!(events.drain(), vec![
670 /// Event::text_message_start("r-msg-1", TextMessageRole::Assistant),
671 /// Event::text_message_content("r-msg-1", "hello"),
672 /// Event::text_message_end("r-msg-1"),
673 /// ]);
674 /// # Ok::<(), ag_ui::server::Error>(())
675 /// ```
676 pub fn drain(&mut self) -> Vec<Event> {
677 let mut events = Vec::new();
678 while let Ok(event) = self.rx.try_recv() {
679 events.push(event);
680 }
681 events
682 }
683
684 /// Closes the channel, so the next emit fails with
685 /// [`Error::Disconnected`].
686 ///
687 /// Unlike dropping the receiver, this keeps what was already emitted: a
688 /// consumer that stops accepting events can still read the ones queued.
689 ///
690 /// ```
691 /// # use ag_ui::RunAgentInput;
692 /// # use ag_ui::server::RunContext;
693 /// let (mut ctx, mut events) = RunContext::<()>::new(RunAgentInput::new("t", "r"))?;
694 /// ctx.say("before")?;
695 ///
696 /// events.close();
697 /// assert!(ctx.say("after").is_err_and(|error| error.is_disconnected()));
698 /// assert_eq!(events.drain().len(), 3);
699 /// # Ok::<(), ag_ui::server::Error>(())
700 /// ```
701 ///
702 /// [`Error::Disconnected`]: crate::server::Error::Disconnected
703 pub fn close(&mut self) {
704 self.rx.close();
705 }
706}
707
708impl Stream for EventReceiver {
709 type Item = Event;
710
711 fn poll_next(
712 mut self: std::pin::Pin<&mut Self>,
713 cx: &mut std::task::Context<'_>,
714 ) -> std::task::Poll<Option<Event>> {
715 self.rx.poll_next_unpin(cx)
716 }
717}