Skip to main content

ag_ui/client/
agent.rs

1//! The low-level API: start a run, get its events.
2//!
3//! [`RemoteAgent`] adds almost nothing to [`Transport`] — a request builder, and
4//! a stream that flattens connecting into streaming. It delivers checked typed
5//! events; a proxy or recorder needing the original JSON uses
6//! [`Transport::run_raw`].
7//!
8//! For a UI, [`Thread`](crate::client::Thread) sits on top of this and does the
9//! assembling.
10//!
11//! ```no_run
12//! # #[cfg(feature = "http")]
13//! # async fn example() -> Result<(), ag_ui::client::Error> {
14//! use ag_ui::client::{HttpAgent, RunParams};
15//! use futures_util::StreamExt;
16//!
17//! let agent = HttpAgent::builder("https://example.com/agent")
18//!     .header("authorization", "Bearer …")
19//!     .build()?;
20//!
21//! let mut events = agent.run_events(
22//!     RunParams::new("thread-1", "run-1").user("msg-1", "What is the weather?"),
23//! );
24//!
25//! while let Some(event) = events.next().await {
26//!     println!("{:?}", event?.event_type());
27//! }
28//! # Ok(())
29//! # }
30//! ```
31
32use crate::{
33    Context, Message, MessageId, ResumeEntry, RunAgentInput, RunId, ThreadId, Tool, UserContent,
34};
35use futures_util::TryStreamExt;
36use serde_json::Value;
37
38use crate::client::transport::{EventStream, Transport, boxed_stream};
39
40#[cfg(feature = "http")]
41use crate::client::error::Result;
42#[cfg(feature = "http")]
43use crate::client::transport::{HttpTransport, HttpTransportBuilder};
44
45/// What to send when starting a run.
46///
47/// A builder over [`RunAgentInput`]: the two ids are required, everything else
48/// has a sensible empty default. `agent.run_events(…)` takes anything that converts
49/// into the input, so a hand-built [`RunAgentInput`] works just as well.
50///
51/// [`RunAgentInput`]: crate::input::RunAgentInput
52#[derive(Clone, Debug, Default, PartialEq)]
53pub struct RunParams {
54    input: RunAgentInput,
55}
56
57impl RunParams {
58    /// A run in `thread_id`, identified by `run_id`.
59    pub fn new(thread_id: impl Into<ThreadId>, run_id: impl Into<RunId>) -> Self {
60        Self {
61            input: RunAgentInput::new(thread_id, run_id),
62        }
63    }
64
65    /// Sets the conversation history, oldest first.
66    #[must_use]
67    pub fn messages(mut self, messages: impl Into<Vec<Message>>) -> Self {
68        self.input.messages = messages.into();
69        self
70    }
71
72    /// Appends one message.
73    #[must_use]
74    pub fn message(mut self, message: impl Into<Message>) -> Self {
75        self.input.messages.push(message.into());
76        self
77    }
78
79    /// Appends a user message — the common case, spelled short.
80    #[must_use]
81    pub fn user(self, id: impl Into<MessageId>, content: impl Into<UserContent>) -> Self {
82        self.message(Message::user(id, content))
83    }
84
85    /// Sets the shared state the agent starts from.
86    #[must_use]
87    pub fn state(mut self, state: impl Into<Value>) -> Self {
88        self.input.state = state.into();
89        self
90    }
91
92    /// Offers tools for this run.
93    #[must_use]
94    pub fn tools(mut self, tools: impl Into<Vec<Tool>>) -> Self {
95        self.input.tools = tools.into();
96        self
97    }
98
99    /// Sets the ambient context entries.
100    #[must_use]
101    pub fn context(mut self, context: impl Into<Vec<Context>>) -> Self {
102        self.input.context = context.into();
103        self
104    }
105
106    /// Sets the passthrough properties, which the protocol never interprets.
107    #[must_use]
108    pub fn forwarded_props(mut self, props: impl Into<Value>) -> Self {
109        self.input.forwarded_props = props.into();
110        self
111    }
112
113    /// Answers the interrupts a previous run paused on. See
114    /// [`crate::client::interrupts`].
115    #[must_use]
116    pub fn resume(mut self, entries: impl Into<Vec<ResumeEntry>>) -> Self {
117        self.input.resume = Some(entries.into());
118        self
119    }
120
121    /// Records the run that spawned this one, for nested agents.
122    #[must_use]
123    pub fn parent_run_id(mut self, run_id: impl Into<RunId>) -> Self {
124        self.input.parent_run_id = Some(run_id.into());
125        self
126    }
127
128    /// Declares the version sent in the run input. Pass `None` for a known
129    /// legacy peer whose request parser cannot accept `protocolVersion`.
130    #[must_use]
131    pub fn protocol_version(mut self, version: Option<String>) -> Self {
132        self.input.protocol_version = version;
133        self
134    }
135
136    /// The request this describes.
137    pub fn into_input(self) -> RunAgentInput {
138        self.input
139    }
140}
141
142impl From<RunParams> for RunAgentInput {
143    fn from(params: RunParams) -> Self {
144        params.input
145    }
146}
147
148impl From<RunAgentInput> for RunParams {
149    fn from(input: RunAgentInput) -> Self {
150        Self { input }
151    }
152}
153
154/// A checked typed event interface over any [`Transport`]. HTTP, an in-process
155/// agent or a recorded fixture can supply events without state management.
156///
157/// # Not `crate::server::Agent`
158///
159/// The client and server APIs sit on opposite ends of the same wire, and the word "agent"
160/// means the opposite thing at each end, so they do not share a name.
161/// `crate::server::Agent` is a *trait you implement* to be an agent;
162/// `RemoteAgent` is a *handle you hold* onto someone else's. An agent that calls
163/// another agent — the composition case — needs both in one file, and
164/// `impl Agent for X { … self.upstream: RemoteAgent<_> … }` reads correctly
165/// only because they are spelled differently.
166///
167#[derive(Clone, Debug, Default)]
168pub struct RemoteAgent<T> {
169    transport: T,
170}
171
172impl<T> RemoteAgent<T> {
173    /// An agent reached through `transport`.
174    pub fn new(transport: T) -> Self {
175        Self { transport }
176    }
177
178    /// The transport underneath.
179    pub fn transport(&self) -> &T {
180        &self.transport
181    }
182
183    /// Unwraps the transport.
184    pub fn into_transport(self) -> T {
185        self.transport
186    }
187}
188
189impl<T: Transport> RemoteAgent<T> {
190    /// Starts a run and streams events after compatibility and enforcement.
191    ///
192    /// Chunks remain chunks; ordering is not verified or assembled here. A UI
193    /// wants [`Thread`](crate::client::Thread), while a proxy needing original
194    /// fields can call [`Transport::run_raw`].
195    ///
196    /// Connecting is folded into the stream: a transport that cannot reach the
197    /// agent yields one error item and ends.
198    pub fn run_events(&self, params: impl Into<RunAgentInput>) -> EventStream {
199        let connecting = self.transport.run_raw(params.into());
200        let raw = futures_util::stream::once(connecting).try_flatten();
201        boxed_stream(crate::client::enforce::stream(raw))
202    }
203}
204
205/// An HTTP endpoint and reusable connection settings. Create independent local
206/// conversations with [`HttpAgent::thread`], or consume typed events with
207/// `run_events`.
208#[cfg(feature = "http")]
209#[derive(Clone, Debug)]
210pub struct HttpAgent {
211    agent: RemoteAgent<std::sync::Arc<HttpTransport>>,
212}
213
214#[cfg(feature = "http")]
215impl HttpAgent {
216    /// Connect to `url` using default settings. No request is made yet.
217    pub fn new(url: impl AsRef<str>) -> Result<Self> {
218        Ok(Self::from_transport(HttpTransport::new(url)?))
219    }
220    /// Use a caller-configured HTTP transport.
221    pub fn from_transport(transport: HttpTransport) -> Self {
222        Self {
223            agent: RemoteAgent::new(std::sync::Arc::new(transport)),
224        }
225    }
226    /// Configure headers, timeouts and the underlying HTTP client.
227    pub fn builder(url: impl AsRef<str>) -> HttpAgentBuilder {
228        HttpAgentBuilder {
229            transport: HttpTransport::builder(url),
230        }
231    }
232    /// An independent local conversation. This does not retrieve remote history.
233    pub fn thread(&self, id: impl Into<ThreadId>) -> crate::client::Thread<HttpTransport> {
234        crate::client::Thread::from_shared(self.agent.transport().clone(), id)
235    }
236    /// Initialize a typed conversation using a serializable state value.
237    pub fn thread_with_state<S: serde::Serialize + serde::de::DeserializeOwned>(
238        &self,
239        id: impl Into<ThreadId>,
240        state: S,
241    ) -> Result<crate::client::Thread<HttpTransport, S>> {
242        self.thread_builder(id)
243            .state(serde_json::to_value(state)?)
244            .build()
245    }
246    /// Configure initial history, state, tools, diagnostics and verification.
247    pub fn thread_builder<S>(
248        &self,
249        id: impl Into<ThreadId>,
250    ) -> crate::client::ThreadBuilder<HttpTransport, S> {
251        crate::client::ThreadBuilder::from_shared(self.agent.transport().clone(), id)
252    }
253    /// Restore a saved local JSON conversation with this endpoint's transport.
254    pub fn restore_thread(
255        &self,
256        snapshot: crate::client::ThreadSnapshot,
257    ) -> Result<crate::client::Thread<HttpTransport>> {
258        self.restore_thread_with_state(snapshot)
259    }
260    /// Restore and validate the current raw state against `S`.
261    pub fn restore_thread_with_state<S: serde::de::DeserializeOwned>(
262        &self,
263        snapshot: crate::client::ThreadSnapshot,
264    ) -> Result<crate::client::Thread<HttpTransport, S>> {
265        crate::client::Thread::restore_shared(self.agent.transport().clone(), snapshot)
266    }
267    /// Typed events after compatibility translation and schema enforcement.
268    /// Chunks are not assembled or applied to conversation state here. Use
269    /// [`Transport::run_raw`] to inspect the original wire JSON.
270    pub fn run_events(&self, params: impl Into<RunAgentInput>) -> EventStream {
271        self.agent.run_events(params)
272    }
273    /// Underlying transport settings.
274    pub fn transport(&self) -> &HttpTransport {
275        self.agent.transport()
276    }
277}
278
279/// Builds an [`HttpAgent`]: base URL, headers, timeouts.
280#[cfg(feature = "http")]
281#[derive(Clone, Debug)]
282pub struct HttpAgentBuilder {
283    transport: HttpTransportBuilder,
284}
285
286#[cfg(feature = "http")]
287impl HttpAgentBuilder {
288    /// Adds a header to every request.
289    #[must_use]
290    pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
291        self.transport = self.transport.header(name, value);
292        self
293    }
294
295    /// Adds several headers.
296    #[must_use]
297    pub fn headers<K, V>(mut self, headers: impl IntoIterator<Item = (K, V)>) -> Self
298    where
299        K: Into<String>,
300        V: Into<String>,
301    {
302        self.transport = self.transport.headers(headers);
303        self
304    }
305
306    /// Bounds the whole run, streaming included.
307    #[must_use]
308    pub fn timeout(mut self, timeout: std::time::Duration) -> Self {
309        self.transport = self.transport.timeout(timeout);
310        self
311    }
312
313    /// Bounds connection setup only, leaving the stream unbounded.
314    #[must_use]
315    pub fn connect_timeout(mut self, timeout: std::time::Duration) -> Self {
316        self.transport = self.transport.connect_timeout(timeout);
317        self
318    }
319
320    /// Uses a caller-supplied `reqwest` client.
321    #[must_use]
322    pub fn client(mut self, client: reqwest::Client) -> Self {
323        self.transport = self.transport.client(client);
324        self
325    }
326
327    /// Builds the agent.
328    ///
329    /// # Errors
330    ///
331    /// [`Error::Config`](crate::client::Error::Config) when the URL or a header is not
332    /// valid.
333    pub fn build(self) -> Result<HttpAgent> {
334        Ok(HttpAgent::from_transport(self.transport.build()?))
335    }
336}