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    // Total wait budget: up to 5 hours (Claude's rate-limit reset window).
247    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                // Check whether any accounts are just temporarily cooling down
257                // (429/529 backoff) rather than permanently disabled / auth_failed.
258                // If so, wait for the soonest one to recover and retry.
259                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; } // auth_failed or permanently off
265                        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; // +50 ms buffer
272                        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(); // accounts may have recovered; try them again
275                    }
276                    _ => return Err(ProxyError::AllAccountsUnavailable),
277                }
278                continue;
279            }
280        };
281
282        let account_name = account.name.clone();
283
284        // Use the live (possibly refreshed) token rather than the one baked into config.
285        // For OpenAI/chatgpt.com accounts, use the id_token (short-lived OIDC JWT) as
286        // the bearer — chatgpt.com's API authenticates via id_token, not access_token.
287        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                // Sleep until the actual reset time if the headers tell us when that is;
317                // otherwise fall back to 60s so we don't hammer the API.
318                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) // +500ms buffer
323                    })
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                    // Access token invalidated (e.g. user logged out) — try refresh.
351                    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                            // Persist to disk so the refreshed token survives a restart.
371                            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                            // Mark as refreshed but don't add to tried — retry this account.
382                            refreshed.insert(account_name);
383                        }
384                        _ => {
385                            // Refresh failed/timed out — cool down, don't permanently disable.
386                            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                    // Already refreshed once and still 401 — cool down this account.
393                    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                // Forbidden — subscription lapsed or org restriction; refreshing won't help.
400                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                // 400, 404, 500, etc. — return as-is, no retry
411                return Ok(response);
412            }
413        }
414    }
415}
416
417// ---------------------------------------------------------------------------
418// Usage extraction
419// ---------------------------------------------------------------------------
420
421/// Intercept a successful response to record token usage, then pass it through.
422///
423/// - Streaming: wraps the body stream with an SSE scanner (zero latency).
424/// - Non-streaming: buffers the body, parses usage, rebuilds the response.
425async 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    // Non-streaming: buffer, extract, rebuild
458    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
479// ---------------------------------------------------------------------------
480// Rate limit prefetch
481// ---------------------------------------------------------------------------
482
483/// For any account with no rate-limit data yet, make a cheap request directly
484/// to the upstream API so we populate metrics without waiting for a real user
485/// request. Runs as a background task after startup.
486pub 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        // Skip if we already have data for this account.
494        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        // Skip accounts with no credentials or no prefetch support.
502        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            // No POST prefetch for this provider — do a lightweight GET auth check instead.
509            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
561/// Build and send a prefetch request for the given provider + token.
562async 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
580/// GET a cheap endpoint to verify credentials are still valid for providers that
581/// don't expose rate-limit headers (e.g. OpenAI). On 401, attempts a token refresh;
582/// marks the account as `reauth_required` if the refresh also fails.
583async 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        // Access token is valid. Do NOT refresh here — rotating the refresh_token races
640        // with codex CLI, which also tries to refresh at startup using the same token.
641        // Proactive refreshing is handled solely by openai_token_refresh_loop.
642    }
643}
644
645// ---------------------------------------------------------------------------
646// Proactive OpenAI token refresh loop
647// ---------------------------------------------------------------------------
648
649/// Returns true if the access_token inside `cred` has fewer than `threshold_mins`
650/// minutes remaining. Falls back to the stored `expires_at` if the JWT cannot be decoded.
651fn 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
661/// Sync live_creds from auth.json if auth.json has a newer token.
662///
663/// Codex CLI refreshes its own token and writes auth.json. Before we refresh,
664/// we pull that in so we don't use a stale refresh_token that codex already rotated.
665async 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
680/// Perform a single proactive refresh for one account and persist the result.
681async 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
711/// Keeps shunt's live credentials in sync with Codex CLI's auth.json.
712///
713/// Strategy: never proactively rotate the refresh_token — that races with
714/// Codex CLI's own refresh logic and causes "invalid_grant" errors. Instead,
715/// just periodically sync from auth.json so shunt picks up whatever Codex wrote.
716/// On-demand refresh (401 handler) covers the case where Codex isn't running
717/// and the token has actually expired.
718pub async fn openai_token_refresh_loop(
719    config: Arc<Config>,
720    state: StateStore,
721    live_creds: LiveCredentials,
722) {
723    // Startup: sync from auth.json first (Codex may have refreshed since shunt last ran).
724    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                // access_token is nearly expired — refresh now so shunt can serve requests immediately.
739                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    // Periodic sync every 5 minutes — picks up any token Codex CLI has written.
747    // No proactive refresh: Codex owns the refresh lifecycle; shunt uses what Codex produces.
748    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
758// ---------------------------------------------------------------------------
759// Error type
760// ---------------------------------------------------------------------------
761
762enum 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
787// ---------------------------------------------------------------------------
788// Recovery watcher — periodically retries token refresh for auth_failed accounts
789// ---------------------------------------------------------------------------
790
791/// Runs as a background task. Every 2 minutes, tries to refresh tokens for any
792/// auth_failed account. If refresh succeeds the account is brought back online
793/// without a process restart. If all accounts remain unrecoverable, fires a
794/// macOS notification (at most once per hour).
795pub 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        // All accounts still auth_failed after refresh attempts — notify.
888        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
909/// Sends a single lightweight prefetch request for `account` immediately after its
910/// cooldown expires, so the router has fresh rate-limit headers before the next
911/// real request arrives.
912async 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
937/// Watches for account cooldowns expiring and triggers a post-cooldown prefetch
938/// so each account re-enters rotation with fresh rate-limit metrics.
939///
940/// Analogous to `recovery_watcher` (which handles `auth_failed` accounts), but
941/// for timed cooldowns (429 / 529 / 401 / 403 backoffs). Sleeps precisely until
942/// the next cooldown deadline rather than polling at a fixed interval.
943pub 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    // In-memory: the cooldown_until_ms value we already ran a post-resume for.
954    // Prevents re-triggering on every poll after expiry.
955    let mut last_resumed: HashMap<String, u64> = HashMap::new();
956    // Accounts whose cooldown was long enough (≥5 min) to deserve a "back online" notification.
957    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; } // auth_failed or permanently disabled
967            let cdl = st.cooldown_until_ms;
968            if cdl == 0 { continue; } // never entered cooldown
969
970            if cdl <= now {
971                // Cooldown expired — skip if we already handled this exact deadline
972                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                // Still cooling — schedule wake at expiry; flag for notification if long
996                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        // Sleep exactly until the next cooldown expires; fall back to 30s poll
1005        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
1012/// Fire a macOS system notification. No-op on other platforms.
1013/// `sound` is a macOS alert sound name ("Basso", "Ping", "Glass", etc.)
1014fn notify(title: &str, body: &str, sound: &str) {
1015    #[cfg(target_os = "macos")]
1016    {
1017        let script = format!(
1018            "display notification {body:?} with title {title:?} sound name {sound:?}"
1019        );
1020        let _ = std::process::Command::new("osascript")
1021            .args(["-e", &script])
1022            .status();
1023    }
1024    #[cfg(not(target_os = "macos"))]
1025    let _ = (title, body, sound);
1026}
1027
1028// ---------------------------------------------------------------------------
1029// OpenAI-compatible API (translates to Anthropic Claude)
1030// ---------------------------------------------------------------------------
1031//
1032// When the OpenAI proxy receives a request at /v1/chat/completions, if an
1033// anthropic_base_url is configured, it translates the request to Anthropic
1034// Messages format and forwards it to the Anthropic proxy (which handles
1035// account selection, token management, and rate limiting).
1036// The response is translated back to OpenAI Chat Completions format.
1037
1038/// Map OpenAI model names → Claude model names.
1039fn map_model(openai_model: &str) -> &'static str {
1040    match openai_model {
1041        m if m.starts_with("claude-") => {
1042            // Already a Claude model name — but we need a &'static str, so match known ones
1043            // or fall through to default
1044            if m.contains("opus")   { "claude-opus-4-6" }
1045            else if m.contains("haiku") { "claude-haiku-4-5-20251001" }
1046            else                    { "claude-sonnet-4-6" }
1047        }
1048        "gpt-4o" | "gpt-4.5" | "o1" | "o1-pro" | "o3" | "o3-pro" | "gpt-5" | "gpt-5.5" => {
1049            "claude-opus-4-6"
1050        }
1051        "gpt-4o-mini" | "gpt-4o-mini-2024-07-18" | "o1-mini" | "o3-mini" => {
1052            "claude-haiku-4-5-20251001"
1053        }
1054        _ => "claude-sonnet-4-6",
1055    }
1056}
1057
1058/// Translate an OpenAI Chat Completions request body to an Anthropic Messages body.
1059fn translate_to_anthropic(body: serde_json::Value) -> serde_json::Value {
1060    let model = body["model"].as_str().unwrap_or("gpt-4o");
1061    let claude_model = map_model(model).to_owned();
1062
1063    // Extract system message from messages array.
1064    let mut system: Option<String> = None;
1065    let mut messages = Vec::new();
1066    if let Some(arr) = body["messages"].as_array() {
1067        for msg in arr {
1068            let role = msg["role"].as_str().unwrap_or("");
1069            let content = msg["content"].as_str().unwrap_or("").to_owned();
1070            if role == "system" {
1071                system = Some(content);
1072            } else {
1073                messages.push(json!({ "role": role, "content": content }));
1074            }
1075        }
1076    }
1077
1078    let max_tokens = body["max_tokens"].as_u64().unwrap_or(8096);
1079    let stream = body["stream"].as_bool().unwrap_or(false);
1080
1081    let mut req = json!({
1082        "model": claude_model,
1083        "messages": messages,
1084        "max_tokens": max_tokens,
1085        "stream": stream,
1086    });
1087
1088    if let Some(sys) = system {
1089        req["system"] = json!(sys);
1090    }
1091    if let Some(temp) = body.get("temperature") {
1092        req["temperature"] = temp.clone();
1093    }
1094    if let Some(sp) = body.get("stop") {
1095        req["stop_sequences"] = sp.clone();
1096    }
1097
1098    req
1099}
1100
1101/// Translate a complete (non-streaming) Anthropic Messages response to OpenAI format.
1102fn translate_from_anthropic(body: serde_json::Value) -> serde_json::Value {
1103    let id = format!("chatcmpl-{}", &uuid_v4()[..8]);
1104    let model = body["model"].as_str().unwrap_or("claude-sonnet-4-6").to_owned();
1105    let content = body["content"]
1106        .as_array()
1107        .and_then(|arr| arr.iter().find_map(|b| b["text"].as_str()))
1108        .unwrap_or("")
1109        .to_owned();
1110    let stop_reason = body["stop_reason"].as_str().unwrap_or("end_turn");
1111    let finish_reason = if stop_reason == "end_turn" { "stop" } else { stop_reason };
1112    let input_tokens = body["usage"]["input_tokens"].as_u64().unwrap_or(0);
1113    let output_tokens = body["usage"]["output_tokens"].as_u64().unwrap_or(0);
1114
1115    json!({
1116        "id": id,
1117        "object": "chat.completion",
1118        "model": model,
1119        "choices": [{
1120            "index": 0,
1121            "message": { "role": "assistant", "content": content },
1122            "finish_reason": finish_reason,
1123        }],
1124        "usage": {
1125            "prompt_tokens": input_tokens,
1126            "completion_tokens": output_tokens,
1127            "total_tokens": input_tokens + output_tokens,
1128        }
1129    })
1130}
1131
1132fn uuid_v4() -> String {
1133    use crate::oauth::rand_bytes;
1134    let b: [u8; 16] = rand_bytes();
1135    format!("{:08x}-{:04x}-{:04x}-{:04x}-{:012x}",
1136        u32::from_be_bytes(b[0..4].try_into().unwrap()),
1137        u16::from_be_bytes(b[4..6].try_into().unwrap()),
1138        u16::from_be_bytes(b[6..8].try_into().unwrap()),
1139        u16::from_be_bytes(b[8..10].try_into().unwrap()),
1140        {
1141            let mut v = 0u64;
1142            for &x in &b[10..16] { v = (v << 8) | x as u64; }
1143            v
1144        }
1145    )
1146}
1147
1148/// GET /v1/models — return Claude models in OpenAI format.
1149async fn openai_models_handler() -> impl IntoResponse {
1150    axum::Json(json!({
1151        "object": "list",
1152        "data": [
1153            { "id": "claude-opus-4-6",           "object": "model", "owned_by": "anthropic" },
1154            { "id": "claude-sonnet-4-6",          "object": "model", "owned_by": "anthropic" },
1155            { "id": "claude-haiku-4-5-20251001",  "object": "model", "owned_by": "anthropic" },
1156        ]
1157    }))
1158}
1159
1160/// POST /v1/chat/completions — translate OpenAI request to Anthropic, proxy through Claude pool.
1161async fn openai_compat_handler(
1162    State(s): State<AppState>,
1163    req: Request,
1164) -> Result<Response, ProxyError> {
1165    let Some(ref anthropic_url) = s.anthropic_base_url else {
1166        // No Anthropic proxy configured — fall back to normal forwarding
1167        return proxy_handler(State(s), req).await;
1168    };
1169
1170    let body_bytes = axum::body::to_bytes(req.into_body(), usize::MAX)
1171        .await
1172        .map_err(|_| ProxyError::BodyRead)?;
1173
1174    let openai_body: serde_json::Value = serde_json::from_slice(&body_bytes)
1175        .unwrap_or(json!({}));
1176
1177    let stream = openai_body["stream"].as_bool().unwrap_or(false);
1178    let anthropic_body = translate_to_anthropic(openai_body);
1179
1180    let client = reqwest::Client::builder()
1181        .timeout(std::time::Duration::from_secs(300))
1182        .build()
1183        .map_err(|_| ProxyError::Upstream)?;
1184
1185    let resp = client
1186        .post(format!("{anthropic_url}/v1/messages"))
1187        .header("content-type", "application/json")
1188        .header("anthropic-version", "2023-06-01")
1189        .header("anthropic-beta", "claude-code-20250219,oauth-2025-04-20")
1190        .header("x-shunt-compat", "openai")
1191        .json(&anthropic_body)
1192        .send()
1193        .await
1194        .map_err(|_| ProxyError::Upstream)?;
1195
1196    if !resp.status().is_success() {
1197        let status = resp.status();
1198        let body = resp.text().await.unwrap_or_default();
1199        let code = status.as_u16();
1200        return Ok(axum::response::Response::builder()
1201            .status(code)
1202            .header("content-type", "application/json")
1203            .body(axum::body::Body::from(body))
1204            .unwrap());
1205    }
1206
1207    if stream {
1208        // Translate Anthropic SSE stream → OpenAI SSE stream
1209        let chat_id = format!("chatcmpl-{}", &uuid_v4()[..8]);
1210        let stream = translate_anthropic_stream(resp, chat_id);
1211        Ok(axum::response::Response::builder()
1212            .status(200)
1213            .header("content-type", "text/event-stream")
1214            .header("cache-control", "no-cache")
1215            .body(axum::body::Body::from_stream(stream))
1216            .unwrap())
1217    } else {
1218        let anthropic_resp: serde_json::Value = resp.json().await.map_err(|_| ProxyError::Upstream)?;
1219        let openai_resp = translate_from_anthropic(anthropic_resp);
1220        Ok(axum::Json(openai_resp).into_response())
1221    }
1222}
1223
1224/// Translate Anthropic SSE events to OpenAI SSE format, yielding raw bytes.
1225fn translate_anthropic_stream(
1226    resp: reqwest::Response,
1227    chat_id: String,
1228) -> impl futures_util::Stream<Item = Result<bytes::Bytes, std::io::Error>> {
1229    use futures_util::StreamExt;
1230
1231    let id = chat_id;
1232    let byte_stream = resp.bytes_stream();
1233
1234    async_stream::stream! {
1235        let mut buf = String::new();
1236        futures_util::pin_mut!(byte_stream);
1237
1238        // Send initial role chunk
1239        let init = format!(
1240            "data: {}\n\n",
1241            serde_json::to_string(&json!({
1242                "id": id,
1243                "object": "chat.completion.chunk",
1244                "choices": [{"index": 0, "delta": {"role": "assistant", "content": ""}, "finish_reason": null}]
1245            })).unwrap()
1246        );
1247        yield Ok(bytes::Bytes::from(init));
1248
1249        while let Some(chunk) = byte_stream.next().await {
1250            let chunk = match chunk {
1251                Ok(c) => c,
1252                Err(_) => break,
1253            };
1254            buf.push_str(&String::from_utf8_lossy(&chunk));
1255
1256            // Process complete SSE lines
1257            while let Some(nl) = buf.find('\n') {
1258                let line = buf[..nl].trim_end_matches('\r').to_owned();
1259                buf = buf[nl + 1..].to_owned();
1260
1261                if !line.starts_with("data: ") { continue; }
1262                let data = &line["data: ".len()..];
1263                if data == "[DONE]" { continue; }
1264
1265                let Ok(event) = serde_json::from_str::<serde_json::Value>(data) else { continue };
1266                let event_type = event["type"].as_str().unwrap_or("");
1267
1268                let maybe_chunk = match event_type {
1269                    "content_block_delta" => {
1270                        let text = event["delta"]["text"].as_str().unwrap_or("");
1271                        if text.is_empty() { continue; }
1272                        Some(json!({
1273                            "id": id,
1274                            "object": "chat.completion.chunk",
1275                            "choices": [{"index": 0, "delta": {"content": text}, "finish_reason": null}]
1276                        }))
1277                    }
1278                    "message_delta" => {
1279                        let stop_reason = event["delta"]["stop_reason"].as_str().unwrap_or("stop");
1280                        let finish = if stop_reason == "end_turn" { "stop" } else { stop_reason };
1281                        Some(json!({
1282                            "id": id,
1283                            "object": "chat.completion.chunk",
1284                            "choices": [{"index": 0, "delta": {}, "finish_reason": finish}]
1285                        }))
1286                    }
1287                    _ => None,
1288                };
1289
1290                if let Some(c) = maybe_chunk {
1291                    let out = format!("data: {}\n\n", serde_json::to_string(&c).unwrap());
1292                    yield Ok(bytes::Bytes::from(out));
1293                }
1294            }
1295        }
1296
1297        yield Ok(bytes::Bytes::from("data: [DONE]\n\n"));
1298    }
1299}