aKode fase 2b-1 (WIP): rimossi cloud-config, apps MCP ChatGPT, upload file, connectors-extension, rate limits backend; plugin remoti in corso (test non ancora compilanti)
Some checks failed
blocking-ci / Bazel (push) Has been cancelled
blocking-ci / Blob size policy (push) Has been cancelled
blocking-ci / cargo-deny (push) Has been cancelled
blocking-ci / Codespell (push) Has been cancelled
blocking-ci / repo-checks (push) Has been cancelled
blocking-ci / rust-ci (push) Has been cancelled
blocking-ci / sdk (push) Has been cancelled
blocking-ci / CI required (push) Has been cancelled
postmerge-ci / rust-ci-full (push) Has been cancelled
postmerge-ci / v8-canary (push) Has been cancelled
postmerge-ci / Postmerge CI results (push) Has been cancelled

This commit is contained in:
Andrea
2026-11-09 13:55:36 +01:00
parent 137106bf17
commit e4209e2755
166 changed files with 155 additions and 31558 deletions

View File

@@ -1,6 +0,0 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "connectors",
crate_name = "codex_connectors_extension",
)

View File

@@ -1,24 +0,0 @@
[package]
edition.workspace = true
license.workspace = true
name = "codex-connectors-extension"
version.workspace = true
[lib]
name = "codex_connectors_extension"
path = "src/lib.rs"
doctest = false
test = false
[lints]
workspace = true
[dependencies]
codex-connectors = { workspace = true }
codex-core-plugins = { workspace = true }
codex-file-system = { workspace = true }
codex-plugin = { workspace = true }
codex-utils-path-uri = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
tracing = { workspace = true }

View File

@@ -1,6 +0,0 @@
//! Plugin app declaration loading.
mod plugin_app;
pub use plugin_app::PluginAppProvider;
pub use plugin_app::PluginAppProviderError;

View File

@@ -1,68 +0,0 @@
use codex_connectors::parse_plugin_app_config;
use codex_core_plugins::ResolvedExecutorPlugin;
use codex_file_system::ReadFileOptions;
use codex_plugin::AppDeclaration;
use codex_plugin::PluginResourceLocator;
use codex_utils_path_uri::PathUri;
use std::io;
use thiserror::Error;
/// Loads app declarations from a resolved plugin.
#[derive(Clone, Copy, Debug, Default)]
pub struct PluginAppProvider;
/// Failure to load app declarations from a plugin.
#[derive(Debug, Error)]
pub enum PluginAppProviderError {
#[error("failed to read app config for selected plugin `{plugin_id}` at `{path}`: {source}")]
ReadConfig {
plugin_id: String,
path: PathUri,
#[source]
source: io::Error,
},
#[error("failed to parse app config for selected plugin `{plugin_id}` at `{path}`: {source}")]
ParseConfig {
plugin_id: String,
path: PathUri,
#[source]
source: serde_json::Error,
},
}
impl PluginAppProvider {
/// Returns the app declarations contributed by `plugin`.
#[tracing::instrument(name = "connectors.plugin.declarations.load", skip_all)]
pub async fn load(
&self,
plugin: &ResolvedExecutorPlugin,
) -> Result<Vec<AppDeclaration>, PluginAppProviderError> {
let resolved_plugin = plugin.plugin();
let plugin_id = resolved_plugin.selected_root_id();
let Some(PluginResourceLocator::Environment {
path: config_path, ..
}) = resolved_plugin.manifest().paths.apps.as_ref()
else {
return Ok(Vec::new());
};
let contents = plugin
.file_system()
.read_file_text(
config_path,
ReadFileOptions::default(),
/*sandbox*/ None,
)
.await
.map_err(|source| PluginAppProviderError::ReadConfig {
plugin_id: plugin_id.to_string(),
path: config_path.clone(),
source,
})?;
parse_plugin_app_config(&contents).map_err(|source| PluginAppProviderError::ParseConfig {
plugin_id: plugin_id.to_string(),
path: config_path.clone(),
source,
})
}
}

View File

