use codex_core::config::Config; use codex_features::Feature; use codex_features::RuntimeAuthMode; use codex_http_client::HttpClient; use codex_http_client::HttpClientFactory; use codex_login::AuthManager; use codex_login::CodexAuth; use codex_login::default_client::RESIDENCY_HEADER_NAME; use codex_login::default_client::create_client_with_chatgpt_cookies; use codex_login::default_client::default_headers; use codex_runtime_agent_instance::RuntimeAuthManager; use std::sync::Arc; use anyhow::Context; use serde::Serialize; use serde::de::DeserializeOwned; use std::sync::LazyLock; use std::sync::Mutex; use std::time::Duration; const OAI_PRODUCT_SKU_HEADER: &str = "OAI-Product-Sku"; const CODEX_PRODUCT_SKU: &str = "codex"; struct CachedChatGptClient { factory: HttpClientFactory, residency: Option>, client: HttpClient, } static CHATGPT_CLIENT: LazyLock>> = LazyLock::new(|| Mutex::new(None)); /// Reuse the client and cookies without changing the caller's captured account policy. fn chatgpt_client(factory: HttpClientFactory) -> HttpClient { let residency = default_headers() .get(RESIDENCY_HEADER_NAME) .map(|value| value.as_bytes().to_vec()); let mut cached = CHATGPT_CLIENT .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); if let Some(cached_client) = cached.as_ref() && cached_client.factory == factory && cached_client.residency == residency { return cached_client.client.clone(); } let client = create_client_with_chatgpt_cookies(&factory); *cached = Some(CachedChatGptClient { factory, residency, client: client.clone(), }); client } /// Make a GET request to the ChatGPT backend API. pub(crate) async fn chatgpt_get_request( config: &Config, path: String, ) -> anyhow::Result { let mut config = config.clone(); let (auth, runtime) = standalone_auth(&mut config).await?; chatgpt_get_request_with_timeout( &config, &auth, runtime.as_ref(), path, /*timeout*/ None, ) .await } pub(crate) async fn standalone_auth( config: &mut Config, ) -> anyhow::Result<( CodexAuth, Option<(Arc, RuntimeAuthMode)>, )> { // Standalone commands create one owner. Freeze the caller's account policy before loading // credentials; this temporary manager does not own later account changes. config.application_network_policy = config .application_network_policy .clone() .for_current_account(); if config.features.enabled(Feature::RuntimeAgentInstances) { codex_model_provider::validate_runtime_destination(Some(&config.chatgpt_base_url))?; } let auth_manager = AuthManager::shared_from_config(config, /*enable_codex_api_key_env*/ false).await?; let runtime = if config.features.enabled(Feature::RuntimeAgentInstances) && codex_runtime_agent_instance::is_openai_api_url(&config.chatgpt_base_url) { let installation_id = codex_core::resolve_installation_id(&config.codex_home).await?; codex_core::build_runtime_auth_manager(config, auth_manager.clone(), &installation_id) .map(|runtime| (runtime, config.runtime_auth_mode)) } else { None }; let auth = auth_manager .auth() .await .ok_or_else(|| anyhow::anyhow!("ChatGPT auth not available"))?; Ok((auth, runtime)) } pub(crate) async fn chatgpt_get_request_with_timeout( config: &Config, auth: &CodexAuth, runtime: Option<&(Arc, RuntimeAuthMode)>, path: String, timeout: Option, ) -> anyhow::Result { let chatgpt_base_url = &config.chatgpt_base_url; anyhow::ensure!( auth.uses_codex_backend(), "ChatGPT backend requests require Codex backend auth" ); anyhow::ensure!( auth.get_account_id().is_some(), "ChatGPT account ID not available, please re-run `codex login`" ); let url = format!( "{}/{}", chatgpt_base_url.trim_end_matches('/'), path.trim_start_matches('/') ); let (client, request_auth) = prepare_client_auth(config, auth, runtime, &url).await?; let mut request = client .get(&url) .headers(default_headers()) .headers( request_auth .auth .apply_auth_headers(Default::default()) .await?, ) .header(OAI_PRODUCT_SKU_HEADER, CODEX_PRODUCT_SKU) .header("Content-Type", "application/json"); if let Some(timeout) = timeout { request = request.timeout(timeout); } let response = request.send().await.context("Failed to send request")?; if response.status().is_success() { let result: T = response .json() .await .context("Failed to parse JSON response")?; Ok(result) } else { let status = response.status(); let body = response.text().await.unwrap_or_default(); anyhow::bail!("Request failed with status {status}: {body}") } } /// Make a POST request to the ChatGPT backend API with an already-captured auth identity. /// /// Callers must capture `auth` and `config.application_network_policy` together and preserve /// that snapshot rather than reacquiring either while the request is in flight. pub(crate) async fn chatgpt_post_request_with_timeout< TResponse: DeserializeOwned, TRequest: Serialize + ?Sized, >( config: &Config, auth: &CodexAuth, path: String, body: &TRequest, timeout: Duration, product_sku: &str, runtime: Option<&(Arc, RuntimeAuthMode)>, ) -> anyhow::Result { anyhow::ensure!( auth.uses_codex_backend(), "ChatGPT backend requests require Codex backend auth" ); anyhow::ensure!( auth.get_account_id().is_some(), "ChatGPT account ID not available, please re-run codex login" ); let url = format!( "{}/{}", config.chatgpt_base_url.trim_end_matches('/'), path.trim_start_matches('/') ); let (client, request_auth) = prepare_client_auth(config, auth, runtime, &url).await?; let response = client .post(&url) .headers(default_headers()) .headers( request_auth .auth .apply_auth_headers(Default::default()) .await?, ) .header(OAI_PRODUCT_SKU_HEADER, product_sku) .header("Content-Type", "application/json") .timeout(timeout) .json(body) .send() .await .context("Failed to send request")?; if response.status().is_success() { response .json() .await .context("Failed to parse JSON response") } else { let status = response.status(); let body = response.text().await.unwrap_or_default(); anyhow::bail!("Request failed with status {status}: {body}") } } /// Keep request credentials and the transport bound to the same account snapshot. async fn prepare_client_auth( config: &Config, auth: &CodexAuth, runtime: Option<&(Arc, RuntimeAuthMode)>, url: &str, ) -> anyhow::Result<(HttpClient, codex_model_provider::ResolvedProviderAuth)> { if runtime.is_some() { codex_model_provider::validate_runtime_destination(Some(url))?; } let resolved = codex_model_provider::auth_provider_for_request( auth, runtime, /*headers*/ &Default::default(), ) .await?; let factory = resolved.bind_http_client_factory(config.http_client_factory())?; let client = chatgpt_client(factory); Ok((client, resolved)) } #[cfg(test)] #[path = "chatgpt_client_runtime_auth_tests.rs"] mod runtime_auth_tests;