Skip to main content

ag_ui/server/
run.rs

1//! The driver: an [`Agent`] plus a [`RunAgentInput`](https://kimsoungryoul.github.io/ag-ui-rust/api/ag_ui/input/struct.RunAgentInput.html) 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//!     .map(|event| event.expect("the stream should not break"))
26//!     .collect()
27//!     .await;
28//!
29//! assert_eq!(events.first().map(Event::event_type), Some(ag_ui::EventType::RunStarted));
30//! assert_eq!(events.last().map(Event::event_type), Some(ag_ui::EventType::RunFinished));
31//! # });
32//! ```
33
34use std::future::Future;
35use std::num::NonZeroUsize;
36use std::pin::Pin;
37use std::task::{Context, Poll};
38
39use crate::{
40    Event, RunAgentInput, RunErrorEvent, RunFinishedEvent, RunId, RunOutcome, RunStartedEvent,
41    ThreadId,
42};
43use futures_channel::mpsc::{self, UnboundedReceiver};
44use futures_core::Stream;
45use futures_util::StreamExt as _;
46
47use crate::server::agent::Agent;
48use crate::server::cancel::CancellationToken;
49use crate::server::context::{RunContext, decode_state};
50use crate::server::emit::EventSink;
51use crate::server::error::{Error, Result};
52use crate::server::transform::{StreamTransformer, TransformerChain};
53
54/// Runs `agent` against `input` with no transformers and a fresh cancellation
55/// token.
56///
57/// [`Runner`] is the same thing with knobs.
58pub fn run<A: Agent>(agent: A, input: RunAgentInput) -> impl Stream<Item = Result<Event>> + Send {
59    Runner::new(agent).run(input)
60}
61
62/// A configured run: the agent, its transformer chain and its cancellation
63/// token.
64///
65/// ```
66/// # use ag_ui::{RunAgentInput, RunOutcome};
67/// # use ag_ui::server::{Agent, FilterToolCalls, Result, RunContext, Runner};
68/// # struct MyAgent;
69/// # impl Agent for MyAgent {
70/// #     type State = ();
71/// #     async fn run(&self, _ctx: &mut RunContext<()>) -> Result<RunOutcome> { Ok(RunOutcome::Success) }
72/// # }
73/// let runner = Runner::new(MyAgent).transformer(FilterToolCalls::deny(["internal_debug"]));
74/// let token = runner.cancellation_token();   // hand this to the transport
75/// let stream = runner.run(RunAgentInput::new("thread-1", "run-1"));
76/// # let _ = (token, stream);
77/// ```
78pub struct Runner<A> {
79    agent: A,
80    chain: TransformerChain,
81    cancel: CancellationToken,
82    echo_input: bool,
83    event_buffer_capacity: Option<NonZeroUsize>,
84}
85
86// Hand-written so that `Runner` is printable whatever the agent is: requiring
87// `A: Debug` would make the bound viral through every wrapper that holds one.
88impl<A> std::fmt::Debug for Runner<A> {
89    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
90        f.debug_struct("Runner")
91            .field("agent", &std::any::type_name::<A>())
92            .field("chain", &self.chain)
93            .field("cancel", &self.cancel)
94            .field("echo_input", &self.echo_input)
95            .field("event_buffer_capacity", &self.event_buffer_capacity)
96            .finish()
97    }
98}
99
100impl<A> Runner<A> {
101    /// Wraps an agent.
102    pub fn new(agent: A) -> Self {
103        Self {
104            agent,
105            chain: TransformerChain::new(),
106            cancel: CancellationToken::new(),
107            echo_input: false,
108            event_buffer_capacity: None,
109        }
110    }
111
112    /// Appends a transformer to the chain. See [`StreamTransformer`].
113    #[must_use]
114    pub fn transformer(mut self, transformer: impl StreamTransformer + 'static) -> Self {
115        self.chain.push(transformer);
116        self
117    }
118
119    /// Replaces the whole transformer chain.
120    #[must_use]
121    pub fn transformers(mut self, chain: TransformerChain) -> Self {
122        self.chain = chain;
123        self
124    }
125
126    /// Uses an existing cancellation token instead of the fresh one.
127    #[must_use]
128    pub fn cancellation(mut self, token: CancellationToken) -> Self {
129        self.cancel = token;
130        self
131    }
132
133    /// A handle on this run's cancellation, for the transport to trip when the
134    /// client disconnects.
135    pub fn cancellation_token(&self) -> CancellationToken {
136        self.cancel.clone()
137    }
138
139    /// Echoes the request back on `RUN_STARTED`, so a recorded stream replays
140    /// without the original HTTP body. Off by default — it is the largest
141    /// payload in the protocol.
142    #[must_use]
143    pub fn echo_input(mut self, echo: bool) -> Self {
144        self.echo_input = echo;
145        self
146    }
147
148    /// Limits queued events, including lifecycle events, after transformation.
149    ///
150    /// Emission is synchronous, so it cannot wait for a slow consumer. When
151    /// full, the sink rejects the next event, appends one reserved `RUN_ERROR`
152    /// with code `EVENT_BUFFER_FULL`, then closes the stream. Already accepted
153    /// events retain their order. This terminal error bypasses transformers.
154    ///
155    /// The default remains unbounded. This bounds event count, not payload
156    /// bytes or allocations made by an agent/transformer before emission.
157    /// Applications with durable execution should reconnect from committed
158    /// state; this transport failure does not decide business success.
159    #[must_use]
160    pub fn event_buffer_capacity(mut self, capacity: NonZeroUsize) -> Self {
161        self.event_buffer_capacity = Some(capacity);
162        self
163    }
164}
165
166impl<A: Agent> Runner<A> {
167    /// Starts the run.
168    ///
169    /// The returned stream emits `RUN_STARTED` first and exactly one of
170    /// `RUN_FINISHED` / `RUN_ERROR` last — including when the agent body does
171    /// nothing, and when it returns `Err` through a `?`.
172    ///
173    /// A panic inside the agent is not caught; it unwinds through whoever is
174    /// polling the stream, as it would through any other future. Use the
175    /// transport's own panic handling if you need a response body for that
176    /// case.
177    pub fn run(self, input: RunAgentInput) -> impl Stream<Item = Result<Event>> + Send {
178        let Self {
179            agent,
180            chain,
181            cancel,
182            echo_input,
183            event_buffer_capacity,
184        } = self;
185        let (tx, rx) = mpsc::unbounded();
186        let sink =
187            EventSink::new(tx, chain, cancel).with_event_buffer_capacity(event_buffer_capacity);
188        RunStream {
189            driver: Some(Box::pin(drive(agent, input, sink, echo_input))),
190            rx,
191        }
192    }
193}
194
195/// Emits `RUN_STARTED`, runs the agent, and emits the terminal event.
196///
197/// Takes the sink by value and only hands it to the context for the duration of
198/// the agent's call: whatever happens in there, the terminal event still goes
199/// through the same transformers and the same verifier.
200async fn drive<A: Agent>(agent: A, input: RunAgentInput, mut sink: EventSink, echo_input: bool) {
201    let thread_id = input.thread_id.clone();
202    let run_id = input.run_id.clone();
203
204    let mut started = RunStartedEvent::new(thread_id.clone(), run_id.clone());
205    started.parent_run_id = input.parent_run_id.clone();
206    if echo_input {
207        started.input = Some(Box::new(input.clone()));
208    }
209    if sink.emit_forced(started.into()).is_err() {
210        // Nobody is listening, or RUN_STARTED was rejected. Either way there is
211        // no run to report on.
212        return;
213    }
214
215    // Decoded before the match so the borrow of `input` ends here: the context
216    // takes the input by value on the next line.
217    let decoded = decode_state::<A::State>(&input.state);
218    let outcome = match decoded {
219        Ok(state) => {
220            let mut ctx = RunContext::from_parts(input, state, sink);
221            let outcome = agent.run(&mut ctx).await;
222            if ctx.is_terminated() {
223                // The agent emitted its own terminal event through `emit`.
224                return;
225            }
226            sink = ctx.into_sink();
227            outcome
228        }
229        Err(error) => Err(error),
230    };
231
232    terminate(&mut sink, outcome, &thread_id, &run_id);
233}
234
235/// Emits exactly one terminal event.
236fn terminate(
237    sink: &mut EventSink,
238    outcome: Result<RunOutcome>,
239    thread_id: &ThreadId,
240    run_id: &RunId,
241) {
242    let event = match outcome {
243        Ok(outcome) => match outcome.validate() {
244            Ok(()) => RunFinishedEvent::new(thread_id.clone(), run_id.clone())
245                .with_outcome(outcome)
246                .into(),
247            Err(error) => error_event(&Error::Protocol(error)),
248        },
249        Err(error) => error_event(&error),
250    };
251
252    let Err(rejected) = sink.emit_forced(event) else {
253        return;
254    };
255    // `RUN_FINISHED` can be rejected — by the verifier, for a message the agent
256    // left open. A run that ends with no terminal event at all is worse than
257    // one that ends badly, so say what went wrong instead. `RUN_ERROR` is
258    // exempt from the open-at-finish rule for exactly this reason.
259    if !rejected.is_disconnected() && !sink.is_terminated() {
260        let _ = sink.emit_forced(error_event(&rejected));
261    }
262}
263
264fn error_event(error: &Error) -> Event {
265    RunErrorEvent::new(error.to_string())
266        .with_code(error.code())
267        .into()
268}
269
270/// The stream half: drains queued events, and polls the agent when there are
271/// none.
272///
273/// The driver future is boxed so the stream is `Unpin` and needs no unsafe
274/// projection — one allocation per run.
275struct RunStream<F> {
276    driver: Option<Pin<Box<F>>>,
277    rx: UnboundedReceiver<Event>,
278}
279
280impl<F: Future<Output = ()>> Stream for RunStream<F> {
281    type Item = Result<Event>;
282
283    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
284        let this = self.get_mut();
285        loop {
286            // Events first: everything the agent has already emitted goes out
287            // before it is polled again, which is what keeps a slow agent's
288            // early output flowing.
289            match this.rx.poll_next_unpin(cx) {
290                Poll::Ready(Some(event)) => return Poll::Ready(Some(Ok(event))),
291                // The driver dropped its sender, or overflow closed the queue.
292                Poll::Ready(None) => {
293                    // Overflow closes the queue even if an agent ignored its
294                    // emit error and then awaited forever.
295                    this.driver = None;
296                    return Poll::Ready(None);
297                }
298                Poll::Pending => {}
299            }
300
301            let Some(driver) = this.driver.as_mut() else {
302                return Poll::Pending;
303            };
304            match driver.as_mut().poll(cx) {
305                // Dropping the future drops the sink, which closes the channel
306                // once the events still queued behind it have been drained.
307                Poll::Ready(()) => this.driver = None,
308                Poll::Pending => return Poll::Pending,
309            }
310        }
311    }
312}