modelbridge 0.5.2

One provider-neutral Rust client for OpenAI, Anthropic, Gemini, Groq, Ollama and friends: streaming, tool calling, an agent loop, usage accounting, and subscription sign-in
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
//! Browser sign-in for the two providers people reach with a subscription
//! rather than a key.
//!
//! The whole flow lives here: PKCE, a loopback listener for the redirect, the
//! token exchange, a credentials file, and a [`Session`] that refreshes and
//! re-persists tokens as they age out. [`Subscription::client`] then hands back
//! a [`crate::ClientBuilder`] already pointed at the right endpoint with the
//! right headers, so an application never writes provider plumbing of its own.
//!
//! ```no_run
//! use modelbridge::oauth::{Store, Subscription};
//! use std::sync::atomic::AtomicBool;
//!
//! let store = Store::at(dirs_next_to_your_config().join("credentials.json"));
//! let subscription = Subscription::Claude;
//!
//! let tokens = match store.load().tokens(subscription.id()).cloned() {
//!     Some(tokens) => tokens,
//!     None => subscription
//!         .login("My App")
//!         .run(&store, &|url| println!("Sign in: {url}"), &AtomicBool::new(false))?,
//! };
//!
//! let session = subscription.session(&store, tokens);
//! let client = subscription.client(session, "claude-sonnet-5").build()?;
//! # fn dirs_next_to_your_config() -> std::path::PathBuf { unimplemented!() }
//! # Ok::<(), modelbridge::Error>(())
//! ```
//!
//! Both routes authenticate as a vendor's own first-party CLI client. That is
//! off-label use: it can stop working without notice, and it is not what a
//! consumer subscription is sold for. The supported path for each is the
//! ordinary API key, and nothing above [`crate::Client`] can tell them apart.

pub mod chatgpt;
pub mod claude;
mod loopback;
mod pkce;
mod store;

use std::collections::HashMap;
use std::sync::atomic::AtomicBool;
use std::sync::{Arc, Mutex, OnceLock};
use std::time::Duration;

use crate::catalog::ApiStyle;
use crate::{ClientBuilder, Error, OAuthTokenProvider};

pub use loopback::Catcher;
pub use pkce::Pkce;
pub use store::{now, Credentials, Store, Tokens};

/// Token endpoints rate limit hard. Never refresh more often than this,
/// however many times the model route is rebuilt.
const REFRESH_INTERVAL: i64 = 30;

/// The two providers reached with a consumer subscription rather than a key.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Subscription {
    ChatGpt,
    Claude,
}

impl Subscription {
    pub const ALL: [Subscription; 2] = [Subscription::ChatGpt, Subscription::Claude];

    /// Recognise a provider id as a subscription route. Returns `None` for the
    /// metered providers, including `openai` and `anthropic`.
    pub fn parse(provider: &str) -> Option<Self> {
        match provider.trim().to_ascii_lowercase().as_str() {
            "chatgpt" | "codex" => Some(Self::ChatGpt),
            "claude" => Some(Self::Claude),
            _ => None,
        }
    }

