From 646ceef400416654e4bf8b933ebc7fdaa89dc7ce Mon Sep 17 00:00:00 2001 From: RCD <90105158+Finesssee@users.noreply.github.com> Date: Wed, 8 Apr 2026 01:19:54 +0700 Subject: [PATCH] feat(rust): introduce provider abstraction and refactor state to be provider-agnostic - Add provider.rs with Provider trait, ProviderId, AuthResult, RefreshResult - Implement CodexProvider wrapping existing Codex device/refresh flows - Refactor state.rs: add provider-generic account methods that legacy codex-specific wrappers delegate to - Simplify remove_account fallback to first remaining account - All 49 tests pass on the new abstraction layer --- rust/proxypilot-rs/src/codex.rs | 70 ++++++++++++++++ rust/proxypilot-rs/src/lib.rs | 1 + rust/proxypilot-rs/src/provider.rs | 124 +++++++++++++++++++++++++++++ rust/proxypilot-rs/src/state.rs | 105 +++++++++++++++--------- 4 files changed, 262 insertions(+), 38 deletions(-) create mode 100644 rust/proxypilot-rs/src/provider.rs diff --git a/rust/proxypilot-rs/src/codex.rs b/rust/proxypilot-rs/src/codex.rs index f28513b3..63ce3b1c 100644 --- a/rust/proxypilot-rs/src/codex.rs +++ b/rust/proxypilot-rs/src/codex.rs @@ -8,6 +8,8 @@ use serde::{Deserialize, Serialize}; use serde_json::Value; use tokio::time::sleep; +use crate::provider::{Provider, ProviderId, RefreshResult}; + pub const CLIENT_ID: &str = "app_EMoamEEZ73f0CkXaXp7hrann"; pub const DEVICE_USER_CODE_URL: &str = "https://auth.openai.com/api/accounts/deviceauth/usercode"; pub const DEVICE_TOKEN_URL: &str = "https://auth.openai.com/api/accounts/deviceauth/token"; @@ -29,6 +31,74 @@ pub struct DeviceAuthResult { pub expires_at: Option, } +pub struct CodexProvider { + upstream_base_url: String, + refresh_token_url: String, + client: Client, +} + +impl CodexProvider { + pub fn new(upstream_base_url: String, refresh_token_url: String) -> Self { + Self { + upstream_base_url, + refresh_token_url, + client: Client::new(), + } + } + + pub fn from_config(config: &crate::config::AppConfig) -> Self { + Self::new( + config.codex.upstream_base_url.clone(), + config.codex.refresh_token_url.clone(), + ) + } +} + +impl Provider for CodexProvider { + fn id(&self) -> ProviderId { + ProviderId::CODEX + } + + fn display_name(&self) -> &'static str { + "Codex (OpenAI)" + } + + fn upstream_base_url(&self) -> &str { + &self.upstream_base_url + } + + fn default_upstream_base_url() -> &'static str { + "https://api.openai.com" + } + + async fn refresh_token( + &self, + refresh_token: &str, + ) -> Result { + let endpoints = if self.refresh_token_url.trim().is_empty() { + DeviceEndpoints::default() + } else { + DeviceEndpoints { + oauth_token_url: self.refresh_token_url.clone(), + ..DeviceEndpoints::default() + } + }; + let result = refresh_with_refresh_token_for_test( + self.client.clone(), + endpoints, + refresh_token, + ) + .await?; + + Ok(RefreshResult { + access_token: result.access_token, + refresh_token: Some(result.refresh_token), + id_token: Some(result.id_token), + expires_at: result.expires_at, + }) + } +} + #[derive(Debug, Clone)] pub struct DeviceEndpoints { pub user_code_url: String, diff --git a/rust/proxypilot-rs/src/lib.rs b/rust/proxypilot-rs/src/lib.rs index 111d101e..e8bd9b2b 100644 --- a/rust/proxypilot-rs/src/lib.rs +++ b/rust/proxypilot-rs/src/lib.rs @@ -4,5 +4,6 @@ pub mod cli; pub mod codex; pub mod config; pub mod proxy; +pub mod provider; pub mod state; pub mod tui; diff --git a/rust/proxypilot-rs/src/provider.rs b/rust/proxypilot-rs/src/provider.rs new file mode 100644 index 00000000..9bf36284 --- /dev/null +++ b/rust/proxypilot-rs/src/provider.rs @@ -0,0 +1,124 @@ +use anyhow::Result; +use serde::{Deserialize, Serialize}; + +use crate::state::AccountEntry; + +pub const CODEX_PROVIDER: &str = "codex"; +pub const CLAUDE_PROVIDER: &str = "claude"; +pub const GEMINI_PROVIDER: &str = "gemini"; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Hash)] +pub struct ProviderId(pub &'static str); + +impl ProviderId { + pub const CODEX: ProviderId = ProviderId(CODEX_PROVIDER); + pub const CLAUDE: ProviderId = ProviderId(CLAUDE_PROVIDER); + pub const GEMINI: ProviderId = ProviderId(GEMINI_PROVIDER); + + pub fn as_str(&self) -> &'static str { + self.0 + } +} + +impl std::fmt::Display for ProviderId { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(self.0) + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct AuthResult { + pub access_token: String, + pub refresh_token: Option, + pub id_token: Option, + pub email: Option, + pub account_id: Option, + pub plan_type: Option, + pub expires_at: Option, +} + +impl AuthResult { + pub fn into_account_entry( + self, + name: String, + source: String, + activate: bool, + ) -> AccountEntry { + AccountEntry { + name, + provider: self.access_token_provider_name().to_string(), + api_key: self.access_token, + refresh_token: self.refresh_token, + id_token: self.id_token, + email: self.email, + account_id: self.account_id, + plan_type: self.plan_type, + expires_at: self.expires_at, + source: Some(source), + } + } + + fn access_token_provider_name(&self) -> &str { + // Default to codex for existing results; providers override as needed. + CODEX_PROVIDER + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct RefreshResult { + pub access_token: String, + pub refresh_token: Option, + pub id_token: Option, + pub expires_at: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ModelInfo { + pub id: String, + pub owned_by: Option, +} + +#[allow(async_fn_in_trait)] +pub trait Provider: Send + Sync + 'static { + fn id(&self) -> ProviderId; + + fn display_name(&self) -> &'static str; + + fn provider_tag(&self) -> &'static str { + self.id().as_str() + } + + fn upstream_base_url(&self) -> &str; + + fn default_upstream_base_url() -> &'static str; + + async fn refresh_token( + &self, + refresh_token: &str, + ) -> Result; + + fn models_path(&self) -> &str { + "/v1/models" + } + + fn chat_completions_path(&self) -> &str { + "/v1/chat/completions" + } + + fn responses_path(&self) -> &str { + "/v1/responses" + } +} + +pub fn provider_from_tag(tag: &str) -> Option { + match tag { + CODEX_PROVIDER => Some(ProviderId::CODEX), + CLAUDE_PROVIDER => Some(ProviderId::CLAUDE), + GEMINI_PROVIDER => Some(ProviderId::GEMINI), + _ => None, + } +} + +pub fn is_known_provider(tag: &str) -> bool { + provider_from_tag(tag).is_some() +} diff --git a/rust/proxypilot-rs/src/state.rs b/rust/proxypilot-rs/src/state.rs index b49b2150..894b33e7 100644 --- a/rust/proxypilot-rs/src/state.rs +++ b/rust/proxypilot-rs/src/state.rs @@ -137,20 +137,18 @@ impl AccountState { if self.active_account.as_deref() == Some(trimmed) { self.active_account = self .accounts - .iter() - .find(|account| account.provider == "codex") - .map(|account| account.name.clone()) - .or_else(|| self.accounts.first().map(|account| account.name.clone())); + .first() + .map(|account| account.name.clone()); } Ok(()) } - pub fn active_codex_account(&self) -> Option { + pub fn active_account_for_provider(&self, provider: &str) -> Option { let active_name = self.active_account.as_deref()?; self.accounts .iter() - .find(|account| account.provider == "codex" && account.name == active_name) + .find(|account| account.provider == provider && account.name == active_name) .map(|account| ActiveCodexAccount { name: account.name.clone(), api_key: account.api_key.clone(), @@ -163,18 +161,11 @@ impl AccountState { }) } - pub fn runtime_usable_codex_account_count(&self) -> usize { - self.accounts - .iter() - .filter(|account| account.provider == "codex" && !account.api_key.trim().is_empty()) - .count() - } - - pub fn codex_account_by_name(&self, name: &str) -> Option { + pub fn account_by_name_and_provider(&self, name: &str, provider: &str) -> Option { let trimmed = name.trim(); self.accounts .iter() - .find(|account| account.provider == "codex" && account.name == trimmed) + .find(|account| account.provider == provider && account.name == trimmed) .map(|account| ActiveCodexAccount { name: account.name.clone(), api_key: account.api_key.clone(), @@ -187,6 +178,56 @@ impl AccountState { }) } + pub fn runtime_usable_account_count_for_provider(&self, provider: &str) -> usize { + self.accounts + .iter() + .filter(|account| account.provider == provider && !account.api_key.trim().is_empty()) + .count() + } + + pub fn update_account_tokens_for_provider( + &mut self, + account_name: &str, + provider: &str, + access_token: String, + refresh_token: Option, + id_token: Option, + email: Option, + account_id: Option, + plan_type: Option, + expires_at: Option, + ) -> Result<()> { + let trimmed = account_name.trim(); + let entry = self + .accounts + .iter_mut() + .find(|account| account.provider == provider && account.name == trimmed) + .ok_or_else(|| anyhow::anyhow!("no saved {} account named {}", provider, trimmed))?; + + entry.api_key = access_token; + if refresh_token.is_some() { entry.refresh_token = refresh_token; } + if id_token.is_some() { entry.id_token = id_token; } + if email.is_some() { entry.email = email; } + if account_id.is_some() { entry.account_id = account_id; } + if plan_type.is_some() { entry.plan_type = plan_type; } + if expires_at.is_some() { entry.expires_at = expires_at; } + Ok(()) + } + + // Legacy codex-specific wrappers (delegate to provider-agnostic methods) + + pub fn active_codex_account(&self) -> Option { + self.active_account_for_provider(crate::provider::CODEX_PROVIDER) + } + + pub fn runtime_usable_codex_account_count(&self) -> usize { + self.runtime_usable_account_count_for_provider(crate::provider::CODEX_PROVIDER) + } + + pub fn codex_account_by_name(&self, name: &str) -> Option { + self.account_by_name_and_provider(name, crate::provider::CODEX_PROVIDER) + } + pub fn effective_codex_api_key(&self, config: &AppConfig) -> Option { self.active_codex_account() .map(|account| account.api_key) @@ -300,29 +341,17 @@ impl AccountState { account_name: &str, result: crate::codex::DeviceAuthResult, ) -> Result<()> { - let trimmed = account_name.trim(); - let entry = self - .accounts - .iter_mut() - .find(|account| account.provider == "codex" && account.name == trimmed) - .ok_or_else(|| anyhow::anyhow!("no saved Codex account named {}", trimmed))?; - - entry.api_key = result.access_token; - entry.refresh_token = optional_trimmed(result.refresh_token); - entry.id_token = optional_trimmed(result.id_token); - if result.email.is_some() { - entry.email = result.email; - } - if result.account_id.is_some() { - entry.account_id = result.account_id; - } - if result.plan_type.is_some() { - entry.plan_type = result.plan_type; - } - if result.expires_at.is_some() { - entry.expires_at = result.expires_at; - } - Ok(()) + self.update_account_tokens_for_provider( + account_name, + crate::provider::CODEX_PROVIDER, + result.access_token, + optional_trimmed(result.refresh_token), + optional_trimmed(result.id_token), + result.email, + result.account_id, + result.plan_type, + result.expires_at, + ) } }