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 credentials: Arc<RwLock<HashMap<String, OAuthCredential>>>,
29 started_ms: u64,
31 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
41pub 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 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 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 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 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 let mut refreshed: HashSet<String> = HashSet::new();
246 let wait_deadline_ms = now_ms() + 5 * 60 * 60 * 1_000;
248
249 loop {
250 let account = match router::pick_account(
251 &s.config.accounts, &s.state, fp_ref, &tried,
252 s.config.server.sticky_ttl_ms, s.config.server.expiry_soon_secs,
253 ) {
254 Some(a) => a,
255 None => {
256 let account_states = s.state.account_states();
260 let now = now_ms();
261 let soonest_ms = s.config.accounts.iter()
262 .filter_map(|a| {
263 let st = account_states.get(&a.name)?;
264 if st.disabled { return None; } if st.cooldown_until_ms > now { Some(st.cooldown_until_ms) } else { None }
266 })
267 .min();
268
269 match soonest_ms {
270 Some(wake_ms) if wake_ms <= wait_deadline_ms => {
271 let wait_ms = wake_ms.saturating_sub(now_ms()) + 50; warn!(wait_ms, "all accounts cooling — waiting for next available account");
273 tokio::time::sleep(std::time::Duration::from_millis(wait_ms)).await;
274 tried.clear(); }
276 _ => return Err(ProxyError::AllAccountsUnavailable),
277 }
278 continue;
279 }
280 };
281
282 let account_name = account.name.clone();
283
284 let token = {
288 let creds = s.credentials.read().await;
289 let cred = creds.get(&account_name)
290 .cloned()
291 .or_else(|| account.credential.clone());
292 match cred {
293 Some(c) => c.access_token,
294 None => String::new(),
295 }
296 };
297
298 let response = s.forwarder
299 .forward(&method, &path, body_bytes.clone(), &headers, account, &token)
300 .await
301 .map_err(|e| {
302 error!("Forward error: {:#}", e);
303 ProxyError::Upstream
304 })?;
305
306 match response.status().as_u16() {
307 200..=299 => {
308 s.state.set_last_used(&account_name);
309 if let Some(info) = account.provider.parse_rate_limits(response.headers()) {
310 s.state.update_rate_limits(&account_name, info);
311 }
312 return Ok(tap_usage(response, &s.state, &account_name, &model, req_start_ms).await);
313 }
314 429 => {
315 let info = account.provider.parse_rate_limits(response.headers());
316 let cooldown_ms = info.as_ref()
319 .and_then(|i| i.reset_5h.or(i.reset_7d))
320 .map(|reset_secs| {
321 let reset_ms = reset_secs.saturating_mul(1_000);
322 reset_ms.saturating_sub(now_ms()).saturating_add(500) })
324 .unwrap_or(60_000);
325 warn!(account = %account_name, cooldown_ms, "429 rate-limited — cooling until reset");
326 if let Some(info) = info {
327 s.state.update_rate_limits(&account_name, info);
328 }
329 s.state.set_cooldown(&account_name, cooldown_ms);
330 if cooldown_ms >= 5 * 60_000 {
331 let mins = cooldown_ms / 60_000;
332 notify(
333 "shunt: Rate Limited",
334 &format!("Account '{account_name}' hit quota limit — cooling {mins}m."),
335 "Ping",
336 );
337 }
338 tried.insert(account_name);
339 }
340 529 => {
341 warn!(account = %account_name, "529 overloaded — cooling 30s");
342 if let Some(info) = account.provider.parse_rate_limits(response.headers()) {
343 s.state.update_rate_limits(&account_name, info);
344 }
345 s.state.set_cooldown(&account_name, 30_000);
346 tried.insert(account_name);
347 }
348 401 => {
349 if !refreshed.contains(&account_name) {
350 let cred = {
352 let creds = s.credentials.read().await;
353 creds.get(&account_name).cloned()
354 .or_else(|| account.credential.clone())
355 };
356 let Some(cred) = cred else {
357 tried.insert(account_name);
358 continue;
359 };
360 match tokio::time::timeout(
361 std::time::Duration::from_secs(10),
362 account.provider.refresh_token(&cred),
363 ).await {
364 Ok(Ok(fresh)) => {
365 warn!(account = %account_name, "401 — token refreshed, retrying");
366 {
367 let mut creds = s.credentials.write().await;
368 creds.insert(account_name.clone(), fresh.clone());
369 }
370 let name = account_name.clone();
372 let fresh = fresh.clone();
373 tokio::task::spawn_blocking(move || {
374 let mut store = CredentialsStore::load();
375 store.accounts.insert(name, fresh.clone());
376 store.save().ok();
377 if fresh.id_token.is_some() {
378 crate::oauth::write_codex_auth_file(&fresh);
379 }
380 });
381 refreshed.insert(account_name);
383 }
384 _ => {
385 error!(account = %account_name, "401 — token refresh failed, cooling 5min");
387 s.state.set_cooldown(&account_name, 5 * 60_000);
388 tried.insert(account_name);
389 }
390 }
391 } else {
392 error!(account = %account_name, "401 after refresh — cooling 5min");
394 s.state.set_cooldown(&account_name, 5 * 60_000);
395 tried.insert(account_name);
396 }
397 }
398 403 => {
399 error!(account = %account_name, "403 forbidden — cooling 30min");
401 s.state.set_cooldown(&account_name, 30 * 60_000);
402 notify(
403 "shunt: Account Forbidden",
404 &format!("Account '{account_name}' got 403 — subscription may have lapsed (cooling 30m)."),
405 "Basso",
406 );
407 tried.insert(account_name);
408 }
409 _ => {
410 return Ok(response);
412 }
413 }
414 }
415}
416
417async fn tap_usage(
426 resp: Response,
427 state: &StateStore,
428 account: &str,
429 model: &str,
430 req_start_ms: u64,
431) -> Response {
432 use axum::body::Body;
433 use crate::state::RequestLog;
434
435 if quota::is_streaming_response(&resp) {
436 let state = state.clone();
437 let account = account.to_owned();
438 let model = model.to_owned();
439 let on_complete = Arc::new(move |input: u64, output: u64| {
440 state.record_usage(&account, input, output);
441 state.record_global(&model, input, output);
442 state.record_request(RequestLog {
443 ts_ms: req_start_ms,
444 account: account.clone(),
445 model: model.clone(),
446 status: 200,
447 input_tokens: input,
448 output_tokens: output,
449 duration_ms: now_ms().saturating_sub(req_start_ms),
450 });
451 });
452 let (parts, body) = resp.into_parts();
453 let wrapped = quota::wrap_streaming_body(body, on_complete);
454 return Response::from_parts(parts, wrapped);
455 }
456
457 let (parts, body) = resp.into_parts();
459 let bytes = match axum::body::to_bytes(body, 64 * 1024 * 1024).await {
460 Ok(b) => b,
461 Err(_) => return Response::from_parts(parts, Body::empty()),
462 };
463 let (input, output) = quota::extract_usage_from_json(&bytes);
464 state.record_usage(account, input, output);
465 state.record_global(model, input, output);
466 state.record_request(RequestLog {
467 ts_ms: req_start_ms,
468 account: account.to_owned(),
469 model: model.to_owned(),
470 status: 200,
471 input_tokens: input,
472 output_tokens: output,
473 duration_ms: now_ms().saturating_sub(req_start_ms),
474 });
475 Response::from_parts(parts, Body::from(bytes))
476}
477
478
479pub async fn prefetch_rate_limits(config: Arc<Config>, state: StateStore) {
487 let client = reqwest::Client::builder()
488 .timeout(std::time::Duration::from_secs(20))
489 .build()
490 .unwrap_or_default();
491
492 for account in &config.accounts {
493 let rl = state.rate_limit_snapshot();
495 if let Some(r) = rl.get(&account.name) {
496 if r.utilization_5h.is_some() || r.utilization_7d.is_some() {
497 continue;
498 }
499 }
500
501 let creds = match account.credential.clone() {
503 Some(c) => c,
504 None => continue,
505 };
506
507 let Some((path, body)) = account.provider.prefetch_request() else {
508 if let Some(probe_path) = account.provider.auth_probe_get_path() {
510 auth_probe_get(&client, probe_path, account, &state).await;
511 }
512 continue;
513 };
514 let url = format!("{}{}", config.server.upstream_url, path);
515
516 let resp = prefetch_send(&client, &url, &account.provider, &creds.access_token, &body).await;
517
518 let r = match resp {
519 Ok(r) => r,
520 Err(e) => { tracing::warn!(account = %account.name, "prefetch failed: {e}"); continue; }
521 };
522
523 if r.status() == reqwest::StatusCode::UNAUTHORIZED {
524 tracing::info!(account = %account.name, "prefetch: token expired, refreshing");
525 let fresh = match account.provider.refresh_token(&creds).await {
526 Ok(f) => f,
527 Err(e) => {
528 tracing::warn!(account = %account.name, "token refresh failed: {e}");
529 state.set_auth_failed(&account.name);
530 continue;
531 }
532 };
533 let mut store = crate::config::CredentialsStore::load();
534 store.accounts.insert(account.name.clone(), fresh.clone());
535 store.save().ok();
536 if fresh.id_token.is_some() {
537 crate::oauth::write_codex_auth_file(&fresh);
538 }
539
540 match prefetch_send(&client, &url, &account.provider, &fresh.access_token, &body).await {
541 Ok(r2) if r2.status() == reqwest::StatusCode::UNAUTHORIZED => {
542 tracing::error!(account = %account.name, "401 after refresh — needs re-authorization");
543 state.set_auth_failed(&account.name);
544 }
545 Ok(r2) => {
546 if let Some(info) = account.provider.parse_rate_limits(r2.headers()) {
547 state.update_rate_limits(&account.name, info);
548 }
549 }
550 Err(e) => tracing::warn!(account = %account.name, "prefetch retry failed: {e}"),
551 }
552 } else {
553 tracing::info!(account = %account.name, status = %r.status(), "prefetch response");
554 if let Some(info) = account.provider.parse_rate_limits(r.headers()) {
555 state.update_rate_limits(&account.name, info);
556 }
557 }
558 }
559}
560
561async fn prefetch_send(
563 client: &reqwest::Client,
564 url: &str,
565 provider: &crate::provider::Provider,
566 token: &str,
567 body: &serde_json::Value,
568) -> anyhow::Result<reqwest::Response> {
569 let mut headers = reqwest::header::HeaderMap::new();
570 provider.inject_auth_headers(&mut headers, token)?;
571 for (name, value) in provider.prefetch_extra_headers() {
572 headers.insert(
573 reqwest::header::HeaderName::from_bytes(name.as_bytes())?,
574 reqwest::header::HeaderValue::from_static(value),
575 );
576 }
577 Ok(client.post(url).headers(headers).json(body).send().await?)
578}
579
580async fn auth_probe_get(
584 client: &reqwest::Client,
585 path: &str,
586 account: &crate::config::AccountConfig,
587 state: &StateStore,
588) {
589 let creds = match account.credential.clone() {
590 Some(c) => c,
591 None => return,
592 };
593 let upstream = match account.provider {
594 crate::provider::Provider::OpenAI => "https://chatgpt.com",
595 crate::provider::Provider::Anthropic => "https://api.anthropic.com",
596 };
597 let url = format!("{}{}", upstream, path);
598
599 let do_get = |token: &str| -> reqwest::RequestBuilder {
600 let mut headers = reqwest::header::HeaderMap::new();
601 let _ = account.provider.inject_auth_headers(&mut headers, token);
602 client.get(&url).headers(headers)
603 };
604
605 let probe_token = &creds.access_token;
606 let resp = match do_get(probe_token).send().await {
607 Ok(r) => r,
608 Err(e) => { tracing::warn!(account = %account.name, "auth probe failed: {e}"); return; }
609 };
610
611 if resp.status() == reqwest::StatusCode::UNAUTHORIZED {
612 tracing::info!(account = %account.name, "auth probe: access token rejected, refreshing");
613 let fresh = match account.provider.refresh_token(&creds).await {
614 Ok(f) => f,
615 Err(e) => {
616 tracing::warn!(account = %account.name, "token refresh failed: {e}");
617 state.set_auth_failed(&account.name);
618 return;
619 }
620 };
621 let mut store = crate::config::CredentialsStore::load();
622 store.accounts.insert(account.name.clone(), fresh.clone());
623 store.save().ok();
624 if fresh.id_token.is_some() {
625 crate::oauth::write_codex_auth_file(&fresh);
626 }
627
628 let fresh_token = fresh.id_token.as_deref().unwrap_or(&fresh.access_token);
629 match do_get(fresh_token).send().await {
630 Ok(r2) if r2.status() == reqwest::StatusCode::UNAUTHORIZED => {
631 tracing::error!(account = %account.name, "401 after refresh — needs re-authorization");
632 state.set_auth_failed(&account.name);
633 }
634 Ok(_) => tracing::info!(account = %account.name, "auth probe ok after refresh"),
635 Err(e) => tracing::warn!(account = %account.name, "auth probe retry failed: {e}"),
636 }
637 } else {
638 tracing::info!(account = %account.name, status = %resp.status(), "auth probe ok");
639 }
643}
644
645fn access_token_expires_soon(cred: &crate::oauth::OAuthCredential, threshold_mins: u64) -> bool {
652 let now_ms = std::time::SystemTime::now()
653 .duration_since(std::time::UNIX_EPOCH)
654 .unwrap_or_default()
655 .as_millis() as u64;
656 let exp_ms = crate::oauth::jwt_exp_ms(&cred.access_token)
657 .unwrap_or(cred.expires_at);
658 exp_ms < now_ms + threshold_mins * 60 * 1_000
659}
660
661async fn sync_live_creds_from_auth_json(
666 account_name: &str,
667 live_creds: &LiveCredentials,
668) {
669 let Some(from_file) = crate::oauth::read_codex_credentials() else { return };
670 let current_exp = live_creds.read().await
671 .get(account_name)
672 .map(|c| c.expires_at)
673 .unwrap_or(0);
674 if from_file.expires_at > current_exp {
675 tracing::info!(account = %account_name, "synced fresher token from auth.json");
676 live_creds.write().await.insert(account_name.to_owned(), from_file);
677 }
678}
679
680async fn do_proactive_refresh(
682 account: &crate::config::AccountConfig,
683 creds: &crate::oauth::OAuthCredential,
684 live_creds: &LiveCredentials,
685 state: &StateStore,
686) {
687 tracing::info!(account = %account.name, "proactive OpenAI token refresh");
688 match account.provider.refresh_token(creds).await {
689 Ok(fresh) => {
690 tracing::info!(account = %account.name, "proactive refresh ok — auth.json updated");
691 {
692 let mut map = live_creds.write().await;
693 map.insert(account.name.clone(), fresh.clone());
694 }
695 let mut store = crate::config::CredentialsStore::load();
696 store.accounts.insert(account.name.clone(), fresh.clone());
697 store.save().ok();
698 if fresh.id_token.is_some() {
699 crate::oauth::write_codex_auth_file(&fresh);
700 }
701 state.clear_auth_failed(&account.name);
702 }
703 Err(e) => {
704 tracing::warn!(account = %account.name, "proactive refresh failed: {e}");
705 state.set_auth_failed(&account.name);
706 }
707 }
708}
709
710
711pub async fn openai_token_refresh_loop(
719 config: Arc<Config>,
720 state: StateStore,
721 live_creds: LiveCredentials,
722) {
723 for account in config.accounts.iter()
725 .filter(|a| a.provider == crate::provider::Provider::OpenAI)
726 {
727 if state.account_states().get(&account.name).map(|s| s.auth_failed).unwrap_or(false) {
728 continue;
729 }
730 sync_live_creds_from_auth_json(&account.name, &live_creds).await;
731
732 let creds = {
733 let map = live_creds.read().await;
734 map.get(&account.name).cloned().or_else(|| account.credential.clone())
735 };
736 if let Some(creds) = creds {
737 if access_token_expires_soon(&creds, 30) {
738 do_proactive_refresh(account, &creds, &live_creds, &state).await;
740 } else {
741 tracing::info!(account = %account.name, "access_token fresh at startup");
742 }
743 }
744 }
745
746 loop {
749 tokio::time::sleep(std::time::Duration::from_secs(5 * 60)).await;
750 for account in config.accounts.iter()
751 .filter(|a| a.provider == crate::provider::Provider::OpenAI)
752 {
753 sync_live_creds_from_auth_json(&account.name, &live_creds).await;
754 }
755 }
756}
757
758enum ProxyError {
763 BodyRead,
764 Upstream,
765 AllAccountsUnavailable,
766 Unauthorized,
767}
768
769impl IntoResponse for ProxyError {
770 fn into_response(self) -> Response {
771 let (status, msg) = match self {
772 ProxyError::BodyRead => (StatusCode::BAD_REQUEST, "failed to read request body"),
773 ProxyError::Upstream => (StatusCode::BAD_GATEWAY, "upstream request failed"),
774 ProxyError::AllAccountsUnavailable => {
775 (StatusCode::SERVICE_UNAVAILABLE, "all accounts are on cooldown or disabled")
776 }
777 ProxyError::Unauthorized => (StatusCode::UNAUTHORIZED, "invalid or missing api key"),
778 };
779
780 (status, axum::Json(json!({
781 "type": "error",
782 "error": {"type": "api_error", "message": msg}
783 }))).into_response()
784 }
785}
786
787pub async fn recovery_watcher(
796 config: Arc<Config>,
797 state: StateStore,
798 credentials: LiveCredentials,
799) {
800 use std::time::{Duration, Instant};
801 const CHECK_INTERVAL: Duration = Duration::from_secs(120);
802 const NOTIFY_COOLDOWN: Duration = Duration::from_secs(3600);
803
804 let account_names: Vec<String> = config.accounts.iter().map(|a| a.name.clone()).collect();
805 let mut last_notified: Option<Instant> = None;
806
807 loop {
808 tokio::time::sleep(CHECK_INTERVAL).await;
809
810 let name_refs: Vec<&str> = account_names.iter().map(String::as_str).collect();
811 let failed = state.auth_failed_accounts(&name_refs);
812 if failed.is_empty() {
813 last_notified = None;
814 continue;
815 }
816
817 tracing::warn!(
818 accounts = ?failed,
819 "recovery: {} account(s) auth_failed, attempting token refresh",
820 failed.len()
821 );
822
823 let mut any_recovered = false;
824
825 for name in &failed {
826 let cred = {
827 let map = credentials.read().await;
828 map.get(*name).cloned()
829 };
830 let Some(cred) = cred else { continue };
831 if cred.refresh_token.is_empty() { continue; }
832
833 let provider = config.accounts.iter()
834 .find(|a| a.name == *name)
835 .map(|a| a.provider.clone())
836 .unwrap_or_default();
837
838 let result = tokio::time::timeout(
839 Duration::from_secs(20),
840 provider.refresh_token(&cred),
841 ).await;
842
843 match result {
844 Ok(Ok(fresh)) => {
845 tracing::info!(account = %name, "recovery: token refreshed — account back online");
846 {
847 let mut map = credentials.write().await;
848 map.insert(name.to_string(), fresh.clone());
849 }
850 let name_owned = name.to_string();
851 let fresh_owned = fresh.clone();
852 tokio::task::spawn_blocking(move || {
853 let mut store = crate::config::CredentialsStore::load();
854 store.accounts.insert(name_owned, fresh_owned.clone());
855 store.save().ok();
856 if fresh_owned.id_token.is_some() {
857 crate::oauth::write_codex_auth_file(&fresh_owned);
858 }
859 });
860 state.clear_auth_failed(name);
861 any_recovered = true;
862 }
863 Ok(Err(e)) => {
864 tracing::error!(account = %name, error = %e, "recovery: token refresh failed");
865 notify(
866 "shunt: Reauth Required",
867 &format!("Account '{name}' needs re-authorization. Run `shunt add-account`."),
868 "Basso",
869 );
870 }
871 Err(_) => {
872 tracing::error!(account = %name, "recovery: token refresh timed out");
873 notify(
874 "shunt: Reauth Required",
875 &format!("Account '{name}' token refresh timed out. Run `shunt add-account`."),
876 "Basso",
877 );
878 }
879 }
880 }
881
882 if any_recovered {
883 tracing::info!("recovery: at least one account is back online");
884 continue;
885 }
886
887 let still_failed = state.auth_failed_accounts(&name_refs);
889 if still_failed.len() == account_names.len() {
890 let should_notify = last_notified
891 .map(|t| t.elapsed() >= NOTIFY_COOLDOWN)
892 .unwrap_or(true);
893 if should_notify {
894 error!(
895 "ALL accounts are offline (auth failed). \
896 Run `shunt add-account` to re-authorize."
897 );
898 notify(
899 "shunt: All Accounts Offline",
900 "All accounts need re-authorization. Run `shunt add-account`.",
901 "Basso",
902 );
903 last_notified = Some(Instant::now());
904 }
905 }
906 }
907}
908
909async fn post_cooldown_prefetch(
913 client: &reqwest::Client,
914 account: &crate::config::AccountConfig,
915 token: &str,
916 state: &StateStore,
917 upstream_url: &str,
918) {
919 let Some((path, body)) = account.provider.prefetch_request() else {
920 if let Some(probe_path) = account.provider.auth_probe_get_path() {
921 auth_probe_get(client, probe_path, account, state).await;
922 }
923 return;
924 };
925 let url = format!("{upstream_url}{path}");
926 match prefetch_send(client, &url, &account.provider, token, &body).await {
927 Ok(r) => {
928 if let Some(info) = account.provider.parse_rate_limits(r.headers()) {
929 state.update_rate_limits(&account.name, info);
930 tracing::info!(account = %account.name, "post-cooldown prefetch: quota refreshed");
931 }
932 }
933 Err(e) => warn!(account = %account.name, "post-cooldown prefetch failed: {e}"),
934 }
935}
936
937pub async fn cooldown_watcher(
944 config: Arc<Config>,
945 state: StateStore,
946 credentials: LiveCredentials,
947) {
948 let client = reqwest::Client::builder()
949 .timeout(std::time::Duration::from_secs(20))
950 .build()
951 .unwrap_or_default();
952
953 let mut last_resumed: HashMap<String, u64> = HashMap::new();
956 let mut notify_on_resume: HashSet<String> = HashSet::new();
958
959 loop {
960 let states = state.account_states();
961 let now = now_ms();
962 let mut next_wake_ms: Option<u64> = None;
963
964 for account in &config.accounts {
965 let Some(st) = states.get(&account.name) else { continue };
966 if st.disabled { continue; } let cdl = st.cooldown_until_ms;
968 if cdl == 0 { continue; } if cdl <= now {
971 let handled = last_resumed.get(&account.name).map(|&t| t >= cdl).unwrap_or(false);
973 if !handled {
974 tracing::info!(account = %account.name, "cooldown expired — strong resume prefetch");
975 let token = {
976 let creds = credentials.read().await;
977 creds.get(&account.name).map(|c| c.access_token.clone())
978 };
979 if let Some(token) = token {
980 post_cooldown_prefetch(
981 &client, account, &token, &state,
982 &config.server.upstream_url,
983 ).await;
984 }
985 if notify_on_resume.remove(&account.name) {
986 notify(
987 "shunt: Account Resumed",
988 &format!("Account '{}' is back online.", account.name),
989 "Glass",
990 );
991 }
992 last_resumed.insert(account.name.clone(), cdl);
993 }
994 } else {
995 let remaining = cdl - now;
997 if remaining >= 5 * 60_000 {
998 notify_on_resume.insert(account.name.clone());
999 }
1000 next_wake_ms = Some(next_wake_ms.map(|m| m.min(cdl)).unwrap_or(cdl));
1001 }
1002 }
1003
1004 let sleep_ms = next_wake_ms
1006 .map(|wake| wake.saturating_sub(now_ms()).max(50))
1007 .unwrap_or(30_000);
1008 tokio::time::sleep(std::time::Duration::from_millis(sleep_ms)).await;
1009 }
1010}
1011
1012use crate::notify::notify;
1013
1014fn map_model(openai_model: &str) -> &'static str {
1026 match openai_model {
1027 m if m.starts_with("claude-") => {
1028 if m.contains("opus") { "claude-opus-4-6" }
1031 else if m.contains("haiku") { "claude-haiku-4-5-20251001" }
1032 else { "claude-sonnet-4-6" }
1033 }
1034 "gpt-4o" | "gpt-4.5" | "o1" | "o1-pro" | "o3" | "o3-pro" | "gpt-5" | "gpt-5.5" => {
1035 "claude-opus-4-6"
1036 }
1037 "gpt-4o-mini" | "gpt-4o-mini-2024-07-18" | "o1-mini" | "o3-mini" => {
1038 "claude-haiku-4-5-20251001"
1039 }
1040 _ => "claude-sonnet-4-6",
1041 }
1042}
1043
1044fn translate_to_anthropic(body: serde_json::Value) -> serde_json::Value {
1046 let model = body["model"].as_str().unwrap_or("gpt-4o");
1047 let claude_model = map_model(model).to_owned();
1048
1049 let mut system: Option<String> = None;
1051 let mut messages = Vec::new();
1052 if let Some(arr) = body["messages"].as_array() {
1053 for msg in arr {
1054 let role = msg["role"].as_str().unwrap_or("");
1055 let content = msg["content"].as_str().unwrap_or("").to_owned();
1056 if role == "system" {
1057 system = Some(content);
1058 } else {
1059 messages.push(json!({ "role": role, "content": content }));
1060 }
1061 }
1062 }
1063
1064 let max_tokens = body["max_tokens"].as_u64().unwrap_or(8096);
1065 let stream = body["stream"].as_bool().unwrap_or(false);
1066
1067 let mut req = json!({
1068 "model": claude_model,
1069 "messages": messages,
1070 "max_tokens": max_tokens,
1071 "stream": stream,
1072 });
1073
1074 if let Some(sys) = system {
1075 req["system"] = json!(sys);
1076 }
1077 if let Some(temp) = body.get("temperature") {
1078 req["temperature"] = temp.clone();
1079 }
1080 if let Some(sp) = body.get("stop") {
1081 req["stop_sequences"] = sp.clone();
1082 }
1083
1084 req
1085}
1086
1087fn translate_from_anthropic(body: serde_json::Value) -> serde_json::Value {
1089 let id = format!("chatcmpl-{}", &uuid_v4()[..8]);
1090 let model = body["model"].as_str().unwrap_or("claude-sonnet-4-6").to_owned();
1091 let content = body["content"]
1092 .as_array()
1093 .and_then(|arr| arr.iter().find_map(|b| b["text"].as_str()))
1094 .unwrap_or("")
1095 .to_owned();
1096 let stop_reason = body["stop_reason"].as_str().unwrap_or("end_turn");
1097 let finish_reason = if stop_reason == "end_turn" { "stop" } else { stop_reason };
1098 let input_tokens = body["usage"]["input_tokens"].as_u64().unwrap_or(0);
1099 let output_tokens = body["usage"]["output_tokens"].as_u64().unwrap_or(0);
1100
1101 json!({
1102 "id": id,
1103 "object": "chat.completion",
1104 "model": model,
1105 "choices": [{
1106 "index": 0,
1107 "message": { "role": "assistant", "content": content },
1108 "finish_reason": finish_reason,
1109 }],
1110 "usage": {
1111 "prompt_tokens": input_tokens,
1112 "completion_tokens": output_tokens,
1113 "total_tokens": input_tokens + output_tokens,
1114 }
1115 })
1116}
1117
1118fn uuid_v4() -> String {
1119 use crate::oauth::rand_bytes;
1120 let b: [u8; 16] = rand_bytes();
1121 format!("{:08x}-{:04x}-{:04x}-{:04x}-{:012x}",
1122 u32::from_be_bytes(b[0..4].try_into().unwrap()),
1123 u16::from_be_bytes(b[4..6].try_into().unwrap()),
1124 u16::from_be_bytes(b[6..8].try_into().unwrap()),
1125 u16::from_be_bytes(b[8..10].try_into().unwrap()),
1126 {
1127 let mut v = 0u64;
1128 for &x in &b[10..16] { v = (v << 8) | x as u64; }
1129 v
1130 }
1131 )
1132}
1133
1134async fn openai_models_handler() -> impl IntoResponse {
1136 axum::Json(json!({
1137 "object": "list",
1138 "data": [
1139 { "id": "claude-opus-4-6", "object": "model", "owned_by": "anthropic" },
1140 { "id": "claude-sonnet-4-6", "object": "model", "owned_by": "anthropic" },
1141 { "id": "claude-haiku-4-5-20251001", "object": "model", "owned_by": "anthropic" },
1142 ]
1143 }))
1144}
1145
1146async fn openai_compat_handler(
1148 State(s): State<AppState>,
1149 req: Request,
1150) -> Result<Response, ProxyError> {
1151 let Some(ref anthropic_url) = s.anthropic_base_url else {
1152 return proxy_handler(State(s), req).await;
1154 };
1155
1156 let body_bytes = axum::body::to_bytes(req.into_body(), usize::MAX)
1157 .await
1158 .map_err(|_| ProxyError::BodyRead)?;
1159
1160 let openai_body: serde_json::Value = serde_json::from_slice(&body_bytes)
1161 .unwrap_or(json!({}));
1162
1163 let stream = openai_body["stream"].as_bool().unwrap_or(false);
1164 let anthropic_body = translate_to_anthropic(openai_body);
1165
1166 let client = reqwest::Client::builder()
1167 .timeout(std::time::Duration::from_secs(300))
1168 .build()
1169 .map_err(|_| ProxyError::Upstream)?;
1170
1171 let resp = client
1172 .post(format!("{anthropic_url}/v1/messages"))
1173 .header("content-type", "application/json")
1174 .header("anthropic-version", "2023-06-01")
1175 .header("anthropic-beta", "claude-code-20250219,oauth-2025-04-20")
1176 .header("x-shunt-compat", "openai")
1177 .json(&anthropic_body)
1178 .send()
1179 .await
1180 .map_err(|_| ProxyError::Upstream)?;
1181
1182 if !resp.status().is_success() {
1183 let status = resp.status();
1184 let body = resp.text().await.unwrap_or_default();
1185 let code = status.as_u16();
1186 return Ok(axum::response::Response::builder()
1187 .status(code)
1188 .header("content-type", "application/json")
1189 .body(axum::body::Body::from(body))
1190 .unwrap());
1191 }
1192
1193 if stream {
1194 let chat_id = format!("chatcmpl-{}", &uuid_v4()[..8]);
1196 let stream = translate_anthropic_stream(resp, chat_id);
1197 Ok(axum::response::Response::builder()
1198 .status(200)
1199 .header("content-type", "text/event-stream")
1200 .header("cache-control", "no-cache")
1201 .body(axum::body::Body::from_stream(stream))
1202 .unwrap())
1203 } else {
1204 let anthropic_resp: serde_json::Value = resp.json().await.map_err(|_| ProxyError::Upstream)?;
1205 let openai_resp = translate_from_anthropic(anthropic_resp);
1206 Ok(axum::Json(openai_resp).into_response())
1207 }
1208}
1209
1210fn translate_anthropic_stream(
1212 resp: reqwest::Response,
1213 chat_id: String,
1214) -> impl futures_util::Stream<Item = Result<bytes::Bytes, std::io::Error>> {
1215 use futures_util::StreamExt;
1216
1217 let id = chat_id;
1218 let byte_stream = resp.bytes_stream();
1219
1220 async_stream::stream! {
1221 let mut buf = String::new();
1222 futures_util::pin_mut!(byte_stream);
1223
1224 let init = format!(
1226 "data: {}\n\n",
1227 serde_json::to_string(&json!({
1228 "id": id,
1229 "object": "chat.completion.chunk",
1230 "choices": [{"index": 0, "delta": {"role": "assistant", "content": ""}, "finish_reason": null}]
1231 })).unwrap()
1232 );
1233 yield Ok(bytes::Bytes::from(init));
1234
1235 while let Some(chunk) = byte_stream.next().await {
1236 let chunk = match chunk {
1237 Ok(c) => c,
1238 Err(_) => break,
1239 };
1240 buf.push_str(&String::from_utf8_lossy(&chunk));
1241
1242 while let Some(nl) = buf.find('\n') {
1244 let line = buf[..nl].trim_end_matches('\r').to_owned();
1245 buf = buf[nl + 1..].to_owned();
1246
1247 if !line.starts_with("data: ") { continue; }
1248 let data = &line["data: ".len()..];
1249 if data == "[DONE]" { continue; }
1250
1251 let Ok(event) = serde_json::from_str::<serde_json::Value>(data) else { continue };
1252 let event_type = event["type"].as_str().unwrap_or("");
1253
1254 let maybe_chunk = match event_type {
1255 "content_block_delta" => {
1256 let text = event["delta"]["text"].as_str().unwrap_or("");
1257 if text.is_empty() { continue; }
1258 Some(json!({
1259 "id": id,
1260 "object": "chat.completion.chunk",
1261 "choices": [{"index": 0, "delta": {"content": text}, "finish_reason": null}]
1262 }))
1263 }
1264 "message_delta" => {
1265 let stop_reason = event["delta"]["stop_reason"].as_str().unwrap_or("stop");
1266 let finish = if stop_reason == "end_turn" { "stop" } else { stop_reason };
1267 Some(json!({
1268 "id": id,
1269 "object": "chat.completion.chunk",
1270 "choices": [{"index": 0, "delta": {}, "finish_reason": finish}]
1271 }))
1272 }
1273 _ => None,
1274 };
1275
1276 if let Some(c) = maybe_chunk {
1277 let out = format!("data: {}\n\n", serde_json::to_string(&c).unwrap());
1278 yield Ok(bytes::Bytes::from(out));
1279 }
1280 }
1281 }
1282
1283 yield Ok(bytes::Bytes::from("data: [DONE]\n\n"));
1284 }
1285}