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 calls
6//! [`Transport::run`] and takes
7//! [`TransportStream::into_json`](crate::client::transport::TransportStream::into_json).
8//!
9//! For a UI, [`Thread`](crate::client::Thread) sits on top of this and does the
10//! assembling.
11//!
12//! ```no_run
13//! # #[cfg(feature = "http")]
14//! # async fn example() -> Result<(), ag_ui::client::Error> {
15//! use ag_ui::client::{HttpAgent, RunParams};
16//! use futures_util::StreamExt;
17//!
18//! let agent = HttpAgent::builder("https://example.com/agent")
19//!     .header("authorization", "Bearer …")
20//!     .build()?;
21//!
22//! let mut events = agent.run_events(
23//!     RunParams::new("thread-1", "run-1").user("msg-1", "What is the weather?"),
24//! );
25//!
26//! while let Some(event) = events.next().await {
27//!     println!("{:?}", event?.event_type());
28//! }
29//! # Ok(())
30//! # }
31//! ```
32
33use crate::{
34    Context, Message, MessageId, ResumeEntry, RunAgentInput, RunId, ThreadId, Tool, UserContent,
35};
36use futures_util::TryStreamExt;
37use serde_json::Value;
38
39use crate::client::transport::{EventStream, Transport, TransportStream};
40
41use crate::client::error::{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
184impl<T: Transport> RemoteAgent<T> {
185    /// Starts a run and streams events after compatibility and enforcement.
186    ///
187    /// Chunks remain chunks; ordering is not verified or assembled here. A UI
188    /// wants [`Thread`](crate::client::Thread), while a proxy needing original
189    /// fields calls [`Transport::run`] and takes
190    /// [`TransportStream::into_json`].
191    ///
192    /// Connecting is folded into the stream: a transport that cannot reach the
193    /// agent yields one error item and ends.
194    ///
195    /// The boundary's warnings are discarded here. A `Thread` reports them;
196    /// [`TransportStream::into_events`] over [`Transport::run`] hands them to
197    /// a callback.
198    ///
199    /// The request omits activity messages, which belong to the local rendering
200    /// history, and upgrades legacy `binary` content to its 1.0 media part.
201    pub fn run_events(&self, params: impl Into<RunAgentInput>) -> EventStream {
202        let input = match outgoing(params.into(), &mut Vec::new()) {
203            Ok(input) => input,
204            Err(error) => return Box::pin(futures_util::stream::once(async { Err(error) })),
205        };
206        Box::pin(crate::client::enforce::unchecked(
207            self.run_checked(input),
208            |_| {},
209        ))
210    }
211
212    /// [`Self::run_events`] with the boundary's warnings left in the stream.
213    pub(crate) fn run_checked(
214        &self,
215        input: RunAgentInput,
216    ) -> crate::client::enforce::CheckedStream {
217        let connecting = self.transport.run(input);
218        Box::pin(
219            futures_util::stream::once(connecting)
220                .map_ok(TransportStream::into_checked)
221                .try_flatten(),
222        )
223    }
224}
225
226/// Translates retired content, then applies the outgoing 1.0 schema before
227/// handing a typed request to a transport. The original conversation is kept.
228pub(crate) fn outgoing(input: RunAgentInput, warnings: &mut Vec<String>) -> Result<RunAgentInput> {
229    Ok(serde_json::from_value(outgoing_json(input, warnings)?)?)
230}
231
232/// The wire form used by the HTTP transport, including direct Transport::run calls.
233pub(crate) fn outgoing_json(mut input: RunAgentInput, warnings: &mut Vec<String>) -> Result<Value> {
234    input
235        .messages
236        .retain(|message| !matches!(message, Message::Activity(_)));
237    crate::message::upgrade_legacy_content(&mut input.messages);
238    crate::protocol::input(serde_json::to_value(input)?, warnings).map_err(Error::Request)
239}
240
241/// An HTTP endpoint and reusable connection settings. Create independent local
242/// conversations with [`HttpAgent::thread`], or consume typed events with
243/// `run_events`.
244#[cfg(feature = "http")]
245#[derive(Clone, Debug)]
246pub struct HttpAgent {
247    agent: RemoteAgent<std::sync::Arc<HttpTransport>>,
248}
249
250#[cfg(feature = "http")]
251impl HttpAgent {
252    /// Connect to `url` using default settings. No request is made yet.
253    pub fn new(url: impl AsRef<str>) -> Result<Self> {
254        Ok(Self::from_transport(HttpTransport::new(url)?))
255    }
256    /// Use a caller-configured HTTP transport.
257    pub fn from_transport(transport: HttpTransport) -> Self {
258        Self {
259            agent: RemoteAgent::new(std::sync::Arc::new(transport)),
260        }
261    }
262    /// Configure headers, timeouts and the underlying HTTP client.
263    pub fn builder(url: impl AsRef<str>) -> HttpAgentBuilder {
264        HttpAgentBuilder {
265            transport: HttpTransport::builder(url),
266        }
267    }
268    /// An independent local conversation. This does not retrieve remote history.
269    pub fn thread(&self, id: impl Into<ThreadId>) -> crate::client::Thread<HttpTransport> {
270        crate::client::Thread::from_shared(self.agent.transport().clone(), id)
271    }
272    /// Initialize a typed conversation using a serializable state value.
273    pub fn thread_with_state<S: serde::Serialize + serde::de::DeserializeOwned>(
274        &self,
275        id: impl Into<ThreadId>,
276        state: S,
277    ) -> Result<crate::client::Thread<HttpTransport, S>> {
278        self.thread_builder(id)
279            .state(serde_json::to_value(state)?)
280            .build()
281    }
282    /// Configure initial history, state, tools, diagnostics and verification.
283    pub fn thread_builder<S>(
284        &self,
285        id: impl Into<ThreadId>,
286    ) -> crate::client::ThreadBuilder<HttpTransport, S> {
287        crate::client::ThreadBuilder::from_shared(self.agent.transport().clone(), id)
288    }
289    /// Restore a saved local JSON conversation with this endpoint's transport.
290    pub fn restore_thread(
291        &self,
292        snapshot: crate::client::ThreadSnapshot,
293    ) -> Result<crate::client::Thread<HttpTransport>> {
294        self.restore_thread_with_state(snapshot)
295    }
296    /// Restore and validate the current raw state against `S`.
297    pub fn restore_thread_with_state<S: serde::de::DeserializeOwned>(
298        &self,
299        snapshot: crate::client::ThreadSnapshot,
300    ) -> Result<crate::client::Thread<HttpTransport, S>> {
301        crate::client::Thread::restore_shared(self.agent.transport().clone(), snapshot)
302    }
303    /// Typed events after compatibility translation and schema enforcement.
304    /// Chunks are not assembled or applied to conversation state here. Use
305    /// [`Transport::run`] and [`TransportStream::into_json`] to inspect the
306    /// original wire JSON.
307    pub fn run_events(&self, params: impl Into<RunAgentInput>) -> EventStream {
308        self.agent.run_events(params)
309    }
310    /// Underlying transport settings.
311    pub fn transport(&self) -> &HttpTransport {
312        self.agent.transport()
313    }
314}
315
316/// Builds an [`HttpAgent`]: base URL, headers, timeouts.
317#[cfg(feature = "http")]
318#[derive(Clone, Debug)]
319pub struct HttpAgentBuilder {
320    transport: HttpTransportBuilder,
321}
322
323#[cfg(feature = "http")]
324impl HttpAgentBuilder {
325    /// Adds a header to every request.
326    #[must_use]
327    pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
328        self.transport = self.transport.header(name, value);
329        self
330    }
331
332    /// Adds several headers.
333    #[must_use]
334    pub fn headers<K, V>(mut self, headers: impl IntoIterator<Item = (K, V)>) -> Self
335    where
336        K: Into<String>,
337        V: Into<String>,
338    {
339        self.transport = self.transport.headers(headers);
340        self
341    }
342
343    /// Bounds the whole run, streaming included.
344    #[must_use]
345    pub fn timeout(mut self, timeout: std::time::Duration) -> Self {
346        self.transport = self.transport.timeout(timeout);
347        self
348    }
349
350    /// Bounds connection setup only, leaving the stream unbounded.
351    #[must_use]
352    pub fn connect_timeout(mut self, timeout: std::time::Duration) -> Self {
353        self.transport = self.transport.connect_timeout(timeout);
354        self
355    }
356
357    /// Allows configured headers or URL credentials on a remote HTTP endpoint.
358    /// See [`HttpTransportBuilder::allow_insecure_http`].
359    #[must_use]
360    pub fn allow_insecure_http(mut self, allow: bool) -> Self {
361        self.transport = self.transport.allow_insecure_http(allow);
362        self
363    }
364
365    /// Uses a caller-supplied `reqwest` client.
366    #[must_use]
367    pub fn client(mut self, client: reqwest::Client) -> Self {
368        self.transport = self.transport.client(client);
369        self
370    }
371
372    /// Builds the agent.
373    ///
374    /// # Errors
375    ///
376    /// [`Error::Config`] when the URL or a header is not
377    /// valid.
378    pub fn build(self) -> Result<HttpAgent> {
379        Ok(HttpAgent::from_transport(self.transport.build()?))
380    }
381}