ante-llm 0.4.2

Streaming LLM client for Anthropic, OpenAI, Gemini and Chat Completions servers, from the Ante coding agent
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
// Copyright 2026 Antigma Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

//! The auth layer: places a connector's credential on its requests and
//! recovers once when the server rejects it.
//!
//! It knows no files, environment variables, subprocesses or OAuth endpoints.
//! A [`TokenSource`] supplies the token to send now and answers a rejection;
//! the application implements it over its credential store. The protocol is
//! this layer's: a 401 or 403 asks the source to recover once, and a
//! recovered token is sent once more.

use std::fmt;
use std::future::Future;
use std::sync::Arc;

use async_trait::async_trait;
use reqwest::header::{AUTHORIZATION, HeaderName, HeaderValue};
use reqwest::{RequestBuilder, Response, StatusCode};

use crate::error::{LlmError, LlmErrorKind};

/// What one request carries.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Token {
    pub value: String,
    /// Headers derived from the token, such as OpenAI's `chatgpt-account-id`.
    pub headers: Vec<(String, String)>,
}

/// Where a connector's token goes on a request.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Placement {
    /// `Authorization: Bearer <token>`.
    Bearer,
    /// The raw token in the named header, such as `x-api-key`.
    Header(String),
}

impl Placement {
    /// `req` with `value` placed.
    pub fn place(&self, req: RequestBuilder, value: &str) -> RequestBuilder {
        match self {
            Placement::Bearer => req.header(AUTHORIZATION, format!("Bearer {value}")),
            Placement::Header(name) => req.header(name, value),
        }
    }

    /// The header that carries `value`, for a transport that cannot go
    /// through a [`RequestBuilder`] (a WebSocket handshake).
    fn header(&self, value: &str) -> Result<(HeaderName, HeaderValue), LlmError> {
        match self {
            Placement::Bearer => header(AUTHORIZATION.as_str(), &format!("Bearer {value}")),
            Placement::Header(name) => header(name, value),
        }
    }
}

/// `name: value` as a typed header.
fn header(name: &str, value: &str) -> Result<(HeaderName, HeaderValue), LlmError> {
    let value = HeaderValue::from_str(value).map_err(|_| {
        LlmError::message(LlmErrorKind::Auth, format!("invalid value for header {name}"))
    })?;
    let name = HeaderName::from_bytes(name.as_bytes()).map_err(|_| {
        LlmError::message(LlmErrorKind::Auth, format!("invalid header name {name}"))
    })?;
    Ok((name, value))
}

/// How the server answered a credential: the two statuses that ask the
/// source to recover.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Rejection {
    /// 401: the credential itself was refused.
    Unauthorized,
    /// 403: the credential was accepted but does not grant the request.
    Forbidden,
}

impl Rejection {
    pub(crate) fn from_status(status: StatusCode) -> Option<Self> {
        match status {
            StatusCode::UNAUTHORIZED => Some(Self::Unauthorized),
            StatusCode::FORBIDDEN => Some(Self::Forbidden),
            _ => None,
        }
    }
}

/// What authenticates a connector: the token to send now, and what to do
/// when the server rejects it.
#[async_trait]
pub trait TokenSource: fmt::Debug + Send + Sync {
    /// The token to send now; `None` when the connector sends no credential.
    async fn token(&self) -> Result<Option<Token>, LlmError>;

    /// The server answered `rejection` to a request that carried `sent`.
    /// `true` when there is a new token to send it again with.
    async fn recover(&self, rejection: Rejection, sent: &Token) -> Result<bool, LlmError>;
}