    pub fn id(self) -> &'static str {
        match self {
            Self::ChatGpt => "chatgpt",
            Self::Claude => "claude",
        }
    }

    pub fn name(self) -> &'static str {
        match self {
            Self::ChatGpt => "ChatGPT subscription",
            Self::Claude => "Claude subscription",
        }
    }

    /// The metered provider running the same models, for model pickers.
    pub fn metered_provider(self) -> &'static str {
        match self {
            Self::ChatGpt => "openai",
            Self::Claude => "anthropic",
        }
    }

    pub fn default_model(self) -> &'static str {
        crate::catalog::provider(self.metered_provider())
            .map(|spec| spec.default_model)
            .unwrap_or_default()
    }

    /// A system prompt the endpoint insists on, prepended to the caller's own.
    pub fn system_prefix(self) -> Option<&'static str> {
        match self {
            Self::ChatGpt => None,
            Self::Claude => Some(claude::SYSTEM_PREFIX),
        }
    }

    /// The Codex backend rejects the Responses API's `max_output_tokens`, so
    /// limits stay prompt-driven there.
    ///
    /// [`Self::client`] applies this itself, so a caller does not have to.
    /// It stays public because an application may want to say so in its own
    /// interface, or size a prompt differently when no cap will be sent.
    pub fn accepts_output_limit(self) -> bool {
        self != Self::ChatGpt
    }

    pub fn port(self) -> u16 {
        match self {
            Self::ChatGpt => chatgpt::REDIRECT_PORT,
            Self::Claude => claude::REDIRECT_PORT,
        }
    }

    /// Whether this store holds usable tokens for the route.
    pub fn signed_in(self, store: &Store) -> bool {
        store.load().tokens(self.id()).is_some()
    }

    /// Configure a browser sign-in. `app` names the application on the page
    /// the browser lands on when it is done.
    pub fn login(self, app: impl Into<String>) -> Login {
        Login {
            subscription: self,
            app: app.into(),
            timeout: Duration::from_secs(300),
        }
    }

    /// Forget the stored sign-in.
    pub fn logout(self, store: &Store) -> crate::Result<()> {
        store.put_tokens(self.id(), None)
    }

    /// The process-wide session for this route; see [`session`].
    pub fn session(self, store: &Store, tokens: Tokens) -> Arc<Session> {
        session(self, store, tokens)
    }

    /// A client builder pointed at this subscription's endpoint, carrying its
    /// required headers and a credential it can refresh.
    pub fn client(self, session: Arc<Session>, model: impl Into<String>) -> ClientBuilder {
        match self {
            Self::ChatGpt => {
                ClientBuilder::custom(self.id(), ApiStyle::Responses, chatgpt::API_URL, model)
                    .accepts_output_limit(false)
                    .header("chatgpt-account-id", session.account_id())
                    .header("openai-beta", "responses=experimental")
                    .header("originator", chatgpt::ORIGINATOR)
                    .header("session_id", session_id())
                    .oauth(session)
            }
            Self::Claude => {
                ClientBuilder::custom(self.id(), ApiStyle::Anthropic, claude::API_URL, model)
                    .header("anthropic-beta", claude::BETA_HEADER)
                    .oauth(session)
            }
        }
    }

    fn authorize_url(self, pkce: &Pkce) -> String {
        match self {
            Self::ChatGpt => chatgpt::authorize_url(&pkce.challenge, &pkce.state),
            Self::Claude => claude::authorize_url(&pkce.challenge, &pkce.verifier),
        }
    }

    /// What the redirect's `state` must equal. The Claude flow echoes the
    /// verifier instead of a separate nonce.
    fn expected_state(self, pkce: &Pkce) -> &str {
        match self {
            Self::ChatGpt => &pkce.state,
            Self::Claude => &pkce.verifier,
        }
    }

    fn exchange(self, code: &str, verifier: &str) -> crate::Result<Tokens> {
        match self {
            Self::ChatGpt => chatgpt::exchange(code, verifier),
            Self::Claude => claude::exchange(code, verifier),
        }
    }

    fn refresh(self, current: &Tokens) -> crate::Result<Tokens> {
        match self {
            Self::ChatGpt => chatgpt::refresh(current),
            Self::Claude => claude::refresh(current),
        }
    }
}

/// A configured browser sign-in.
pub struct Login {
    subscription: Subscription,
    app: String,
    timeout: Duration,
}

impl Login {
    /// How long to wait for someone to finish signing in.
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Run the whole flow and store the result.
    ///
    /// `announce` receives the authorization URL before the browser opens, so
    /// an interface can show it in case the browser does not. `cancel` lets it
    /// abandon a sign-in the user walked away from.
    pub fn run(
        &self,
        store: &Store,
        announce: &dyn Fn(&str),
        cancel: &AtomicBool,
    ) -> crate::Result<Tokens> {
        let subscription = self.subscription;
        let pkce = Pkce::generate()?;
        // Bind first: better to fail now than after the password has been typed.
        let catcher = Catcher::bind(subscription.port(), &self.app)?;
        let url = subscription.authorize_url(&pkce);
        announce(&url);
        open_browser(&url);

        let params = catcher.wait(self.timeout, cancel)?;
        if let Some(error) = params.get("error") {
            let detail = params
                .get("error_description")
                .map(|detail| format!(" ({detail})"))
                .unwrap_or_default();
            return Err(Error::Auth(format!(
                "authorization denied: {error}{detail}"
            )));
        }
        if params.get("state").map(String::as_str) != Some(subscription.expected_state(&pkce)) {
            return Err(Error::Auth(
                "state mismatch on the OAuth redirect; aborting".into(),
            ));
        }
        let code = params
            .get("code")
            .ok_or_else(|| Error::Auth("no authorization code in the redirect".into()))?;

        let tokens = subscription
            .exchange(code, &pkce.verifier)
            .map_err(rate_limit_hint)?;
        store.put_tokens(subscription.id(), Some(tokens.clone()))?;
        Ok(tokens)
    }
}

