Skip to main content

ag_ui/server/
run.rs

1//! The driver: an [`Agent`] plus a [`RunAgentInput`] in, a [`Stream`] of
2//! events out.
3//!
4//! The stream owns the agent's future and polls it itself, so this crate needs
5//! no executor of its own — no `tokio::spawn`, nothing to configure, and the
6//! same code runs on wasm. Draining the stream *is* running the agent.
7//!
8//! ```
9//! # use ag_ui::{Event, RunAgentInput, RunOutcome};
10//! # use ag_ui::server::{Agent, Result, RunContext, run};
11//! # use futures_util::StreamExt;
12//! struct Greeter;
13//!
14//! impl Agent for Greeter {
15//!     type State = ();
16//!     async fn run(&self, ctx: &mut RunContext<()>) -> Result<RunOutcome> {
17//!         ctx.say("hello")?;
18//!         Ok(RunOutcome::Success)
19//!     }
20//! }
21//!
22//! # let rt = tokio::runtime::Builder::new_current_thread().build().unwrap();
23//! # rt.block_on(async {
24//! let events: Vec<Event> = run(Greeter, RunAgentInput::new("thread-1", "run-1"))
25//!     .collect()
26//!     .await;
27//!
28//! assert_eq!(events.first().map(Event::event_type), Some(ag_ui::EventType::RunStarted));
29//! assert_eq!(events.last().map(Event::event_type), Some(ag_ui::EventType::RunFinished));
30//! # });
31//! ```
32//!
33//! # A run that outlives its response
34//!
35//! Draining the stream is running the agent, so the agent stops where it is
36//! when the stream is dropped, and one stream has one reader. A request and
37//! its response need no more. A server whose runs go on after the client
38//! that started them has gone does: a second client on the same thread, a
39//! client that joins a run in progress, a run that another process carries
40//! on.
41//!
42//! Such a server stores the events and fans them out itself. Admission,
43//! storage and recovery are its own. What it takes from here:
44//!
45//! - [`Runner::into_parts`] hands out the future that drives the agent and
46//!   the receiver of what it emits. The driver goes on an executor the
47//!   server chooses, and the events go to its store.
48//! - [`Runner::continue_run`] drives a run that another driver began, from
49//!   the events already sent: no second `RUN_STARTED`, and ordering checks
50//!   that start where the run is. A server that builds its events by hand
51//!   does the same with `EventVerifier::replay`, in [`verify`].
52//! - [`RunProgress`] folds the events of a run so far into what the run has
53//!   open, and builds the prelude a client that joins it is sent first. A
54//!   client's stream has to begin with `RUN_STARTED`, so the prelude does,
55//!   and it stands for the events already sent: a client is sent one or the
56//!   other, never both.
57//!
58//! None of these spawns anything. The crate still has no executor of its
59//! own.
60//!
61//! [`verify`]: crate::server::verify
62//! [`RunProgress`]: crate::server::RunProgress
63
64use std::future::Future;
65use std::num::NonZeroUsize;
66use std::pin::Pin;
67use std::task::{Context, Poll};
68
69use crate::{
70    Event, EventType, RunAgentInput, RunErrorEvent, RunFinishedEvent, RunId, RunOutcome,
71    RunStartedEvent, ThreadId, TokenUsage,
72};
73use futures_channel::mpsc;
74use futures_core::Stream;
75use futures_util::StreamExt as _;
76
77use crate::server::agent::Agent;
78use crate::server::cancel::CancellationToken;
79use crate::server::context::{RunContext, Terminal, decode_state};
80use crate::server::emit::{EventReceiver, EventSink};
81use crate::server::error::{Error, Result, Rule, VerificationError};
82use crate::server::transform::{StreamTransformer, TransformerChain};
83
84/// Runs `agent` against `input` with no transformers and a fresh cancellation
85/// token.
86///
87/// [`Runner`] is the same thing with knobs.
88pub fn run<A: Agent>(agent: A, input: RunAgentInput) -> impl Stream<Item = Event> + Send {
89    Runner::new(agent).run(input)
90}
91
92/// A configured run: the agent, its transformer chain and its cancellation
93/// token.
94///
95/// ```
96/// # use ag_ui::{RunAgentInput, RunOutcome};
97/// # use ag_ui::server::{Agent, FilterToolCalls, Result, RunContext, Runner};
98/// # struct MyAgent;
99/// # impl Agent for MyAgent {
100/// #     type State = ();
101/// #     async fn run(&self, _ctx: &mut RunContext<()>) -> Result<RunOutcome> { Ok(RunOutcome::Success) }
102/// # }
103/// let runner = Runner::new(MyAgent).transformer(FilterToolCalls::deny(["internal_debug"]));
104/// let token = runner.cancellation_token();   // hand this to the transport
105/// let stream = runner.run(RunAgentInput::new("thread-1", "run-1"));
106/// # let _ = (token, stream);
107/// ```
108pub struct Runner<A> {
109    agent: A,
110    chain: TransformerChain,
111    cancel: CancellationToken,
112    echo_input: bool,
113    event_buffer_capacity: Option<NonZeroUsize>,
114}
115
116// Hand-written so that `Runner` is printable whatever the agent is: requiring
117// `A: Debug` would make the bound viral through every wrapper that holds one.
118impl<A> std::fmt::Debug for Runner<A> {
119    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
120        f.debug_struct("Runner")
121            .field("agent", &std::any::type_name::<A>())
122            .field("chain", &self.chain)
123            .field("cancel", &self.cancel)
124            .field("echo_input", &self.echo_input)
125            .field("event_buffer_capacity", &self.event_buffer_capacity)
126            .finish()
127    }
128}
129
130impl<A> Runner<A> {
131    /// Wraps an agent.
132    pub fn new(agent: A) -> Self {
133        Self {
134            agent,
135            chain: TransformerChain::new(),
136            cancel: CancellationToken::new(),
137            echo_input: false,
138            event_buffer_capacity: None,
139        }
140    }
141
142    /// Appends a transformer to the chain. See [`StreamTransformer`].
143    #[must_use]
144    pub fn transformer(mut self, transformer: impl StreamTransformer + 'static) -> Self {
145        self.chain.push(transformer);
146        self
147    }
148
149    /// Replaces the whole transformer chain.
150    #[must_use]
151    pub fn transformers(mut self, chain: TransformerChain) -> Self {
152        self.chain = chain;
153        self
154    }
155
156    /// Uses an existing cancellation token instead of the fresh one.
157    #[must_use]
158    pub fn cancellation(mut self, token: CancellationToken) -> Self {
159        self.cancel = token;
160        self
161    }
162
163    /// A handle on this run's cancellation, for the transport to trip when the
164    /// client disconnects.
165    pub fn cancellation_token(&self) -> CancellationToken {
166        self.cancel.clone()
167    }
168
169    /// Echoes the request back on `RUN_STARTED`, so a recorded stream replays
170    /// without the original HTTP body. Off by default — it is the largest
171    /// payload in the protocol.
172    ///
173    /// This decides only what goes on the wire. The verifier and every
174    /// transformer learn the request's history either way (see
175    /// [`StreamTransformer::seed`]), so a resumed run behaves the same with
176    /// and without the echo.
177    #[must_use]
178    pub fn echo_input(mut self, echo: bool) -> Self {
179        self.echo_input = echo;
180        self
181    }
182
183    /// Limits queued events, including lifecycle events, after transformation.
184    ///
185    /// Emission is synchronous, so it cannot wait for a slow consumer. When
186    /// full, the sink rejects the next event, appends one reserved `RUN_ERROR`
187    /// with code `EVENT_BUFFER_FULL`, then closes the stream. Already accepted
188    /// events retain their order. This terminal error bypasses transformers.
189    ///
190    /// The default remains unbounded. This bounds event count, not payload
191    /// bytes or allocations made by an agent/transformer before emission.
192    /// Applications with durable execution should reconnect from committed
193    /// state; this transport failure does not decide business success.
194    #[must_use]
195    pub fn event_buffer_capacity(mut self, capacity: NonZeroUsize) -> Self {
196        self.event_buffer_capacity = Some(capacity);
197        self
198    }
199}
200
201impl<A: Agent> Runner<A> {
202    /// Starts the run.
203    ///
204    /// The returned stream emits `RUN_STARTED` first and exactly one of
205    /// `RUN_FINISHED` / `RUN_ERROR` last — including when the agent body does
206    /// nothing, and when it returns `Err` through a `?`.
207    ///
208    /// The stream yields [`Event`], not `Result<Event>`: whatever goes wrong
209    /// inside a run is reported in the stream, as `RUN_ERROR`, so there is no
210    /// error left for an item to carry.
211    ///
212    /// A panic inside the agent is not caught; it unwinds through whoever is
213    /// polling the stream, as it would through any other future. Use the
214    /// transport's own panic handling if you need a response body for that
215    /// case.
216    ///
217    /// # The run lives as long as the stream
218    ///
219    /// The agent advances only while the stream is polled, and is dropped
220    /// with it. A stream dropped before its terminal event leaves a run that
221    /// stopped where it was: no `RUN_FINISHED` and no `RUN_ERROR`, for
222    /// anyone. That is the right lifetime for a run that answers one
223    /// request, where the response body is the stream and a client that goes
224    /// away takes the run with it.
225    ///
226    /// It is the wrong one for a run that outlives its response. Take the
227    /// halves with [`into_parts`](Self::into_parts) instead; the [module
228    /// docs](self#a-run-that-outlives-its-response) say what else such a
229    /// server needs.
230    pub fn run(self, input: RunAgentInput) -> impl Stream<Item = Event> + Send {
231        let (driver, events) = self.into_parts(input);
232        RunStream {
233            driver: Some(Box::pin(driver)),
234            events,
235        }
236    }
237
238    /// Starts the run as its two halves: the future that drives the agent,
239    /// and the receiver of what it emits.
240    ///
241    /// For a run that is not tied to one response. Put the driver on an
242    /// executor of your choosing and send the events wherever they are
243    /// stored and fanned out. The agent then advances whether or not anyone
244    /// is reading, and a client that disconnects ends nothing.
245    ///
246    /// Everything [`run`](Self::run) promises holds for the halves:
247    /// `RUN_STARTED` first, exactly one terminal event last, the transformer
248    /// chain, the cancellation token, the typed emitters and the ordering
249    /// checks. `run` is these two halves joined in one stream.
250    ///
251    /// ```
252    /// # use ag_ui::{Event, EventType, RunAgentInput, RunOutcome};
253    /// # use ag_ui::server::{Agent, Result, RunContext, Runner};
254    /// # use futures_util::StreamExt;
255    /// # struct Greeter;
256    /// # impl Agent for Greeter {
257    /// #     type State = ();
258    /// #     async fn run(&self, ctx: &mut RunContext<()>) -> Result<RunOutcome> {
259    /// #         ctx.say("hello")?;
260    /// #         Ok(RunOutcome::Success)
261    /// #     }
262    /// # }
263    /// # let rt = tokio::runtime::Builder::new_current_thread().build().unwrap();
264    /// # rt.block_on(async {
265    /// let runner = Runner::new(Greeter);
266    /// let (driver, mut events) = runner.into_parts(RunAgentInput::new("thread-1", "run-1"));
267    ///
268    /// // Any executor will do: the driver is a plain future.
269    /// let run = tokio::spawn(driver);
270    ///
271    /// // Store each event, and send it to whoever is on the thread now.
272    /// let mut stored = Vec::new();
273    /// while let Some(event) = events.next().await {
274    ///     stored.push(event);
275    /// }
276    /// // The receiver ended, so nothing more will arrive: stop the driver.
277    /// run.abort();
278    ///
279    /// assert_eq!(stored.first().map(Event::event_type), Some(EventType::RunStarted));
280    /// assert_eq!(stored.last().map(Event::event_type), Some(EventType::RunFinished));
281    /// # });
282    /// ```
283    ///
284    /// # What the stream did for you
285    ///
286    /// Three things, which are now the caller's:
287    ///
288    /// - **Poll the driver to completion.** The terminal event is emitted by
289    ///   the driver, after the agent returns. A driver dropped earlier ends
290    ///   the receiver with no terminal event.
291    /// - **Drop the driver when the receiver ends.** The receiver ends when
292    ///   the driver has finished, and also when a bounded queue overflows
293    ///   ([`event_buffer_capacity`](Self::event_buffer_capacity)): the sink
294    ///   then queues its `RUN_ERROR` and closes. An agent that ignores the
295    ///   error its emit returned can go on awaiting forever, and nothing it
296    ///   does after that reaches anyone.
297    /// - **Keep the receiver, or cancel.** Dropping the receiver fails every
298    ///   later emit with [`Error::Disconnected`], which unwinds an agent that
299    ///   uses `?`. To stop a run on purpose, trip the
300    ///   [`cancellation_token`](Self::cancellation_token): the run then
301    ///   closes what it opened and ends with a cancelled `RUN_FINISHED`.
302    ///
303    /// The receiver holds one run's events for one reader. Giving them to
304    /// several clients, and to one that joins later, is the application's:
305    /// [`RunProgress`](crate::server::RunProgress) builds what a client that
306    /// joins a run in progress is sent first.
307    pub fn into_parts(
308        self,
309        input: RunAgentInput,
310    ) -> (impl Future<Output = ()> + Send, EventReceiver) {
311        let echo_input = self.echo_input;
312        let (agent, sink, events) = self.split(&input.run_id);
313        let opening = Opening::Start { echo_input };
314        (drive(agent, input, sink, opening), events)
315    }
316
317    /// Carries on a run that another driver began: the same halves as
318    /// [`into_parts`](Self::into_parts), for a run whose first events are
319    /// already sent.
320    ///
321    /// `sent` is every event of the run that went out, in order, as stored.
322    /// It may begin with the runs that came before on the same stream; the
323    /// run continued is the last one it starts. `input` is the request the
324    /// run is continued from: the thread and run ids of the run, the
325    /// `messages` it started with, and the state as it stands now, which
326    /// the agent reads as its own.
327    ///
328    /// The driver emits no `RUN_STARTED`, and it ends the run with exactly
329    /// one terminal event, as any driver does. What it emits continues the
330    /// stream that `sent` began:
331    ///
332    /// - the ordering checks start from where the run is, so an entity the
333    ///   earlier driver left open can be continued and closed, and has to be
334    ///   closed before `RUN_FINISHED`;
335    /// - the first state the agent publishes is compared with the state the
336    ///   events sent left a client holding, and goes out as a delta against
337    ///   it;
338    /// - a subagent left active is closed by the agent, or by the driver when
339    ///   the run is cancelled;
340    /// - the ids the context hands out count on from the ones `sent` used,
341    ///   and are never one of them.
342    ///
343    /// The transformers start fresh. They are seeded with `input.messages`
344    /// and then shown `sent` ([`StreamTransformer::replay`]), and from there
345    /// they are fed what the agent emits. `sent` is the output of the earlier
346    /// driver's chain, so a transformer learns from it what a consumer was
347    /// sent, and not what that chain kept back:
348    /// [`FilterToolCalls`](crate::server::FilterToolCalls) lets this driver
349    /// finish and answer a call that was sent, and drops an event of a call
350    /// it has no record of, which is what a call the earlier filter dropped
351    /// looks like from here.
352    ///
353    /// An entity the earlier driver opened has no handle here. Continue and
354    /// close it with [`RunContext::emit`], naming its id. A run that is
355    /// cancelled cannot: every emit fails once the token is tripped. So the
356    /// driver closes what `sent` left open before the `RUN_FINISHED` that
357    /// cancels the run, innermost first and each under the subagent that
358    /// opened it: a message, a tool call, a reasoning message, a reasoning
359    /// block, a step. A run that is not cancelled has to close them itself,
360    /// and its `RUN_FINISHED` is refused while one is open, with the
361    /// `verify` feature or without.
362    /// [`echo_input`](Self::echo_input) has nothing to echo on, since no
363    /// `RUN_STARTED` is sent.
364    ///
365    /// ```
366    /// # use ag_ui::{Event, EventType, RunAgentInput, RunOutcome, TextMessageRole};
367    /// # use ag_ui::server::{Agent, Result, RunContext, Runner};
368    /// # use futures_util::StreamExt;
369    /// /// Finishes the sentence another process left open.
370    /// struct Finisher;
371    ///
372    /// impl Agent for Finisher {
373    ///     type State = ();
374    ///     async fn run(&self, ctx: &mut RunContext<()>) -> Result<RunOutcome> {
375    ///         ctx.emit(Event::text_message_content("msg-1", " world"))?;
376    ///         ctx.emit(Event::text_message_end("msg-1"))?;
377    ///         Ok(RunOutcome::Success)
378    ///     }
379    /// }
380    ///
381    /// # let rt = tokio::runtime::Builder::new_current_thread().build().unwrap();
382    /// # rt.block_on(async {
383    /// // What the store holds of the run: the process driving it stopped here.
384    /// let sent = [
385    ///     Event::run_started("thread-1", "run-1"),
386    ///     Event::text_message_start("msg-1", TextMessageRole::Assistant),
387    ///     Event::text_message_content("msg-1", "Hello"),
388    /// ];
389    ///
390    /// let request = RunAgentInput::new("thread-1", "run-1");
391    /// let (driver, events) = Runner::new(Finisher).continue_run(request, &sent)?;
392    /// tokio::spawn(driver);
393    ///
394    /// let rest: Vec<EventType> = events.map(|event| event.event_type()).collect().await;
395    /// assert_eq!(
396    ///     rest,
397    ///     [
398    ///         EventType::TextMessageContent,
399    ///         EventType::TextMessageEnd,
400    ///         EventType::RunFinished,
401    ///     ]
402    /// );
403    /// # Ok::<(), ag_ui::server::Error>(())
404    /// # })?;
405    /// # Ok::<(), ag_ui::server::Error>(())
406    /// ```
407    ///
408    /// # Errors
409    ///
410    /// Nothing is driven and nothing is emitted when there is no run to
411    /// continue:
412    ///
413    /// - [`Error::Verification`] when `sent` holds no `RUN_STARTED`, when
414    ///   the last run it starts already ended, or, with the `verify`
415    ///   feature, when an event in it breaks the ordering rules: the error
416    ///   is that event's;
417    /// - [`Error::Json`] when a `STATE_DELTA` in `sent` carries a patch that
418    ///   is not well formed;
419    /// - [`Error::Protocol`] when `input` names another thread or run than
420    ///   the last `RUN_STARTED` in `sent`.
421    pub fn continue_run(
422        self,
423        input: RunAgentInput,
424        sent: &[Event],
425    ) -> Result<(impl Future<Output = ()> + Send + use<A>, EventReceiver)> {
426        let (agent, mut sink, events) = self.split(&input.run_id);
427        // As the first driver did before its first event: a result in `sent`
428        // may answer a call the request's history introduced.
429        sink.seed(&input.messages);
430        // Then what the first driver sent: this one finishes and answers
431        // calls that one opened.
432        sink.show_sent(sent);
433        let mut started = None;
434        let mut ended = None;
435        for event in sent {
436            sink.replay(event)?;
437            match event {
438                // The run to continue is the last one `sent` starts: the
439                // ones before it are the stream's history.
440                Event::RunStarted(event) => {
441                    started = Some(event);
442                    ended = None;
443                }
444                Event::RunFinished(_) | Event::RunError(_) => ended = Some(event.event_type()),
445                _ => {}
446            }
447        }
448        let nothing_to_continue = |event, rule, why: &str| {
449            let detail = format!("there is no run to continue: {why}");
450            Error::from(VerificationError::new(event, rule, detail))
451        };
452        if let Some(terminal) = ended {
453            return Err(nothing_to_continue(
454                terminal,
455                Rule::RunEnded,
456                "the run already ended",
457            ));
458        }
459        let Some(started) = started else {
460            return Err(nothing_to_continue(
461                EventType::RunStarted,
462                Rule::OutOfOrder,
463                "no RUN_STARTED was sent",
464            ));
465        };
466        if started.thread_id != input.thread_id || started.run_id != input.run_id {
467            return Err(Error::Protocol(crate::Error::Protocol(format!(
468                "the run that was started is {:?} on thread {:?}, and the input to continue it \
469                 names run {:?} on thread {:?}",
470                started.run_id.as_str(),
471                started.thread_id.as_str(),
472                input.run_id.as_str(),
473                input.thread_id.as_str(),
474            ))));
475        }
476        Ok((drive(agent, input, sink, Opening::Continue), events))
477    }
478
479    /// The agent, the write end of its event stream and the read end.
480    fn split(self, run_id: &RunId) -> (A, EventSink, EventReceiver) {
481        let Self {
482            agent,
483            chain,
484            cancel,
485            echo_input: _,
486            event_buffer_capacity,
487        } = self;
488        let (tx, rx) = mpsc::unbounded();
489        let sink = EventSink::new(run_id.clone(), tx, chain, cancel)
490            .with_event_buffer_capacity(event_buffer_capacity);
491        (agent, sink, EventReceiver::new(rx))
492    }
493}
494
495/// How a driver opens its part of the run.
496enum Opening {
497    /// With `RUN_STARTED`: the run begins here.
498    Start { echo_input: bool },
499    /// With nothing: an earlier driver began the run, and the sink already
500    /// holds what it sent.
501    Continue,
502}
503
504/// Opens the run, runs the agent, and emits the terminal event.
505///
506/// Takes the sink by value and only hands it to the context for the duration of
507/// the agent's call: whatever happens in there, the terminal event still goes
508/// through the same transformers and the same verifier.
509async fn drive<A: Agent>(agent: A, input: RunAgentInput, mut sink: EventSink, opening: Opening) {
510    let thread_id = input.thread_id.clone();
511    let run_id = input.run_id.clone();
512
513    if let Opening::Start { echo_input } = opening {
514        // Seed history whether or not the client asked for an input echo.
515        sink.seed(&input.messages);
516        let mut started = RunStartedEvent::new(thread_id.clone(), run_id.clone());
517        started.parent_run_id = input.parent_run_id.clone();
518        if echo_input {
519            started.input = Some(Box::new(input.clone()));
520        }
521        if sink.emit_forced(started.into()).is_err() {
522            return;
523        }
524    }
525
526    // Decoded before the match so the borrow of `input` ends here: the context
527    // takes the input by value on the next line.
528    let decoded = decode_state::<A::State>(&input.state);
529    let (outcome, terminal) = match decoded {
530        Ok(state) => {
531            let mut ctx = RunContext::from_parts(input, state, sink);
532            let outcome = agent.run(&mut ctx).await;
533            if ctx.is_terminated() {
534                // The agent emitted its own terminal event through `emit`.
535                return;
536            }
537            let terminal;
538            (sink, terminal) = ctx.into_parts();
539            (outcome, terminal)
540        }
541        Err(error) => (Err(error), Terminal::default()),
542    };
543
544    terminate(&mut sink, outcome, terminal, &thread_id, &run_id);
545}
546
547/// Emits exactly one terminal event, carrying the result and usage the agent
548/// reported through its context.
549fn terminate(
550    sink: &mut EventSink,
551    outcome: Result<RunOutcome>,
552    terminal: Terminal,
553    thread_id: &ThreadId,
554    run_id: &RunId,
555) {
556    // AG-UI 1.0, "Cancelled runs": a cancelled run closes what it opened
557    // before the RUN_FINISHED that cancels it. The handles closed theirs on
558    // the way out. Two things have no handle to close them. A subagent the
559    // agent left active has no ending to infer, so the driver reports it as
560    // stopped by the cancellation. And what an earlier driver of the run
561    // left open is this run's to close, which its agent no longer can: an
562    // emit after cancellation fails.
563    if matches!(outcome, Ok(RunOutcome::Cancelled) | Err(Error::Cancelled)) {
564        sink.close_unclosed(&Error::Cancelled);
565    }
566    let usage = terminal.usage();
567    let finished = |outcome| {
568        let mut finished =
569            RunFinishedEvent::new(thread_id.clone(), run_id.clone()).with_outcome(outcome);
570        finished.result = terminal.result.clone();
571        finished.usage = usage.clone();
572        Event::from(finished)
573    };
574    let event = match outcome {
575        Ok(outcome) => match outcome.validate() {
576            Ok(()) => finished(outcome),
577            Err(error) => error_event(&Error::Protocol(error), usage.clone()),
578        },
579        // A deliberate stop is a closed run, provided all open entities were
580        // closed. If a raw emit left one open, the verifier rejects
581        // RUN_FINISHED and the fallback below reports RUN_ERROR instead.
582        Err(Error::Cancelled) => finished(RunOutcome::Cancelled),
583        Err(error) => error_event(&error, usage.clone()),
584    };
585
586    if let Err(rejected) = sink.emit_forced(event) {
587        if rejected.is_disconnected() || sink.is_terminated() {
588            return;
589        }
590        // Preserve the transformer's opportunity to redact or reclassify the error.
591        let _ = sink.emit_forced(error_event(&rejected, usage));
592    }
593    if !sink.is_terminated() {
594        // A transformer may have dropped or replaced every terminal event.
595        // Only this fixed diagnostic bypasses the chain. Original payloads,
596        // including usage, may have been filtered intentionally.
597        let error = RunErrorEvent::new("the transformer chain did not deliver a terminal event")
598            .with_code("PROTOCOL_VIOLATION");
599        let _ = sink.send(error.into());
600    }
601}
602
603fn error_event(error: &Error, usage: Option<Vec<TokenUsage>>) -> Event {
604    let mut event = RunErrorEvent::new(error.to_string()).with_code(error.code());
605    event.usage = usage;
606    event.into()
607}
608
609/// The stream half: drains queued events, and polls the agent when there are
610/// none.
611///
612/// The driver future is boxed so the stream is `Unpin` and needs no unsafe
613/// projection — one allocation per run.
614struct RunStream<F> {
615    driver: Option<Pin<Box<F>>>,
616    events: EventReceiver,
617}
618
619impl<F: Future<Output = ()>> Stream for RunStream<F> {
620    type Item = Event;
621
622    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
623        let this = self.get_mut();
624        loop {
625            // Events first: everything the agent has already emitted goes out
626            // before it is polled again, which is what keeps a slow agent's
627            // early output flowing.
628            match this.events.poll_next_unpin(cx) {
629                Poll::Ready(Some(event)) => return Poll::Ready(Some(event)),
630                // The driver dropped its sender, or overflow closed the queue.
631                Poll::Ready(None) => {
632                    // Overflow closes the queue even if an agent ignored its
633                    // emit error and then awaited forever.
634                    this.driver = None;
635                    return Poll::Ready(None);
636                }
637                Poll::Pending => {}
638            }
639
640            let Some(driver) = this.driver.as_mut() else {
641                return Poll::Pending;
642            };
643            match driver.as_mut().poll(cx) {
644                // Dropping the future drops the sink, which closes the channel
645                // once the events still queued behind it have been drained.
646                Poll::Ready(()) => this.driver = None,
647                Poll::Pending => return Poll::Pending,
648            }
649        }
650    }
651}
652
653/// A run-owned source error means execution has ended, so it becomes the
654/// run's `RUN_ERROR` and nothing after it is read. External subscriptions use
655/// a separate transport path, where source errors cannot claim a run failed.
656#[cfg(feature = "axum")]
657pub(crate) fn terminal_error_events<S>(
658    events: S,
659    cancellation: Option<CancellationToken>,
660) -> impl Stream<Item = Event> + Send
661where
662    S: Stream<Item = Result<Event>> + Send + 'static,
663{
664    futures_util::stream::unfold(Some(Box::pin(events)), move |events| {
665        let cancellation = cancellation.clone();
666        async move {
667            let mut events = events?;
668            match events.next().await {
669                Some(Ok(event)) => Some((event, Some(events))),
670                Some(Err(error)) => {
671                    if let Some(token) = cancellation {
672                        token.cancel();
673                    }
674                    drop(events);
675                    let event =
676                        Event::from(RunErrorEvent::new(error.to_string()).with_code(error.code()));
677                    Some((event, None))
678                }
679                None => None,
680            }
681        }
682    })
683}