@@ -13,16 +13,5 @@ doctest = false
workspace = true
[dependencies]
codex-backend-client = { workspace = true }
codex-extension-api = { workspace = true }
codex-features = { workspace = true }
codex-http-client = { workspace = true }
codex-login = { workspace = true }
codex-model-provider = { workspace = true }
codex-runtime-agent-instance = { workspace = true }
serde_json = { workspace = true }
tokio = { workspace = true, features = ["time"] }
[dev-dependencies]
tokio = { workspace = true, features = ["macros", "rt"] }
wiremock = { workspace = true }

View File

@@ -1,236 +0,0 @@
use std::sync::Arc;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::time::Duration;
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
use codex_login::AuthManager;
use codex_login::CodexAuth;
use codex_login::ExternalAuth;
use codex_login::ExternalAuthFuture;
use codex_login::ExternalAuthRefreshContext;
use tokio::sync::Notify;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
use super::policy::resolve_attribution_policy;
fn enterprise_auth_manager() -> Arc<AuthManager> {
AuthManager::from_auth_for_testing(enterprise_auth("workspace-123"))
}
fn http_client_factory() -> HttpClientFactory {
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault)
}
fn enterprise_auth(account_id: &str) -> CodexAuth {
CodexAuth::from_external_chatgpt_tokens("e30.e30.c2ln", account_id, Some("enterprise"))
.expect("fake ChatGPT auth should parse")
}
struct StaticExternalAuth(CodexAuth);
impl ExternalAuth for StaticExternalAuth {
fn resolve(&self) -> ExternalAuthFuture<'_, CodexAuth> {
Box::pin(async { Ok(self.0.clone()) })
}
fn refresh(&self, _context: ExternalAuthRefreshContext) -> ExternalAuthFuture<'_, CodexAuth> {
self.resolve()
}
}
async fn set_auth(auth_manager: &AuthManager, account_id: &str) {
auth_manager
.set_external_auth(Arc::new(StaticExternalAuth(enterprise_auth(account_id))))
.await
.expect("auth refresh should succeed");
}
#[tokio::test]
async fn policy_resolution_recovers_after_unauthorized() {
let server = MockServer::start().await;
let request_count = Arc::new(AtomicUsize::new(0));
Mock::given(method("GET"))
.and(path("/backend-api/wham/settings/user"))
.respond_with({
let request_count = request_count.clone();
move |_request: &wiremock::Request| {
if request_count.fetch_add(1, Ordering::SeqCst) == 0 {
ResponseTemplate::new(401)
} else {
ResponseTemplate::new(200)
.set_body_json(serde_json::json!({"commit_attribution_enabled": true}))
}
}
})
.expect(2)
.mount(&server)
.await;
let auth_manager = enterprise_auth_manager();
set_auth(auth_manager.as_ref(), "workspace-123").await;
let policy = resolve_attribution_policy(
&auth_manager,
&format!("{}/backend-api", server.uri()),
&http_client_factory(),
/*runtime_auth*/ None,
)
.await
.expect("policy resolution should not time out")
.expect("policy should resolve after auth recovery");
assert!(policy.enabled);
assert_eq!(request_count.load(Ordering::SeqCst), 2);
server.verify().await;
}
#[tokio::test]
async fn policy_resolution_retries_after_auth_refresh() {
let server = MockServer::start().await;
let request_started = Arc::new(Notify::new());
let request_count = Arc::new(AtomicUsize::new(0));
Mock::given(method("GET"))
.and(path("/backend-api/wham/settings/user"))
.respond_with({
let request_started = request_started.clone();
let request_count = request_count.clone();
move |_request: &wiremock::Request| match request_count.fetch_add(1, Ordering::SeqCst) {
0 => {
request_started.notify_one();
ResponseTemplate::new(200)
.set_delay(Duration::from_millis(100))
.set_body_json(serde_json::json!({
"commit_attribution_enabled": true,
}))
}
1 => ResponseTemplate::new(401),
_ => ResponseTemplate::new(200).set_body_json(serde_json::json!({
"commit_attribution_enabled": true,
})),
}
})
.expect(3)
.mount(&server)
.await;
let auth_manager = enterprise_auth_manager();
let resolve = tokio::spawn({
let auth_manager = auth_manager.clone();
let base_url = format!("{}/backend-api", server.uri());
async move {
resolve_attribution_policy(
&auth_manager,
&base_url,
&http_client_factory(),
/*runtime_auth*/ None,
)
.await
.ok()
.flatten()
}
});
tokio::time::timeout(Duration::from_secs(5), request_started.notified())
.await
.expect("first settings request should start");
set_auth(auth_manager.as_ref(), "workspace-456").await;
assert!(
resolve
.await
.expect("policy task should complete")
.expect("policy should resolve after refresh")
.enabled
);
server.verify().await;
}
struct RotatingExternalAuth(AtomicUsize);
impl ExternalAuth for RotatingExternalAuth {
fn resolve(&self) -> ExternalAuthFuture<'_, CodexAuth> {
Box::pin(async {
let generation = self.0.load(Ordering::SeqCst);
CodexAuth::from_external_chatgpt_tokens(
&format!("e30.e30.signature-{generation}"),
"workspace-123",
Some("enterprise"),
)
})
}
fn refresh(&self, _context: ExternalAuthRefreshContext) -> ExternalAuthFuture<'_, CodexAuth> {
self.0.fetch_add(/*val*/ 1, Ordering::SeqCst);
self.resolve()
}
}
#[tokio::test]
async fn world_state_stops_after_rejected_refresh() {
use codex_extension_api::ContextContributor;
use codex_extension_api::ExtensionData;
use codex_extension_api::PreviousWorldStateSection;
use codex_extension_api::WorldStateContributionInput;
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/backend-api/wham/settings/user"))
.respond_with(ResponseTemplate::new(401))
.expect(2)
.mount(&server)
.await;
let source = Arc::new(RotatingExternalAuth(AtomicUsize::new(/*v*/ 0)));
let auth_manager = enterprise_auth_manager();
auth_manager
.set_external_auth(source.clone())
.await
.expect("external credentials should load");
let extension = super::GitAttributionExtension {
auth_manager,
base_url: format!("{}/backend-api", server.uri()),
http_client_factory: http_client_factory(),
};
let model_info = serde_json::from_value(serde_json::json!({
"slug": "test-model",
"display_name": "Test model",
"supported_reasoning_levels": [],
"shell_type": "shell_command",
"visibility": "list",
"supported_in_api": true,
"priority": 0,
"support_verbosity": false,
"truncation_policy": {"mode": "bytes", "limit": 10000},
"experimental_supported_tools": []
}))
.expect("model metadata should parse");
let store = ExtensionData::new("test");
let sections = tokio::time::timeout(
Duration::from_secs(2),
extension.contribute_world_state(WorldStateContributionInput {
thread_id: Default::default(),
turn_id: "turn",
model_info: &model_info,
environments: &[],
extension_metrics: None,
session_store: &store,
thread_store: &store,
turn_store: &store,
step_store: &store,
previous_world_state: None,
}),
)
.await
.expect("an optional settings failure must not keep refreshing credentials");
assert_eq!(source.0.load(Ordering::SeqCst), 1);
assert!(sections.iter().all(|section| {
section
.render_diff(PreviousWorldStateSection::Absent)
.1
.is_none()
}));
server.verify().await;
}

