Skip to main content

cpa_exec/
lib.rs

1//! Upstream executors. One module per provider; each owns its wire format, auth headers
2//! and HTTP client profile. [`Executors`] dispatches on `Credential::provider`.
3//!
4//! Each call gets the config snapshot current when the request started, so a hot reload
5//! never changes behaviour halfway through one execution.
6//!
7//! Credential preparation (token refresh, device identity creation) is a two-step
8//! contract so the runtime can single-flight it: [`Executors::readiness`] is a cheap
9//! check, and [`Executors::prepare`] does the work and returns a [`MetadataPatch`] that
10//! the runtime commits. Executors never write credential files themselves.
11//!
12//! [`Readiness`] separates the two reasons Go prepares a credential. Requests block only
13//! on [`Readiness::PrepareNow`] (Go `RequestAuthPreparer`: Claude identity, Meta API-key
14//! mint, Antigravity project ID; also an Antigravity token inside five minutes of
15//! expiry, which Go's executor refreshes inline). Token refresh is
16//! [`Readiness::RefreshSoon`]: the
17//! background loop refreshes inside the provider's refresh lead while requests keep
18//! using the current token, and an upstream 401 triggers one refresh-and-retry (Go
19//! `tryRefreshAfterUnauthorized`). An already expired token is still `RefreshSoon`:
20//! Go sends it and recovers on 401.
21
22pub mod aistudio;
23pub mod antigravity;
24pub mod antigravity_auth;
25mod antigravity_compaction;
26pub mod antigravity_credits;
27mod antigravity_models;
28mod antigravity_replay;
29mod antigravity_request;
30pub mod antigravity_version;
31pub mod claude;
32pub mod claude_login;
33pub mod codex;
34mod codex_capture;
35mod codex_client;
36mod codex_images;
37mod codex_json;
38pub mod codex_live;
39pub mod codex_oauth;
40pub mod codex_quota;
41pub mod codex_refresh;
42mod codex_replay;
43mod codex_request;
44mod codex_response;
45pub mod codex_siwc;
46pub mod codex_siwc_bind;
47mod codex_sse;
48#[cfg(test)]
49mod codex_testkit;
50mod codex_tls;
51mod codex_tokens;
52mod codex_ws;
53pub mod devin;
54pub mod devin_auth;
55pub mod devin_models;
56mod devin_payload;
57mod devin_request;
58mod devin_wire;
59pub mod gemini;
60mod gemini_payload;
61mod gemini_stream;
62mod home_replay;
63pub mod kimi;
64pub mod kimi_auth;
65#[cfg(test)]
66mod kimi_fixture;
67mod kimi_http;
68mod kimi_replay;
69pub mod meta;
70pub mod meta_auth;
71mod meta_codex;
72mod meta_wire;
73pub mod oauth;
74pub mod openai_compat;
75mod openai_compat_go;
76mod openai_compat_http;
77pub mod openai_compat_multipart;
78mod openai_compat_payload;
79#[cfg(test)]
80mod openai_compat_usage;
81mod payload_barrier;
82mod payload_media;
83pub mod proxy;
84mod quota;
85mod rawjson;
86mod replay;
87#[cfg(test)]
88mod test_tls;
89mod tls;
90mod tokenizer;
91mod tokens;
92mod translate;
93mod upstream;
94pub mod vertex;
95pub mod vertex_auth;
96mod vertex_openapi;
97mod wire;
98mod ws_observation;
99pub mod wsrelay;
100pub mod xai;
101pub mod xai_auth;
102mod xai_replay;
103mod xai_request;
104mod xai_response;
105pub mod xai_url;
106mod xai_ws;
107
108use cpa_core::config::Config;
109use cpa_core::credential::{Credential, MetadataPatch};
110use cpa_core::exec::{ExecError, ExecRequest, ExecResponse, ExecSession, FailureScope};
111
112/// Go `Auth.ExpirationTime`, `authLastRefreshTimestamp` and `authPreferredInterval`, for
113/// the server's plugin refresh schedule (Go `shouldRefresh` for providers without a lead).
114pub use kimi_http::{expiration, last_refresh, preferred_interval};
115/// Go `helps.EnsureResponsesUsageDetails`, for paths outside the executors (plugin
116/// executors' Responses payloads and stream chunks).
117pub use openai_compat_payload::ensure_responses_usage_details;
118pub use xai_ws::websockets_enabled;
119
120/// An account email as a credential file-name segment. Deliberate difference: Go puts
121/// the provider's email into the file name unchanged, so a `/`, `\\` or drive `:` in it
122/// would place the file outside auth-dir. Those and control characters become `_`, and
123/// a changed email gets a hash of the original, so it does not take the file of an
124/// account whose email is the sanitized text. An email that already ends in `-` and
125/// eight hex digits, in either case, gets the hash too, so it cannot match a changed
126/// email's name, also on case-insensitive file systems. [`other_account_file`] covers
127/// files written before this and hash collisions.
128/// Ordinary addresses are unchanged, so existing file names stay the same.
129pub(crate) fn file_name_email(email: &str) -> String {
130    let clean: String = email
131        .chars()
132        .map(|c| {
133            if matches!(c, '/' | '\\' | ':') || c.is_control() {
134                '_'
135            } else {
136                c
137            }
138        })
139        .collect();
140    let b = email.as_bytes();
141    let hash_like = b.len() >= 9 && b[b.len() - 9] == b'-' && b[b.len() - 8..].iter().all(u8::is_ascii_hexdigit);
142    if clean == email && !hash_like {
143        return clean;
144    }
145    use sha2::Digest;
146    let digest = sha2::Sha256::digest(email.as_bytes());
147    let hash: String = digest[..4].iter().map(|b| format!("{b:02x}")).collect();
148    format!("{clean}-{hash}")
149}
150
151/// Whether the credential file at `path` belongs to another account than the login
152/// about to replace it: its stored `email` or one of the `ids` (stored key, new value)
153/// differs, ignoring case as Go's legacy matching does, where both sides are set. Deliberate
154/// difference: Go replaces the file whoever it belonged to. With sanitized emails in
155/// file names, a file written earlier for another account can hold the same name, so
156/// the login is refused instead. A missing or unreadable file is not another account's.
157pub(crate) fn other_account_file(path: &std::path::Path, email: &str, ids: &[(&str, &str)]) -> bool {
158    use cpa_core::gostr::GoStr;
159    let Some(existing) = std::fs::read(path)
160        .ok()
161        .and_then(|raw| serde_json::from_slice::<serde_json::Map<String, serde_json::Value>>(&raw).ok())
162    else {
163        return false;
164    };
165    let stored = |key: &str| {
166        existing
167            .get(key)
168            .and_then(serde_json::Value::as_str)
169            .unwrap_or_default()
170            .trim()
171    };
172    let set = |a: &str, b: &str| !a.is_empty() && !b.trim().is_empty();
173    let email_differs = set(stored("email"), email) && !stored("email").go_eq_fold(email.trim());
174    email_differs
175        || ids
176            .iter()
177            .any(|&(key, new)| set(stored(key), new) && !stored(key).go_eq_fold(new.trim()))
178}
179
180/// The error text of a login refused by [`other_account_file`].
181pub(crate) const OTHER_ACCOUNT_FILE: &str = "credential file belongs to another account";
182
183/// What a credential needs before or around use. See the module docs.
184#[derive(Debug, Clone, Copy, PartialEq, Eq)]
185pub enum Readiness {
186    /// Usable as is; nothing to refresh.
187    Ready,
188    /// Usable now; the background refresh loop should prepare it.
189    RefreshSoon,
190    /// Unusable until prepared; requests wait on the single-flighted preparation.
191    PrepareNow,
192}
193
194pub struct Executors {
195    pub claude: claude::ClaudeExecutor,
196    pub codex: codex::CodexExecutor,
197    /// Device-login providers (Kimi, Meta, Devin). `Default` builds production clients.
198    pub devices: DeviceExecutors,
199    /// API-key upstreams speaking OpenAI wire formats (OpenAI-compatible providers, xAI).
200    pub openai: OpenAIExecutors,
201    /// Google-family providers (Gemini API keys, native Interactions keys).
202    pub google: GoogleExecutors,
203}
204
205/// Google-family executors, grouped like [`DeviceExecutors`].
206#[derive(Default)]
207pub struct GoogleExecutors {
208    /// `gemini` and `gemini-interactions` API keys.
209    pub gemini: gemini::GeminiExecutor,
210    /// `vertex` service accounts and API keys.
211    pub vertex: vertex::VertexExecutor,
212    /// `aistudio` sessions on the `/v1/ws` relay, which the server route shares.
213    pub aistudio: aistudio::AiStudioExecutor,
214    /// `antigravity` OAuth credentials.
215    pub antigravity: antigravity::AntigravityExecutor,
216}
217
218/// OpenAI-wire executors, grouped like [`DeviceExecutors`].
219#[derive(Default)]
220pub struct OpenAIExecutors {
221    pub compat: openai_compat::OpenAICompatExecutor,
222    pub xai: xai::XaiExecutor,
223}
224
225/// Executors for the device-login providers, grouped so adding one does not touch every
226/// [`Executors`] construction site.
227#[derive(Default)]
228pub struct DeviceExecutors {
229    pub kimi: kimi::KimiExecutor,
230    pub meta: meta::MetaExecutor,
231    pub devin: devin::DevinExecutor,
232}
233
234impl Executors {
235    pub async fn execute(
236        &self,
237        credential: &Credential,
238        req: ExecRequest,
239        cfg: &Config,
240    ) -> Result<ExecResponse, ExecError> {
241        match credential.provider.as_str() {
242            "claude" => self.claude.execute(credential, req, cfg).await,
243            "codex" => self.codex.execute(credential, req, cfg).await,
244            p if kimi::PROVIDERS.contains(&p) => self.devices.kimi.execute(&self.claude, credential, req, cfg).await,
245            meta::PROVIDER => self.devices.meta.execute(credential, req, cfg).await,
246            devin::PROVIDER => self.devices.devin.execute(credential, req, cfg).await,
247            p if openai_compat::handles(p) => self.openai.compat.execute(credential, req, cfg).await,
248            p if gemini::handles(p) => self.google.gemini.execute(credential, req, cfg).await,
249            p if vertex::handles(p) => self.google.vertex.execute(credential, req, cfg).await,
250            p if aistudio::handles(p) => self.google.aistudio.execute(credential, req, cfg).await,
251            antigravity::PROVIDER => self.google.antigravity.execute(credential, req, cfg).await,
252            xai::PROVIDER => self.openai.xai.execute(credential, req, cfg, false).await,
253            other => Err(no_executor(other)),
254        }
255    }
256
257    /// The Images API (`/v1/images/generations`, `/v1/images/edits`) for providers that
258    /// serve it directly. `request_path` is the inbound route; `req.stream` asks for the
259    /// upstream event stream passed through raw.
260    pub async fn images(
261        &self,
262        credential: &Credential,
263        req: ExecRequest,
264        request_path: &str,
265        cfg: &Config,
266    ) -> Result<ExecResponse, ExecError> {
267        match credential.provider.as_str() {
268            "codex" => self.codex.images(credential, req, request_path, cfg).await,
269            p if openai_compat::handles(p) => self.openai.compat.images(credential, req, request_path, cfg).await,
270            xai::PROVIDER => self.openai.xai.images(credential, req, request_path, cfg).await,
271            other => Err(no_executor(other)),
272        }
273    }
274
275    /// The Videos API (`/v1/videos*`, `/openai/v1/videos*`) for providers that serve it.
276    /// `request_path` is the inbound route; a route other than generations, edits or
277    /// extensions polls the job named by the body's `request_id`.
278    pub async fn videos(
279        &self,
280        credential: &Credential,
281        req: ExecRequest,
282        request_path: &str,
283        cfg: &Config,
284    ) -> Result<ExecResponse, ExecError> {
285        match credential.provider.as_str() {
286            xai::PROVIDER => self.openai.xai.videos(credential, req, request_path, cfg).await,
287            other => Err(no_executor(other)),
288        }
289    }
290
291    /// The OpenAI speech routes (`/v1/audio/speech`, `/v1/tts`): Go's `openai-speech`
292    /// source, which only the xAI executor serves.
293    pub async fn speech(
294        &self,
295        credential: &Credential,
296        req: ExecRequest,
297        cfg: &Config,
298    ) -> Result<ExecResponse, ExecError> {
299        match credential.provider.as_str() {
300            xai::PROVIDER => self.openai.xai.speech(credential, req, cfg).await,
301            other => Err(no_executor(other)),
302        }
303    }
304
305    /// One turn of a downstream Responses WebSocket session. Codex and xAI credentials
306    /// with `websockets` keep a pooled upstream socket per session; every other credential
307    /// runs an ordinary execution and cannot continue upstream state, so a continuation
308    /// turn fails with [`ExecError::replay_required`].
309    pub async fn execute_in_session(
310        &self,
311        credential: &Credential,
312        req: ExecRequest,
313        cfg: &Config,
314        session: &ExecSession,
315    ) -> Result<ExecResponse, ExecError> {
316        match credential.provider.as_str() {
317            "codex" => self.codex.execute_in_session(credential, req, cfg, session).await,
318            xai::PROVIDER => self.openai.xai.execute_in_session(credential, req, cfg, session).await,
319            _ if session.continuation => Err(ExecError::replay_required()),
320            _ => self.execute(credential, req, cfg).await,
321        }
322    }
323
324    /// Whether `credential` keeps upstream conversation state on a session socket, so
325    /// the next turn may be sent as an incremental continuation.
326    pub fn session_upstream(&self, credential: &Credential) -> bool {
327        match credential.provider.as_str() {
328            "codex" => codex::CodexExecutor::upstream_websocket(credential),
329            xai::PROVIDER => xai::XaiExecutor::session_upstream(credential),
330            _ => false,
331        }
332    }
333
334    /// Resolves when an upstream socket held for session `id` is lost; pending forever
335    /// when no executor holds one.
336    pub fn session_closed(&self, id: &str) -> impl std::future::Future<Output = ExecError> + Send + 'static {
337        let codex = self.codex.session_closed(id);
338        let xai = self.openai.xai.session_closed(id);
339        async move {
340            tokio::select! {
341                error = codex => error,
342                error = xai => error,
343            }
344        }
345    }
346
347    /// Releases everything executors hold for session `id`.
348    pub fn close_session(&self, id: &str) {
349        self.codex.close_session(id);
350        self.openai.xai.close_session(id);
351    }
352
353    /// Go `CloseCodexWebsocketSessionsForAuthID` and `CloseXAIWebsocketSessionsForAuthID`
354    /// for the credential store: given a removed credential's id, ends only the upstream
355    /// WebSocket sessions that credential serves.
356    pub fn credential_session_closer(&self) -> impl Fn(&str) + Send + Sync + 'static {
357        let codex = self.codex.ws.clone();
358        let xai = self.openai.xai.ws.clone();
359        move |id| {
360            codex.close_credential(id);
361            xai.close_credential(id);
362        }
363    }
364
365    /// Whether an executor serves this provider. Credentials of other providers never
366    /// enter selection (Go skips auths whose executor is not registered).
367    pub fn supports(&self, provider: &str) -> bool {
368        matches!(
369            provider,
370            "claude" | "codex" | meta::PROVIDER | xai::PROVIDER | devin::PROVIDER
371        ) || kimi::PROVIDERS.contains(&provider)
372            || openai_compat::handles(provider)
373            || gemini::handles(provider)
374            || vertex::handles(provider)
375            || aistudio::handles(provider)
376            || antigravity::handles(provider)
377    }
378
379    /// Go `authHasRefreshCredential`: whether an upstream 401 on `credential` should be
380    /// followed by one forced [`Self::prepare`] and a retry (Go
381    /// `tryRefreshAfterUnauthorized`). A refresh token qualifies for every provider;
382    /// Meta re-mints its API key from its device token. Providers that recover from a
383    /// 401 another way add an arm here.
384    pub fn has_refresh_credential(&self, credential: &Credential) -> bool {
385        let filled = |v: Option<&str>| v.is_some_and(|v| !v.trim().is_empty());
386        if filled(credential.str("refresh_token")) || filled(credential.str("refreshToken")) {
387            return true;
388        }
389        // Go `CodexSIWCNeedsRefresh`'s hasRefresh: a `siwc` refresh token and client ID.
390        // ponytail: Go asks it of every provider; Codex only until the Claude replay.
391        if credential.provider == "codex" && codex_siwc::refresh_due(credential, chrono::Utc::now()).is_some() {
392            return true;
393        }
394        credential.provider.trim().eq_ignore_ascii_case("meta")
395            && (filled(credential.str("dca_token"))
396                || filled(credential.attributes.get("dca_token").map(String::as_str)))
397    }
398
399    /// Whether `credential` needs preparation, and whether requests must wait for it.
400    /// Must be cheap and side-effect free. Providers without request-time preparation
401    /// report `RefreshSoon` whenever `needs_prepare` holds.
402    pub fn readiness(&self, credential: &Credential, cfg: &Config) -> Readiness {
403        if !self.needs_prepare(credential, cfg) {
404            return Readiness::Ready;
405        }
406        match credential.provider.as_str() {
407            "claude" if oauth::needs_identity(credential) => Readiness::PrepareNow,
408            meta::PROVIDER if self.devices.meta.must_mint(credential) => Readiness::PrepareNow,
409            antigravity::PROVIDER if self.google.antigravity.must_prepare(credential) => Readiness::PrepareNow,
410            _ => Readiness::RefreshSoon,
411        }
412    }
413
414    /// Whether `credential` needs any preparation (`readiness` is not `Ready`). Must be
415    /// cheap and side-effect free. Providers implement this; the runtime reads
416    /// [`Self::readiness`].
417    pub fn needs_prepare(&self, credential: &Credential, cfg: &Config) -> bool {
418        self.needs_prepare_at(credential, cfg, chrono::Utc::now())
419    }
420
421    /// [`Self::needs_prepare`] as of `now`. Once true it stays true as time passes until
422    /// the credential is prepared: every provider compares an expiry or a last refresh
423    /// with the clock.
424    pub fn needs_prepare_at(&self, credential: &Credential, cfg: &Config, now: chrono::DateTime<chrono::Utc>) -> bool {
425        match credential.provider.as_str() {
426            "claude" => self.claude.needs_prepare_at(credential, cfg, now),
427            "codex" => self.codex.needs_prepare_at(credential, cfg, now),
428            p if kimi::PROVIDERS.contains(&p) => self.devices.kimi.needs_prepare_at(credential, cfg, now),
429            meta::PROVIDER => self.devices.meta.needs_prepare_at(credential, cfg, now),
430            xai::PROVIDER => self.openai.xai.needs_prepare_at(credential, cfg, now),
431            devin::PROVIDER => self.devices.devin.needs_prepare_at(credential, cfg, now),
432            antigravity::PROVIDER => self.google.antigravity.needs_prepare_at(credential, cfg, now),
433            _ => false,
434        }
435    }
436
437    /// The earliest time within `horizon` of `now` at which `credential` needs
438    /// preparation (`now` if it already does), to one second. Bisects
439    /// [`Self::needs_prepare_at`], so every provider's own rule decides; about a dozen
440    /// cheap evaluations for a credential that comes due inside the horizon, one for
441    /// the rest.
442    pub fn prepare_due(
443        &self,
444        credential: &Credential,
445        cfg: &Config,
446        now: chrono::DateTime<chrono::Utc>,
447        horizon: chrono::Duration,
448    ) -> Option<chrono::DateTime<chrono::Utc>> {
449        if self.needs_prepare_at(credential, cfg, now) {
450            return Some(now);
451        }
452        let (mut lo, mut hi) = (now, now + horizon);
453        if !self.needs_prepare_at(credential, cfg, hi) {
454            return None;
455        }
456        while hi - lo > chrono::Duration::seconds(1) {
457            let mid = lo + (hi - lo) / 2;
458            if self.needs_prepare_at(credential, cfg, mid) {
459                hi = mid;
460            } else {
461                lo = mid;
462            }
463        }
464        Some(hi)
465    }
466
467    /// The runtime registered models for `credentials` (Go `registerModelsForAuth`):
468    /// providers that probe capabilities after registration start here. Must not block.
469    pub fn models_registered(&self, credentials: &[std::sync::Arc<Credential>], cfg: &Config) {
470        self.google.antigravity.models_registered(credentials, cfg);
471    }
472
473    /// [`Self::prepare`] for a credential whose access token an upstream rejected, or a
474    /// management refresh: Codex refreshes even when not due (Go marks the token rejected
475    /// or forces the refresh). Other providers prepare as usual; most of them (Claude
476    /// once its identity is known, Kimi, Meta, Devin) refresh whenever asked.
477    pub async fn prepare_forced(&self, credential: &Credential, cfg: &Config) -> Result<MetadataPatch, ExecError> {
478        match credential.provider.as_str() {
479            "codex" => self.codex.refresh_now(credential, cfg).await,
480            _ => self.prepare(credential, cfg).await,
481        }
482    }
483
484    /// [`Self::prepare_forced`] for a management refresh (Go `IsForceRefreshContext`):
485    /// Codex refreshes every token partition that can refresh.
486    pub async fn prepare_management(&self, credential: &Credential, cfg: &Config) -> Result<MetadataPatch, ExecError> {
487        match credential.provider.as_str() {
488            "codex" => self.codex.refresh_all(credential, cfg).await,
489            _ => self.prepare_forced(credential, cfg).await,
490        }
491    }
492
493    /// Prepares `credential` and returns the metadata change to commit.
494    pub async fn prepare(&self, credential: &Credential, cfg: &Config) -> Result<MetadataPatch, ExecError> {
495        match credential.provider.as_str() {
496            "claude" => self.claude.prepare(credential, cfg).await,
497            "codex" => self.codex.prepare(credential, cfg).await,
498            p if kimi::PROVIDERS.contains(&p) => self.devices.kimi.prepare(credential, cfg).await,
499            meta::PROVIDER => self.devices.meta.prepare(credential, cfg).await,
500            xai::PROVIDER => self.openai.xai.prepare(credential, cfg).await,
501            devin::PROVIDER => self.devices.devin.prepare(credential, cfg).await,
502            antigravity::PROVIDER => self.google.antigravity.prepare(credential, cfg).await,
503            other => Err(no_executor(other)),
504        }
505    }
506}
507
508fn no_executor(provider: &str) -> ExecError {
509    ExecError::local(
510        500,
511        FailureScope::Credential,
512        format!("no executor for provider {provider:?}"),
513    )
514}
515
516#[cfg(test)]
517mod readiness_tests {
518    use super::{Executors, Readiness, claude};
519    use cpa_core::config::Config;
520    use cpa_core::credential::Credential;
521    use std::path::Path;
522
523    fn credential(metadata: serde_json::Value) -> Credential {
524        Credential::from_file(
525            Path::new("/auth"),
526            Path::new("/auth/a.json"),
527            metadata.as_object().unwrap().clone(),
528        )
529        .unwrap()
530    }
531
532    fn rfc3339(offset: chrono::Duration) -> String {
533        (chrono::Utc::now() + offset).to_rfc3339()
534    }
535
536    /// Requests block only on Go `ShouldPrepareRequestAuth` (Claude: an OAuth token
537    /// without a canonical device pool or account UUID). Expiry, even past expiry, is a
538    /// background refresh.
539    #[test]
540    fn only_missing_identity_blocks_requests() {
541        let executors = Executors {
542            claude: claude::ClaudeExecutor::new("http://127.0.0.1:1").unwrap(),
543            codex: Default::default(),
544            devices: Default::default(),
545            openai: Default::default(),
546            google: Default::default(),
547        };
548        let cfg = Config::default();
549        let pool = serde_json::json!(["a".repeat(64)]);
550        let identified = |expired: String| {
551            credential(serde_json::json!({
552                "type": "claude",
553                "access_token": "sk-ant-oat01-fake",
554                "refresh_token": "fake-refresh",
555                "claude_device_ids": pool,
556                "account_uuid": "fake-account",
557                "expired": expired,
558            }))
559        };
560        let cases = [
561            (identified(rfc3339(chrono::Duration::days(2))), Readiness::Ready),
562            (identified(rfc3339(chrono::Duration::hours(1))), Readiness::RefreshSoon),
563            (identified(rfc3339(-chrono::Duration::hours(1))), Readiness::RefreshSoon),
564            (
565                credential(serde_json::json!({
566                    "type": "claude",
567                    "access_token": "sk-ant-oat01-fake",
568                    "refresh_token": "fake-refresh",
569                    "expired": rfc3339(-chrono::Duration::hours(1)),
570                })),
571                Readiness::PrepareNow,
572            ),
573            (
574                credential(serde_json::json!({"type": "claude", "access_token": "sk-ant-api03-fake"})),
575                Readiness::Ready,
576            ),
577            (
578                credential(serde_json::json!({
579                    "type": "kimi",
580                    "access_token": "fake-access",
581                    "refresh_token": "fake-refresh",
582                    "expired": rfc3339(-chrono::Duration::hours(1)),
583                })),
584                Readiness::RefreshSoon,
585            ),
586            // Antigravity: requests wait for the project ID and for a token valid five
587            // more minutes (Go's inline refresh); otherwise the token refreshes 30
588            // minutes ahead in the background.
589            (
590                credential(serde_json::json!({
591                    "type": "antigravity",
592                    "access_token": "fake-access",
593                    "refresh_token": "fake-refresh",
594                    "expired": rfc3339(chrono::Duration::hours(5)),
595                })),
596                Readiness::PrepareNow,
597            ),
598            (
599                credential(serde_json::json!({
600                    "type": "antigravity",
601                    "project_id": "proj-1",
602                    "access_token": "fake-access",
603                    "refresh_token": "fake-refresh",
604                    "expired": rfc3339(chrono::Duration::minutes(20)),
605                })),
606                Readiness::RefreshSoon,
607            ),
608            (
609                credential(serde_json::json!({
610                    "type": "antigravity",
611                    "project_id": "proj-1",
612                    "access_token": "fake-access",
613                    "refresh_token": "fake-refresh",
614                    "expired": rfc3339(chrono::Duration::minutes(6)),
615                })),
616                Readiness::RefreshSoon,
617            ),
618            (
619                credential(serde_json::json!({
620                    "type": "antigravity",
621                    "project_id": "proj-1",
622                    "access_token": "fake-access",
623                    "refresh_token": "fake-refresh",
624                    "expired": rfc3339(chrono::Duration::minutes(4)),
625                })),
626                Readiness::PrepareNow,
627            ),
628            (
629                credential(serde_json::json!({
630                    "type": "antigravity",
631                    "project_id": "proj-1",
632                    "refresh_token": "fake-refresh",
633                    "expired": rfc3339(chrono::Duration::minutes(40)),
634                })),
635                Readiness::PrepareNow,
636            ),
637            (
638                credential(serde_json::json!({
639                    "type": "antigravity",
640                    "project_id": "proj-1",
641                    "access_token": "fake-access",
642                })),
643                Readiness::PrepareNow,
644            ),
645            (
646                credential(serde_json::json!({
647                    "type": "antigravity",
648                    "project_id": "proj-1",
649                    "access_token": "fake-access",
650                    "refresh_token": "fake-refresh",
651                    "expired": rfc3339(chrono::Duration::minutes(40)),
652                })),
653                Readiness::Ready,
654            ),
655        ];
656        for (i, (c, expected)) in cases.iter().enumerate() {
657            assert_eq!(executors.readiness(c, &cfg), *expected, "case {i}");
658        }
659    }
660
661    /// The refresh loop sleeps until `prepare_due`: each provider's own lead before
662    /// expiry (Claude 4 h, Kimi 5 min), to the second, `now` once due, and nothing past
663    /// the horizon.
664    #[test]
665    fn prepare_due_finds_each_providers_deadline() {
666        let executors = Executors {
667            claude: claude::ClaudeExecutor::new("http://127.0.0.1:1").unwrap(),
668            codex: Default::default(),
669            devices: Default::default(),
670            openai: Default::default(),
671            google: Default::default(),
672        };
673        let cfg = Config::default();
674        let now = chrono::Utc::now();
675        let horizon = chrono::Duration::hours(1);
676        let with_expiry = |provider: &str, expiry: chrono::DateTime<chrono::Utc>| {
677            credential(serde_json::json!({
678                "type": provider,
679                "access_token": "fake-access",
680                "refresh_token": "fake-refresh",
681                "expired": expiry.to_rfc3339(),
682            }))
683        };
684        let near = |got: Option<chrono::DateTime<chrono::Utc>>, want: chrono::DateTime<chrono::Utc>| {
685            let got = got.expect("due inside the horizon");
686            assert!((got - want).num_milliseconds().abs() <= 1000, "{got} vs {want}");
687        };
688        let offset = chrono::Duration::seconds(1337);
689        let claude = with_expiry("claude", now + chrono::Duration::hours(4) + offset);
690        near(executors.prepare_due(&claude, &cfg, now, horizon), now + offset);
691        let kimi = with_expiry("kimi", now + chrono::Duration::minutes(5) + offset);
692        near(executors.prepare_due(&kimi, &cfg, now, horizon), now + offset);
693        let due = with_expiry("claude", now - chrono::Duration::hours(1));
694        assert_eq!(executors.prepare_due(&due, &cfg, now, horizon), Some(now));
695        let later = with_expiry("claude", now + chrono::Duration::hours(6));
696        assert_eq!(executors.prepare_due(&later, &cfg, now, horizon), None);
697        let api_key = credential(serde_json::json!({"type": "claude", "access_token": "sk-ant-api03-fake"}));
698        assert_eq!(executors.prepare_due(&api_key, &cfg, now, horizon), None);
699    }
700
701    /// Go `authHasRefreshCredential`.
702    #[test]
703    fn refresh_credentials_follow_go() {
704        let executors = Executors {
705            claude: claude::ClaudeExecutor::new("http://127.0.0.1:1").unwrap(),
706            codex: Default::default(),
707            openai: Default::default(),
708            google: Default::default(),
709            devices: Default::default(),
710        };
711        let has = |m: serde_json::Value| executors.has_refresh_credential(&credential(m));
712        assert!(has(serde_json::json!({"type": "claude", "refresh_token": "fake"})));
713        assert!(has(serde_json::json!({"type": "kimi", "refreshToken": "fake"})));
714        assert!(!has(serde_json::json!({"type": "claude", "refresh_token": "  "})));
715        // A Sign in with ChatGPT partition needs its refresh token and client ID.
716        assert!(has(
717            serde_json::json!({"type": "codex", "siwc": {"refresh_token": "fake", "client_id": "c"}})
718        ));
719        assert!(!has(
720            serde_json::json!({"type": "codex", "siwc": {"refresh_token": "fake"}})
721        ));
722        assert!(
723            !has(serde_json::json!({"type": "claude", "siwc": {"refresh_token": "fake", "client_id": "c"}})),
724            "SIWC is Codex's"
725        );
726        assert!(has(serde_json::json!({"type": "meta", "dca_token": "fake"})));
727        assert!(
728            !has(serde_json::json!({"type": "claude", "dca_token": "fake"})),
729            "dca_token is Meta's"
730        );
731        let mut meta = credential(serde_json::json!({"type": "meta"}));
732        assert!(!executors.has_refresh_credential(&meta));
733        meta.attributes.insert("dca_token".into(), "fake".into());
734        assert!(executors.has_refresh_credential(&meta));
735    }
736}