aKode fase 2b-2: rimosso login ChatGPT e tutti i sottosistemi solo-ChatGPT

- Login: resta solo chiave API (+ header, Bedrock). Rimossi OAuth/browser,
  device code, refresh/revoke su auth.openai.com, PAT, agent/workload identity,
  runtime agent instance, backend-client e openapi-models, workspace routing.
- Rimossi: generazione immagini (ext + skill imagegen), history notes, plugin
  remoti (catalogo, sync, share), cyber access program, daybreak, cloud config
  e requirements (config_server ora fail-closed), attestation, frozen cloud
  skills, EMA MCP auth, Codex Apps/connettori, ricerca ospitata, header/zstd/
  routing/cookie del backend Codex, fallback OPENAI_API_KEY del realtime.
- Messaggi d'errore senza link a chatgpt.com.
- Chiavi di config legacy accettate e ignorate; feature rimosse = Stage::Removed.
- Test: cancellati solo quelli del codice rimosso; test di sicurezza
  (sandbox estensioni, permessi, redazione, auth storage, requirements)
  adattati. Restano solo fallimenti d'ambiente (code-mode-host/V8, ~/.agents).
- Istruzioni di sistema invariate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-10 16:20:15 +01:00
parent 82347a58ed
commit 6089fbde91
1573 changed files with 10289 additions and 177679 deletions

View File