View File

@@ -1,118 +1,38 @@
mod policy;
mod world_state;
use std::sync::Arc;
use std::time::Instant;
use codex_extension_api::ContextContributor;
use codex_extension_api::ExtensionFuture;
use codex_extension_api::ExtensionRegistryBuilder;
use codex_extension_api::WorldStateContributionInput;
use codex_extension_api::WorldStateSectionContribution;
use codex_http_client::HttpClientFactory;
use codex_login::AuthManager;
use codex_model_provider::ProviderAuthContext;
use crate::policy::GitAttributionPolicy;
use crate::policy::GitAttributionRetry;
use crate::policy::POLICY_RETRY_DELAY;
use crate::policy::auth_generation;
use crate::policy::cached_attribution_policy;
use crate::policy::resolve_attribution_policy;
use crate::policy::retry_deferred;
use crate::world_state::git_attribution_world_state_section;
/// Local default for commit and pull request attribution. aKode never fetches a
/// remote workspace policy, so attribution stays disabled.
const ATTRIBUTION_ENABLED_BY_DEFAULT: bool = false;
/// Contributes model instructions for agent-created git commits and pull requests.
#[derive(Clone)]
struct GitAttributionExtension {
auth_manager: Arc<AuthManager>,
base_url: String,
http_client_factory: HttpClientFactory,
enabled: bool,
}
impl ContextContributor for GitAttributionExtension {
fn contribute_world_state<'a>(
&'a self,
input: WorldStateContributionInput<'a>,
_input: WorldStateContributionInput<'a>,
) -> ExtensionFuture<'a, Vec<WorldStateSectionContribution>> {
Box::pin(async move {
let auth_context = input.thread_store.get::<ProviderAuthContext>();
let auth_manager = auth_context
.as_ref()
.map_or(&self.auth_manager, |context| &context.credentials);
let runtime_auth = auth_context
.as_ref()
.and_then(|context| context.runtime_auth.as_ref());
let enabled = loop {
let current_auth_generation = auth_generation(auth_manager.as_ref());
let policy = match cached_attribution_policy(
input.thread_store,
input.turn_store,
current_auth_generation,
) {
Some(policy) => policy,
None if retry_deferred(input.thread_store, current_auth_generation) => {
GitAttributionPolicy {
auth_generation: current_auth_generation,
enabled: false,
}
}
None => {
match resolve_attribution_policy(
auth_manager,
&self.base_url,
&self.http_client_factory,
runtime_auth,
)
.await
{
Ok(Some(policy)) => {
input.thread_store.insert(policy.clone());
policy
}
Ok(None) => {
input.turn_store.insert(GitAttributionPolicy {
auth_generation: current_auth_generation,
enabled: false,
});
break false;
}
Err(_) => {
let auth_generation = auth_generation(auth_manager.as_ref());
if auth_generation == current_auth_generation {
input.thread_store.insert(GitAttributionRetry {
auth_generation,
retry_at: Instant::now() + POLICY_RETRY_DELAY,
});
}
break false;
}
}
}
};
if policy.auth_generation == auth_generation(auth_manager.as_ref()) {
break policy.enabled;
}
};
vec![git_attribution_world_state_section(enabled)]
})
let enabled = self.enabled;
Box::pin(async move { vec![git_attribution_world_state_section(enabled)] })
}
}
/// Installs the git-attribution contributor into the extension registry.
pub fn install<C: Sync>(
registry: &mut ExtensionRegistryBuilder<C>,
auth_manager: Arc<AuthManager>,
base_url: String,
http_client_factory: HttpClientFactory,
) {
pub fn install<C: Sync>(registry: &mut ExtensionRegistryBuilder<C>) {
registry.prompt_contributor(Arc::new(GitAttributionExtension {
auth_manager,
base_url,
http_client_factory,
enabled: ATTRIBUTION_ENABLED_BY_DEFAULT,
}));
}
#[cfg(test)]
#[path = "git_attribution_tests.rs"]
mod tests;

View File

@@ -1,122 +0,0 @@
use std::sync::Arc;
use std::time::Duration;
use std::time::Instant;
use codex_backend_client::Client as BackendClient;
use codex_extension_api::ExtensionData;
use codex_features::RuntimeAuthMode;
use codex_http_client::HttpClientFactory;
use codex_login::AuthManager;
use codex_runtime_agent_instance::RuntimeAuthManager;
use tokio::time::timeout;
#[derive(Clone, Debug)]
pub(super) struct GitAttributionPolicy {
pub(super) auth_generation: u64,
pub(super) enabled: bool,
}
pub(super) struct GitAttributionRetry {
pub(super) auth_generation: u64,
pub(super) retry_at: Instant,
}
pub(super) fn retry_deferred(thread_store: &ExtensionData, auth_generation: u64) -> bool {
thread_store
.get::<GitAttributionRetry>()
.is_some_and(|retry| {
retry.auth_generation == auth_generation && retry.retry_at > Instant::now()
})
}
pub(super) fn cached_attribution_policy(
thread_store: &ExtensionData,
turn_store: &ExtensionData,
auth_generation: u64,
) -> Option<GitAttributionPolicy> {
thread_store
.get::<GitAttributionPolicy>()
.filter(|policy| policy.auth_generation == auth_generation)
.or_else(|| {
turn_store
.get::<GitAttributionPolicy>()
.filter(|policy| policy.auth_generation == auth_generation)
})
.map(|policy| policy.as_ref().clone())
}
#[cfg(not(test))]
const POLICY_RESOLUTION_TIMEOUT: Duration = Duration::from_secs(5);
#[cfg(test)]
const POLICY_RESOLUTION_TIMEOUT: Duration = Duration::from_millis(500);
pub(super) const POLICY_RETRY_DELAY: Duration = Duration::from_secs(30);
pub(super) async fn resolve_attribution_policy(
auth_manager: &Arc<AuthManager>,
base_url: &str,
http_client_factory: &HttpClientFactory,
runtime_auth: Option<&(Arc<RuntimeAuthManager>, RuntimeAuthMode)>,
) -> Result<Option<GitAttributionPolicy>, tokio::time::error::Elapsed> {
timeout(POLICY_RESOLUTION_TIMEOUT, async {
let mut recovery_generation = auth_generation(auth_manager);
let mut auth_recovery = auth_manager.unauthorized_recovery();
loop {
let auth_generation_at_start = auth_generation(auth_manager);
if auth_generation_at_start != recovery_generation {
auth_recovery = auth_manager.unauthorized_recovery();
recovery_generation = auth_generation_at_start;
}
let auth = auth_manager.auth_with_http_client_factory().await;
if auth_generation(auth_manager) != auth_generation_at_start {
continue;
}
let enabled = match auth {
Some((auth, captured_factory)) if auth.uses_codex_backend() => {
let policy = http_client_factory
.network_policy()
.clone()
.with_account_binding(captured_factory.network_policy())?;
let client = BackendClient::from_auth_with_runtime(
base_url,
&auth,
http_client_factory.clone().with_network_policy(policy),
runtime_auth,
/*headers*/ &Default::default(),
)
.await;
if auth_generation(auth_manager) != auth_generation_at_start {
continue;
}
let settings = client.ok()?.get_user_settings().await;
if auth_generation(auth_manager) != auth_generation_at_start {
continue;
}
match settings {
Ok(settings) => Some(settings.commit_attribution_enabled),
Err(err) if err.is_unauthorized() && auth_recovery.has_next() => {
if auth_recovery.next().await.is_ok() {
recovery_generation = auth_generation(auth_manager);
continue;
}
None
}
Err(_) => None,
}
}
Some(_) | None => Some(false),
};
if auth_generation(auth_manager) != auth_generation_at_start {
continue;
}
return enabled.map(|enabled| GitAttributionPolicy {
auth_generation: auth_generation_at_start,
enabled,
});
}
})
.await
}
pub(super) fn auth_generation(auth_manager: &AuthManager) -> u64 {
*auth_manager.auth_change_receiver().borrow()
}

View File

@@ -18,7 +18,6 @@ codex-core = { workspace = true }
codex-core-plugins = { workspace = true }
codex-config = { workspace = true }
codex-connectors = { workspace = true }
codex-connectors-extension = { workspace = true }
codex-exec-server = { workspace = true }
codex-extension-api = { workspace = true }
codex-features = { workspace = true }

View File

@@ -1,12 +1,3 @@
use codex_core::config::Config;
use codex_extension_api::ExtensionFuture;
use codex_extension_api::ExtensionRegistryBuilder;
use codex_extension_api::McpServerContribution;
use codex_extension_api::McpServerContributionContext;
use codex_extension_api::McpServerContributor;
use codex_mcp::CODEX_APPS_MCP_SERVER_NAME;
use codex_mcp::hosted_plugin_runtime_mcp_server_config;
mod catalog_observability;
mod cloud_plugin;
mod plugin;
@@ -27,40 +18,3 @@ pub use plugin_providers::PluginProviders;
pub use stream_manager::McpEventStreamManager;
pub use stream_manager::McpEventStreamUpdate;
struct HostedPluginRuntimeExtension;
impl McpServerContributor<Config> for HostedPluginRuntimeExtension {
fn id(&self) -> &'static str {
"hosted_plugin_runtime"
}
fn contribute<'a>(
&'a self,
context: McpServerContributionContext<'a, Config>,
) -> ExtensionFuture<'a, Vec<McpServerContribution>> {
Box::pin(async move {
let config = context.config();
let name = CODEX_APPS_MCP_SERVER_NAME.to_string();
if !config.features.enabled(codex_features::Feature::Apps) {
return vec![McpServerContribution::Remove { name }];
}
vec![McpServerContribution::HostedApps {
config: Box::new(hosted_plugin_runtime_mcp_server_config(
&config.chatgpt_base_url,
config.apps_mcp_product_sku.as_deref(),
context.originator(),
)),
protocol_mode: None,
}]
})
}
}
pub fn install(builder: &mut ExtensionRegistryBuilder<Config>) {
builder.mcp_server_contributor(std::sync::Arc::new(HostedPluginRuntimeExtension));
}
#[cfg(test)]
#[path = "lib_tests.rs"]
mod tests;