/// A rate-limited token endpoint says so in JSON nobody wants to read.
fn rate_limit_hint(error: Error) -> Error {
    let text = error.to_string();
    if text.contains("429") || text.contains("rate_limit") {
        Error::RateLimited {
            message: "the sign-in endpoint is rate limiting. Wait a minute or two and try again; \
                      repeated sign-in attempts make it last longer."
                .into(),
            retry_after: Some(Duration::from_secs(60)),
        }
    } else {
        error
    }
}

/// Hand a URL to whatever the platform opens links with.
pub fn open_browser(url: &str) {
    #[cfg(windows)]
    // Call the URL handler directly: passing an OAuth URL through `cmd /C start`
    // makes cmd treat every `&` as a command separator.
    let spawned = std::process::Command::new("rundll32.exe")
        .args(["url.dll,FileProtocolHandler", url])
        .spawn();
    #[cfg(target_os = "macos")]
    let spawned = std::process::Command::new("open").arg(url).spawn();
    #[cfg(all(unix, not(target_os = "macos")))]
    let spawned = std::process::Command::new("xdg-open").arg(url).spawn();
    let _ = spawned;
}

/// A random v4 UUID. The Codex backend wants a session id on every request,
/// and a dependency for sixteen random bytes would be silly.
pub fn session_id() -> String {
    let mut bytes = [0u8; 16];
    if getrandom::getrandom(&mut bytes).is_err() {
        bytes.copy_from_slice(&(now() as u128).to_le_bytes());
    }
    bytes[6] = (bytes[6] & 0x0f) | 0x40;
    bytes[8] = (bytes[8] & 0x3f) | 0x80;
    let hex: String = bytes.iter().map(|byte| format!("{byte:02x}")).collect();
    format!(
        "{}-{}-{}-{}-{}",
        &hex[0..8],
        &hex[8..12],
        &hex[12..16],
        &hex[16..20],
        &hex[20..32]
    )
}

// ---------------------------------------------------------------------------
// Token endpoints
// ---------------------------------------------------------------------------

fn post(url: &str, content_type: &str, body: &str) -> crate::Result<String> {
    let agent = ureq::AgentBuilder::new()
        .timeout_connect(Duration::from_secs(20))
        .timeout_read(Duration::from_secs(60))
        .build();
    match agent
        .post(url)
        .set("content-type", content_type)
        .set("accept", "application/json")
        .send_string(body)
    {
        Ok(response) => response
            .into_string()
            .map_err(|error| Error::Decode(format!("reading token response: {error}"))),
        Err(ureq::Error::Status(status, response)) => {
            let detail = response.into_string().unwrap_or_default();
            Err(Error::Auth(format!(
                "token endpoint returned HTTP {status}: {}",
                detail.trim()
            )))
        }
        Err(error) => Err(Error::Network(format!("token request failed: {error}"))),
    }
}

fn post_form(url: &str, body: &str) -> crate::Result<String> {
    post(url, "application/x-www-form-urlencoded", body)
}

fn post_json(url: &str, body: &str) -> crate::Result<String> {
    post(url, "application/json", body)
}

// ---------------------------------------------------------------------------
// Sessions
// ---------------------------------------------------------------------------

/// The credential a subscription route hands to a client, refreshing and
/// persisting tokens as they age out.
pub struct Session {
    subscription: Subscription,
    store: Store,
    tokens: Mutex<Tokens>,
    /// When the last refresh was attempted, successful or not.
    last_refresh: Mutex<i64>,
}

