ag_ui/server/mod.rs
1//! Host an [AG-UI] agent in Rust.
2//!
3//! AG-UI is the protocol between a user-facing application and an agent
4//! backend: a POST carrying [`RunAgentInput`],
5//! answered by a stream of typed events. This crate is the server half —
6//! implement [`Agent`], hand it to [`run()`], and you have a stream a transport
7//! can serialize. [`axum`] mounts it on a router; nothing here depends on
8//! a web framework, an executor or an LLM client.
9//!
10//! ```
11//! use ag_ui::{Event, EventType, RunAgentInput, RunOutcome};
12//! use ag_ui::server::{Agent, Result, RunContext, run};
13//! use futures_util::StreamExt;
14//! use serde::{Deserialize, Serialize};
15//!
16//! /// State the client mirrors and the agent updates.
17//! #[derive(Default, Serialize, Deserialize)]
18//! struct Draft {
19//! revision: u32,
20//! title: String,
21//! }
22//!
23//! struct Editor;
24//!
25//! impl Agent for Editor {
26//! type State = Draft;
27//!
28//! async fn run(&self, ctx: &mut RunContext<Draft>) -> Result<RunOutcome> {
29//! // A step brackets a phase of the run. Its guard emits
30//! // STEP_FINISHED on drop, so an early `?` cannot skip it.
31//! let mut step = ctx.step("draft")?;
32//!
33//! // Reasoning the client can render, in its own REASONING_* block.
34//! step.think("The user wants a title.")?;
35//!
36//! // A message streams as TEXT_MESSAGE_START / _CONTENT* / _END.
37//! let mut message = step.assistant_message()?;
38//! message.delta("Naming it ")?;
39//! message.delta("\"Q3 plan\".")?;
40//! message.end()?;
41//!
42//! // Publishing state diffs against the last snapshot and sends
43//! // whichever of STATE_SNAPSHOT / STATE_DELTA is smaller.
44//! step.update_state(|draft| {
45//! draft.revision += 1;
46//! draft.title = "Q3 plan".into();
47//! })?;
48//!
49//! drop(step); // or just let it fall out of scope
50//! Ok(RunOutcome::Success)
51//! }
52//! }
53//!
54//! # let rt = tokio::runtime::Builder::new_current_thread().build().unwrap();
55//! # rt.block_on(async {
56//! let input = RunAgentInput::new("thread-1", "run-1");
57//! let events: Vec<Event> = run(Editor, input)
58//! .collect()
59//! .await;
60//!
61//! let types: Vec<EventType> = events.iter().map(Event::event_type).collect();
62//! assert_eq!(
63//! types,
64//! [
65//! EventType::RunStarted,
66//! EventType::StepStarted,
67//! EventType::ReasoningStart,
68//! EventType::ReasoningMessageStart,
69//! EventType::ReasoningMessageContent,
70//! EventType::ReasoningMessageEnd,
71//! EventType::ReasoningEnd,
72//! EventType::TextMessageStart,
73//! EventType::TextMessageContent,
74//! EventType::TextMessageContent,
75//! EventType::TextMessageEnd,
76//! EventType::StateSnapshot,
77//! EventType::StepFinished,
78//! EventType::RunFinished,
79//! ]
80//! );
81//! # });
82//! ```
83//!
84//! # The four things that shape this API
85//!
86//! **Protocol misuse should not compile.** Event ordering is enforced by
87//! [typestate handles](emit) that borrow the run context mutably, so
88//! interleaving two messages is a borrow-check error. The handles emit their
89//! terminating event on `Drop`, so it cannot be forgotten. What the borrow
90//! checker cannot catch — raw [`emit`](RunContext::emit) calls — a runtime
91//! [ordering verifier](verify) catches, on by default.
92//!
93//! **The emit path is synchronous.** `Drop` cannot be async, so a handle cannot
94//! `await` while emitting its terminator: `msg.delta(text)?` takes no `.await`.
95//! Emitters push into a channel and the transport drains it. Set
96//! [`Runner::event_buffer_capacity`] to terminate on overflow; the default
97//! remains unbounded.
98//!
99//! **Executor-agnostic.** `futures` primitives throughout, no tokio in the
100//! dependency list, no `spawn`. [`CancellationToken`] is an `AtomicBool` and a
101//! waker list rather than `tokio_util`'s. Polling the stream is what runs the
102//! agent. A run that has to outlive its response is taken as two halves
103//! instead, the driver for an executor of your own and the events for your
104//! store: see [the `run` module](mod@run#a-run-that-outlives-its-response).
105//!
106//! **One extension point.** Everything that observes or rewrites the stream is
107//! a [`StreamTransformer`]. There is no parallel builder of callbacks; the
108//! hooks other SDKs expose that way are built-in transformers here —
109//! [`FilterToolCalls`], [`ToolResultToState`].
110//!
111//! # Human in the loop
112//!
113//! Return [`RunOutcome::Interrupt`] to pause
114//! a run. The client answers, and the next request carries the answers in
115//! [`RunContext::resume`]:
116//!
117//! ```
118//! # use ag_ui::{Interrupt, ResumeStatus, RunOutcome};
119//! # use ag_ui::server::{Agent, Result, RunContext};
120//! # struct Approver;
121//! impl Agent for Approver {
122//! type State = ();
123//!
124//! async fn run(&self, ctx: &mut RunContext<()>) -> Result<RunOutcome> {
125//! match ctx.resume_for("delete-everything") {
126//! None => Ok(RunOutcome::interrupt(vec![Interrupt::new(
127//! "delete-everything",
128//! "tool_approval",
129//! )])),
130//! Some(answer) if answer.status == ResumeStatus::Resolved => {
131//! ctx.say("Done.")?;
132//! Ok(RunOutcome::Success)
133//! }
134//! Some(_) => {
135//! ctx.say("Cancelled.")?;
136//! Ok(RunOutcome::Success)
137//! }
138//! }
139//! }
140//! }
141//! ```
142//!
143//! # Subagents
144//!
145//! An agent that delegates opens a [`RunContext::subagent`] scope. Everything
146//! emitted through the handle — text, tool calls, reasoning, steps, nested
147//! subagents — comes out attributed to that invocation, bracketed by
148//! `SUBAGENT_STARTED` and `SUBAGENT_FINISHED`, so a client can group the
149//! output by who produced it:
150//!
151//! ```
152//! # use ag_ui::{Event, EventType, RunAgentInput, RunOutcome};
153//! # use ag_ui::server::{Agent, Result, RunContext, run};
154//! # use futures_util::StreamExt;
155//! # struct Supervisor;
156//! impl Agent for Supervisor {
157//! type State = ();
158//!
159//! async fn run(&self, ctx: &mut RunContext<()>) -> Result<RunOutcome> {
160//! let mut planner = ctx.subagent("planner")?;
161//! planner.say("Two tasks: scope, then risks.")?;
162//! {
163//! let mut estimator = planner.subagent("estimator")?; // nested
164//! estimator.say("About a day each.")?;
165//! estimator.finish()?; // SUBAGENT_FINISHED
166//! }
167//! planner.finish_with(serde_json::json!({ "tasks": 2 }))?;
168//!
169//! ctx.say("Plan ready.")?; // the parent's own
170//! Ok(RunOutcome::Success)
171//! }
172//! }
173//! # let rt = tokio::runtime::Builder::new_current_thread().build().unwrap();
174//! # rt.block_on(async {
175//! # let events: Vec<Event> = run(Supervisor, RunAgentInput::new("thread-1", "run-1"))
176//! # .collect()
177//! # .await;
178//! # assert_eq!(events.last().map(Event::event_type), Some(EventType::RunFinished));
179//! # });
180//! ```
181//!
182//! What a consumer sees is a producer-side choice, because a client older than
183//! subagent support fails while decoding the lifecycle events. The default
184//! sends the stream as emitted; [`SubagentVisibility::inline`] flattens it to
185//! the pre-subagent shape and [`SubagentVisibility::hidden`] keeps only the
186//! parent's own events — both are ordinary transformers.
187//!
188//! # Features
189//!
190//! - `verify` *(default)* — the ordering state machine. Off, the whole
191//! verifier is a zero-sized type whose checks compile away.
192//!
193//! [AG-UI]: https://docs.ag-ui.com
194//! [`axum`]: https://docs.rs/ag-ui/latest/ag_ui/axum/index.html
195//
196// Core protocol items are spelled as absolute links to the published rustdoc
197// rather than as intra-doc paths. `cargo doc --no-deps` — which is what CI and
198// the Pages deploy both run — cannot emit a path into a crate it is not
199// documenting, and it does not warn: a cross-crate intra-doc link silently
200// becomes literal `[text]`, and the `[text](path)` form silently becomes an
201// href of `path`, which renders as a link and 404s. See the `doc-links` job.
202//! [`RunAgentInput`]: crate::input::RunAgentInput
203//! [`RunOutcome::Interrupt`]: crate::outcome::RunOutcome::Interrupt
204
205pub mod agent;
206pub mod cancel;
207pub mod context;
208pub mod emit;
209pub mod error;
210pub mod progress;
211pub mod run;
212pub mod state;
213pub mod transform;
214pub mod verify;
215
216pub use agent::{Agent, AgentState, BoxAgent, DynAgent};
217pub use cancel::{CancellationToken, Cancelled};
218pub use context::RunContext;
219pub use emit::{
220 EventReceiver, MessageHandle, ReasoningHandle, StepGuard, SubagentHandle, ToolCallHandle,
221};
222pub use error::{Error, Result, Rule, VerificationError};
223pub use progress::{OpenEntity, Prelude, RunProgress};
224pub use run::{Runner, run};
225pub use state::{StateManager, StatePublish};
226pub use transform::{
227 FilterToolCalls, StreamTransformer, SubagentFilter, SubagentVisibility, ToolResultToState,
228 TransformerChain,
229};
230
231#[cfg(feature = "verify")]
232pub use verify::EventVerifier;