View File

@@ -1,61 +0,0 @@
use super::*;
use codex_config::McpServerTransportConfig;
use codex_core::config::ConfigBuilder;
use codex_extension_api::ExtensionData;
use codex_extension_api::ExtensionDataInit;
use pretty_assertions::assert_eq;
#[tokio::test]
async fn hosted_plugin_runtime_forwards_thread_originator() -> Result<(), Box<dyn std::error::Error>>
{
let codex_home = tempfile::tempdir()?;
let config = ConfigBuilder::default()
.codex_home(codex_home.path().to_path_buf())
.fallback_cwd(Some(codex_home.path().to_path_buf()))
.cli_overrides(vec![
("features.apps".to_string(), true.into()),
("chatgpt_base_url".to_string(), "https://chatgpt.com".into()),
])
.build()
.await?;
let thread_init = ExtensionDataInit::new();
let thread_store = ExtensionData::new("thread");
let contributions = HostedPluginRuntimeExtension
.contribute(McpServerContributionContext::for_step(
&config,
&thread_init,
&thread_store,
"codex_work_desktop",
/*ready_selected_capability_roots*/ &[],
/*executor_capability_discovery*/ None,
/*executor_capability_discovery_v2*/ None,
))
.await;
let [
McpServerContribution::HostedApps {
config: server,
protocol_mode: None,
},
] = contributions.as_slice()
else {
panic!("hosted plugin runtime should contribute one server");
};
let McpServerTransportConfig::StreamableHttp { http_headers, .. } = &server.transport else {
panic!("hosted plugin runtime should use streamable HTTP");
};
assert_eq!(
http_headers
.as_ref()
.and_then(|headers| headers.get("originator")),
Some(&"codex_work_desktop".to_string())
);
Ok(())
}
#[path = "event_stream_tests.rs"]
mod event_stream_tests;
#[path = "stream_manager_tests.rs"]
mod stream_manager_tests;

