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/// What a credential needs before or around use. See the module docs.
121#[derive(Debug, Clone, Copy, PartialEq, Eq)]
122pub enum Readiness {
123    /// Usable as is; nothing to refresh.
124    Ready,
125    /// Usable now; the background refresh loop should prepare it.
126    RefreshSoon,
127    /// Unusable until prepared; requests wait on the single-flighted preparation.
128    PrepareNow,
129}
130
131pub struct Executors {
132    pub claude: claude::ClaudeExecutor,
133    pub codex: codex::CodexExecutor,
134    /// Device-login providers (Kimi, Meta, Devin). `Default` builds production clients.
135    pub devices: DeviceExecutors,
136    /// API-key upstreams speaking OpenAI wire formats (OpenAI-compatible providers, xAI).
137    pub openai: OpenAIExecutors,
138    /// Google-family providers (Gemini API keys, native Interactions keys).
139    pub google: GoogleExecutors,
140}
141
142/// Google-family executors, grouped like [`DeviceExecutors`].
143#[derive(Default)]
144pub struct GoogleExecutors {
145    /// `gemini` and `gemini-interactions` API keys.
146    pub gemini: gemini::GeminiExecutor,
147    /// `vertex` service accounts and API keys.
148    pub vertex: vertex::VertexExecutor,
149    /// `aistudio` sessions on the `/v1/ws` relay, which the server route shares.
150    pub aistudio: aistudio::AiStudioExecutor,
151    /// `antigravity` OAuth credentials.
152    pub antigravity: antigravity::AntigravityExecutor,
153}
154
155/// OpenAI-wire executors, grouped like [`DeviceExecutors`].
156#[derive(Default)]
157pub struct OpenAIExecutors {
158    pub compat: openai_compat::OpenAICompatExecutor,
159    pub xai: xai::XaiExecutor,
160}
161
162/// Executors for the device-login providers, grouped so adding one does not touch every
163/// [`Executors`] construction site.
164#[derive(Default)]
165pub struct DeviceExecutors {
166    pub kimi: kimi::KimiExecutor,
167    pub meta: meta::MetaExecutor,
168    pub devin: devin::DevinExecutor,
169}
170
171impl Executors {
172    pub async fn execute(
173        &self,
174        credential: &Credential,
175        req: ExecRequest,
176        cfg: &Config,
177    ) -> Result<ExecResponse, ExecError> {
178        match credential.provider.as_str() {
179            "claude" => self.claude.execute(credential, req, cfg).await,
180            "codex" => self.codex.execute(credential, req, cfg).await,
181            p if kimi::PROVIDERS.contains(&p) => self.devices.kimi.execute(&self.claude, credential, req, cfg).await,
182            meta::PROVIDER => self.devices.meta.execute(credential, req, cfg).await,
183            devin::PROVIDER => self.devices.devin.execute(credential, req, cfg).await,
184            p if openai_compat::handles(p) => self.openai.compat.execute(credential, req, cfg).await,
185            p if gemini::handles(p) => self.google.gemini.execute(credential, req, cfg).await,
186            p if vertex::handles(p) => self.google.vertex.execute(credential, req, cfg).await,
187            p if aistudio::handles(p) => self.google.aistudio.execute(credential, req, cfg).await,
188            antigravity::PROVIDER => self.google.antigravity.execute(credential, req, cfg).await,
189            xai::PROVIDER => self.openai.xai.execute(credential, req, cfg, false).await,
190            other => Err(no_executor(other)),
191        }
192    }
193
194    /// The Images API (`/v1/images/generations`, `/v1/images/edits`) for providers that
195    /// serve it directly. `request_path` is the inbound route; `req.stream` asks for the
196    /// upstream event stream passed through raw.
197    pub async fn images(
198        &self,
199        credential: &Credential,
200        req: ExecRequest,
201        request_path: &str,
202        cfg: &Config,
203    ) -> Result<ExecResponse, ExecError> {
204        match credential.provider.as_str() {
205            "codex" => self.codex.images(credential, req, request_path, cfg).await,
206            p if openai_compat::handles(p) => self.openai.compat.images(credential, req, request_path, cfg).await,
207            xai::PROVIDER => self.openai.xai.images(credential, req, request_path, cfg).await,
208            other => Err(no_executor(other)),
209        }
210    }
211
212    /// The Videos API (`/v1/videos*`, `/openai/v1/videos*`) for providers that serve it.
213    /// `request_path` is the inbound route; a route other than generations, edits or
214    /// extensions polls the job named by the body's `request_id`.
215    pub async fn videos(
216        &self,
217        credential: &Credential,
218        req: ExecRequest,
219        request_path: &str,
220        cfg: &Config,
221    ) -> Result<ExecResponse, ExecError> {
222        match credential.provider.as_str() {
223            xai::PROVIDER => self.openai.xai.videos(credential, req, request_path, cfg).await,
224            other => Err(no_executor(other)),
225        }
226    }
227
228    /// The OpenAI speech routes (`/v1/audio/speech`, `/v1/tts`): Go's `openai-speech`
229    /// source, which only the xAI executor serves.
230    pub async fn speech(
231        &self,
232        credential: &Credential,
233        req: ExecRequest,
234        cfg: &Config,
235    ) -> Result<ExecResponse, ExecError> {
236        match credential.provider.as_str() {
237            xai::PROVIDER => self.openai.xai.speech(credential, req, cfg).await,
238            other => Err(no_executor(other)),
239        }
240    }
241
242    /// One turn of a downstream Responses WebSocket session. Codex and xAI credentials
243    /// with `websockets` keep a pooled upstream socket per session; every other credential
244    /// runs an ordinary execution and cannot continue upstream state, so a continuation
245    /// turn fails with [`ExecError::replay_required`].
246    pub async fn execute_in_session(
247        &self,
248        credential: &Credential,
249        req: ExecRequest,
250        cfg: &Config,
251        session: &ExecSession,
252    ) -> Result<ExecResponse, ExecError> {
253        match credential.provider.as_str() {
254            "codex" => self.codex.execute_in_session(credential, req, cfg, session).await,
255            xai::PROVIDER => self.openai.xai.execute_in_session(credential, req, cfg, session).await,
256            _ if session.continuation => Err(ExecError::replay_required()),
257            _ => self.execute(credential, req, cfg).await,
258        }
259    }
260
261    /// Whether `credential` keeps upstream conversation state on a session socket, so
262    /// the next turn may be sent as an incremental continuation.
263    pub fn session_upstream(&self, credential: &Credential) -> bool {
264        match credential.provider.as_str() {
265            "codex" => codex::CodexExecutor::upstream_websocket(credential),
266            xai::PROVIDER => xai::XaiExecutor::session_upstream(credential),
267            _ => false,
268        }
269    }
270
271    /// Resolves when an upstream socket held for session `id` is lost; pending forever
272    /// when no executor holds one.
273    pub fn session_closed(&self, id: &str) -> impl std::future::Future<Output = ExecError> + Send + 'static {
274        let codex = self.codex.session_closed(id);
275        let xai = self.openai.xai.session_closed(id);
276        async move {
277            tokio::select! {
278                error = codex => error,
279                error = xai => error,
280            }
281        }
282    }
283
284    /// Releases everything executors hold for session `id`.
285    pub fn close_session(&self, id: &str) {
286        self.codex.close_session(id);
287        self.openai.xai.close_session(id);
288    }
289
290    /// Go `CloseCodexWebsocketSessionsForAuthID` and `CloseXAIWebsocketSessionsForAuthID`
291    /// for the credential store: given a removed credential's id, ends only the upstream
292    /// WebSocket sessions that credential serves.
293    pub fn credential_session_closer(&self) -> impl Fn(&str) + Send + Sync + 'static {
294        let codex = self.codex.ws.clone();
295        let xai = self.openai.xai.ws.clone();
296        move |id| {
297            codex.close_credential(id);
298            xai.close_credential(id);
299        }
300    }
301
302    /// Whether an executor serves this provider. Credentials of other providers never
303    /// enter selection (Go skips auths whose executor is not registered).
304    pub fn supports(&self, provider: &str) -> bool {
305        matches!(
306            provider,
307            "claude" | "codex" | meta::PROVIDER | xai::PROVIDER | devin::PROVIDER
308        ) || kimi::PROVIDERS.contains(&provider)
309            || openai_compat::handles(provider)
310            || gemini::handles(provider)
311            || vertex::handles(provider)
312            || aistudio::handles(provider)
313            || antigravity::handles(provider)
314    }
315
316    /// Go `authHasRefreshCredential`: whether an upstream 401 on `credential` should be
317    /// followed by one forced [`Self::prepare`] and a retry (Go
318    /// `tryRefreshAfterUnauthorized`). A refresh token qualifies for every provider;
319    /// Meta re-mints its API key from its device token. Providers that recover from a
320    /// 401 another way add an arm here.
321    pub fn has_refresh_credential(&self, credential: &Credential) -> bool {
322        let filled = |v: Option<&str>| v.is_some_and(|v| !v.trim().is_empty());
323        if filled(credential.str("refresh_token")) || filled(credential.str("refreshToken")) {
324            return true;
325        }
326        // Go `CodexSIWCNeedsRefresh`'s hasRefresh: a `siwc` refresh token and client ID.
327        // ponytail: Go asks it of every provider; Codex only until the Claude replay.
328        if credential.provider == "codex" && codex_siwc::refresh_due(credential, chrono::Utc::now()).is_some() {
329            return true;
330        }
331        credential.provider.trim().eq_ignore_ascii_case("meta")
332            && (filled(credential.str("dca_token"))
333                || filled(credential.attributes.get("dca_token").map(String::as_str)))
334    }
335
336    /// Whether `credential` needs preparation, and whether requests must wait for it.
337    /// Must be cheap and side-effect free. Providers without request-time preparation
338    /// report `RefreshSoon` whenever `needs_prepare` holds.
339    pub fn readiness(&self, credential: &Credential, cfg: &Config) -> Readiness {
340        if !self.needs_prepare(credential, cfg) {
341            return Readiness::Ready;
342        }
343        match credential.provider.as_str() {
344            "claude" if oauth::needs_identity(credential) => Readiness::PrepareNow,
345            meta::PROVIDER if self.devices.meta.must_mint(credential) => Readiness::PrepareNow,
346            antigravity::PROVIDER if self.google.antigravity.must_prepare(credential) => Readiness::PrepareNow,
347            _ => Readiness::RefreshSoon,
348        }
349    }
350
351    /// Whether `credential` needs any preparation (`readiness` is not `Ready`). Must be
352    /// cheap and side-effect free. Providers implement this; the runtime reads
353    /// [`Self::readiness`].
354    pub fn needs_prepare(&self, credential: &Credential, cfg: &Config) -> bool {
355        self.needs_prepare_at(credential, cfg, chrono::Utc::now())
356    }
357
358    /// [`Self::needs_prepare`] as of `now`. Once true it stays true as time passes until
359    /// the credential is prepared: every provider compares an expiry or a last refresh
360    /// with the clock.
361    pub fn needs_prepare_at(&self, credential: &Credential, cfg: &Config, now: chrono::DateTime<chrono::Utc>) -> bool {
362        match credential.provider.as_str() {
363            "claude" => self.claude.needs_prepare_at(credential, cfg, now),
364            "codex" => self.codex.needs_prepare_at(credential, cfg, now),
365            p if kimi::PROVIDERS.contains(&p) => self.devices.kimi.needs_prepare_at(credential, cfg, now),
366            meta::PROVIDER => self.devices.meta.needs_prepare_at(credential, cfg, now),
367            xai::PROVIDER => self.openai.xai.needs_prepare_at(credential, cfg, now),
368            devin::PROVIDER => self.devices.devin.needs_prepare_at(credential, cfg, now),
369            antigravity::PROVIDER => self.google.antigravity.needs_prepare_at(credential, cfg, now),
370            _ => false,
371        }
372    }
373
374    /// The earliest time within `horizon` of `now` at which `credential` needs
375    /// preparation (`now` if it already does), to one second. Bisects
376    /// [`Self::needs_prepare_at`], so every provider's own rule decides; about a dozen
377    /// cheap evaluations for a credential that comes due inside the horizon, one for
378    /// the rest.
379    pub fn prepare_due(
380        &self,
381        credential: &Credential,
382        cfg: &Config,
383        now: chrono::DateTime<chrono::Utc>,
384        horizon: chrono::Duration,
385    ) -> Option<chrono::DateTime<chrono::Utc>> {
386        if self.needs_prepare_at(credential, cfg, now) {
387            return Some(now);
388        }
389        let (mut lo, mut hi) = (now, now + horizon);
390        if !self.needs_prepare_at(credential, cfg, hi) {
391            return None;
392        }
393        while hi - lo > chrono::Duration::seconds(1) {
394            let mid = lo + (hi - lo) / 2;
395            if self.needs_prepare_at(credential, cfg, mid) {
396                hi = mid;
397            } else {
398                lo = mid;
399            }
400        }
401        Some(hi)
402    }
403
404    /// The runtime registered models for `credentials` (Go `registerModelsForAuth`):
405    /// providers that probe capabilities after registration start here. Must not block.
406    pub fn models_registered(&self, credentials: &[std::sync::Arc<Credential>], cfg: &Config) {
407        self.google.antigravity.models_registered(credentials, cfg);
408    }
409
410    /// [`Self::prepare`] for a credential whose access token an upstream rejected, or a
411    /// management refresh: Codex refreshes even when not due (Go marks the token rejected
412    /// or forces the refresh). Other providers prepare as usual; most of them (Claude
413    /// once its identity is known, Kimi, Meta, Devin) refresh whenever asked.
414    pub async fn prepare_forced(&self, credential: &Credential, cfg: &Config) -> Result<MetadataPatch, ExecError> {
415        match credential.provider.as_str() {
416            "codex" => self.codex.refresh_now(credential, cfg).await,
417            _ => self.prepare(credential, cfg).await,
418        }
419    }
420
421    /// [`Self::prepare_forced`] for a management refresh (Go `IsForceRefreshContext`):
422    /// Codex refreshes every token partition that can refresh.
423    pub async fn prepare_management(&self, credential: &Credential, cfg: &Config) -> Result<MetadataPatch, ExecError> {
424        match credential.provider.as_str() {
425            "codex" => self.codex.refresh_all(credential, cfg).await,
426            _ => self.prepare_forced(credential, cfg).await,
427        }
428    }
429
430    /// Prepares `credential` and returns the metadata change to commit.
431    pub async fn prepare(&self, credential: &Credential, cfg: &Config) -> Result<MetadataPatch, ExecError> {
432        match credential.provider.as_str() {
433            "claude" => self.claude.prepare(credential, cfg).await,
434            "codex" => self.codex.prepare(credential, cfg).await,
435            p if kimi::PROVIDERS.contains(&p) => self.devices.kimi.prepare(credential, cfg).await,
436            meta::PROVIDER => self.devices.meta.prepare(credential, cfg).await,
437            xai::PROVIDER => self.openai.xai.prepare(credential, cfg).await,
438            devin::PROVIDER => self.devices.devin.prepare(credential, cfg).await,
439            antigravity::PROVIDER => self.google.antigravity.prepare(credential, cfg).await,
440            other => Err(no_executor(other)),
441        }
442    }
443}
444
445fn no_executor(provider: &str) -> ExecError {
446    ExecError::local(
447        500,
448        FailureScope::Credential,
449        format!("no executor for provider {provider:?}"),
450    )
451}
452
453#[cfg(test)]
454mod readiness_tests {
455    use super::{Executors, Readiness, claude};
456    use cpa_core::config::Config;
457    use cpa_core::credential::Credential;
458    use std::path::Path;
459
460    fn credential(metadata: serde_json::Value) -> Credential {
461        Credential::from_file(
462            Path::new("/auth"),
463            Path::new("/auth/a.json"),
464            metadata.as_object().unwrap().clone(),
465        )
466        .unwrap()
467    }
468
469    fn rfc3339(offset: chrono::Duration) -> String {
470        (chrono::Utc::now() + offset).to_rfc3339()
471    }
472
473    /// Requests block only on Go `ShouldPrepareRequestAuth` (Claude: an OAuth token
474    /// without a canonical device pool or account UUID). Expiry, even past expiry, is a
475    /// background refresh.
476    #[test]
477    fn only_missing_identity_blocks_requests() {
478        let executors = Executors {
479            claude: claude::ClaudeExecutor::new("http://127.0.0.1:1").unwrap(),
480            codex: Default::default(),
481            devices: Default::default(),
482            openai: Default::default(),
483            google: Default::default(),
484        };
485        let cfg = Config::default();
486        let pool = serde_json::json!(["a".repeat(64)]);
487        let identified = |expired: String| {
488            credential(serde_json::json!({
489                "type": "claude",
490                "access_token": "sk-ant-oat01-fake",
491                "refresh_token": "fake-refresh",
492                "claude_device_ids": pool,
493                "account_uuid": "fake-account",
494                "expired": expired,
495            }))
496        };
497        let cases = [
498            (identified(rfc3339(chrono::Duration::days(2))), Readiness::Ready),
499            (identified(rfc3339(chrono::Duration::hours(1))), Readiness::RefreshSoon),
500            (identified(rfc3339(-chrono::Duration::hours(1))), Readiness::RefreshSoon),
501            (
502                credential(serde_json::json!({
503                    "type": "claude",
504                    "access_token": "sk-ant-oat01-fake",
505                    "refresh_token": "fake-refresh",
506                    "expired": rfc3339(-chrono::Duration::hours(1)),
507                })),
508                Readiness::PrepareNow,
509            ),
510            (
511                credential(serde_json::json!({"type": "claude", "access_token": "sk-ant-api03-fake"})),
512                Readiness::Ready,
513            ),
514            (
515                credential(serde_json::json!({
516                    "type": "kimi",
517                    "access_token": "fake-access",
518                    "refresh_token": "fake-refresh",
519                    "expired": rfc3339(-chrono::Duration::hours(1)),
520                })),
521                Readiness::RefreshSoon,
522            ),
523            // Antigravity: requests wait for the project ID and for a token valid five
524            // more minutes (Go's inline refresh); otherwise the token refreshes 30
525            // minutes ahead in the background.
526            (
527                credential(serde_json::json!({
528                    "type": "antigravity",
529                    "access_token": "fake-access",
530                    "refresh_token": "fake-refresh",
531                    "expired": rfc3339(chrono::Duration::hours(5)),
532                })),
533                Readiness::PrepareNow,
534            ),
535            (
536                credential(serde_json::json!({
537                    "type": "antigravity",
538                    "project_id": "proj-1",
539                    "access_token": "fake-access",
540                    "refresh_token": "fake-refresh",
541                    "expired": rfc3339(chrono::Duration::minutes(20)),
542                })),
543                Readiness::RefreshSoon,
544            ),
545            (
546                credential(serde_json::json!({
547                    "type": "antigravity",
548                    "project_id": "proj-1",
549                    "access_token": "fake-access",
550                    "refresh_token": "fake-refresh",
551                    "expired": rfc3339(chrono::Duration::minutes(6)),
552                })),
553                Readiness::RefreshSoon,
554            ),
555            (
556                credential(serde_json::json!({
557                    "type": "antigravity",
558                    "project_id": "proj-1",
559                    "access_token": "fake-access",
560                    "refresh_token": "fake-refresh",
561                    "expired": rfc3339(chrono::Duration::minutes(4)),
562                })),
563                Readiness::PrepareNow,
564            ),
565            (
566                credential(serde_json::json!({
567                    "type": "antigravity",
568                    "project_id": "proj-1",
569                    "refresh_token": "fake-refresh",
570                    "expired": rfc3339(chrono::Duration::minutes(40)),
571                })),
572                Readiness::PrepareNow,
573            ),
574            (
575                credential(serde_json::json!({
576                    "type": "antigravity",
577                    "project_id": "proj-1",
578                    "access_token": "fake-access",
579                })),
580                Readiness::PrepareNow,
581            ),
582            (
583                credential(serde_json::json!({
584                    "type": "antigravity",
585                    "project_id": "proj-1",
586                    "access_token": "fake-access",
587                    "refresh_token": "fake-refresh",
588                    "expired": rfc3339(chrono::Duration::minutes(40)),
589                })),
590                Readiness::Ready,
591            ),
592        ];
593        for (i, (c, expected)) in cases.iter().enumerate() {
594            assert_eq!(executors.readiness(c, &cfg), *expected, "case {i}");
595        }
596    }
597
598    /// The refresh loop sleeps until `prepare_due`: each provider's own lead before
599    /// expiry (Claude 4 h, Kimi 5 min), to the second, `now` once due, and nothing past
600    /// the horizon.
601    #[test]
602    fn prepare_due_finds_each_providers_deadline() {
603        let executors = Executors {
604            claude: claude::ClaudeExecutor::new("http://127.0.0.1:1").unwrap(),
605            codex: Default::default(),
606            devices: Default::default(),
607            openai: Default::default(),
608            google: Default::default(),
609        };
610        let cfg = Config::default();
611        let now = chrono::Utc::now();
612        let horizon = chrono::Duration::hours(1);
613        let with_expiry = |provider: &str, expiry: chrono::DateTime<chrono::Utc>| {
614            credential(serde_json::json!({
615                "type": provider,
616                "access_token": "fake-access",
617                "refresh_token": "fake-refresh",
618                "expired": expiry.to_rfc3339(),
619            }))
620        };
621        let near = |got: Option<chrono::DateTime<chrono::Utc>>, want: chrono::DateTime<chrono::Utc>| {
622            let got = got.expect("due inside the horizon");
623            assert!((got - want).num_milliseconds().abs() <= 1000, "{got} vs {want}");
624        };
625        let offset = chrono::Duration::seconds(1337);
626        let claude = with_expiry("claude", now + chrono::Duration::hours(4) + offset);
627        near(executors.prepare_due(&claude, &cfg, now, horizon), now + offset);
628        let kimi = with_expiry("kimi", now + chrono::Duration::minutes(5) + offset);
629        near(executors.prepare_due(&kimi, &cfg, now, horizon), now + offset);
630        let due = with_expiry("claude", now - chrono::Duration::hours(1));
631        assert_eq!(executors.prepare_due(&due, &cfg, now, horizon), Some(now));
632        let later = with_expiry("claude", now + chrono::Duration::hours(6));
633        assert_eq!(executors.prepare_due(&later, &cfg, now, horizon), None);
634        let api_key = credential(serde_json::json!({"type": "claude", "access_token": "sk-ant-api03-fake"}));
635        assert_eq!(executors.prepare_due(&api_key, &cfg, now, horizon), None);
636    }
637
638    /// Go `authHasRefreshCredential`.
639    #[test]
640    fn refresh_credentials_follow_go() {
641        let executors = Executors {
642            claude: claude::ClaudeExecutor::new("http://127.0.0.1:1").unwrap(),
643            codex: Default::default(),
644            openai: Default::default(),
645            google: Default::default(),
646            devices: Default::default(),
647        };
648        let has = |m: serde_json::Value| executors.has_refresh_credential(&credential(m));
649        assert!(has(serde_json::json!({"type": "claude", "refresh_token": "fake"})));
650        assert!(has(serde_json::json!({"type": "kimi", "refreshToken": "fake"})));
651        assert!(!has(serde_json::json!({"type": "claude", "refresh_token": "  "})));
652        // A Sign in with ChatGPT partition needs its refresh token and client ID.
653        assert!(has(
654            serde_json::json!({"type": "codex", "siwc": {"refresh_token": "fake", "client_id": "c"}})
655        ));
656        assert!(!has(
657            serde_json::json!({"type": "codex", "siwc": {"refresh_token": "fake"}})
658        ));
659        assert!(
660            !has(serde_json::json!({"type": "claude", "siwc": {"refresh_token": "fake", "client_id": "c"}})),
661            "SIWC is Codex's"
662        );
663        assert!(has(serde_json::json!({"type": "meta", "dca_token": "fake"})));
664        assert!(
665            !has(serde_json::json!({"type": "claude", "dca_token": "fake"})),
666            "dca_token is Meta's"
667        );
668        let mut meta = credential(serde_json::json!({"type": "meta"}));
669        assert!(!executors.has_refresh_credential(&meta));
670        meta.attributes.insert("dca_token".into(), "fake".into());
671        assert!(executors.has_refresh_credential(&meta));
672    }
673}