ag_ui/lib.rs
1//! A Rust SDK for the [AG-UI protocol] — hosting an agent and consuming one.
2//!
3//! AG-UI is the protocol between a user-facing application and an agent
4//! backend. A run is a stream of [`Event`]s: the agent opens messages, streams
5//! text and reasoning, calls tools, publishes state, and finishes — or pauses
6//! for human input.
7//!
8//! An independent SDK, not an official AG-UI project. The event surface is
9//! checked against a vendored copy of the AG-UI 1.0 JSON Schema. The
10//! `ag-ui-core` and `ag-ui-client` packages on crates.io are an earlier,
11//! unrelated SDK.
12//!
13//! # What is in the box
14//!
15//! The crate root is the shared vocabulary: the types, their exact JSON
16//! representation, and the SSE framing that carries them. No runtime, no I/O,
17//! no async — that part compiles for everyone.
18//!
19//! Everything past it is a feature, because most programs want one side of the
20//! protocol and should not pay to compile the other. Each entry below is
21//! gated the same way its module is: a link to an item this build does not
22//! have is a rustdoc error, not a dead link, which is what the `doc-features`
23//! CI job exists to catch.
24//!
25#![cfg_attr(
26 feature = "server",
27 doc = "- [`server`] — host an agent. Implement [`server::Agent`], hand it to",
28 doc = " [`server::run()`], and you have a stream a transport can serialize."
29)]
30#![cfg_attr(
31 not(feature = "server"),
32 doc = "- `server` *(off in this build)* — host an agent: the `Agent` trait, and",
33 doc = " `run()` to turn one into a stream a transport can serialize."
34)]
35#![cfg_attr(
36 feature = "client",
37 doc = "- [`client`] — consume a remote agent, materializing its events into",
38 doc = " messages and state."
39)]
40#![cfg_attr(
41 not(feature = "client"),
42 doc = "- `client` *(off in this build)* — consume a remote agent, materializing",
43 doc = " its events into messages and state."
44)]
45#![cfg_attr(
46 feature = "axum",
47 doc = "- [`axum`] — mount a hosted agent on an axum router, one call."
48)]
49#![cfg_attr(
50 not(feature = "axum"),
51 doc = "- `axum` *(off in this build)* — mount a hosted agent on an axum router."
52)]
53//!
54//! Each runtime keeps its own `Error` and `Result` under its own module. A
55//! bare [`Error`] is always a protocol error, `ag_ui::server::Error` is a
56//! hosting error, and collapsing them into the root would hide a distinction
57//! that matters at every `?`.
58//!
59//! ```
60//! # #[cfg(feature = "sse")] {
61//! use ag_ui::{Event, EventStreamFormatter, SseFormatter, TextMessageRole};
62//!
63//! let formatter = SseFormatter::new();
64//! let run = [
65//! Event::run_started("thread-1", "run-1"),
66//! Event::text_message_start("msg-1", TextMessageRole::Assistant),
67//! Event::text_message_content("msg-1", "Hello"),
68//! Event::text_message_end("msg-1"),
69//! Event::run_finished_success("thread-1", "run-1"),
70//! ];
71//!
72//! let body: String = run
73//! .iter()
74//! .map(|event| formatter.encode_to_string(event).unwrap())
75//! .collect();
76//!
77//! assert!(body.starts_with(r#"data: {"type":"RUN_STARTED","threadId":"thread-1""#));
78//! # }
79//! ```
80//!
81//! # Identifiers are strings
82//!
83//! [`ThreadId`], [`RunId`] and friends wrap [`String`], not `Uuid`. Producers
84//! send arbitrary strings and a stricter type would reject valid traffic — see
85//! the [`ids`] module for the history.
86//!
87//! # Features
88//!
89// A feature list is the one place a doc link is guaranteed to name something
90// the current build may not have. Gated so the link stays live where the item
91// exists — see `doc-features` in CI.
92#![cfg_attr(
93 feature = "sse",
94 doc = "- `sse` *(default)* — [`SseFormatter`] and `text/event-stream` framing."
95)]
96#![cfg_attr(
97 not(feature = "sse"),
98 doc = "- `sse` *(default, off in this build)* — `SseFormatter` and `text/event-stream` framing."
99)]
100//! - `protobuf` — a documented stub that names the binary media type and
101//! encodes nothing. The stock TypeScript client asks for SSE; the
102//! `encode::protobuf` module explains why there is no encoder.
103//! - `schemars` — derives `schemars::JsonSchema` on the public types.
104//! - `utoipa` — derives `utoipa::ToSchema` on the public types.
105//! - `server` — the server runtime: the agent trait, typestate emitters, state
106//! deltas. Executor-agnostic; no tokio.
107//! - `verify` *(default)* — `server`'s ordering state machine. Off, the whole
108//! verifier is a zero-sized type whose checks compile away. Listed in
109//! `default` rather than implied by `server` so `default-features = false`
110//! can drop it.
111//! - `client` — the client runtime, transport-agnostic.
112//! - `http` — adds the reqwest-backed transport to `client`. What most
113//! consumers want; leave it off for wasm or a custom transport.
114//! - `axum` — mounts a hosted agent on an axum router. Implies `server` and
115//! `sse`, and is the one feature that pulls in tokio.
116//!
117//! ```toml
118//! [dependencies]
119//! # host an agent behind axum
120//! ag-ui = { version = "0.5", features = ["axum"] }
121//! # or consume one over HTTP
122//! ag-ui = { version = "0.5", features = ["http"] }
123//! ```
124//!
125//! [AG-UI protocol]: https://github.com/ag-ui-protocol/ag-ui
126
127#![forbid(unsafe_code)]
128#![warn(missing_docs)]
129#![warn(missing_debug_implementations)]
130// A library writes only to what its caller hands it. What it has to report
131// goes back through the API: a run's diagnostics, a hook, a return value.
132#![warn(clippy::print_stdout, clippy::print_stderr)]
133// Stamps "Available on crate feature X" on every gated item in the rendered
134// docs. Only ever set by docs.rs and the `cargo doc` recipe in CONTRIBUTING, so
135// it costs a stable build nothing.
136#![cfg_attr(docsrs, feature(doc_cfg))]
137
138// `readme = "README.md"` in Cargo.toml makes that file the crate's front page
139// wherever the package is presented, so its examples are doctested: a stale one
140// is a red build rather than a bad first impression. `cfg(doctest)` is what
141// keeps this module out of the rendered docs — it compiles the examples rather
142// than publishing them.
143// Gated on `sse` because that is the feature the example demonstrates.
144#[cfg(all(doctest, feature = "sse"))]
145#[doc = include_str!("../README.md")]
146mod readme {}
147
148pub mod capabilities;
149pub mod context;
150pub mod error;
151pub mod event;
152pub mod ids;
153pub mod input;
154pub mod message;
155pub mod metadata;
156pub mod outcome;
157pub mod patch;
158pub mod token_usage;
159pub mod tool;
160
161mod serde_util;
162
163#[cfg(any(feature = "client", feature = "axum"))]
164mod protocol;
165
166// The protocol rules both runtimes enforce, each in one place: the order
167// events may arrive in, and what a `*_CHUNK` event stands for.
168#[cfg(any(feature = "client", all(feature = "server", feature = "verify")))]
169mod ordering;
170#[cfg(any(feature = "client", feature = "server"))]
171mod streams;
172
173#[cfg(any(feature = "sse", feature = "protobuf"))]
174pub mod encode;
175
176// The runtimes. Each carries its own `Error` and `Result`, which is why they
177// stay behind a module path instead of being flattened into the root the way
178// the protocol types are: `ag_ui::Error` is a protocol error, `ag_ui::server::Error`
179// is a hosting error, and collapsing them would make the distinction invisible.
180#[cfg(feature = "axum")]
181pub mod axum;
182#[cfg(feature = "client")]
183pub mod client;
184// Hidden subagent streams reuse the message reducer without enabling client I/O.
185#[cfg(all(feature = "server", not(feature = "client")))]
186#[allow(dead_code)]
187mod client {
188 pub(crate) mod apply;
189 mod error;
190}
191#[cfg(feature = "server")]
192pub mod server;
193
194/// A JSON object — the Rust spelling of TypeScript's `Record<string, any>`.
195///
196/// Member order follows the consumer's `serde_json` configuration. The SDK
197/// does not enable `preserve_order` for downstream applications.
198pub type JsonObject = serde_json::Map<String, serde_json::Value>;
199
200pub use capabilities::{
201 AgentCapabilities, ExecutionCapabilities, HumanInTheLoopCapabilities, IdentityCapabilities,
202 MultiAgentCapabilities, MultimodalCapabilities, MultimodalInputCapabilities,
203 MultimodalOutputCapabilities, OutputCapabilities, ReasoningCapabilities, StateCapabilities,
204 SubagentInfo, ToolsCapabilities, TransportCapabilities,
205};
206// The pre-1.0 spelling, kept as a deprecated alias.
207#[allow(deprecated)]
208pub use capabilities::SubAgentInfo;
209pub use context::Context;
210pub use error::{Error, Result};
211pub use event::{
212 ActivityDeltaEvent, ActivitySnapshotEvent, BaseEvent, CustomEvent, Event, EventType,
213 MessagesSnapshotEvent, RawEvent, ReasoningEncryptedValueEvent, ReasoningEncryptedValueSubtype,
214 ReasoningEndEvent, ReasoningMessageChunkEvent, ReasoningMessageContentEvent,
215 ReasoningMessageEndEvent, ReasoningMessageStartEvent, ReasoningRole, ReasoningStartEvent,
216 RunErrorEvent, RunFinishedEvent, RunStartedEvent, StateDeltaEvent, StateSnapshotEvent,
217 StepFinishedEvent, StepStartedEvent, SubagentErrorEvent, SubagentFinishedEvent,
218 SubagentOutcome, SubagentStartedEvent, TextMessageChunkEvent, TextMessageContentEvent,
219 TextMessageEndEvent, TextMessageRole, TextMessageStartEvent, ToolCallArgsEvent,
220 ToolCallChunkEvent, ToolCallEndEvent, ToolCallResultEvent, ToolCallStartEvent, ToolResultRole,
221};
222// Still part of the protocol, so still re-exported; downstream users get the
223// deprecation warning at their use site, not here.
224#[allow(deprecated)]
225pub use event::{
226 ThinkingEndEvent, ThinkingStartEvent, ThinkingTextMessageContentEvent,
227 ThinkingTextMessageEndEvent, ThinkingTextMessageStartEvent,
228};
229pub use ids::{AgentId, MessageId, RunId, StepName, SubagentRunId, ThreadId, ToolCallId};
230pub use input::{PROTOCOL_VERSION, RunAgentInput};
231pub use message::{
232 ActivityMessage, AssistantMessage, BinaryInputContent, DeveloperMessage, InputContent,
233 InputContentSource, MediaInputContent, Message, ReasoningMessage, Role, SystemMessage,
234 TextInputContent, ToolContent, ToolMessage, UserContent, UserMessage,
235};
236pub use metadata::{AGUI_METADATA_KEY, merge_metadata};
237pub use outcome::{Interrupt, ResumeEntry, ResumeStatus, RunOutcome};
238pub use patch::{JsonPatch, PatchOperation};
239pub use token_usage::{TokenUsage, aggregate_token_usage};
240pub use tool::{FunctionCall, Tool, ToolCall, ToolCallKind};
241
242#[cfg(feature = "protobuf")]
243pub use encode::protobuf::ProtobufFormatter;
244#[cfg(feature = "sse")]
245pub use encode::sse::SseFormatter;
246#[cfg(any(feature = "sse", feature = "protobuf"))]
247pub use encode::{
248 EventStreamFormatter, PROTOBUF_MEDIA_TYPE, SSE_MEDIA_TYPE, media_type, supported_media_types,
249};