View File

@@ -1,5 +1,4 @@
use codex_config::types::PluginsConfigToml;
use codex_connectors_extension::PluginAppProvider;
use codex_core::config::Config;
use codex_core_plugins::ExecutorPluginProviderError;
use codex_core_plugins::PluginIdentity;
@@ -125,14 +124,8 @@ impl PluginContributor {
};
let metadata = match plugin {
Some(plugin) => {
// MCP server and app declarations are separate
// executor-owned files. Read them together so a remote environment only
// pays for the slower read instead of both reads back-to-back.
let (servers, app_declarations) = tokio::join!(
PluginMcpProvider.load(&plugin),
PluginAppProvider.load(&plugin)
);
let servers = servers.unwrap_or_else(|err| {
// ChatGPT app declarations are ignored in aKode; only MCP servers load.
let servers = PluginMcpProvider.load(&plugin).await.unwrap_or_else(|err| {
tracing::warn!(
selected_root = selected_root.id,
error = %err,
@@ -140,18 +133,7 @@ impl PluginContributor {
);
Vec::new()
});
let connector_ids = app_declarations
.unwrap_or_else(|err| {
tracing::warn!(
selected_root = selected_root.id,
error = %err,
"failed to load selected plugin apps"
);
Vec::new()
})
.into_iter()
.map(|declaration| declaration.connector_id.0)
.collect();
let connector_ids = Vec::new();
let CapabilityRootLocation::Environment { environment_id, .. } =
&selected_root.location;
Some(SelectedPluginContribution {

View File

@@ -1,233 +0,0 @@
use std::sync::Arc;
use codex_config::McpServerTransportConfig;
use codex_config::test_support::CloudConfigBundleFixture;
use codex_core::McpManager;
use codex_core::config::Config;
use codex_core::config::ConfigBuilder;
use codex_core::plugins_manager_for_config;
use codex_extension_api::ExtensionRegistryBuilder;
use codex_extension_api::McpServerContribution;
use codex_extension_api::McpServerContributionContext;
use codex_extension_api::McpServerContributor;
use codex_login::AuthManager;
use codex_login::CodexAuth;
use codex_login::test_support::auth_manager_from_optional_auth;
use codex_mcp::CODEX_APPS_MCP_SERVER_NAME;
use pretty_assertions::assert_eq;
type TestResult = Result<(), Box<dyn std::error::Error>>;
#[tokio::test]
async fn contributes_hosted_plugin_runtime_without_an_executor() -> TestResult {
let codex_home = tempfile::tempdir()?;
let config = ConfigBuilder::default()
.codex_home(codex_home.path().to_path_buf())
.fallback_cwd(Some(codex_home.path().to_path_buf()))
.cli_overrides(vec![
("features.apps".to_string(), true.into()),
("chatgpt_base_url".to_string(), "https://chatgpt.com".into()),
])
.build()
.await?;
let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing();
let manager = installed_manager(&config, Some(auth.clone()));
let servers = manager.effective_servers(&config, Some(&auth)).await;
let server = servers
.get(CODEX_APPS_MCP_SERVER_NAME)
.ok_or("hosted plugin runtime should be contributed as a configured server")?
.config();
let McpServerTransportConfig::StreamableHttp { url, .. } = &server.transport else {
panic!("hosted plugin runtime should use streamable HTTP");
};
assert_eq!(url, "https://chatgpt.com/backend-api/ps/mcp");
Ok(())
}
#[tokio::test]
async fn runtime_overlay_preserves_disabled_server() -> TestResult {
let codex_home = tempfile::tempdir()?;
let config = ConfigBuilder::default()
.codex_home(codex_home.path().to_path_buf())
.fallback_cwd(Some(codex_home.path().to_path_buf()))
.cli_overrides(vec![
("features.apps".to_string(), true.into()),
(
"mcp_servers.codex_apps.url".to_string(),
"https://example.com/mcp".into(),
),
("mcp_servers.codex_apps.enabled".to_string(), false.into()),
])
.cloud_config_bundle(
CloudConfigBundleFixture::loader_with_enterprise_requirement("[mcp_servers]"),
)
.build()
.await?;
let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing();
let manager = installed_manager(&config, Some(auth.clone()));
let configured = manager.configured_servers(&config).await;
// Standalone login must still reject requirements-denied, explicitly disabled entries.
let login_client = Arc::new(codex_exec_server::RouteAwareHttpClient::new(
config.http_client_factory(),
));
assert_eq!(
codex_mcp::apply_http_headers_helper(
login_client,
&configured[CODEX_APPS_MCP_SERVER_NAME],
codex_home.path().to_path_buf(),
)
.err(),
Some("the MCP server is disabled by managed requirements".to_string())
);
let servers = manager.effective_servers(&config, Some(&auth)).await;
let server = servers
.get(CODEX_APPS_MCP_SERVER_NAME)
.ok_or("hosted plugin runtime should remain configured")?;
assert!(!server.enabled());
Ok(())
}
#[tokio::test]
async fn default_fallback_overwrites_reserved_config_without_an_extension() -> TestResult {
let codex_home = tempfile::tempdir()?;
let config = ConfigBuilder::default()
.codex_home(codex_home.path().to_path_buf())
.fallback_cwd(Some(codex_home.path().to_path_buf()))
.cli_overrides(vec![
("features.apps".to_string(), true.into()),
(
"mcp_servers.codex_apps.url".to_string(),
"https://example.com/mcp".into(),
),
])
.build()
.await?;
let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing();
let manager = McpManager::new(Arc::new(plugins_manager_for_config(
&config,
AuthManager::from_auth_for_testing(auth.clone()),
)));
let servers = manager.effective_servers(&config, Some(&auth)).await;
let server = servers
.get(CODEX_APPS_MCP_SERVER_NAME)
.ok_or("default Apps MCP should be present")?
.config();
let McpServerTransportConfig::StreamableHttp { url, .. } = &server.transport else {
panic!("default Apps MCP should use streamable HTTP");
};
assert_eq!(url, "https://chatgpt.com/backend-api/ps/mcp");
Ok(())
}
#[tokio::test]
async fn later_extension_can_remove_same_name_registration() -> TestResult {
let codex_home = tempfile::tempdir()?;
let config = ConfigBuilder::default()
.codex_home(codex_home.path().to_path_buf())
.fallback_cwd(Some(codex_home.path().to_path_buf()))
.cli_overrides(vec![("features.apps".to_string(), true.into())])
.build()
.await?;
let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing();
let mut builder = ExtensionRegistryBuilder::new();
codex_mcp_extension::install(&mut builder);
builder.mcp_server_contributor(Arc::new(RemoveCodexApps));
let manager = McpManager::new_with_extensions(
Arc::new(plugins_manager_for_config(
&config,
AuthManager::from_auth_for_testing(auth.clone()),
)),
Arc::new(builder.build()),
codex_core::CodexAppsToolsCache::default(),
);
let servers = manager.effective_servers(&config, Some(&auth)).await;
assert!(!servers.contains_key(CODEX_APPS_MCP_SERVER_NAME));
Ok(())
}
#[tokio::test]
async fn hosted_apps_mcp_requires_chatgpt_auth() -> TestResult {
let codex_home = tempfile::tempdir()?;
let config = ConfigBuilder::default()
.codex_home(codex_home.path().to_path_buf())
.fallback_cwd(Some(codex_home.path().to_path_buf()))
.cli_overrides(vec![("features.apps".to_string(), true.into())])
.build()
.await?;
let auth = CodexAuth::from_api_key("test");
let manager = installed_manager(&config, Some(auth.clone()));
let servers = manager.effective_servers(&config, Some(&auth)).await;
assert!(!servers.contains_key(CODEX_APPS_MCP_SERVER_NAME));
Ok(())
}
#[tokio::test]
async fn disabled_apps_remove_reserved_server_config_for_all_hosts() -> TestResult {
let codex_home = tempfile::tempdir()?;
let config = ConfigBuilder::default()
.codex_home(codex_home.path().to_path_buf())
.fallback_cwd(Some(codex_home.path().to_path_buf()))
.cli_overrides(vec![
("features.apps".to_string(), false.into()),
(
"mcp_servers.codex_apps.url".to_string(),
"https://example.com/mcp".into(),
),
])
.build()
.await?;
let managers = [
installed_manager(&config, /*auth*/ None),
McpManager::new(Arc::new(plugins_manager_for_config(
&config,
auth_manager_from_optional_auth(/*auth*/ None),
))),
];
for manager in managers {
let servers = manager.runtime_servers(&config).await;
assert!(!servers.contains_key(CODEX_APPS_MCP_SERVER_NAME));
}
Ok(())
}
fn installed_manager(config: &Config, auth: Option<CodexAuth>) -> McpManager {
let mut builder = ExtensionRegistryBuilder::new();
codex_mcp_extension::install(&mut builder);
McpManager::new_with_extensions(
Arc::new(plugins_manager_for_config(
config,
auth_manager_from_optional_auth(auth),
)),
Arc::new(builder.build()),
codex_core::CodexAppsToolsCache::default(),
)
}
struct RemoveCodexApps;
impl McpServerContributor<Config> for RemoveCodexApps {
fn id(&self) -> &'static str {
"remove_codex_apps"
}
fn contribute<'a>(
&'a self,
_context: McpServerContributionContext<'a, Config>,
) -> codex_extension_api::ExtensionFuture<'a, Vec<McpServerContribution>> {
Box::pin(async move {
vec![McpServerContribution::Remove {
name: CODEX_APPS_MCP_SERVER_NAME.to_string(),
}]
})
}
}