impl dyn TokenSource + '_ {
    /// Run `call` with the token to send now, and once more with a recovered
    /// token when `rejected` reads a rejection off the outcome and the
    /// source recovers. The outcome of the last call is returned; only the
    /// source's own failures are errors here.
    pub async fn call<T, F, Fut>(
        &self,
        mut call: F,
        rejected: impl Fn(&T) -> Option<Rejection>,
    ) -> Result<T, LlmError>
    where
        F: FnMut(Option<Token>) -> Fut,
        Fut: Future<Output = T>,
    {
        let token = self.token().await?;
        let outcome = call(token.clone()).await;
        let (Some(rejection), Some(sent)) = (rejected(&outcome), token) else {
            return Ok(outcome);
        };
        if !self.recover(rejection, &sent).await? {
            return Ok(outcome);
        }
        tracing::info!(?rejection, "recovered credential; resending");
        Ok(call(self.token().await?).await)
    }
}

/// Sends no credential.
#[derive(Debug)]
struct Unauthenticated;

#[async_trait]
impl TokenSource for Unauthenticated {
    async fn token(&self) -> Result<Option<Token>, LlmError> {
        Ok(None)
    }

    async fn recover(&self, _rejection: Rejection, _sent: &Token) -> Result<bool, LlmError> {
        Ok(false)
    }
}

/// Sends one fixed key, such as an API key. A rejection of it is final:
/// there is nothing to refresh.
struct StaticKey(String);

/// The key stays out of logs.
impl fmt::Debug for StaticKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("StaticKey(..)")
    }
}

#[async_trait]
impl TokenSource for StaticKey {
    async fn token(&self) -> Result<Option<Token>, LlmError> {
        Ok(Some(Token { value: self.0.clone(), headers: Vec::new() }))
    }

    async fn recover(&self, _rejection: Rejection, _sent: &Token) -> Result<bool, LlmError> {
        Ok(false)
    }
}

/// An HTTP client that authenticates as one connector: every request carries
/// the token its source supplies, placed the connector's way, and a
/// rejection is answered with one recovery and one resend.
#[derive(Debug, Clone)]
pub struct AuthedClient {
    http: reqwest::Client,
    placement: Placement,
    source: Arc<dyn TokenSource>,
}

impl AuthedClient {
    pub fn new(http: reqwest::Client, placement: Placement, source: Arc<dyn TokenSource>) -> Self {
        Self { http, placement, source }
    }

    /// A client that sends the same `key` on every request, such as an API
    /// key. A request the server rejects is not sent again.
    pub fn static_key(http: reqwest::Client, placement: Placement, key: impl Into<String>) -> Self {
        Self::new(http, placement, Arc::new(StaticKey(key.into())))
    }

    /// A client that sends no credential.
    pub fn unauthenticated(http: reqwest::Client) -> Self {
        Self::new(http, Placement::Bearer, Arc::new(Unauthenticated))
    }

    /// The credential source, for a transport that cannot go through
    /// reqwest's [`RequestBuilder`] and runs the protocol itself.
    pub fn source(&self) -> &dyn TokenSource {
        &*self.source
    }

    /// The HTTP client, for the same transport.
    pub fn http(&self) -> &reqwest::Client {
        &self.http
    }

    /// The headers that carry `token` the way this client places it, with
    /// the token's derived headers.
    pub fn headers(&self, token: &Token) -> Result<Vec<(HeaderName, HeaderValue)>, LlmError> {
        std::iter::once(self.placement.header(&token.value))
            .chain(token.headers.iter().map(|(name, value)| header(name, value)))
            .collect()
    }

    /// Send the request `make` builds, with the token placed. The inner
    /// result is reqwest's; the outer error is the source's.
    pub async fn send(
        &self,
        mut make: impl FnMut(&reqwest::Client) -> RequestBuilder,
    ) -> Result<Result<Response, reqwest::Error>, LlmError> {
        self.source
            .call(
                |token| {
                    let req = make(&self.http);
                    let req =
                        match &token {
                            Some(token) => token.headers.iter().fold(
                                self.placement.place(req, &token.value),
                                |req, (name, value)| req.header(name, value),
                            ),
                            None => req,
                        };
                    req.send()
                },
                |outcome| {
                    outcome
                        .as_ref()
                        .ok()
                        .and_then(|response| Rejection::from_status(response.status()))
                },
            )
            .await
    }
}

