Skip to main content

ag_ui/client/transport/
http.rs

1//! The `reqwest`-backed HTTP transport.
2//!
3//! One POST of the [`RunAgentInput`] as JSON, one `text/event-stream` response
4//! decoded by [`crate::client::transport::sse`]. This module is the only place in the
5//! crate that pulls in an HTTP client, and it sits behind the `http` feature so
6//! that a wasm or custom-transport build never sees it.
7
8use futures_util::StreamExt;
9use std::time::Duration;
10
11use crate::{RunAgentInput, SSE_MEDIA_TYPE};
12use reqwest::header::{ACCEPT, CONTENT_TYPE, HeaderMap, HeaderName, HeaderValue};
13use reqwest::{Client, Url};
14
15use crate::client::error::{Error, Result};
16use crate::client::transport::sse::decode_raw_events;
17use crate::client::transport::{Transport, TransportFuture, TransportStream};
18
19/// Maximum number of response bytes retained before decoding an HTTP error body.
20const MAX_ERROR_BODY: usize = 2048;
21/// Total budget for reading a non-success response body, not an SSE run.
22const ERROR_BODY_TIMEOUT: Duration = Duration::from_secs(1);
23
24/// POSTs a run to an HTTP endpoint and streams the response.
25#[derive(Clone)]
26pub struct HttpTransport {
27    client: Client,
28    url: Url,
29    headers: HeaderMap,
30    timeout: Option<Duration>,
31}
32
33impl std::fmt::Debug for HttpTransport {
34    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
35        f.debug_struct("HttpTransport")
36            .field("timeout", &self.timeout)
37            .field("headers", &"<redacted>")
38            .finish_non_exhaustive()
39    }
40}
41
42impl HttpTransport {
43    /// A transport pointed at an agent's run endpoint, with default settings.
44    /// The default client does not follow redirects.
45    ///
46    /// # Errors
47    ///
48    /// [`Error::Config`] when the URL does not parse, or the HTTP client cannot
49    /// be built, or remote HTTP credentials require explicit opt-in.
50    pub fn new(url: impl AsRef<str>) -> Result<Self> {
51        Self::builder(url).build()
52    }
53
54    /// A builder, for headers, timeouts, or a pre-configured client.
55    pub fn builder(url: impl AsRef<str>) -> HttpTransportBuilder {
56        HttpTransportBuilder::new(url)
57    }
58
59    /// The endpoint this transport posts to.
60    pub fn url(&self) -> &Url {
61        &self.url
62    }
63
64    /// The headers sent with every run.
65    pub fn headers(&self) -> &HeaderMap {
66        &self.headers
67    }
68}
69
70impl Transport for HttpTransport {
71    fn run(&self, input: RunAgentInput) -> TransportFuture {
72        // Cloned rather than borrowed so the future outlives this call; see the
73        // note on [`Transport`]. A `reqwest::Client` is an `Arc` inside.
74        let client = self.client.clone();
75        let url = self.url.clone();
76        let headers = self.headers.clone();
77        let timeout = self.timeout;
78
79        Box::pin(async move {
80            let input = crate::client::agent::outgoing_json(input, &mut Vec::new())?;
81            let mut request = client.post(url).headers(headers).json(&input);
82            if let Some(timeout) = timeout {
83                request = request.timeout(timeout);
84            }
85
86            let response = request
87                .send()
88                .await
89                .map_err(|error| Error::transport(error.without_url()))?;
90            let status = response.status();
91            if !status.is_success() {
92                let mut stream = response.bytes_stream();
93                let mut body = Vec::with_capacity(MAX_ERROR_BODY);
94                let _ = tokio::time::timeout(ERROR_BODY_TIMEOUT, async {
95                    while body.len() < MAX_ERROR_BODY {
96                        let Some(Ok(chunk)) = stream.next().await else {
97                            break;
98                        };
99                        let remaining = MAX_ERROR_BODY - body.len();
100                        body.extend_from_slice(&chunk[..chunk.len().min(remaining)]);
101                    }
102                })
103                .await;
104                return Err(Error::Http {
105                    status: status.as_u16(),
106                    body: String::from_utf8_lossy(&body).into_owned(),
107                });
108            }
109
110            let content_type = response.headers().get(CONTENT_TYPE);
111            let is_sse = content_type
112                .and_then(|value| value.to_str().ok())
113                .and_then(|value| value.split(';').next())
114                .is_some_and(|value| value.trim().eq_ignore_ascii_case(SSE_MEDIA_TYPE));
115            if !is_sse {
116                let actual = match content_type {
117                    Some(value) => value
118                        .to_str()
119                        .map(str::to_owned)
120                        .unwrap_or_else(|_| "<non-UTF-8>".to_owned()),
121                    None => "<missing>".to_owned(),
122                };
123                return Err(Error::UnexpectedContentType(actual));
124            }
125
126            Ok(TransportStream::json(decode_raw_events(
127                response.bytes_stream(),
128            )))
129        })
130    }
131}
132
133/// Builds an [`HttpTransport`].
134///
135/// Header values are validated when [`HttpTransportBuilder::build`] is called,
136/// so a chain of setters stays a chain and does not thread a `Result` through
137/// every step.
138#[derive(Clone)]
139pub struct HttpTransportBuilder {
140    url: String,
141    headers: Vec<(String, String)>,
142    timeout: Option<Duration>,
143    connect_timeout: Option<Duration>,
144    client: Option<Client>,
145    allow_insecure_http: bool,
146}
147
148impl std::fmt::Debug for HttpTransportBuilder {
149    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
150        f.debug_struct("HttpTransportBuilder")
151            .field("timeout", &self.timeout)
152            .field("connect_timeout", &self.connect_timeout)
153            .field("headers", &"<redacted>")
154            .finish_non_exhaustive()
155    }
156}
157
158impl HttpTransportBuilder {
159    /// A builder for an agent at `url`.
160    pub fn new(url: impl AsRef<str>) -> Self {
161        Self {
162            url: url.as_ref().to_owned(),
163            headers: Vec::new(),
164            timeout: None,
165            connect_timeout: None,
166            client: None,
167            allow_insecure_http: false,
168        }
169    }
170
171    /// Adds a header to every request — an API key, a tenant id, a trace
172    /// header.
173    #[must_use]
174    pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
175        self.headers.push((name.into(), value.into()));
176        self
177    }
178
179    /// Adds several headers.
180    #[must_use]
181    pub fn headers<K, V>(mut self, headers: impl IntoIterator<Item = (K, V)>) -> Self
182    where
183        K: Into<String>,
184        V: Into<String>,
185    {
186        self.headers
187            .extend(headers.into_iter().map(|(k, v)| (k.into(), v.into())));
188        self
189    }
190
191    /// Bounds the whole run: connecting, headers, *and* streaming the body.
192    ///
193    /// An agent that thinks for longer than this has its stream cut off, so a
194    /// long-running agent wants [`HttpTransportBuilder::connect_timeout`]
195    /// instead.
196    #[must_use]
197    pub fn timeout(mut self, timeout: Duration) -> Self {
198        self.timeout = Some(timeout);
199        self
200    }
201
202    /// Bounds only connection setup, leaving the stream itself unbounded.
203    #[must_use]
204    pub fn connect_timeout(mut self, timeout: Duration) -> Self {
205        self.connect_timeout = Some(timeout);
206        self
207    }
208
209    /// Allows custom headers, URL user information, query strings, or a custom
210    /// client on a remote HTTP connection. These can carry credentials. HTTPS
211    /// and loopback HTTP endpoints can use them by default.
212    #[must_use]
213    pub fn allow_insecure_http(mut self, allow: bool) -> Self {
214        self.allow_insecure_http = allow;
215        self
216    }
217
218    /// Uses a caller-supplied client, for proxies, custom TLS roots, or a
219    /// connection pool shared with the rest of an application.
220    ///
221    /// The supplied client retains its redirect policy. Choose that policy
222    /// carefully: redirects can resend the request body and custom headers.
223    #[must_use]
224    pub fn client(mut self, client: Client) -> Self {
225        self.client = Some(client);
226        self
227    }
228
229    /// Builds the transport.
230    ///
231    /// # Errors
232    ///
233    /// [`Error::Config`] when the URL, a header name, or a header value is not
234    /// valid, when remote HTTP requires [explicit opt-in](Self::allow_insecure_http),
235    /// or when the HTTP client cannot be built.
236    pub fn build(self) -> Result<HttpTransport> {
237        let url = Url::parse(&self.url)
238            .map_err(|error| Error::Config(format!("invalid endpoint URL: {error}")))?;
239
240        if !matches!(url.scheme(), "http" | "https") {
241            return Err(Error::Config("expected an HTTP or HTTPS endpoint".into()));
242        }
243        if url.scheme() == "http"
244            && !self.allow_insecure_http
245            && (!self.headers.is_empty()
246                || self.client.is_some()
247                || !url.username().is_empty()
248                || url.password().is_some()
249                || url.query().is_some())
250            && !is_loopback(&url)
251        {
252            return Err(Error::Config(
253                "remote HTTP endpoints with custom headers, a custom client, user information or a query require HTTPS or allow_insecure_http(true)".into()
254            ));
255        }
256
257        let mut headers = HeaderMap::with_capacity(self.headers.len() + 1);
258        headers.insert(ACCEPT, HeaderValue::from_static(SSE_MEDIA_TYPE));
259        for (name, value) in self.headers {
260            let name = HeaderName::try_from(name.as_str())
261                .map_err(|error| Error::Config(format!("invalid header name {name:?}: {error}")))?;
262            let mut value = HeaderValue::try_from(value.as_str()).map_err(|error| {
263                Error::Config(format!("invalid value for header {name:?}: {error}"))
264            })?;
265            value.set_sensitive(true);
266            headers.insert(name, value);
267        }
268
269        let client = match self.client {
270            Some(client) => client,
271            None => {
272                let mut builder = Client::builder().redirect(reqwest::redirect::Policy::none());
273                if let Some(timeout) = self.connect_timeout {
274                    builder = builder.connect_timeout(timeout);
275                }
276                builder.build().map_err(|error| {
277                    Error::Config(format!("could not build HTTP client: {error}"))
278                })?
279            }
280        };
281
282        Ok(HttpTransport {
283            client,
284            url,
285            headers,
286            timeout: self.timeout,
287        })
288    }
289}
290
291/// The URL parser normalizes IPv4 spellings and brackets IPv6 literals.
292fn is_loopback(url: &Url) -> bool {
293    let Some(host) = url.host_str() else {
294        return false;
295    };
296    host.trim_end_matches('.').eq_ignore_ascii_case("localhost")
297        || host
298            .trim_start_matches('[')
299            .trim_end_matches(']')
300            .parse::<std::net::IpAddr>()
301            .is_ok_and(|address| address.is_loopback())
302}