/// One session per subscription for the life of the process.
///
/// Switching model or reopening a settings screen rebuilds the model route,
/// and a fresh token holder each time would refresh each time — which is how a
/// token endpoint starts answering 429.
pub fn session(subscription: Subscription, store: &Store, tokens: Tokens) -> Arc<Session> {
    static SESSIONS: OnceLock<Mutex<HashMap<String, Arc<Session>>>> = OnceLock::new();
    let sessions = SESSIONS.get_or_init(|| Mutex::new(HashMap::new()));
    let mut sessions = match sessions.lock() {
        Ok(sessions) => sessions,
        Err(poisoned) => poisoned.into_inner(),
    };
    let key = format!("{}@{}", subscription.id(), store.path().display());
    match sessions.get(&key) {
        // A fresh sign-in replaces the stored tokens, so adopt them.
        Some(existing) => {
            existing.adopt(tokens);
            Arc::clone(existing)
        }
        None => {
            let session = Arc::new(Session::new(subscription, store.clone(), tokens));
            sessions.insert(key, Arc::clone(&session));
            session
        }
    }
}

impl Session {
    pub fn new(subscription: Subscription, store: Store, tokens: Tokens) -> Self {
        Self {
            subscription,
            store,
            tokens: Mutex::new(tokens),
            last_refresh: Mutex::new(0),
        }
    }

    pub fn subscription(&self) -> Subscription {
        self.subscription
    }

    pub fn account_id(&self) -> String {
        self.tokens
            .lock()
            .map(|tokens| tokens.account_id.clone())
            .unwrap_or_default()
    }

    /// Take newer tokens, which is what a fresh sign-in produces.
    fn adopt(&self, tokens: Tokens) {
        if let Ok(mut held) = self.tokens.lock() {
            if tokens.expires_at > held.expires_at {
                *held = tokens;
            }
        }
    }

    fn renew(&self) -> crate::Result<String> {
        let mut last = self
            .last_refresh
            .lock()
            .map_err(|_| Error::Auth("token store poisoned".into()))?;
        let since = now() - *last;
        if since < REFRESH_INTERVAL {
            return Err(Error::RateLimited {
                message: format!("refreshed {since}s ago; waiting before asking again"),
                retry_after: Some(Duration::from_secs((REFRESH_INTERVAL - since) as u64)),
            });
        }
        *last = now();
        drop(last);

        let current = self
            .tokens
            .lock()
            .map_err(|_| Error::Auth("token store poisoned".into()))?
            .clone();
        let fresh = self
            .subscription
            .refresh(&current)
            .map_err(rate_limit_hint)?;
        self.store
            .put_tokens(self.subscription.id(), Some(fresh.clone()))?;
        let access = fresh.access_token.clone();
        *self
            .tokens
            .lock()
            .map_err(|_| Error::Auth("token store poisoned".into()))? = fresh;
        Ok(access)
    }
}

impl OAuthTokenProvider for Session {
    fn access_token(&self) -> std::result::Result<String, String> {
        let current = self
            .tokens
            .lock()
            .map_err(|_| "token store poisoned".to_string())?
            .clone();
        if current.expired() {
            // A failed pre-emptive refresh is not fatal: the request may still
            // succeed, and a 401 triggers one more attempt.
            if let Ok(access) = self.renew() {
                return Ok(access);
            }
        }
        Ok(current.access_token)
    }

