Skip to main content

ag_ui/
lib.rs

1//! An independent Rust SDK for the [AG-UI protocol] — hosting an agent and
2//! consuming one.
3//!
4//! AG-UI is the protocol between a user-facing application and an agent
5//! backend. A run is a stream of [`Event`]s: the agent opens messages, streams
6//! text and reasoning, calls tools, publishes state, and finishes — or pauses
7//! for human input.
8//!
9//! <div class="warning">
10//!
11//! This is not an official AG-UI SDK and is not affiliated with the AG-UI
12//! protocol organisation. It is a separate implementation that tracks the
13//! protocol's TypeScript schemas; see the repository for how that is enforced.
14//!
15//! </div>
16//!
17//! # What is in the box
18//!
19//! The crate root is the shared vocabulary: the types, their exact JSON
20//! representation, and the SSE framing that carries them. No runtime, no I/O,
21//! no async — that part compiles for everyone.
22//!
23//! Everything past it is a feature, because most programs want one side of the
24//! protocol and should not pay to compile the other. Each entry below is
25//! gated the same way its module is: a link to an item this build does not
26//! have is a rustdoc error, not a dead link, which is what the `doc-features`
27//! CI job exists to catch.
28//!
29#![cfg_attr(
30    feature = "serve",
31    doc = "- [`serve`] — host an agent. Implement [`serve::Agent`], hand it to",
32    doc = "  [`serve::run()`], and you have a stream a transport can serialize."
33)]
34#![cfg_attr(
35    not(feature = "serve"),
36    doc = "- `serve` *(off in this build)* — host an agent: the `Agent` trait, and",
37    doc = "  `run()` to turn one into a stream a transport can serialize."
38)]
39#![cfg_attr(
40    feature = "client",
41    doc = "- [`client`] — consume a remote agent, materializing its events into",
42    doc = "  messages and state."
43)]
44#![cfg_attr(
45    not(feature = "client"),
46    doc = "- `client` *(off in this build)* — consume a remote agent, materializing",
47    doc = "  its events into messages and state."
48)]
49#![cfg_attr(
50    feature = "axum",
51    doc = "- [`axum`] — mount a hosted agent on an axum router, one call."
52)]
53#![cfg_attr(
54    not(feature = "axum"),
55    doc = "- `axum` *(off in this build)* — mount a hosted agent on an axum router."
56)]
57//!
58//! Each runtime keeps its own `Error` and `Result` under its own module. A
59//! bare [`Error`] is always a protocol error, `ag_ui::serve::Error` is a
60//! hosting error, and collapsing them into the root would hide a distinction
61//! that matters at every `?`.
62//!
63//! ```
64//! # #[cfg(feature = "sse")] {
65//! use ag_ui::{Event, EventStreamFormatter, SseFormatter, TextMessageRole};
66//!
67//! let formatter = SseFormatter::new();
68//! let run = [
69//!     Event::run_started("thread-1", "run-1"),
70//!     Event::text_message_start("msg-1", TextMessageRole::Assistant),
71//!     Event::text_message_content("msg-1", "Hello"),
72//!     Event::text_message_end("msg-1"),
73//!     Event::run_finished_success("thread-1", "run-1"),
74//! ];
75//!
76//! let body: String = run
77//!     .iter()
78//!     .map(|event| formatter.encode_to_string(event).unwrap())
79//!     .collect();
80//!
81//! assert!(body.starts_with(r#"data: {"type":"RUN_STARTED","threadId":"thread-1""#));
82//! # }
83//! ```
84//!
85//! # Identifiers are strings
86//!
87//! [`ThreadId`], [`RunId`] and friends wrap [`String`], not `Uuid`. Producers
88//! send arbitrary strings and a stricter type would reject valid traffic — see
89//! the [`ids`] module for the history.
90//!
91//! # Features
92//!
93// A feature list is the one place a doc link is guaranteed to name something
94// the current build may not have. Gated so the link stays live where the item
95// exists — see `doc-features` in CI.
96#![cfg_attr(
97    feature = "sse",
98    doc = "- `sse` *(default)* — [`SseFormatter`] and `text/event-stream` framing."
99)]
100#![cfg_attr(
101    not(feature = "sse"),
102    doc = "- `sse` *(default, off in this build)* — `SseFormatter` and `text/event-stream` framing."
103)]
104//! - `protobuf` — the binary transport's media type and a documented stub; the
105//!   `encode::protobuf` module explains why there is no encoder.
106//! - `schemars` — derives `schemars::JsonSchema` on the public types.
107//! - `utoipa` — derives `utoipa::ToSchema` on the public types.
108//! - `serve` — the server runtime: the agent trait, typestate emitters, state
109//!   deltas. Executor-agnostic; no tokio.
110//! - `verify` *(default)* — `serve`'s ordering state machine. Off, the whole
111//!   verifier is a zero-sized type whose checks compile away. Listed in
112//!   `default` rather than implied by `serve` so `default-features = false`
113//!   can drop it.
114//! - `client` — the client runtime, transport-agnostic.
115//! - `http` — adds the reqwest-backed transport to `client`. What most
116//!   consumers want; leave it off for wasm or a custom transport.
117//! - `axum` — mounts a hosted agent on an axum router. Implies `serve` and
118//!   `sse`, and is the one feature that pulls in tokio.
119//!
120//! ```toml
121//! [dependencies]
122//! # host an agent behind axum
123//! ag-ui = { version = "0.1", features = ["axum"] }
124//! # or consume one over HTTP
125//! ag-ui = { version = "0.1", features = ["http"] }
126//! ```
127//!
128//! [AG-UI protocol]: https://github.com/ag-ui-protocol/ag-ui
129
130#![forbid(unsafe_code)]
131#![warn(missing_docs)]
132#![warn(missing_debug_implementations)]
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 outcome;
156pub mod patch;
157pub mod token_usage;
158pub mod tool;
159
160#[cfg(any(feature = "sse", feature = "protobuf"))]
161pub mod encode;
162
163// The runtimes. Each carries its own `Error` and `Result`, which is why they
164// stay behind a module path instead of being flattened into the root the way
165// the protocol types are: `ag_ui::Error` is a protocol error, `ag_ui::serve::Error`
166// is a hosting error, and collapsing them would make the distinction invisible.
167#[cfg(feature = "axum")]
168pub mod axum;
169#[cfg(feature = "client")]
170pub mod client;
171#[cfg(feature = "serve")]
172pub mod serve;
173
174/// A JSON object — the Rust spelling of TypeScript's `Record<string, any>`.
175///
176/// Key order is preserved, so a payload that round-trips through this crate
177/// comes back out in the order it arrived.
178pub type JsonObject = serde_json::Map<String, serde_json::Value>;
179
180pub use capabilities::{
181    AgentCapabilities, ExecutionCapabilities, HumanInTheLoopCapabilities, IdentityCapabilities,
182    MultiAgentCapabilities, MultimodalCapabilities, MultimodalInputCapabilities,
183    MultimodalOutputCapabilities, OutputCapabilities, ReasoningCapabilities, StateCapabilities,
184    SubAgentInfo, ToolsCapabilities, TransportCapabilities,
185};
186pub use context::Context;
187pub use error::{Error, Result};
188pub use event::{
189    ActivityDeltaEvent, ActivitySnapshotEvent, BaseEvent, CustomEvent, Event, EventType,
190    MessagesSnapshotEvent, RawEvent, ReasoningEncryptedValueEvent, ReasoningEncryptedValueSubtype,
191    ReasoningEndEvent, ReasoningMessageChunkEvent, ReasoningMessageContentEvent,
192    ReasoningMessageEndEvent, ReasoningMessageStartEvent, ReasoningRole, ReasoningStartEvent,
193    RunErrorEvent, RunFinishedEvent, RunStartedEvent, StateDeltaEvent, StateSnapshotEvent,
194    StepFinishedEvent, StepStartedEvent, TextMessageChunkEvent, TextMessageContentEvent,
195    TextMessageEndEvent, TextMessageRole, TextMessageStartEvent, ToolCallArgsEvent,
196    ToolCallChunkEvent, ToolCallEndEvent, ToolCallResultEvent, ToolCallStartEvent, ToolResultRole,
197};
198// Still part of the protocol, so still re-exported; downstream users get the
199// deprecation warning at their use site, not here.
200#[allow(deprecated)]
201pub use event::{
202    ThinkingEndEvent, ThinkingStartEvent, ThinkingTextMessageContentEvent,
203    ThinkingTextMessageEndEvent, ThinkingTextMessageStartEvent,
204};
205pub use ids::{AgentId, MessageId, RunId, StepName, ThreadId, ToolCallId};
206pub use input::RunAgentInput;
207pub use message::{
208    ActivityMessage, AssistantMessage, BinaryInputContent, DeveloperMessage, InputContent,
209    InputContentSource, MediaInputContent, Message, ReasoningMessage, Role, SystemMessage,
210    TextInputContent, ToolMessage, UserContent, UserMessage,
211};
212pub use outcome::{Interrupt, ResumeEntry, ResumeStatus, RunOutcome};
213pub use patch::{JsonPatch, PatchOperation};
214pub use token_usage::{TokenUsage, aggregate_token_usage};
215pub use tool::{FunctionCall, Tool, ToolCall, ToolCallKind};
216
217#[cfg(feature = "protobuf")]
218pub use encode::protobuf::ProtobufFormatter;
219#[cfg(feature = "sse")]
220pub use encode::sse::SseFormatter;
221#[cfg(any(feature = "sse", feature = "protobuf"))]
222pub use encode::{
223    EventStreamFormatter, PROTOBUF_MEDIA_TYPE, SSE_MEDIA_TYPE, media_type, supported_media_types,
224};