#[cfg(test)]
pub(crate) mod test_support {
    use std::sync::Mutex;

    use super::*;

    /// A source over a fixed list of tokens: `token` returns the current
    /// one, `recover` records the rejection and moves to the next.
    #[derive(Debug)]
    pub struct StubSource {
        tokens: Vec<Token>,
        current: Mutex<usize>,
        /// Each rejection with the value it answered.
        pub rejections: Mutex<Vec<(Rejection, String)>>,
    }

    impl StubSource {
        pub fn new(tokens: impl IntoIterator<Item = &'static str>) -> Self {
            let tokens = tokens
                .into_iter()
                .map(|value| Token { value: value.to_string(), headers: Vec::new() })
                .collect();
            Self { tokens, current: Mutex::new(0), rejections: Mutex::new(Vec::new()) }
        }

        pub fn with_headers(mut self, headers: Vec<(String, String)>) -> Self {
            for token in &mut self.tokens {
                token.headers = headers.clone();
            }
            self
        }
    }

    #[async_trait]
    impl TokenSource for StubSource {
        async fn token(&self) -> Result<Option<Token>, LlmError> {
            Ok(self.tokens.get(*self.current.lock().unwrap()).cloned())
        }

        async fn recover(&self, rejection: Rejection, sent: &Token) -> Result<bool, LlmError> {
            self.rejections.lock().unwrap().push((rejection, sent.value.clone()));
            let mut current = self.current.lock().unwrap();
            if *current + 1 < self.tokens.len() {
                *current += 1;
                Ok(true)
            } else {
                Ok(false)
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::test_support::StubSource;
    use super::*;
    use wiremock::matchers::{header, method};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    fn client(placement: Placement, source: StubSource) -> AuthedClient {
        AuthedClient::new(reqwest::Client::new(), placement, Arc::new(source))
    }

    async fn server_rejecting(token: &str) -> MockServer {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(header("authorization", format!("Bearer {token}").as_str()))
            .respond_with(ResponseTemplate::new(401))
            .mount(&server)
            .await;
        Mock::given(method("GET")).respond_with(ResponseTemplate::new(200)).mount(&server).await;
        server
    }

    #[tokio::test]
    async fn a_rejected_token_is_recovered_and_the_request_resent_once() {
        let server = server_rejecting("old").await;
        let client = client(Placement::Bearer, StubSource::new(["old", "new"]));

        let response = client.send(|http| http.get(server.uri())).await.unwrap().unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        let requests = server.received_requests().await.unwrap();
        let sent: Vec<_> = requests
            .iter()
            .map(|r| r.headers["authorization"].to_str().unwrap().to_string())
            .collect();
        assert_eq!(sent, ["Bearer old", "Bearer new"]);
    }

    #[tokio::test]
    async fn a_source_that_cannot_recover_leaves_the_rejection_to_the_caller() {
        let server = server_rejecting("only").await;
        let source = StubSource::new(["only"]);
        let client = client(Placement::Bearer, source);

        let response = client.send(|http| http.get(server.uri())).await.unwrap().unwrap();

        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
        assert_eq!(server.received_requests().await.unwrap().len(), 1, "no second attempt");
    }

    #[tokio::test]
    async fn a_second_rejection_is_not_recovered_again() {
        let server = MockServer::start().await;
        Mock::given(method("GET")).respond_with(ResponseTemplate::new(401)).mount(&server).await;
        let client = client(Placement::Bearer, StubSource::new(["a", "b", "c"]));

        let response = client.send(|http| http.get(server.uri())).await.unwrap().unwrap();

        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
        assert_eq!(server.received_requests().await.unwrap().len(), 2, "one recovery per send");
    }

    #[tokio::test]
    async fn forbidden_asks_the_source_and_other_statuses_do_not() {
        for (status, asked) in [(403u16, true), (429, false), (500, false)] {
            let server = MockServer::start().await;
            Mock::given(method("GET"))
                .respond_with(ResponseTemplate::new(status))
                .mount(&server)
                .await;
            let source = Arc::new(StubSource::new(["t"]));
            let client =
                AuthedClient::new(reqwest::Client::new(), Placement::Bearer, source.clone());

            client.send(|http| http.get(server.uri())).await.unwrap().unwrap();

            let rejections = source.rejections.lock().unwrap();
            assert_eq!(rejections.len(), usize::from(asked), "status {status}");
            if asked {
                assert_eq!(rejections[0], (Rejection::Forbidden, "t".to_string()));
            }
        }
    }

    #[tokio::test]
    async fn an_unauthenticated_client_sends_no_credential() {
        let server = MockServer::start().await;
        Mock::given(method("GET")).respond_with(ResponseTemplate::new(401)).mount(&server).await;
        let client = AuthedClient::unauthenticated(reqwest::Client::new());

        client.send(|http| http.get(server.uri())).await.unwrap().unwrap();

        let requests = server.received_requests().await.unwrap();
        assert_eq!(requests.len(), 1);
        assert!(!requests[0].headers.contains_key("authorization"));
    }

    #[tokio::test]
    async fn a_static_key_is_sent_as_placed_and_a_rejection_is_final() {
        let server = MockServer::start().await;
        Mock::given(method("GET")).respond_with(ResponseTemplate::new(401)).mount(&server).await;
        let http = reqwest::Client::new();
        let bearer = AuthedClient::static_key(http.clone(), Placement::Bearer, "sk-1");
        let raw = AuthedClient::static_key(http, Placement::Header("x-api-key".to_string()), "k");

        let response = bearer.send(|http| http.get(server.uri())).await.unwrap().unwrap();
        raw.send(|http| http.get(server.uri())).await.unwrap().unwrap();

        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
        let requests = server.received_requests().await.unwrap();
        assert_eq!(requests.len(), 2, "one attempt each");
        assert_eq!(requests[0].headers["authorization"], "Bearer sk-1");
        assert_eq!(requests[1].headers["x-api-key"], "k");
        assert!(!format!("{bearer:?}").contains("sk-1"), "the key stays out of Debug output");
    }

    #[tokio::test]
    async fn header_placement_sends_the_raw_token_and_its_derived_headers() {
        let server = MockServer::start().await;
        Mock::given(method("GET")).respond_with(ResponseTemplate::new(200)).mount(&server).await;
        let source = StubSource::new(["k"])
            .with_headers(vec![("x-account".to_string(), "acct-1".to_string())]);
        let client = client(Placement::Header("x-api-key".to_string()), source);

        client.send(|http| http.get(server.uri())).await.unwrap().unwrap();

        let requests = server.received_requests().await.unwrap();
        assert_eq!(requests[0].headers["x-api-key"], "k");
        assert_eq!(requests[0].headers["x-account"], "acct-1");
        assert!(!requests[0].headers.contains_key("authorization"));
    }

    #[test]
    fn transport_headers_carry_the_token() {
        let token = Token {
            value: "t".to_string(),
            headers: vec![("x-extra".to_string(), "1".to_string())],
        };
        let headers = |placement| client(placement, StubSource::new([])).headers(&token);

        let bearer = headers(Placement::Bearer).unwrap();
        assert_eq!(bearer[0].0, AUTHORIZATION);
        assert_eq!(bearer[0].1, "Bearer t");
        assert_eq!(bearer[1].0.as_str(), "x-extra");

        let raw = headers(Placement::Header("x-api-key".to_string())).unwrap();
        assert_eq!(raw[0].0.as_str(), "x-api-key");
        assert_eq!(raw[0].1, "t");

        let err = headers(Placement::Header("not a header".to_string())).unwrap_err();
        assert_eq!(err.kind, LlmErrorKind::Auth);
    }
}