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
120pub(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
151pub(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
180pub(crate) const OTHER_ACCOUNT_FILE: &str = "credential file belongs to another account";
182
183#[derive(Debug, Clone, Copy, PartialEq, Eq)]
185pub enum Readiness {
186 Ready,
188 RefreshSoon,
190 PrepareNow,
192}
193
194pub struct Executors {
195 pub claude: claude::ClaudeExecutor,
196 pub codex: codex::CodexExecutor,
197 pub devices: DeviceExecutors,
199 pub openai: OpenAIExecutors,
201 pub google: GoogleExecutors,
203}
204
205#[derive(Default)]
207pub struct GoogleExecutors {
208 pub gemini: gemini::GeminiExecutor,
210 pub vertex: vertex::VertexExecutor,
212 pub aistudio: aistudio::AiStudioExecutor,
214 pub antigravity: antigravity::AntigravityExecutor,
216}
217
218#[derive(Default)]
220pub struct OpenAIExecutors {
221 pub compat: openai_compat::OpenAICompatExecutor,
222 pub xai: xai::XaiExecutor,
223}
224
225#[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 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 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 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 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 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 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 pub fn close_session(&self, id: &str) {
349 self.codex.close_session(id);
350 self.openai.xai.close_session(id);
351 }
352
353 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 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 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 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 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 pub fn needs_prepare(&self, credential: &Credential, cfg: &Config) -> bool {
418 self.needs_prepare_at(credential, cfg, chrono::Utc::now())
419 }
420
421 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 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 pub fn models_registered(&self, credentials: &[std::sync::Arc<Credential>], cfg: &Config) {
470 self.google.antigravity.models_registered(credentials, cfg);
471 }
472
473 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 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 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 #[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 (
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 #[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 #[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 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}