@@ -13,10 +13,7 @@ async fn queued_notifications_follow_auth_owner_changes(owner_generation: u64) {
let (tx, mut rx) = mpsc::channel(/*buffer*/ 1);
let outgoing = OutgoingMessageSender::new(tx.clone());
let (changes, auth_changes) = watch::channel(AuthChangeState::default());
let updated = AccountUpdatedNotification {
auth_mode: None,
plan_type: None,
};
let updated = AccountUpdatedNotification { auth_mode: None };
tx.send(OutgoingEnvelope::Broadcast {
message: timestamped_server_notification(ServerNotification::AccountUpdated(
updated.clone(),
@@ -28,7 +25,6 @@ async fn queued_notifications_follow_auth_owner_changes(owner_generation: u64) {
login_id: Some("queued-login".into()),
success: true,
error: None,
onboarding_entrypoint: None,
};
let notification = if login {
AccountNotification::LoginCompleted(payload.clone())

View File

@@ -1,11 +1,10 @@
//! Installs application requirements at startup and explicit config/account reloads.
//! Local policy limits cloud bootstrap; config construction rejects superseded policy snapshots.
//! Config construction rejects superseded policy snapshots.
use super::ApplicationPolicyLoad;
use super::ApplicationPolicySnapshot;
use super::ConfigManager;
use codex_config::ApplicationRequirementsToml;
use codex_config::CloudConfigBundleLoader;
use codex_config::NetworkDomainPermissionToml;
use codex_http_client::DestinationPolicy;
use codex_http_client::NetworkPolicyDenied;
@@ -52,7 +51,7 @@ impl ConfigManager {
&self.loader_overrides,
)
.await?;
let application = sources.compose(Default::default())?;
let application = sources.compose()?;
self.local_network_policy
.publish(local_revision, destination_policy(application.as_ref()));
Ok(sources)
@@ -75,25 +74,11 @@ impl ConfigManager {
.map_err(io::Error::other)?;
let revision = self.network_policy.policy().revision();
let local_sources = self.load_local_network_policy(revision).await?;
let cloud_config = self.current_managed_config_loader();
let result = async {
let cloud_snapshot = cloud_config.get_snapshot().await;
let cloud = cloud_snapshot.bundle.clone().map_err(io::Error::other)?;
let application = local_sources.compose(
cloud
.as_ref()
.map(|bundle| bundle.requirements_toml.clone())
.unwrap_or_default(),
)?;
Ok::<_, io::Error>((
destination_policy(application.as_ref()),
cloud,
cloud_snapshot,
))
}
.await;
let result = local_sources
.compose()
.map(|application| destination_policy(application.as_ref()));
match result {
Ok((policy, cloud, cloud_snapshot)) => {
Ok(policy) => {
let mut current = self.network_policy_snapshot.write().map_err(|_| {
io::Error::other("application network policy snapshot lock poisoned")
})?;
@@ -101,11 +86,7 @@ impl ConfigManager {
*current = None;
return Err(io::Error::other(NetworkPolicyDenied::Revoked));
}
let next = ApplicationPolicySnapshot {
revision,
policy,
cloud,
};
let next = ApplicationPolicySnapshot { revision, policy };
// Concurrent config loads may finish together if their actual inputs are unchanged.
let snapshot = match current.as_ref() {
Some(snapshot) if snapshot.as_ref() == &next => Arc::clone(snapshot),
@@ -115,10 +96,7 @@ impl ConfigManager {
snapshot
}
};
Ok(ApplicationPolicyLoad {
cloud_config: CloudConfigBundleLoader::from_snapshot(cloud_snapshot),
snapshot,
})
Ok(ApplicationPolicyLoad { snapshot })
}
Err(error) => {
self.fail_application_policy(revision)?;

View File

@@ -2,18 +2,11 @@
use super::ConfigManager;
use anyhow::Result;
use codex_config::CloudConfigBundleLoader;
use codex_config::LoaderOverrides;
use codex_config::test_support::CloudConfigBundleFixture;
use codex_config::test_support::ManagedConfigFixture;
use codex_http_client::NetworkPolicyDenied;
use pretty_assertions::assert_eq;
use std::sync::Arc;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::time::Duration;
use tempfile::tempdir;
use tokio::sync::Semaphore;
use tokio::time::timeout;
#[tokio::test]
async fn embedded_transports_stay_blocked_until_the_same_policy_is_published() -> Result<()> {
@@ -64,7 +57,6 @@ async fn embedded_transports_stay_blocked_until_the_same_policy_is_published() -
home.path().to_path_buf(),
Vec::new(),
overrides,
CloudConfigBundleLoader::default(),
)
.with_embedded_network_policy(policy);
drop(manager.refresh_application_network_policy().await?);
@@ -107,7 +99,7 @@ async fn embedded_transports_stay_blocked_until_the_same_policy_is_published() -
}
#[tokio::test]
async fn embedded_caller_activation_uses_cloud_requirements() -> Result<()> {
async fn embedded_caller_activation_uses_managed_requirements() -> Result<()> {
use crate::in_process::EmbeddedNetworkPolicy;
use codex_core::config::ConfigBuilder;
@@ -116,9 +108,9 @@ async fn embedded_caller_activation_uses_cloud_requirements() -> Result<()> {
let policy = EmbeddedNetworkPolicy::load(&overrides).await;
let mut config = ConfigBuilder::default()
.codex_home(home.path().to_path_buf())
.loader_overrides(overrides)
.cloud_config_bundle(
CloudConfigBundleFixture::loader_with_enterprise_requirement("[application.network]"),
.loader_overrides(
ManagedConfigFixture::requirements("[application.network]")
.loader_overrides(home.path(), overrides)?,
)
.build()
.await?;
@@ -136,64 +128,27 @@ async fn embedded_caller_activation_uses_cloud_requirements() -> Result<()> {
}
#[tokio::test]
async fn overlapping_policy_reloads_publish_in_order() -> Result<()> {
async fn successive_policy_reloads_publish_in_order() -> Result<()> {
let home = tempdir()?;
let entered = Arc::new(Semaphore::new(/*permits*/ 0));
let release = Arc::new(Semaphore::new(/*permits*/ 0));
let calls = Arc::new(AtomicUsize::new(/*v*/ 0));
let loader = CloudConfigBundleLoader::from_getter({
let (entered, release, calls) = (entered.clone(), release.clone(), calls.clone());
move || {
let (entered, release, calls) = (entered.clone(), release.clone(), calls.clone());
async move {
let call = calls.fetch_add(/*val*/ 1, Ordering::SeqCst);
let host = if call == 0 {
entered.add_permits(/*n*/ 1);
release
.acquire()
.await
.expect("release first reload")
.forget();
"old.example"
} else if call == 3 {
"old.example"
} else {
"new.example"
};
Ok(Some(
CloudConfigBundleFixture::enterprise_requirement(format!(
"[application.network.domains]\n'{host}' = 'allow'"
))
.into_bundle(),
))
}
}
});
let requirements = home.path().join("requirements.toml");
let write_allowed_host = |host: &str| {
std::fs::write(
&requirements,
format!("[application.network.domains]\n'{host}' = 'allow'"),
)
};
let manager = ConfigManager::new_for_tests(
home.path().to_path_buf(),
Vec::new(),
LoaderOverrides::without_managed_config_for_tests(),
loader,
LoaderOverrides {
system_requirements_path: Some(requirements.clone()),
..LoaderOverrides::without_managed_config_for_tests()
},
);
let first = tokio::spawn({
let manager = manager.clone();
async move { manager.refresh_application_network_policy().await }
});
entered.acquire().await?.forget();
let mut second = tokio::spawn({
let manager = manager.clone();
async move { manager.refresh_application_network_policy().await }
});
assert!(
timeout(Duration::from_millis(/*millis*/ 100), &mut second)
.await
.is_err()
);
assert_eq!(calls.load(Ordering::SeqCst), 1);
release.add_permits(/*n*/ 1);
let first_load = first.await??;
let second_load = timeout(Duration::from_secs(/*secs*/ 5), second).await???;
assert_eq!(calls.load(Ordering::SeqCst), 2);
write_allowed_host("old.example")?;
let first_load = manager.refresh_application_network_policy().await?;
write_allowed_host("new.example")?;
let second_load = manager.refresh_application_network_policy().await?;
manager.check_application_policy_load(&second_load)?;
let stale = manager
.check_application_policy_load(&first_load)
@@ -215,6 +170,7 @@ async fn overlapping_policy_reloads_publish_in_order() -> Result<()> {
let unchanged = manager.refresh_application_network_policy().await?;
manager.check_application_policy_load(&second_load)?;
manager.check_application_policy_load(&unchanged)?;
write_allowed_host("old.example")?;
let restored = manager.refresh_application_network_policy().await?;
manager.check_application_policy_load(&restored)?;
assert!(manager.check_application_policy_load(&first_load).is_err());
@@ -222,36 +178,3 @@ async fn overlapping_policy_reloads_publish_in_order() -> Result<()> {
Ok(())
}
#[tokio::test]
async fn cloud_config_change_supersedes_load_even_when_network_rules_are_unchanged() -> Result<()> {
let home = tempdir()?;
let calls = AtomicUsize::new(/*v*/ 0);
let loader = CloudConfigBundleLoader::from_getter(move || {
let model = if calls.fetch_add(/*val*/ 1, Ordering::SeqCst) == 0 {
"old"
} else {
"new"
};
async move {
Ok(Some(
CloudConfigBundleFixture::enterprise_config(format!("model = '{model}'"))
.into_bundle(),
))
}
});
let manager = ConfigManager::new_for_tests(
home.path().to_path_buf(),
Vec::new(),
LoaderOverrides::without_managed_config_for_tests(),
loader,
);
let first = manager.refresh_application_network_policy().await?;
let second = manager.refresh_application_network_policy().await?;
manager.check_application_policy_load(&second)?;
let stale = manager.check_application_policy_load(&first).unwrap_err();
assert_eq!(
stale.get_ref().and_then(|error| error.downcast_ref()),
Some(&NetworkPolicyDenied::Revoked)
);
Ok(())
}

View File

@@ -1,220 +0,0 @@
use std::sync::Arc;
use std::sync::Weak;
use axum::http::HeaderValue;
use codex_app_server_protocol::AttestationGenerateParams;
use codex_app_server_protocol::AttestationGenerateResponse;
use codex_app_server_protocol::ServerRequestPayload;
use codex_core::AttestationContext;
use codex_core::AttestationProvider;
use codex_core::GenerateAttestationFuture;
use serde::Serialize;
use tokio::time::Duration;
use tokio::time::timeout;
use tracing::warn;
use crate::outgoing_message::OutgoingMessageSender;
use crate::thread_state::ThreadStateManager;
const ATTESTATION_GENERATE_TIMEOUT: Duration = Duration::from_millis(100);
pub(crate) fn app_server_attestation_provider(
outgoing: Arc<OutgoingMessageSender>,
thread_state_manager: ThreadStateManager,
) -> Arc<dyn AttestationProvider> {
Arc::new(AppServerAttestationProvider {
outgoing: Arc::downgrade(&outgoing),
thread_state_manager,
})
}
struct AppServerAttestationProvider {
outgoing: Weak<OutgoingMessageSender>,
thread_state_manager: ThreadStateManager,
}
impl std::fmt::Debug for AppServerAttestationProvider {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("AppServerAttestationProvider")
.finish()
}
}
impl AttestationProvider for AppServerAttestationProvider {
fn header_for_request(&self, context: AttestationContext) -> GenerateAttestationFuture<'_> {
let Some(outgoing) = self.outgoing.upgrade() else {
return Box::pin(async { None });
};
let thread_state_manager = self.thread_state_manager.clone();
Box::pin(async move {
request_attestation_header_value_with_timeout(
outgoing,
thread_state_manager,
context.thread_id,
ATTESTATION_GENERATE_TIMEOUT,
)
.await
.and_then(|value| HeaderValue::from_bytes(value.as_bytes()).ok())
})
}
}
async fn request_attestation_header_value_with_timeout(
outgoing: Arc<OutgoingMessageSender>,
thread_state_manager: ThreadStateManager,
thread_id: codex_protocol::ThreadId,
timeout_duration: Duration,
) -> Option<String> {
let connection_id = thread_state_manager
.first_attestation_capable_connection_for_thread(thread_id)
.await?;
let connection_ids = [connection_id];
let (request_id, rx) = outgoing
.send_request_to_connections(
Some(&connection_ids),
ServerRequestPayload::AttestationGenerate(AttestationGenerateParams {}),
/*thread_id*/ None,
)
.await;
let result = match timeout(timeout_duration, rx).await {
Ok(Ok(Ok(result))) => result,
Ok(Ok(Err(err))) => {
// Don't log err.message because it may contain a token.
warn!(code = err.code, "attestation generation request failed");
return app_server_attestation_header_value(
AppServerAttestationStatus::RequestFailed,
/*token*/ None,
);
}
Ok(Err(err)) => {
warn!("attestation generation request canceled: {err}");
return app_server_attestation_header_value(
AppServerAttestationStatus::RequestCanceled,
/*token*/ None,
);
}
Err(_) => {
let _canceled = outgoing.cancel_request(&request_id).await;
warn!(
timeout_seconds = timeout_duration.as_secs(),
"attestation generation request timed out"
);
return app_server_attestation_header_value(
AppServerAttestationStatus::Timeout,
/*token*/ None,
);
}
};
match serde_json::from_value::<AttestationGenerateResponse>(result) {
Ok(response) => app_server_attestation_header_value(
AppServerAttestationStatus::Ok,
Some(&response.token),
),
Err(err) => {
warn!(
error_category = ?err.classify(),
"failed to deserialize attestation generation response"
);
app_server_attestation_header_value(
AppServerAttestationStatus::MalformedResponse,
/*token*/ None,
)
}
}
}
#[derive(Clone, Copy)]
enum AppServerAttestationStatus {
Ok,
Timeout,
RequestFailed,
RequestCanceled,
MalformedResponse,
}
impl AppServerAttestationStatus {
const fn code(self) -> u8 {
match self {
Self::Ok => 0,
Self::Timeout => 1,
Self::RequestFailed => 2,
Self::RequestCanceled => 3,
Self::MalformedResponse => 4,
}
}
}
#[derive(Serialize)]
struct AppServerAttestationEnvelope<'a> {
v: u8,
s: u8,
#[serde(skip_serializing_if = "Option::is_none")]
t: Option<&'a str>,
}
fn app_server_attestation_header_value(
status: AppServerAttestationStatus,
token: Option<&str>,
) -> Option<String> {
serde_json::to_string(&AppServerAttestationEnvelope {
v: 1,
s: status.code(),
t: token,
})
.map_err(|err| warn!("failed to serialize app-server attestation envelope: {err}"))
.ok()
}
#[cfg(test)]
mod tests {
use super::AppServerAttestationStatus;
use super::app_server_attestation_header_value;
use pretty_assertions::assert_eq;
#[test]
fn app_server_attestation_header_value_wraps_opaque_client_payloads() {
assert_eq!(
app_server_attestation_header_value(
AppServerAttestationStatus::Ok,
Some("v1.opaque-client-payload"),
),
Some(r#"{"v":1,"s":0,"t":"v1.opaque-client-payload"}"#.to_string())
);
}
#[test]
fn app_server_attestation_header_value_reports_app_server_failures() {
assert_eq!(
app_server_attestation_header_value(
AppServerAttestationStatus::Timeout,
/*token*/ None,
),
Some(r#"{"v":1,"s":1}"#.to_string())
);
assert_eq!(
app_server_attestation_header_value(
AppServerAttestationStatus::RequestFailed,
/*token*/ None,
),
Some(r#"{"v":1,"s":2}"#.to_string())
);
assert_eq!(
app_server_attestation_header_value(
AppServerAttestationStatus::RequestCanceled,
/*token*/ None,
),
Some(r#"{"v":1,"s":3}"#.to_string())
);
assert_eq!(
app_server_attestation_header_value(
AppServerAttestationStatus::MalformedResponse,
/*token*/ None
),
Some(r#"{"v":1,"s":4}"#.to_string())
);
}
}

View File

@@ -10,11 +10,7 @@ use codex_protocol::auth::AuthMode;
pub(crate) fn auth_mode_to_api(auth_mode: AuthMode) -> ApiAuthMode {
match auth_mode {
AuthMode::ApiKey => ApiAuthMode::ApiKey,
AuthMode::Chatgpt => ApiAuthMode::Chatgpt,
AuthMode::ChatgptAuthTokens => ApiAuthMode::ChatgptAuthTokens,
AuthMode::Headers => ApiAuthMode::Headers,
AuthMode::AgentIdentity => ApiAuthMode::AgentIdentity,
AuthMode::PersonalAccessToken => ApiAuthMode::PersonalAccessToken,
AuthMode::BedrockApiKey => ApiAuthMode::BedrockApiKey,
AuthMode::BedrockAccessKeys => ApiAuthMode::BedrockAccessKeys,
}

View File

@@ -39,9 +39,7 @@ use codex_app_server_protocol::McpServerElicitationRequestParams;
use codex_app_server_protocol::McpServerElicitationRequestResponse;
use codex_app_server_protocol::McpServerStartupState;
use codex_app_server_protocol::McpServerStatusUpdatedNotification;
use codex_app_server_protocol::ModelReroutedNotification;
use codex_app_server_protocol::ModelSafetyBufferingUpdatedNotification;
use codex_app_server_protocol::ModelVerificationNotification;
use codex_app_server_protocol::NetworkApprovalContext as V2NetworkApprovalContext;
use codex_app_server_protocol::NetworkPolicyAmendment as V2NetworkPolicyAmendment;
use codex_app_server_protocol::NetworkPolicyRuleAction as V2NetworkPolicyRuleAction;
@@ -397,28 +395,6 @@ pub(crate) async fn apply_bespoke_event_handling(
.await;
}
}
EventMsg::ModelReroute(event) => {
let notification = ModelReroutedNotification {
thread_id: conversation_id.to_string(),
turn_id: event_turn_id.clone(),
from_model: event.from_model,
to_model: event.to_model,
reason: event.reason.into(),
};
outgoing
.send_server_notification(ServerNotification::ModelRerouted(notification))
.await;
}
EventMsg::ModelVerification(event) => {
let notification = ModelVerificationNotification {
thread_id: conversation_id.to_string(),
turn_id: event_turn_id.clone(),
verifications: event.verifications.into_iter().map(Into::into).collect(),
};
outgoing
.send_server_notification(ServerNotification::ModelVerification(notification))
.await;
}
EventMsg::TurnModerationMetadata(event) => {
let notification = TurnModerationMetadataNotification {
thread_id: conversation_id.to_string(),
@@ -2707,7 +2683,7 @@ mod tests {
let config = load_default_config_for_test(&codex_home).await;
let thread_manager = Arc::new(
codex_core::test_support::thread_manager_with_models_provider_and_home(
CodexAuth::create_dummy_chatgpt_auth_for_testing(),
CodexAuth::from_api_key("test"),
config.model_provider.clone(),
config.codex_home.to_path_buf(),
Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()),
@@ -3151,7 +3127,7 @@ mod tests {
let config = load_default_config_for_test(&codex_home).await;
let thread_manager = Arc::new(
codex_core::test_support::thread_manager_with_models_provider_and_home(
CodexAuth::create_dummy_chatgpt_auth_for_testing(),
CodexAuth::from_api_key("test"),
config.model_provider.clone(),
config.codex_home.to_path_buf(),
Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()),
@@ -3285,7 +3261,7 @@ mod tests {
let config = load_default_config_for_test(&codex_home).await;
let thread_manager = Arc::new(
codex_core::test_support::thread_manager_with_models_provider_and_home(
CodexAuth::create_dummy_chatgpt_auth_for_testing(),
CodexAuth::from_api_key("test"),
config.model_provider.clone(),
config.codex_home.to_path_buf(),
Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()),
@@ -3379,7 +3355,7 @@ mod tests {
let config = load_default_config_for_test(&codex_home).await;
let thread_manager = Arc::new(
codex_core::test_support::thread_manager_with_models_provider_and_home(
CodexAuth::create_dummy_chatgpt_auth_for_testing(),
CodexAuth::from_api_key("test"),
config.model_provider.clone(),
config.codex_home.to_path_buf(),
Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()),

View File

@@ -18,9 +18,6 @@ pub(crate) fn config_layer_source_to_api(source: ConfigLayerSource) -> ApiConfig
}
ConfigLayerSource::Mdm { domain, key } => ApiConfigLayerSource::Mdm { domain, key },
ConfigLayerSource::System { file } => ApiConfigLayerSource::System { file },
ConfigLayerSource::EnterpriseManaged { id, name } => {
ApiConfigLayerSource::EnterpriseManaged { id, name }
}
ConfigLayerSource::User { file, profile } => ApiConfigLayerSource::User { file, profile },
ConfigLayerSource::Project { dot_codex_folder } => {
ApiConfigLayerSource::Project { dot_codex_folder }

View File

@@ -1,6 +1,5 @@
use codex_app_server_protocol::ModelProviderError;
use codex_arg0::Arg0DispatchPaths;
use codex_config::CloudConfigBundleLoader;
use codex_config::ConfigLayerStack;
use codex_config::LoaderOverrides;
use codex_config::ThreadConfigLoader;
@@ -28,9 +27,7 @@ use std::collections::HashMap;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::RwLock;
use tokio_util::sync::CancellationToken;
use toml::Value as TomlValue;
use tracing::instrument;
use tracing::warn;
@@ -46,21 +43,12 @@ pub(crate) struct ConfigManager {
runtime_feature_enablement: Arc<RwLock<BTreeMap<String, bool>>>,
loader_overrides: LoaderOverrides,
strict_config: bool,
cloud_config_bundle: Arc<RwLock<CloudConfigBundleLoader>>,
arg0_paths: Arg0DispatchPaths,
thread_config_loader: Arc<dyn ThreadConfigLoader>,
pub(crate) thread_config_loader: Arc<dyn ThreadConfigLoader>,
network_policy: codex_http_client::NetworkPolicyController,
local_network_policy: codex_http_client::NetworkPolicyController,
network_policy_reload: Arc<tokio::sync::Semaphore>,
network_policy_snapshot: Arc<RwLock<Option<Arc<ApplicationPolicySnapshot>>>>,
/// Captured before config loading so a reload also revokes pending startups.
mcp_ema_cancellation: Arc<Mutex<EmaCancellationRoots>>,
}
#[derive(Default)]
struct EmaCancellationRoots {
startup: CancellationToken,
lifetime: CancellationToken,
}
/// Startup configuration, including whether loading had to fall back to defaults.
@@ -69,15 +57,14 @@ pub(crate) struct StartupConfig {
pub(crate) used_defaults: bool,
}
/// Local auth authority and the cloud-backed configuration loaded with it.
pub(crate) struct CloudStartupConfig {
/// Startup configuration loaded with local fallback, plus the strictly loaded configuration.
pub(crate) struct ManagedStartupConfig {
pub(crate) bootstrap: Config,
pub(crate) config: std::io::Result<Config>,
}
/// Configuration and policy must finish loading against the same account and cloud snapshot.
/// Configuration and policy must finish loading against the same policy snapshot.
pub(crate) struct ApplicationPolicyLoad {
cloud_config: CloudConfigBundleLoader,
snapshot: Arc<ApplicationPolicySnapshot>,
}
@@ -85,7 +72,6 @@ pub(crate) struct ApplicationPolicyLoad {
struct ApplicationPolicySnapshot {
revision: codex_http_client::NetworkPolicyRevision,
policy: codex_http_client::DestinationPolicy,
cloud: Option<codex_config::CloudConfigBundle>,
}
impl ConfigManager {
@@ -94,7 +80,6 @@ impl ConfigManager {
cli_overrides: Vec<(String, TomlValue)>,
loader_overrides: LoaderOverrides,
strict_config: bool,
cloud_config_bundle: CloudConfigBundleLoader,
arg0_paths: Arg0DispatchPaths,
thread_config_loader: Arc<dyn ThreadConfigLoader>,
) -> Self {
@@ -105,14 +90,12 @@ impl ConfigManager {
runtime_feature_enablement: Arc::new(RwLock::new(BTreeMap::new())),
loader_overrides,
strict_config,
cloud_config_bundle: Arc::new(RwLock::new(cloud_config_bundle)),
arg0_paths,
thread_config_loader,
network_policy,
local_network_policy: Default::default(),
network_policy_reload: Arc::new(tokio::sync::Semaphore::new(/*permits*/ 1)),
network_policy_snapshot: Arc::default(),
mcp_ema_cancellation: Arc::default(),
}
}
@@ -120,35 +103,6 @@ impl ConfigManager {
self.codex_home.as_path()
}
/// Explicit account, policy-owner, and enterprise-login changes revoke cached access.
pub(crate) fn revoke_mcp_ema(&self) {
let mut current = self
.mcp_ema_cancellation
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
current.startup.cancel();
current.lifetime.cancel();
*current = EmaCancellationRoots::default();
}
/// Published threads are validated individually by the existing refresh loop.
pub(crate) fn revoke_mcp_ema_startups(&self) {
let mut current = self
.mcp_ema_cancellation
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
current.startup.cancel();
current.startup = CancellationToken::new();
}
fn capture_mcp_ema_cancellation(&self) -> codex_config::McpEmaCancellation {
let current = self
.mcp_ema_cancellation
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
codex_config::McpEmaCancellation::pending(current.startup.clone(), current.lifetime.clone())
}
pub(crate) fn with_embedded_network_policy(
mut self,
policy: crate::in_process::EmbeddedNetworkPolicy,
@@ -173,13 +127,6 @@ impl ConfigManager {
.unwrap_or_default()
}
pub(crate) fn current_managed_config_loader(&self) -> CloudConfigBundleLoader {
self.cloud_config_bundle
.read()
.map(|guard| guard.clone())
.unwrap_or_default()
}
pub(crate) fn extend_runtime_feature_enablement<I>(&self, enablement: I) -> Result<(), ()>
where
I: IntoIterator<Item = (String, bool)>,
@@ -190,28 +137,6 @@ impl ConfigManager {
Ok(())
}
/// aKode never fetches managed config bundles from a remote service, so an
/// auth change only resets any previously installed loader.
pub(crate) fn update_managed_config_loader(
&self,
_auth_manager: Arc<AuthManager>,
_config: &Config,
) {
self.clear_chatgpt_config_loader();
}
pub(crate) fn clear_chatgpt_config_loader(&self) {
if let Ok(mut guard) = self.cloud_config_bundle.write() {
if guard.config_server().is_none() {
guard.retire_ema_policy();
*guard = CloudConfigBundleLoader::default();
}
} else {
warn!("failed to clear cloud config bundle loader");
}
self.revoke_mcp_ema();
}
pub(crate) async fn sync_default_client_residency_requirement(&self) {
match self.load_latest_config(/*fallback_cwd*/ None).await {
Ok(config) => {
@@ -243,7 +168,6 @@ impl ConfigManager {
/// Loads system, user, and runtime settings without discovering a project
/// from the app-server process's working directory.
pub(crate) async fn load_non_project_config(&self) -> std::io::Result<Config> {
let mcp_ema_cancellation = self.capture_mcp_ema_cancellation();
let policy_load = self.refresh_application_network_policy().await?;
let mut config = ConfigBuilder::default()
.codex_home(self.codex_home.clone())
@@ -251,7 +175,6 @@ impl ConfigManager {
.loader_overrides(self.loader_overrides.clone())
.strict_config(self.strict_config)
.fallback_cwd(Some(self.codex_home.clone()))
.cloud_config_bundle(policy_load.cloud_config.clone())
.thread_config_loader(Arc::clone(&self.thread_config_loader))
.without_project_context()
.build()
@@ -260,9 +183,6 @@ impl ConfigManager {
self.apply_network_policy(&mut config);
self.apply_runtime_feature_enablement(&mut config);
self.apply_arg0_paths(&mut config);
config.config_layer_stack = config
.config_layer_stack
.with_mcp_ema_cancellation(mcp_ema_cancellation);
Ok(config)
}
@@ -271,7 +191,6 @@ impl ConfigManager {
session_layers: &ConfigLayerStack,
cwd: &Path,
) -> std::io::Result<Config> {
let mcp_ema_cancellation = self.capture_mcp_ema_cancellation();
let codex_home = AbsolutePathBuf::from_absolute_path(&self.codex_home)?;
let layers = self
.load_config_layers_for_cwd(AbsolutePathBuf::from_absolute_path(cwd)?)
@@ -286,38 +205,6 @@ impl ConfigManager {
self.apply_network_policy(&mut config);
self.apply_runtime_feature_enablement(&mut config);
self.apply_arg0_paths(&mut config);
config.config_layer_stack = config
.config_layer_stack
.with_mcp_ema_cancellation(mcp_ema_cancellation);
Ok(config)
}
/// Refreshes global settings and managed requirements using already fetched session layers.
pub(crate) async fn load_retained_session_config(
&self,
session_layers: &ConfigLayerStack,
cwd: &Path,
) -> std::io::Result<Config> {
let mcp_ema_cancellation = self.capture_mcp_ema_cancellation();
let mut manager = self.clone();
manager.thread_config_loader = Arc::new(codex_config::NoopThreadConfigLoader);
let refreshed_layers = manager
.load_config_layers_for_cwd(AbsolutePathBuf::from_absolute_path(cwd)?)
.await?;
// Merge the retained provider definitions before resolving managed provider selection.
let mut config = Config::rebuild_with_session_layers(
session_layers,
cwd.to_path_buf(),
&refreshed_layers,
AbsolutePathBuf::from_absolute_path(&self.codex_home)?,
)
.await?;
self.apply_network_policy(&mut config);
self.apply_runtime_feature_enablement(&mut config);
self.apply_arg0_paths(&mut config);
config.config_layer_stack = config
.config_layer_stack
.with_mcp_ema_cancellation(mcp_ema_cancellation);
Ok(config)
}
@@ -335,7 +222,6 @@ impl ConfigManager {
codex_config::ConfigLoadOptions {
loader_overrides: self.loader_overrides.clone(),
strict_config: self.strict_config,
cloud_config_bundle: policy_load.cloud_config.clone(),
},
)
.await?;
@@ -394,23 +280,24 @@ impl ConfigManager {
Ok(())
}
/// Load local policy before auth, then fetch the account's cloud configuration.
/// Callers choose their error/recovery policy before initializing any runtimes.
/// Loads a bootstrap config (falling back to defaults when allowed) and the
/// strictly loaded config. Callers choose their error/recovery policy before
/// initializing any runtimes.
pub(crate) async fn load_managed_startup_config(
&self,
cwd: Option<PathBuf>,
) -> std::io::Result<CloudStartupConfig> {
) -> std::io::Result<ManagedStartupConfig> {
let bootstrap = self.load_startup_config(cwd.clone()).await?.config;
let auth =
AuthManager::shared_from_config(&bootstrap, /*enable_codex_api_key_env*/ false)
.await
.map_err(std::io::Error::other)?;
self.update_managed_config_loader(auth, &bootstrap);
// Fail closed before startup when managed authentication requirements
// leave no usable login method, even if the bootstrap fell back to defaults.
AuthManager::shared_from_config(&bootstrap, /*enable_codex_api_key_env*/ false)
.await
.map_err(std::io::Error::other)?;
let config = self.load_latest_config(cwd).await;
Ok(CloudStartupConfig { bootstrap, config })
Ok(ManagedStartupConfig { bootstrap, config })
}
/// Installs local policy before cloud access; failed policy loads block traffic while
/// Installs local policy first; failed policy loads block traffic while
/// non-strict startup remains available for configuration repair.
pub(crate) async fn load_startup_config(
&self,
@@ -438,7 +325,6 @@ impl ConfigManager {
}
pub(crate) async fn load_default_config(&self) -> std::io::Result<Config> {
let mcp_ema_cancellation = self.capture_mcp_ema_cancellation();
let mut loader_overrides = self.loader_overrides.clone();
loader_overrides.ignore_user_config = true;
loader_overrides.ignore_project_config = true;
@@ -449,15 +335,11 @@ impl ConfigManager {
.cli_overrides(self.current_cli_overrides())
.loader_overrides(loader_overrides)
.fallback_cwd(Some(self.codex_home.clone()))
.cloud_config_bundle(CloudConfigBundleLoader::default())
.build()
.await?;
self.apply_network_policy(&mut config);
self.apply_runtime_feature_enablement(&mut config);
self.apply_arg0_paths(&mut config);
config.config_layer_stack = config
.config_layer_stack
.with_mcp_ema_cancellation(mcp_ema_cancellation);
Ok(config)
}
@@ -641,7 +523,6 @@ impl ConfigManager {
&ConfigLayerStack,
) -> std::io::Result<()>,
) -> std::io::Result<Config> {
let mcp_ema_cancellation = self.capture_mcp_ema_cancellation();
let policy_load = self.refresh_application_network_policy().await?;
let mut request_overrides = request_overrides.unwrap_or_default();
if let Some(value) = request_overrides.remove("bypass_hook_trust") {
@@ -668,7 +549,6 @@ impl ConfigManager {
.strict_config(self.strict_config)
.harness_overrides(typesafe_overrides)
.fallback_cwd(fallback_cwd)
.cloud_config_bundle(policy_load.cloud_config.clone())
.thread_config_loader(Arc::clone(&self.thread_config_loader))
.build_with_validation(validate)
.await;
@@ -677,9 +557,6 @@ impl ConfigManager {
self.apply_network_policy(&mut config);
self.apply_runtime_feature_enablement(&mut config);
self.apply_arg0_paths(&mut config);
config.config_layer_stack = config
.config_layer_stack
.with_mcp_ema_cancellation(mcp_ema_cancellation);
Ok(config)
}
@@ -703,7 +580,6 @@ impl ConfigManager {
codex_config::ConfigLoadOptions {
loader_overrides: self.loader_overrides().clone(),
strict_config: self.strict_config,
cloud_config_bundle: policy_load.cloud_config.clone(),
},
self.thread_config_loader.as_ref(),
)
@@ -750,14 +626,12 @@ impl ConfigManager {
codex_home: PathBuf,
cli_overrides: Vec<(String, TomlValue)>,
loader_overrides: LoaderOverrides,
cloud_config_bundle: CloudConfigBundleLoader,
) -> Self {
Self::new(
codex_home,
cli_overrides,
loader_overrides,
/*strict_config*/ false,
cloud_config_bundle,
Arg0DispatchPaths::default(),
Arc::new(codex_config::NoopThreadConfigLoader),
)
@@ -769,7 +643,6 @@ impl ConfigManager {
codex_home,
Vec::new(),
LoaderOverrides::without_managed_config_for_tests(),
CloudConfigBundleLoader::default(),
)
}
}

View File

@@ -2,14 +2,12 @@
use super::*;
use anyhow::Result;
use codex_config::CloudConfigBundleLoadError;
use codex_config::CloudConfigBundleLoadErrorCode;
use codex_config::ThreadConfigContext;
use codex_config::ThreadConfigLoadError;
use codex_config::ThreadConfigLoadErrorCode;
use codex_config::ThreadConfigLoaderFuture;
use codex_config::ThreadConfigSource;
use codex_config::test_support::CloudConfigBundleFixture;
use codex_config::test_support::ManagedConfigFixture;
use pretty_assertions::assert_eq;
use tempfile::tempdir;
use test_case::test_case;
@@ -19,8 +17,6 @@ use test_case::test_case;
#[test_case(GCP_PROVIDER_ID, "project_id = 'example-project'\nlocation = 'us-central1'", "example-project", "other-project", None; "gcp_project")]
#[test_case(GCP_PROVIDER_ID, "project_id = 'example-project'\nlocation = 'us-central1'", "us-central1", "us-east4", None; "gcp_location")]
#[test_case(GCP_PROVIDER_ID, "project_id = 'example-project'\nauth.command = 'print-token'", "print-token", "other-token", None; "gcp_auth")]
#[test_case("openai", "model_catalog_url = 'https://chatgpt.com/backend-api/codex/models'", "https://chatgpt.com/backend-api/codex/models", "https://chatgpt.com/backend-api/codex/other-models", None; "openai_catalog")]
#[test_case("openai", "model_catalog_url = 'https://chatgpt.com/backend-api/codex/models'", "https://chatgpt.com/backend-api/codex/models", "https://chatgpt.com/backend-api/codex/other-models", Some("https://us.api.openai.com/v1"); "openai_regional_catalog")]
#[tokio::test]
async fn provider_requirements_resolve_builtin_overrides(
provider_id: &str,
@@ -40,12 +36,11 @@ async fn provider_requirements_resolve_builtin_overrides(
let requirements = format!(
"model_provider = '{provider_id}'\n[model_providers.{provider_id}]\n{provider_config}"
);
let manager = ConfigManager::new_for_tests(
home.path().to_path_buf(),
Vec::new(),
LoaderOverrides::without_managed_config_for_tests(),
CloudConfigBundleFixture::loader_with_enterprise_requirement(&requirements),
);
let manager = ConfigManager::new_for_tests(home.path().to_path_buf(),
Vec::new(),
(ManagedConfigFixture::requirements(&requirements))
.loader_overrides_for_tests(home.path())?,
);
let current = manager
.load_latest_config(Some(workspace.path().to_path_buf()))
.await?;
@@ -59,14 +54,13 @@ async fn provider_requirements_resolve_builtin_overrides(
}
manager.check_thread_model_provider(&current).await?;
let changed = ConfigManager::new_for_tests(
home.path().to_path_buf(),
Vec::new(),
LoaderOverrides::without_managed_config_for_tests(),
CloudConfigBundleFixture::loader_with_enterprise_requirement(
let changed = ConfigManager::new_for_tests(home.path().to_path_buf(),
Vec::new(),
(ManagedConfigFixture::requirements(
requirements.replace(original, replacement),
),
);
))
.loader_overrides_for_tests(home.path())?,
);
assert_eq!(
changed
.check_thread_model_provider(&current)
@@ -115,19 +109,12 @@ async fn provider_requirements_do_not_reload_thread_config() -> Result<()> {
.is_err()
);
manager.check_thread_model_provider(&current).await?;
manager.cloud_config_bundle = Arc::new(RwLock::new(
CloudConfigBundleFixture::loader_with_enterprise_requirement("model_provider = 'retained'"),
));
let retained = manager
.load_retained_session_config(&current.config_layer_stack, &current.cwd)
.await?;
assert_eq!(retained.model_provider, current.model_provider);
let factory = current.http_client_factory();
assert_eq!(retained.http_client_factory(), factory);
manager.loader_overrides = ManagedConfigFixture::requirements("model_provider = 'retained'")
.loader_overrides_for_tests(home.path())?;
manager.check_thread_model_provider(&current).await?;
manager.cloud_config_bundle = Arc::new(RwLock::new(
CloudConfigBundleFixture::loader_with_enterprise_requirement("model_provider = 'other'"),
));
manager.loader_overrides = ManagedConfigFixture::requirements("model_provider = 'other'")
.loader_overrides_for_tests(home.path())?;
assert_eq!(
manager
.check_thread_model_provider(&current)
@@ -154,7 +141,6 @@ async fn provider_requirements_ignore_system_defaults_but_reject_requirement_cha
home.path().to_path_buf(),
Vec::new(),
overrides,
CloudConfigBundleLoader::default(),
);
let current = manager.load_latest_config(/*fallback_cwd*/ None).await?;
@@ -213,21 +199,12 @@ async fn provider_requirement_load_errors_reject_input() -> Result<()> {
let previous = ConfigManager::without_managed_config_for_tests(home.path().to_path_buf())
.load_latest_config(/*fallback_cwd*/ None)
.await?;
for loader in [
CloudConfigBundleFixture::loader_with_enterprise_requirement("invalid toml !!!"),
CloudConfigBundleLoader::new(async {
Err(CloudConfigBundleLoadError::new(
CloudConfigBundleLoadErrorCode::RequestFailed,
/*status_code*/ None,
"policy unavailable",
))
}),
] {
{
let manager = ConfigManager::new_for_tests(
home.path().to_path_buf(),
Vec::new(),
LoaderOverrides::without_managed_config_for_tests(),
loader,
ManagedConfigFixture::requirements("invalid toml !!!")
.loader_overrides_for_tests(home.path())?,
);
assert!(
manager
@@ -243,17 +220,21 @@ async fn provider_requirement_load_errors_reject_input() -> Result<()> {
#[tokio::test]
async fn catalog_reload_uses_latest_model_provider() -> Result<()> {
let home = tempdir()?;
let manager = ConfigManager::new_for_tests(
home.path().to_path_buf(),
Vec::new(),
LoaderOverrides::without_managed_config_for_tests(),
CloudConfigBundleFixture::loader_with_enterprise_requirement(
let manager = ConfigManager::new_for_tests(home.path().to_path_buf(),
Vec::new(),
(ManagedConfigFixture::requirements(
"model_provider = 'gateway'\n[model_providers.gateway]\nname = 'Gateway'\nbase_url = 'https://example.test'",
),
);
))
.loader_overrides_for_tests(home.path())?,
);
let startup = manager.load_non_project_config().await?;
assert_eq!(startup.model_provider_id, "gateway");
manager.clear_chatgpt_config_loader();
// Removing the managed requirements file removes the managed selection.
std::fs::remove_file(
home.path()
.join("managed-config-fixture")
.join("requirements.toml"),
)?;
let refreshed = manager
.load_startup_config(/*fallback_cwd*/ None)
.await?

View File

@@ -25,8 +25,6 @@ use codex_config::is_structured_feature_path;
use codex_config::merge_toml_values;
use codex_config::shell_environment_filter_entry;
use codex_config::validate_shell_environment_policy_filter_config;
use codex_connectors::apps_config_from_layer_stack;
use codex_connectors::apps_config_origins_from_layer_stack;
use codex_core::config::deserialize_config_toml_with_base;
use codex_core::config::edit::ConfigEdit;
use codex_core::config::edit::ConfigEditsBuilder;
@@ -153,7 +151,6 @@ impl ConfigManager {
let mut effective_config_toml = ConfigToml::try_from(layers.effective_config())
.map_err(|err| ConfigManagerError::toml("invalid configuration", err))?;
effective_config_toml.apps = apps_config_from_layer_stack(&layers);
layers
.requirements_toml()
.apply_exact_to_config(&mut effective_config_toml);
@@ -174,8 +171,6 @@ impl ConfigManager {
.exact_requirement_for_config_path(segments)
.is_none()
});
origins.retain(|path, _| !path.starts_with("apps."));
origins.extend(apps_config_origins_from_layer_stack(&layers));
origins.retain(|_, metadata| {
!matches!(&metadata.name, ConfigLayerSource::PackagedDefaults { .. })
});
@@ -931,9 +926,6 @@ fn override_message(layer: &ConfigLayerSource) -> String {
ConfigLayerSource::System { file } => {
format!("Overridden by managed config (system): {}", file.display())
}
ConfigLayerSource::EnterpriseManaged { id: _, name } => {
format!("Overridden by enterprise-managed config: {name}")
}
ConfigLayerSource::Project { dot_codex_folder } => format!(
"Overridden by project config: {}/{CONFIG_TOML_FILE}",
dot_codex_folder.display(),

View File

@@ -1,16 +1,12 @@
use super::*;
use anyhow::Result;
use axum::http::HeaderValue;
use codex_app_server_protocol::AppConfig;
use codex_app_server_protocol::AppToolApproval;
use codex_app_server_protocol::AppsConfig;
use codex_app_server_protocol::AskForApproval;
use codex_app_server_protocol::ConfigLayerSource as ApiConfigLayerSource;
use codex_config::CloudConfigBundleLoader;
use codex_config::LoaderOverrides;
use codex_config::test_support::CloudConfigBundleFixture;
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
use codex_config::test_support::ManagedConfigFixture;
use codex_utils_absolute_path::AbsolutePathBuf;
use pretty_assertions::assert_eq;
use tempfile::tempdir;
@@ -253,15 +249,15 @@ fn provider_remapping_respects_lower_layer_eviction() -> Result<()> {
)
.unwrap();
let mut layers = vec![ConfigLayerEntry::new(
ConfigLayerSource::System { file: file.clone() },
ConfigLayerSource::Mdm {
domain: "test".into(),
key: "test".into(),
},
complete(lower_id),
)];
if let Some(id) = middle {
layers.push(ConfigLayerEntry::new(
ConfigLayerSource::EnterpriseManaged {
id: "test".into(),
name: "test".into(),
},
ConfigLayerSource::System { file: file.clone() },
complete(id),
));
}
@@ -708,49 +704,6 @@ personality = true
Ok(())
}
#[tokio::test]
async fn psp_feature_configures_first_party_routing() -> Result<()> {
let tmp = tempdir()?;
let service = ConfigManager::new_for_tests(
tmp.path().to_path_buf(),
Vec::new(),
LoaderOverrides::without_managed_config_for_tests(),
CloudConfigBundleLoader::default(),
);
let config = service
.load_with_overrides(
Some(
[(
"features".to_string(),
serde_json::json!({ "apps": true, "psp": true }),
)]
.into_iter()
.collect(),
),
Default::default(),
)
.await?;
assert!(config.features.enabled(codex_features::Feature::Psp));
assert_eq!(
config.http_client_factory(),
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault)
.with_system_proxy_fallback()
.with_network_policy(config.application_network_policy.clone())
.with_chatgpt_cookies([HeaderValue::from_static("oai-chat-psp=true")])
);
assert_eq!(
config
.config_layer_stack
.effective_config()
.get("features")
.and_then(|features| features.get("psp")),
Some(&toml::Value::Boolean(true))
);
Ok(())
}
#[tokio::test]
async fn clear_missing_nested_config_is_noop() -> Result<()> {
let tmp = tempdir().expect("tempdir");
@@ -1029,7 +982,6 @@ async fn read_includes_origins_and_layers() {
tmp.path().to_path_buf(),
vec![],
LoaderOverrides::with_managed_config_path_for_tests(managed_path.clone()),
CloudConfigBundleLoader::default(),
);
let response = service
@@ -1108,7 +1060,6 @@ writable_roots = ["~/code"]
tmp.path().to_path_buf(),
vec![],
loader_overrides,
CloudConfigBundleLoader::default(),
);
let response = service
@@ -1148,7 +1099,6 @@ async fn write_value_reports_override() {
tmp.path().to_path_buf(),
vec![],
LoaderOverrides::with_managed_config_path_for_tests(managed_path.clone()),
CloudConfigBundleLoader::default(),
);
let result = service
@@ -1213,20 +1163,37 @@ async fn provider_setup_checks_versions_and_provider_write_uses_last_write_wins(
tmp.path().join(CONFIG_TOML_FILE),
"model = 'before'\n[model_providers.gateway]\nname = 'Before'\nenv_key = 'BEFORE_KEY'",
)?;
let calls = std::sync::atomic::AtomicUsize::new(/*v*/ 0);
let config_path = tmp.path().join(CONFIG_TOML_FILE);
let loader = CloudConfigBundleLoader::from_getter(move || {
if calls.fetch_add(/*val*/ 1, std::sync::atomic::Ordering::SeqCst) == 1 {
std::fs::write(&config_path, "model = 'newer'\n[model_providers.gateway]\nname = 'Another writer'\nenv_key = 'OTHER_KEY'").expect("intervening config write");
/// Simulates another writer that changes the user config while the write
/// is in flight (on the second configuration load).
struct InterveningWriter {
calls: std::sync::atomic::AtomicUsize,
config_path: std::path::PathBuf,
}
impl codex_config::ThreadConfigLoader for InterveningWriter {
fn load(
&self,
_context: codex_config::ThreadConfigContext,
) -> codex_config::ThreadConfigLoaderFuture<'_, Vec<codex_config::ThreadConfigSource>>
{
if self
.calls
.fetch_add(/*val*/ 1, std::sync::atomic::Ordering::SeqCst)
== 1
{
std::fs::write(&self.config_path, "model = 'newer'\n[model_providers.gateway]\nname = 'Another writer'\nenv_key = 'OTHER_KEY'").expect("intervening config write");
}
Box::pin(std::future::ready(Ok(Vec::new())))
}
std::future::ready(Ok(None))
});
let service = ConfigManager::new_for_tests(
}
let mut service = ConfigManager::new_for_tests(
tmp.path().to_path_buf(),
vec![],
LoaderOverrides::without_managed_config_for_tests(),
loader,
);
service.thread_config_loader = std::sync::Arc::new(InterveningWriter {
calls: std::sync::atomic::AtomicUsize::new(/*v*/ 0),
config_path: tmp.path().join(CONFIG_TOML_FILE),
});
let response = service
.model_provider_config_write(serde_json::from_value(serde_json::json!({
"settings":{"type":"customGateway","providerId":"gateway","name":"Gateway", "baseUrl":"https://gateway.example.test"}
@@ -1326,7 +1293,6 @@ async fn model_provider_settings_use_the_active_profile_layer() -> Result<()> {
home.path().to_path_buf(),
cli_overrides,
overrides.clone(),
CloudConfigBundleLoader::default(),
)
};
let manager = service(vec![]);
@@ -1451,7 +1417,6 @@ async fn write_value_defaults_to_selected_user_config_path() {
tmp.path().to_path_buf(),
vec![],
loader_overrides,
CloudConfigBundleLoader::default(),
);
service
.write_value(ConfigValueWriteParams {
@@ -1496,7 +1461,6 @@ async fn load_default_config_preserves_managed_requirements_and_selected_user_co
tmp.path().to_path_buf(),
vec![],
loader_overrides,
CloudConfigBundleLoader::default(),
);
service
@@ -1537,7 +1501,6 @@ async fn managed_auth_policy_survives_unusable_requirements_file_changes() -> Re
tmp.path().to_path_buf(),
Vec::new(),
LoaderOverrides::with_managed_config_path_for_tests(tmp.path().join("managed_config.toml")),
CloudConfigBundleLoader::default(),
);
let startup = service.load_latest_config(/*fallback_cwd*/ None).await?;
let auth_manager = codex_login::AuthManager::shared_from_config(
@@ -1564,10 +1527,6 @@ async fn managed_auth_policy_survives_unusable_requirements_file_changes() -> Re
!auth_manager
.is_login_method_allowed(codex_protocol::config_types::ForcedLoginMethod::Chatgpt)
);
assert_eq!(
auth_manager.effective_chatgpt_workspaces(),
Some(vec!["startup".to_string()])
);
Ok(())
}
@@ -1605,7 +1564,6 @@ url_prefix_from_env = "VENDOR_ENDPOINT"
tmp.path().to_path_buf(),
vec![],
LoaderOverrides::with_managed_config_path_for_tests(managed_path),
CloudConfigBundleLoader::default(),
);
let result = service
.write_value(ConfigValueWriteParams {
@@ -1659,7 +1617,6 @@ async fn thread_refresh_resolves_preserved_layers_before_materialization() -> Re
Vec::new(),
loader_overrides,
/*strict_config*/ true,
CloudConfigBundleLoader::default(),
Default::default(),
Arc::new(codex_config::NoopThreadConfigLoader),
);
@@ -1724,7 +1681,6 @@ async fn invalid_user_value_rejected_even_if_overridden_by_managed() {
tmp.path().to_path_buf(),
vec![],
LoaderOverrides::with_managed_config_path_for_tests(managed_path.clone()),
CloudConfigBundleLoader::default(),
);
let error = service
@@ -1807,17 +1763,16 @@ async fn write_value_rejects_feature_requirement_conflict() {
let tmp = tempdir().expect("tempdir");
std::fs::write(tmp.path().join(CONFIG_TOML_FILE), "").unwrap();
let service = ConfigManager::new_for_tests(
tmp.path().to_path_buf(),
vec![],
LoaderOverrides::without_managed_config_for_tests(),
CloudConfigBundleFixture::loader_with_enterprise_requirement(
let service = ConfigManager::new_for_tests(tmp.path().to_path_buf(),
vec![],
(ManagedConfigFixture::requirements(
r#"
[features]
fast_mode = true
"#,
),
);
))
.loader_overrides_for_tests(tmp.path()).expect("write managed config fixture"),
);
let error = service
.write_value(ConfigValueWriteParams {
@@ -1852,12 +1807,11 @@ async fn write_value_rejects_exact_managed_requirement() {
let path = tmp.path().join(CONFIG_TOML_FILE);
std::fs::write(&path, "allow_login_shell = true\n").unwrap();
let service = ConfigManager::new_for_tests(
tmp.path().to_path_buf(),
vec![],
LoaderOverrides::without_managed_config_for_tests(),
CloudConfigBundleFixture::loader_with_enterprise_requirement("allow_login_shell = false"),
);
let service = ConfigManager::new_for_tests(tmp.path().to_path_buf(),
vec![],
(ManagedConfigFixture::requirements("allow_login_shell = false"))
.loader_overrides_for_tests(tmp.path()).expect("write managed config fixture"),
);
let error = service
.write_value(ConfigValueWriteParams {
@@ -1886,11 +1840,9 @@ async fn write_value_rejects_managed_otel_values_and_preserves_unmanaged_sibling
let tmp = tempdir().expect("tempdir");
let path = tmp.path().join(CONFIG_TOML_FILE);
std::fs::write(&path, "").expect("write user config");
let service = ConfigManager::new_for_tests(
tmp.path().to_path_buf(),
vec![],
LoaderOverrides::without_managed_config_for_tests(),
CloudConfigBundleFixture::loader_with_enterprise_requirement(
let service = ConfigManager::new_for_tests(tmp.path().to_path_buf(),
vec![],
(ManagedConfigFixture::requirements(
r#"[otel]
tool_result = { max_bytes = 1024 }
log_user_prompt = false
@@ -1901,8 +1853,9 @@ trace_exporter = "none"
metrics_exporter = "none"
span_attributes = { "service.name" = "managed-service" }
tracestate = { managed = { tenant = "enterprise" }, empty = {} }"#,
),
);
))
.loader_overrides_for_tests(tmp.path()).expect("write managed config fixture"),
);
for (key_path, managed) in [
("otel", true),
("otel.log_user_prompt", true),
@@ -1972,12 +1925,11 @@ enabled = false
"#,
toml_path(tmp.path(), "managed-sqlite"),
);
let service = ConfigManager::new_for_tests(
tmp.path().to_path_buf(),
vec![],
LoaderOverrides::without_managed_config_for_tests(),
CloudConfigBundleFixture::loader_with_enterprise_requirement(requirements),
);
let service = ConfigManager::new_for_tests(tmp.path().to_path_buf(),
vec![],
(ManagedConfigFixture::requirements(requirements))
.loader_overrides_for_tests(tmp.path()).expect("write managed config fixture"),
);
let response = service
.read(ConfigReadParams {
@@ -2020,18 +1972,17 @@ span_attributes = { "service.name" = "user-service", "service.version" = "user-v
tracestate = { managed = { tenant = "user-tenant", region = "us" }, local = { tenant = "preserved" }, empty = { tenant = "also-preserved" } }"#,
)
.expect("write user config");
let service = ConfigManager::new_for_tests(
tmp.path().to_path_buf(),
vec![],
LoaderOverrides::without_managed_config_for_tests(),
CloudConfigBundleFixture::loader_with_enterprise_requirement(
let service = ConfigManager::new_for_tests(tmp.path().to_path_buf(),
vec![],
(ManagedConfigFixture::requirements(
r#"[otel]
log_user_prompt = false
exporter = "none"
span_attributes = { "service.name" = "managed-service" }
tracestate = { managed = { tenant = "enterprise" }, empty = {} }"#,
),
);
))
.loader_overrides_for_tests(tmp.path()).expect("write managed config fixture"),
);
let response = service
.read(ConfigReadParams {
include_layers: false,
@@ -2079,15 +2030,14 @@ async fn read_projects_managed_otel_tool_result_and_omits_its_origin() {
tool_result = { max_bytes = 1234 }"#,
)
.expect("write user config");
let service = ConfigManager::new_for_tests(
tmp.path().to_path_buf(),
vec![],
LoaderOverrides::without_managed_config_for_tests(),
CloudConfigBundleFixture::loader_with_enterprise_requirement(
let service = ConfigManager::new_for_tests(tmp.path().to_path_buf(),
vec![],
(ManagedConfigFixture::requirements(
r#"[otel]
tool_result = { max_bytes = 4096 }"#,
),
);
))
.loader_overrides_for_tests(tmp.path()).expect("write managed config fixture"),
);
let response = service
.read(ConfigReadParams {
@@ -2162,16 +2112,15 @@ async fn write_value_allows_unmanaged_setting_with_exact_requirement() {
let path = tmp.path().join(CONFIG_TOML_FILE);
std::fs::write(&path, "").unwrap();
let service = ConfigManager::new_for_tests(
tmp.path().to_path_buf(),
vec![],
LoaderOverrides::without_managed_config_for_tests(),
CloudConfigBundleFixture::loader_with_enterprise_requirement(
let service = ConfigManager::new_for_tests(tmp.path().to_path_buf(),
vec![],
(ManagedConfigFixture::requirements(
r#"
allow_login_shell = false
"#,
),
);
))
.loader_overrides_for_tests(tmp.path()).expect("write managed config fixture"),
);
service
.write_value(ConfigValueWriteParams {
@@ -2211,7 +2160,6 @@ async fn read_reports_managed_overrides_user_and_session_flags() {
tmp.path().to_path_buf(),
cli_overrides,
LoaderOverrides::with_managed_config_path_for_tests(managed_path.clone()),
CloudConfigBundleLoader::default(),
);
let response = service
@@ -2270,7 +2218,6 @@ async fn write_value_reports_managed_override() {
tmp.path().to_path_buf(),
vec![],
LoaderOverrides::with_managed_config_path_for_tests(managed_path.clone()),
CloudConfigBundleLoader::default(),
);
let result = service
@@ -2313,7 +2260,6 @@ span_attributes = { "service.name" = "managed-service" }"#,
tmp.path().to_path_buf(),
vec![],
LoaderOverrides::with_managed_config_path_for_tests(managed_path),
CloudConfigBundleLoader::default(),
);
let read = service
@@ -2393,7 +2339,6 @@ async fn multi_agent_v2_boolean_layer_owns_enabled_origin_and_overrides() {
tmp.path().to_path_buf(),
vec![],
LoaderOverrides::with_managed_config_path_for_tests(managed_path),
CloudConfigBundleLoader::default(),
);
let read = service
@@ -2453,7 +2398,6 @@ async fn structured_feature_toggle_ignores_unrelated_managed_settings() -> Resul
tmp.path().to_path_buf(),
vec![],
LoaderOverrides::with_managed_config_path_for_tests(managed_path.clone()),
CloudConfigBundleLoader::default(),
);
service
@@ -2494,7 +2438,6 @@ async fn structured_feature_toggle_ignores_unrelated_managed_settings() -> Resul
tmp.path().to_path_buf(),
vec![],
loader_overrides,
CloudConfigBundleLoader::default(),
);
profile_service
.write_value(ConfigValueWriteParams {
@@ -3137,7 +3080,6 @@ exclude = ["AWS_*"]
tmp.path().to_path_buf(),
vec![],
LoaderOverrides::with_managed_config_path_for_tests(managed_path),
CloudConfigBundleLoader::default(),
);
let response = service
@@ -3176,7 +3118,7 @@ exclude = ["AWS_*"]
}
#[tokio::test]
async fn allowed_login_methods_follow_current_forced_workspaces() -> Result<()> {
async fn allowed_login_methods_follow_managed_workspaces() -> Result<()> {
use codex_protocol::config_types::ForcedLoginMethod;
let tmp = tempdir()?;
@@ -3189,31 +3131,18 @@ async fn allowed_login_methods_follow_current_forced_workspaces() -> Result<()>
tmp.path().to_path_buf(),
Vec::new(),
LoaderOverrides::with_managed_config_path_for_tests(tmp.path().join("managed_config.toml")),
CloudConfigBundleLoader::default(),
);
let config = service.load_latest_config(/*fallback_cwd*/ None).await?;
let auth = codex_login::AuthManager::shared_from_config(
&config, /*enable_codex_api_key_env*/ false,
)
.await?;
for (workspaces, expected) in [
(
Some(vec!["managed".to_string()]),
vec![ForcedLoginMethod::Api, ForcedLoginMethod::Chatgpt],
),
(
Some(vec!["other".to_string()]),
vec![ForcedLoginMethod::Api],
),
(Some(Vec::new()), vec![ForcedLoginMethod::Api]),
(
None,
vec![ForcedLoginMethod::Api, ForcedLoginMethod::Chatgpt],
),
] {
auth.set_forced_chatgpt_workspace_id(workspaces);
assert_eq!(auth.allowed_login_methods(), expected);
}
// Managed workspaces only gate the non-API-key login method, which stays allowed
// while the allowlist is non-empty.
assert_eq!(
auth.allowed_login_methods(),
vec![ForcedLoginMethod::Api, ForcedLoginMethod::Chatgpt]
);
Ok(())
}
@@ -3228,7 +3157,6 @@ async fn permission_config_reload_merges_session_layers() -> Result<()> {
Vec::new(),
LoaderOverrides::without_managed_config_for_tests(),
/*strict_config*/ false,
CloudConfigBundleLoader::default(),
codex_arg0::Arg0DispatchPaths::default(),
std::sync::Arc::new(codex_config::NoopThreadConfigLoader),
);
@@ -3277,23 +3205,22 @@ async fn permission_config_reload_merges_session_layers() -> Result<()> {
Ok(())
}
/// Cloud storage requirements override user config and reject leaf or whole-table writes without touching the file.
/// Managed storage requirements override user config and reject leaf or whole-table writes without touching the file.
#[tokio::test]
async fn cloud_desktop_storage_requirements_control_reads_and_writes() {
async fn managed_desktop_storage_requirements_control_reads_and_writes() {
let tmp = tempdir().expect("tempdir");
let path = tmp.path().join(CONFIG_TOML_FILE);
let original = "[desktop]\ndefaultProjectParent = 'user'\nprojectlessWorkspaceRoot = 'user'\nlocaleOverride = 'en-US'\n";
std::fs::write(&path, original).unwrap();
let service = ConfigManager::new_for_tests(
tmp.path().to_path_buf(),
vec![],
LoaderOverrides::without_managed_config_for_tests(),
CloudConfigBundleFixture::loader_with_enterprise_requirement(format!(
let service = ConfigManager::new_for_tests(tmp.path().to_path_buf(),
vec![],
(ManagedConfigFixture::requirements(format!(
"[application.storage]\ndefault_project_parent = \"{}\"\nprojectless_workspace_root = \"{}\"",
toml_path(tmp.path(), "projects"),
toml_path(tmp.path(), "chats"),
)),
);
)))
.loader_overrides_for_tests(tmp.path()).expect("write managed config fixture"),
);
let response = service
.read(ConfigReadParams {
include_layers: false,
@@ -3432,7 +3359,6 @@ async fn model_provider_list_allows_user_overrides_of_system_defaults() -> Resul
tmp.path().to_path_buf(),
cli_overrides,
overrides.clone(),
CloudConfigBundleLoader::default(),
);
let response = service
.model_provider_list(ModelProviderListParams {})
@@ -3502,7 +3428,6 @@ async fn model_provider_list_checks_builtin_configuration_fields() -> Result<()>
home.path().to_path_buf(),
overrides,
LoaderOverrides::without_managed_config_for_tests(),
CloudConfigBundleLoader::default(),
);
let list = service
.model_provider_list(ModelProviderListParams {})
@@ -3551,7 +3476,6 @@ async fn model_provider_list_checks_builtin_configuration_fields() -> Result<()>
home.path().to_path_buf(),
overrides,
LoaderOverrides::without_managed_config_for_tests(),
CloudConfigBundleLoader::default(),
);
let list = service
.model_provider_list(ModelProviderListParams {})

View File

@@ -1,33 +1,13 @@
use std::collections::BTreeSet;
use std::sync::Arc;
use codex_app_server_protocol::ConfigBatchWriteParams;
use codex_app_server_protocol::ConfigEdit;
use codex_app_server_protocol::MergeStrategy;
use codex_core::ThreadManager;
use codex_core_plugins::EffectivePluginsChange;
use codex_core_plugins::remote::RemotePluginMaterialization;
use codex_core_plugins::remote::RemotePluginScope;
use codex_core_plugins::remote::RemotePluginShareDiscoverability;
use codex_login::AuthManager;
use serde_json::json;
use tracing::warn;
use crate::config_manager::ConfigManager;
use crate::request_processors::ConfigRequestProcessor;
use crate::request_serialization::RequestSerializationAccess;
use crate::request_serialization::RequestSerializationQueueKey;
use crate::request_serialization::RequestSerializationQueues;
/// Refresh plugin consumers and trust hooks from newly materialized Workspace + Listed bundles.
/// Refresh plugin consumers after the effective plugin set changes.
pub(crate) fn effective_plugins_changed_callback(
auth_manager: Arc<AuthManager>,
thread_manager: Arc<ThreadManager>,
config_manager: ConfigManager,
config_processor: ConfigRequestProcessor,
request_serialization_queues: RequestSerializationQueues,
) -> Arc<dyn Fn(EffectivePluginsChange) + Send + Sync> {
Arc::new(move |change| {
Arc::new(move |_change| {
thread_manager.plugins_manager().clear_cache();
thread_manager.skills_service().clear_cache();
@@ -36,142 +16,5 @@ pub(crate) fn effective_plugins_changed_callback(
refresh_thread_manager.invalidate_mcp_runtimes().await;
refresh_thread_manager.refresh_hook_runtimes().await;
});
if change.materialized_remote_plugins.is_empty() {
return;
}
let trust_auth_manager = Arc::clone(&auth_manager);
let trust_thread_manager = Arc::clone(&thread_manager);
let trust_config_manager = config_manager.clone();
let trust_config_processor = config_processor.clone();
let trust_request_serialization_queues = request_serialization_queues.clone();
tokio::spawn(async move {
trust_request_serialization_queues
.enqueue_background(
RequestSerializationQueueKey::Global("config"),
RequestSerializationAccess::Exclusive,
async move {
if let Err(err) = trust_materialized_plugin_hooks(
change.materialized_remote_plugins,
&trust_auth_manager,
&trust_thread_manager,
&trust_config_manager,
&trust_config_processor,
)
.await
{
warn!(error = %err, "failed to trust materialized plugin hooks");
}
},
)
.await;
});
})
}
fn workspace_listed_plugin_ids(
materializations: Vec<RemotePluginMaterialization>,
current_account_id: &str,
) -> BTreeSet<String> {
materializations
.into_iter()
.filter(|plugin| {
plugin.scope == RemotePluginScope::Workspace
&& plugin.discoverability == Some(RemotePluginShareDiscoverability::Listed)
&& plugin.authenticated_account_id.as_deref() == Some(current_account_id)
})
.map(|plugin| plugin.plugin_id.as_key())
.collect()
}
fn hook_trusted_hash_edit(hook_key: &str, current_hash: &str) -> ConfigEdit {
let escaped_hook_key = hook_key.replace('\\', "\\\\").replace('"', "\\\"");
ConfigEdit {
key_path: format!(r#"hooks.state."{escaped_hook_key}".trusted_hash"#),
value: json!(current_hash),
merge_strategy: MergeStrategy::Replace,
}
}
pub(crate) async fn trust_materialized_plugin_hooks(
materializations: Vec<RemotePluginMaterialization>,
auth_manager: &AuthManager,
thread_manager: &ThreadManager,
config_manager: &ConfigManager,
config_processor: &ConfigRequestProcessor,
) -> Result<(), String> {
let Some(current_account_id) = auth_manager
.auth_cached()
.and_then(|auth| auth.get_account_id())
else {
return Ok(());
};
let plugin_ids = workspace_listed_plugin_ids(materializations, &current_account_id);
if plugin_ids.is_empty() {
return Ok(());
}
let config = config_manager
.load_latest_config(/*fallback_cwd*/ None)
.await
.map_err(|err| format!("failed to reload config: {err}"))?;
let plugin_outcome = thread_manager
.plugins_manager()
.plugins_for_config(&config.plugins_config_input())
.await;
let hooks_config = codex_hooks::HooksConfig {
feature_enabled: true,
bypass_hook_trust: config.bypass_hook_trust,
config_layer_stack: Some(config.config_layer_stack),
plugin_hook_sources: plugin_outcome.effective_plugin_hook_sources(),
plugin_hook_load_warnings: plugin_outcome.effective_plugin_hook_warnings(),
..Default::default()
};
let hooks = tokio::task::spawn_blocking(move || codex_hooks::list_hooks(hooks_config))
.await
.map_err(|err| format!("hook discovery task failed: {err}"))?;
if !hooks.warnings.is_empty() {
warn!(
warnings = ?hooks.warnings,
"hook discovery reported warnings while trusting materialized plugins"
);
}
let edits = hooks
.hooks
.into_iter()
.filter(|hook| {
hook.plugin_id
.as_ref()
.is_some_and(|plugin_id| plugin_ids.contains(plugin_id))
})
.map(|hook| hook_trusted_hash_edit(&hook.key, &hook.current_hash))
.collect::<Vec<_>>();
if edits.is_empty() {
return Ok(());
}
if auth_manager
.auth_cached()
.and_then(|auth| auth.get_account_id())
.as_deref()
!= Some(current_account_id.as_str())
{
warn!("skipping materialized plugin hook trust after account changed");
return Ok(());
}
let params = ConfigBatchWriteParams {
edits,
file_path: None,
expected_version: None,
reload_user_config: true,
};
config_processor
.batch_write(params)
.await
.map_err(|err| format!("failed to write hook trust: {}", err.message))?;
Ok(())
}
#[cfg(test)]
#[path = "effective_plugin_change_tests.rs"]
mod tests;

View File

@@ -1,63 +0,0 @@
use super::*;
use codex_plugin::PluginId;
use pretty_assertions::assert_eq;
#[test]
fn only_workspace_listed_materializations_are_eligible() {
let materialization =
|name: &str,
scope: RemotePluginScope,
discoverability: Option<RemotePluginShareDiscoverability>| {
RemotePluginMaterialization {
plugin_id: PluginId::new(name.to_string(), "test".to_string())
.expect("valid plugin id"),
scope,
discoverability,
authenticated_account_id: Some("account-123".to_string()),
}
};
let mut materializations = vec![
materialization(
"eligible",
RemotePluginScope::Workspace,
Some(RemotePluginShareDiscoverability::Listed),
),
materialization(
"unlisted",
RemotePluginScope::Workspace,
Some(RemotePluginShareDiscoverability::Unlisted),
),
materialization(
"private",
RemotePluginScope::Workspace,
Some(RemotePluginShareDiscoverability::Private),
),
materialization("workspace-missing", RemotePluginScope::Workspace, None),
materialization("global", RemotePluginScope::Global, None),
materialization("user", RemotePluginScope::User, None),
];
let mut wrong_account = materialization(
"wrong-account",
RemotePluginScope::Workspace,
Some(RemotePluginShareDiscoverability::Listed),
);
wrong_account.authenticated_account_id = Some("account-456".to_string());
materializations.push(wrong_account);
let plugin_ids = workspace_listed_plugin_ids(materializations, "account-123");
assert_eq!(plugin_ids, BTreeSet::from(["eligible@test".to_string()]));
}
#[test]
fn hook_trusted_hash_edit_targets_only_escaped_leaf() {
assert_eq!(
hook_trusted_hash_edit(r#"plugin."quoted"\path"#, "sha256:current"),
ConfigEdit {
key_path: r#"hooks.state."plugin.\"quoted\"\\path".trusted_hash"#.to_string(),
value: serde_json::json!("sha256:current"),
merge_strategy: MergeStrategy::Replace,
}
);
}

View File

@@ -38,7 +38,6 @@ pub(crate) struct ThreadExtensionDependencies {
pub(crate) goal_service: Arc<GoalService>,
pub(crate) environment_manager: Arc<EnvironmentManager>,
pub(crate) executor_skill_provider: Arc<dyn codex_skills_extension::SkillProvider>,
pub(crate) cloud_skill_provider: Option<Arc<dyn codex_skills_extension::SkillProvider>>,
/// Process-scoped queue shared by idle dispatch and app-server requests.
pub(crate) queue_service: Option<Arc<QueuedItemService>>,
pub(crate) turn_start_admission: Option<Arc<dyn TurnStartAdmission>>,
@@ -57,7 +56,6 @@ pub(crate) fn thread_extensions(
goal_service,
environment_manager,
executor_skill_provider,
cloud_skill_provider,
queue_service,
turn_start_admission,
} = dependencies;
@@ -74,7 +72,6 @@ pub(crate) fn thread_extensions(
if let Some(queue_service) = queue_service {
codex_queue_extension::install(&mut builder, queue_service);
}
codex_history_notes_extension::install(&mut builder, auth_manager.clone());
crate::install_agent_message_board(&mut builder, thread_manager.clone());
if let Some(state_db) = state_db {
codex_goal_extension::install_with_backend(
@@ -93,16 +90,10 @@ pub(crate) fn thread_extensions(
codex_guardian_v2::install(&mut builder, thread_manager);
codex_memories_extension::install(&mut builder, codex_otel::global());
codex_mcp_extension::install_plugins(&mut builder, environment_manager);
codex_web_search_extension::install(&mut builder, auth_manager.clone());
codex_image_generation_extension::install(&mut builder, auth_manager, |config: &Config| {
Some(config.codex_home.clone())
});
let mut skill_providers = codex_skills_extension::SkillProviders::new()
codex_web_search_extension::install(&mut builder, auth_manager);
let skill_providers = codex_skills_extension::SkillProviders::new()
.with_executor_provider(executor_skill_provider)
.with_host_provider(Arc::new(codex_skills_extension::HostSkillProvider::new()));
if let Some(provider) = cloud_skill_provider {
skill_providers = skill_providers.with_cloud_provider(provider);
}
codex_skills_extension::install_with_providers_and_metrics(
&mut builder,
skill_providers,
@@ -117,7 +108,6 @@ pub(crate) fn thread_extensions(
.enabled(codex_features::Feature::OmitSkillDescriptions),
max_context_tokens: config.skill_max_context_tokens,
bundled_skills_enabled: config.bundled_skills_enabled(),
cloud_skill_enabled: config.cloud_skill_enabled,
shadow_selection_enabled: config
.features
.enabled(codex_features::Feature::SkillSearch),
@@ -311,7 +301,6 @@ mod tests {
use crate::outgoing_message::ConnectionId;
use crate::outgoing_message::OutgoingEnvelope;
use crate::outgoing_message::OutgoingMessage;
use crate::thread_state::ConnectionCapabilities;
use super::*;
@@ -401,7 +390,7 @@ mod tests {
let thread_state_manager = ThreadStateManager::new();
for connection_id in [subscribed_connection, unrelated_connection] {
thread_state_manager
.connection_initialized(connection_id, ConnectionCapabilities::default())
.connection_initialized(connection_id)
.await;
}
assert!(
@@ -455,7 +444,7 @@ mod tests {
let subscribed_connection = ConnectionId(1);
let thread_state_manager = ThreadStateManager::new();
thread_state_manager
.connection_initialized(subscribed_connection, ConnectionCapabilities::default())
.connection_initialized(subscribed_connection)
.await;
let sink = app_server_extension_event_sink(outgoing, thread_state_manager.clone());
@@ -508,7 +497,7 @@ mod tests {
let subscribed_connection = ConnectionId(1);
let thread_state_manager = ThreadStateManager::new();
thread_state_manager
.connection_initialized(subscribed_connection, ConnectionCapabilities::default())
.connection_initialized(subscribed_connection)
.await;
assert!(
thread_state_manager

View File

@@ -1,98 +0,0 @@
use std::sync::Arc;
use std::sync::RwLock;
use codex_app_server_protocol::ChatgptAuthTokensRefreshParams;
use codex_app_server_protocol::ChatgptAuthTokensRefreshReason;
use codex_app_server_protocol::ChatgptAuthTokensRefreshResponse;
use codex_app_server_protocol::ServerRequestPayload;
use codex_login::CodexAuth;
use codex_login::ExternalAuthFuture;
use codex_login::auth::ExternalAuth;
use codex_login::auth::ExternalAuthRefreshContext;
use codex_login::auth::ExternalAuthRefreshReason;
use tokio::time::Duration;
use tokio::time::timeout;
use crate::outgoing_message::OutgoingMessageSender;
const EXTERNAL_AUTH_REFRESH_TIMEOUT: Duration = Duration::from_secs(10);
pub(crate) struct ExternalAuthBridge {
outgoing: Arc<OutgoingMessageSender>,
auth: RwLock<CodexAuth>,
}
impl ExternalAuthBridge {
pub(crate) fn new(outgoing: Arc<OutgoingMessageSender>, auth: CodexAuth) -> Self {
Self {
outgoing,
auth: RwLock::new(auth),
}
}
async fn refresh(&self, context: ExternalAuthRefreshContext) -> std::io::Result<CodexAuth> {
let reason = match context.reason {
ExternalAuthRefreshReason::Unauthorized => ChatgptAuthTokensRefreshReason::Unauthorized,
};
let params = ChatgptAuthTokensRefreshParams {
reason,
previous_account_id: context.previous_account_id,
};
let (request_id, rx) = self
.outgoing
.send_request(ServerRequestPayload::ChatgptAuthTokensRefresh(params))
.await;
let result = match timeout(EXTERNAL_AUTH_REFRESH_TIMEOUT, rx).await {
Ok(result) => {
let result = result.map_err(|err| {
std::io::Error::other(format!("auth refresh request canceled: {err}"))
})?;
result.map_err(|err| {
// Don't log err.message because it may contain a token.
let code = err.code;
std::io::Error::other(format!("auth refresh request failed: code={code}"))
})?
}
Err(_) => {
let _canceled = self.outgoing.cancel_request(&request_id).await;
return Err(std::io::Error::other(format!(
"auth refresh request timed out after {}s",
EXTERNAL_AUTH_REFRESH_TIMEOUT.as_secs()
)));
}
};
// Don't propagate parser error messages because they may contain a token.
let response: ChatgptAuthTokensRefreshResponse = serde_json::from_value(result)
.map_err(|_| std::io::Error::other("invalid auth refresh response"))?;
let auth = CodexAuth::from_external_chatgpt_tokens(
response.access_token.as_str(),
response.chatgpt_account_id.as_str(),
response.chatgpt_plan_type.as_deref(),
)
.map_err(|err| {
std::io::Error::new(err.kind(), "auth refresh returned invalid credentials")
})?;
*self
.auth
.write()
.map_err(|_| std::io::Error::other("external auth lock is poisoned"))? = auth.clone();
Ok(auth)
}
}
impl ExternalAuth for ExternalAuthBridge {
fn resolve(&self) -> ExternalAuthFuture<'_, CodexAuth> {
Box::pin(async {
self.auth
.read()
.map(|auth| auth.clone())
.map_err(|_| std::io::Error::other("external auth lock is poisoned"))
})
}
fn refresh(&self, context: ExternalAuthRefreshContext) -> ExternalAuthFuture<'_, CodexAuth> {
Box::pin(ExternalAuthBridge::refresh(self, context))
}
}

View File

@@ -80,7 +80,6 @@ use codex_app_server_protocol::ServerNotification;
use codex_app_server_protocol::ServerRequest;
use codex_app_server_protocol::ThreadItemPayload;
use codex_arg0::Arg0DispatchPaths;
use codex_config::CloudConfigBundleLoader;
use codex_config::LoaderOverrides;
use codex_config::ThreadConfigLoader;
use codex_core::check_execpolicy_for_warnings;
@@ -148,8 +147,6 @@ pub struct InProcessStartArgs {
pub loader_overrides: LoaderOverrides,
/// Whether config API paths should reject unknown config fields.
pub strict_config: bool,
/// Preloaded cloud config bundle provider.
pub cloud_config_bundle: CloudConfigBundleLoader,
/// Policy shared with transports created by the embedder before startup.
pub embedded_network_policy: EmbeddedNetworkPolicy,
/// Loader used to fetch typed thread config sources before a thread starts.
@@ -437,7 +434,6 @@ async fn start_uninitialized(mut args: InProcessStartArgs) -> IoResult<InProcess
args.cli_overrides,
args.loader_overrides,
args.strict_config,
args.cloud_config_bundle,
args.arg0_paths.clone(),
args.thread_config_loader,
)
@@ -458,11 +454,6 @@ async fn start_uninitialized(mut args: InProcessStartArgs) -> IoResult<InProcess
let runtime_handle = tokio::spawn(async move {
let (outgoing_tx, outgoing_rx) = mpsc::channel::<OutgoingEnvelope>(channel_capacity);
let runtime_auth_slot = args
.config
.features
.enabled(codex_features::Feature::RuntimeAgentInstances)
.then(codex_runtime_agent_instance::RuntimeAuthSlot::default);
// A client can be waiting for process/kill while nobody is polling next_event.
let (process_reply_tx, mut process_reply_rx) = mpsc::channel(channel_capacity);
let outgoing_message_sender = Arc::new(
@@ -509,7 +500,6 @@ async fn start_uninitialized(mut args: InProcessStartArgs) -> IoResult<InProcess
let mut processor_handle = tokio::spawn(async move {
let (startup_warnings_tx, mut startup_warnings_rx) = mpsc::unbounded_channel();
let processor = Arc::new(MessageProcessor::new(MessageProcessorArgs {
cloud_skill_provider: None,
outgoing: Arc::clone(&processor_outgoing),
arg0_paths: args.arg0_paths,
config: args.config,
@@ -526,7 +516,6 @@ async fn start_uninitialized(mut args: InProcessStartArgs) -> IoResult<InProcess
&auth_manager,
))),
auth_manager,
runtime_auth_slot,
installation_id,
code_mode_session_provider: None,
remote_control_handle: None,
@@ -910,7 +899,6 @@ mod tests {
cli_overrides: Vec::new(),
loader_overrides: LoaderOverrides::default(),
strict_config: false,
cloud_config_bundle: CloudConfigBundleLoader::default(),
embedded_network_policy: Default::default(),
thread_config_loader: Arc::new(codex_config::NoopThreadConfigLoader),
feedback: CodexFeedback::new(),

View File

@@ -17,7 +17,7 @@ pub struct EmbeddedNetworkPolicy {
}
impl EmbeddedNetworkPolicy {
/// Loads the local rules for cloud bootstrap; all other traffic starts unavailable.
/// Loads the local application network rules; all other traffic starts unavailable.
pub async fn load(overrides: &codex_config::LoaderOverrides) -> Self {
let policy = Self::default();
let local = async {
@@ -26,7 +26,7 @@ impl EmbeddedNetworkPolicy {
overrides,
)
.await?
.compose(Default::default())
.compose()
}
.await;
if let Ok(application) = local {
@@ -80,9 +80,7 @@ pub(super) async fn configure(
.config;
let caller_auth = config.auth_config();
let bootstrap_auth = codex_login::AuthConfig {
chatgpt_base_url: Some(bootstrap_config.chatgpt_base_url.clone()),
forced_login_method: bootstrap_config.forced_login_method,
forced_chatgpt_workspace_id: bootstrap_config.forced_chatgpt_workspace_id.clone(),
managed_auth_policy: bootstrap_config
.config_layer_stack
.requirements()
@@ -91,22 +89,13 @@ pub(super) async fn configure(
..caller_auth.clone()
};
bootstrap_auth.validate()?;
let bootstrap_auth_manager = AuthManager::shared_from_auth_config(
bootstrap_auth,
/*enable_codex_api_key_env*/ false,
)
.await
.map_err(IoError::other)?;
config_manager.update_managed_config_loader(bootstrap_auth_manager, &bootstrap_config);
let policy_config = config_manager
.load_startup_config(Some(config.cwd.to_path_buf()))
.await?
.config;
config.validate_windows_mxc_requirement_from(&policy_config)?;
let auth_config = codex_login::AuthConfig {
chatgpt_base_url: Some(policy_config.chatgpt_base_url.clone()),
forced_login_method: policy_config.forced_login_method,
forced_chatgpt_workspace_id: policy_config.forced_chatgpt_workspace_id.clone(),
managed_auth_policy: policy_config
.config_layer_stack
.requirements()
@@ -136,7 +125,6 @@ pub(super) async fn configure(
config.application_auth_route_config = policy_config.application_auth_route_config;
config.forced_login_method = policy_config.forced_login_method;
config.forced_chatgpt_workspace_id = policy_config.forced_chatgpt_workspace_id;
config_manager.update_managed_config_loader(policy_auth_manager, config);
codex_login::default_client::set_default_client_residency_requirement(
config.enforce_residency.value(),
);

View File

@@ -3,7 +3,6 @@
use super::configure;
use crate::config_manager::ConfigManager;
use codex_arg0::Arg0DispatchPaths;
use codex_config::CloudConfigBundleLoader;
use codex_config::LoaderOverrides;
use codex_config::NoopThreadConfigLoader;
use codex_core::config::ConfigBuilder;
@@ -53,7 +52,6 @@ async fn startup_reloads_the_callers_selected_project() -> anyhow::Result<()> {
Vec::new(),
loader_overrides,
/*strict_config*/ true,
CloudConfigBundleLoader::default(),
Arg0DispatchPaths::default(),
Arc::new(NoopThreadConfigLoader),
);

View File

@@ -97,7 +97,6 @@ pub use codex_agent_message_board_host::delete_agent_message_boards;
pub use codex_agent_message_board_host::install_agent_message_board;
mod app_server_tracing;
mod attestation;
mod auth_mode;
mod bespoke_event_handling;
#[doc(hidden)]
@@ -119,7 +118,6 @@ mod effective_plugin_change;
mod error_code;
mod extensions;
mod external_agent_migration;
mod external_auth;
mod filters;
mod fs_watch;
mod fuzzy_file_search;
@@ -477,8 +475,6 @@ pub enum PluginStartupTasks {
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AppServerRuntimeOptions {
/// Optional host-owned frozen cloud skill catalog and resources, loaded once at startup.
pub cloud_skills_snapshot: Option<std::path::PathBuf>,
pub code_mode_host_transport: CodeModeHostTransport,
pub plugin_startup_tasks: PluginStartupTasks,
pub remote_control_startup_mode: RemoteControlStartupMode,
@@ -489,7 +485,6 @@ pub struct AppServerRuntimeOptions {
impl Default for AppServerRuntimeOptions {
fn default() -> Self {
Self {
cloud_skills_snapshot: None,
code_mode_host_transport: CodeModeHostTransport::Local,
plugin_startup_tasks: PluginStartupTasks::Start,
remote_control_startup_mode: RemoteControlStartupMode::ResolvePersisted,
@@ -510,18 +505,6 @@ pub async fn run_main_with_transport_options(
auth: WebsocketAuthSettings,
runtime_options: AppServerRuntimeOptions,
) -> IoResult<AppServerExit> {
let cloud_skill_provider = match runtime_options.cloud_skills_snapshot {
Some(path) => {
let provider = tokio::task::spawn_blocking(move || {
codex_skills_extension::FrozenCloudSkillProvider::from_file(&path)
})
.await
.map_err(std::io::Error::other)?
.map_err(|err| std::io::Error::new(ErrorKind::InvalidInput, err))?;
Some(Arc::new(provider) as Arc<dyn codex_skills_extension::SkillProvider>)
}
None => None,
};
#[cfg(target_os = "windows")]
let _registered_core = codex_windows_sandbox::registered_core_requested();
let managed_daemon = matches!(&transport, AppServerTransport::UnixSocket { .. })
@@ -558,7 +541,6 @@ pub async fn run_main_with_transport_options(
cli_kv_overrides.clone(),
loader_overrides,
strict_config,
Default::default(),
arg0_paths.clone(),
Arc::new(NoopThreadConfigLoader),
);
@@ -594,7 +576,6 @@ pub async fn run_main_with_transport_options(
AuthManager::shared_from_config(&config, /*enable_codex_api_key_env*/ false)
.await
.map_err(std::io::Error::other)?;
config_manager.update_managed_config_loader(auth_manager.clone(), &config);
config_manager
.sync_default_client_residency_requirement()
.await;
@@ -694,10 +675,6 @@ pub async fn run_main_with_transport_options(
});
}
let runtime_auth_slot = config
.features
.enabled(Feature::RuntimeAgentInstances)
.then(codex_runtime_agent_instance::RuntimeAuthSlot::default);
let outgoing_message_sender = Arc::new(OutgoingMessageSender::new(outgoing_tx));
let feedback = CodexFeedback::new();
@@ -861,9 +838,6 @@ pub async fn run_main_with_transport_options(
let (remote_control_accept_handle, remote_control_handle) = start_remote_control(
RemoteControlStartConfig {
runtime_auth: runtime_auth_slot
.clone()
.map(|slot| (slot, config.runtime_auth_mode)),
remote_control_url: config.chatgpt_base_url.clone(),
installation_id: installation_id.clone(),
policy: remote_control_policy,
@@ -972,7 +946,6 @@ pub async fn run_main_with_transport_options(
let outbound_control_tx = outbound_control_tx;
let (startup_warnings_tx, mut startup_warnings_rx) = mpsc::unbounded_channel();
let mut processor = MessageProcessor::new(MessageProcessorArgs {
cloud_skill_provider,
outgoing: outgoing_message_sender,
arg0_paths,
config: Arc::new(config),
@@ -989,7 +962,6 @@ pub async fn run_main_with_transport_options(
&auth_manager,
))),
auth_manager,
runtime_auth_slot,
installation_id,
code_mode_session_provider,
remote_control_handle: Some(remote_control_handle.clone()),
@@ -1240,12 +1212,7 @@ pub async fn run_main_with_transport_options(
)
.await;
processor
.connection_initialized(
connection_id,
connection_state
.session
.request_attestation(),
)
.connection_initialized(connection_id)
.await;
connection_state
.outbound_initialized

View File

@@ -30,9 +30,6 @@ const DISABLE_MANAGED_CONFIG_ENV_VAR: &str = "CODEX_APP_SERVER_DISABLE_MANAGED_C
#[derive(Debug, Parser)]
#[command(version)]
struct AppServerArgs {
/// Load frozen cloud skills from a JSON snapshot instead of a live skill service.
#[arg(long, value_name = "PATH")]
cloud_skills_snapshot: Option<PathBuf>,
#[command(flatten)]
config_overrides: CliConfigOverrides,
@@ -80,7 +77,6 @@ fn main() -> anyhow::Result<()> {
let _ = codex_app_server::take_remote_control_disabled_env();
arg0_dispatch_or_else(move |arg0_paths: Arg0DispatchPaths| async move {
let AppServerArgs {
cloud_skills_snapshot,
config_overrides,
code_mode_host,
listen,
@@ -101,7 +97,6 @@ fn main() -> anyhow::Result<()> {
let transport = listen;
let auth = auth.try_into_settings()?;
let mut runtime_options = AppServerRuntimeOptions {
cloud_skills_snapshot,
code_mode_host_transport: code_mode_host.into(),
managed_daemon,
..Default::default()

View File

@@ -46,7 +46,6 @@ async fn reload_mcp_config_with_policy(
config_manager: &ConfigManager,
policy: ReloadPolicy,
) -> io::Result<()> {
config_manager.revoke_mcp_ema_startups();
let mut rejected = false;
let mut load_error = None;
let mut completed: Vec<Arc<CodexThread>> = Vec::new();
@@ -91,18 +90,17 @@ async fn reload_mcp_config_with_policy(
warn!(%thread_id, %err, "failed to load session configuration");
}
target_load_error = Some(err);
disabled_enterprise_config(&current_config)
current_config.as_ref().clone()
}
}
} else {
disabled_enterprise_config(&current_config)
current_config.as_ref().clone()
};
match target.refresh_mcp_config(current_config, next_config).await {
ConfigRefreshOutcome::Published => {}
ConfigRefreshOutcome::Rejected => rejected = true,
ConfigRefreshOutcome::Stale => {
if attempt == 2 {
target.disable_mcp_enterprise_auth().await;
rejected = true;
}
continue;
@@ -122,7 +120,6 @@ async fn reload_mcp_config_with_policy(
if let Ok(thread) = thread_manager.get_thread(thread_id).await
&& !completed.iter().any(|done| Arc::ptr_eq(done, &thread))
{
thread.disable_mcp_enterprise_auth().await;
rejected = true;
}
}
@@ -136,21 +133,12 @@ async fn reload_mcp_config_with_policy(
}
if rejected && matches!(policy, ReloadPolicy::Strict) {
return Err(io::Error::other(
"enterprise MCP configuration was rejected; affected sessions retained their previous configuration with enterprise MCP disabled",
"MCP configuration was rejected; affected sessions retained their previous configuration",
));
}
Ok(())
}
fn disabled_enterprise_config(current_config: &Config) -> Config {
let mut config = current_config.clone();
config.disable_mcp_enterprise_auth();
config.config_layer_stack = config
.config_layer_stack
.with_cloud_config_binding(/*binding*/ None);
config
}
async fn load_refresh_config(
current_config: &Config,
config_manager: &ConfigManager,
@@ -169,7 +157,6 @@ mod tests {
use crate::extensions::ThreadExtensionDependencies;
use crate::extensions::thread_extensions;
use codex_arg0::Arg0DispatchPaths;
use codex_config::CloudConfigBundleLoader;
use codex_config::LoaderOverrides;
use codex_config::ThreadConfigContext;
use codex_config::ThreadConfigLoadError;
@@ -372,8 +359,7 @@ enabled = false
let current_config = thread.config().await;
let refresh_config = load_refresh_config(&current_config, &config_manager).await?;
let mut actual = refresh_config.mcp_servers.get().clone();
actual.remove(codex_mcp::CODEX_APPS_MCP_SERVER_NAME);
let actual = refresh_config.mcp_servers.get().clone();
let expected = serde_json::from_value::<HashMap<String, McpServerConfig>>(json!({
"global": {
"command": "global-mcp",
@@ -411,12 +397,6 @@ enabled = false
Some(temp_dir.path().join("good")),
)
.await?;
assert!(
!pending_startup
.config_layer_stack
.mcp_ema_cancellation()
.is_cancelled()
);
// Prediction forks inherit a published config and may outlive their parent.
let parent = thread_manager
.start_thread(codex_core::StartThreadOptions::new(pending_startup.clone()))
@@ -437,44 +417,8 @@ enabled = false
reload_mcp_config(&thread_manager, &config_manager).await?;
let fork = thread_manager.start_thread(inherited_fork).await?;
assert!(
fork.thread
.config()
.await
.config_layer_stack
.mcp_ema_cancellation()
.is_cancelled()
);
fork.thread.shutdown_and_wait().await?;
parent.thread.shutdown_and_wait().await?;
assert!(
pending_startup
.config_layer_stack
.mcp_ema_cancellation()
.is_cancelled()
);
assert!(
thread
.config()
.await
.config_layer_stack
.mcp_ema_cancellation()
.is_cancelled()
);
let fresh_startup = config_manager
.load_for_cwd(
/*request_overrides*/ None,
ConfigOverrides::default(),
Some(temp_dir.path().join("good")),
)
.await?;
assert!(
!fresh_startup
.config_layer_stack
.mcp_ema_cancellation()
.is_cancelled()
);
assert!(
thread
.config()
@@ -542,7 +486,6 @@ enabled = false
good_config.codex_home.to_path_buf(),
)),
),
codex_core::CodexAppsToolsCache::default(),
SessionSource::Exec,
Arc::clone(&environment_manager),
thread_extensions(
@@ -551,7 +494,6 @@ enabled = false
sample_responses: Arc::new(
crate::thread_sample::SampleResponseRegistry::default(),
),
cloud_skill_provider: None,
event_sink: Arc::new(NoopExtensionEventSink),
auth_manager: auth_manager.clone(),
state_db: Some(state_db.clone()),
@@ -569,7 +511,6 @@ enabled = false
codex_core::passthrough_image_store(),
Arc::clone(&thread_store),
codex_core::local_agent_graph_store_from_state_db(Some(&state_db)),
/*attestation_provider*/ None,
/*external_time_provider*/ None,
)
});
@@ -592,7 +533,6 @@ enabled = false
Vec::new(),
LoaderOverrides::without_managed_config_for_tests(),
/*strict_config*/ false,
CloudConfigBundleLoader::default(),
Arg0DispatchPaths::default(),
loader.clone(),
);

View File

@@ -5,11 +5,9 @@ use std::sync::Arc;
use std::sync::OnceLock;
use std::sync::atomic::AtomicBool;
use crate::attestation::app_server_attestation_provider;
use crate::config_manager::ConfigManager;
use crate::connection_rpc_gate::ConnectionRpcGate;
use crate::current_time::app_server_time_provider;
use crate::error_code::internal_error;
use crate::error_code::invalid_params;
use crate::error_code::invalid_request;
use crate::error_code::method_not_found;
@@ -35,8 +33,6 @@ use crate::request_processors::FsRequestProcessor;
use crate::request_processors::GitRequestProcessor;
use crate::request_processors::InitializeRequestProcessor;
use crate::request_processors::MarketplaceRequestProcessor;
use crate::request_processors::McpEventStreamReady;
use crate::request_processors::McpEventStreams;
use crate::request_processors::McpRequestProcessor;
use crate::request_processors::PluginRequestProcessor;
use crate::request_processors::ProcessExecRequestProcessor;
@@ -56,7 +52,6 @@ use crate::request_serialization::RequestSerializationQueueKey;
use crate::request_serialization::RequestSerializationQueues;
use crate::skills_watcher::SkillsWatcher;
use crate::startup_warnings::StartupWarnings;
use crate::thread_state::ConnectionCapabilities;
use crate::thread_state::ThreadStateManager;
use crate::transport::AppServerTransport;
use crate::transport::RemoteControlHandle;
@@ -94,7 +89,6 @@ use codex_protocol::protocol::SessionSource;
use codex_protocol::protocol::W3cTraceContext;
use codex_queue_extension::QueuedItemService;
use codex_rollout::StateDbHandle;
use codex_runtime_agent_instance::RuntimeAuthSlot;
use codex_state::log_db::LogDbLayer;
use codex_thread_store::LocalQueueStore;
use codex_thread_store::QueueStore;
@@ -182,7 +176,6 @@ pub(crate) struct ConnectionSessionState {
disconnect: CancellationToken,
pub(crate) rpc_gate: Arc<ConnectionRpcGate>,
pub(crate) origin: crate::transport::ConnectionOrigin,
pub(crate) mcp_event_streams: McpEventStreams,
initialized: OnceLock<InitializedConnectionSessionState>,
}
@@ -192,7 +185,6 @@ pub(crate) struct InitializedConnectionSessionState {
pub(crate) opted_out_notification_methods: HashSet<String>,
pub(crate) app_server_client_name: String,
pub(crate) client_version: String,
pub(crate) request_attestation: bool,
pub(crate) client_mcp_extensions: ClientMcpExtensions,
}
@@ -202,7 +194,6 @@ impl ConnectionSessionState {
origin,
disconnect: CancellationToken::new(),
rpc_gate: Arc::new(ConnectionRpcGate::new()),
mcp_event_streams: McpEventStreams::default(),
initialized: OnceLock::new(),
}
}
@@ -236,12 +227,6 @@ impl ConnectionSessionState {
.map(|session| session.client_version.as_str())
}
pub(crate) fn request_attestation(&self) -> bool {
self.initialized
.get()
.is_some_and(|session| session.request_attestation)
}
pub(crate) fn client_mcp_extensions(&self) -> ClientMcpExtensions {
self.initialized
.get()
@@ -254,7 +239,6 @@ impl ConnectionSessionState {
}
pub(crate) struct MessageProcessorArgs {
pub(crate) cloud_skill_provider: Option<Arc<dyn codex_skills_extension::SkillProvider>>,
pub(crate) outgoing: Arc<OutgoingMessageSender>,
pub(crate) arg0_paths: Arg0DispatchPaths,
pub(crate) config: Arc<Config>,
@@ -269,7 +253,6 @@ pub(crate) struct MessageProcessorArgs {
pub(crate) startup_warnings_tx: mpsc::UnboundedSender<String>,
pub(crate) session_source: SessionSource,
pub(crate) auth_manager: Arc<AuthManager>,
pub(crate) runtime_auth_slot: Option<RuntimeAuthSlot>,
pub(crate) user_verification: Arc<crate::user_verification::Service>,
pub(crate) installation_id: String,
pub(crate) code_mode_session_provider: Option<Arc<dyn CodeModeSessionProvider>>,
@@ -283,7 +266,6 @@ impl MessageProcessor {
/// `Sender` so handlers can enqueue messages to be written to stdout.
pub(crate) fn new(args: MessageProcessorArgs) -> Self {
let MessageProcessorArgs {
cloud_skill_provider,
outgoing,
arg0_paths,
config,
@@ -297,7 +279,6 @@ impl MessageProcessor {
startup_warnings_tx,
session_source,
auth_manager,
runtime_auth_slot,
user_verification,
installation_id,
code_mode_session_provider,
@@ -374,7 +355,6 @@ impl MessageProcessor {
let manager = ThreadManager::new(
config.as_ref(),
startup,
codex_core::CodexAppsToolsCache::default(),
session_source,
environment_manager,
thread_extensions(
@@ -388,7 +368,6 @@ impl MessageProcessor {
goal_service: Arc::clone(&goal_service),
environment_manager: Arc::clone(&environment_manager_for_extensions),
executor_skill_provider: Arc::clone(&executor_skill_provider),
cloud_skill_provider: cloud_skill_provider.clone(),
queue_service: queue_service.clone(),
turn_start_admission: Some(Arc::clone(&turn_start_admission)),
},
@@ -399,10 +378,6 @@ impl MessageProcessor {
codex_core::passthrough_image_store(),
Arc::clone(&thread_store),
codex_core::local_agent_graph_store_from_state_db(state_db.as_ref()),
Some(app_server_attestation_provider(
outgoing.clone(),
thread_state_manager.clone(),
)),
{
let time_provider =
app_server_time_provider(outgoing.clone(), thread_state_manager.clone());
@@ -414,11 +389,6 @@ impl MessageProcessor {
None => manager,
}
});
let runtime_auth = thread_manager.runtime_auth_manager();
if let (Some(slot), Some(runtime)) = (runtime_auth_slot, &runtime_auth) {
// Bind runtime auth requests to the harness registration.
slot.get_or_init(|| Arc::clone(runtime));
}
let model_catalog = Arc::new(crate::model_catalog::ModelCatalog::new(
config_manager.clone(),
startup_cwd,
@@ -444,13 +414,9 @@ impl MessageProcessor {
Arc::clone(&model_catalog),
);
let on_effective_plugins_changed =
crate::effective_plugin_change::effective_plugins_changed_callback(
auth_manager.clone(),
Arc::clone(&thread_manager),
config_manager.clone(),
config_processor.clone(),
request_serialization_queues.clone(),
);
crate::effective_plugin_change::effective_plugins_changed_callback(Arc::clone(
&thread_manager,
));
let account_processor = AccountRequestProcessor::new(
auth_manager.clone(),
Arc::clone(&thread_manager),
@@ -479,7 +445,6 @@ impl MessageProcessor {
Arc::clone(&environment_manager_for_requests),
);
let feedback_processor = FeedbackRequestProcessor::new(
auth_manager.clone(),
Arc::clone(&thread_manager),
Arc::clone(&config),
feedback,
@@ -492,10 +457,8 @@ impl MessageProcessor {
let mcp_processor = McpRequestProcessor::new(
auth_manager.clone(),
Arc::clone(&thread_manager),
thread_state_manager.clone(),
outgoing.clone(),
config_manager.clone(),
account_processor.clone(),
);
let plugin_processor = PluginRequestProcessor::new(
auth_manager.clone(),
@@ -832,20 +795,9 @@ impl MessageProcessor {
.await;
}
pub(crate) async fn connection_initialized(
&self,
connection_id: ConnectionId,
request_attestation: bool,
) {
self.account_processor
.notify_workspace_routing_to_connection(connection_id);
pub(crate) async fn connection_initialized(&self, connection_id: ConnectionId) {
self.thread_processor
.connection_initialized(
connection_id,
ConnectionCapabilities {
request_attestation,
},
)
.connection_initialized(connection_id)
.await;
}
@@ -903,7 +855,6 @@ impl MessageProcessor {
self.outgoing
.disconnect_user_verification_connection(connection_id)
.await;
session_state.mcp_event_streams.clear().await;
if timeout(
CONNECTION_RPC_DRAIN_TIMEOUT,
session_state.rpc_gate.shutdown(),
@@ -976,7 +927,7 @@ impl MessageProcessor {
)
.await?;
if connection_initialized {
self.connection_initialized(connection_id, session.request_attestation())
self.connection_initialized(connection_id)
.await;
}
return Ok(());
@@ -1032,15 +983,6 @@ impl MessageProcessor {
_ => (None, false),
};
let event_stream_ready = match &codex_request {
ClientRequest::McpServerEventStreamStart { params, .. } => Some(
session
.mcp_event_streams
.start(connection_id, params.clone(), self.mcp_processor.clone())
.await?,
),
_ => None,
};
let serialization_scope = codex_request.serialization_scope();
let error_request_id = connection_request_id.clone();
let rpc_gate = Arc::clone(&session.rpc_gate);
@@ -1068,7 +1010,6 @@ impl MessageProcessor {
codex_request,
request_context,
session,
event_stream_ready,
),
))
.await;
@@ -1098,7 +1039,6 @@ impl MessageProcessor {
codex_request: ClientRequest,
request_context: RequestContext,
session: Arc<ConnectionSessionState>,
event_stream_ready: Option<McpEventStreamReady>,
) -> Result<(), JSONRPCErrorError> {
let connection_id = connection_request_id.connection_id;
let app_server_client_name = session.app_server_client_name().map(str::to_string);
@@ -1328,15 +1268,9 @@ impl MessageProcessor {
.await
}
ClientRequest::ThreadUnsubscribe { params, .. } => {
let thread_id = params.thread_id.clone();
let response = self
.thread_processor
self.thread_processor
.thread_unsubscribe(&request_id, params)
.await?;
if let Ok(thread_id) = ThreadId::from_string(&thread_id) {
session.mcp_event_streams.stop_thread(thread_id).await;
}
Ok(response)
.await
}
ClientRequest::ThreadResume { params, .. } => {
self.thread_processor
@@ -1626,52 +1560,9 @@ impl MessageProcessor {
ClientRequest::PluginInstalled { params, .. } => {
self.plugin_processor.plugin_installed(params).await
}
ClientRequest::PluginReconcile { params, .. } => {
self.plugin_processor
.plugin_reconcile(
params,
self.config_processor.clone(),
&self.request_serialization_queues,
)
.await
}
ClientRequest::PluginRead { params, .. } => {
self.plugin_processor.plugin_read(params).await
}
ClientRequest::PluginSkillRead { params, .. } => {
self.plugin_processor.plugin_skill_read(params).await
}
ClientRequest::PluginShareSave { params, .. } => {
self.plugin_processor.plugin_share_save(params).await
}
ClientRequest::PluginShareUpdateTargets { params, .. } => {
self.plugin_processor
.plugin_share_update_targets(params)
.await
}
ClientRequest::PluginShareList { params, .. } => {
self.plugin_processor.plugin_share_list(params).await
}
ClientRequest::PluginShareCheckout { params, .. } => {
self.plugin_processor.plugin_share_checkout(params).await
}
ClientRequest::PluginShareDelete { params, .. } => {
self.plugin_processor.plugin_share_delete(params).await
}
// ChatGPT apps/connectors are not available in aKode.
ClientRequest::AppsRead { .. } => {
Err(method_not_found("ChatGPT apps are not available in aKode"))
}
ClientRequest::AppsList { .. } => Ok(Some(
codex_app_server_protocol::AppsListResponse {
data: Vec::new(),
next_cursor: None,
}
.into(),
)),
ClientRequest::AppsInstalled { .. } => Ok(Some(
codex_app_server_protocol::AppsInstalledResponse { apps: Vec::new() }.into(),
)),
ClientRequest::SkillsConfigWrite { params, .. } => {
self.catalog_processor.skills_config_write(params).await
}
@@ -1796,27 +1687,6 @@ impl MessageProcessor {
.mcp_resource_read(&request_id, params)
.await
}
ClientRequest::McpServerEventStreamStart { params, .. } => {
let ready = event_stream_ready.ok_or_else(|| {
internal_error("MCP event subscription was not reserved before startup")
})?;
session
.mcp_event_streams
.wait_for_activation(&params.subscription_id, ready)
.await?;
Ok(Some(
codex_app_server_protocol::McpServerEventStreamStartResponse {}.into(),
))
}
ClientRequest::McpServerEventStreamStop { params, .. } => {
session
.mcp_event_streams
.stop(&params.subscription_id)
.await;
Ok(Some(
codex_app_server_protocol::McpServerEventStreamStopResponse {}.into(),
))
}
ClientRequest::McpServerToolCall { params, .. } => {
self.mcp_processor
.mcp_server_tool_call(&request_id, params)
@@ -1875,16 +1745,6 @@ impl MessageProcessor {
.await
.map(|response| Some(response.into()))
}
ClientRequest::AccountSessionsList { params, .. } => self
.account_processor
.list_account_sessions(params)
.await
.map(|response| Some(ClientResponsePayload::AccountSessionsList(response))),
ClientRequest::AccountSessionsSwitch { params, .. } => self
.account_processor
.switch_account_session(params, &self.thread_processor, &self.turn_admission)
.await
.map(|response| Some(ClientResponsePayload::AccountSessionsSwitch(response))),
ClientRequest::LogoutAccount { .. } => {
self.account_processor
.logout_account(request_id.clone())
@@ -2007,6 +1867,3 @@ mod gateway_oauth_tests;
#[path = "message_processor_thread_lifecycle_tests.rs"]
mod thread_lifecycle_tests;
#[cfg(test)]
#[path = "message_processor_workspace_routing_tests.rs"]
mod workspace_routing_tests;

View File

@@ -332,7 +332,7 @@ async fn disconnected_v2_child_lifecycle(unload_delay_secs: u64, ephemeral: bool
let _: InitializeResponse =
read_response_from(&mut outgoing, owner_id, /*request_id*/ 1).await;
processor
.connection_initialized(owner_id, owner.request_attestation())
.connection_initialized(owner_id)
.await;
send_request(
&processor,
@@ -608,7 +608,7 @@ decision = "prompt-user"
let _: InitializeResponse =
read_response_from(&mut outgoing, id, /*request_id*/ 1).await;
processor
.connection_initialized(id, session.request_attestation())
.connection_initialized(id)
.await;
}
send_request(
@@ -680,7 +680,7 @@ decision = "prompt-user"
let _: InitializeResponse =
read_response_from(&mut outgoing, unrelated_id, /*request_id*/ 1).await;
processor
.connection_initialized(unrelated_id, unrelated.request_attestation())
.connection_initialized(unrelated_id)
.await;
for connection_id in [incompatible_id, unrelated_id] {
processor

View File

@@ -22,7 +22,6 @@ use codex_app_server_protocol::TurnStartParams;
use codex_app_server_protocol::TurnStartResponse;
use codex_app_server_protocol::UserInput;
use codex_arg0::Arg0DispatchPaths;
use codex_config::CloudConfigBundleLoader;
use codex_config::LoaderOverrides;
use codex_core::config::Config;
use codex_core::config::ConfigBuilder;
@@ -248,13 +247,11 @@ pub(super) async fn build_test_processor(
config.codex_home.join("managed_config.toml").to_path_buf(),
),
/*strict_config*/ false,
CloudConfigBundleLoader::default(),
Arg0DispatchPaths::default(),
Arc::new(codex_config::NoopThreadConfigLoader),
);
let outgoing = Arc::new(OutgoingMessageSender::new(outgoing_tx));
let processor = Arc::new(MessageProcessor::new(MessageProcessorArgs {
cloud_skill_provider: None,
outgoing,
arg0_paths: Arg0DispatchPaths::default(),
startup_cwd: Some(config.cwd.to_path_buf()),
@@ -271,7 +268,6 @@ pub(super) async fn build_test_processor(
&auth_manager,
))),
auth_manager,
runtime_auth_slot: None,
installation_id: "11111111-1111-4111-8111-111111111111".to_string(),
code_mode_session_provider: None,
remote_control_handle: None,
@@ -700,7 +696,6 @@ async fn turn_start_jsonrpc_span_parents_core_turn_spans() -> Result<()> {
output_schema: None,
collaboration_mode: None,
multi_agent_mode: None,
cyber_access_program: None,
},
},
Some(remote_trace),

View File

@@ -1,151 +0,0 @@
//! Exercises background routing call sites and explicit account reads through JSON-RPC.
use super::message_processor_tracing_tests::TEST_CONNECTION_ID;
use super::message_processor_tracing_tests::read_response;
use super::*;
use codex_app_server_protocol::GetAccountResponse;
use codex_app_server_protocol::InitializeResponse;
use codex_config::CloudConfigBundleLoader;
use codex_config::LoaderOverrides;
use codex_config::types::AuthCredentialsStoreMode;
use codex_login::AuthKeyringBackendKind;
use pretty_assertions::assert_eq;
use serde_json::json;
use test_case::test_case;
use tokio::sync::mpsc;
#[test_case(None; "signed_out")]
#[test_case(Some("dummy"); "api_key")]
#[tokio::test]
async fn background_routing_call_sites_skip_config(api_key: Option<&str>) -> anyhow::Result<()> {
let home = tempfile::tempdir()?;
if let Some(api_key) = api_key {
codex_login::login_with_api_key(
home.path(),
api_key,
AuthCredentialsStoreMode::File,
AuthKeyringBackendKind::default(),
)?;
}
let config = Arc::new(
codex_core::config::ConfigBuilder::default()
.codex_home(home.path().to_path_buf())
.loader_overrides(LoaderOverrides::without_managed_config_for_tests())
.build()
.await?,
);
let auth_manager = Arc::new(
AuthManager::new(
home.path().to_path_buf(),
/*enable_codex_api_key_env*/ false,
AuthCredentialsStoreMode::File,
/*forced_chatgpt_workspace_id*/ None,
Some(config.chatgpt_base_url.clone()),
AuthKeyringBackendKind::default(),
config.auth_config().auth_route_config,
)
.await,
);
let (loads_tx, mut loads_rx) = mpsc::unbounded_channel();
let loader = CloudConfigBundleLoader::from_getter(move || {
loads_tx.send(()).expect("config-load observer is alive");
async { Ok(None) }
});
let config_manager = ConfigManager::new_for_tests(
home.path().to_path_buf(),
Vec::new(),
LoaderOverrides::without_managed_config_for_tests(),
loader,
);
let (outgoing_tx, mut outgoing_rx) = mpsc::channel(/*buffer*/ 16);
let outgoing = Arc::new(OutgoingMessageSender::new(outgoing_tx));
let processor = Arc::new(MessageProcessor::new(MessageProcessorArgs {
cloud_skill_provider: None,
outgoing,
arg0_paths: Arg0DispatchPaths::default(),
startup_cwd: Some(config.cwd.to_path_buf()),
config,
config_manager,
environment_manager: Arc::new(EnvironmentManager::default_for_tests()),
feedback: CodexFeedback::new(),
log_db: None,
state_db: None,
config_warnings: Vec::new(),
startup_warnings_tx: mpsc::unbounded_channel().0,
session_source: SessionSource::VSCode,
user_verification: Arc::new(crate::user_verification::Service::new(Arc::clone(
&auth_manager,
))),
auth_manager,
runtime_auth_slot: None,
installation_id: "11111111-1111-4111-8111-111111111111".to_string(),
code_mode_session_provider: None,
remote_control_handle: None,
// Isolate routing from unrelated plugin startup configuration loads.
plugin_startup_tasks: None,
}));
// The model catalog has its own legitimate config refresh, outside routing.
processor.models_refresh_worker.shutdown();
// Observe the task scheduled by real processor construction, not the helper.
assert!(
tokio::time::timeout(Duration::from_secs(/*secs*/ 1), loads_rx.recv())
.await
.is_err(),
"startup routing entered configuration loading"
);
let session = Arc::new(ConnectionSessionState::new(
crate::transport::ConnectionOrigin::Stdio,
));
processor
.process_request(
TEST_CONNECTION_ID,
serde_json::from_value(json!({
"id": 1, "method": "initialize", "params": {
"clientInfo": {"name": "workspace-routing-test", "version": "1"}
}
}))?,
&crate::transport::AppServerTransport::Stdio,
Arc::clone(&session),
)
.await;
let _: InitializeResponse = read_response(&mut outgoing_rx, /*request_id*/ 1).await;
// Complete the same post-initialize hook used by the real transports.
processor
.connection_initialized(TEST_CONNECTION_ID, /*request_attestation*/ false)
.await;
assert!(
tokio::time::timeout(Duration::from_secs(/*secs*/ 1), loads_rx.recv())
.await
.is_err(),
"connection initialization routing entered configuration loading"
);
processor
.process_request(
TEST_CONNECTION_ID,
serde_json::from_value(json!({
"id": 2, "method": "account/read", "params": {"refreshToken": false}
}))?,
&crate::transport::AppServerTransport::Stdio,
session,
)
.await;
let response: GetAccountResponse = read_response(&mut outgoing_rx, /*request_id*/ 2).await;
assert_eq!(
response,
GetAccountResponse {
user_id: None,
account: api_key.map(|_| codex_app_server_protocol::Account::ApiKey {}),
requires_openai_auth: true,
workspace_routing: None,
}
);
assert_eq!(
loads_rx.try_recv(),
Ok(()),
"explicit account/read must reload config"
);
processor.shutdown_threads().await;
Ok(())
}

View File

@@ -51,7 +51,6 @@ fn model_from_preset(preset: ModelPreset) -> Model {
})
.collect(),
default_service_tier: preset.default_service_tier,
available_access_programs: preset.available_access_programs.map(Into::into),
is_default: preset.is_default,
}
}

View File

@@ -3,10 +3,7 @@ use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::time::Duration;
use codex_config::CloudConfigBundle;
use codex_config::CloudConfigBundleLoader;
use codex_config::LoaderOverrides;
use codex_config::test_support::CloudConfigBundleFixture;
use codex_core::config::ConfigBuilder;
use codex_core::config::ConfigOverrides;
use codex_feedback::CodexFeedback;
@@ -23,8 +20,6 @@ use codex_utils_absolute_path::AbsolutePathBuf;
use pretty_assertions::assert_eq;
use tempfile::tempdir;
use tokio::sync::Notify;
use tokio::sync::mpsc;
use tokio::sync::oneshot;
use tracing_subscriber::layer::SubscriberExt;
use super::*;
@@ -47,7 +42,6 @@ fn test_thread_manager(
Arc::new(codex_core::ThreadManager::new(
config,
startup,
codex_core::CodexAppsToolsCache::default(),
codex_protocol::protocol::SessionSource::Exec,
Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()),
codex_extension_api::empty_extension_registry(),
@@ -55,7 +49,6 @@ fn test_thread_manager(
codex_core::passthrough_image_store(),
codex_core::ThreadStoreBuilder::from_config(config, /*state_db*/ None).build(),
/*agent_graph_store*/ None,
/*attestation_provider*/ None,
/*external_time_provider*/ None,
))
}
@@ -107,10 +100,6 @@ impl ModelsEndpointClient for TestModelsEndpoint {
true
}
fn uses_codex_backend(&self) -> ModelsEndpointFuture<'_, bool> {
Box::pin(async { false })
}
fn list_models<'a>(
&'a self,
_client_version: &'a str,
@@ -149,7 +138,6 @@ async fn refreshes_immediately_periodically_and_stops_when_dropped() {
LoaderOverrides::with_managed_config_path_for_tests(
codex_home.path().join("managed_config.toml"),
),
CloudConfigBundleLoader::default(),
);
// The TUI forwards its typed --oss selection through the raw CLI overrides too.
let config = Arc::new(
@@ -234,19 +222,15 @@ async fn background_refresh_blocks_invalid_requirements_then_recovers() -> anyho
.load_non_project_config()
.await?,
);
let (checks_tx, mut checks_rx) = mpsc::unbounded_channel();
let loader = CloudConfigBundleLoader::from_getter(move || {
let (reply_tx, reply_rx) = oneshot::channel::<Option<CloudConfigBundle>>();
checks_tx
.send(reply_tx)
.expect("requirements check receiver");
async move { Ok(reply_rx.await.expect("requirements check response")) }
});
// Managed requirements are read from this local file on every refresh.
let requirements_path = home.path().join("requirements.toml");
let config_manager = crate::config_manager::ConfigManager::new_for_tests(
home.path().to_path_buf(),
Vec::new(),
LoaderOverrides::without_managed_config_for_tests(),
loader,
LoaderOverrides {
system_requirements_path: Some(requirements_path.clone()),
..LoaderOverrides::without_managed_config_for_tests()
},
);
let endpoint = TestModelsEndpoint::new();
let models_manager: SharedModelsManager = Arc::new(OpenAiModelsManager::new(
@@ -272,32 +256,42 @@ async fn background_refresh_blocks_invalid_requirements_then_recovers() -> anyho
tracing_subscriber::registry().with(feedback.logger_layer()),
);
let worker = spawn_with_interval(&catalog, Duration::from_millis(/*millis*/ 10));
let blocked_refreshes = || {
String::from_utf8_lossy(
&feedback
.snapshot(/*session_id*/ None)
.log_attachment(/*logs_override*/ None)
.buffer,
)
.matches("model catalog refresh blocked by provider requirements")
.count()
};
tokio::time::timeout(Duration::from_secs(/*secs*/ 10), async {
for expected in 1..=2 {
checks_rx.recv().await.unwrap().send(/*t*/ None).unwrap();
endpoint.wait_for_fetch_count(expected).await;
}
// Let the in-flight request finish, then control each refresh's requirements.
endpoint.release_second_fetch.notify_one();
let mut next_check = checks_rx.recv().await.unwrap();
// Install each requirement before letting the in-flight request finish,
// then wait for a later refresh to be blocked by it.
let mut released = false;
for requirements in [
"model_provider = 'other'",
"model_provider = []",
"[model_providers.gateway]\nexperimental_bearer_token = 'private-provider-token-marker' trailing",
] {
next_check
.send(Some(
CloudConfigBundleFixture::enterprise_requirement(requirements).into_bundle(),
))
.unwrap();
// Reaching the next check proves the previous refresh completed. Keep
// this check blocked while asserting that the previous one did not fetch.
next_check = checks_rx.recv().await.unwrap();
std::fs::write(&requirements_path, requirements).expect("write requirements");
let blocked = blocked_refreshes();
if !released {
endpoint.release_second_fetch.notify_one();
released = true;
}
while blocked_refreshes() <= blocked {
tokio::time::sleep(Duration::from_millis(/*millis*/ 5)).await;
}
assert_eq!(endpoint.fetch_count.load(Ordering::SeqCst), 2);
}
next_check.send(/*t*/ None).unwrap();
std::fs::remove_file(&requirements_path).expect("remove requirements");
endpoint.wait_for_fetch_count(/*expected*/ 3).await;
})
.await?;
@@ -314,34 +308,19 @@ async fn background_refresh_blocks_invalid_requirements_then_recovers() -> anyho
Ok(())
}
/// A transient cloud failure must not pin the fallback catalog after policy recovers.
/// A transient requirements failure must not pin the fallback catalog after policy recovers.
#[tokio::test]
async fn catalog_reload_recovers_after_cloud_failure() -> anyhow::Result<()> {
async fn catalog_reload_recovers_after_requirements_failure() -> anyhow::Result<()> {
let home = tempdir()?;
let failed = Arc::new(std::sync::atomic::AtomicBool::new(false));
let loader_failed = Arc::clone(&failed);
let loader = CloudConfigBundleLoader::from_getter(move || {
let failed = Arc::clone(&loader_failed);
async move {
if failed.load(Ordering::SeqCst) {
Err(codex_config::CloudConfigBundleLoadError::new(
codex_config::CloudConfigBundleLoadErrorCode::RequestFailed,
/*status_code*/ None,
"test cloud timeout",
))
} else {
Ok(Some(
CloudConfigBundleFixture::enterprise_requirement("model_provider = 'ollama'")
.into_bundle(),
))
}
}
});
let requirements_path = home.path().join("requirements.toml");
std::fs::write(&requirements_path, "model_provider = 'ollama'")?;
let manager = crate::config_manager::ConfigManager::new_for_tests(
home.path().to_path_buf(),
Vec::new(),
LoaderOverrides::without_managed_config_for_tests(),
loader,
LoaderOverrides {
system_requirements_path: Some(requirements_path.clone()),
..LoaderOverrides::without_managed_config_for_tests()
},
);
let config = Arc::new(manager.load_non_project_config().await?);
let auth = codex_login::AuthManager::shared_from_config(
@@ -355,11 +334,11 @@ async fn catalog_reload_recovers_after_cloud_failure() -> anyhow::Result<()> {
Arc::clone(&config),
test_thread_manager(&config, /*models_manager*/ None, auth),
));
failed.store(true, Ordering::SeqCst);
std::fs::write(&requirements_path, "[malformed")?;
catalog.invalidate().await;
assert_eq!(catalog.current().await?.0.model_provider_id, "openai");
assert!(catalog.list_models(RefreshStrategy::Offline).await.is_err());
failed.store(false, Ordering::SeqCst);
std::fs::write(&requirements_path, "model_provider = 'ollama'")?;
// Exercise the same online request used by the periodic background worker.
catalog.list_models(RefreshStrategy::Online).await?;
assert_eq!(catalog.current().await?.0.model_provider_id, "ollama");

View File

@@ -101,10 +101,8 @@ pub(crate) fn without_notification_media(notification: ServerNotification) -> Se
| ServerNotification::McpToolCallProgress(_)
| ServerNotification::McpServerOauthLoginCompleted(_)
| ServerNotification::McpServerStatusUpdated(_)
| ServerNotification::McpServerEventStream(_)
| ServerNotification::AccountUpdated(_)
| ServerNotification::AccountRateLimitsUpdated(_)
| ServerNotification::AppListUpdated(_)
| ServerNotification::RemoteControlStatusChanged(_)
| ServerNotification::ExternalAgentConfigImportProgress(_)
| ServerNotification::ExternalAgentConfigImportCompleted(_)
@@ -113,8 +111,6 @@ pub(crate) fn without_notification_media(notification: ServerNotification) -> Se
| ServerNotification::ReasoningSummaryPartAdded(_)
| ServerNotification::ReasoningTextDelta(_)
| ServerNotification::ContextCompacted(_)
| ServerNotification::ModelRerouted(_)
| ServerNotification::ModelVerification(_)
| ServerNotification::AuthRecoveryStarted(_)
| ServerNotification::AuthRecoveryCompleted(_)
| ServerNotification::TurnModerationMetadata(_)

View File

@@ -340,6 +340,7 @@ impl OutgoingMessageSender {
self.request_contexts.lock().await.len()
}
#[cfg(test)]
pub(crate) async fn send_request(
&self,
request: ServerRequestPayload,
@@ -954,13 +955,10 @@ mod tests {
use codex_app_server_protocol::CommandExecutionApprovalDecision;
use codex_app_server_protocol::CommandExecutionRequestApprovalParams;
use codex_app_server_protocol::ConfigWarningNotification;
use codex_app_server_protocol::ContextCompactedNotification;
use codex_app_server_protocol::DynamicToolCallParams;
use codex_app_server_protocol::FileChangeRequestApprovalParams;
use codex_app_server_protocol::GuardianWarningNotification;
use codex_app_server_protocol::ModelRerouteReason;
use codex_app_server_protocol::ModelReroutedNotification;
use codex_app_server_protocol::ModelVerification;
use codex_app_server_protocol::ModelVerificationNotification;
use codex_app_server_protocol::RateLimitSnapshot;
use codex_app_server_protocol::RateLimitWindow;
use codex_app_server_protocol::ServerResponse;
@@ -982,7 +980,6 @@ mod tests {
login_id: Some(Uuid::nil().to_string()),
success: true,
error: None,
onboarding_entrypoint: None,
});
let jsonrpc_notification =
@@ -997,7 +994,6 @@ mod tests {
"loginId": Uuid::nil().to_string(),
"success": true,
"error": null,
"onboardingEntrypoint": null,
},
"emittedAtMs": 1_234,
}),
@@ -1014,7 +1010,6 @@ mod tests {
login_id: Some(Uuid::nil().to_string()),
success: true,
error: None,
onboarding_entrypoint: None,
});
assert_eq!(
@@ -1024,7 +1019,6 @@ mod tests {
"loginId": Uuid::nil().to_string(),
"success": true,
"error": null,
"onboardingEntrypoint": null,
},
}),
serde_json::to_value(notification)
@@ -1086,16 +1080,14 @@ mod tests {
#[test]
fn verify_account_updated_notification_serialization() {
let notification = ServerNotification::AccountUpdated(AccountUpdatedNotification {
auth_mode: Some(AuthMode::Chatgpt),
plan_type: Some(PlanType::SelfServeBusinessProLite),
auth_mode: Some(AuthMode::ApiKey),
});
assert_eq!(
json!({
"method": "account/updated",
"params": {
"authMode": "chatgpt",
"planType": "self_serve_business_prolite"
"authMode": "apikey"
},
}),
serde_json::to_value(notification)
@@ -1148,56 +1140,6 @@ mod tests {
);
}
#[test]
fn verify_model_rerouted_notification_serialization() {
let notification = ServerNotification::ModelRerouted(ModelReroutedNotification {
thread_id: "thread-1".to_string(),
turn_id: "turn-1".to_string(),
from_model: "gpt-5.3-codex".to_string(),
to_model: "gpt-5.2".to_string(),
reason: ModelRerouteReason::HighRiskCyberActivity,
});
assert_eq!(
json!({
"method": "model/rerouted",
"params": {
"threadId": "thread-1",
"turnId": "turn-1",
"fromModel": "gpt-5.3-codex",
"toModel": "gpt-5.2",
"reason": "highRiskCyberActivity",
},
}),
serde_json::to_value(notification)
.expect("ensure the notification serializes correctly"),
"ensure the notification serializes correctly"
);
}
#[test]
fn verify_model_verification_notification_serialization() {
let notification = ServerNotification::ModelVerification(ModelVerificationNotification {
thread_id: "thread-1".to_string(),
turn_id: "turn-1".to_string(),
verifications: vec![ModelVerification::TrustedAccessForCyber],
});
assert_eq!(
json!({
"method": "model/verification",
"params": {
"threadId": "thread-1",
"turnId": "turn-1",
"verifications": ["trustedAccessForCyber"],
},
}),
serde_json::to_value(notification)
.expect("ensure the notification serializes correctly"),
"ensure the notification serializes correctly"
);
}
#[test]
fn verify_turn_moderation_metadata_notification_serialization() {
let notification =
@@ -1442,12 +1384,9 @@ mod tests {
outgoing
.send_server_notification_to_connection_and_wait(
ConnectionId(42),
ServerNotification::ModelRerouted(ModelReroutedNotification {
ServerNotification::ContextCompacted(ContextCompactedNotification {
thread_id: "thread-1".to_string(),
turn_id: "turn-1".to_string(),
from_model: "gpt-5.3-codex".to_string(),
to_model: "gpt-5.2".to_string(),
reason: ModelRerouteReason::HighRiskCyberActivity,
}),
)
.await

View File

@@ -21,8 +21,6 @@ use codex_app_server_protocol::AccountUpdatedNotification;
use codex_app_server_protocol::AdditionalContextEntry;
use codex_app_server_protocol::AdditionalContextKind;
use codex_app_server_protocol::AppSummary;
use codex_app_server_protocol::AppTemplateSummary;
use codex_app_server_protocol::AppTemplateUnavailableReason;
use codex_app_server_protocol::AskForApproval;
use codex_app_server_protocol::AuthMode;
use codex_app_server_protocol::CancelLoginAccountParams;
@@ -78,7 +76,6 @@ use codex_app_server_protocol::ListMcpServerStatusResponse;
use codex_app_server_protocol::LoginAccountParams;
use codex_app_server_protocol::LoginAccountResponse;
use codex_app_server_protocol::LoginApiKeyParams;
use codex_app_server_protocol::LoginAppBrand;
use codex_app_server_protocol::LogoutAccountResponse;
use codex_app_server_protocol::MarketplaceAddParams;
use codex_app_server_protocol::MarketplaceAddResponse;
@@ -114,23 +111,11 @@ use codex_app_server_protocol::PluginInstallResponse;
use codex_app_server_protocol::PluginInstalledParams;
use codex_app_server_protocol::PluginInstalledResponse;
use codex_app_server_protocol::PluginInterface;
use codex_app_server_protocol::PluginListMarketplaceKind;
use codex_app_server_protocol::PluginListParams;
use codex_app_server_protocol::PluginListResponse;
use codex_app_server_protocol::PluginMarketplaceEntry;
use codex_app_server_protocol::PluginReadParams;
use codex_app_server_protocol::PluginReadResponse;
use codex_app_server_protocol::PluginShareCheckoutParams;
use codex_app_server_protocol::PluginShareContext;
use codex_app_server_protocol::PluginShareDeleteParams;
use codex_app_server_protocol::PluginShareDiscoverability;
use codex_app_server_protocol::PluginShareListParams;
use codex_app_server_protocol::PluginSharePrincipal;
use codex_app_server_protocol::PluginSharePrincipalType;
use codex_app_server_protocol::PluginShareSaveParams;
use codex_app_server_protocol::PluginShareUpdateTargetsParams;
use codex_app_server_protocol::PluginSkillReadParams;
use codex_app_server_protocol::PluginSkillReadResponse;
use codex_app_server_protocol::PluginSource;
use codex_app_server_protocol::PluginSummary;
use codex_app_server_protocol::PluginUninstallParams;
@@ -277,9 +262,6 @@ use codex_app_server_protocol::WindowsSandboxSetupMode;
use codex_app_server_protocol::WindowsSandboxSetupStartParams;
use codex_app_server_protocol::WindowsSandboxSetupStartResponse;
use codex_arg0::Arg0DispatchPaths;
use codex_backend_client::Client as BackendClient;
use codex_config::CloudConfigBundleLoadError;
use codex_config::CloudConfigBundleLoadErrorCode;
use codex_config::ConfigLayerStack;
use codex_config::loader::project_trust_key;
use codex_config::types::McpServerTransportConfig;
@@ -322,7 +304,6 @@ use codex_core_plugins::PluginInstallError as CorePluginInstallError;
use codex_core_plugins::PluginInstallRequest;
use codex_core_plugins::PluginReadRequest;
use codex_core_plugins::PluginUninstallError as CorePluginUninstallError;
use codex_core_plugins::loader::load_plugin_apps;
use codex_core_plugins::manifest::PluginManifestInterface;
use codex_core_plugins::marketplace::MarketplaceError;
use codex_core_plugins::marketplace::MarketplacePluginSource;
@@ -332,13 +313,6 @@ use codex_core_plugins::marketplace_add::add_marketplace as add_marketplace_to_c
use codex_core_plugins::marketplace_remove::MarketplaceRemoveError;
use codex_core_plugins::marketplace_remove::MarketplaceRemoveRequest as CoreMarketplaceRemoveRequest;
use codex_core_plugins::marketplace_remove::remove_marketplace;
use codex_core_plugins::remote::RemoteMarketplace;
use codex_core_plugins::remote::RemoteMarketplaceSource;
use codex_core_plugins::remote::RemotePluginCatalogError;
use codex_core_plugins::remote::RemotePluginDetail as RemoteCatalogPluginDetail;
use codex_core_plugins::remote::RemotePluginServiceConfig;
use codex_core_plugins::remote::RemotePluginShareContext as RemoteCatalogPluginShareContext;
use codex_core_plugins::remote::RemotePluginSummary as RemoteCatalogPluginSummary;
use codex_exec_server::EnvironmentManager;
use codex_exec_server::EnvironmentObservedStatus;
use codex_exec_server::LOCAL_ENVIRONMENT_ID;
@@ -352,18 +326,9 @@ use codex_feedback::FeedbackSaveOptions;
use codex_git_utils::git_diff_to_remote;
use codex_git_utils::resolve_root_git_project_for_trust;
use codex_login::AuthManager;
use codex_login::CODEX_OPEN_APP_URL;
use codex_login::CodexAuth;
use codex_login::LoginSuccessPage;
use codex_login::LoginSuccessPageBrand;
use codex_login::ServerOptions as LoginServerOptions;
use codex_login::ShutdownHandle;
use codex_login::complete_device_code_login;
use codex_login::login_with_api_key;
use codex_login::login_with_bedrock_api_key;
use codex_login::oauth_client_id;
use codex_login::request_device_code;
use codex_login::run_login_server;
use codex_mcp::McpRuntimeContext;
use codex_mcp::McpServerStatusSnapshot;
use codex_mcp::McpSnapshotDetail;
@@ -455,7 +420,6 @@ use codex_utils_pty::DEFAULT_OUTPUT_BYTES_CAP;
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::collections::HashSet;
use std::io::Error as IoError;
use std::path::Path;
use std::path::PathBuf;
use std::result::Result;
@@ -498,7 +462,6 @@ mod fs_processor;
mod git_processor;
mod initialize_processor;
mod marketplace_processor;
mod mcp_event_stream;
mod mcp_processor;
mod memory_status;
mod persisted_resume_settings;
@@ -532,8 +495,6 @@ pub(crate) use fs_processor::FsRequestProcessor;
pub(crate) use git_processor::GitRequestProcessor;
pub(crate) use initialize_processor::InitializeRequestProcessor;
pub(crate) use marketplace_processor::MarketplaceRequestProcessor;
pub(crate) use mcp_event_stream::McpEventStreamReady;
pub(crate) use mcp_event_stream::McpEventStreams;
pub(crate) use mcp_processor::McpRequestProcessor;
pub(crate) use plugins::PluginRequestProcessor;
pub(crate) use process_exec_processor::ProcessExecRequestProcessor;
@@ -551,7 +512,6 @@ use crate::error_code::internal_error;
use crate::error_code::invalid_request;
use crate::filters::compute_source_filters;
use crate::filters::source_kind_matches;
use crate::thread_state::ConnectionCapabilities;
use crate::thread_state::PendingThreadUnloads;
use crate::thread_state::ThreadListenerCommand;
use crate::thread_state::ThreadState;

View File

@@ -4,73 +4,20 @@ use super::bedrock_auth::prepare_bedrock_provider;
use super::config_processor::map_error as map_config_error;
use super::*;
use crate::auth_mode::auth_mode_to_api;
use crate::external_auth::ExternalAuthBridge;
use crate::model_catalog::ModelCatalog;
use crate::outgoing_message::AccountNotification;
use codex_app_server_protocol::DesktopOnboardingEntrypoint;
use codex_login::LoginOnboardingEntrypoint;
use codex_login::login_with_bedrock_access_keys;
use codex_mcp::ema_auth_scope;
use codex_model_provider::is_supported_amazon_bedrock_region;
use codex_otel::auth_storage::AuthStorageOriginator;
use codex_rmcp_client::EnterpriseOAuthCredentialGuard;
mod account_read;
mod bedrock_gov_cloud;
mod bedrock_setup;
mod enterprise_login;
mod gateway_oauth;
mod gcp_setup;
mod security_setup;
mod workspace_routing;
mod workspace_switching;
pub(super) use enterprise_login::EnterpriseLoginCompletion;
pub(super) use enterprise_login::EnterpriseLoginTarget;
pub(crate) use gcp_setup::handle_gcp_setup;
// Duration before a browser ChatGPT login attempt is abandoned.
const LOGIN_CHATGPT_TIMEOUT: Duration = Duration::from_secs(10 * 60);
// Packaged clients use this together with the OAuth client ID override for staging login.
const LOGIN_ISSUER_OVERRIDE_ENV_VAR: &str = "CODEX_APP_SERVER_LOGIN_ISSUER";
// The development success-page redirect remains debug-only.
#[cfg(debug_assertions)]
const LOGIN_OPEN_APP_URL_OVERRIDE_ENV_VAR: &str = "CODEX_APP_SERVER_DEV_OPEN_APP_URL";
enum ActiveLogin {
Browser {
shutdown_handle: ShutdownHandle,
login_id: Uuid,
},
DeviceCode {
cancel: CancellationToken,
login_id: Uuid,
},
}
impl ActiveLogin {
fn login_id(&self) -> Uuid {
match self {
ActiveLogin::Browser { login_id, .. } | ActiveLogin::DeviceCode { login_id, .. } => {
*login_id
}
}
}
fn cancel(&self) {
match self {
ActiveLogin::Browser {
shutdown_handle, ..
} => shutdown_handle.shutdown(),
ActiveLogin::DeviceCode { cancel, .. } => cancel.cancel(),
}
}
}
#[derive(Clone, Copy, Debug)]
enum CancelLoginError {
NotFound,
}
enum RefreshTokenRequestOutcome {
NotAttemptedOrSucceeded,
FailedTransiently,
@@ -91,12 +38,6 @@ enum BedrockLoginCredentials {
},
}
impl Drop for ActiveLogin {
fn drop(&mut self) {
self.cancel();
}
}
#[derive(Clone)]
pub(crate) struct AccountRequestProcessor {
auth_manager: Arc<AuthManager>,
@@ -105,15 +46,10 @@ pub(crate) struct AccountRequestProcessor {
config: Arc<Config>,
config_manager: ConfigManager,
model_catalog: Arc<ModelCatalog>,
active_login: Arc<Mutex<Option<ActiveLogin>>>,
workspace_routing: Arc<Mutex<Option<workspace_routing::CachedWorkspaceRouting>>>,
workspace_routing_fetches: Arc<Mutex<workspace_routing::WorkspaceRoutingFetches>>,
workspace_routing_shutdown: CancellationToken,
gateway_login: Arc<std::sync::Mutex<Option<gateway_oauth::ActiveGatewayLogin>>>,
gateway_clients:
Arc<std::sync::Mutex<HashMap<String, Arc<codex_model_provider::GatewayAuthManager>>>>,
_gateway_notifications: Arc<tokio_util::task::AbortOnDropHandle<()>>,
pub(super) enterprise_login: Arc<enterprise_login::EnterpriseLoginState>,
}
impl AccountRequestProcessor {
@@ -130,12 +66,7 @@ impl AccountRequestProcessor {
config_manager.clone(),
Arc::clone(&outgoing),
);
let enterprise_login = Arc::new(enterprise_login::EnterpriseLoginState::new(
Arc::clone(&auth_manager),
Arc::clone(&thread_manager),
config_manager.clone(),
));
let processor = Arc::new(Self {
Arc::new(Self {
_gateway_notifications: Arc::new(gateway_notifications),
auth_manager,
thread_manager,
@@ -143,25 +74,9 @@ impl AccountRequestProcessor {
config,
config_manager,
model_catalog,
active_login: Arc::new(Mutex::new(None)),
gateway_login: Arc::new(std::sync::Mutex::new(/*t*/ None)),
gateway_clients: Arc::new(std::sync::Mutex::new(HashMap::new())),
workspace_routing: Arc::new(Mutex::new(None)),
workspace_routing_fetches: Arc::new(Mutex::new(HashMap::new())),
workspace_routing_shutdown: CancellationToken::new(),
enterprise_login,
});
let resolver: Arc<dyn codex_login::WorkspaceRoutingResolver> = processor.clone();
processor
.auth_manager
.set_workspace_routing_resolver(Arc::downgrade(&resolver));
let startup = processor.clone();
tokio::spawn(async move {
let _ = startup
.read_account_for_background_workspace_routing()
.await;
});
processor
})
}
pub(crate) async fn login_account(
@@ -199,15 +114,9 @@ impl AccountRequestProcessor {
pub(crate) async fn cancel_active_login(&self) {
self.cancel_gateway_login();
self.enterprise_login.cancel(/*login_id*/ None).await;
let mut guard = self.active_login.lock().await;
if let Some(active_login) = guard.take() {
drop(active_login);
}
}
pub(crate) fn clear_external_auth(&self) {
self.workspace_routing_shutdown.cancel();
self.auth_manager.clear_external_auth();
}
@@ -218,7 +127,6 @@ impl AccountRequestProcessor {
.as_ref()
.map(CodexAuth::api_auth_mode)
.map(auth_mode_to_api),
plan_type: auth.as_ref().and_then(CodexAuth::account_plan_type),
}
}
@@ -236,55 +144,15 @@ impl AccountRequestProcessor {
}
}
async fn maybe_refresh_plugin_caches_for_current_config(
/// Account changes alter app routing, so loaded plugin capabilities must be rebuilt.
fn refresh_plugin_caches_after_account_change(
config_manager: &ConfigManager,
thread_manager: &Arc<ThreadManager>,
auth: Option<CodexAuth>,
) {
thread_manager
.plugins_manager()
.clear_recommended_plugins_cache();
match config_manager
.load_latest_config(/*fallback_cwd*/ None)
.await
{
Ok(config) => {
let runtime_auth = thread_manager.runtime_auth_for_config(&config);
Self::spawn_effective_plugins_changed_task(
Arc::clone(thread_manager),
config_manager.clone(),
);
let plugins_config = config.plugins_config_input();
let refresh_thread_manager = Arc::clone(thread_manager);
let refresh_config_manager = config_manager.clone();
let on_effective_plugins_changed: Arc<
dyn Fn(codex_core_plugins::EffectivePluginsChange) + Send + Sync,
> = Arc::new(move |_change| {
Self::spawn_effective_plugins_changed_task(
Arc::clone(&refresh_thread_manager),
refresh_config_manager.clone(),
);
});
// aKode: no curated marketplace sync after account changes.
if let Err(err) = runtime_auth {
warn!("failed to initialize runtime auth for remote plugin refresh: {err}");
return;
}
thread_manager
.plugins_manager()
.maybe_start_remote_plugin_caches_refresh(
&plugins_config,
auth,
Some(on_effective_plugins_changed),
);
}
Err(err) => {
warn!(
"failed to reload config after account changed, skipping remote installed plugins cache refresh: {err}"
);
}
}
Self::spawn_effective_plugins_changed_task(
Arc::clone(thread_manager),
config_manager.clone(),
);
}
fn spawn_effective_plugins_changed_task(
@@ -305,53 +173,11 @@ impl AccountRequestProcessor {
request_id: ConnectionRequestId,
params: LoginAccountParams,
) -> Result<(), JSONRPCErrorError> {
if self.auth_manager.is_workload_identity_selected() {
return Err(self.configured_auth_owned_by_host_error());
}
self.enterprise_login.cancel(/*login_id*/ None).await;
match params {
LoginAccountParams::ApiKey { api_key } => {
self.login_api_key_v2(request_id, LoginApiKeyParams { api_key })
.await;
}
LoginAccountParams::Chatgpt {
app_brand,
codex_streamlined_login,
use_hosted_login_success_page,
} => {
let login_success_page = if use_hosted_login_success_page {
let app_brand = match app_brand.unwrap_or_default() {
LoginAppBrand::Codex => LoginSuccessPageBrand::Codex,
LoginAppBrand::Chatgpt => LoginSuccessPageBrand::Chatgpt,
};
LoginSuccessPage::Hosted {
url: CODEX_OPEN_APP_URL.parse().map_err(|err| {
internal_error(format!("invalid Codex open app URL: {err}"))
})?,
app_brand,
}
} else {
LoginSuccessPage::default()
};
self.login_chatgpt_v2(request_id, codex_streamlined_login, login_success_page)
.await;
}
LoginAccountParams::ChatgptDeviceCode => {
self.login_chatgpt_device_code_v2(request_id).await;
}
LoginAccountParams::ChatgptAuthTokens {
access_token,
chatgpt_account_id,
chatgpt_plan_type,
} => {
self.login_chatgpt_auth_tokens(
request_id,
access_token,
chatgpt_account_id,
chatgpt_plan_type,
)
.await;
}
LoginAccountParams::AmazonBedrock { api_key, region } => {
self.login_amazon_bedrock_v2(
request_id,
@@ -381,28 +207,10 @@ impl AccountRequestProcessor {
Ok(())
}
fn external_auth_active_error(&self) -> JSONRPCErrorError {
invalid_request(
"External auth is active. Use account/login/start (chatgptAuthTokens) to update it or account/logout to clear it.",
)
}
fn configured_auth_owned_by_host_error(&self) -> JSONRPCErrorError {
invalid_request(
"Configured external authentication is owned by the app-server host and cannot be changed through account RPCs.",
)
}
fn ensure_provider_login_allowed(
&self,
provider: CloudLoginProvider,
) -> Result<(), JSONRPCErrorError> {
if self.auth_manager.is_workload_identity_selected() {
return Err(self.configured_auth_owned_by_host_error());
}
if self.auth_manager.is_external_chatgpt_auth_active() {
return Err(self.external_auth_active_error());
}
if !self
.auth_manager
.is_login_method_allowed(ForcedLoginMethod::Api)
@@ -412,7 +220,7 @@ impl AccountRequestProcessor {
CloudLoginProvider::Gcp => "Google Cloud setup",
};
return Err(invalid_request(format!(
"{operation} is disabled. Use ChatGPT login instead."
"{operation} is disabled by the configured login policy."
)));
}
Ok(())
@@ -422,27 +230,15 @@ impl AccountRequestProcessor {
&self,
params: &LoginApiKeyParams,
) -> std::result::Result<(), JSONRPCErrorError> {
if self.auth_manager.is_external_chatgpt_auth_active() {
return Err(self.external_auth_active_error());
}
if !self
.auth_manager
.is_login_method_allowed(ForcedLoginMethod::Api)
{
return Err(invalid_request(
"API key login is disabled. Use ChatGPT login instead.",
"API key login is disabled by the configured login policy.",
));
}
// Cancel any active login attempt.
{
let mut guard = self.active_login.lock().await;
if let Some(active) = guard.take() {
drop(active);
}
}
match login_with_api_key(
&self.config.codex_home,
&params.api_key,
@@ -451,7 +247,6 @@ impl AccountRequestProcessor {
) {
Ok(()) => {
self.auth_manager.reload().await;
self.config_manager.clear_chatgpt_config_loader();
Ok(())
}
Err(err) => Err(internal_error(format!("failed to save api key: {err}"))),
@@ -553,7 +348,6 @@ impl AccountRequestProcessor {
}
.map_err(|err| internal_error(format!("failed to save Amazon Bedrock auth: {err}")))?;
self.auth_manager.reload().await;
self.config_manager.clear_chatgpt_config_loader();
Ok(LoginAccountResponse::AmazonBedrock {})
}
.await;
@@ -569,340 +363,17 @@ impl AccountRequestProcessor {
}
}
// Build options for a ChatGPT login attempt; performs validation.
async fn login_chatgpt_common(
&self,
codex_streamlined_login: bool,
login_success_page: LoginSuccessPage,
) -> std::result::Result<LoginServerOptions, JSONRPCErrorError> {
let config = self.config.as_ref();
if self.auth_manager.is_external_chatgpt_auth_active() {
return Err(self.external_auth_active_error());
}
if !self
.auth_manager
.is_login_method_allowed(ForcedLoginMethod::Chatgpt)
{
return Err(invalid_request(
"ChatGPT login is disabled. Use API key login instead.",
));
}
let mut opts = LoginServerOptions {
open_browser: false,
codex_streamlined_login,
login_success_page,
..LoginServerOptions::new(
config.codex_home.to_path_buf(),
oauth_client_id(),
self.auth_manager.effective_chatgpt_workspaces(),
config.cli_auth_credentials_store_mode,
config.auth_keyring_backend_kind(),
config.auth_route_config(),
)
};
if let Ok(issuer) = std::env::var(LOGIN_ISSUER_OVERRIDE_ENV_VAR)
&& !issuer.trim().is_empty()
{
opts.issuer = issuer;
}
#[cfg(debug_assertions)]
if let LoginSuccessPage::Hosted { url, .. } = &mut opts.login_success_page
&& let Ok(open_app_url) = std::env::var(LOGIN_OPEN_APP_URL_OVERRIDE_ENV_VAR)
&& !open_app_url.trim().is_empty()
{
*url = open_app_url
.parse()
.map_err(|err| internal_error(format!("invalid Codex open app URL: {err}")))?;
}
Ok(opts)
}
fn login_chatgpt_device_code_start_error(err: IoError) -> JSONRPCErrorError {
let is_not_found = err.kind() == std::io::ErrorKind::NotFound;
if is_not_found {
invalid_request(err.to_string())
} else {
internal_error(format!("failed to request device code: {err}"))
}
}
async fn login_chatgpt_v2(
&self,
request_id: ConnectionRequestId,
codex_streamlined_login: bool,
login_success_page: LoginSuccessPage,
) {
let result = self
.login_chatgpt_response(codex_streamlined_login, login_success_page)
.await;
self.outgoing.send_result(request_id, result).await;
}
async fn login_chatgpt_response(
&self,
codex_streamlined_login: bool,
login_success_page: LoginSuccessPage,
) -> Result<LoginAccountResponse, JSONRPCErrorError> {
let opts = self
.login_chatgpt_common(codex_streamlined_login, login_success_page)
.await?;
let (login_id, auth_url) = self.start_browser_login(opts, /*pause*/ None).await?;
Ok(LoginAccountResponse::Chatgpt { login_id, auth_url })
}
async fn start_browser_login(
&self,
opts: LoginServerOptions,
pause: Option<crate::turn_admission::TurnAdmissionPause>,
) -> Result<(String, String), JSONRPCErrorError> {
let server = run_login_server(opts)
.map_err(|err| internal_error(format!("failed to start login server: {err}")))?;
let login_id = Uuid::new_v4();
let shutdown_handle = server.cancel_handle();
// Replace active login if present.
{
let mut guard = self.active_login.lock().await;
if let Some(existing) = guard.take() {
drop(existing);
}
*guard = Some(ActiveLogin::Browser {
shutdown_handle: shutdown_handle.clone(),
login_id,
});
}
let processor = self.clone();
let active_login = self.active_login.clone();
let auth_url = server.auth_url.clone();
let task = async move {
// Workspace credentials may change in the callback. Resume turns after caches and clients are updated.
let _pause = pause;
let (success, error_msg, onboarding_entrypoint) = match tokio::time::timeout(
LOGIN_CHATGPT_TIMEOUT,
server.block_until_done_with_callback_result(),
)
.await
{
Ok(Ok(result)) => (
true,
None,
result
.onboarding_entrypoint
.map(|LoginOnboardingEntrypoint::LifeSciences| {
DesktopOnboardingEntrypoint::LifeSciences
}),
),
Ok(Err(err)) => (false, Some(format!("Login server error: {err}")), None),
Err(_elapsed) => {
shutdown_handle.shutdown();
(false, Some("Login timed out".to_string()), None)
}
};
processor
.send_chatgpt_login_completion_notifications(AccountLoginCompletedNotification {
login_id: Some(login_id.to_string()),
success,
error: error_msg,
onboarding_entrypoint,
})
.await;
// Clear the active login if it matches this attempt. It may have been replaced or cancelled.
let mut guard = active_login.lock().await;
if guard.as_ref().map(ActiveLogin::login_id) == Some(login_id) {
*guard = None;
}
};
tokio::spawn(AuthStorageOriginator::current().scope(task));
Ok((login_id.to_string(), auth_url))
}
async fn login_chatgpt_device_code_v2(&self, request_id: ConnectionRequestId) {
let result = self.login_chatgpt_device_code_response().await;
self.outgoing.send_result(request_id, result).await;
}
async fn login_chatgpt_device_code_response(
&self,
) -> Result<LoginAccountResponse, JSONRPCErrorError> {
let opts = self
.login_chatgpt_common(
/*codex_streamlined_login*/ false,
LoginSuccessPage::default(),
)
.await?;
let device_code = request_device_code(&opts)
.await
.map_err(Self::login_chatgpt_device_code_start_error)?;
let login_id = Uuid::new_v4();
let cancel = CancellationToken::new();
{
let mut guard = self.active_login.lock().await;
if let Some(existing) = guard.take() {
drop(existing);
}
*guard = Some(ActiveLogin::DeviceCode {
cancel: cancel.clone(),
login_id,
});
}
let verification_url = device_code.verification_url.clone();
let user_code = device_code.user_code.clone();
let processor = self.clone();
let active_login = self.active_login.clone();
let task = async move {
let (success, error_msg) = tokio::select! {
_ = cancel.cancelled() => {
(false, Some("Login was not completed".to_string()))
}
r = complete_device_code_login(opts, device_code) => {
match r {
Ok(()) => (true, None),
Err(err) => (false, Some(err.to_string())),
}
}
};
processor
.send_chatgpt_login_completion_notifications(AccountLoginCompletedNotification {
login_id: Some(login_id.to_string()),
success,
error: error_msg,
onboarding_entrypoint: None,
})
.await;
let mut guard = active_login.lock().await;
if guard.as_ref().map(ActiveLogin::login_id) == Some(login_id) {
*guard = None;
}
};
tokio::spawn(AuthStorageOriginator::current().scope(task));
Ok(LoginAccountResponse::ChatgptDeviceCode {
login_id: login_id.to_string(),
verification_url,
user_code,
})
}
async fn cancel_login_chatgpt_common(
&self,
login_id: Uuid,
) -> std::result::Result<(), CancelLoginError> {
let mut guard = self.active_login.lock().await;
if guard.as_ref().map(ActiveLogin::login_id) == Some(login_id) {
if let Some(active) = guard.take() {
drop(active);
}
Ok(())
} else {
Err(CancelLoginError::NotFound)
}
}
async fn cancel_login_response(
&self,
params: CancelLoginAccountParams,
) -> Result<CancelLoginAccountResponse, JSONRPCErrorError> {
let login_id = params.login_id;
let uuid = Uuid::parse_str(&login_id)
Uuid::parse_str(&login_id)
.map_err(|_| invalid_request(format!("invalid login id: {login_id}")))?;
if self.enterprise_login.cancel(Some(&login_id)).await {
return Ok(CancelLoginAccountResponse {
status: CancelLoginAccountStatus::Canceled,
});
}
let status = match self.cancel_login_chatgpt_common(uuid).await {
Ok(()) => CancelLoginAccountStatus::Canceled,
Err(CancelLoginError::NotFound) => CancelLoginAccountStatus::NotFound,
};
Ok(CancelLoginAccountResponse { status })
}
async fn login_chatgpt_auth_tokens(
&self,
request_id: ConnectionRequestId,
access_token: String,
chatgpt_account_id: String,
chatgpt_plan_type: Option<String>,
) {
let result = self
.login_chatgpt_auth_tokens_response(access_token, chatgpt_account_id, chatgpt_plan_type)
.await;
let logged_in = result.is_ok();
if logged_in {
self.model_catalog.invalidate().await;
}
self.outgoing.send_result(request_id, result).await;
if logged_in {
self.send_login_success_notifications(/*login_id*/ None)
.await;
}
}
async fn login_chatgpt_auth_tokens_response(
&self,
access_token: String,
chatgpt_account_id: String,
chatgpt_plan_type: Option<String>,
) -> Result<LoginAccountResponse, JSONRPCErrorError> {
if !self
.auth_manager
.is_login_method_allowed(ForcedLoginMethod::Chatgpt)
{
return Err(invalid_request(
"External ChatGPT auth is disabled. Use API key login instead.",
));
}
// Cancel any active login attempt to avoid persisting managed auth state.
{
let mut guard = self.active_login.lock().await;
if let Some(active) = guard.take() {
drop(active);
}
}
if let Some(expected_workspaces) = self.auth_manager.effective_chatgpt_workspaces()
&& !expected_workspaces.contains(&chatgpt_account_id)
{
return Err(invalid_request(format!(
"External auth must use one of workspace(s) {expected_workspaces:?}, but received {chatgpt_account_id:?}.",
)));
}
let auth = CodexAuth::from_external_chatgpt_tokens(
&access_token,
&chatgpt_account_id,
chatgpt_plan_type.as_deref(),
)
.map_err(|err| internal_error(format!("failed to set external auth: {err}")))?;
self.auth_manager
.set_external_auth(Arc::new(ExternalAuthBridge::new(
Arc::clone(&self.outgoing),
auth,
)))
.await
.map_err(|err| internal_error(format!("failed to set external auth: {err}")))?;
self.config_manager
.update_managed_config_loader(self.auth_manager.clone(), &self.config);
self.config_manager
.sync_default_client_residency_requirement()
.await;
Ok(LoginAccountResponse::ChatgptAuthTokens {})
// No account login flow is cancellable by id.
Ok(CancelLoginAccountResponse {
status: CancelLoginAccountStatus::NotFound,
})
}
async fn send_login_success_notifications(&self, login_id: Option<Uuid>) {
@@ -911,7 +382,6 @@ impl AccountRequestProcessor {
login_id: login_id.map(|id| id.to_string()),
success: true,
error: None,
onboarding_entrypoint: None,
})
.await;
}
@@ -923,18 +393,16 @@ impl AccountRequestProcessor {
let auth_changes = self.auth_manager.auth_change_state_receiver();
let owner_generation = auth_changes.borrow().owner_generation;
if payload.success
&& let Err(error) = self.read_account(/*request*/ None).await
&& let Err(error) = self.read_account().await
{
payload.success = false;
payload.error = Some(error.to_string());
}
if payload.success && auth_changes.borrow().owner_generation == owner_generation {
Self::maybe_refresh_plugin_caches_for_current_config(
Self::refresh_plugin_caches_after_account_change(
&self.config_manager,
&self.thread_manager,
self.auth_manager.auth_cached(),
)
.await;
);
}
let success = payload.success;
@@ -960,35 +428,7 @@ impl AccountRequestProcessor {
}
}
async fn send_chatgpt_login_completion_notifications(
&self,
mut payload_v2: AccountLoginCompletedNotification,
) {
if payload_v2.success {
self.auth_manager.reload().await;
let auth_changes = self.auth_manager.auth_change_state_receiver();
let owner_generation = auth_changes.borrow().owner_generation;
self.thread_manager.invalidate_mcp_runtimes().await;
self.config_manager
.update_managed_config_loader(self.auth_manager.clone(), &self.config);
self.config_manager
.sync_default_client_residency_requirement()
.await;
if auth_changes.borrow().owner_generation != owner_generation {
payload_v2.success = false;
payload_v2.error = Some("account changed before sign-in completed".into());
}
}
if payload_v2.success {
self.model_catalog.invalidate().await;
}
self.send_account_login_notifications(payload_v2).await;
}
async fn logout_common(&self) -> std::result::Result<Option<AuthMode>, JSONRPCErrorError> {
if self.auth_manager.is_workload_identity_selected() {
return Err(self.configured_auth_owned_by_host_error());
}
self.cancel_active_login().await;
let config =
logout_configured_account(&self.config_manager, &self.auth_manager, &self.config)
@@ -997,14 +437,11 @@ impl AccountRequestProcessor {
clear_account_configuration(&self.config_manager, &config).await?;
self.model_catalog.invalidate().await;
*self.workspace_routing.lock().await = None;
Self::maybe_refresh_plugin_caches_for_current_config(
Self::refresh_plugin_caches_after_account_change(
&self.config_manager,
&self.thread_manager,
self.auth_manager.auth_cached(),
)
.await;
);
// Reflect the current auth method after logout (likely None).
Ok(self
@@ -1017,15 +454,11 @@ impl AccountRequestProcessor {
async fn logout_v2(&self, request_id: ConnectionRequestId) -> Result<(), JSONRPCErrorError> {
let result = self.logout_common().await;
let account_updated =
result
.as_ref()
.ok()
.cloned()
.map(|auth_mode| AccountUpdatedNotification {
auth_mode,
plan_type: None,
});
let account_updated = result
.as_ref()
.ok()
.cloned()
.map(|auth_mode| AccountUpdatedNotification { auth_mode });
self.outgoing
.send_result(request_id, result.map(|_| LogoutAccountResponse {}))
.await;
@@ -1039,9 +472,6 @@ impl AccountRequestProcessor {
}
async fn refresh_token_if_requested(&self, do_refresh: bool) -> RefreshTokenRequestOutcome {
if self.auth_manager.is_external_chatgpt_auth_active() {
return RefreshTokenRequestOutcome::NotAttemptedOrSucceeded;
}
if do_refresh && let Err(err) = self.auth_manager.refresh_token().await {
let failed_reason = err.failed_reason();
if failed_reason.is_none() {
@@ -1085,31 +515,24 @@ impl AccountRequestProcessor {
let permanent_refresh_failure =
self.auth_manager.refresh_failure_for_auth(&auth).is_some();
let auth_mode = auth_mode_to_api(auth.api_auth_mode());
let (reported_auth_method, token_opt) =
if self.auth_manager.is_workload_identity_selected()
|| matches!(
auth,
CodexAuth::Headers(_)
| CodexAuth::AgentIdentity(_)
| CodexAuth::PersonalAccessToken(_)
)
|| include_token && permanent_refresh_failure
{
// Host-owned and metadata-bearing credentials are never exported.
(Some(auth_mode), None)
} else {
match auth.get_token() {
Ok(token) if !token.is_empty() => {
let tok = if include_token { Some(token) } else { None };
(Some(auth_mode), tok)
}
Ok(_) => (None, None),
Err(err) => {
tracing::warn!("failed to get token for auth status: {err}");
(None, None)
}
let (reported_auth_method, token_opt) = if matches!(auth, CodexAuth::Headers(_))
|| include_token && permanent_refresh_failure
{
// Host-owned and metadata-bearing credentials are never exported.
(Some(auth_mode), None)
} else {
match auth.get_token() {
Ok(token) if !token.is_empty() => {
let tok = if include_token { Some(token) } else { None };
(Some(auth_mode), tok)
}
};
Ok(_) => (None, None),
Err(err) => {
tracing::warn!("failed to get token for auth status: {err}");
(None, None)
}
}
};
GetAuthStatusResponse {
auth_method: reported_auth_method,
auth_token: token_opt,
@@ -1134,60 +557,23 @@ pub(crate) async fn logout_configured_account(
auth_manager: &Arc<AuthManager>,
fallback_config: &Config,
) -> Result<Config, JSONRPCErrorError> {
// Another process may have changed the persisted workspace. Reload both
// Another process may have changed the persisted credentials. Reload both
// account authority and its policy before selecting a grant to remove.
auth_manager
.reload_with_cached_auth()
.await
.map_err(|err| internal_error(format!("logout failed: {err}")))?;
config_manager.update_managed_config_loader(Arc::clone(auth_manager), fallback_config);
let config = config_manager
.load_latest_config(/*fallback_cwd*/ None)
.await;
let scope = ema_auth_scope(auth_manager.auth_cached().as_ref());
let enterprise_policy_failed = scope.is_some() && config.is_err();
// Startup policy may belong to another workspace. Never use that fallback
// to select a credential; a policy failure must not block primary logout.
let enterprise_grant = config.as_ref().ok().and_then(|config| {
scope
.as_ref()
.zip(config.mcp_enterprise_managed_auth.as_ref())
.map(|(scope, profile)| {
(
profile.idp.credential_name(scope),
profile.idp.issuer.clone(),
config.auth_keyring_backend_kind(),
)
})
});
let config = config.unwrap_or_else(|_| fallback_config.clone());
// Retain the credential lock through primary logout. Otherwise a second
// process can commit after deletion but before the account is removed.
let enterprise_guard =
if let Some((credential_name, issuer, keyring_backend)) = enterprise_grant {
EnterpriseOAuthCredentialGuard::acquire(&credential_name, &issuer, keyring_backend)
.await
.map(Some)
} else {
Ok(None)
};
let cleanup_failed = match &enterprise_guard {
Ok(Some(guard)) => guard.delete_tokens().is_err(),
Ok(None) => false,
Err(_) => true,
};
if enterprise_policy_failed || cleanup_failed {
tracing::warn!("Failed to remove enterprise authorization; continuing account logout");
}
match auth_manager.logout_with_revoke().await {
match auth_manager.logout().await {
Ok(_) => {}
Err(err) => {
return Err(internal_error(format!("logout failed: {err}")));
}
}
drop(enterprise_guard);
Ok(config)
}
@@ -1196,7 +582,6 @@ pub(crate) async fn clear_account_configuration(
config_manager: &ConfigManager,
config: &Config,
) -> Result<(), JSONRPCErrorError> {
config_manager.clear_chatgpt_config_loader();
if config.model_provider.is_amazon_bedrock() {
clear_user_model_provider_if_bedrock(config_manager, config).await?;
}

View File

@@ -0,0 +1,33 @@
//! Reads the provider-reported account for the current configuration and credentials.
use super::*;
use codex_model_provider::ProviderAccountError;
use codex_model_provider::ProviderAccountState;
impl AccountRequestProcessor {
pub(crate) async fn get_account(
&self,
_params: GetAccountParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
let account_state = self
.read_account()
.await
.map_err(|error| invalid_request(error.to_string()))?;
Ok(Some(
GetAccountResponse {
account: account_state.account.map(Account::from),
requires_openai_auth: account_state.requires_openai_auth,
}
.into(),
))
}
pub(super) async fn read_account(&self) -> Result<ProviderAccountState, ProviderAccountError> {
let config = self.load_latest_config().await;
create_model_provider(
config.model_provider.clone(),
Some(self.auth_manager.clone()),
)
.account_state()
}
}

View File

@@ -1,313 +0,0 @@
//! Owns one explicit enterprise sign-in attempt for a configured MCP server.
//! Start, replacement, cancellation, and local commit admission all pass through this state.
//! The credential store separately fences logins invalidated by another process.
use super::*;
use anyhow::Context;
use codex_config::McpEmaRegistration;
use codex_config::types::AuthKeyringBackendKind;
use codex_mcp::ema_auth_scope;
use codex_rmcp_client::EmaErrorDetail;
use codex_rmcp_client::EnterpriseOAuthLoginRequest;
use codex_rmcp_client::perform_enterprise_oauth_login_return_url;
use futures::FutureExt;
use tokio::sync::watch;
pub(crate) struct EnterpriseLoginTarget {
pub(crate) thread_id: String,
pub(crate) server_name: String,
pub(crate) registration: McpEmaRegistration,
}
#[derive(Clone, Copy, Eq, PartialEq)]
pub(crate) enum EnterpriseLoginCompletion {
Pending,
Succeeded,
Failed(EmaErrorDetail),
}
impl EnterpriseLoginCompletion {
pub(crate) fn is_complete(self) -> bool {
matches!(self, Self::Succeeded | Self::Failed(_))
}
}
pub(crate) struct EnterpriseLogin {
pub(crate) login_id: String,
pub(crate) authorization_url: String,
pub(crate) completion: watch::Receiver<EnterpriseLoginCompletion>,
}
pub(crate) struct EnterpriseLoginState {
auth_manager: Arc<AuthManager>,
thread_manager: Arc<ThreadManager>,
config_manager: ConfigManager,
// Cancellation and commit admission use this same lock. A cancelled attempt cannot commit.
active: Mutex<Option<EnterpriseLoginAttempt>>,
// Start and cancel hold this through callback shutdown; the worker never acquires it.
start_gate: Mutex<()>,
// Account changes cancel queued and running setup before waiting for start_gate.
setup_cancel: Mutex<CancellationToken>,
}
struct EnterpriseLoginAttempt {
login_id: String,
cancel: CancellationToken,
completion: watch::Receiver<EnterpriseLoginCompletion>,
}
impl Drop for EnterpriseLoginAttempt {
fn drop(&mut self) {
self.cancel.cancel();
}
}
impl EnterpriseLoginState {
pub(super) fn new(
auth_manager: Arc<AuthManager>,
thread_manager: Arc<ThreadManager>,
config_manager: ConfigManager,
) -> Self {
Self {
auth_manager,
thread_manager,
config_manager,
active: Mutex::new(None),
start_gate: Mutex::new(()),
setup_cancel: Mutex::new(CancellationToken::new()),
}
}
#[expect(
clippy::await_holding_invalid_type,
reason = "serialize start/cancel through callback shutdown; the worker uses a separate state lock"
)]
pub(super) async fn cancel(&self, login_id: Option<&str>) -> bool {
if login_id.is_none() {
let mut setup_cancel = self.setup_cancel.lock().await;
setup_cancel.cancel();
*setup_cancel = CancellationToken::new();
}
let (login_id, mut completion) = {
let active = self.active.lock().await;
if login_id.is_some_and(|id| active.as_ref().is_none_or(|a| a.login_id != id)) {
return false;
}
let Some(attempt) = active.as_ref() else {
return false;
};
attempt.cancel.cancel();
(attempt.login_id.clone(), attempt.completion.clone())
};
// A partial callback request can stall the blocking HTTP worker. Cancellation
// already fences commit; primary logout must not wait indefinitely for I/O.
if tokio::time::timeout(std::time::Duration::from_secs(10), async {
let _start = self.start_gate.lock().await;
completion.wait_for(|state| state.is_complete()).await
})
.await
.is_ok()
{
self.clear(&login_id).await;
}
// Retain a timed-out attempt so a replacement still waits for port cleanup.
true
}
async fn clear(&self, login_id: &str) {
let mut active = self.active.lock().await;
if active
.as_ref()
.is_some_and(|attempt| attempt.login_id == login_id)
{
*active = None;
}
}
async fn configuration_is_current(
&self,
target: &EnterpriseLoginTarget,
keyring_backend: AuthKeyringBackendKind,
) -> bool {
let Ok(thread_id) = ThreadId::from_string(&target.thread_id) else {
return false;
};
let Ok(thread) = self.thread_manager.get_thread(thread_id).await else {
return false;
};
let current = thread.config().await;
let Ok(config) = self
.config_manager
.load_latest_config_with_session_layers(&current.config_layer_stack, &current.cwd)
.await
else {
return false;
};
let config = thread.runtime_mcp_config_and_context(&config).await.0;
let auth = self.auth_manager.auth_cached();
let servers = codex_mcp::effective_mcp_servers(&config, auth.as_ref());
config.xaa_enabled
&& config.auth_keyring_backend_kind == keyring_backend
&& servers.get(&target.server_name).is_some_and(|server| {
server.config().enabled
&& server.config().ema_registration() == Some(&target.registration)
})
}
#[expect(
clippy::await_holding_invalid_type,
reason = "serialize start/cancel through callback shutdown; the worker uses a separate state lock"
)]
pub(crate) async fn start(
self: &Arc<Self>,
request: EnterpriseOAuthLoginRequest<'_>,
scope: codex_config::McpEmaAuthScope,
target: EnterpriseLoginTarget,
) -> Result<EnterpriseLogin, JSONRPCErrorError> {
// MCP requests are not in the account request queue. Serialize start and
// cancellation here; the separate commit gate stays responsive to the worker.
let setup_cancel = self.setup_cancel.lock().await.child_token();
let _start = tokio::select! {
biased;
_ = setup_cancel.cancelled() => return Err(internal_error("enterprise sign-in was cancelled")),
guard = self.start_gate.lock() => guard,
};
let previous = {
let active = self.active.lock().await;
// Keep the cancelled attempt installed until its callback worker closes.
// A cancelled replacement request leaves the next start responsible for waiting.
active.as_ref().map(|attempt| {
attempt.cancel.cancel();
(attempt.login_id.clone(), attempt.completion.clone())
})
};
if let Some((login_id, mut completion)) = previous {
// An abandoned setup request drops its flow and closes this channel.
let _ = tokio::select! {
biased;
_ = setup_cancel.cancelled() => return Err(internal_error("enterprise sign-in was cancelled")),
result = tokio::time::timeout(
std::time::Duration::from_secs(10),
completion.wait_for(|state| state.is_complete()),
) => result.map_err(|_| internal_error("previous enterprise sign-in did not close"))?,
};
self.clear(&login_id).await;
}
let login_generation = self
.auth_manager
.auth_change_state_receiver()
.borrow()
.login_generation;
let account = self
.auth_manager
.auth_cached()
.filter(|auth| ema_auth_scope(Some(auth)).as_ref() == Some(&scope))
.ok_or_else(|| internal_error("Codex account changed during enterprise sign-in"))?;
if !self
.auth_manager
.account_login_is_current(&account)
.await
.unwrap_or(false)
{
return Err(internal_error(
"Codex account changed during enterprise sign-in",
));
}
let keyring_backend = request.keyring_backend_kind;
// Keep commit cancellation under `active`; cancelling the setup epoch must
// not race an already-admitted synchronous credential write.
let cancel = CancellationToken::new();
let login_id = Uuid::new_v4().to_string();
let (completed, completion) = watch::channel(EnterpriseLoginCompletion::Pending);
*self.active.lock().await = Some(EnterpriseLoginAttempt {
login_id: login_id.clone(),
cancel: cancel.clone(),
completion: completion.clone(),
});
let handle = tokio::select! {
biased;
_ = setup_cancel.cancelled() => Err(internal_error("enterprise sign-in was cancelled")),
_ = cancel.cancelled() => Err(internal_error("enterprise sign-in was cancelled")),
result = perform_enterprise_oauth_login_return_url(request) =>
result.map_err(|error| internal_error(
EmaErrorDetail::from_error(
&error.context(EmaErrorDetail::new("failed to start enterprise sign-in")),
).to_string(),
)),
};
let handle = match handle {
Ok(handle) => handle,
Err(error) => {
self.clear(&login_id).await;
completed.send_replace(EnterpriseLoginCompletion::Failed(EmaErrorDetail::new(
"failed to start enterprise sign-in",
)));
return Err(error);
}
};
let callback_closed = handle.callback_closed().shared();
let authorization_url = handle.authorization_url();
let lifecycle = Arc::clone(self);
let completion_id = login_id.clone();
tokio::spawn(async move {
let result = tokio::select! {
biased;
_ = cancel.cancelled() =>
Err(EmaErrorDetail::new("Enterprise sign-in was cancelled.").into()),
result = async {
let credentials = handle.wait().await.context(EmaErrorDetail::new(
"Enterprise sign-in authorization failed.",
))?;
callback_closed.clone().await;
let mut active = credentials.commit_if(|| async {
lifecycle.auth_manager.reload().await;
let eligible = lifecycle.auth_manager.account_login_is_current(&account).await.unwrap_or(false)
&& lifecycle.configuration_is_current(&target, keyring_backend).await;
// Reread persisted account authority after acquiring the credential
// lock, including changes made by another app-server process.
lifecycle.auth_manager.reload().await;
if !eligible || !lifecycle.auth_manager.account_login_is_current(&account).await.unwrap_or(false) {
return None;
}
// Keep cancellation responsive during the async checks above.
// Once admitted, retain this guard through the synchronous write.
let active = lifecycle.active.lock().await;
let current = active.as_ref().is_some_and(|attempt| {
attempt.login_id == completion_id && !attempt.cancel.is_cancelled()
})
&& lifecycle.auth_manager.auth_change_state_receiver().borrow().login_generation == login_generation
&& ema_auth_scope(lifecycle.auth_manager.auth_cached().as_ref()).as_ref() == Some(&scope);
if !current {
return None;
}
// The credential lock is held: revoke cached bearers before replacing
// the grant, and let new threads pin only the committed credential.
lifecycle.config_manager.revoke_mcp_ema();
Some(active)
}).await.context(EmaErrorDetail::new(
"Enterprise sign-in credential commit failed.",
))?;
// A successful commit is no longer cancelable. Clear it while
// still holding the commit gate.
*active = None;
Ok(())
} => result,
};
// The canceled wait future has dropped its listener guard. Also wait
// for the blocking callback worker before allowing a fixed-port retry.
callback_closed.await;
if result.is_err() {
lifecycle.clear(&completion_id).await;
}
completed.send_replace(match result {
Ok(()) => EnterpriseLoginCompletion::Succeeded,
Err(error) => EnterpriseLoginCompletion::Failed(EmaErrorDetail::from_error(&error)),
});
});
Ok(EnterpriseLogin {
login_id,
authorization_url,
completion,
})
}
}

View File

@@ -1,115 +1,10 @@
//! Keep optional security reminders on the app-server's existing runtime identity.
//! Only saved ChatGPT credentials matching the active login may fetch a notice.
//! Security reminders are a ChatGPT account feature; aKode credentials never have one.
use super::*;
use codex_app_server_protocol::AccountSecuritySetupAction;
use codex_app_server_protocol::AccountSecuritySetupNotice;
use codex_app_server_protocol::GetAccountSecuritySetupResponse;
use codex_http_client::ClientRouteClass;
use codex_http_client::RouteAwareClientPool;
use serde::Deserialize;
#[derive(Deserialize)]
struct Response {
notice: Option<Notice>,
}
#[derive(Deserialize)]
struct Notice {
title: String,
description: String,
action: AccountSecuritySetupAction,
}
impl AccountRequestProcessor {
pub(crate) async fn get_account_security_setup(&self) -> GetAccountSecuritySetupResponse {
let notice = tokio::time::timeout(Duration::from_secs(/*secs*/ 3), async {
let config = self.load_latest_config().await;
let (auth, factory) = self.auth_manager.auth_with_http_client_factory().await?;
let source_generation = self
.auth_manager
.auth_change_state_for(&auth)?
.source_generation;
let saved = config
.auth_config()
.load_auth(/*enable_codex_api_key_env*/ false)
.await
.ok()
.flatten()?;
if !matches!(saved, CodexAuth::Chatgpt(_)) || saved.is_fedramp_account() {
return None;
}
if auth.auth_mode() != codex_protocol::auth::AuthMode::Chatgpt
|| saved.get_token().ok()? != auth.get_token().ok()?
{
return None;
}
let account_id = auth.get_account_id()?;
let user_id = auth.get_chatgpt_user_id()?;
let url = format!(
"{}/wham/security-setup",
config.chatgpt_base_url.trim_end_matches('/')
);
let runtime = self
.thread_manager
.runtime_auth_for_config(&config)
.ok()?
.filter(|_| codex_runtime_agent_instance::is_openai_api_url(&url));
let resolved = codex_model_provider::auth_provider_for_request(
&auth,
runtime.as_ref(),
/*headers*/ &Default::default(),
)
.await
.ok()?;
let factory = resolved.bind_http_client_factory(factory).ok()?;
let client =
RouteAwareClientPool::new_without_redirects(factory, ClientRouteClass::Api);
let mut headers = resolved
.auth
.apply_auth_headers(Default::default())
.await
.ok()?;
headers.insert("chatgpt-account-id", account_id.parse().ok()?);
resolved.validate_headers(&headers).ok()?;
let response = client
.get(&url)
.headers(headers)
.header(
"User-Agent",
codex_login::default_client::get_codex_user_agent(),
)
.send()
.await
.ok()?;
if !response.status().is_success() {
return None;
}
let notice = response.json::<Response>().await.ok()?.notice?;
let current = self.auth_manager.auth().await?;
if self
.auth_manager
.auth_change_state_for(&auth)?
.source_generation
!= source_generation
|| current.auth_mode() != codex_protocol::auth::AuthMode::Chatgpt
|| current.get_account_id().as_ref() != Some(&account_id)
|| current.get_chatgpt_user_id().as_ref() != Some(&user_id)
|| current.is_fedramp_account()
{
return None;
}
Some(AccountSecuritySetupNotice {
account_id,
user_id,
title: notice.title,
description: notice.description,
action: notice.action,
})
})
.await
.ok()
.flatten();
GetAccountSecuritySetupResponse { notice }
GetAccountSecuritySetupResponse { notice: None }
}
}

View File

@@ -1,641 +0,0 @@
//! Discovers routing for the selected ChatGPT workspace without crossing auth owners.
//! Discovery is coordinated per routing key; a cache miss never proves independence.
//! Credential refreshes invalidate the cache, but do not cancel same-owner discovery.
//! Model sessions retain their original bootstrap scope across configuration changes.
use super::*;
use codex_app_server_protocol::AccountRoutingOverride;
use codex_backend_client::AccountEntry;
use codex_config::ConfigLoadError;
use codex_http_client::NetworkPolicyDenied;
use codex_login::RefreshTokenError;
use codex_login::WorkspaceRouting;
use codex_login::WorkspaceRoutingRequest;
use codex_login::WorkspaceRoutingResolver;
use codex_login::auth::RefreshTokenFailedError;
use codex_model_provider::ProviderAccount;
use codex_model_provider::ProviderAccountError;
use codex_model_provider::ProviderAccountState;
use std::future::Future;
use std::io;
use std::pin::Pin;
use std::sync::Weak;
use tokio::sync::Semaphore;
use url::Url;
#[derive(Clone, PartialEq, Eq, Hash)]
pub(super) struct WorkspaceRoutingKey {
auth_generation: u64,
chatgpt_account_id: String,
effective_chatgpt_base_url: String,
required_chatgpt_base_url: Option<String>,
}
// Results live through same-key waiters, even if another key replaces the cache.
// Weak entries are pruned on the next read after those requests finish.
pub(super) type WorkspaceRoutingFetches = HashMap<WorkspaceRoutingKey, Weak<WorkspaceRoutingFetch>>;
pub(super) struct WorkspaceRoutingFetch {
discovery: Semaphore,
routing: Mutex<Option<CachedWorkspaceRouting>>,
}
#[derive(Clone)]
pub(super) struct CachedWorkspaceRouting {
key: WorkspaceRoutingKey,
routing: WorkspaceRouting,
name: Option<String>,
}
pub(super) struct AccountRead {
account_state: ProviderAccountState,
user_id: Option<String>,
pub(super) workspace_routing: Option<WorkspaceRouting>,
workspace_name: Option<String>,
}
#[derive(Debug, PartialEq, Eq, thiserror::Error)]
pub(super) enum AccountReadError {
#[error(transparent)]
InvalidAccount(#[from] ProviderAccountError),
#[error(transparent)]
Routing(#[from] WorkspaceRoutingError),
}
/// Routing failures carry no account, URL, or backend data. Config failures retain
/// only a location or structured error category, never the raw config error.
#[derive(Debug, PartialEq, Eq, thiserror::Error)]
pub(super) enum WorkspaceRoutingError {
#[error("failed to load workspace requirements: {0}")]
RequirementsLoad(String),
#[error("workspace routing requires a ChatGPT account id")]
MissingAccountId,
#[error("workspace routing discovery cancelled")]
DiscoveryCancelled,
#[error("account changed during workspace routing discovery")]
AccountChanged,
#[error("workspace routing discovery unauthorized (401)")]
DiscoveryUnauthorized,
#[error(transparent)]
RefreshTokenRejected(RefreshTokenFailedError),
#[error("workspace routing discovery failed")]
DiscoveryFailed,
#[error("selected workspace missing from routing discovery")]
MissingWorkspace,
#[error("duplicate workspace in routing discovery")]
DuplicateWorkspace,
#[error("failed to reload workspace requirements: {0}")]
RequirementsReload(String),
#[error("configuration changed during workspace routing discovery; retry account/read")]
ConfigurationChanged,
#[error("invalid model provider URL")]
InvalidProviderUrl,
#[error("invalid ChatGPT backend URL")]
InvalidBootstrapUrl,
#[error("invalid session ChatGPT backend URL")]
InvalidSessionBootstrapUrl,
#[error("ChatGPT backend changed; start a new thread before sending more content")]
SessionBackendChanged,
#[error("workspace routing discovery cancelled during shutdown")]
Shutdown,
#[error("workspace routing discovery timed out")]
DiscoveryTimeout,
#[error("workspace routing discovery missing backend origin")]
MissingBackendOrigin,
#[error("workspace routing discovery has invalid account routing override")]
InvalidRoutingOverride,
#[error("workspace routing discovery must return an origin")]
BackendIsNotOrigin,
#[error("required ChatGPT backend conflicts with workspace routing")]
BackendConflict,
#[error("invalid workspace backend URL")]
InvalidBackendUrl,
#[error("workspace backend must use an HTTPS origin without credentials")]
InvalidBackendOrigin,
}
fn workspace_config_load_reason(error: &io::Error) -> String {
// Parser messages and cloud bundle errors can quote secrets, even without
// their source snippets. Retain only structured diagnostics before these
// errors reach JSON-RPC clients, login notifications, or tracing.
let mut current = error
.get_ref()
.map(|source| source as &(dyn std::error::Error + 'static));
while let Some(source) = current {
if let Some(config) = source.downcast_ref::<ConfigLoadError>() {
let config = config.config_error();
let start = config.range.start;
// Non-file diagnostics store a display name, which can contain
// backend-supplied policy names and IDs, in this field.
if !config.path.is_absolute() {
return format!(
"invalid non-file configuration at line {}, column {}",
start.line, start.column
);
}
return format!(
"invalid configuration at {}:{}:{}",
config.path.display(),
start.line,
start.column
);
}
if let Some(cloud) = source.downcast_ref::<CloudConfigBundleLoadError>() {
let reason = match cloud.code() {
CloudConfigBundleLoadErrorCode::Timeout => "request timed out",
CloudConfigBundleLoadErrorCode::Auth
| CloudConfigBundleLoadErrorCode::RequestFailed => {
// Cloud loading currently erases the typed denial. Match
// only known safe policy messages, never forward raw text.
let message = cloud.to_string();
if let Some(policy) = [
NetworkPolicyDenied::Unavailable,
NetworkPolicyDenied::Destination,
NetworkPolicyDenied::Revoked,
NetworkPolicyDenied::UnsupportedTransport,
]
.into_iter()
.find(|policy| policy.to_string() == message)
{
return policy.to_string();
}
if cloud.code() == CloudConfigBundleLoadErrorCode::Auth {
"authentication failed"
} else {
"request failed"
}
}
CloudConfigBundleLoadErrorCode::InvalidBundle => "invalid bundle",
CloudConfigBundleLoadErrorCode::Internal => "internal error",
};
return match cloud.status_code() {
Some(status) => format!("cloud config: {reason} (HTTP {status})"),
None => format!("cloud config: {reason}"),
};
}
if let Some(policy) = source.downcast_ref::<NetworkPolicyDenied>() {
return policy.to_string();
}
current = source.source();
}
// Use the OS error or kind, never an untyped error's potentially secret message.
match error.raw_os_error() {
Some(code) => io::Error::from_raw_os_error(code).to_string(),
None => error.kind().to_string(),
}
}
impl WorkspaceRoutingResolver for AccountRequestProcessor {
fn resolve(
&self,
request: WorkspaceRoutingRequest,
) -> Pin<Box<dyn Future<Output = io::Result<Option<WorkspaceRouting>>> + Send + '_>> {
Box::pin(async move {
self.read_account(Some(&request))
.await
.map(|account| account.workspace_routing)
.map_err(|error| match error {
AccountReadError::InvalidAccount(error) => io::Error::other(error),
AccountReadError::Routing(WorkspaceRoutingError::RefreshTokenRejected(
error,
)) => io::Error::new(io::ErrorKind::PermissionDenied, error),
AccountReadError::Routing(error) => io::Error::new(
if error == WorkspaceRoutingError::DiscoveryUnauthorized {
io::ErrorKind::PermissionDenied
} else {
io::ErrorKind::Other
},
error,
),
})
})
}
}
impl AccountRequestProcessor {
pub(super) async fn read_account_for_background_workspace_routing(
&self,
) -> Result<Option<AccountRead>, AccountReadError> {
if !self
.auth_manager
.auth_cached()
.as_ref()
.is_some_and(CodexAuth::is_chatgpt_auth)
{
return Ok(None);
}
self.read_account(/*request*/ None).await.map(Some)
}
pub(crate) fn notify_workspace_routing_to_connection(&self, connection_id: ConnectionId) {
let processor = self.clone();
let auth_changes = self.auth_manager.auth_change_state_receiver();
let owner_generation = auth_changes.borrow().owner_generation;
tokio::spawn(async move {
if auth_changes.borrow().owner_generation != owner_generation {
return;
}
if let Ok(Some(response)) = processor
.read_account_for_background_workspace_routing()
.await
&& response.workspace_routing.is_some()
&& auth_changes.borrow().owner_generation == owner_generation
{
let notification = processor.current_account_updated_notification();
processor
.outgoing
.send_account_notification(
Some(connection_id),
&auth_changes,
owner_generation,
AccountNotification::Updated(notification),
)
.await;
}
});
}
pub(crate) async fn get_account(
&self,
params: GetAccountParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
self.refresh_token_if_requested(params.refresh_token).await;
let read = self
.read_account(/*request*/ None)
.await
.map_err(|error| match error {
AccountReadError::InvalidAccount(error) => invalid_request(error.to_string()),
AccountReadError::Routing(error) => internal_error(error.to_string()),
})?;
let mut account = read.account_state.account.map(Account::from);
if let Some(Account::Chatgpt { workspace_name, .. }) = &mut account {
*workspace_name = read.workspace_name;
}
Ok(Some(
GetAccountResponse {
account,
user_id: read.user_id,
requires_openai_auth: read.account_state.requires_openai_auth,
workspace_routing: read.workspace_routing.map(|routing| {
codex_app_server_protocol::WorkspaceRouting {
chatgpt_account_id: routing.chatgpt_account_id,
backend_origin: routing.backend_origin,
account_routing_override: match routing.account_routing_override.as_str() {
"NO_CONSTRAINT" => AccountRoutingOverride::NoConstraint,
"us" => AccountRoutingOverride::Us,
"us_cr" => AccountRoutingOverride::UsCr,
_ => unreachable!("routing discovery validates the override"),
},
}
}),
}
.into(),
))
}
pub(super) async fn read_account(
&self,
request: Option<&WorkspaceRoutingRequest>,
) -> Result<AccountRead, AccountReadError> {
let mut auth_changes = self.auth_manager.auth_change_state_receiver();
let auth_state = *auth_changes.borrow_and_update();
let current_auth_changes = auth_changes.clone();
let read = Box::pin(async {
let load_config = async || {
match request.and_then(|request| request.session.as_deref()) {
Some(session) => {
self.config_manager
.load_retained_session_config(&session.config_layer_stack, &session.cwd)
.await
}
None => {
self.config_manager
.load_latest_config(/*fallback_cwd*/ None)
.await
}
}
};
let config = match load_config().await {
Ok(config) => config,
Err(_)
if !self
.auth_manager
.auth_cached()
.as_ref()
.is_some_and(CodexAuth::is_chatgpt_auth) =>
{
self.config.as_ref().clone()
}
Err(error) => {
return Err(WorkspaceRoutingError::RequirementsLoad(
workspace_config_load_reason(&error),
)
.into());
}
};
let auth = self.auth_manager.auth_cached();
let provider = create_model_provider(
config.model_provider.clone(),
Some(self.auth_manager.clone()),
);
let account_state = provider
.account_state()
.map_err(AccountReadError::InvalidAccount)?;
let user_id = auth
.as_ref()
.filter(|_| {
matches!(
&account_state.account,
Some(ProviderAccount::Chatgpt { .. })
)
})
.and_then(CodexAuth::get_chatgpt_user_id);
let mut workspace_routing = if let Some((auth, account_id)) = auth
.as_ref()
.filter(|auth| {
auth.is_chatgpt_auth()
&& (request.is_some()
|| matches!(
account_state.account,
Some(ProviderAccount::Chatgpt { .. })
))
})
.and_then(|auth| auth.get_account_id().map(|account_id| (auth, account_id)))
{
if account_id.is_empty() {
return Err(WorkspaceRoutingError::MissingAccountId.into());
}
let required_chatgpt_base_url = config
.config_layer_stack
.requirements_toml()
.chatgpt_base_url
.clone();
let key = WorkspaceRoutingKey {
auth_generation: auth_state.generation,
chatgpt_account_id: account_id.clone(),
effective_chatgpt_base_url: config.chatgpt_base_url.clone(),
required_chatgpt_base_url: required_chatgpt_base_url.clone(),
};
let fetch = {
let mut fetches = self.workspace_routing_fetches.lock().await;
fetches.retain(|_, fetch| fetch.strong_count() > 0);
if let Some(fetch) = fetches.get(&key).and_then(Weak::upgrade) {
fetch
} else {
let fetch = Arc::new(WorkspaceRoutingFetch {
discovery: Semaphore::new(/*permits*/ 1),
routing: Mutex::new(/*t*/ None),
});
fetches.insert(key.clone(), Arc::downgrade(&fetch));
fetch
}
};
let _permit = fetch
.discovery
.acquire()
.await
.map_err(|_| WorkspaceRoutingError::DiscoveryCancelled)?;
let fetched = fetch.routing.lock().await.clone();
let cached = match fetched {
Some(routing) => Some(routing),
None => self
.workspace_routing
.lock()
.await
.as_ref()
.filter(|cached| cached.key == key)
.cloned(),
};
let routing = if let Some(cached) = cached {
cached
} else {
let runtime = self
.thread_manager
.runtime_auth_for_config(&config)
.map_err(|_| WorkspaceRoutingError::DiscoveryFailed)?;
let mut recovery = self.auth_manager.unauthorized_recovery();
let mut discovery_auth = auth.clone();
let mut discovery_generation = auth_state.generation;
let response = loop {
let client = BackendClient::from_auth_with_runtime(
&config.chatgpt_base_url,
&discovery_auth,
config.http_client_factory(),
runtime.as_ref(),
/*headers*/ &Default::default(),
)
.await
.map_err(|_| WorkspaceRoutingError::DiscoveryFailed)?;
match client.get_accounts_check().await {
Ok(response) => break response,
Err(error) => {
let unauthorized = error.is_unauthorized();
if unauthorized && recovery.has_next() {
let result = recovery.next().await;
let refreshed = *current_auth_changes.borrow();
if refreshed.owner_generation != auth_state.owner_generation {
return Err(WorkspaceRoutingError::AccountChanged.into());
}
if let Err(error) = result
&& refreshed.generation == discovery_generation
{
let cached_failure = self
.auth_manager
.refresh_failure_for_auth(&discovery_auth);
if let RefreshTokenError::Permanent(failed) = error
&& !self.auth_manager.has_external_auth()
&& cached_failure.as_ref() == Some(&failed)
{
return Err(
WorkspaceRoutingError::RefreshTokenRejected(failed)
.into(),
);
}
return Err(
WorkspaceRoutingError::DiscoveryUnauthorized.into()
);
}
discovery_generation = refreshed.generation;
discovery_auth = self
.auth_manager
.auth_cached()
.ok_or(WorkspaceRoutingError::AccountChanged)?;
continue;
}
return Err(if unauthorized {
WorkspaceRoutingError::DiscoveryUnauthorized
} else {
WorkspaceRoutingError::DiscoveryFailed
}
.into());
}
}
};
let mut accounts = response
.accounts
.into_iter()
.filter(|account| account.id == account_id);
let mut entry = accounts
.next()
.ok_or(WorkspaceRoutingError::MissingWorkspace)?;
if accounts.next().is_some() {
return Err(WorkspaceRoutingError::DuplicateWorkspace.into());
}
let latest_config = load_config().await.map_err(|error| {
WorkspaceRoutingError::RequirementsReload(workspace_config_load_reason(
&error,
))
})?;
if latest_config.chatgpt_base_url != config.chatgpt_base_url
|| latest_config.model_provider != config.model_provider
|| latest_config
.config_layer_stack
.requirements_toml()
.chatgpt_base_url
!= required_chatgpt_base_url
{
return Err(WorkspaceRoutingError::ConfigurationChanged.into());
}
let name = entry.name.take();
let routing = resolve_routing(
entry,
required_chatgpt_base_url.as_deref(),
&config.chatgpt_base_url,
)?;
let mut cached = self.workspace_routing.lock().await;
if current_auth_changes.borrow().owner_generation != auth_state.owner_generation
{
return Err(WorkspaceRoutingError::AccountChanged.into());
}
let routing = CachedWorkspaceRouting {
key: WorkspaceRoutingKey {
auth_generation: discovery_generation,
..key
},
routing,
name,
};
// Same-owner refresh can complete a newer discovery first.
if current_auth_changes.borrow().generation == discovery_generation {
*cached = Some(routing.clone());
}
routing
};
*fetch.routing.lock().await = Some(routing.clone());
Some(routing)
} else {
*self.workspace_routing.lock().await = None;
None
};
if let Some(request) = request.filter(|_| workspace_routing.is_some()) {
let origin = Url::parse(&request.provider_base_url)
.map_err(|_| WorkspaceRoutingError::InvalidProviderUrl)?
.origin();
let bootstrap_origin = Url::parse(&config.chatgpt_base_url)
.map_err(|_| WorkspaceRoutingError::InvalidBootstrapUrl)?
.origin();
let session_bootstrap_origin = Url::parse(&request.chatgpt_base_url)
.map_err(|_| WorkspaceRoutingError::InvalidSessionBootstrapUrl)?
.origin();
let selected_backend = workspace_routing.as_ref().is_some_and(|routing| {
routing.routing.backend_origin == origin.ascii_serialization()
});
let workspace_bound = request.previously_routed
|| request.provider_base_url == codex_model_provider::CHATGPT_CODEX_BASE_URL
|| origin == session_bootstrap_origin
|| (session_bootstrap_origin == bootstrap_origin && selected_backend);
if !workspace_bound {
workspace_routing = None;
} else if session_bootstrap_origin != bootstrap_origin {
return Err(WorkspaceRoutingError::SessionBackendChanged.into());
}
}
let (workspace_routing, workspace_name) = workspace_routing
.map(|workspace| (Some(workspace.routing), workspace.name))
.unwrap_or_default();
Ok(AccountRead {
account_state,
user_id,
workspace_routing,
workspace_name,
})
});
let result = tokio::select! {
biased;
_ = self.workspace_routing_shutdown.cancelled() => {
return Err(WorkspaceRoutingError::Shutdown.into());
}
_ = auth_changes.wait_for(|state| state.owner_generation != auth_state.owner_generation) => {
return Err(WorkspaceRoutingError::AccountChanged.into());
}
result = tokio::time::timeout(Duration::from_secs(/*secs*/ 15), read) => {
result.map_err(|_| WorkspaceRoutingError::DiscoveryTimeout)?
}
};
if auth_changes.borrow().owner_generation != auth_state.owner_generation {
return Err(WorkspaceRoutingError::AccountChanged.into());
}
result
}
}
fn resolve_routing(
entry: AccountEntry,
required_chatgpt_base_url: Option<&str>,
effective_base_url: &str,
) -> Result<WorkspaceRouting, AccountReadError> {
let backend = entry
.workspace_backend_origin
.ok_or(WorkspaceRoutingError::MissingBackendOrigin)?;
let account_routing_override = match entry.account_routing_override.as_deref() {
Some(value @ ("NO_CONSTRAINT" | "us" | "us_cr")) => value.to_owned(),
_ => {
return Err(WorkspaceRoutingError::InvalidRoutingOverride.into());
}
};
let required = required_chatgpt_base_url
.map(parse_backend_url)
.transpose()?;
let discovered = if backend == "NO_CONSTRAINT" {
None
} else {
let url = parse_backend_url(&backend)?;
if url.path() != "/" || url.query().is_some() || url.fragment().is_some() {
return Err(WorkspaceRoutingError::BackendIsNotOrigin.into());
}
Some(url)
};
let origin = match (required, discovered) {
(Some(required), Some(discovered)) => {
if required.origin() != discovered.origin() {
return Err(WorkspaceRoutingError::BackendConflict.into());
}
required.origin()
}
(Some(url), None) | (None, Some(url)) => url.origin(),
(None, None) => parse_backend_url(effective_base_url)?.origin(),
};
Ok(WorkspaceRouting {
chatgpt_account_id: entry.id,
backend_origin: origin.ascii_serialization(),
account_routing_override,
})
}
fn parse_backend_url(value: &str) -> Result<Url, AccountReadError> {
let url = Url::parse(value).map_err(|_| WorkspaceRoutingError::InvalidBackendUrl)?;
if url.scheme() != "https"
|| url.host_str().is_none()
|| !url.username().is_empty()
|| url.password().is_some()
|| value.trim() != value
{
return Err(WorkspaceRoutingError::InvalidBackendOrigin.into());
}
Ok(url)
}
#[cfg(test)]
#[path = "workspace_routing_tests.rs"]
mod tests;

View File

@@ -1,243 +0,0 @@
//! Origin resolution, strict discovery validation, and background read eligibility.
use super::*;
use pretty_assertions::assert_eq;
use serde_json::Value;
use test_case::test_case;
#[test_case(CloudConfigBundleLoadErrorCode::RequestFailed, "cloud config: request failed"; "request")]
#[test_case(CloudConfigBundleLoadErrorCode::Auth, "cloud config: authentication failed"; "refresh")]
fn cloud_failures_preserve_policy_denials_but_redact_other_messages(
code: CloudConfigBundleLoadErrorCode,
redacted: &str,
) {
let denied = NetworkPolicyDenied::Destination.to_string();
for (message, expected) in [
(denied.clone(), denied),
(
"destination denied by application network policy: sk-test-private-value".into(),
redacted.into(),
),
] {
let error = io::Error::other(CloudConfigBundleLoadError::new(
code, /*status_code*/ None, message,
));
assert_eq!(workspace_config_load_reason(&error), expected);
}
}
#[test_case(None; "signed_out")]
#[test_case(Some("dummy"); "api_key")]
#[tokio::test]
async fn background_routing_skips_config_until_chatgpt_sign_in(
api_key: Option<&str>,
) -> anyhow::Result<()> {
use app_test_support::ChatGptAuthFixture;
use app_test_support::write_chatgpt_auth;
use codex_config::CloudConfigBundleLoader;
use codex_config::LoaderOverrides;
use codex_config::types::AuthCredentialsStoreMode;
use codex_exec_server::EnvironmentManager;
use codex_login::AuthKeyringBackendKind;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
let home = tempfile::tempdir()?;
let backend = wiremock::MockServer::start().await;
app_test_support::mount_workspace_routing(&backend).await;
let loads = Arc::new(AtomicUsize::new(/*v*/ 0));
let calls = Arc::clone(&loads);
let loader = CloudConfigBundleLoader::from_getter(move || {
calls.fetch_add(/*val*/ 1, Ordering::SeqCst);
async { Ok(None) }
});
let manager = ConfigManager::new_for_tests(
home.path().to_path_buf(),
vec![(
"chatgpt_base_url".into(),
format!("{}/backend-api", backend.uri()).into(),
)],
LoaderOverrides::without_managed_config_for_tests(),
loader,
);
let config = Arc::new(
manager
.load_latest_config(Some(home.path().to_path_buf()))
.await?,
);
if let Some(api_key) = api_key {
codex_login::login_with_api_key(
home.path(),
api_key,
AuthCredentialsStoreMode::File,
AuthKeyringBackendKind::default(),
)?;
}
let auth_manager = Arc::new(
AuthManager::new(
home.path().to_path_buf(),
/*enable_codex_api_key_env*/ false,
AuthCredentialsStoreMode::File,
/*forced_chatgpt_workspace_id*/ None,
Some(config.chatgpt_base_url.clone()),
AuthKeyringBackendKind::default(),
config.auth_config().auth_route_config,
)
.await,
);
let threads = Arc::new(
codex_core::test_support::thread_manager_with_models_provider_and_home(
CodexAuth::from_api_key("dummy"),
config.model_provider.clone(),
config.codex_home.to_path_buf(),
Arc::new(EnvironmentManager::default_for_tests()),
),
);
let (sender, _receiver) = tokio::sync::mpsc::channel(16);
let outgoing = Arc::new(OutgoingMessageSender::new(sender));
let model_catalog = Arc::new(crate::model_catalog::ModelCatalog::new(
manager.clone(),
Some(config.cwd.to_path_buf()),
Arc::clone(&config),
Arc::clone(&threads),
));
let processor = AccountRequestProcessor::new(
Arc::clone(&auth_manager),
threads,
outgoing,
config,
manager,
model_catalog,
);
let initial_loads = loads.load(Ordering::SeqCst);
for _ in 0..3 {
assert!(
processor
.read_account_for_background_workspace_routing()
.await?
.is_none()
);
}
assert_eq!(loads.load(Ordering::SeqCst), initial_loads);
processor.read_account(/*request*/ None).await?;
assert!(loads.load(Ordering::SeqCst) > initial_loads);
write_chatgpt_auth(
home.path(),
ChatGptAuthFixture::new("access-chatgpt").account_id("account-123"),
AuthCredentialsStoreMode::File,
)?;
assert!(auth_manager.reload().await);
let initial_loads = loads.load(Ordering::SeqCst);
let read = processor
.read_account_for_background_workspace_routing()
.await?
.unwrap();
assert_eq!(
read.workspace_routing,
Some(WorkspaceRouting {
chatgpt_account_id: "account-123".into(),
backend_origin: "https://chatgpt.com".into(),
account_routing_override: "NO_CONSTRAINT".into(),
})
);
assert!(loads.load(Ordering::SeqCst) > initial_loads);
let config_path = home.path().join("config.toml");
std::fs::write(&config_path, "invalid = [ 'sk-test-private-value',")?;
let Err(error) = processor
.read_account_for_background_workspace_routing()
.await
else {
panic!("invalid config must prevent workspace routing");
};
let message = error.to_string();
assert!(
message.starts_with(&format!(
"failed to load workspace requirements: invalid configuration at {}:1:",
config_path.display(),
)),
"{message}"
);
assert!(!message.contains("sk-test-private-value"), "{message}");
Ok(())
}
#[test_case(Some("https://gov.chatgpt.com/backend-api/"), "NO_CONSTRAINT", "https://gov.chatgpt.com"; "configured_only")]
#[test_case(None, "https://gov.chatgpt.com", "https://gov.chatgpt.com"; "discovered_only")]
#[test_case(Some("https://GOV.chatgpt.com:443/backend-api/"), "https://gov.chatgpt.com", "https://gov.chatgpt.com"; "matching_effective_port")]
#[test_case(Some("https://example.com:8443/backend-api/"), "https://example.com:8443", "https://example.com:8443"; "custom_port")]
#[test_case(None, "NO_CONSTRAINT", "https://chatgpt.com"; "existing_default")]
fn resolves_origins(required: Option<&str>, discovered: &str, expected: &str) {
let entry = serde_json::from_value(serde_json::json!({
"id": "workspace", "workspace_backend_origin": discovered,
"account_routing_override": "NO_CONSTRAINT",
}))
.unwrap();
assert_eq!(
resolve_routing(entry, required, "https://chatgpt.com/backend-api/").unwrap(),
WorkspaceRouting {
chatgpt_account_id: "workspace".into(),
backend_origin: expected.into(),
account_routing_override: "NO_CONSTRAINT".into(),
}
);
}
#[test_case("https://other.example/backend-api/", "https://gov.chatgpt.com"; "host_conflict")]
#[test_case("http://gov.chatgpt.com/backend-api/", "https://gov.chatgpt.com"; "scheme_conflict")]
#[test_case("https://gov.chatgpt.com:444/backend-api/", "https://gov.chatgpt.com"; "port_conflict")]
fn rejects_conflicting_origins(required: &str, discovered: &str) {
let entry = serde_json::from_value(serde_json::json!({
"id": "workspace", "workspace_backend_origin": discovered,
"account_routing_override": "us_cr",
}))
.unwrap();
assert!(resolve_routing(entry, Some(required), "https://chatgpt.com").is_err());
}
#[test_case(serde_json::json!(null), serde_json::json!("us_cr"), WorkspaceRoutingError::MissingBackendOrigin; "null_origin")]
#[test_case(serde_json::json!("NO_CONSTRAINT"), serde_json::json!(null), WorkspaceRoutingError::InvalidRoutingOverride; "null_routing")]
#[test_case(serde_json::json!(""), serde_json::json!("us_cr"), WorkspaceRoutingError::InvalidBackendUrl; "empty_origin")]
#[test_case(serde_json::json!("https://example.com/backend-api/"), serde_json::json!("us_cr"), WorkspaceRoutingError::BackendIsNotOrigin; "origin_with_path")]
#[test_case(serde_json::json!("https://example.com?query"), serde_json::json!("us_cr"), WorkspaceRoutingError::BackendIsNotOrigin; "origin_with_query")]
#[test_case(serde_json::json!("https://example.com#fragment"), serde_json::json!("us_cr"), WorkspaceRoutingError::BackendIsNotOrigin; "origin_with_fragment")]
#[test_case(serde_json::json!("https://user:pass@example.com"), serde_json::json!("us_cr"), WorkspaceRoutingError::InvalidBackendOrigin; "credentials")]
#[test_case(serde_json::json!("http://example.com"), serde_json::json!("us_cr"), WorkspaceRoutingError::InvalidBackendOrigin; "insecure_origin")]
#[test_case(serde_json::json!("NO_CONSTRAINT"), serde_json::json!("unknown"), WorkspaceRoutingError::InvalidRoutingOverride; "unknown_routing")]
#[test_case(serde_json::json!("NO_CONSTRAINT"), serde_json::json!(""), WorkspaceRoutingError::InvalidRoutingOverride; "empty_routing")]
fn rejects_invalid_discovery(backend: Value, routing: Value, expected: WorkspaceRoutingError) {
let entry = serde_json::from_value(serde_json::json!({
"id": "workspace", "workspace_backend_origin": backend, "account_routing_override": routing,
}))
.unwrap();
assert_eq!(
resolve_routing(
entry,
/*required_chatgpt_base_url*/ None,
"https://chatgpt.com"
),
Err(AccountReadError::Routing(expected))
);
}
#[test]
fn unrestricted_discovery_uses_effective_custom_backend() {
let entry = serde_json::from_value(serde_json::json!({
"id": "workspace", "workspace_backend_origin": "NO_CONSTRAINT", "account_routing_override": "us",
})).unwrap();
assert_eq!(
resolve_routing(
entry,
/*required_chatgpt_base_url*/ None,
"https://custom.example:8443/backend-api/"
)
.unwrap(),
WorkspaceRouting {
chatgpt_account_id: "workspace".into(),
backend_origin: "https://custom.example:8443".into(),
account_routing_override: "us".into(),
}
);
}

View File

@@ -1,255 +0,0 @@
//! Lists the active managed login and switches its workspace through the account-session API.
use super::*;
use codex_app_server_protocol::AccountSession;
use codex_app_server_protocol::AccountSessionWorkspace;
use codex_app_server_protocol::AccountSessionWorkspaceKind;
use codex_app_server_protocol::AccountSessionsListParams;
use codex_app_server_protocol::AccountSessionsResponse;
use codex_app_server_protocol::AccountSessionsSwitchParams;
use codex_app_server_protocol::AccountSessionsSwitchResponse;
impl AccountRequestProcessor {
pub(crate) async fn list_account_sessions(
&self,
params: AccountSessionsListParams,
) -> Result<AccountSessionsResponse, JSONRPCErrorError> {
let auth = if params.refresh_workspace_metadata {
self.auth_manager.auth().await
} else {
self.auth_manager.auth_cached()
}
.filter(|_| !self.auth_manager.has_external_auth());
let session_id = auth
.as_ref()
.and_then(CodexAuth::managed_account_session_id);
let (Some(auth), Some(session_id)) = (auth, session_id) else {
return Ok(AccountSessionsResponse {
active_session_id: None,
sessions: vec![],
});
};
let account_id = auth.get_account_id();
let mut workspaces = account_id
.iter()
.map(|id| AccountSessionWorkspace {
account_id: id.clone(),
name: None,
image_url: None,
kind: None,
})
.collect();
if params.refresh_workspace_metadata {
let accounts = self.workspace_memberships(&auth).await?;
workspaces = accounts
.accounts
.into_iter()
.map(|account| AccountSessionWorkspace {
account_id: account.id,
name: account.name,
image_url: account.profile_picture_url,
kind: match account.structure.as_str() {
"personal" => Some(AccountSessionWorkspaceKind::Personal),
"workspace" => Some(AccountSessionWorkspaceKind::Workspace),
_ => None,
},
})
.collect::<Vec<_>>();
workspaces.sort_by_key(|workspace| {
accounts
.account_ordering
.iter()
.position(|id| id == &workspace.account_id)
.unwrap_or(usize::MAX)
});
let current = self.auth_manager.auth_cached();
if self.auth_manager.has_external_auth()
|| current
.as_ref()
.and_then(CodexAuth::managed_account_session_id)
.as_deref()
!= Some(&session_id)
|| current.and_then(|auth| auth.get_account_id()) != account_id
{
return Err(invalid_request(
"Authentication changed while listing account sessions",
));
}
}
Ok(AccountSessionsResponse {
active_session_id: Some(session_id.clone()),
sessions: vec![AccountSession {
session_id,
email: auth.get_account_email(),
user_id: auth.get_chatgpt_user_id(),
display_name: None,
image_url: None,
last_used_at: chrono::Utc::now().timestamp(),
is_active: true,
selected_workspace_account_id: account_id,
workspaces,
}],
})
}
async fn workspace_memberships(
&self,
auth: &CodexAuth,
) -> Result<codex_backend_client::AccountsCheckResponse, JSONRPCErrorError> {
let client = BackendClient::from_auth(
self.config.chatgpt_base_url.clone(),
auth,
self.config.http_client_factory(),
);
tokio::time::timeout(
Duration::from_secs(/*secs*/ 30),
client.get_accounts_check(),
)
.await
.map_err(|_| internal_error("Workspace metadata request timed out"))?
.map_err(|_| internal_error("Failed to fetch workspace metadata"))
}
pub(crate) async fn switch_account_session(
&self,
params: AccountSessionsSwitchParams,
threads: &crate::request_processors::ThreadRequestProcessor,
admission: &crate::turn_admission::TurnAdmission,
) -> Result<AccountSessionsSwitchResponse, JSONRPCErrorError> {
if self.active_login.lock().await.is_some() {
return Err(invalid_request(
"Finish or cancel the current login before switching workspaces",
));
}
self.auth_manager
.validate_workspace_switch(&params.session_id, &params.account_id)
.map_err(|error| invalid_request(error.to_string()))?;
if self
.auth_manager
.auth_cached()
.and_then(|auth| auth.get_account_id())
.as_deref()
== Some(&params.account_id)
{
return self.account_session_switch_response(&params).await;
}
let auth = self
.auth_manager
.auth_cached()
.ok_or_else(|| invalid_request("Authentication is unavailable"))?;
let memberships = self.workspace_memberships(&auth).await?;
let mut matches = memberships
.accounts
.iter()
.filter(|account| account.id == params.account_id);
let Some(target) = matches.next() else {
return Err(invalid_request("The selected workspace is unavailable"));
};
if matches.next().is_some() || target.is_deactivated {
return Err(invalid_request("The selected workspace is unavailable"));
}
// The exchange strips the FedRAMP hint from the server session's token templates.
if auth.is_fedramp_account()
|| target.is_fedramp_compliant_workspace
|| target.workspace_backend_origin.as_deref() == Some("https://gov.chatgpt.com")
{
return Err(invalid_request("Sign in to switch government workspaces"));
}
self.auth_manager
.validate_workspace_switch(&params.session_id, &params.account_id)
.map_err(|error| invalid_request(error.to_string()))?;
if target.can_access_with_session == Some(false) {
if !params.allow_browser_login {
return Err(invalid_request(
"The selected workspace requires a new sign-in",
));
}
let mut opts = self
.login_chatgpt_common(
/*codex_streamlined_login*/ true,
LoginSuccessPage::default(),
)
.await?;
opts.workspace_login = Some(
auth.workspace_login(
&params.session_id,
params.account_id.clone(),
target.sso_connection_name.clone(),
)
.map_err(|error| invalid_request(error.to_string()))?,
);
opts.forced_chatgpt_workspace_id = Some(vec![params.account_id]);
let pause = admission.pause().await?;
threads.unload_for_workspace_switch().await?;
let (login_id, auth_url) = self.start_browser_login(opts, Some(pause)).await?;
return Ok(AccountSessionsSwitchResponse::BrowserLogin { login_id, auth_url });
}
let _pause = admission.pause().await?;
threads.unload_for_workspace_switch().await?;
let switched = self
.auth_manager
.switch_workspace(&params.session_id, &params.account_id)
.await
.map_err(|error| invalid_request(error.to_string()))?;
let auth_changes = self.auth_manager.auth_change_state_receiver();
let owner_generation = auth_changes.borrow().owner_generation;
self.reload_workspace_config().await;
// Routing includes fatal authorization and policy checks. Restore the
// previous login on any failure, unless another auth operation replaced it.
if let Err(error) = self.read_account(/*request*/ None).await {
let rollback = self.auth_manager.rollback_workspace_switch(switched).await;
self.reload_workspace_config().await;
rollback.map_err(|rollback| internal_error(format!("Workspace validation failed: {error}; could not restore the previous workspace: {rollback}")))?;
return Err(internal_error(format!(
"Workspace validation failed: {error}"
)));
}
self.thread_manager.invalidate_mcp_runtimes().await;
self.model_catalog.invalidate().await;
Self::maybe_refresh_plugin_caches_for_current_config(
&self.config_manager,
&self.thread_manager,
self.auth_manager.auth_cached(),
)
.await;
self.outgoing
.send_account_notification(
/*connection_id*/ None,
&auth_changes,
owner_generation,
AccountNotification::Updated(self.current_account_updated_notification()),
)
.await;
self.account_session_switch_response(&params).await
}
async fn reload_workspace_config(&self) {
self.config_manager
.update_managed_config_loader(self.auth_manager.clone(), &self.config);
self.config_manager
.sync_default_client_residency_requirement()
.await;
}
async fn account_session_switch_response(
&self,
params: &AccountSessionsSwitchParams,
) -> Result<AccountSessionsSwitchResponse, JSONRPCErrorError> {
let response = self
.list_account_sessions(AccountSessionsListParams {
refresh_workspace_metadata: false,
})
.await?;
if response.active_session_id.as_deref() != Some(&params.session_id)
|| !response.sessions.iter().any(|session| {
session.session_id == params.session_id
&& session.selected_workspace_account_id.as_deref() == Some(&params.account_id)
})
{
return Err(invalid_request(
"Authentication changed during workspace switching",
));
}
Ok(AccountSessionsSwitchResponse::Switched { sessions: response })
}
}

View File

@@ -38,8 +38,7 @@ fn skills_to_info(
short_description: interface.short_description,
icon_small: interface.icon_small,
icon_large: interface.icon_large,
icon_small_url: None,
icon_large_url: None,
brand_color: interface.brand_color,
default_prompt: interface.default_prompt,
}

View File

@@ -1,18 +1,5 @@
use super::*;
fn cloud_config_bundle_load_error(err: &std::io::Error) -> Option<&CloudConfigBundleLoadError> {
let mut current: Option<&(dyn std::error::Error + 'static)> = err
.get_ref()
.map(|source| source as &(dyn std::error::Error + 'static));
while let Some(source) = current {
if let Some(cloud_error) = source.downcast_ref::<CloudConfigBundleLoadError>() {
return Some(cloud_error);
}
current = source.source();
}
None
}
pub(super) fn model_provider_error(provider: &ModelProviderError) -> JSONRPCErrorError {
let mut error = invalid_request(provider.to_string());
error.data = serde_json::to_value(provider).ok();
@@ -29,22 +16,5 @@ pub(crate) fn config_load_error(err: &std::io::Error) -> JSONRPCErrorError {
}
current = source.source();
}
let data = cloud_config_bundle_load_error(err).map(|cloud_error| {
let mut data = serde_json::json!({
"reason": "cloudConfigBundle",
"errorCode": format!("{:?}", cloud_error.code()),
"detail": cloud_error.to_string(),
});
if let Some(status_code) = cloud_error.status_code() {
data["statusCode"] = serde_json::json!(status_code);
}
if cloud_error.code() == CloudConfigBundleLoadErrorCode::Auth {
data["action"] = serde_json::json!("relogin");
}
data
});
let mut error = invalid_request(format!("failed to load configuration: {err}"));
error.data = data;
error
invalid_request(format!("failed to load configuration: {err}"))
}

View File

@@ -65,18 +65,15 @@ const BACKGROUND_PAGINATED_ROLLOUT_MIGRATION_FEATURE: &str =
"background_paginated_rollout_migration";
const SUPPORTED_EXPERIMENTAL_FEATURE_ENABLEMENT: &[&str] = &[
"api_key_cyber_access_programs",
"api_key_model_discovery",
"auth_elicitation",
BACKGROUND_PAGINATED_ROLLOUT_MIGRATION_FEATURE,
"codex_apps_mcp_2026_07_28",
"mcp_2026_07_28",
"mcp_connection_sharing",
"mcp_lazy_stdio_startup",
"memories",
"mentions_v2",
"remote_control",
"remote_plugin",
"tool_suggest",
"windows_sandbox_service",
];
@@ -241,7 +238,6 @@ impl ConfigRequestProcessor {
let provider = create_model_provider(config.model_provider, /*auth_manager*/ None);
let capabilities = provider.capabilities();
Ok(ModelProviderCapabilitiesReadResponse {
image_generation: capabilities.image_generation,
web_search: capabilities.web_search,
})
}
@@ -358,14 +354,8 @@ pub(super) async fn reload_user_config(
}
async fn reload_user_config_inner(config_manager: &ConfigManager, thread_manager: &ThreadManager) {
config_manager.revoke_mcp_ema_startups();
if let Err(err) = config_manager.load_config_layers(/*cwd*/ None).await {
tracing::warn!("failed to rebuild user config for runtime refresh: {err}");
for thread_id in thread_manager.list_thread_ids().await {
if let Ok(thread) = thread_manager.get_thread(thread_id).await {
thread.disable_mcp_enterprise_auth().await;
}
}
return;
}
let thread_ids = thread_manager.list_thread_ids().await;
@@ -385,7 +375,6 @@ async fn reload_user_config_inner(config_manager: &ConfigManager, thread_manager
Ok(config) => config,
Err(err) => {
tracing::warn!(%thread_id, %err, "failed to reload thread configuration");
thread.disable_mcp_enterprise_auth().await;
break;
}
};
@@ -416,8 +405,7 @@ async fn reload_user_config_inner(config_manager: &ConfigManager, thread_manager
}
}
if attempt == 3 {
thread.disable_mcp_enterprise_auth().await;
tracing::warn!(%thread_id, "configuration kept changing during user reload; enterprise MCP disabled");
tracing::warn!(%thread_id, "configuration kept changing during user reload");
}
}
}
@@ -933,7 +921,6 @@ mod tests {
use codex_config::BrowserUseAccessApprovalLifetimeToml;
use codex_config::BrowserUseOriginPolicyToml;
use codex_config::BrowserUseRequirementsToml;
use codex_config::CloudConfigBundleLoader;
use codex_config::ComputerUseMacosRequirementsToml;
use codex_config::ComputerUseRequirementsToml;
use codex_config::ComputerUseWindowsExeRequirementToml;
@@ -962,14 +949,8 @@ mod tests {
std::fs::write(
&managed_config_path,
r#"
[features]
use_xaa = true
[mcp_enterprise_managed_auth.idp]
issuer = "https://idp.example"
client_id = "idp-client"
[mcp_servers.enterprise]
url = "https://resource.example/mcp"
auth = "ema_auth"
oauth_resource = "https://resource.example/mcp"
[mcp_servers.enterprise.oauth]
client_id = "mcp-client"
@@ -984,7 +965,6 @@ client_id = "mcp-client"
home.path().to_path_buf(),
Vec::new(),
LoaderOverrides::with_managed_config_path_for_tests(managed_config_path),
CloudConfigBundleLoader::default(),
);
let initial = config_manager
.load_latest_config(Some(home.path().to_path_buf()))

View File

@@ -86,7 +86,6 @@ async fn user_reload_promotes_plugin_and_feature_requirements_without_server_cha
Vec::new(),
overrides,
/*strict_config*/ false,
codex_config::CloudConfigBundleLoader::default(),
codex_arg0::Arg0DispatchPaths::default(),
Arc::new(codex_config::NoopThreadConfigLoader),
);
@@ -153,100 +152,3 @@ async fn user_reload_promotes_plugin_and_feature_requirements_without_server_cha
Ok(())
}
#[test_case::test_case(codex_config::CloudConfigBundleBindingStatus::Stale)]
#[test_case::test_case(codex_config::CloudConfigBundleBindingStatus::Suspended)]
#[tokio::test]
async fn mcp_refresh_rejects_superseded_app_server_policy(
status: codex_config::CloudConfigBundleBindingStatus,
) -> anyhow::Result<()> {
use codex_config::CloudConfigBundle;
use codex_config::CloudConfigBundleLoader;
use codex_config::CloudConfigBundlePolicy;
use codex_config::CloudConfigBundleSnapshot;
use codex_core::ConfigRefreshOutcome;
let home = tempfile::tempdir()?;
let policy = CloudConfigBundlePolicy::default();
let mut snapshot = CloudConfigBundleSnapshot {
config_server: None,
bundle: Ok(None),
binding: None,
};
policy.publish_snapshot(&mut snapshot);
let loader =
CloudConfigBundleLoader::default().with_ema_policy_snapshots(policy.clone(), move || {
let snapshot = snapshot.clone();
async move { snapshot }
});
let manager = ConfigManager::new(
home.path().to_path_buf(),
Vec::new(),
codex_config::LoaderOverrides::without_managed_config_for_tests(),
/*strict_config*/ false,
loader,
codex_arg0::Arg0DispatchPaths::default(),
Arc::new(codex_config::NoopThreadConfigLoader),
);
let initial = manager
.load_latest_config(Some(home.path().to_path_buf()))
.await?;
let threads = codex_core::test_support::thread_manager_with_models_provider_and_home(
CodexAuth::from_api_key("dummy"),
initial.model_provider.clone(),
initial.codex_home.to_path_buf(),
Arc::new(EnvironmentManager::default_for_tests()),
);
let thread = threads
.start_thread(codex_core::StartThreadOptions::new(initial))
.await?
.thread;
let current = thread.config().await;
let next = manager
.load_latest_config_with_session_layers(&current.config_layer_stack, &current.cwd)
.await?;
let mut replacement = CloudConfigBundle::default();
replacement
.config_toml
.enterprise_managed
.push(codex_config::CloudConfigFragment {
id: "replacement".into(),
name: "replacement".into(),
contents: "model = 'replacement-model'".into(),
});
policy.observe_remote_bundle(&replacement);
if status == codex_config::CloudConfigBundleBindingStatus::Stale {
policy.publish_snapshot(&mut CloudConfigBundleSnapshot {
config_server: None,
bundle: Ok(Some(replacement)),
binding: None,
});
}
assert_eq!(
next.config_layer_stack
.cloud_config_binding()
.expect("app-server must retain the policy binding")
.read()
.status,
status,
);
let outcome = thread.refresh_mcp_config(Arc::clone(&current), next).await;
let expected = match status {
codex_config::CloudConfigBundleBindingStatus::Stale => ConfigRefreshOutcome::Stale,
codex_config::CloudConfigBundleBindingStatus::Suspended => ConfigRefreshOutcome::Rejected,
codex_config::CloudConfigBundleBindingStatus::Current => unreachable!(),
};
assert_eq!(outcome, expected);
if status == codex_config::CloudConfigBundleBindingStatus::Stale {
assert!(Arc::ptr_eq(&current, &thread.config().await));
} else {
assert!(
thread
.config()
.await
.config_layer_stack
.cloud_config_binding()
.is_none()
);
}
Ok(())
}

View File

@@ -94,7 +94,6 @@ impl ThreadRequestProcessor {
turn_trigger: Some("daemon_recovery".to_string()),
final_output_json_schema: saved.output_schema,
service_tier: saved.service_tier,
cyber_access_program: saved.cyber_access_program,
root_turn_id: previous_context.root_turn_id.clone(),
..Default::default()
},

View File

@@ -44,7 +44,6 @@ impl ThreadRequestProcessor {
turn_id,
output_schema: options.final_output_json_schema,
service_tier: options.service_tier,
cyber_access_program: options.cyber_access_program,
local_environment: Some((&environment).into()),
},
);

View File

@@ -3,11 +3,6 @@ use super::*;
use crate::error_code::OVERLOADED_ERROR_CODE;
use codex_app_server_protocol::FeedbackSaveParams;
use codex_app_server_protocol::FeedbackSaveResponse;
use codex_connectors::ConnectorDirectoryCacheContext;
use codex_connectors::ConnectorDirectoryCacheKey;
use codex_connectors::connector_runtime_cache_path;
use codex_feedback::CODEX_APP_DIRECTORY_CACHE_ATTACHMENT_FILENAME;
use codex_feedback::CODEX_APPS_TOOLS_CACHE_ATTACHMENT_FILENAME;
use codex_feedback::FeedbackAttachment;
use codex_feedback::FeedbackSnapshot;
#[cfg(target_os = "windows")]
@@ -28,7 +23,6 @@ struct SavedFeedback {
#[derive(Clone)]
pub(crate) struct FeedbackRequestProcessor {
auth_manager: Arc<AuthManager>,
thread_manager: Arc<ThreadManager>,
config: Arc<Config>,
feedback: CodexFeedback,
@@ -39,7 +33,6 @@ pub(crate) struct FeedbackRequestProcessor {
impl FeedbackRequestProcessor {
pub(crate) fn new(
auth_manager: Arc<AuthManager>,
thread_manager: Arc<ThreadManager>,
config: Arc<Config>,
feedback: CodexFeedback,
@@ -47,7 +40,6 @@ impl FeedbackRequestProcessor {
state_db: Option<StateDbHandle>,
) -> Self {
Self {
auth_manager,
thread_manager,
config,
feedback,
@@ -115,7 +107,6 @@ impl FeedbackRequestProcessor {
None => None,
};
let auth = self.auth_manager.auth_cached();
let turn_metadata = if let Some(conversation_id) = conversation_id
&& let Some(rollout_path) = self
.resolve_rollout_path(conversation_id, self.state_db.as_ref())
@@ -132,18 +123,6 @@ impl FeedbackRequestProcessor {
apply_feedback_turn_metadata(&mut report_tags, turn_metadata);
let prompt_hash = report_tags.get("prompt_hash").cloned();
if let Some(chatgpt_user_id) = auth
.as_ref()
.and_then(codex_login::CodexAuth::get_chatgpt_user_id)
{
tracing::info!(target: "feedback_tags", chatgpt_user_id);
}
if let Some(account_id) = auth
.as_ref()
.and_then(codex_login::CodexAuth::get_account_id)
{
tracing::info!(target: "feedback_tags", account_id);
}
let snapshot = self.feedback.snapshot(conversation_id);
let mut extra_attachments = Vec::new();
let mut feedback_index = None;
@@ -255,15 +234,6 @@ impl FeedbackRequestProcessor {
{
attachment_paths.push(sandbox_log_attachment);
}
for cache_attachment in tool_cache_feedback_attachments(
self.config.codex_home.as_path(),
&self.config.chatgpt_base_url,
auth.as_ref(),
) {
if seen_attachment_paths.insert(cache_attachment.path.clone()) {
attachment_paths.push(cache_attachment);
}
}
}
if let Some(extra_log_files) = extra_log_files {
for extra_log_file in extra_log_files {
@@ -461,47 +431,6 @@ fn normalized_prompt_hash(prompt: &str) -> String {
format!("{:x}", Sha256::digest(normalized_prompt.as_bytes()))
}
fn tool_cache_feedback_attachments(
codex_home: &Path,
chatgpt_base_url: &str,
auth: Option<&CodexAuth>,
) -> Vec<FeedbackAttachmentPath> {
let mut attachments = Vec::with_capacity(2);
let tools_cache_path = connector_runtime_cache_path(codex_home, auth);
if tools_cache_path.is_file() {
attachments.push(FeedbackAttachmentPath {
path: tools_cache_path,
attachment_filename_override: Some(
CODEX_APPS_TOOLS_CACHE_ATTACHMENT_FILENAME.to_string(),
),
});
}
let Some(auth) = auth.filter(|auth| auth.uses_codex_backend()) else {
return attachments;
};
let directory_cache_context = ConnectorDirectoryCacheContext::new(
codex_home.to_path_buf(),
ConnectorDirectoryCacheKey::new(
chatgpt_base_url.to_string(),
auth.get_account_id(),
auth.get_chatgpt_user_id(),
auth.is_workspace_account(),
),
);
let directory_cache_path = directory_cache_context.cache_path();
if directory_cache_path.is_file() {
attachments.push(FeedbackAttachmentPath {
path: directory_cache_path,
attachment_filename_override: Some(
CODEX_APP_DIRECTORY_CACHE_ATTACHMENT_FILENAME.to_string(),
),
});
}
attachments
}
fn auto_review_rollout_filename(thread_id: ThreadId) -> String {
format!("auto-review-rollout-{thread_id}.jsonl")
}
@@ -589,7 +518,6 @@ mod tests {
use codex_rollout::RolloutLine;
use core_test_support::responses::start_mock_server;
use core_test_support::test_codex::test_codex;
use http::HeaderMap;
use pretty_assertions::assert_eq;
#[tokio::test]
@@ -826,7 +754,6 @@ mod tests {
collaboration_mode: None,
multi_agent_version: None,
realtime_active: None,
cyber_access_program: None,
effort: effort.clone(),
summary: Some(ReasoningSummary::Auto),
}),
@@ -843,98 +770,6 @@ mod tests {
(tempdir, rollout_path)
}
#[test]
fn tool_cache_feedback_attachments_include_existing_active_cache_files() {
let codex_home = tempfile::tempdir().expect("create tempdir");
let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing();
let tools_cache_path = connector_runtime_cache_path(codex_home.path(), Some(&auth));
std::fs::create_dir_all(tools_cache_path.parent().expect("tools cache parent"))
.expect("create tools cache directory");
std::fs::write(&tools_cache_path, b"tools").expect("write tools cache");
let account_id = auth.get_account_id().expect("dummy auth account id");
let directory_cache_context = ConnectorDirectoryCacheContext::new(
codex_home.path().to_path_buf(),
ConnectorDirectoryCacheKey::new(
"https://chatgpt.com/backend-api".to_string(),
Some(account_id),
auth.get_chatgpt_user_id(),
auth.is_workspace_account(),
),
);
let directory_cache_path = directory_cache_context.cache_path();
std::fs::create_dir_all(
directory_cache_path
.parent()
.expect("directory cache parent"),
)
.expect("create directory cache directory");
std::fs::write(&directory_cache_path, b"directory").expect("write directory cache");
let attachments = tool_cache_feedback_attachments(
codex_home.path(),
"https://chatgpt.com/backend-api",
Some(&auth),
)
.into_iter()
.map(|attachment| (attachment.path, attachment.attachment_filename_override))
.collect::<Vec<_>>();
assert_eq!(
attachments,
vec![
(
tools_cache_path,
Some(CODEX_APPS_TOOLS_CACHE_ATTACHMENT_FILENAME.to_string()),
),
(
directory_cache_path,
Some(CODEX_APP_DIRECTORY_CACHE_ATTACHMENT_FILENAME.to_string()),
),
]
);
}
#[test]
fn tool_cache_feedback_attachments_include_directory_cache_without_account_id() {
let codex_home = tempfile::tempdir().expect("create tempdir");
let auth = CodexAuth::Headers(codex_login::AuthHeaders::new(HeaderMap::new()));
let directory_cache_context = ConnectorDirectoryCacheContext::new(
codex_home.path().to_path_buf(),
ConnectorDirectoryCacheKey::new(
"https://chatgpt.com/backend-api".to_string(),
/*account_id*/ None,
auth.get_chatgpt_user_id(),
auth.is_workspace_account(),
),
);
let directory_cache_path = directory_cache_context.cache_path();
std::fs::create_dir_all(
directory_cache_path
.parent()
.expect("directory cache parent"),
)
.expect("create directory cache directory");
std::fs::write(&directory_cache_path, b"directory").expect("write directory cache");
let attachments = tool_cache_feedback_attachments(
codex_home.path(),
"https://chatgpt.com/backend-api",
Some(&auth),
)
.into_iter()
.map(|attachment| (attachment.path, attachment.attachment_filename_override))
.collect::<Vec<_>>();
assert_eq!(
attachments,
vec![(
directory_cache_path,
Some(CODEX_APP_DIRECTORY_CACHE_ATTACHMENT_FILENAME.to_string()),
)]
);
}
#[cfg(target_os = "windows")]
#[test]
fn windows_sandbox_log_attachment_uses_current_log() {

View File

@@ -70,7 +70,6 @@ impl InitializeRequestProcessor {
// with initialize-time mismatch rejection.
let capabilities = params.capabilities.unwrap_or_default();
let experimental_api_enabled = capabilities.experimental_api;
let request_attestation = capabilities.request_attestation;
let extensions = capabilities.extensions.as_ref();
let mut client_mcp_extensions = codex_mcp::client_mcp_extensions(
extensions,
@@ -126,7 +125,6 @@ impl InitializeRequestProcessor {
opted_out_notification_methods: opt_out_notification_methods.into_iter().collect(),
app_server_client_name: name.clone(),
client_version: version,
request_attestation,
client_mcp_extensions,
})
.is_err()

View File

@@ -1,335 +0,0 @@
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use codex_app_server_protocol::JSONRPCErrorError;
use codex_app_server_protocol::McpServerEventNotification;
use codex_app_server_protocol::McpServerEventStreamNotification;
use codex_app_server_protocol::McpServerEventStreamStartParams;
use codex_app_server_protocol::ServerNotification;
use codex_core::CodexThread;
use codex_login::AuthManager;
use codex_mcp::CODEX_APPS_MCP_SERVER_NAME;
use codex_mcp::McpEventStream;
use codex_protocol::ThreadId;
use serde_json::Value;
use tokio::sync::Mutex;
use tokio::sync::oneshot;
use tokio::sync::watch;
use tokio::task::JoinHandle;
use super::mcp_processor::McpRequestProcessor;
use crate::error_code::OVERLOADED_ERROR_CODE;
use crate::error_code::internal_error;
use crate::error_code::invalid_request;
use crate::outgoing_message::ConnectionId;
use crate::outgoing_message::OutgoingMessageSender;
const MAX_MCP_EVENT_STREAMS_PER_CONNECTION: usize = 64;
const MAX_MCP_EVENT_STREAM_RECONNECT_ATTEMPTS: u32 = 3;
const MCP_EVENT_STREAM_RECONNECT_DELAY: Duration = Duration::from_secs(/*secs*/ 1);
const MCP_EVENT_STREAM_STARTUP_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 90);
pub(crate) type McpEventStreamReady = oneshot::Receiver<Result<(), JSONRPCErrorError>>;
#[derive(Debug)]
struct McpEventStreamTask {
thread_id: ThreadId,
task: JoinHandle<()>,
}
#[derive(Debug, Default)]
pub(crate) struct McpEventStreams {
tasks: Mutex<HashMap<String, McpEventStreamTask>>,
}
impl McpEventStreams {
pub(crate) async fn start(
&self,
connection_id: ConnectionId,
params: McpServerEventStreamStartParams,
processor: McpRequestProcessor,
) -> Result<McpEventStreamReady, JSONRPCErrorError> {
if params.server != CODEX_APPS_MCP_SERVER_NAME {
return Err(invalid_request(
"MCP event subscriptions are only supported for hosted apps",
));
}
let thread_id = ThreadId::from_string(&params.thread_id)
.map_err(|error| invalid_request(format!("invalid thread id: {error}")))?;
let subscription_id = params.subscription_id.clone();
let (ready_tx, ready_rx) = oneshot::channel();
{
let mut tasks = self.tasks.lock().await;
tasks.retain(|_, task| !task.task.is_finished());
if tasks.contains_key(&subscription_id) {
return Err(invalid_request(format!(
"MCP event subscription '{subscription_id}' already exists"
)));
}
if tasks.len() >= MAX_MCP_EVENT_STREAMS_PER_CONNECTION {
return Err(JSONRPCErrorError {
code: OVERLOADED_ERROR_CODE,
message: format!(
"MCP event subscription limit of {MAX_MCP_EVENT_STREAMS_PER_CONNECTION} reached"
),
data: None,
});
}
let task = tokio::spawn(async move {
let mut auth_changes =
McpEventStreamAuthChanges::new(Arc::clone(&processor.auth_manager));
let opened = tokio::select! {
() = auth_changes.changed() => Err(internal_error(
"MCP event subscription authentication changed during startup",
)),
result = async {
if !processor
.thread_state_manager
.subscribed_connection_ids(thread_id)
.await
.contains(&connection_id)
{
return Err(invalid_request(format!(
"connection is not subscribed to thread '{thread_id}'"
)));
}
let (_, thread) = processor.load_thread(&params.thread_id).await?;
let stream = thread
.start_mcp_event_stream(
&params.name,
params.arguments.clone(),
params.meta.clone(),
)
.await
.map_err(|error| internal_error(format!(
"failed to start MCP event stream for '{}': {error:#}",
params.server
)))?;
Ok((stream, thread))
} => result,
};
match opened {
Ok((stream, thread)) => {
forward_events(
connection_id,
&params,
processor.outgoing.as_ref(),
thread,
stream,
auth_changes,
ready_tx,
)
.await;
}
Err(error) => {
let _ = ready_tx.send(Err(error));
}
}
});
tasks.insert(subscription_id, McpEventStreamTask { thread_id, task });
}
Ok(ready_rx)
}
pub(crate) async fn wait_for_activation(
&self,
subscription_id: &str,
ready: McpEventStreamReady,
) -> Result<(), JSONRPCErrorError> {
match tokio::time::timeout(MCP_EVENT_STREAM_STARTUP_TIMEOUT, ready).await {
Ok(Ok(result)) => result,
Ok(Err(_)) => Err(internal_error(
"MCP event stream ended before becoming active",
)),
Err(_) => {
self.stop(subscription_id).await;
Err(internal_error("MCP event stream startup timed out"))
}
}
}
pub(crate) async fn stop(&self, subscription_id: &str) {
let task = self.tasks.lock().await.remove(subscription_id);
if let Some(task) = task {
task.task.abort();
let _ = task.task.await;
}
}
pub(crate) async fn stop_thread(&self, thread_id: ThreadId) {
self.stop_matching(Some(thread_id)).await;
}
pub(crate) async fn clear(&self) {
self.stop_matching(/*thread_id*/ None).await;
}
async fn stop_matching(&self, thread_id: Option<ThreadId>) {
let tasks = self
.tasks
.lock()
.await
.extract_if(|_, task| thread_id.is_none_or(|id| task.thread_id == id))
.map(|(_, task)| task)
.collect::<Vec<_>>();
for task in tasks {
task.task.abort();
let _ = task.task.await;
}
}
}
async fn forward_events(
connection_id: ConnectionId,
params: &McpServerEventStreamStartParams,
outgoing: &OutgoingMessageSender,
thread: Arc<CodexThread>,
mut stream: McpEventStream,
mut auth_changes: McpEventStreamAuthChanges,
ready: oneshot::Sender<Result<(), JSONRPCErrorError>>,
) {
let mut ready = Some(ready);
let mut reconnect_attempts = 0;
let mut reconnect_deadline = None;
let send = |notification| {
outgoing.send_server_notification_to_connection_and_wait(
connection_id,
ServerNotification::McpServerEventStream(McpServerEventStreamNotification {
subscription_id: params.subscription_id.clone(),
notification,
}),
)
};
loop {
let notification = tokio::select! {
biased;
() = auth_changes.changed() => break,
() = thread.wait_until_terminated() => break,
result = stream.recv() => match result {
Ok(Some(notification)) => notification,
Ok(None)
if ready.is_none()
&& reconnect_attempts < MAX_MCP_EVENT_STREAM_RECONNECT_ATTEMPTS =>
{
reconnect_attempts += 1;
let deadline = *reconnect_deadline.get_or_insert_with(|| {
tokio::time::Instant::now() + MCP_EVENT_STREAM_STARTUP_TIMEOUT
});
tokio::select! {
biased;
() = auth_changes.changed() => break,
() = thread.wait_until_terminated() => break,
result = tokio::time::timeout_at(deadline, async {
tokio::time::sleep(
MCP_EVENT_STREAM_RECONNECT_DELAY
* (1 << (reconnect_attempts - 1)),
)
.await;
let mut stream = thread
.start_mcp_event_stream(
&params.name,
params.arguments.clone(),
params.meta.clone(),
)
.await?;
let notification = stream.recv().await?;
Ok::<_, anyhow::Error>((stream, notification))
}) => match result {
Ok(Ok((reconnected, Some(notification)))) => {
stream = reconnected;
notification
}
Ok(Ok((_, None)) | Err(_)) => continue,
Err(_) => break,
},
}
}
Ok(None) => break,
Err(error) => {
if let Some(ready) = ready.take() {
let _ = ready.send(Err(internal_error(format!("{error:#}"))));
}
break;
}
},
};
let active = notification.method == "notifications/events/active";
let terminated = notification.method == "notifications/events/terminated";
if !send(McpServerEventNotification {
method: notification.method,
params: notification
.params
.unwrap_or_else(|| Value::Object(Default::default())),
})
.await
{
break;
}
if active && let Some(ready) = ready.take() {
let _ = ready.send(Ok(()));
}
if terminated {
return;
}
if !active {
reconnect_attempts = 0;
reconnect_deadline = None;
}
}
if let Some(ready) = ready {
let _ = ready.send(Err(internal_error(
"MCP event stream ended before becoming active",
)));
} else {
send(McpServerEventNotification {
method: "notifications/events/terminated".to_string(),
params: Value::Object(Default::default()),
})
.await;
}
}
struct McpEventStreamAuthChanges {
manager: Arc<AuthManager>,
receiver: watch::Receiver<u64>,
revision: u64,
principal: Option<(Option<String>, Option<String>)>,
}
impl McpEventStreamAuthChanges {
fn new(manager: Arc<AuthManager>) -> Self {
let receiver = manager.auth_change_receiver();
let revision = *receiver.borrow();
let principal = manager
.auth_cached()
.map(|auth| (auth.get_account_id(), auth.get_chatgpt_user_id()));
Self {
manager,
receiver,
revision,
principal,
}
}
async fn changed(&mut self) {
loop {
if self
.manager
.auth_cached()
.map(|auth| (auth.get_account_id(), auth.get_chatgpt_user_id()))
!= self.principal
{
return;
}
if self.receiver.changed().await.is_err() || self.principal == Some((None, None)) {
return;
}
let revision = *self.receiver.borrow_and_update();
if revision.wrapping_sub(self.revision) > 1 {
return;
}
self.revision = revision;
}
}
}

View File

@@ -1,17 +1,12 @@
use super::account_processor::EnterpriseLoginCompletion;
use super::account_processor::EnterpriseLoginTarget;
use super::thread_input::ensure_direct_input_allowed;
use super::*;
use codex_config::types::McpServerAuth;
use codex_mcp::McpServerSource;
use codex_mcp::ReadResourceRequestParams;
use codex_mcp::ema_auth_scope;
use codex_mcp::resolve_oauth_callback;
use codex_otel::auth_storage::AuthStorageOriginator;
use codex_rmcp_client::EnterpriseOAuthLoginRequest;
use std::future::Future;
use crate::thread_state::ThreadStateManager;
const MCP_THREAD_ID_META_KEY: &str = "threadId";
@@ -21,26 +16,20 @@ pub(crate) struct McpRequestProcessor {
thread_manager: Arc<ThreadManager>,
pub(super) outgoing: Arc<OutgoingMessageSender>,
config_manager: ConfigManager,
account_processor: Arc<AccountRequestProcessor>,
pub(super) thread_state_manager: ThreadStateManager,
}
impl McpRequestProcessor {
pub(crate) fn new(
auth_manager: Arc<AuthManager>,
thread_manager: Arc<ThreadManager>,
thread_state_manager: ThreadStateManager,
outgoing: Arc<OutgoingMessageSender>,
config_manager: ConfigManager,
account_processor: Arc<AccountRequestProcessor>,
) -> Self {
Self {
auth_manager,
thread_manager,
outgoing,
config_manager,
account_processor,
thread_state_manager,
}
}
@@ -174,97 +163,16 @@ impl McpRequestProcessor {
StreamableHttpRedirectMode::Legacy
};
let server = server.config();
let enterprise = matches!(server.auth, McpServerAuth::EmaAuth);
if matches!(server.auth, McpServerAuth::EmaAuth) {
return Err(invalid_request(format!(
"MCP server '{name}' uses enterprise-managed authorization, which is not supported."
)));
}
let (authorization_url, login_id, completion): (
String,
String,
futures::future::BoxFuture<'static, anyhow::Result<()>>,
) = if enterprise {
let thread_id = thread_id.clone().ok_or_else(|| {
invalid_request("enterprise MCP login requires a connected thread")
})?;
if !mcp_config.xaa_enabled {
return Err(invalid_request(
"enterprise MCP authentication requires `[features].use_xaa = true`",
));
}
if !server.enabled {
return Err(invalid_request(format!("MCP server '{name}' is disabled.")));
}
server
.validate_ema_auth_transport()
.map_err(|reason| invalid_request(format!("MCP server '{name}' {reason}")))?;
if client_registration.is_some() {
return Err(invalid_request(
"enterprise MCP login uses the configured enterprise client and does not support clientRegistration overrides",
));
}
// Resource scopes and per-server callbacks do not alter the shared IdP registration.
let scope = ema_auth_scope(auth.as_ref()).ok_or_else(|| {
invalid_request(
"enterprise MCP authentication requires a signed-in Codex user and workspace",
)
})?;
let idp = server.oauth_idp().ok_or_else(|| {
invalid_request(format!(
"MCP server '{name}' has no configured enterprise IdP"
))
})?;
let registration = server.ema_registration().cloned().ok_or_else(|| {
invalid_request(format!(
"MCP server '{name}' has no validated enterprise registration"
))
})?;
let credential_name = idp.credential_name(&scope);
let http_client =
runtime_context
.resolve_http_client(&name, server)
.map_err(|err| {
internal_error(format!("failed to resolve MCP server runtime: {err}"))
})?;
let login = self
.account_processor
.enterprise_login
.start(
EnterpriseOAuthLoginRequest {
credential_name: &credential_name,
issuer: &idp.issuer,
client_id: &idp.client_id,
client_secret: idp.client_secret.as_ref().map(|secret| secret.as_str()),
token_endpoint_auth_method: idp.token_endpoint_auth_method,
keyring_backend_kind: mcp_config.auth_keyring_backend_kind,
callback_port: mcp_config.mcp_oauth_callback_port,
callback_url: mcp_config.mcp_oauth_callback_url.as_deref(),
timeout_secs,
http_client,
redirect_mode,
},
scope,
EnterpriseLoginTarget {
thread_id,
server_name: name.clone(),
registration,
},
)
.await?;
let mut completion = login.completion;
(
login.authorization_url,
login.login_id,
Box::pin(async move {
match completion.wait_for(|state| state.is_complete()).await {
Ok(result) => match *result {
EnterpriseLoginCompletion::Succeeded => Ok(()),
EnterpriseLoginCompletion::Failed(detail) => Err(detail.into()),
EnterpriseLoginCompletion::Pending => {
Err(anyhow::anyhow!("Enterprise sign-in failed."))
}
},
_ => Err(anyhow::anyhow!("Enterprise sign-in failed.")),
}
}),
)
} else {
) = {
let (url, http_headers, env_http_headers) = match &server.transport {
McpServerTransportConfig::StreamableHttp {
url,
@@ -350,7 +258,7 @@ impl McpRequestProcessor {
Ok(()) => (true, None),
Err(err) => (false, Some(err.to_string())),
};
if success && !enterprise {
if success {
thread_manager.invalidate_mcp_runtimes().await;
}
@@ -432,11 +340,7 @@ impl McpRequestProcessor {
.as_ref()
.map(|thread| thread.mcp_manager())
.unwrap_or_else(|| self.thread_manager.mcp_manager());
self.thread_manager
.runtime_auth_for_mcp_manager(&config, &mcp_manager)
.map_err(|error| internal_error(error.to_string()))?;
let auth = mcp_manager.auth_manager().auth().await;
let runtime_auth = mcp_manager.runtime_auth_for_config(&config);
let (mcp_config, runtime_context) = match thread.as_ref() {
Some(thread) => thread.runtime_mcp_config_and_context(&config).await,
None => (
@@ -447,66 +351,15 @@ impl McpRequestProcessor {
),
),
};
let mut snapshot = collect_mcp_server_status_snapshot_with_detail(
let snapshot = collect_mcp_server_status_snapshot_with_detail(
&mcp_config,
auth.as_ref(),
Some(&self.auth_manager),
runtime_auth,
runtime_context,
mcp_manager.codex_apps_tools_cache(),
mcp_manager.tool_catalog_cache(),
detail,
params.server_name.as_deref(),
)
.await;
if mcp_config.xaa_enabled
&& let Some(thread) = thread.as_ref()
{
// EMA can only use its admitted thread connection. Keep ordinary
// status discovery unchanged and replace the threadless EMA results.
for (name, server) in mcp_config.mcp_server_catalog.configured_servers() {
if !matches!(server.auth, McpServerAuth::EmaAuth) {
continue;
}
let (selected_config, mut selected) = thread
.mcp_server_status_snapshot(
&name,
detail,
mcp_config.mcp_server_catalog.server(&name),
)
.await
.map_err(|error| {
internal_error(format!("failed to read MCP server status: {error:#}"))
})?;
if selected_config.mcp_server_catalog.server(&name)
!= mcp_config.mcp_server_catalog.server(&name)
{
continue;
}
snapshot.server_infos.remove(&name);
snapshot.server_infos.extend(selected.server_infos);
snapshot.server_capabilities.remove(&name);
if let Some(capabilities) = selected.server_capabilities.remove(&name) {
snapshot
.server_capabilities
.insert(name.clone(), capabilities);
}
snapshot.tools_by_server.remove(&name);
snapshot.tools_by_server.extend(selected.tools_by_server);
snapshot.tool_list_meta.remove(&name);
snapshot.tool_list_meta.extend(selected.tool_list_meta);
snapshot.tools_errors.remove(&name);
snapshot.tools_errors.extend(selected.tools_errors);
snapshot.resources.remove(&name);
snapshot.resources.extend(selected.resources);
snapshot.resource_templates.remove(&name);
snapshot
.resource_templates
.extend(selected.resource_templates);
snapshot.auth_statuses.remove(&name);
snapshot.auth_statuses.extend(selected.auth_statuses);
}
}
(Arc::new(mcp_config), snapshot)
};
@@ -621,59 +474,24 @@ impl McpRequestProcessor {
let McpResourceReadParams {
meta,
thread_id,
origin_call_id,
server,
uri,
connector_id,
target,
} = params;
let mut resource_params = ReadResourceRequestParams::new(uri);
let mut meta = meta.unwrap_or_default();
let is_codex_apps = server == codex_mcp::CODEX_APPS_MCP_SERVER_NAME;
let reserved_key = meta.iter().find_map(|(key, value)| match key.as_str() {
"x-codex-turn-metadata"
| MCP_THREAD_ID_META_KEY
| codex_mcp::MCP_CONNECTION_LEASE_META_KEY => Some(key.as_str()),
"connector_id" | "link_id" if is_codex_apps => Some(key.as_str()),
// This legacy routing hint can override an explicit app and account target.
"_codex_apps" if is_codex_apps && value.get("resource_uri").is_some() => {
Some("_codex_apps.resource_uri")
}
_ => None,
let meta = meta.unwrap_or_default();
let reserved_key = meta.keys().find(|key| {
matches!(
key.as_str(),
"x-codex-turn-metadata"
| MCP_THREAD_ID_META_KEY
| codex_mcp::MCP_CONNECTION_LEASE_META_KEY
)
});
if let Some(key) = reserved_key {
return Err(invalid_request(format!(
"reserved resource read metadata key: {key}"
)));
}
if let Some(connector_id) = connector_id {
meta.insert(
"x-codex-turn-metadata".to_string(),
serde_json::json!({
"mcp_request_meta": {"selected_connector_ids": [connector_id]},
}),
);
}
if origin_call_id.is_none()
&& let Some(target) = target
{
if !is_codex_apps
|| target.connector_id.trim().is_empty()
|| target
.link_id
.as_ref()
.is_some_and(|id| id.trim().is_empty() || id.starts_with("synthetic_link::"))
{
return Err(invalid_request(
"target requires codex_apps, a connectorId, and a real linkId or null",
));
}
meta.insert(
"connector_id".to_string(),
serde_json::json!(target.connector_id),
);
meta.insert("link_id".to_string(), serde_json::json!(target.link_id));
}
if !meta.is_empty() {
resource_params.meta = Some(meta.into());
}
@@ -683,35 +501,17 @@ impl McpRequestProcessor {
let request_id = request_id.clone();
let task = async move {
let origin_call_id = origin_call_id.filter(|_| is_codex_apps);
let result = match origin_call_id.as_deref() {
Some(call_id) => {
thread
.read_mcp_resource_for_call(call_id, resource_params)
.await
}
None => thread.read_mcp_resource(&server, resource_params).await,
};
Self::send_mcp_resource_read_response(outgoing, request_id, result, origin_call_id)
.await;
let result = thread.read_mcp_resource(&server, resource_params).await;
Self::send_mcp_resource_read_response(outgoing, request_id, result).await;
};
tokio::spawn(AuthStorageOriginator::current().scope(task));
return Ok(());
}
if origin_call_id.is_some() {
return Err(invalid_request("originCallId requires threadId"));
}
let config = self.load_global_config().await?;
let mcp_manager = self.thread_manager.mcp_manager();
let mcp_config = mcp_manager.runtime_config(&config).await;
let codex_apps_tools_cache = mcp_manager.codex_apps_tools_cache();
let tool_catalog_cache = mcp_manager.tool_catalog_cache();
self.thread_manager
.runtime_auth_for_mcp_manager(&config, &mcp_manager)
.map_err(|error| internal_error(error.to_string()))?;
let runtime_auth = mcp_manager.runtime_auth_for_config(&config);
let auth = mcp_manager.auth_manager().auth().await;
let environment_manager = self.thread_manager.environment_manager();
// This threadless resource-read path has no turn cwd or turn-selected
@@ -725,19 +525,14 @@ impl McpRequestProcessor {
let result = read_mcp_resource_without_thread(
&mcp_config,
auth.as_ref(),
runtime_auth,
runtime_context,
codex_apps_tools_cache,
tool_catalog_cache,
&server,
resource_params,
)
.await
.and_then(|result| serde_json::to_value(result).map_err(anyhow::Error::from));
Self::send_mcp_resource_read_response(
outgoing, request_id, result, /*origin_call_id*/ None,
)
.await;
Self::send_mcp_resource_read_response(outgoing, request_id, result).await;
};
tokio::spawn(AuthStorageOriginator::current().scope(task));
Ok(())
@@ -747,7 +542,6 @@ impl McpRequestProcessor {
outgoing: Arc<OutgoingMessageSender>,
request_id: ConnectionRequestId,
result: anyhow::Result<serde_json::Value>,
origin_call_id: Option<String>,
) {
let result = result
.map_err(mcp_operation_error)
@@ -757,10 +551,6 @@ impl McpRequestProcessor {
"failed to deserialize MCP resource read response: {error}"
))
})
})
.map(|mut response| {
response.origin_call_id = origin_call_id;
response
});
outgoing.send_result(request_id, result).await;
}

View File

@@ -79,7 +79,6 @@ fn turn_context_item(
collaboration_mode: None,
multi_agent_version: None,
realtime_active: None,
cyber_access_program: None,
effort: None,
summary: Some(codex_protocol::config_types::ReasoningSummary::Auto),
})

File diff suppressed because it is too large Load Diff

View File

@@ -1,111 +0,0 @@
//! Exposes shared installed-plugin reconciliation with hook lifecycle updates.
use super::*;
use crate::effective_plugin_change::trust_materialized_plugin_hooks;
use crate::request_serialization::RequestSerializationAccess;
use crate::request_serialization::RequestSerializationQueueKey;
use crate::request_serialization::RequestSerializationQueues;
use codex_app_server_protocol::PluginReconcileChangedPlugin;
use codex_app_server_protocol::PluginReconcileParams;
use codex_app_server_protocol::PluginReconcileResponse;
use codex_core_plugins::remote::RemotePluginShareDiscoverability;
impl PluginRequestProcessor {
#[tracing::instrument(level = "debug", skip_all, fields(reason = ?params.reason))]
pub(crate) async fn plugin_reconcile(
&self,
params: PluginReconcileParams,
config_processor: ConfigRequestProcessor,
request_serialization_queues: &RequestSerializationQueues,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
let config = self.load_latest_config(/*fallback_cwd*/ None).await?;
let plugins_input = config.plugins_config_input();
let auth = self.auth_manager.auth().await;
if !plugins_input.plugins_enabled
|| !auth.as_ref().is_some_and(CodexAuth::uses_codex_backend)
{
return Ok(Some(PluginReconcileResponse::default().into()));
}
// Match background bundle sync: remote_plugin controls catalog visibility, not sync.
// The shared reconciler owns synchronization, auth checks, and cache publication.
let outcome = self
.thread_manager
.plugins_manager()
.reconcile_remote_installed_plugins(&plugins_input, auth.as_ref())
.await
.map_err(|err| {
internal_error(format!(
"failed to reconcile remote installed plugins: {err}"
))
})?;
let hooks_changed = outcome
.changed_plugins
.iter()
.any(|plugin| plugin.capabilities.has_hooks);
// Preserve materialization-owned trust: unchanged background passes cannot recover it.
// Serialize hook updates with config writes, after releasing the bundle writer gate.
// Changes without hooks or eligible materializations still skip this queue.
if hooks_changed
|| outcome.materialized_remote_plugins.iter().any(|plugin| {
plugin.scope == RemotePluginScope::Workspace
&& plugin.discoverability == Some(RemotePluginShareDiscoverability::Listed)
})
{
let materializations = outcome.materialized_remote_plugins.clone();
let processor = self.clone();
let (complete, completion) = tokio::sync::oneshot::channel();
request_serialization_queues
.enqueue_background(
RequestSerializationQueueKey::Global("config"),
RequestSerializationAccess::Exclusive,
async move {
let result = trust_materialized_plugin_hooks(
materializations,
&processor.auth_manager,
&processor.thread_manager,
&processor.config_manager,
&config_processor,
)
.await;
// Removals and disablements have no trust write to rebuild loaded hooks.
// Rebuild after the trust attempt, even if it failed, to drop stale hooks.
if hooks_changed {
processor.thread_manager.refresh_hook_runtimes().await;
}
let _ = complete.send(result);
},
)
.await;
completion
.await
.map_err(|err| {
internal_error(format!("plugin hook trust update was cancelled: {err}"))
})?
.map_err(|err| {
internal_error(format!("failed to trust materialized plugin hooks: {err}"))
})?;
}
Ok(Some(
PluginReconcileResponse {
changed_plugins: outcome
.changed_plugins
.into_iter()
.map(|plugin| PluginReconcileChangedPlugin {
id: plugin.plugin_id,
has_mcps: plugin.capabilities.has_mcps,
has_apps: plugin.capabilities.has_apps,
has_hooks: plugin.capabilities.has_hooks,
has_skills: plugin.capabilities.has_skills,
})
.collect(),
failed_remote_plugin_ids: outcome.failed_remote_plugin_ids,
failed_materialization_remote_plugin_ids: outcome
.failed_materialization_remote_plugin_ids,
}
.into(),
))
}
}

View File

@@ -4,11 +4,8 @@ use codex_app_server_protocol::PluginSearchResponse;
use codex_app_server_protocol::PluginSearchResult;
use codex_app_server_protocol::PluginSearchScope;
use codex_core_plugins::OPENAI_BUNDLED_MARKETPLACE_NAME;
use codex_core_plugins::remote::RemotePluginSearchRequest;
use codex_core_plugins::remote::search_remote_plugins;
use codex_core_plugins::is_openai_curated_marketplace_name;
const DEFAULT_PLUGIN_SEARCH_LIMIT: u32 = 16;
const MAX_PLUGIN_SEARCH_LIMIT: u32 = 1_000;
const MAX_LOCAL_PLUGIN_SEARCH_RESULTS: usize = 100;
const PLUGIN_SEARCH_NO_MATCH_RANK: usize = 6;
@@ -31,14 +28,16 @@ impl PluginRequestProcessor {
scope,
cwds,
cursor,
limit,
// Pagination limits only applied to the removed remote catalog.
limit: _,
} = params;
let search_term = search_term.trim();
let empty_response = || PluginSearchResponse {
data: Vec::new(),
next_cursor: None,
};
if search_term.is_empty() {
// All local results are returned on the first page.
if search_term.is_empty() || cursor.is_some() {
return Ok(empty_response());
}
@@ -48,88 +47,6 @@ impl PluginRequestProcessor {
if !config.features.enabled(Feature::Plugins) {
return Ok(empty_response());
}
let plugin_sharing_enabled = config.features.enabled(Feature::PluginSharing);
let auth = self.auth_manager.auth().await;
let auth_mode = auth.as_ref().map(CodexAuth::api_auth_mode);
let remote_plugin_enabled = config.features.enabled(Feature::RemotePlugin);
let use_remote_global_catalog =
remote_plugin_enabled && auth_mode.is_some_and(DomainAuthMode::uses_codex_backend);
let remote_scope = if remote_plugin_enabled {
Some(scope.map(|scope| match scope {
PluginSearchScope::Global => RemotePluginScope::Global,
PluginSearchScope::Workspace => RemotePluginScope::Workspace,
PluginSearchScope::Personal => RemotePluginScope::User,
}))
} else {
match scope {
None | Some(PluginSearchScope::Workspace) => {
Some(Some(RemotePluginScope::Workspace))
}
Some(PluginSearchScope::Global | PluginSearchScope::Personal) => None,
}
};
let limit = limit
.unwrap_or(DEFAULT_PLUGIN_SEARCH_LIMIT)
.clamp(1, MAX_PLUGIN_SEARCH_LIMIT);
let mut next_cursor = None;
let mut remote_results = Vec::new();
if auth_mode.is_some_and(DomainAuthMode::uses_codex_backend)
&& let Some(remote_scope) = remote_scope
{
let page = search_remote_plugins(
&remote_plugin_service_config(&self.thread_manager, &config)?,
auth.as_ref(),
RemotePluginSearchRequest {
query: search_term,
scope: remote_scope,
limit,
page_token: cursor.as_deref(),
},
)
.await
.map_err(|err| {
remote_plugin_catalog_error_to_jsonrpc(err, "search remote plugin catalog")
})?;
next_cursor = page.next_page_token;
remote_results.reserve(page.plugins.len());
let plugin_policy = &config.plugins;
for plugin in page.plugins {
let plugin_id = PluginId::parse(&plugin.id).map_err(|err| {
internal_error(format!("invalid remote plugin search result id: {err}"))
})?;
// NOTE: (brisebois) filter out plugins from the results that belong to "shared"
// marketplaces if plugin sharing is disabled. There is a chance that this filters
// out all results and returns an empty list to the client. Ideally this filtering
// would be done server-side to avoid this problem.
if !plugin_sharing_enabled
&& matches!(
plugin_id.marketplace_name.as_str(),
REMOTE_WORKSPACE_SHARED_WITH_ME_MARKETPLACE_NAME
| REMOTE_WORKSPACE_SHARED_WITH_ME_PRIVATE_MARKETPLACE_NAME
| REMOTE_WORKSPACE_SHARED_WITH_ME_UNLISTED_MARKETPLACE_NAME
)
{
continue;
}
remote_results.push(plugin_search_result(
remote_plugin_summary_to_info(plugin, plugin_policy),
plugin_id.marketplace_name,
/*marketplace_path*/ None,
));
}
}
// All local results are stitched into the first page; if
// we are not on the first page, don't even check local
if cursor.is_some() {
return Ok(PluginSearchResponse {
data: remote_results,
next_cursor,
});
}
let normalized_search_term = normalize_search_text(search_term);
let mut local_results = Vec::new();
@@ -137,19 +54,11 @@ impl PluginRequestProcessor {
let roots = cwds.unwrap_or_default();
let plugins_input = config.plugins_config_input();
let plugins_manager = self.thread_manager.plugins_manager();
let shared_plugin_ids_by_local_path = load_shared_plugin_ids_by_local_path(&config)
.unwrap_or_else(|err| {
warn!(
error = %err.message,
"plugin/search could not load shared plugin identities"
);
Default::default()
});
let outcome = tokio::task::spawn_blocking(move || {
plugins_manager.list_marketplaces_for_config(
&plugins_input,
&roots,
/*include_openai_curated*/ !use_remote_global_catalog,
/*include_openai_curated*/ true,
)
})
.await
@@ -170,10 +79,7 @@ impl PluginRequestProcessor {
}
for plugin in marketplace.plugins {
let plugin = convert_configured_marketplace_plugin_to_plugin_summary(
plugin,
&shared_plugin_ids_by_local_path,
);
let plugin = convert_configured_marketplace_plugin_to_plugin_summary(plugin);
local_results.push(plugin_search_result(
plugin,
marketplace.name.clone(),
@@ -183,60 +89,19 @@ impl PluginRequestProcessor {
}
}
let mut data = Vec::with_capacity(
local_results.len().min(MAX_LOCAL_PLUGIN_SEARCH_RESULTS) + remote_results.len(),
);
let mut local_matches = Vec::new();
let mut remote_results = remote_results.into_iter().map(Some).collect::<Vec<_>>();
let mut seen_local_plugin_identities = HashSet::new();
for local_result in local_results {
let local_remote_plugin_id =
local_result.plugin.remote_plugin_id.as_deref().or_else(|| {
local_result
.plugin
.share_context
.as_ref()
.map(|context| context.remote_plugin_id.as_str())
});
let remote_result_index = remote_results.iter().position(|remote_result| {
remote_result.as_ref().is_some_and(|remote_result| {
local_remote_plugin_id.is_some_and(|remote_plugin_id| {
remote_result.plugin.remote_plugin_id.as_deref() == Some(remote_plugin_id)
}) || local_result.plugin.id == remote_result.plugin.id
|| (is_openai_curated_marketplace_name(&local_result.marketplace_name)
&& remote_result.marketplace_name == REMOTE_GLOBAL_MARKETPLACE_NAME
&& local_result.plugin.name == remote_result.plugin.name)
})
});
if remote_result_index.is_none()
&& plugin_search_match_rank(&local_result.plugin, &normalized_search_term).is_none()
{
if plugin_search_match_rank(&local_result.plugin, &normalized_search_term).is_none() {
continue;
}
let local_identity = local_remote_plugin_id.map_or_else(
|| {
if is_openai_curated_marketplace_name(&local_result.marketplace_name) {
format!("curated:{}", local_result.plugin.name)
} else {
format!("plugin:{}", local_result.plugin.id)
}
},
|remote_plugin_id| format!("remote:{remote_plugin_id}"),
);
if !seen_local_plugin_identities.insert(local_identity) {
continue;
}
if let Some(remote_result_index) = remote_result_index
&& let Some(mut remote_result) = remote_results[remote_result_index].take()
{
remote_result.plugin.installed = local_result.plugin.installed;
remote_result.plugin.local_version = local_result.plugin.local_version;
data.push(remote_result);
} else {
let local_identity =
if is_openai_curated_marketplace_name(&local_result.marketplace_name) {
format!("curated:{}", local_result.plugin.name)
} else {
format!("plugin:{}", local_result.plugin.id)
};
if seen_local_plugin_identities.insert(local_identity) {
local_matches.push(local_result);
}
}
@@ -246,14 +111,11 @@ impl PluginRequestProcessor {
.unwrap_or(PLUGIN_SEARCH_NO_MATCH_RANK)
});
local_matches.truncate(MAX_LOCAL_PLUGIN_SEARCH_RESULTS);
data.extend(local_matches);
data.extend(remote_results.into_iter().flatten());
data.sort_by_key(|result| {
plugin_search_match_rank(&result.plugin, &normalized_search_term)
.unwrap_or(PLUGIN_SEARCH_NO_MATCH_RANK)
});
Ok(PluginSearchResponse { data, next_cursor })
Ok(PluginSearchResponse {
data: local_matches,
next_cursor: None,
})
}
}
@@ -283,7 +145,6 @@ fn marketplace_matches_search_scope(
OPENAI_BUNDLED_MARKETPLACE_NAME
| "openai-bundled-alpha"
| "codex-official"
| "openai-curated-remote"
| "openai-primary-runtime"
);

View File

@@ -10,7 +10,6 @@ use crate::config_manager::ConfigManager;
use crate::outgoing_message::OutgoingEnvelope;
use crate::outgoing_message::OutgoingMessage;
use crate::thread_sample::SampleResponseRegistry;
use crate::thread_state::ConnectionCapabilities;
use crate::thread_state::PendingNetworkApproval;
use crate::thread_state::resolve_server_request_on_thread_listener;
use anyhow::Context;
@@ -99,7 +98,7 @@ async fn listener_shutdown_releases_runtime_and_preserves_other_subscribers(
];
for &connection_id in &connection_ids {
processor
.connection_initialized(connection_id, ConnectionCapabilities::default())
.connection_initialized(connection_id)
.await;
}
let network_request_id = RequestId::Integer(4);

View File

@@ -4,11 +4,6 @@ mod daemon_continuation;
#[path = "daemon_snapshot.rs"]
mod daemon_snapshot;
mod workspace_switching;
#[path = "thread_resume_account.rs"]
mod thread_resume_account;
use super::persisted_resume_settings::PersistedResumeSettings;
use super::persisted_resume_settings::latest_owned_thread_settings;
use super::persisted_resume_settings::latest_persisted_model_settings;
@@ -1296,7 +1291,6 @@ impl ThreadRequestProcessor {
session_start_source,
thread_source,
project_id,
daybreak_enabled,
environments,
} = params;
if matches!(
@@ -1381,7 +1375,6 @@ impl ThreadRequestProcessor {
session_start_source,
thread_source.map(Into::into),
project_id,
daybreak_enabled,
environment_requests,
service_name,
allow_provider_model_fallback,
@@ -1463,7 +1456,6 @@ impl ThreadRequestProcessor {
session_start_source: Option<codex_app_server_protocol::ThreadStartSource>,
thread_source: Option<codex_protocol::protocol::ThreadSource>,
project_id: Option<String>,
daybreak_enabled: Option<bool>,
environment_requests: Option<Vec<TurnEnvironmentRequest>>,
service_name: Option<String>,
allow_provider_model_fallback: bool,
@@ -1477,11 +1469,6 @@ impl ThreadRequestProcessor {
.load_with_overrides(config_overrides.clone(), typesafe_overrides.clone())
.await
.map_err(|err| config_load_error(&err))?;
if config.ephemeral && daybreak_enabled.is_some() {
return Err(invalid_request(
"daybreakEnabled is not supported for ephemeral threads",
));
}
// Project-local config can launch host processes, so only the effective
// permissions after managed constraints can imply project trust.
let effective_permission_profile = config.permissions.effective_permission_profile();
@@ -1611,7 +1598,6 @@ impl ThreadRequestProcessor {
thread_store.as_ref(),
StoreThreadMetadataPatch {
project_id: project_id.clone().map(Some),
daybreak_enabled,
..Default::default()
},
"thread/start",
@@ -1622,7 +1608,7 @@ impl ThreadRequestProcessor {
.unwrap_or_else(|| listener_task_context.thread_manager.reserve_thread_id());
start_options.reserved_thread_id = Some(thread_id);
// Startup can prewarm the Responses socket before start_thread returns.
// Register the creating client first so that handshake can request attestation.
// Register the creating client first so it observes the startup handshake.
listener_task_context
.thread_state_manager
.try_add_connection_to_thread(thread_id, request_id.connection_id)
@@ -1706,7 +1692,6 @@ impl ThreadRequestProcessor {
session_configured.rollout_path.clone(),
);
thread.project_id = project_id.clone();
thread.daybreak_enabled = daybreak_enabled;
// Auto-attach a thread listener when starting a thread.
log_listener_attach_result(
@@ -2057,7 +2042,6 @@ impl ThreadRequestProcessor {
thread_id,
project_id,
git_info,
daybreak_enabled,
} = params;
let thread_uuid = ThreadId::from_string(&thread_id)
.map_err(|err| invalid_request(format!("invalid thread id: {err}")))?;
@@ -2080,7 +2064,7 @@ impl ThreadRequestProcessor {
}
}
if git_info.is_none() && project_id.is_none() && daybreak_enabled.is_none() {
if git_info.is_none() && project_id.is_none() {
return Err(invalid_request(
"thread metadata update must include at least one field",
));
@@ -2158,7 +2142,6 @@ impl ThreadRequestProcessor {
let patch = StoreThreadMetadataPatch {
git_info,
project_id: project_update.clone(),
daybreak_enabled,
..Default::default()
};
let updated_thread = self
@@ -2283,15 +2266,7 @@ impl ThreadRequestProcessor {
"thread/revert only supports paginated threads",
));
}
let mut config = thread.config().await.as_ref().clone();
// Give the replacement its own pending lifetime before removal revokes the old runtime.
let ema_cancellation = config
.config_layer_stack
.mcp_ema_cancellation()
.for_startup();
config.config_layer_stack = config
.config_layer_stack
.with_mcp_ema_cancellation(ema_cancellation);
let config = thread.config().await.as_ref().clone();
let runtime_snapshot = ThreadRevertRuntimeSnapshot {
config,
settings: thread.restorable_thread_settings().await,
@@ -3128,17 +3103,6 @@ impl ThreadRequestProcessor {
thread_id: ThreadId,
include_turns: bool,
) -> Result<Thread, ThreadReadViewError> {
// Read staging first: persistence can consume it while the stored thread is read.
let pending_daybreak_enabled = self
.thread_store
.read_pending_thread_metadata(thread_id)
.await
.map_err(|err| {
ThreadReadViewError::Internal(format!(
"failed to read pending thread metadata: {err}"
))
})?
.and_then(|metadata| metadata.daybreak_enabled);
let loaded_thread = self.thread_manager.get_thread(thread_id).await.ok();
let mut thread = if include_turns {
if let Some(loaded_thread) = loaded_thread.as_ref() {
@@ -3192,8 +3156,6 @@ impl ThreadRequestProcessor {
)));
};
thread.daybreak_enabled = thread.daybreak_enabled.or(pending_daybreak_enabled);
let has_live_in_progress_turn = if let Some(loaded_thread) = loaded_thread.as_ref() {
matches!(loaded_thread.agent_status().await, AgentStatus::Running)
} else {
@@ -3920,13 +3882,9 @@ impl ThreadRequestProcessor {
self.thread_manager.subscribe_thread_created()
}
pub(crate) async fn connection_initialized(
&self,
connection_id: ConnectionId,
capabilities: ConnectionCapabilities,
) {
pub(crate) async fn connection_initialized(&self, connection_id: ConnectionId) {
self.thread_state_manager
.connection_initialized(connection_id, capabilities)
.connection_initialized(connection_id)
.await;
}
@@ -4074,12 +4032,6 @@ impl ThreadRequestProcessor {
.await?
}
};
thread_resume_account::check(
&self.config.features,
app_server_client_name.as_deref(),
&self.auth_manager,
&stored_thread,
)?;
let (thread_history, stored_thread) = self
.load_resume_initial_history_from_stored_thread(
stored_thread,
@@ -4726,12 +4678,6 @@ impl ThreadRequestProcessor {
};
if let Some((existing_thread_id, existing_thread, mut source_thread)) = running_thread {
thread_resume_account::check(
&self.config.features,
app_server_client_name.as_deref(),
&self.auth_manager,
&source_thread,
)?;
let paginated_resume =
matches!(source_thread.history_mode, ThreadHistoryMode::Paginated);
let existing_thread_rollout_path = existing_thread.rollout_path();
@@ -5736,7 +5682,6 @@ impl ThreadRequestProcessor {
self.thread_store.as_ref(),
StoreThreadMetadataPatch {
project_id: inherited_project_id.clone().map(Some),
daybreak_enabled: source_thread.daybreak_enabled,
..Default::default()
},
"thread/fork",
@@ -6043,8 +5988,8 @@ impl ThreadRequestProcessor {
return None;
}
Some(LocalHistoryAccount {
user_id: auth.as_ref().and_then(CodexAuth::get_chatgpt_user_id),
account_id: auth.as_ref().and_then(CodexAuth::get_account_id),
user_id: None,
account_id: None,
})
}
@@ -6749,7 +6694,6 @@ fn thread_from_stored_thread(
thread_source: thread.thread_source.map(Into::into),
git_info,
name: thread.name,
daybreak_enabled: thread.daybreak_enabled,
turns: Vec::new(),
};
(thread, history)
@@ -6935,7 +6879,6 @@ fn build_thread_from_snapshot(
thread_source: config_snapshot.thread_source.clone().map(Into::into),
git_info: None,
name: None,
daybreak_enabled: None,
turns: Vec::new(),
}
}

View File

@@ -1,34 +0,0 @@
//! Unloads old-workspace runtimes while turn admission is paused by the account switch.
//! Resuming a thread builds fresh policy and transport state for the new workspace.
use super::*;
impl ThreadRequestProcessor {
pub(crate) async fn unload_for_workspace_switch(&self) -> Result<(), JSONRPCErrorError> {
let report = self
.thread_manager
.shutdown_all_threads_bounded(Duration::from_secs(/*secs*/ 10))
.await;
for thread_id in report.completed {
self.finalize_thread_teardown(thread_id).await;
self.outgoing
.send_server_notification(ServerNotification::ThreadClosed(
codex_app_server_protocol::ThreadClosedNotification {
thread_id: thread_id.to_string(),
},
))
.await;
}
// A delegated child may have started while its parent was shutting down.
// Never replace credentials until every runtime has stopped.
if !report.submit_failed.is_empty()
|| !report.timed_out.is_empty()
|| !self.thread_manager.list_thread_ids().await.is_empty()
{
return Err(internal_error(
"Some threads are still running; retry the workspace switch",
));
}
Ok(())
}
}

View File

@@ -155,7 +155,6 @@ mod thread_processor_behavior_tests {
use codex_app_server_protocol::ThreadItem;
use codex_app_server_protocol::ThreadItemPayload;
use codex_app_server_protocol::ToolRequestUserInputParams;
use codex_config::CloudConfigBundleLoader;
use codex_config::LoaderOverrides;
use codex_config::SessionThreadConfig;
use codex_config::StaticThreadConfigLoader;
@@ -523,7 +522,6 @@ mod thread_processor_behavior_tests {
section_position: None,
section_entered_at: None,
project_id: None,
daybreak_enabled: None,
cwd: PathBuf::from("/tmp"),
cli_version: "0.0.0".to_string(),
source: SessionSource::Cli,
@@ -553,34 +551,7 @@ mod thread_processor_behavior_tests {
}
#[test]
fn config_load_error_marks_cloud_config_bundle_failures_for_relogin() {
let err = std::io::Error::other(CloudConfigBundleLoadError::new(
CloudConfigBundleLoadErrorCode::Auth,
Some(401),
"Your authentication session could not be refreshed automatically. Please log out and sign in again.",
));
let error = config_load_error(&err);
assert_eq!(
error.data,
Some(json!({
"reason": "cloudConfigBundle",
"errorCode": "Auth",
"action": "relogin",
"statusCode": 401,
"detail": "Your authentication session could not be refreshed automatically. Please log out and sign in again.",
}))
);
assert!(
error.message.contains("failed to load configuration"),
"unexpected error message: {}",
error.message
);
}
#[test]
fn config_load_error_leaves_non_cloud_config_bundle_failures_unmarked() {
fn config_load_error_leaves_generic_failures_unmarked() {
let err = std::io::Error::other("required MCP servers failed to initialize");
let error = config_load_error(&err);
@@ -593,46 +564,6 @@ mod thread_processor_behavior_tests {
);
}
#[test]
fn config_load_error_marks_non_auth_cloud_config_bundle_failures_without_relogin() {
let err = std::io::Error::other(CloudConfigBundleLoadError::new(
CloudConfigBundleLoadErrorCode::RequestFailed,
/*status_code*/ None,
"Failed to load cloud config bundle (workspace-managed policies).",
));
let error = config_load_error(&err);
assert_eq!(
error.data,
Some(json!({
"reason": "cloudConfigBundle",
"errorCode": "RequestFailed",
"detail": "Failed to load cloud config bundle (workspace-managed policies).",
}))
);
}
#[test]
fn config_load_error_marks_invalid_cloud_config_bundle_failures_without_relogin() {
let err = std::io::Error::other(CloudConfigBundleLoadError::new(
CloudConfigBundleLoadErrorCode::InvalidBundle,
/*status_code*/ None,
"invalid cloud config bundle: invalid cloud config fragment Base policy (cfg_123)",
));
let error = config_load_error(&err);
assert_eq!(
error.data,
Some(json!({
"reason": "cloudConfigBundle",
"errorCode": "InvalidBundle",
"detail": "invalid cloud config bundle: invalid cloud config fragment Base policy (cfg_123)",
}))
);
}
#[tokio::test]
async fn derive_config_from_params_uses_session_thread_config_model_provider() -> Result<()> {
let temp_dir = TempDir::new()?;
@@ -668,7 +599,6 @@ mod thread_processor_behavior_tests {
Vec::new(),
LoaderOverrides::default(),
/*strict_config*/ false,
CloudConfigBundleLoader::default(),
Arg0DispatchPaths::default(),
Arc::new(StaticThreadConfigLoader::new(vec![
ThreadConfigSource::Session(SessionThreadConfig {
@@ -1241,7 +1171,7 @@ mod thread_processor_behavior_tests {
let (cancel_tx, cancel_rx) = oneshot::channel();
manager
.connection_initialized(connection, ConnectionCapabilities::default())
.connection_initialized(connection)
.await;
assert!(
manager
@@ -1289,10 +1219,10 @@ mod thread_processor_behavior_tests {
let (cancel_tx, mut cancel_rx) = oneshot::channel();
manager
.connection_initialized(connection_a, ConnectionCapabilities::default())
.connection_initialized(connection_a)
.await;
manager
.connection_initialized(connection_b, ConnectionCapabilities::default())
.connection_initialized(connection_b)
.await;
assert!(
manager
@@ -1334,10 +1264,10 @@ mod thread_processor_behavior_tests {
let connection_b = ConnectionId(2);
manager
.connection_initialized(connection_a, ConnectionCapabilities::default())
.connection_initialized(connection_a)
.await;
manager
.connection_initialized(connection_b, ConnectionCapabilities::default())
.connection_initialized(connection_b)
.await;
assert!(
manager
@@ -1381,7 +1311,7 @@ mod thread_processor_behavior_tests {
let thread_id = ThreadId::from_string("ba62fd70-2ec2-4b1b-9d94-355694332dd2")?;
let connection = ConnectionId(1);
manager
.connection_initialized(connection, ConnectionCapabilities::default())
.connection_initialized(connection)
.await;
let wait_for_subscriber = manager.wait_for_thread_subscriber(thread_id);
@@ -1407,7 +1337,7 @@ mod thread_processor_behavior_tests {
let connection = ConnectionId(1);
manager
.connection_initialized(connection, ConnectionCapabilities::default())
.connection_initialized(connection)
.await;
let threads_to_unload = manager.remove_connection(connection).await;
assert_eq!(threads_to_unload, Vec::<ThreadId>::new());
@@ -1421,78 +1351,4 @@ mod thread_processor_behavior_tests {
Ok(())
}
#[tokio::test]
async fn first_attestation_capable_connection_for_thread_only_uses_thread_subscribers()
-> Result<()> {
let manager = ThreadStateManager::new();
let thread_id = ThreadId::from_string("dfbd9a95-2f44-470a-8bd8-1cfc04efc243")?;
let other_thread_id = ThreadId::from_string("6c9a74e4-5e59-479e-90bf-5c5798bb50aa")?;
let unrelated_supported_connection = ConnectionId(1);
let earlier_supported_connection = ConnectionId(2);
let later_supported_connection = ConnectionId(3);
let unsupported_connection = ConnectionId(4);
manager
.connection_initialized(
unrelated_supported_connection,
ConnectionCapabilities {
request_attestation: true,
},
)
.await;
manager
.connection_initialized(
earlier_supported_connection,
ConnectionCapabilities {
request_attestation: true,
},
)
.await;
manager
.connection_initialized(
later_supported_connection,
ConnectionCapabilities {
request_attestation: true,
},
)
.await;
manager
.connection_initialized(unsupported_connection, ConnectionCapabilities::default())
.await;
assert!(
manager
.try_add_connection_to_thread(other_thread_id, unrelated_supported_connection)
.await
);
assert!(
manager
.try_add_connection_to_thread(thread_id, later_supported_connection)
.await
);
assert!(
manager
.try_add_connection_to_thread(thread_id, earlier_supported_connection)
.await
);
assert!(
manager
.try_add_connection_to_thread(thread_id, unsupported_connection)
.await
);
assert_eq!(
manager
.first_attestation_capable_connection_for_thread(thread_id)
.await,
Some(earlier_supported_connection)
);
assert_eq!(
manager
.first_attestation_capable_connection_for_thread(other_thread_id)
.await,
Some(unrelated_supported_connection)
);
Ok(())
}
}

View File

@@ -1,46 +0,0 @@
//! Applies the rollout-gated CLI account check before resuming or attaching to a local thread.
//! Creator tags are immutable; untagged threads and other clients retain existing behavior.
use crate::error_code::invalid_request;
use codex_app_server_protocol::JSONRPCErrorError;
use codex_features::Feature;
use codex_features::Features;
use codex_login::AuthManager;
use codex_login::CodexAuth;
use codex_thread_store::StoredThread;
pub(super) fn check(
features: &Features,
client_name: Option<&str>,
auth_manager: &AuthManager,
thread: &StoredThread,
) -> Result<(), JSONRPCErrorError> {
if !features.enabled(Feature::CliResumeAccountCheck)
|| !matches!(client_name, Some("codex-tui" | "codex_exec"))
|| thread.rollout_path.is_none()
|| (thread.creator_user_id.is_none() && thread.creator_account_id.is_none())
{
return Ok(());
}
let Some(auth) = auth_manager
.auth_cached()
.filter(CodexAuth::is_chatgpt_auth)
else {
// API keys and other auth modes do not identify a comparable ChatGPT account.
return Ok(());
};
if thread
.creator_user_id
.as_ref()
.is_some_and(|creator| auth.get_chatgpt_user_id().as_ref() != Some(creator))
|| thread
.creator_account_id
.as_ref()
.is_some_and(|creator| auth.get_account_id().as_ref() != Some(creator))
{
return Err(invalid_request(
"This thread was created with a different ChatGPT account or workspace. Sign in with the original account to resume it.",
));
}
Ok(())
}

View File

@@ -226,7 +226,6 @@ mod tests {
section: None,
section_entered_at: None,
project_id: None,
daybreak_enabled: None,
history_mode: Default::default(),
model_provider: "mock_provider".to_string(),
model: None,

View File

@@ -1,5 +1,7 @@
use super::*;
#[cfg(test)]
use std::io::Error as IoError;
#[cfg(test)]
use chrono::DateTime;
#[cfg(test)]
use chrono::Utc;
@@ -290,7 +292,6 @@ pub(crate) fn summary_to_thread(
thread_source: None,
git_info,
name: None,
daybreak_enabled: None,
turns: Vec::new(),
}
}

View File

@@ -653,7 +653,6 @@ impl TurnRequestProcessor {
final_output_json_schema: params.output_schema,
service_tier: params.service_tier_for_turn,
prompt_cache_ttl: None,
cyber_access_program: params.cyber_access_program.map(Into::into),
..Default::default()
})
.with_additional_context(additional_context)

View File

@@ -125,13 +125,6 @@ impl QueuedInitializedRequest {
}
}
fn new_background(future: impl Future<Output = ()> + Send + 'static) -> Self {
Self {
gate: None,
future: Box::pin(future),
}
}
pub(crate) async fn run(self) {
let Self { gate, future } = self;
match gate {
@@ -176,21 +169,6 @@ impl RequestSerializationQueues {
}
}
/// Enqueue app-owned work alongside RPCs that mutate the same serialized resource.
pub(crate) async fn enqueue_background(
&self,
key: RequestSerializationQueueKey,
access: RequestSerializationAccess,
future: impl Future<Output = ()> + Send + 'static,
) {
self.enqueue(
key,
access,
QueuedInitializedRequest::new_background(future),
)
.await;
}
pub(crate) async fn enqueue(
&self,
key: RequestSerializationQueueKey,

View File

@@ -17,8 +17,6 @@ use codex_login::default_client::SetOriginatorError;
use codex_login::default_client::USER_AGENT_SUFFIX;
use codex_login::default_client::set_default_client_residency_requirement;
use codex_login::default_client::set_default_originator;
use codex_login::is_workload_identity_selected;
use codex_login::read_codex_access_token_from_env;
use codex_utils_cli::CliConfigOverrides;
use serde::Serialize;
use std::io;
@@ -83,13 +81,6 @@ async fn read_startup_config(
strict_config: bool,
startup: StartupConfigArgs,
) -> Result<StartupConfig, JSONRPCErrorError> {
if startup.startup_sign_out
&& (is_workload_identity_selected() || read_codex_access_token_from_env().is_some())
{
return Err(crate::error_code::invalid_request(
"Configured external authentication is owned by the app-server host and cannot be changed during startup recovery.",
));
}
if let Some(client) = startup.startup_client_info {
match set_default_originator(client.name.clone()) {
Ok(()) | Err(SetOriginatorError::AlreadyInitialized) => {}
@@ -114,7 +105,6 @@ async fn read_startup_config(
overrides,
loader_overrides,
strict_config,
Default::default(),
arg0_paths,
Arc::new(NoopThreadConfigLoader),
);
@@ -133,7 +123,6 @@ async fn read_startup_config(
// Preserve local credential authority while using the effective HTTP route.
let mut auth_config = loaded.bootstrap.auth_config();
auth_config.auth_route_config = config.auth_route_config();
auth_config.chatgpt_base_url = Some(config.chatgpt_base_url.clone());
let auth = AuthManager::shared_from_auth_config(
auth_config,
/*enable_codex_api_key_env*/ false,
@@ -143,7 +132,6 @@ async fn read_startup_config(
set_default_client_residency_requirement(config.enforce_residency.value());
let config = logout_configured_account(&manager, &auth, &config).await?;
clear_account_configuration(&manager, &config).await?;
manager.update_managed_config_loader(Arc::clone(&auth), &config);
manager
.load_latest_config(cwd)
.await
@@ -157,10 +145,9 @@ async fn read_startup_config(
.map_err(startup_error)?;
let auth_config = config.auth_config();
auth_config.validate().map_err(startup_error)?;
let allowed_login_methods = auth_config.managed_auth_policy.allowed_login_methods(
auth_config.forced_login_method,
auth_config.forced_chatgpt_workspace_id.as_deref(),
);
let allowed_login_methods = auth_config
.managed_auth_policy
.allowed_login_methods(auth_config.forced_login_method);
let requirements = config.config_layer_stack.requirements_toml();
Ok(StartupConfig {
app_server_version: env!("CARGO_PKG_VERSION"),

View File

@@ -388,16 +388,11 @@ impl ThreadEntry {
#[derive(Default)]
struct ThreadStateManagerInner {
live_connections: HashMap<ConnectionId, ConnectionCapabilities>,
live_connections: HashSet<ConnectionId>,
threads: HashMap<ThreadId, ThreadEntry>,
thread_ids_by_connection: HashMap<ConnectionId, HashSet<ThreadId>>,
}
#[derive(Clone, Copy, Default)]
pub(crate) struct ConnectionCapabilities {
pub(crate) request_attestation: bool,
}
#[derive(Clone, Default)]
pub(crate) struct ThreadStateManager {
state: Arc<Mutex<ThreadStateManagerInner>>,
@@ -448,37 +443,14 @@ impl ThreadStateManager {
Self::default()
}
pub(crate) async fn connection_initialized(
&self,
connection_id: ConnectionId,
capabilities: ConnectionCapabilities,
) {
pub(crate) async fn connection_initialized(&self, connection_id: ConnectionId) {
self.state
.lock()
.await
.live_connections
.insert(connection_id, capabilities);
.insert(connection_id);
}
pub(crate) async fn first_attestation_capable_connection_for_thread(
&self,
thread_id: ThreadId,
) -> Option<ConnectionId> {
let state = self.state.lock().await;
state
.threads
.get(&thread_id)?
.connection_ids
.iter()
.filter_map(|connection_id| {
state
.live_connections
.get(connection_id)?
.request_attestation
.then_some(*connection_id)
})
.min_by_key(|connection_id| connection_id.0)
}
pub(crate) async fn wait_for_thread_subscriber(&self, thread_id: ThreadId) {
let mut has_connections = {
@@ -692,11 +664,11 @@ impl ThreadStateManager {
}
let attached = connection_ids
.iter()
.any(|connection_id| live_connections.contains_key(connection_id));
.any(|connection_id| live_connections.contains(connection_id));
let installed = install(attached)?;
let entry = slot.or_insert_with(|| ThreadEntry::new(Arc::clone(candidate.state())));
for &connection_id in connection_ids {
if live_connections.contains_key(&connection_id) {
if live_connections.contains(&connection_id) {
thread_ids_by_connection
.entry(connection_id)
.or_default()
@@ -718,7 +690,7 @@ impl ThreadStateManager {
connection_id: ConnectionId,
) -> bool {
let mut state = self.state.lock().await;
if !state.live_connections.contains_key(&connection_id) {
if !state.live_connections.contains(&connection_id) {
return false;
}
state

View File

@@ -6,13 +6,11 @@ use std::sync::Arc;
use std::sync::Mutex;
use tokio::sync::watch;
use crate::error_code::invalid_request;
use crate::error_code::server_draining_error;
#[derive(Debug, Default)]
struct AdmissionState {
closed: bool,
paused: bool,
active: usize,
}
@@ -32,32 +30,8 @@ impl Default for TurnAdmission {
}
pub(crate) struct TurnPermit(TurnAdmission);
pub(crate) struct TurnAdmissionPause(TurnAdmission);
impl TurnAdmission {
pub(crate) async fn pause(&self) -> Result<TurnAdmissionPause, JSONRPCErrorError> {
let mut active = self.subscribe_active();
{
let mut state = self
.state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if state.closed || state.paused {
return Err(invalid_request("Runtime changes are already paused"));
}
state.paused = true;
}
let pause = TurnAdmissionPause(self.clone());
tokio::time::timeout(
std::time::Duration::from_secs(/*secs*/ 10),
active.wait_for(|active| *active == 0),
)
.await
.map_err(|_| invalid_request("Work is still starting; retry the workspace switch"))?
.map_err(|_| invalid_request("Turn admission is unavailable"))?;
Ok(pause)
}
pub(crate) fn begin_drain(&self) {
self.state
.lock()
@@ -79,27 +53,12 @@ impl TurnAdmission {
if state.closed {
return Err(server_draining_error());
}
if state.paused {
return Err(invalid_request(
"Workspace change in progress; retry when it completes",
));
}
state.active += 1;
self.active_tx.send_replace(state.active);
Ok(TurnPermit(self.clone()))
}
}
impl Drop for TurnAdmissionPause {
fn drop(&mut self) {
self.0
.state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.paused = false;
}
}
impl TurnStartAdmission for TurnAdmission {
fn admit_turn_start(&self) -> Option<Box<dyn Send>> {
self.admit()

View File

@@ -26,26 +26,3 @@ fn drain_rejects_new_work_without_waiting_for_admitted_work() {
drop(automatic);
assert_eq!(*active.borrow(), 0);
}
#[tokio::test]
async fn workspace_pause_waits_for_admitted_work_and_preserves_shutdown_drain() {
let admission = TurnAdmission::default();
let in_flight = admission.admit().unwrap();
let pending_pause = admission.pause();
tokio::pin!(pending_pause);
tokio::select! {
biased;
_ = &mut pending_pause => panic!("pause completed before the existing request"),
() = async {} => {}
}
assert!(admission.admit().is_err());
assert!(admission.admit_turn_start().is_none());
drop(in_flight);
let pause = pending_pause.await.unwrap();
drop(pause);
drop(admission.admit().unwrap());
let pause = admission.pause().await.unwrap();
admission.begin_drain();
drop(pause);
assert!(admission.admit().is_err());
}

View File

@@ -128,9 +128,19 @@ impl GuardedResponse {
}
fn identity(auth_manager: &AuthManager) -> Option<String> {
auth_manager.auth_cached()?.get_chatgpt_account_user_id()
credential_identity(&auth_manager.auth_cached()?)
}
/// Local identity of the selected credential. Stored credentials carry no account,
/// so verification is bound to a one-way digest of the bearer credential itself:
/// replacing or removing the credential changes the owner.
pub(crate) fn credential_identity(auth: &codex_login::CodexAuth) -> Option<String> {
use sha2::Digest;
let token = auth.get_token().ok().filter(|token| !token.is_empty())?;
Some(format!("{:x}", sha2::Sha256::digest(token.as_bytes())))
}
enum NativeOperation {
Status,
Enroll,

View File

@@ -6,8 +6,7 @@ use super::*;
#[derive(Clone, PartialEq, Eq)]
pub(super) struct Identity {
user_id: String,
account_id: String,
credential: String,
}
impl OutgoingMessageSender {
@@ -60,8 +59,7 @@ impl OutgoingMessageSender {
pub(super) fn verification_identity(&self) -> Option<Identity> {
let auth = self.verification_auth.get()?.auth_cached()?;
Some(Identity {
user_id: auth.get_chatgpt_user_id()?,
account_id: auth.get_account_id()?,
credential: crate::user_verification::credential_identity(&auth)?,
})
}

View File

@@ -1,6 +1,4 @@
use super::*;
use app_test_support::ChatGptAuthFixture;
use app_test_support::write_chatgpt_auth;
use codex_app_server_protocol::McpServerElicitationRequest;
use codex_app_server_protocol::McpServerElicitationRequestParams;
use codex_config::types::AuthCredentialsStoreMode;
@@ -174,7 +172,7 @@ async fn verification_without_a_connected_app_has_no_pending_callback() {
async fn auth_manager(home: &std::path::Path) -> Arc<AuthManager> {
let auth = AuthManager::from_auth_for_testing_with_home(
CodexAuth::create_dummy_chatgpt_auth_for_testing(),
CodexAuth::from_api_key("token-0"),
home.to_path_buf(),
);
write_auth(home, "token-1", "account-1");
@@ -191,13 +189,13 @@ async fn reload_auth(auth: &AuthManager) {
}
fn write_auth(home: &std::path::Path, token: &str, account: &str) {
write_chatgpt_auth(
// Each credential change is a new owner; the account label only distinguishes fixtures.
let _ = account;
codex_login::login_with_api_key(
home,
ChatGptAuthFixture::new(token)
.chatgpt_user_id("user-1")
.account_id(account)
.chatgpt_account_id(account),
token,
AuthCredentialsStoreMode::File,
codex_login::AuthKeyringBackendKind::default(),
)
.unwrap();
}

View File

@@ -12,14 +12,9 @@ use crate::outgoing_message::OutgoingMessage;
use crate::outgoing_message::OutgoingMessageSender;
use crate::transport::AppServerTransport;
use anyhow::Result;
use app_test_support::ChatGptAuthFixture;
use app_test_support::write_chatgpt_auth;
use base64::Engine as _;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use codex_arg0::Arg0DispatchPaths;
use codex_config::CloudConfigBundleLoader;
use codex_config::LoaderOverrides;
use codex_config::types::AuthCredentialsStoreMode;
use codex_arg0::Arg0DispatchPaths;
use codex_config::LoaderOverrides;
use codex_core::config::ConfigBuilder;
use codex_exec_server::EnvironmentManager;
use codex_feedback::CodexFeedback;
@@ -142,14 +137,12 @@ impl Harness {
Vec::new(),
LoaderOverrides::default(),
/*strict_config*/ false,
CloudConfigBundleLoader::default(),
Arg0DispatchPaths::default(),
Arc::new(codex_config::NoopThreadConfigLoader),
);
let (sender, messages) = mpsc::channel(/*buffer*/ 16);
let outgoing = Arc::new(OutgoingMessageSender::new(sender));
let processor = Arc::new(MessageProcessor::new(MessageProcessorArgs {
cloud_skill_provider: None,
outgoing: Arc::clone(&outgoing),
arg0_paths: Arg0DispatchPaths::default(),
startup_cwd: Some(config.cwd.to_path_buf()),
@@ -164,7 +157,6 @@ impl Harness {
session_source: SessionSource::Cli,
auth_manager: Arc::clone(&auth),
user_verification: Arc::clone(&service),
runtime_auth_slot: None,
installation_id: "11111111-1111-4111-8111-111111111111".into(),
code_mode_session_provider: None,
remote_control_handle: None,
@@ -261,13 +253,11 @@ impl Harness {
}
pub(super) fn write_auth(home: &std::path::Path, token: &str) -> Result<()> {
let payload = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&json!({"jti": token, "https://api.openai.com/auth": {"chatgpt_account_id": "account-1", "chatgpt_account_user_id": "membership-1"}}))?);
write_chatgpt_auth(
codex_login::login_with_api_key(
home,
ChatGptAuthFixture::new(format!("header.{payload}.signature"))
.chatgpt_user_id("user-1")
.account_id("account-1")
.chatgpt_account_id("account-1"),
token,
AuthCredentialsStoreMode::File,
)
codex_login::AuthKeyringBackendKind::default(),
)?;
Ok(())
}