1pub 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
112pub use kimi_http::{expiration, last_refresh, preferred_interval};
115pub use openai_compat_payload::ensure_responses_usage_details;
118pub use xai_ws::websockets_enabled;
119
120#[derive(Debug, Clone, Copy, PartialEq, Eq)]
122pub enum Readiness {
123 Ready,
125 RefreshSoon,
127 PrepareNow,
129}
130
131pub struct Executors {
132 pub claude: claude::ClaudeExecutor,
133 pub codex: codex::CodexExecutor,
134 pub devices: DeviceExecutors,
136 pub openai: OpenAIExecutors,
138 pub google: GoogleExecutors,
140}
141
142#[derive(Default)]
144pub struct GoogleExecutors {
145 pub gemini: gemini::GeminiExecutor,
147 pub vertex: vertex::VertexExecutor,
149 pub aistudio: aistudio::AiStudioExecutor,
151 pub antigravity: antigravity::AntigravityExecutor,
153}
154
155#[derive(Default)]
157pub struct OpenAIExecutors {
158 pub compat: openai_compat::OpenAICompatExecutor,
159 pub xai: xai::XaiExecutor,
160}
161
162#[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 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 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 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 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 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 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 pub fn close_session(&self, id: &str) {
286 self.codex.close_session(id);
287 self.openai.xai.close_session(id);
288 }
289
290 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 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 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 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 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 pub fn needs_prepare(&self, credential: &Credential, cfg: &Config) -> bool {
355 self.needs_prepare_at(credential, cfg, chrono::Utc::now())
356 }
357
358 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 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 pub fn models_registered(&self, credentials: &[std::sync::Arc<Credential>], cfg: &Config) {
407 self.google.antigravity.models_registered(credentials, cfg);
408 }
409
410 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 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 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 #[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 (
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 #[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 #[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 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}