Skip to main content

shunt/
proxy.rs

1use std::collections::{HashMap, HashSet};
2use std::sync::Arc;
3
4use axum::extract::{Request, State};
5use axum::http::StatusCode;
6use axum::response::{IntoResponse, Response};
7use axum::routing::{get, post};
8use axum::Router;
9use bytes::Bytes;
10use serde_json::json;
11use tokio::sync::RwLock;
12use tracing::{error, warn};
13
14use crate::config::{state_path, Config, CredentialsStore};
15use crate::forwarder::Forwarder;
16use crate::oauth::OAuthCredential;
17use crate::provider::Provider;
18use crate::quota;
19use crate::router;
20use crate::state::StateStore;
21
22#[derive(Clone)]
23struct AppState {
24    config: Arc<Config>,
25    forwarder: Arc<Forwarder>,
26    state: StateStore,
27    /// Live credentials — can be refreshed at runtime without restarting.
28    credentials: Arc<RwLock<HashMap<String, OAuthCredential>>>,
29    /// Epoch-ms when this proxy instance started.
30    started_ms: u64,
31    /// If set, /v1/chat/completions requests are translated and forwarded here
32    /// (the Anthropic proxy base URL, e.g. "http://127.0.0.1:8082").
33    anthropic_base_url: Option<String>,
34}
35
36pub fn create_app(config: Config) -> anyhow::Result<Router> {
37    let (app, _) = create_app_with_state(config, StateStore::load(&state_path()), None)?;
38    Ok(app)
39}
40
41/// Shared live credentials map — can be written to without restarting the proxy.
42pub type LiveCredentials = Arc<RwLock<HashMap<String, OAuthCredential>>>;
43
44pub fn create_app_with_state(
45    config: Config,
46    state: StateStore,
47    anthropic_base_url: Option<String>,
48) -> anyhow::Result<(Router, LiveCredentials)> {
49    let forwarder = Forwarder::new(&config.server.upstream_url, config.server.request_timeout_secs)?;
50
51    // Accounts with no credential are shown in status but skipped during routing.
52    // Mark them disabled immediately so the router ignores them.
53    for a in config.accounts.iter().filter(|a| a.credential.is_none()) {
54        state.set_auth_failed(&a.name);
55    }
56
57    let credentials: LiveCredentials = Arc::new(RwLock::new(
58        config.accounts.iter()
59            .filter_map(|a| a.credential.as_ref().map(|c| (a.name.clone(), c.clone())))
60            .collect::<HashMap<_, _>>(),
61    ));
62
63    let app_state = AppState {
64        config: Arc::new(config),
65        forwarder: Arc::new(forwarder),
66        state,
67        credentials: Arc::clone(&credentials),
68        started_ms: now_ms(),
69        anthropic_base_url,
70    };
71
72    // Register proxy routes appropriate for the provider.
73    // Anthropic: explicit paths only (maintains existing behaviour).
74    // OpenAI/others: wildcard catches all paths; also expose OpenAI-compat
75    //   endpoints that translate to Claude when anthropic_base_url is set.
76    let provider = app_state.config.accounts.first()
77        .map(|a| &a.provider)
78        .cloned()
79        .unwrap_or_default();
80
81    let proxy_routes = match provider {
82        Provider::Anthropic => Router::new()
83            .route("/v1/messages", post(proxy_handler))
84            .route("/v1/messages/count_tokens", post(proxy_handler)),
85        Provider::OpenAI => Router::new()
86            .route("/v1/chat/completions", post(openai_compat_handler))
87            .route("/v1/models", get(openai_models_handler))
88            .fallback(proxy_handler),
89    };
90
91    let app = Router::new()
92        .route("/health", get(health))
93        .route("/status", get(status_handler))
94        .route("/use", post(use_handler))
95        .merge(proxy_routes)
96        .with_state(app_state);
97
98    Ok((app, credentials))
99}
100
101async fn health() -> impl IntoResponse {
102    axum::Json(json!({"status": "ok"}))
103}
104
105async fn status_handler(State(s): State<AppState>) -> impl IntoResponse {
106    let account_states = s.state.account_states();
107    let quotas = s.state.quota_snapshot();
108    let rate_limits = s.state.rate_limit_snapshot();
109
110    let accounts: Vec<_> = s.config.accounts.iter().map(|a| {
111        let st = account_states.get(&a.name);
112        let avail_status = if st.map(|s| s.auth_failed).unwrap_or(false) {
113            "reauth_required"
114        } else if st.map(|s| s.disabled).unwrap_or(false) {
115            "disabled"
116        } else if s.state.is_available(&a.name) {
117            "available"
118        } else {
119            "cooling"
120        };
121
122        let quota = quotas.get(&a.name);
123        let window_expires_ms = quota.and_then(|q| q.window_expires_ms());
124        let window_expires_ms = window_expires_ms.filter(|&e| e > now_ms());
125        let tokens_used = quota.map(|q| json!({
126            "input": q.input_tokens,
127            "output": q.output_tokens,
128            "total": q.total_tokens(),
129        }));
130
131        let rl = rate_limits.get(&a.name);
132        let rate_limit = rl.map(|r| json!({
133            "utilization_5h": r.utilization_5h,
134            "reset_5h": r.reset_5h,
135            "status_5h": r.status_5h,
136            "utilization_7d": r.utilization_7d,
137            "reset_7d": r.reset_7d,
138            "status_7d": r.status_7d,
139            "representative_claim": r.representative_claim,
140            "updated_ms": r.updated_ms,
141        }));
142
143        let acc_state = account_states.get(&a.name);
144        let email = a.credential.as_ref().and_then(|c| c.email.as_deref()).map(|e| e.to_owned());
145        let disabled = acc_state.map(|s| s.disabled).unwrap_or(false);
146        let auth_failed = acc_state.map(|s| s.auth_failed).unwrap_or(false);
147        let cooldown_until_ms = acc_state.map(|s| s.cooldown_until_ms).unwrap_or(0);
148        let utilization_5h = rl.and_then(|r| r.utilization_5h).unwrap_or(0.0);
149        let reset_5h = rl.and_then(|r| r.reset_5h);
150        let total_tokens = quota.map(|q| q.total_tokens()).unwrap_or(0);
151        let available = s.state.is_available(&a.name);
152
153        json!({
154            "name": a.name,
155            "email": email,
156            "plan_type": a.plan_type,
157            "status": avail_status,
158            "available": available,
159            "disabled": disabled,
160            "auth_failed": auth_failed,
161            "cooldown_until_ms": cooldown_until_ms,
162            "utilization_5h": utilization_5h,
163            "reset_5h": reset_5h,
164            "total_tokens": total_tokens,
165            "window_expires_ms": window_expires_ms,
166            "tokens_used": tokens_used,
167            "rate_limit": rate_limit,
168        })
169    }).collect();
170
171    let recent_requests = s.state.recent_requests_snapshot();
172    let savings = s.state.savings_snapshot();
173
174    axum::Json(json!({
175        "version": env!("CARGO_PKG_VERSION"),
176        "started_ms": s.started_ms,
177        "accounts": accounts,
178        "pinned_account": s.state.get_pinned(),
179        "last_used_account": s.state.get_last_used(),
180        "recent_requests": recent_requests,
181        "savings": savings,
182    }))
183}
184
185async fn use_handler(
186    State(s): State<AppState>,
187    axum::Json(body): axum::Json<serde_json::Value>,
188) -> impl IntoResponse {
189    let account = body["account"].as_str().map(|s| s.to_owned());
190    // Validate the account name exists (unless clearing to auto)
191    if let Some(ref name) = account {
192        if name != "auto" && !s.config.accounts.iter().any(|a| &a.name == name) {
193            return axum::Json(json!({
194                "error": format!("unknown account '{name}'")
195            }));
196        }
197        let pinned = if name == "auto" { None } else { Some(name.clone()) };
198        s.state.set_pinned(pinned);
199        axum::Json(json!({ "pinned": name }))
200    } else {
201        s.state.set_pinned(None);
202        axum::Json(json!({ "pinned": null }))
203    }
204}
205
206fn now_ms() -> u64 {
207    use std::time::{SystemTime, UNIX_EPOCH};
208    SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_millis() as u64
209}
210
211async fn proxy_handler(
212    State(s): State<AppState>,
213    req: Request,
214) -> Result<Response, ProxyError> {
215    // Remote auth: if a remote_key is configured, the client must supply it as x-api-key.
216    if let Some(ref expected) = s.config.server.remote_key {
217        let provided = req.headers()
218            .get("x-api-key")
219            .and_then(|v| v.to_str().ok())
220            .unwrap_or("");
221        if provided != expected {
222            return Err(ProxyError::Unauthorized);
223        }
224    }
225
226    let method = req.method().as_str().to_owned();
227    let path = req.uri().path().to_owned();
228    let headers = req.headers().clone();
229
230    let body_bytes: Bytes = axum::body::to_bytes(req.into_body(), usize::MAX)
231        .await
232        .map_err(|_| ProxyError::BodyRead)?;
233
234    let model = serde_json::from_slice::<serde_json::Value>(&body_bytes)
235        .ok()
236        .and_then(|v| v["model"].as_str().map(|s| s.to_owned()))
237        .unwrap_or_default();
238    let req_start_ms = now_ms();
239
240    let fp = router::fingerprint(&body_bytes);
241    let fp_ref = fp.as_deref();
242
243    let mut tried: HashSet<String> = HashSet::new();
244    // Track accounts we've already attempted a token refresh for this request.
245    let mut refreshed: HashSet<String> = HashSet::new();
246
247    loop {
248        let account = match router::pick_account(
249            &s.config.accounts, &s.state, fp_ref, &tried,
250            s.config.server.sticky_ttl_ms, s.config.server.expiry_soon_secs,
251        ) {
252            Some(a) => a,
253            None => return Err(ProxyError::AllAccountsUnavailable),
254        };
255
256        let account_name = account.name.clone();
257
258        // Use the live (possibly refreshed) token rather than the one baked into config.
259        let token = {
260            let creds = s.credentials.read().await;
261            creds.get(&account_name)
262                .map(|c| c.access_token.clone())
263                .or_else(|| account.credential.as_ref().map(|c| c.access_token.clone()))
264                .unwrap_or_default()
265        };
266
267        let response = s.forwarder
268            .forward(&method, &path, body_bytes.clone(), &headers, account, &token)
269            .await
270            .map_err(|e| {
271                error!("Forward error: {:#}", e);
272                ProxyError::Upstream
273            })?;
274
275        match response.status().as_u16() {
276            200..=299 => {
277                s.state.set_last_used(&account_name);
278                if let Some(info) = account.provider.parse_rate_limits(response.headers()) {
279                    s.state.update_rate_limits(&account_name, info);
280                }
281                return Ok(tap_usage(response, &s.state, &account_name, &model, req_start_ms).await);
282            }
283            429 => {
284                warn!(account = %account_name, "429 rate-limited — cooling 60s");
285                if let Some(info) = account.provider.parse_rate_limits(response.headers()) {
286                    s.state.update_rate_limits(&account_name, info);
287                }
288                s.state.set_cooldown(&account_name, 60_000);
289                tried.insert(account_name);
290            }
291            529 => {
292                warn!(account = %account_name, "529 overloaded — cooling 30s");
293                if let Some(info) = account.provider.parse_rate_limits(response.headers()) {
294                    s.state.update_rate_limits(&account_name, info);
295                }
296                s.state.set_cooldown(&account_name, 30_000);
297                tried.insert(account_name);
298            }
299            401 => {
300                if !refreshed.contains(&account_name) {
301                    // Access token invalidated (e.g. user logged out) — try refresh.
302                    let cred = {
303                        let creds = s.credentials.read().await;
304                        creds.get(&account_name).cloned()
305                            .or_else(|| account.credential.clone())
306                    };
307                    let Some(cred) = cred else {
308                        tried.insert(account_name);
309                        continue;
310                    };
311                    match tokio::time::timeout(
312                        std::time::Duration::from_secs(10),
313                        account.provider.refresh_token(&cred),
314                    ).await {
315                        Ok(Ok(fresh)) => {
316                            warn!(account = %account_name, "401 — token refreshed, retrying");
317                            {
318                                let mut creds = s.credentials.write().await;
319                                creds.insert(account_name.clone(), fresh.clone());
320                            }
321                            // Persist to disk so the refreshed token survives a restart.
322                            let name = account_name.clone();
323                            let fresh = fresh.clone();
324                            tokio::task::spawn_blocking(move || {
325                                let mut store = CredentialsStore::load();
326                                store.accounts.insert(name, fresh.clone());
327                                store.save().ok();
328                                if fresh.id_token.is_some() {
329                                    crate::oauth::write_codex_auth_file(&fresh);
330                                }
331                            });
332                            // Mark as refreshed but don't add to tried — retry this account.
333                            refreshed.insert(account_name);
334                        }
335                        _ => {
336                            // Refresh failed/timed out — cool down, don't permanently disable.
337                            error!(account = %account_name, "401 — token refresh failed, cooling 5min");
338                            s.state.set_cooldown(&account_name, 5 * 60_000);
339                            tried.insert(account_name);
340                        }
341                    }
342                } else {
343                    // Already refreshed once and still 401 — cool down this account.
344                    error!(account = %account_name, "401 after refresh — cooling 5min");
345                    s.state.set_cooldown(&account_name, 5 * 60_000);
346                    tried.insert(account_name);
347                }
348            }
349            403 => {
350                // Forbidden — subscription lapsed or org restriction; refreshing won't help.
351                error!(account = %account_name, "403 forbidden — cooling 30min");
352                s.state.set_cooldown(&account_name, 30 * 60_000);
353                tried.insert(account_name);
354            }
355            _ => {
356                // 400, 404, 500, etc. — return as-is, no retry
357                return Ok(response);
358            }
359        }
360    }
361}
362
363// ---------------------------------------------------------------------------
364// Usage extraction
365// ---------------------------------------------------------------------------
366
367/// Intercept a successful response to record token usage, then pass it through.
368///
369/// - Streaming: wraps the body stream with an SSE scanner (zero latency).
370/// - Non-streaming: buffers the body, parses usage, rebuilds the response.
371async fn tap_usage(
372    resp: Response,
373    state: &StateStore,
374    account: &str,
375    model: &str,
376    req_start_ms: u64,
377) -> Response {
378    use axum::body::Body;
379    use crate::state::RequestLog;
380
381    if quota::is_streaming_response(&resp) {
382        let state = state.clone();
383        let account = account.to_owned();
384        let model = model.to_owned();
385        let on_complete = Arc::new(move |input: u64, output: u64| {
386            state.record_usage(&account, input, output);
387            state.record_global(&model, input, output);
388            state.record_request(RequestLog {
389                ts_ms: req_start_ms,
390                account: account.clone(),
391                model: model.clone(),
392                status: 200,
393                input_tokens: input,
394                output_tokens: output,
395                duration_ms: now_ms().saturating_sub(req_start_ms),
396            });
397        });
398        let (parts, body) = resp.into_parts();
399        let wrapped = quota::wrap_streaming_body(body, on_complete);
400        return Response::from_parts(parts, wrapped);
401    }
402
403    // Non-streaming: buffer, extract, rebuild
404    let (parts, body) = resp.into_parts();
405    let bytes = match axum::body::to_bytes(body, 64 * 1024 * 1024).await {
406        Ok(b) => b,
407        Err(_) => return Response::from_parts(parts, Body::empty()),
408    };
409    let (input, output) = quota::extract_usage_from_json(&bytes);
410    state.record_usage(account, input, output);
411    state.record_global(model, input, output);
412    state.record_request(RequestLog {
413        ts_ms: req_start_ms,
414        account: account.to_owned(),
415        model: model.to_owned(),
416        status: 200,
417        input_tokens: input,
418        output_tokens: output,
419        duration_ms: now_ms().saturating_sub(req_start_ms),
420    });
421    Response::from_parts(parts, Body::from(bytes))
422}
423
424
425// ---------------------------------------------------------------------------
426// Rate limit prefetch
427// ---------------------------------------------------------------------------
428
429/// For any account with no rate-limit data yet, make a cheap request directly
430/// to the upstream API so we populate metrics without waiting for a real user
431/// request. Runs as a background task after startup.
432pub async fn prefetch_rate_limits(config: Arc<Config>, state: StateStore) {
433    let client = reqwest::Client::builder()
434        .timeout(std::time::Duration::from_secs(20))
435        .build()
436        .unwrap_or_default();
437
438    for account in &config.accounts {
439        // Skip if we already have data for this account.
440        let rl = state.rate_limit_snapshot();
441        if let Some(r) = rl.get(&account.name) {
442            if r.utilization_5h.is_some() || r.utilization_7d.is_some() {
443                continue;
444            }
445        }
446
447        // Skip accounts with no credentials or no prefetch support.
448        let creds = match account.credential.clone() {
449            Some(c) => c,
450            None => continue,
451        };
452
453        let Some((path, body)) = account.provider.prefetch_request() else {
454            // No POST prefetch for this provider — do a lightweight GET auth check instead.
455            if let Some(probe_path) = account.provider.auth_probe_get_path() {
456                auth_probe_get(&client, probe_path, account, &state).await;
457            }
458            continue;
459        };
460        let url = format!("{}{}", config.server.upstream_url, path);
461
462        let resp = prefetch_send(&client, &url, &account.provider, &creds.access_token, &body).await;
463
464        let r = match resp {
465            Ok(r) => r,
466            Err(e) => { tracing::warn!(account = %account.name, "prefetch failed: {e}"); continue; }
467        };
468
469        if r.status() == reqwest::StatusCode::UNAUTHORIZED {
470            tracing::info!(account = %account.name, "prefetch: token expired, refreshing");
471            let fresh = match account.provider.refresh_token(&creds).await {
472                Ok(f) => f,
473                Err(e) => {
474                    tracing::warn!(account = %account.name, "token refresh failed: {e}");
475                    state.set_auth_failed(&account.name);
476                    continue;
477                }
478            };
479            let mut store = crate::config::CredentialsStore::load();
480            store.accounts.insert(account.name.clone(), fresh.clone());
481            store.save().ok();
482            if fresh.id_token.is_some() {
483                crate::oauth::write_codex_auth_file(&fresh);
484            }
485
486            match prefetch_send(&client, &url, &account.provider, &fresh.access_token, &body).await {
487                Ok(r2) if r2.status() == reqwest::StatusCode::UNAUTHORIZED => {
488                    tracing::error!(account = %account.name, "401 after refresh — needs re-authorization");
489                    state.set_auth_failed(&account.name);
490                }
491                Ok(r2) => {
492                    if let Some(info) = account.provider.parse_rate_limits(r2.headers()) {
493                        state.update_rate_limits(&account.name, info);
494                    }
495                }
496                Err(e) => tracing::warn!(account = %account.name, "prefetch retry failed: {e}"),
497            }
498        } else {
499            tracing::info!(account = %account.name, status = %r.status(), "prefetch response");
500            if let Some(info) = account.provider.parse_rate_limits(r.headers()) {
501                state.update_rate_limits(&account.name, info);
502            }
503        }
504    }
505}
506
507/// Build and send a prefetch request for the given provider + token.
508async fn prefetch_send(
509    client: &reqwest::Client,
510    url: &str,
511    provider: &crate::provider::Provider,
512    token: &str,
513    body: &serde_json::Value,
514) -> anyhow::Result<reqwest::Response> {
515    let mut headers = reqwest::header::HeaderMap::new();
516    provider.inject_auth_headers(&mut headers, token)?;
517    for (name, value) in provider.prefetch_extra_headers() {
518        headers.insert(
519            reqwest::header::HeaderName::from_bytes(name.as_bytes())?,
520            reqwest::header::HeaderValue::from_static(value),
521        );
522    }
523    Ok(client.post(url).headers(headers).json(body).send().await?)
524}
525
526/// GET a cheap endpoint to verify credentials are still valid for providers that
527/// don't expose rate-limit headers (e.g. OpenAI). On 401, attempts a token refresh;
528/// marks the account as `reauth_required` if the refresh also fails.
529async fn auth_probe_get(
530    client: &reqwest::Client,
531    path: &str,
532    account: &crate::config::AccountConfig,
533    state: &StateStore,
534) {
535    let creds = match account.credential.clone() {
536        Some(c) => c,
537        None => return,
538    };
539    let upstream = match account.provider {
540        crate::provider::Provider::OpenAI => "https://chatgpt.com",
541        crate::provider::Provider::Anthropic => "https://api.anthropic.com",
542    };
543    let url = format!("{}{}", upstream, path);
544
545    let do_get = |token: &str| -> reqwest::RequestBuilder {
546        let mut headers = reqwest::header::HeaderMap::new();
547        let _ = account.provider.inject_auth_headers(&mut headers, token);
548        client.get(&url).headers(headers)
549    };
550
551    let resp = match do_get(&creds.access_token).send().await {
552        Ok(r) => r,
553        Err(e) => { tracing::warn!(account = %account.name, "auth probe failed: {e}"); return; }
554    };
555
556    if resp.status() == reqwest::StatusCode::UNAUTHORIZED {
557        tracing::info!(account = %account.name, "auth probe: access token rejected, refreshing");
558        let fresh = match account.provider.refresh_token(&creds).await {
559            Ok(f) => f,
560            Err(e) => {
561                tracing::warn!(account = %account.name, "token refresh failed: {e}");
562                state.set_auth_failed(&account.name);
563                return;
564            }
565        };
566        let mut store = crate::config::CredentialsStore::load();
567        store.accounts.insert(account.name.clone(), fresh.clone());
568        store.save().ok();
569        if fresh.id_token.is_some() {
570            crate::oauth::write_codex_auth_file(&fresh);
571        }
572
573        match do_get(&fresh.access_token).send().await {
574            Ok(r2) if r2.status() == reqwest::StatusCode::UNAUTHORIZED => {
575                tracing::error!(account = %account.name, "401 after refresh — needs re-authorization");
576                state.set_auth_failed(&account.name);
577            }
578            Ok(_) => tracing::info!(account = %account.name, "auth probe ok after refresh"),
579            Err(e) => tracing::warn!(account = %account.name, "auth probe retry failed: {e}"),
580        }
581    } else {
582        tracing::info!(account = %account.name, status = %resp.status(), "auth probe ok");
583        // Access token is valid. Do NOT refresh here — rotating the refresh_token races
584        // with codex CLI, which also tries to refresh at startup using the same token.
585        // Proactive refreshing is handled solely by openai_token_refresh_loop.
586    }
587}
588
589// ---------------------------------------------------------------------------
590// Proactive OpenAI token refresh loop
591// ---------------------------------------------------------------------------
592
593/// Returns true if the id_token inside `cred` has fewer than `threshold_mins`
594/// minutes remaining, or if there is no id_token / it cannot be parsed.
595fn id_token_expires_soon(cred: &crate::oauth::OAuthCredential, threshold_mins: u64) -> bool {
596    let Some(ref id_tok) = cred.id_token else { return true };
597    let Some(exp_ms) = crate::oauth::jwt_exp_ms(id_tok) else { return true };
598    let now_ms = std::time::SystemTime::now()
599        .duration_since(std::time::UNIX_EPOCH)
600        .unwrap_or_default()
601        .as_millis() as u64;
602    exp_ms < now_ms + threshold_mins * 60 * 1_000
603}
604
605/// Sync live_creds from auth.json if auth.json has a newer token.
606///
607/// Codex CLI refreshes its own token and writes auth.json. Before we refresh,
608/// we pull that in so we don't use a stale refresh_token that codex already rotated.
609async fn sync_live_creds_from_auth_json(
610    account_name: &str,
611    live_creds: &LiveCredentials,
612) {
613    let Some(from_file) = crate::oauth::read_codex_credentials() else { return };
614    let current_exp = live_creds.read().await
615        .get(account_name)
616        .map(|c| c.expires_at)
617        .unwrap_or(0);
618    if from_file.expires_at > current_exp {
619        tracing::info!(account = %account_name, "synced fresher token from auth.json");
620        live_creds.write().await.insert(account_name.to_owned(), from_file);
621    }
622}
623
624/// Perform a single proactive refresh for one account and persist the result.
625async fn do_proactive_refresh(
626    account: &crate::config::AccountConfig,
627    creds: &crate::oauth::OAuthCredential,
628    live_creds: &LiveCredentials,
629    state: &StateStore,
630) {
631    tracing::info!(account = %account.name, "proactive OpenAI token refresh");
632    match account.provider.refresh_token(creds).await {
633        Ok(fresh) => {
634            tracing::info!(account = %account.name, "proactive refresh ok — auth.json updated");
635            {
636                let mut map = live_creds.write().await;
637                map.insert(account.name.clone(), fresh.clone());
638            }
639            let mut store = crate::config::CredentialsStore::load();
640            store.accounts.insert(account.name.clone(), fresh.clone());
641            store.save().ok();
642            if fresh.id_token.is_some() {
643                crate::oauth::write_codex_auth_file(&fresh);
644            }
645            state.clear_auth_failed(&account.name);
646        }
647        Err(e) => {
648            tracing::warn!(account = %account.name, "proactive refresh failed: {e}");
649            state.set_auth_failed(&account.name);
650        }
651    }
652}
653
654/// Keeps OpenAI `id_token`s perpetually fresh.
655///
656/// Strategy:
657/// - At startup: only refresh if the id_token is already expired (< 2 min left).
658///   If the token is fresh, we skip — codex CLI does its own startup refresh and
659///   rotating the token from two places simultaneously causes "invalid_grant".
660/// - Every 45 minutes: re-sync from auth.json (codex may have refreshed it),
661///   then refresh only if id_token has < 15 minutes left.
662///
663/// This avoids racing with codex CLI's startup refresh while still ensuring
664/// the token is always fresh when codex needs it.
665pub async fn openai_token_refresh_loop(
666    config: Arc<Config>,
667    state: StateStore,
668    live_creds: LiveCredentials,
669) {
670    // Startup pass: only refresh if token is already expired.
671    for account in config.accounts.iter()
672        .filter(|a| a.provider == crate::provider::Provider::OpenAI)
673    {
674        if state.account_states().get(&account.name).map(|s| s.auth_failed).unwrap_or(false) {
675            continue;
676        }
677        let creds = {
678            let map = live_creds.read().await;
679            map.get(&account.name).cloned().or_else(|| account.credential.clone())
680        };
681        if let Some(creds) = creds {
682            if id_token_expires_soon(&creds, 2) {
683                // Token already expired (or expiring within 2 min) at startup — refresh now.
684                do_proactive_refresh(account, &creds, &live_creds, &state).await;
685            } else {
686                tracing::info!(account = %account.name, "id_token fresh at startup — skipping immediate refresh");
687            }
688        }
689    }
690
691    loop {
692        // Check every 45 minutes. This is well within the 60-minute id_token TTL,
693        // so we'll always catch expiring tokens before codex CLI needs to.
694        tokio::time::sleep(std::time::Duration::from_secs(45 * 60)).await;
695
696        for account in config.accounts.iter()
697            .filter(|a| a.provider == crate::provider::Provider::OpenAI)
698        {
699            if state.account_states().get(&account.name).map(|s| s.auth_failed).unwrap_or(false) {
700                continue;
701            }
702
703            // Pull in any token rotation codex CLI has done since our last refresh.
704            sync_live_creds_from_auth_json(&account.name, &live_creds).await;
705
706            let creds = {
707                let map = live_creds.read().await;
708                map.get(&account.name).cloned().or_else(|| account.credential.clone())
709            };
710            let Some(creds) = creds else { continue };
711
712            // Only refresh if id_token has < 15 minutes left.
713            if !id_token_expires_soon(&creds, 15) {
714                tracing::debug!(account = %account.name, "id_token still fresh, skipping refresh");
715                continue;
716            }
717
718            do_proactive_refresh(account, &creds, &live_creds, &state).await;
719        }
720    }
721}
722
723// ---------------------------------------------------------------------------
724// Error type
725// ---------------------------------------------------------------------------
726
727enum ProxyError {
728    BodyRead,
729    Upstream,
730    AllAccountsUnavailable,
731    Unauthorized,
732}
733
734impl IntoResponse for ProxyError {
735    fn into_response(self) -> Response {
736        let (status, msg) = match self {
737            ProxyError::BodyRead => (StatusCode::BAD_REQUEST, "failed to read request body"),
738            ProxyError::Upstream => (StatusCode::BAD_GATEWAY, "upstream request failed"),
739            ProxyError::AllAccountsUnavailable => {
740                (StatusCode::SERVICE_UNAVAILABLE, "all accounts are on cooldown or disabled")
741            }
742            ProxyError::Unauthorized => (StatusCode::UNAUTHORIZED, "invalid or missing api key"),
743        };
744
745        (status, axum::Json(json!({
746            "type": "error",
747            "error": {"type": "api_error", "message": msg}
748        }))).into_response()
749    }
750}
751
752// ---------------------------------------------------------------------------
753// Recovery watcher — periodically retries token refresh for auth_failed accounts
754// ---------------------------------------------------------------------------
755
756/// Runs as a background task. Every 2 minutes, tries to refresh tokens for any
757/// auth_failed account. If refresh succeeds the account is brought back online
758/// without a process restart. If all accounts remain unrecoverable, fires a
759/// macOS notification (at most once per hour).
760pub async fn recovery_watcher(
761    config: Arc<Config>,
762    state: StateStore,
763    credentials: LiveCredentials,
764) {
765    use std::time::{Duration, Instant};
766    const CHECK_INTERVAL: Duration = Duration::from_secs(120);
767    const NOTIFY_COOLDOWN: Duration = Duration::from_secs(3600);
768
769    let account_names: Vec<String> = config.accounts.iter().map(|a| a.name.clone()).collect();
770    let mut last_notified: Option<Instant> = None;
771
772    loop {
773        tokio::time::sleep(CHECK_INTERVAL).await;
774
775        let name_refs: Vec<&str> = account_names.iter().map(String::as_str).collect();
776        let failed = state.auth_failed_accounts(&name_refs);
777        if failed.is_empty() {
778            last_notified = None;
779            continue;
780        }
781
782        tracing::warn!(
783            accounts = ?failed,
784            "recovery: {} account(s) auth_failed, attempting token refresh",
785            failed.len()
786        );
787
788        let mut any_recovered = false;
789
790        for name in &failed {
791            let cred = {
792                let map = credentials.read().await;
793                map.get(*name).cloned()
794            };
795            let Some(cred) = cred else { continue };
796            if cred.refresh_token.is_empty() { continue; }
797
798            let provider = config.accounts.iter()
799                .find(|a| a.name == *name)
800                .map(|a| a.provider.clone())
801                .unwrap_or_default();
802
803            let result = tokio::time::timeout(
804                Duration::from_secs(20),
805                provider.refresh_token(&cred),
806            ).await;
807
808            match result {
809                Ok(Ok(fresh)) => {
810                    tracing::info!(account = %name, "recovery: token refreshed — account back online");
811                    {
812                        let mut map = credentials.write().await;
813                        map.insert(name.to_string(), fresh.clone());
814                    }
815                    let name_owned = name.to_string();
816                    let fresh_owned = fresh.clone();
817                    tokio::task::spawn_blocking(move || {
818                        let mut store = crate::config::CredentialsStore::load();
819                        store.accounts.insert(name_owned, fresh_owned.clone());
820                        store.save().ok();
821                        if fresh_owned.id_token.is_some() {
822                            crate::oauth::write_codex_auth_file(&fresh_owned);
823                        }
824                    });
825                    state.clear_auth_failed(name);
826                    any_recovered = true;
827                }
828                Ok(Err(e)) => {
829                    tracing::error!(account = %name, error = %e, "recovery: token refresh failed");
830                }
831                Err(_) => {
832                    tracing::error!(account = %name, "recovery: token refresh timed out");
833                }
834            }
835        }
836
837        if any_recovered {
838            tracing::info!("recovery: at least one account is back online");
839            continue;
840        }
841
842        // All accounts still auth_failed after refresh attempts — notify.
843        let still_failed = state.auth_failed_accounts(&name_refs);
844        if still_failed.len() == account_names.len() {
845            let should_notify = last_notified
846                .map(|t| t.elapsed() >= NOTIFY_COOLDOWN)
847                .unwrap_or(true);
848            if should_notify {
849                error!(
850                    "ALL accounts are offline (auth failed). \
851                     Run `shunt add-account` to re-authorize."
852                );
853                notify_all_accounts_offline();
854                last_notified = Some(Instant::now());
855            }
856        }
857    }
858}
859
860fn notify_all_accounts_offline() {
861    #[cfg(target_os = "macos")]
862    {
863        let _ = std::process::Command::new("osascript")
864            .args(["-e", concat!(
865                r#"display notification "#,
866                r#""All accounts have lost authentication. Run `shunt add-account` to re-authorize." "#,
867                r#"with title "shunt: All Accounts Offline" sound name "Basso""#
868            )])
869            .status();
870    }
871}
872
873// ---------------------------------------------------------------------------
874// OpenAI-compatible API (translates to Anthropic Claude)
875// ---------------------------------------------------------------------------
876//
877// When the OpenAI proxy receives a request at /v1/chat/completions, if an
878// anthropic_base_url is configured, it translates the request to Anthropic
879// Messages format and forwards it to the Anthropic proxy (which handles
880// account selection, token management, and rate limiting).
881// The response is translated back to OpenAI Chat Completions format.
882
883/// Map OpenAI model names → Claude model names.
884fn map_model(openai_model: &str) -> &'static str {
885    match openai_model {
886        m if m.starts_with("claude-") => {
887            // Already a Claude model name — but we need a &'static str, so match known ones
888            // or fall through to default
889            if m.contains("opus")   { "claude-opus-4-6" }
890            else if m.contains("haiku") { "claude-haiku-4-5-20251001" }
891            else                    { "claude-sonnet-4-6" }
892        }
893        "gpt-4o" | "gpt-4.5" | "o1" | "o1-pro" | "o3" | "o3-pro" | "gpt-5" | "gpt-5.5" => {
894            "claude-opus-4-6"
895        }
896        "gpt-4o-mini" | "gpt-4o-mini-2024-07-18" | "o1-mini" | "o3-mini" => {
897            "claude-haiku-4-5-20251001"
898        }
899        _ => "claude-sonnet-4-6",
900    }
901}
902
903/// Translate an OpenAI Chat Completions request body to an Anthropic Messages body.
904fn translate_to_anthropic(body: serde_json::Value) -> serde_json::Value {
905    let model = body["model"].as_str().unwrap_or("gpt-4o");
906    let claude_model = map_model(model).to_owned();
907
908    // Extract system message from messages array.
909    let mut system: Option<String> = None;
910    let mut messages = Vec::new();
911    if let Some(arr) = body["messages"].as_array() {
912        for msg in arr {
913            let role = msg["role"].as_str().unwrap_or("");
914            let content = msg["content"].as_str().unwrap_or("").to_owned();
915            if role == "system" {
916                system = Some(content);
917            } else {
918                messages.push(json!({ "role": role, "content": content }));
919            }
920        }
921    }
922
923    let max_tokens = body["max_tokens"].as_u64().unwrap_or(8096);
924    let stream = body["stream"].as_bool().unwrap_or(false);
925
926    let mut req = json!({
927        "model": claude_model,
928        "messages": messages,
929        "max_tokens": max_tokens,
930        "stream": stream,
931    });
932
933    if let Some(sys) = system {
934        req["system"] = json!(sys);
935    }
936    if let Some(temp) = body.get("temperature") {
937        req["temperature"] = temp.clone();
938    }
939    if let Some(sp) = body.get("stop") {
940        req["stop_sequences"] = sp.clone();
941    }
942
943    req
944}
945
946/// Translate a complete (non-streaming) Anthropic Messages response to OpenAI format.
947fn translate_from_anthropic(body: serde_json::Value) -> serde_json::Value {
948    let id = format!("chatcmpl-{}", &uuid_v4()[..8]);
949    let model = body["model"].as_str().unwrap_or("claude-sonnet-4-6").to_owned();
950    let content = body["content"]
951        .as_array()
952        .and_then(|arr| arr.iter().find_map(|b| b["text"].as_str()))
953        .unwrap_or("")
954        .to_owned();
955    let stop_reason = body["stop_reason"].as_str().unwrap_or("end_turn");
956    let finish_reason = if stop_reason == "end_turn" { "stop" } else { stop_reason };
957    let input_tokens = body["usage"]["input_tokens"].as_u64().unwrap_or(0);
958    let output_tokens = body["usage"]["output_tokens"].as_u64().unwrap_or(0);
959
960    json!({
961        "id": id,
962        "object": "chat.completion",
963        "model": model,
964        "choices": [{
965            "index": 0,
966            "message": { "role": "assistant", "content": content },
967            "finish_reason": finish_reason,
968        }],
969        "usage": {
970            "prompt_tokens": input_tokens,
971            "completion_tokens": output_tokens,
972            "total_tokens": input_tokens + output_tokens,
973        }
974    })
975}
976
977fn uuid_v4() -> String {
978    use crate::oauth::rand_bytes;
979    let b: [u8; 16] = rand_bytes();
980    format!("{:08x}-{:04x}-{:04x}-{:04x}-{:012x}",
981        u32::from_be_bytes(b[0..4].try_into().unwrap()),
982        u16::from_be_bytes(b[4..6].try_into().unwrap()),
983        u16::from_be_bytes(b[6..8].try_into().unwrap()),
984        u16::from_be_bytes(b[8..10].try_into().unwrap()),
985        {
986            let mut v = 0u64;
987            for &x in &b[10..16] { v = (v << 8) | x as u64; }
988            v
989        }
990    )
991}
992
993/// GET /v1/models — return Claude models in OpenAI format.
994async fn openai_models_handler() -> impl IntoResponse {
995    axum::Json(json!({
996        "object": "list",
997        "data": [
998            { "id": "claude-opus-4-6",           "object": "model", "owned_by": "anthropic" },
999            { "id": "claude-sonnet-4-6",          "object": "model", "owned_by": "anthropic" },
1000            { "id": "claude-haiku-4-5-20251001",  "object": "model", "owned_by": "anthropic" },
1001        ]
1002    }))
1003}
1004
1005/// POST /v1/chat/completions — translate OpenAI request to Anthropic, proxy through Claude pool.
1006async fn openai_compat_handler(
1007    State(s): State<AppState>,
1008    req: Request,
1009) -> Result<Response, ProxyError> {
1010    let Some(ref anthropic_url) = s.anthropic_base_url else {
1011        // No Anthropic proxy configured — fall back to normal forwarding
1012        return proxy_handler(State(s), req).await;
1013    };
1014
1015    let body_bytes = axum::body::to_bytes(req.into_body(), usize::MAX)
1016        .await
1017        .map_err(|_| ProxyError::BodyRead)?;
1018
1019    let openai_body: serde_json::Value = serde_json::from_slice(&body_bytes)
1020        .unwrap_or(json!({}));
1021
1022    let stream = openai_body["stream"].as_bool().unwrap_or(false);
1023    let anthropic_body = translate_to_anthropic(openai_body);
1024
1025    let client = reqwest::Client::builder()
1026        .timeout(std::time::Duration::from_secs(300))
1027        .build()
1028        .map_err(|_| ProxyError::Upstream)?;
1029
1030    let resp = client
1031        .post(format!("{anthropic_url}/v1/messages"))
1032        .header("content-type", "application/json")
1033        .header("anthropic-version", "2023-06-01")
1034        .header("anthropic-beta", "claude-code-20250219,oauth-2025-04-20")
1035        .header("x-shunt-compat", "openai")
1036        .json(&anthropic_body)
1037        .send()
1038        .await
1039        .map_err(|_| ProxyError::Upstream)?;
1040
1041    if !resp.status().is_success() {
1042        let status = resp.status();
1043        let body = resp.text().await.unwrap_or_default();
1044        let code = status.as_u16();
1045        return Ok(axum::response::Response::builder()
1046            .status(code)
1047            .header("content-type", "application/json")
1048            .body(axum::body::Body::from(body))
1049            .unwrap());
1050    }
1051
1052    if stream {
1053        // Translate Anthropic SSE stream → OpenAI SSE stream
1054        let chat_id = format!("chatcmpl-{}", &uuid_v4()[..8]);
1055        let stream = translate_anthropic_stream(resp, chat_id);
1056        Ok(axum::response::Response::builder()
1057            .status(200)
1058            .header("content-type", "text/event-stream")
1059            .header("cache-control", "no-cache")
1060            .body(axum::body::Body::from_stream(stream))
1061            .unwrap())
1062    } else {
1063        let anthropic_resp: serde_json::Value = resp.json().await.map_err(|_| ProxyError::Upstream)?;
1064        let openai_resp = translate_from_anthropic(anthropic_resp);
1065        Ok(axum::Json(openai_resp).into_response())
1066    }
1067}
1068
1069/// Translate Anthropic SSE events to OpenAI SSE format, yielding raw bytes.
1070fn translate_anthropic_stream(
1071    resp: reqwest::Response,
1072    chat_id: String,
1073) -> impl futures_util::Stream<Item = Result<bytes::Bytes, std::io::Error>> {
1074    use futures_util::StreamExt;
1075
1076    let id = chat_id;
1077    let byte_stream = resp.bytes_stream();
1078
1079    async_stream::stream! {
1080        let mut buf = String::new();
1081        futures_util::pin_mut!(byte_stream);
1082
1083        // Send initial role chunk
1084        let init = format!(
1085            "data: {}\n\n",
1086            serde_json::to_string(&json!({
1087                "id": id,
1088                "object": "chat.completion.chunk",
1089                "choices": [{"index": 0, "delta": {"role": "assistant", "content": ""}, "finish_reason": null}]
1090            })).unwrap()
1091        );
1092        yield Ok(bytes::Bytes::from(init));
1093
1094        while let Some(chunk) = byte_stream.next().await {
1095            let chunk = match chunk {
1096                Ok(c) => c,
1097                Err(_) => break,
1098            };
1099            buf.push_str(&String::from_utf8_lossy(&chunk));
1100
1101            // Process complete SSE lines
1102            while let Some(nl) = buf.find('\n') {
1103                let line = buf[..nl].trim_end_matches('\r').to_owned();
1104                buf = buf[nl + 1..].to_owned();
1105
1106                if !line.starts_with("data: ") { continue; }
1107                let data = &line["data: ".len()..];
1108                if data == "[DONE]" { continue; }
1109
1110                let Ok(event) = serde_json::from_str::<serde_json::Value>(data) else { continue };
1111                let event_type = event["type"].as_str().unwrap_or("");
1112
1113                let maybe_chunk = match event_type {
1114                    "content_block_delta" => {
1115                        let text = event["delta"]["text"].as_str().unwrap_or("");
1116                        if text.is_empty() { continue; }
1117                        Some(json!({
1118                            "id": id,
1119                            "object": "chat.completion.chunk",
1120                            "choices": [{"index": 0, "delta": {"content": text}, "finish_reason": null}]
1121                        }))
1122                    }
1123                    "message_delta" => {
1124                        let stop_reason = event["delta"]["stop_reason"].as_str().unwrap_or("stop");
1125                        let finish = if stop_reason == "end_turn" { "stop" } else { stop_reason };
1126                        Some(json!({
1127                            "id": id,
1128                            "object": "chat.completion.chunk",
1129                            "choices": [{"index": 0, "delta": {}, "finish_reason": finish}]
1130                        }))
1131                    }
1132                    _ => None,
1133                };
1134
1135                if let Some(c) = maybe_chunk {
1136                    let out = format!("data: {}\n\n", serde_json::to_string(&c).unwrap());
1137                    yield Ok(bytes::Bytes::from(out));
1138                }
1139            }
1140        }
1141
1142        yield Ok(bytes::Bytes::from("data: [DONE]\n\n"));
1143    }
1144}