    fn refresh_access_token(&self) -> std::result::Result<String, String> {
        self.renew().map_err(|error| {
            format!(
                "{} sign-in expired and could not be refreshed ({error}). Sign in to {} again.",
                self.subscription.name(),
                self.subscription.id()
            )
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn subscription_ids_and_aliases_resolve() {
        assert_eq!(Subscription::parse("chatgpt"), Some(Subscription::ChatGpt));
        assert_eq!(Subscription::parse("Codex"), Some(Subscription::ChatGpt));
        assert_eq!(Subscription::parse("claude"), Some(Subscription::Claude));
        assert_eq!(Subscription::parse("openai"), None);
        assert_eq!(Subscription::parse("anthropic"), None);
    }

    #[test]
    fn each_subscription_names_the_metered_provider_behind_it() {
        assert_eq!(Subscription::ChatGpt.metered_provider(), "openai");
        assert_eq!(Subscription::Claude.metered_provider(), "anthropic");
        assert!(!Subscription::Claude.default_model().is_empty());
    }

    #[test]
    fn each_flow_checks_the_state_value_it_actually_sends() {
        let pkce = Pkce::generate().unwrap();
        assert_eq!(Subscription::ChatGpt.expected_state(&pkce), pkce.state);
        assert_eq!(Subscription::Claude.expected_state(&pkce), pkce.verifier);
        assert!(Subscription::Claude
            .authorize_url(&pkce)
            .contains(&pkce::encode(&pkce.verifier)));
    }

    #[test]
    fn the_two_routes_use_different_loopback_ports() {
        assert_ne!(Subscription::ChatGpt.port(), Subscription::Claude.port());
    }

    #[test]
    fn only_the_claude_route_carries_a_required_system_prefix() {
        assert!(Subscription::ChatGpt.system_prefix().is_none());
        assert!(Subscription::Claude.system_prefix().is_some());
        assert!(!Subscription::ChatGpt.accepts_output_limit());
        assert!(Subscription::Claude.accepts_output_limit());
    }

    #[test]
    fn session_ids_look_like_version_four_uuids() {
        let id = session_id();
        let fields: Vec<&str> = id.split('-').collect();
        assert_eq!(
            fields.iter().map(|field| field.len()).collect::<Vec<_>>(),
            vec![8, 4, 4, 4, 12]
        );
        assert!(fields[2].starts_with('4'));
        assert!(id.chars().all(|ch| ch.is_ascii_hexdigit() || ch == '-'));
        assert_ne!(session_id(), id);
    }

    #[test]
    fn a_session_hands_over_the_token_it_holds() {
        let session = Session::new(
            Subscription::Claude,
            Store::at(std::env::temp_dir().join("modelbridge-unused.json")),
            Tokens {
                access_token: "at".into(),
                ..Tokens::default()
            },
        );
        assert_eq!(session.access_token().unwrap(), "at");
    }

    #[test]
    fn a_second_refresh_within_the_interval_is_refused_rather_than_sent() {
        let session = Session::new(
            Subscription::Claude,
            Store::at(std::env::temp_dir().join("modelbridge-unused.json")),
            Tokens {
                access_token: "at".into(),
                refresh_token: "rt".into(),
                ..Tokens::default()
            },
        );
        // Pretend a refresh just happened. The next one must be refused here,
        // without a request, which is what protects the endpoint.
        *session.last_refresh.lock().unwrap() = now();
        assert!(matches!(session.renew(), Err(Error::RateLimited { .. })));
    }

    #[test]
    fn a_subscription_client_carries_its_required_headers() {
        let store = Store::at(std::env::temp_dir().join("modelbridge-unused.json"));
        let session = Arc::new(Session::new(
            Subscription::Claude,
            store,
            Tokens {
                access_token: "at".into(),
                ..Tokens::default()
            },
        ));
        let client = Subscription::Claude
            .client(session, "claude-sonnet-5")
            .build()
            .unwrap();
        assert_eq!(client.provider(), "claude");
        assert_eq!(client.model(), "claude-sonnet-5");
    }

    #[test]
    fn the_chatgpt_route_sends_no_output_limit_even_when_a_request_names_one() {
        fn client_for(subscription: Subscription, model: &str) -> crate::Client {
            let session = Arc::new(Session::new(
                subscription,
                Store::at(std::env::temp_dir().join("modelbridge-unused.json")),
                Tokens {
                    access_token: "at".into(),
                    ..Tokens::default()
                },
            ));
            subscription.client(session, model).build().unwrap()
        }

        let request = crate::Request::new("Be brief")
            .user("hello")
            .max_output_tokens(420);

        // The Codex backend answers `HTTP 400: Unsupported parameter:
        // max_output_tokens`, so the field must never reach it.
        let body = client_for(Subscription::ChatGpt, "gpt-5.6-luna").request_body(&request);
        assert!(
            body["max_output_tokens"].is_null(),
            "the Codex backend would reject this body: {body}"
        );

        let body = client_for(Subscription::Claude, "claude-sonnet-5").request_body(&request);
        assert_eq!(body["max_tokens"], 420, "every other route stays capped");
    }
}