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

@@ -3,8 +3,7 @@
//! This module contains the thread-owned MCP runtime and data that describes the
//! environment in which MCP servers execute. Transport startup lives in
//! [`crate::rmcp_client`] and connection-set behavior lives in
//! [`crate::connection_manager`]. Registry removal revokes EMA authority before
//! the thread becomes untracked.
//! [`crate::connection_manager`].
mod status;
@@ -17,7 +16,6 @@ use std::collections::HashSet;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::OnceLock;
use std::sync::Weak;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::AtomicU64;
@@ -27,21 +25,16 @@ use std::time::Duration;
use arc_swap::ArcSwap;
use async_channel::Sender;
use codex_config::types::McpServerDisabledReason;
use codex_connectors::ConnectorRuntimeContextKey;
use codex_connectors::ConnectorRuntimeManager;
use codex_exec_server::Environment;
use codex_exec_server::EnvironmentManager;
use codex_exec_server::HttpClient;
use codex_exec_server::RouteAwareHttpClient;
use codex_login::AuthManager;
use codex_login::CodexAuth;
use codex_protocol::ThreadId;
use codex_protocol::capabilities::SelectedCapabilityRoot;
use codex_protocol::mcp::CallToolResult;
use codex_protocol::mcp::ClientMcpExtensions;
use codex_protocol::mcp::McpResourceOriginCheckpoint;
use codex_protocol::protocol::Event;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::TurnEnvironmentSelection;
use codex_rmcp_client::ElicitationResponse;
use codex_rmcp_client::with_http_headers_helper;
@@ -55,7 +48,6 @@ use tracing::warn;
use crate::McpConfig;
use crate::binding::McpBinding;
use crate::binding::PreparedMcpCall;
use crate::client_tool_catalog::CodexAppsToolSnapshot;
use crate::connection_manager::BindingCatalogRevision;
use crate::connection_manager::McpConnectionSet;
use crate::connection_manager::PreviousMcpConnections;
@@ -63,10 +55,7 @@ use crate::connection_pool::McpConnectionPool;
use crate::elicitation::ElicitationLifecycle;
use crate::elicitation::ElicitationRequestRouter;
use crate::elicitation::ElicitationReviewerHandle;
use crate::event_stream::McpEventStreamOpener;
use crate::mcp::CODEX_APPS_MCP_SERVER_NAME;
use crate::resource_client::McpResourceServerCacheKey;
use crate::resource_origin::ResourceOrigins;
use crate::server::EffectiveMcpServer;
use crate::tool_catalog_cache::McpToolCatalogCache;
use crate::tools::ToolInfo;
@@ -104,16 +93,10 @@ pub struct McpRuntimeInput {
pub tx_event: Option<Sender<Event>>,
pub startup_cancellation_token: CancellationToken,
pub runtime_context: McpRuntimeContext,
pub codex_apps_tools_cache: ConnectorRuntimeManager<ToolInfo>,
pub tool_catalog_cache: McpToolCatalogCache,
pub codex_apps_tools_cache_key: ConnectorRuntimeContextKey,
pub client_mcp_extensions: ClientMcpExtensions,
pub auth: Option<CodexAuth>,
pub auth_manager: Option<Arc<AuthManager>>,
pub runtime_auth: Option<(
codex_runtime_agent_instance::RuntimeAuthSlot,
codex_features::RuntimeAuthMode,
)>,
pub elicitation_reviewer: Option<ElicitationReviewerHandle>,
pub elicitation_lifecycle: Option<ElicitationLifecycle>,
}
@@ -126,18 +109,9 @@ pub struct McpRuntime {
current: ArcSwap<PublishedMcpRuntime>,
// Old bindings keep leases alive after publication; cancellation alone does not release them.
superseded_connections: Mutex<Vec<Weak<McpConnectionSet>>>,
event_stream_cancellation: Mutex<EventStreamCancellation>,
reconnect_pending: AtomicBool,
resource_cache_generation: AtomicU64,
elicitation_router: ElicitationRequestRouter,
resource_origins: Mutex<ResourceOrigins>,
ema_auth: OnceLock<crate::ema_auth::EmaAuthContext>,
}
struct EventStreamCancellation {
event_server_available: bool,
cancel_event_streams_on_server_removal: watch::Sender<()>,
retained_subscription_cancellation: Option<watch::Sender<()>>,
}
struct PublishedMcpRuntime {
@@ -172,35 +146,12 @@ impl AuthOwner {
}
}
fn ensure_host_owned_apps_registration(
current: &PublishedMcpRuntime,
server: &str,
) -> anyhow::Result<()> {
if !current
.config
.as_ref()
.and_then(|config| config.mcp_server_catalog.server(server))
.is_some_and(|registration| {
registration
.source()
.is_host_owned_apps(server, registration.config())
})
{
anyhow::bail!("MCP server '{server}' is not registered by the hosted runtime");
}
Ok(())
}
impl PublishedMcpRuntime {
// Shared by dirty detection and cache-key publication so their auth rules agree.
fn auth_matches(&self, auth: Option<&CodexAuth>) -> bool {
match (self.auth.as_ref(), auth) {
(Some(previous), Some(latest)) => {
previous == latest
&& previous.get_account_id() == latest.get_account_id()
&& previous.get_chatgpt_user_id() == latest.get_chatgpt_user_id()
&& previous.is_fedramp_account() == latest.is_fedramp_account()
&& self.auth_token == latest.get_token().ok()
previous == latest && self.auth_token == latest.get_token().ok()
}
(None, None) => true,
(Some(_), None) | (None, Some(_)) => false,
@@ -284,72 +235,12 @@ impl McpRuntime {
cached_binding: Mutex::new(None),
}),
superseded_connections: Mutex::default(),
event_stream_cancellation: Mutex::new(EventStreamCancellation {
event_server_available: false,
cancel_event_streams_on_server_removal: watch::channel(()).0,
retained_subscription_cancellation: None,
}),
reconnect_pending: AtomicBool::new(false),
resource_cache_generation: AtomicU64::new(0),
elicitation_router: ElicitationRequestRouter::default(),
resource_origins: Mutex::default(),
ema_auth: OnceLock::new(),
}
}
/// Updates this thread's bounded resource provenance from a live or restored event.
pub fn observe_event(&self, event: &EventMsg) {
if !matches!(
event,
EventMsg::TurnStarted(_)
| EventMsg::ItemCompleted(_)
| EventMsg::McpToolCallEnd(_)
| EventMsg::ThreadRolledBack(_)
) {
return;
}
self.resource_origins
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.observe(event);
}
/// Captures bounded widget provenance for the next compaction checkpoint.
pub fn resource_origin_checkpoint(&self) -> Option<McpResourceOriginCheckpoint> {
self.resource_origins
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.checkpoint()
}
/// Restores widget provenance retained by a compaction checkpoint.
pub fn restore_resource_origin_checkpoint(&self, checkpoint: &McpResourceOriginCheckpoint) {
self.resource_origins
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.restore_checkpoint(checkpoint);
}
/// Reads a widget through the current binding of the app tool that produced it.
pub async fn read_resource_for_call(
&self,
thread_id: ThreadId,
call_id: &str,
params: ReadResourceRequestParams,
) -> anyhow::Result<ReadResourceResult> {
let origin = self
.resource_origins
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.find(call_id)?;
let binding = self
.current_binding_for_call(crate::CODEX_APPS_MCP_SERVER_NAME)
.await
.ok_or_else(|| anyhow::anyhow!("codex_apps MCP server is unavailable"))?;
origin.read(&binding, thread_id, params).await
}
pub async fn new(input: McpRuntimeInput) -> Self {
let runtime = Self::empty(input.config.prefix_mcp_tool_names);
runtime.replace(input).await;
@@ -367,47 +258,9 @@ impl McpRuntime {
reconnect.claimed = false;
}
/// Starts fresh connections and returns their complete, refreshed Apps catalog.
pub async fn replace_fresh(&self, input: McpRuntimeInput) -> anyhow::Result<Vec<ToolInfo>> {
self.publish(input, /*reuse_previous*/ false).await;
self.latest_hard_refresh_codex_apps_tools_cache().await
}
/// Revoke a removed thread's EMA access before releasing the registry lock.
pub fn revoke_ema(&self) {
if let Some(Ok(auth)) = self.ema_auth.get() {
auth.authority.revoke();
}
}
/// Drain EMA responses after its configuration binding has been revoked.
pub async fn quiesce_ema(&self) {
if let Some(Ok(auth)) = self.ema_auth.get() {
auth.authority.revoke();
auth.authority.quiesce().await;
}
}
async fn publish(&self, input: McpRuntimeInput, reuse_previous: bool) {
let current = self.current.load_full();
let retain_ema = current.config.is_some();
let ema_auth = (input.config.xaa_enabled
&& input.mcp_servers.values().any(|server| {
server.config().enabled
&& matches!(server.config().auth, codex_config::McpServerAuth::EmaAuth)
}))
.then(|| {
self.ema_auth
.get_or_init(|| {
crate::ema_auth::EmaAuth::new(
Arc::clone(&input.config),
input.auth.as_ref(),
input.auth_manager.as_ref(),
)
.map_err(Into::into)
})
.clone()
});
let has_predecessor = current.config.is_some();
let (publish, publication_gate) = McpPublicationGate::pending();
let config = Arc::clone(&input.config);
let auth = input.auth.clone();
@@ -442,8 +295,7 @@ impl McpRuntime {
// Keep MCP startup state out of the caller's nested session-initialization future.
let connections = Arc::new(
Box::pin(McpConnectionSet::new(
ema_auth,
retain_ema.then_some(current.connections.as_ref()),
has_predecessor.then_some(current.connections.as_ref()),
reuse_previous.then_some(PreviousMcpConnections {
connections: &current.connections,
same_owner,
@@ -454,19 +306,6 @@ impl McpRuntime {
))
.await,
);
let hosted_event_server_retained = connections.contains_server(CODEX_APPS_MCP_SERVER_NAME)
&& config
.mcp_server_catalog
.server(CODEX_APPS_MCP_SERVER_NAME)
.is_some_and(|registration| {
registration
.source()
.is_host_owned_apps(CODEX_APPS_MCP_SERVER_NAME, registration.config())
});
let mut cancellation = self
.event_stream_cancellation
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
{
let mut superseded = self
.superseded_connections
@@ -490,15 +329,6 @@ impl McpRuntime {
cached_binding: Mutex::new(None),
}));
let _ = publish.send(true);
cancellation.event_server_available = hosted_event_server_retained;
if !hosted_event_server_retained {
cancellation
.cancel_event_streams_on_server_removal
.send_replace(());
if let Some(retained) = &cancellation.retained_subscription_cancellation {
retained.send_replace(());
}
}
}
/// Ensures the next refresh creates fresh connections for every configured server.
@@ -732,34 +562,6 @@ impl McpRuntime {
.await
}
pub async fn latest_hard_refresh_codex_apps_tools_cache(
&self,
) -> anyhow::Result<Vec<ToolInfo>> {
self.latest_connections()
.refresh_codex_apps_tools_for_discovery()
.await
}
/// Refreshes the published Apps client and returns its exact inventory and MCP eligibility.
pub async fn refresh_codex_apps_tools(&self) -> anyhow::Result<CodexAppsToolSnapshot> {
let current = self.current.load_full();
let config = current
.config
.as_deref()
.ok_or_else(|| anyhow::anyhow!("MCP runtime is not configured"))?;
current
.connections
.refresh_codex_apps_client_catalog(config)
.await
}
/// Returns tools from this thread’s ready, unshared Apps MCP client.
/// Returns an empty list if the client is absent, still starting, or uses
/// a shared catalog. Does not start or wait for discovery.
pub async fn apps_tools_from_mcp_client(&self) -> Vec<ToolInfo> {
self.latest_connections().apps_tools_from_mcp_client().await
}
/// Lists the latest known tools for non-model discovery surfaces.
///
/// Unlike [`Self::current_binding`], this may return cached tools while their
@@ -917,70 +719,6 @@ impl McpRuntime {
Arc::clone(&self.current.load().connections)
}
pub(crate) fn latest_host_owned_codex_apps_connections(
&self,
) -> anyhow::Result<Arc<McpConnectionSet>> {
let current = self.current.load();
ensure_host_owned_apps_registration(&current, CODEX_APPS_MCP_SERVER_NAME)?;
Ok(Arc::clone(&current.connections))
}
pub(crate) fn latest_connections_for_event_server(
&self,
server: &str,
) -> anyhow::Result<(Arc<McpConnectionSet>, watch::Receiver<()>)> {
let cancellation = self
.event_stream_cancellation
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let cancel_event_streams_on_server_removal = cancellation
.cancel_event_streams_on_server_removal
.subscribe();
let current = self.current.load();
if server == CODEX_APPS_MCP_SERVER_NAME {
ensure_host_owned_apps_registration(&current, server)?;
}
Ok((
Arc::clone(&current.connections),
cancel_event_streams_on_server_removal,
))
}
pub(crate) fn event_stream_opener(&self) -> anyhow::Result<McpEventStreamOpener> {
let cancellation = self
.event_stream_cancellation
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let connection = self
.current
.load()
.connections
.event_stream_connection
.clone()
.ok_or_else(|| anyhow::anyhow!("Event subscriptions are unavailable for this task"))?;
let cancel_event_streams_on_server_removal = cancellation
.retained_subscription_cancellation
.as_ref()
.unwrap_or(&cancellation.cancel_event_streams_on_server_removal)
.clone();
Ok(McpEventStreamOpener {
connection,
cancellation_receiver: cancel_event_streams_on_server_removal.subscribe(),
cancel_event_streams_on_server_removal,
})
}
pub(crate) fn forward_event_server_removals_to(&self, retained: watch::Sender<()>) {
let mut cancellation = self
.event_stream_cancellation
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if !cancellation.event_server_available {
retained.send_replace(());
}
cancellation.retained_subscription_cancellation = Some(retained);
}
pub async fn shutdown(&self) {
self.elicitation_router.close().await;
let superseded = std::mem::take(
@@ -1091,14 +829,6 @@ impl McpRuntimeContext {
self.local_process_cwd.clone()
}
pub(crate) fn http_client_factory(&self) -> codex_http_client::HttpClientFactory {
self.environment_manager.http_client_factory().clone()
}
pub(crate) fn set_local_http_client(&mut self, client: Arc<dyn HttpClient>) {
self.local_http_client = client;
}
pub(crate) fn local_http_client(&self) -> Arc<dyn HttpClient> {
Arc::clone(&self.local_http_client)
}
@@ -1231,27 +961,16 @@ mod tests {
#[tokio::test]
async fn cached_bindings_follow_the_clients_catalog_revision() -> anyhow::Result<()> {
let codex_home = tempfile::tempdir()?;
let cache_context = ConnectorRuntimeManager::<ToolInfo>::default().context(
codex_home.path().to_path_buf(),
ConnectorRuntimeContextKey::personal(
/*account_id*/ None, /*chatgpt_user_id*/ None,
),
);
let connections =
crate::connection_manager::tests::create_test_manager_with_ready_apps_client(
cache_context,
"search",
/*list_started*/ None,
/*release_list*/ None,
)
.await?;
let connections = crate::connection_manager::tests::create_test_manager_with_ready_client(
"docs", "search", /*list_started*/ None, /*release_list*/ None,
)
.await?;
// Complete the fixture's shared startup future before testing stable reuse.
connections.list_all_tools().await;
let mut config = crate::mcp::tests::test_mcp_config(codex_home.path().to_path_buf());
config.server_permissions.insert(
CODEX_APPS_MCP_SERVER_NAME.to_string(),
McpServerPermissions::Thread,
);
config
.server_permissions
.insert("docs".to_string(), McpServerPermissions::Thread);
let published = Arc::new(PublishedMcpRuntime {
connections: Arc::clone(&connections),
config: Some(Arc::new(config)),
@@ -1270,10 +989,7 @@ mod tests {
runtime.current.store(Arc::clone(&published));
runtime
.latest_call_tool_without_attribution(
CODEX_APPS_MCP_SERVER_NAME,
"search",
/*arguments*/ None,
/*meta*/ None,
"docs", "search", /*arguments*/ None, /*meta*/ None,
)
.await?;
assert!(published.cached_binding.lock().unwrap().is_none());
@@ -1293,7 +1009,16 @@ mod tests {
.expect("cached initial binding");
assert!(Arc::ptr_eq(&before, &repeated));
connections.refresh_codex_apps_tools_for_discovery().await?;
let client = connections
.test_client("docs")
.ready_client()
.expect("ready test client");
let mut refreshed_tool = crate::connection_manager::tests::create_test_tool("docs", "search");
refreshed_tool.tool.description = Some("refreshed".into());
client
.tool_catalog
.replace_for_test(vec![refreshed_tool])
.await;
let refreshed = McpRuntime::binding_from_published_runtime(
Arc::clone(&published),
@@ -1304,7 +1029,7 @@ mod tests {
.expect("refreshed binding");
assert!(!Arc::ptr_eq(&before, &refreshed));
let call = refreshed
.prepare_call(CODEX_APPS_MCP_SERVER_NAME, "search")
.prepare_call("docs", "search")
.expect("refreshed call");
let error = call
.call_with_preparation(/*requested_timeout*/ None, || async {