Skip to main content

ag_ui/server/
agent.rs

1//! The boundary: implement [`Agent`], get an AG-UI endpoint.
2//!
3//! This crate depends on no LLM client. The .NET SDK can build on
4//! `Microsoft.Extensions.AI` because .NET has one blessed chat abstraction;
5//! Rust has `async-openai`, `rig-core` and `genai` with no winner, so binding
6//! to any of them would make this crate useless to two thirds of the ecosystem.
7//! A framework integration is an `impl Agent for …` in its own crate.
8
9use std::future::Future;
10use std::pin::Pin;
11use std::sync::Arc;
12
13use crate::RunOutcome;
14use serde::Serialize;
15use serde::de::DeserializeOwned;
16
17use crate::server::context::RunContext;
18use crate::server::error::Result;
19
20/// What a run's shared state must be.
21///
22/// A blanket implementation covers every type that qualifies; you never write
23/// `impl AgentState`. Use `()` when the agent keeps no state.
24pub trait AgentState: Serialize + DeserializeOwned + Default + Send {}
25
26impl<T> AgentState for T where T: Serialize + DeserializeOwned + Default + Send {}
27
28/// An agent that can serve one AG-UI run.
29///
30/// This is the *hosting* side of the word. The consuming side —
31/// a handle onto somebody else's agent — is
32/// `client::RemoteAgent`, deliberately spelled differently so that an
33/// agent which calls another agent can import both.
34///
35/// ```
36/// use ag_ui::RunOutcome;
37/// use ag_ui::server::{Agent, Result, RunContext};
38///
39/// struct Echo;
40///
41/// impl Agent for Echo {
42///     type State = ();
43///
44///     async fn run(&self, ctx: &mut RunContext<()>) -> Result<RunOutcome> {
45///         let mut message = ctx.assistant_message()?;
46///         message.delta("you said something")?;
47///         message.end()?;
48///         Ok(RunOutcome::Success)
49///     }
50/// }
51/// ```
52///
53/// # Why `async fn` and not `#[async_trait]`
54///
55/// The trait uses a native `-> impl Future + Send` return (an RPITIT), so
56/// implementations are plain `async fn` with no macro, no `Box::pin` per call
57/// and no allocation. The cost is that the trait is not `dyn`-compatible; when
58/// you need `Box<dyn …>` — a registry of agents behind one endpoint, say —
59/// [`DynAgent`] is the boxed adapter, and [`BoxAgent`] implements `Agent`
60/// again, so the driver takes it like any other.
61///
62/// # Why `&mut RunContext` and not `RunContext`
63///
64/// The driver has to emit `RUN_FINISHED` or `RUN_ERROR` *after* the agent
65/// returns, through the same transformer chain and the same ordering verifier
66/// the agent used. Handing the context over by value would drop both with the
67/// agent's last statement.
68pub trait Agent: Send + Sync {
69    /// The run's shared state, deserialized from
70    /// [`RunAgentInput::state`](crate::input::RunAgentInput::state) and published
71    /// through [`RunContext::set_state`].
72    type State: AgentState;
73
74    /// Serves one run.
75    ///
76    /// Returning `Ok(RunOutcome::Success)` finishes the run;
77    /// `Ok(RunOutcome::Interrupt { .. })` pauses it for human input; `Err`
78    /// becomes a `RUN_ERROR` event, never a panic and never a truncated
79    /// stream.
80    fn run(
81        &self,
82        ctx: &mut RunContext<Self::State>,
83    ) -> impl Future<Output = Result<RunOutcome>> + Send;
84}
85
86/// The `dyn`-compatible form of [`Agent`].
87///
88/// Implemented for every `Agent`, so `Box::new(my_agent) as BoxAgent<_>` just
89/// works. The only difference is one boxed future per run.
90pub trait DynAgent: Send + Sync {
91    /// The run's shared state — see [`Agent::State`].
92    type State: AgentState;
93
94    /// Serves one run, boxing the future so the trait stays object-safe.
95    fn run_boxed<'a>(
96        &'a self,
97        ctx: &'a mut RunContext<Self::State>,
98    ) -> Pin<Box<dyn Future<Output = Result<RunOutcome>> + Send + 'a>>;
99}
100
101impl<A: Agent> DynAgent for A {
102    type State = A::State;
103
104    fn run_boxed<'a>(
105        &'a self,
106        ctx: &'a mut RunContext<Self::State>,
107    ) -> Pin<Box<dyn Future<Output = Result<RunOutcome>> + Send + 'a>> {
108        Box::pin(self.run(ctx))
109    }
110}
111
112/// A type-erased agent over state `S`.
113///
114/// ```
115/// # use ag_ui::RunOutcome;
116/// # use ag_ui::server::{Agent, BoxAgent, Result, RunContext};
117/// struct Fixed(&'static str);
118///
119/// impl Agent for Fixed {
120///     type State = ();
121///     async fn run(&self, ctx: &mut RunContext<()>) -> Result<RunOutcome> {
122///         ctx.say(self.0)?;
123///         Ok(RunOutcome::Success)
124///     }
125/// }
126///
127/// let agents: Vec<BoxAgent<()>> = vec![Box::new(Fixed("a")), Box::new(Fixed("b"))];
128/// assert_eq!(agents.len(), 2);
129/// ```
130pub type BoxAgent<S> = Box<dyn DynAgent<State = S>>;
131
132impl<S: AgentState> Agent for BoxAgent<S> {
133    type State = S;
134
135    async fn run(&self, ctx: &mut RunContext<Self::State>) -> Result<RunOutcome> {
136        (**self).run_boxed(ctx).await
137    }
138}
139
140impl<A: Agent> Agent for &A {
141    type State = A::State;
142
143    async fn run(&self, ctx: &mut RunContext<Self::State>) -> Result<RunOutcome> {
144        (**self).run(ctx).await
145    }
146}
147
148impl<A: Agent> Agent for Arc<A> {
149    type State = A::State;
150
151    async fn run(&self, ctx: &mut RunContext<Self::State>) -> Result<RunOutcome> {
152        (**self).run(ctx).await
153    }
154}