Honor per-executor plugin settings in capability discovery (#64052)

## Why

A plugin can be installed in several executor environments. Disabling one
installation should leave the others available, while a thread-wide exclusion
needs to apply across environments.

## What changed

- In executor capability discovery V2, allow an executor to list its own
  plugin installations subject to marketplace policy. A named entry such as
  `"notes@market": {}` inherits the executor default when the thread has
  no enablement preference. A default alone does not list any plugins.
- Apply thread enablement preferences across installations and scope executor
  opt-outs to the affected installation. When MCP server names are shared,
  use the first enabled installation.
- Preserve connector mappings for explicit `disabledPluginIds` exclusions
  so Apps tool search can honor them even when the executor has already
  disabled the installation.

## Testing

Add regression coverage for marketplace filtering, thread and executor
precedence, installation-scoped exclusions, and Apps connector suppression
after an executor opt-out.

GitOrigin-RevId: d3465a38f3ebf5042d5c45dabfdb32f8ada81727
This commit is contained in:
Anthony Tafoya
2026-11-26 02:32:11 +00:00
committed by copyberry
parent 5148e3d642
commit 963d4f5717
40 changed files with 843 additions and 117 deletions
+14 -3
View File
@@ -584,6 +584,12 @@ Attachment creation and deletion requests using the same thread ID are serialize
# Thread plugin settings
In `thread/start` config, a named plugin entry such as `"notes@market": {}`
lists the plugin. Without an explicit `enabled` flag, it inherits the default.
In the effective thread config, an empty `plugins._default` means
`enabled = true`. Omitting `plugins._default` leaves the fallback unset.
Plugin summaries returned by `plugin/list`, `plugin/installed`, `plugin/read`,
and `plugin/share/list` report effective `enabled` state. When
`plugins._default.enabled` is configured, an explicit
@@ -599,9 +605,14 @@ Apps authentication setup without writing an `enabled` override.
`thread/settings/update` and `turn/start` accept `disabledPluginIds`, a list of
`PluginSummary.id` values from `plugin/list`, in the
`<plugin-name>@<marketplace-name>` format. A supplied list replaces the selection;
omission or `null` preserves it, and `[]` clears it. Saving this selection does
not yet filter plugin capabilities.
`<plugin-name>@<marketplace-name>` format. A supplied list replaces the selection.
Omission or `null` preserves it, and `[]` clears it.
Setting a plugin's `enabled` flag to `false` in thread or executor config
does not by itself hide tools offered independently by Apps. With
`disabledPluginIds`, Core also hides Apps tools whose connector IDs it can
associate with an excluded plugin. A connector shared with another enabled
plugin remains visible unless its canonical owner is excluded.
Read the selection from `threadSettings.disabledPluginIds` in
`thread/settings/updated` notifications, or from `disabledPluginIds` in
+1 -8
View File
@@ -21,6 +21,7 @@ pub use codex_protocol::config_types::AltScreenMode;
pub use codex_protocol::config_types::ApprovalsReviewer;
pub use codex_protocol::config_types::ModeKind;
pub use codex_protocol::config_types::Personality;
pub use codex_protocol::config_types::PluginsDefaultConfig;
use codex_protocol::config_types::SERVICE_TIER_DEFAULT_REQUEST_VALUE;
pub use codex_protocol::config_types::ServiceTier;
use codex_protocol::config_types::ToolExposureSurface;
@@ -1168,14 +1169,6 @@ pub use crate::skills_config::BundledSkillsConfig;
pub use crate::skills_config::SkillConfig;
pub use crate::skills_config::SkillsConfig;
/// Default activation settings for installed plugins.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct PluginsDefaultConfig {
#[serde(default = "default_enabled")]
pub enabled: bool,
}
/// Plugin activation and capability settings loaded from configuration layers.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default, JsonSchema)]
#[schemars(deny_unknown_fields)]
+68 -9
View File
@@ -1,11 +1,70 @@
//! Source-neutral plugin catalogs, reconciliation, and source-aware enablement policy.
use codex_config::types::PluginConfig;
use crate::marketplace_policy::PluginMarketplaceFilter;
use crate::marketplace_policy::parse_configured_plugins;
use codex_config::ConfigLayerStack;
use codex_core_plugin_common::PluginIdentity;
use codex_protocol::protocol::EnvironmentPluginsConfig;
use codex_utils_path_uri::PathUri;
use serde_json::Value;
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::collections::HashSet;
use std::path::Path;
/// Thread configuration shared by all installations, with executor entries scoped by environment.
#[derive(Default)]
pub struct PluginCatalogConfig<'a> {
thread_plugin_ids: HashSet<String>,
/// Environments that list each additional plugin ID.
executor_plugin_ids: HashMap<&'a str, HashSet<&'a str>>,
}
impl<'a> PluginCatalogConfig<'a> {
/// Resolve marketplace policy once and check each distinct plugin ID once per selection.
pub fn from_thread_and_executors(
stack: &ConfigLayerStack,
codex_home: &Path,
executor_plugin_configs: impl IntoIterator<Item = (&'a str, &'a EnvironmentPluginsConfig)>,
) -> Self {
let mut config = stack.effective_config();
let thread_plugins = config.get("plugins").and_then(toml::Value::as_table);
let mut executor_plugin_ids: HashMap<&str, HashSet<&str>> = HashMap::new();
for (environment_id, plugins) in executor_plugin_configs {
for id in plugins.plugins.keys() {
// Check the original thread keys so a filtered-out ID cannot be reintroduced.
if !thread_plugins.is_some_and(|plugins| plugins.contains_key(id)) {
executor_plugin_ids
.entry(id)
.or_default()
.insert(environment_id);
}
}
}
if thread_plugins.is_none() && executor_plugin_ids.is_empty() {
return Self::default();
}
let filter = PluginMarketplaceFilter::new(&config, stack.requirements(), codex_home);
filter.retain_plugins(&mut config);
let Some(thread) = parse_configured_plugins(config) else {
return Self::default();
};
executor_plugin_ids.retain(|plugin_id, _| filter.allows_marketplace_for(plugin_id));
Self {
thread_plugin_ids: thread.into_keys().collect(),
executor_plugin_ids,
}
}
pub(crate) fn includes(&self, environment_id: &str, plugin_id: &str) -> bool {
self.thread_plugin_ids.contains(plugin_id)
|| self
.executor_plugin_ids
.get(plugin_id)
.is_some_and(|environments| environments.contains(environment_id))
}
}
/// One source's discovery snapshot; only a complete empty catalog establishes absence.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
@@ -30,11 +89,9 @@ pub struct PluginCatalogEntry {
}
impl PluginCatalogEntry {
/// Disabled entries never project. Otherwise Cloud membership supplies enablement;
/// executor-only entries require every installation's local plugin ID in the supplied
/// config, where omitted enablement retains the configured plugin's default.
/// A remote identity alone does not establish Cloud membership.
pub fn is_enabled(&self, configured_plugins: &HashMap<String, PluginConfig>) -> bool {
/// The source must enable the entry. Executor-only installations also
/// require a named entry that passes marketplace policy.
pub fn is_allowed_by(&self, config: &PluginCatalogConfig<'_>) -> bool {
if !self.enabled {
return false;
}
@@ -44,9 +101,11 @@ impl PluginCatalogEntry {
.any(|location| matches!(location, PluginSourceLocation::Cloud { .. }));
is_cloud_plugin
|| self.locations.iter().all(|location| match location {
PluginSourceLocation::Executor { plugin_id, .. } => configured_plugins
.get(plugin_id)
.is_some_and(|plugin| plugin.enabled.unwrap_or(true)),
PluginSourceLocation::Executor {
environment_id,
plugin_id,
..
} => config.includes(environment_id, plugin_id),
PluginSourceLocation::Cloud { .. } => true,
})
}
+1
View File
@@ -62,6 +62,7 @@ pub use app_mcp_routing::apps_route_available;
pub use artifact_operation::ArtifactOperation;
pub use artifact_operation::recognize_artifact_operation;
pub use catalog::PluginCatalog;
pub use catalog::PluginCatalogConfig;
pub use catalog::PluginCatalogEntry;
pub use catalog::PluginSourceLocation;
pub use catalog::merge_catalogs;
+77 -44
View File
@@ -213,50 +213,78 @@ pub(crate) fn policy_filtered_plugin_config(
config_layer_stack: &ConfigLayerStack,
codex_home: &Path,
) -> Option<toml::Value> {
let mut effective_config = config_layer_stack.effective_config();
if effective_config.get("plugins").is_none() && effective_config.get("marketplaces").is_none() {
let mut config = config_layer_stack.effective_config();
if config.get("plugins").is_none() && config.get("marketplaces").is_none() {
return None;
}
let policy = MarketplacePolicy::from_requirements(config_layer_stack.requirements());
let allowed_marketplace_names =
allowed_configured_marketplace_names_with_policy(&effective_config, &policy, codex_home);
let configured_marketplace_names = effective_config
.get("marketplaces")
.and_then(toml::Value::as_table)
.map(|marketplaces| marketplaces.keys().cloned().collect::<HashSet<_>>())
.unwrap_or_default();
if let Some(marketplaces) = effective_config
let filter =
PluginMarketplaceFilter::new(&config, config_layer_stack.requirements(), codex_home);
if let Some(marketplaces) = config
.get_mut("marketplaces")
.and_then(toml::Value::as_table_mut)
{
marketplaces
.retain(|marketplace_name, _| allowed_marketplace_names.contains(marketplace_name));
marketplaces.retain(|name, _| filter.allowed_marketplaces.contains(name));
}
if let Some(plugins) = effective_config
.get_mut("plugins")
.and_then(toml::Value::as_table_mut)
{
plugins.retain(|plugin_key, _| {
if plugin_key == "_default" {
return true;
}
let Ok(plugin_id) = PluginId::parse(plugin_key) else {
return !policy.is_restricted();
};
let marketplace_name = &plugin_id.marketplace_name;
if configured_marketplace_names.contains(marketplace_name) {
return allowed_marketplace_names.contains(marketplace_name);
}
if is_openai_curated_marketplace_name(marketplace_name) {
return policy
.validate_git_source(OPENAI_PLUGINS_GIT_URL, /*ref_name*/ None)
.is_ok();
}
!policy.is_restricted()
});
filter.retain_plugins(&mut config);
Some(config)
}
/// Keep the original marketplace names so a blocked source cannot look unconfigured.
pub(crate) struct PluginMarketplaceFilter {
policy: MarketplacePolicy,
allowed_marketplaces: HashSet<String>,
configured_marketplaces: HashSet<String>,
}
impl PluginMarketplaceFilter {
pub(crate) fn new(
config: &toml::Value,
requirements: &ConfigRequirements,
codex_home: &Path,
) -> Self {
let policy = MarketplacePolicy::from_requirements(requirements);
let allowed_marketplaces =
allowed_configured_marketplace_names_with_policy(config, &policy, codex_home);
let configured_marketplaces = config
.get("marketplaces")
.and_then(toml::Value::as_table)
.map(|marketplaces| marketplaces.keys().cloned().collect())
.unwrap_or_default();
Self {
policy,
allowed_marketplaces,
configured_marketplaces,
}
}
pub(crate) fn retain_plugins(&self, config: &mut toml::Value) {
if let Some(plugins) = config
.get_mut("plugins")
.and_then(toml::Value::as_table_mut)
{
plugins.retain(|plugin_id, _| self.allows_marketplace_for(plugin_id));
}
}
pub(crate) fn allows_marketplace_for(&self, plugin_id: &str) -> bool {
if plugin_id == "_default" {
return true;
}
let Ok(plugin_id) = PluginId::parse(plugin_id) else {
return !self.policy.is_restricted();
};
let marketplace_name = &plugin_id.marketplace_name;
if self.configured_marketplaces.contains(marketplace_name) {
return self.allowed_marketplaces.contains(marketplace_name);
}
if is_openai_curated_marketplace_name(marketplace_name) {
return self
.policy
.validate_git_source(OPENAI_PLUGINS_GIT_URL, /*ref_name*/ None)
.is_ok();
}
!self.policy.is_restricted()
}
Some(effective_config)
}
pub fn allowed_configured_marketplace_names(
@@ -299,18 +327,23 @@ pub fn configured_plugins_from_stack(
config_layer_stack: &ConfigLayerStack,
codex_home: &Path,
) -> HashMap<String, PluginConfig> {
let Some(effective_config) = policy_filtered_plugin_config(config_layer_stack, codex_home)
else {
let Some(config) = policy_filtered_plugin_config(config_layer_stack, codex_home) else {
return HashMap::new();
};
let Some(plugins_value) = effective_config.get("plugins") else {
return HashMap::new();
parse_configured_plugins(config).unwrap_or_default()
}
pub(crate) fn parse_configured_plugins(
mut config: toml::Value,
) -> Option<HashMap<String, PluginConfig>> {
let Some(plugins) = config.as_table_mut()?.remove("plugins") else {
return Some(HashMap::new());
};
match PluginsConfigToml::deserialize(plugins_value.clone()) {
Ok(plugins) => plugins.plugins,
match PluginsConfigToml::deserialize(plugins) {
Ok(plugins) => Some(plugins.plugins),
Err(err) => {
tracing::warn!("invalid plugins config: {err}");
HashMap::new()
None
}
}
}
@@ -584,6 +584,28 @@ enabled = true
vec!["sample@allowed".to_string()]
);
let opt_ins = serde_json::from_value(serde_json::json!({
"sample@blocked": { "enabled": true },
"extra@allowed": {},
"extra@blocked": {},
}))
.expect("executor plugin settings");
let catalog = crate::PluginCatalogConfig::from_thread_and_executors(
&stack,
codex_home.path(),
[("a", &opt_ins), ("b", &opt_ins)],
);
// A shared policy decision for the same extra ID must preserve both opt-ins.
for environment in ["a", "b", "c"] {
assert!(catalog.includes(environment, "sample@allowed"));
assert!(!catalog.includes(environment, "sample@blocked"));
assert!(!catalog.includes(environment, "extra@blocked"));
assert_eq!(
catalog.includes(environment, "extra@allowed"),
environment != "c"
);
}
let raw = stack.effective_user_config().expect("raw user config");
assert!(raw["marketplaces"]["blocked"].is_table());
assert!(raw["plugins"]["sample@blocked"].is_table());
+1
View File
@@ -404,6 +404,7 @@ fn resolved_local_environments<const N: usize>(
),
shell_environment_policy: Default::default(),
exec_policy: None,
plugins: Default::default(),
mcp_policy: None,
network_policy: None,
selected_capability_roots: Vec::new(),
@@ -49,6 +49,7 @@ pub(super) fn test_environment_config() -> EnvironmentConfig {
permission_profile: PermissionProfileSnapshot::legacy(PermissionProfile::read_only()),
shell_environment_policy: Default::default(),
exec_policy: None,
plugins: Default::default(),
mcp_policy: None,
network_policy: None,
selected_capability_roots: Vec::new(),
@@ -236,6 +237,7 @@ async fn local_environment_uses_configured_shell_and_login_policy() {
),
shell_environment_policy: Default::default(),
exec_policy: None,
plugins: Default::default(),
mcp_policy: None,
network_policy: None,
selected_capability_roots: Vec::new(),
@@ -516,6 +518,7 @@ async fn snapshot_refreshes_readiness_in_selection_order(
),
shell_environment_policy: Default::default(),
exec_policy: None,
plugins: Default::default(),
mcp_policy: None,
network_policy: None,
selected_capability_roots: Vec::new(),
@@ -955,6 +958,7 @@ async fn inherited_environment_reuses_parent_handle_and_uses_child_config() {
),
shell_environment_policy: Default::default(),
exec_policy: None,
plugins: Default::default(),
mcp_policy: None,
network_policy: None,
selected_capability_roots: Vec::new(),
@@ -1031,6 +1035,7 @@ async fn owner_environment_config_is_inherited_and_reset_for_new_cwd() {
permission_profile: PermissionProfileSnapshot::legacy(PermissionProfile::read_only()),
shell_environment_policy: Default::default(),
exec_policy: None,
plugins: Default::default(),
mcp_policy: None,
network_policy: None,
selected_capability_roots: vec![root("parent-root")],
+52 -21
View File
@@ -18,6 +18,7 @@ use codex_extension_api::ExtensionDataInit;
use codex_extension_api::ExtensionRegistry;
use codex_extension_api::McpServerContribution;
use codex_extension_api::McpServerContributionContext;
use codex_extension_api::PluginEnablement;
use codex_extension_api::SelectedPlugin;
use codex_extension_api::SelectedPluginIdentity;
use codex_extension_api::SelectedPluginSnapshot;
@@ -259,11 +260,11 @@ impl McpManager {
&self,
context: McpServerContributionContext<'a, Config>,
plugins_config: &PluginsConfigToml,
disabled_plugin_ids: &'a [String],
explicitly_disabled_plugin_ids: &'a [String],
) -> SelectedPluginSnapshot {
let context = context.with_disabled_plugin_ids(disabled_plugin_ids);
let context = context.with_disabled_plugin_ids(explicitly_disabled_plugin_ids);
let mut selected = SelectedPluginSnapshot {
disabled_plugin_ids: disabled_plugin_ids.to_vec(),
disabled_plugin_ids: explicitly_disabled_plugin_ids.to_vec(),
..Default::default()
};
let available_roots = available_plugin_roots(context);
@@ -280,13 +281,21 @@ impl McpManager {
if !available_roots.contains(&selected_root_id) {
continue;
}
if !enabled
if enabled != PluginEnablement::Enabled
|| legacy_thread_disables_plugin(context, plugins_config, &plugin_id)
|| !context.config().features.enabled(Feature::Plugins)
|| !plugins_config.allows_plugin(&plugin_id)
|| disabled_plugin_ids.contains(&plugin_id)
|| disabled_plugin_ids.iter().any(|id| id == identity.as_str())
|| explicitly_disabled_plugin_ids.contains(&plugin_id)
|| explicitly_disabled_plugin_ids
.iter()
.any(|id| id == identity.as_str())
{
selected.disabled_plugin_roots.push(selected_root_id);
if enabled == PluginEnablement::DisabledForThread
&& context.executor_capability_discovery_v2().is_some()
&& !selected.disabled_plugin_ids.contains(&plugin_id)
{
selected.disabled_plugin_ids.push(plugin_id);
}
} else {
selected.plugins.push(SelectedPluginIdentity {
selected_root_id: Some(selected_root_id),
@@ -296,7 +305,7 @@ impl McpManager {
}
if context.config().features.enabled(Feature::Plugins) {
for plugin_id in contributor.hosted_plugin_ids(context) {
if !disabled_plugin_ids.contains(&plugin_id) {
if !explicitly_disabled_plugin_ids.contains(&plugin_id) {
selected.plugins.push(SelectedPluginIdentity {
selected_root_id: None,
plugin_id: CatalogPluginIdentity::Remote {
@@ -315,7 +324,7 @@ impl McpManager {
context: McpServerContributionContext<'_, Config>,
originator: Option<&str>,
environment_scope: McpEnvironmentScope<'_>,
disabled_plugin_ids: &[String],
explicitly_disabled_plugin_ids: &[String],
) -> McpRuntimeProjection {
let config = context.config();
if context
@@ -336,7 +345,7 @@ impl McpManager {
let mut selected_plugin_registrations = Vec::new();
let mut selected_plugins = Vec::new();
let mut disabled_plugin_roots = Vec::new();
let mut suppressed_plugin_ids = disabled_plugin_ids.to_vec();
let mut thread_disabled_plugin_ids = explicitly_disabled_plugin_ids.to_vec();
let mut overlays = Vec::new();
// A contributor can emit multiple ordered actions, so order each action globally rather
// than enumerating contributors.
@@ -353,18 +362,30 @@ impl McpManager {
mcp,
} in contributor.selected_plugins(context, plugins_config).await
{
if !enabled || !plugins_config.allows_plugin(&plugin_id) {
let disabled_for_thread = enabled == PluginEnablement::DisabledForThread
|| legacy_thread_disables_plugin(context, plugins_config, &plugin_id);
let disabled_for_installation =
enabled == PluginEnablement::DisabledForInstallation;
let excluded_by_plugin_id = explicitly_disabled_plugin_ids.contains(&plugin_id);
let excluded_by_caller = excluded_by_plugin_id
|| explicitly_disabled_plugin_ids
.iter()
.any(|id| id == identity.as_str());
// Apps needs the connector mapping when the caller excludes this plugin ID.
if (disabled_for_thread || disabled_for_installation) && !excluded_by_plugin_id {
disabled_plugin_roots.push(selected_root_id);
suppressed_plugin_ids.push(plugin_id);
if disabled_for_thread && !thread_disabled_plugin_ids.contains(&plugin_id) {
thread_disabled_plugin_ids.push(plugin_id);
}
continue;
}
let selection_order = plugin_selection_order;
plugin_selection_order += 1;
let disabled = disabled_plugin_ids.contains(&plugin_id)
|| disabled_plugin_ids.iter().any(|id| id == identity.as_str());
if !config.features.enabled(Feature::Plugins) || disabled {
if !config.features.enabled(Feature::Plugins) || excluded_by_caller {
disabled_plugin_roots.push(selected_root_id);
suppressed_plugin_ids.push(plugin_id.clone());
if !thread_disabled_plugin_ids.contains(&plugin_id) {
thread_disabled_plugin_ids.push(plugin_id.clone());
}
} else {
selected_plugins.push(SelectedPluginIdentity {
selected_root_id: Some(selected_root_id),
@@ -372,7 +393,7 @@ impl McpManager {
});
}
let contribution = mcp.await;
if !disabled {
if !excluded_by_caller {
for (name, server) in contribution.servers {
selected_plugin_registrations.push(
McpServerRegistration::from_selected_plugin(
@@ -464,7 +485,7 @@ impl McpManager {
connector_ids,
} => {
if config.features.enabled(Feature::Plugins) {
if !disabled_plugin_ids.contains(&plugin_id) {
if !explicitly_disabled_plugin_ids.contains(&plugin_id) {
selected_plugins.push(SelectedPluginIdentity {
selected_root_id: None,
plugin_id: CatalogPluginIdentity::Remote {
@@ -506,12 +527,12 @@ impl McpManager {
let connector_snapshot = if config.features.enabled(Feature::Plugins) {
self.plugins_manager.connector_snapshot(
host_plugin_connector_sources.chain(selected_plugin_connector_sources),
disabled_plugin_ids,
explicitly_disabled_plugin_ids,
)
} else {
Default::default()
};
let loaded_plugins = loaded_plugins.without_plugins(disabled_plugin_ids);
let loaded_plugins = loaded_plugins.without_plugins(explicitly_disabled_plugin_ids);
let plugins_available =
!selected_plugins.is_empty() || !loaded_plugins.capability_summaries().is_empty();
let mut mcp_config = config
@@ -572,7 +593,7 @@ impl McpManager {
selected_plugins: SelectedPluginSnapshot {
plugins: selected_plugins,
disabled_plugin_roots,
disabled_plugin_ids: suppressed_plugin_ids,
disabled_plugin_ids: thread_disabled_plugin_ids,
},
}
}
@@ -604,6 +625,16 @@ impl McpManager {
}
}
/// Only V1 and direct root selection need Core's thread-config check.
/// V2 already includes the thread's settings in `SelectedPlugin::enabled`.
fn legacy_thread_disables_plugin(
context: McpServerContributionContext<'_, Config>,
thread_plugins: &PluginsConfigToml,
plugin_id: &str,
) -> bool {
context.executor_capability_discovery_v2().is_none() && !thread_plugins.allows_plugin(plugin_id)
}
fn available_plugin_roots(context: McpServerContributionContext<'_, Config>) -> HashSet<String> {
let mut roots = context
.ready_selected_capability_roots()
+1
View File
@@ -1689,6 +1689,7 @@ async fn mcp_sandbox_cwd_uses_matching_server_environment_uri() -> anyhow::Resul
.snapshot(),
shell_environment_policy: Default::default(),
exec_policy: None,
plugins: Default::default(),
mcp_policy: None,
network_policy: None,
selected_capability_roots: Vec::new(),
+1
View File
@@ -221,6 +221,7 @@ impl SessionConfiguration {
.windows_sandbox_type_from_config(),
use_legacy_landlock: self.use_legacy_landlock,
exec_policy: None,
plugins: Default::default(),
mcp_policy: None,
network_policy: None,
selected_capability_roots: Vec::new(),
@@ -387,6 +387,7 @@ async fn inactive_profiles_keep_snapshots_but_active_brokers_require_sandbox() -
permission_profile: PermissionProfileSnapshot::legacy(permission_profile),
shell_environment_policy: ShellEnvironmentPolicy::default(),
exec_policy: None,
plugins: Default::default(),
mcp_policy: None,
network_policy: None,
selected_capability_roots: Vec::new(),
+2 -1
View File
@@ -2081,6 +2081,7 @@ async fn spawn_internal_session_preserves_parent_lineage_without_forking_history
exec_policy: Some(codex_execpolicy::RequirementsExecPolicy::new(
codex_execpolicy::Policy::empty(),
)),
plugins: Default::default(),
mcp_policy: None,
network_policy: None,
selected_capability_roots: Vec::new(),
@@ -2369,7 +2370,7 @@ async fn start_thread_seeds_extension_data_for_mcp_and_lifecycle_contributors()
identity: codex_core_plugins::PluginIdentity::Local {
plugin_id: plugin_id.clone(),
},
enabled: true,
enabled: codex_extension_api::PluginEnablement::Enabled,
mcp: Box::pin(async move {
mcp_loaded.fetch_add(1, Ordering::Relaxed);
codex_extension_api::SelectedPluginContribution {
@@ -40,6 +40,7 @@ fn test_turn_environment(environment_id: &str) -> crate::session::turn_context::
),
shell_environment_policy: Default::default(),
exec_policy: None,
plugins: Default::default(),
mcp_policy: None,
network_policy: None,
selected_capability_roots: Vec::new(),
@@ -759,6 +759,7 @@ mod tests {
),
shell_environment_policy: Default::default(),
exec_policy: None,
plugins: Default::default(),
mcp_policy: None,
network_policy: None,
selected_capability_roots: Vec::new(),
+1
View File
@@ -173,6 +173,7 @@ pub fn environment_config_for_selection(
windows_sandbox_type: permissions.windows_sandbox_type,
use_legacy_landlock: config.features.use_legacy_landlock(),
exec_policy: None,
plugins: Default::default(),
mcp_policy: None,
network_policy: None,
selected_capability_roots: Vec::new(),
@@ -483,6 +483,7 @@ async fn v2_residency_reload_preserves_inherited_environment_and_tools(
windows_sandbox_type: test.config.permissions.windows_sandbox_type,
use_legacy_landlock: test.config.features.use_legacy_landlock(),
exec_policy: None,
plugins: Default::default(),
mcp_policy: None,
network_policy: None,
selected_capability_roots: Vec::new(),
+3
View File
@@ -919,6 +919,7 @@ async fn environment_command_restrictions_override_saved_prefix_approvals() -> R
windows_sandbox_type: test.config.permissions.windows_sandbox_type,
use_legacy_landlock: test.config.features.use_legacy_landlock(),
exec_policy: Some(RequirementsExecPolicy::new(invalid_policy)),
plugins: Default::default(),
mcp_policy: None,
network_policy: None,
selected_capability_roots: Vec::new(),
@@ -947,6 +948,7 @@ async fn environment_command_restrictions_override_saved_prefix_approvals() -> R
windows_sandbox_type: test.config.permissions.windows_sandbox_type,
use_legacy_landlock: test.config.features.use_legacy_landlock(),
exec_policy: Some(RequirementsExecPolicy::new(environment_policy)),
plugins: Default::default(),
mcp_policy: None,
network_policy: None,
selected_capability_roots: Vec::new(),
@@ -1056,6 +1058,7 @@ async fn environment_command_policy_changes_invalidate_session_approvals() -> Re
windows_sandbox_type: test.config.permissions.windows_sandbox_type,
use_legacy_landlock: test.config.features.use_legacy_landlock(),
exec_policy: Some(RequirementsExecPolicy::new(policy)),
plugins: Default::default(),
mcp_policy: None,
network_policy: None,
selected_capability_roots: Vec::new(),
@@ -150,7 +150,7 @@ impl McpServerContributor<Config> for DiscoveryRecorder {
plugin_id: "inert-sentinel@market".to_string(),
},
plugin_id: "inert-sentinel@market".to_string(),
enabled: true,
enabled: codex_extension_api::PluginEnablement::Enabled,
mcp: Box::pin(async {
codex_extension_api::SelectedPluginContribution {
plugin_display_name: "Inert sentinel".to_string(),
@@ -1357,6 +1357,7 @@ pub(super) async fn check_acquisition(enabled: bool, version: &'static str) -> R
windows_sandbox_type: test.config.permissions.windows_sandbox_type,
use_legacy_landlock: test.config.features.use_legacy_landlock(),
exec_policy: None,
plugins: Default::default(),
mcp_policy: None,
network_policy: None,
selected_capability_roots: if acquires_v2 {
@@ -2134,11 +2135,180 @@ async fn auth_rotation_refreshes_plugin_acceptance_before_merged_skills() -> Res
Ok(())
}
#[test_case::test_case("Stop"; "stop")]
#[test_case::test_case("Interrupt"; "interrupt")]
#[test_case::test_case(true; "thread disable without a default")]
#[test_case::test_case(false; "executor opt out")]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn v2_plugin_disable_preserves_scope(thread_denies: bool) -> Result<()> {
skip_if_no_network!(Ok(()));
let executor = Executor::start(/*supports_v2*/ true, DiscoveryFailure::None).await?;
let model = responses::start_mock_server().await;
let home = Arc::new(tempfile::TempDir::new()?);
let plugin_id = "inert-sentinel@market";
let setting = if thread_denies { "enabled = false" } else { "" };
std::fs::write(
home.path().join("config.toml"),
format!("[plugins.\"{plugin_id}\"]\n{setting}\n"),
)?;
let selected_plugins = Arc::new(Mutex::new(None));
let mut extensions = ExtensionRegistryBuilder::new();
extensions.tool_contributor(Arc::new(DiscoveryRecorder {
mcp_projections: AtomicUsize::new(0),
snapshots: Arc::new(Mutex::new(Vec::new())),
selected_plugins: Arc::clone(&selected_plugins),
}));
codex_mcp_extension::install_plugins(
&mut extensions,
Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()),
);
let test = test_codex()
.with_home(home)
.with_extensions(Arc::new(extensions.build()))
.with_exec_server_url(executor.url.clone())
.with_config(|config| {
config
.features
.enable(Feature::Plugins)
.expect("enable plugins");
config
.features
.enable(Feature::ExecutorCapabilityDiscoveryV2)
.expect("enable V2");
})
.build_with_auto_env(&model)
.await?;
let mut selection = test.executor_environment().selection().clone();
selection.environment_id = codex_exec_server::REMOTE_ENVIRONMENT_ID.to_string();
let root_id = format!("{}:{plugin_id}", selection.environment_id);
let mut config = environment_config_for_selection(&test.config, &selection);
config.plugins = serde_json::from_value(json!({ (plugin_id): { "enabled": thread_denies } }))?;
selection.config = codex_protocol::protocol::EnvironmentConfigState::Ready(config);
responses::mount_sse_once(
&model,
responses::sse(vec![
responses::ev_response_created("response"),
responses::ev_completed("response"),
]),
)
.await;
test.submit_turn_with_environments("Hello", Some(vec![selection]))
.await?;
let snapshot = selected_plugins
.lock()
.await
.take()
.context("step plugin snapshot")?;
assert_eq!(snapshot.disabled_plugin_roots, vec![root_id]);
let expected_ids = if thread_denies {
vec![plugin_id.to_string()]
} else {
Vec::new()
};
assert_eq!(snapshot.disabled_plugin_ids, expected_ids);
Ok(())
}
/// An executor opt-out must not undo an explicit plugin ID exclusion from Apps tool search.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn v2_executor_opt_out_preserves_disabled_plugin_connectors() -> Result<()> {
skip_if_no_network!(Ok(()));
let executor = Executor::start(/*supports_v2*/ true, DiscoveryFailure::None).await?;
let plugin_id = "calendar@market";
*executor.inventory.lock().await = Some(json!({
"plugins": [{
"id": plugin_id, "displayName": "Calendar", "remotePluginId": null,
"version": "1", "root": "file:///calendar",
"files": {
"manifest": {"path": "file:///calendar/.codex-plugin/plugin.json",
"contents": r#"{"name":"calendar"}"#},
"mcpConfig": null,
"appsConfig": {"path": "file:///calendar/.app.json",
"contents": r#"{"apps":{"calendar":{"id":"calendar"}}}"#}
},
"skills": []
}],
"skills": [], "warnings": []
}));
let model = responses::start_mock_server().await;
let apps = AppsTestServer::mount_with_connector_name(&model, "Google Calendar").await?;
let mut extensions = ExtensionRegistryBuilder::new();
codex_mcp_extension::install_plugins(
&mut extensions,
Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()),
);
let test = test_codex()
.with_auth(CodexAuth::create_dummy_chatgpt_auth_for_testing())
.with_extensions(Arc::new(extensions.build()))
.with_exec_server_url(executor.url.clone())
.with_config(move |config| {
config.chatgpt_base_url = apps.chatgpt_base_url;
for feature in [
Feature::Apps,
Feature::Plugins,
Feature::ExecutorCapabilityDiscoveryV2,
] {
config
.features
.enable(feature)
.expect("enable Apps and executor plugin discovery");
}
})
.build_with_auto_env(&model)
.await?;
let mut selection = test.executor_environment().selection().clone();
selection.environment_id = codex_exec_server::REMOTE_ENVIRONMENT_ID.to_owned();
let mut config = environment_config_for_selection(&test.config, &selection);
config.plugins = serde_json::from_value(json!({ (plugin_id): { "enabled": false } }))?;
selection.config = codex_protocol::protocol::EnvironmentConfigState::Ready(config);
for (call_id, disabled_ids, visible) in [
("local-only", vec![], true),
("explicit-disable", vec![plugin_id.to_owned()], false),
] {
test.codex
.update_thread_settings(codex_protocol::protocol::ThreadSettingsOverrides {
disabled_plugin_ids: Some(disabled_ids),
..Default::default()
})
.await?;
let mock = responses::mount_sse_sequence(
&model,
vec![
responses::sse(vec![
responses::ev_tool_search_call(
call_id,
&json!({"query": "create calendar event"}),
),
responses::ev_completed("search"),
]),
responses::sse(vec![responses::ev_completed("done")]),
],
)
.await;
test.submit_turn_with_environments(
"Find the calendar tool.",
Some(vec![selection.clone()]),
)
.await?;
let output = mock.requests()[1].tool_search_output(call_id);
assert_eq!(
responses::namespace_child_tool(
&output,
"mcp__codex_apps__google_calendar",
core_test_support::apps_test_server::SEARCH_CALENDAR_CREATE_TOOL,
)
.is_some(),
visible
);
}
Ok(())
}
#[test_case::test_case("Stop", false; "stop")]
#[test_case::test_case("Interrupt", false; "interrupt")]
#[test_case::test_case("Stop", true; "executor opt in")]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn v2_cleanup_hooks_follow_plugin_selection_without_legacy_roots(
hook_event: &'static str,
executor_opt_in: bool,
) -> Result<()> {
skip_if_no_network!(Ok(()));
let model = responses::start_mock_server().await;
@@ -2195,10 +2365,12 @@ async fn v2_cleanup_hooks_follow_plugin_selection_without_legacy_roots(
Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()),
);
let home = Arc::new(tempfile::TempDir::new()?);
std::fs::write(
home.path().join("config.toml"),
"[plugins.\"computer-use@openai-bundled\"]\nenabled = true\n",
)?;
if !executor_opt_in {
std::fs::write(
home.path().join("config.toml"),
"[plugins.\"computer-use@openai-bundled\"]\nenabled = true\n",
)?;
}
let test = test_codex()
.with_home(home)
.with_extensions(Arc::new(extensions.build()))
@@ -2231,6 +2403,12 @@ async fn v2_cleanup_hooks_follow_plugin_selection_without_legacy_roots(
let mut selection = test.executor_environment().selection().clone();
selection.environment_id = codex_exec_server::REMOTE_ENVIRONMENT_ID.to_string();
selection.selected_capability_roots = Default::default();
if executor_opt_in {
let mut config = environment_config_for_selection(&test.config, &selection);
config.plugins =
serde_json::from_value(json!({"computer-use@openai-bundled": {"enabled": true}}))?;
selection.config = codex_protocol::protocol::EnvironmentConfigState::Ready(config);
}
for disabled in [false, true] {
core_test_support::submit_thread_settings(
&test.codex,
@@ -2225,6 +2225,7 @@ async fn guardian_session_is_reused_for_consecutive_tool_reviews_without_prewarm
windows_sandbox_type: test.config.permissions.windows_sandbox_type,
use_legacy_landlock: test.config.features.use_legacy_landlock(),
exec_policy: None,
plugins: Default::default(),
mcp_policy: None,
network_policy: None,
selected_capability_roots: Vec::new(),
@@ -1854,6 +1854,7 @@ impl ExecutorHookFixture {
windows_sandbox_type: self.test.config.permissions.windows_sandbox_type,
use_legacy_landlock: self.test.config.features.use_legacy_landlock(),
exec_policy: None,
plugins: Default::default(),
mcp_policy: None,
network_policy: None,
selected_capability_roots: self
@@ -377,6 +377,7 @@ async fn skill_mcp_dependency_oauth_uses_configured_http_client() -> Result<()>
windows_sandbox_type: fixture.config.permissions.windows_sandbox_type,
use_legacy_landlock: fixture.config.features.use_legacy_landlock(),
exec_policy: None,
plugins: Default::default(),
mcp_policy: Some(EnvironmentMcpPolicy {
servers: Some(BTreeMap::from([(
SERVER_NAME.to_string(),
@@ -1034,6 +1034,7 @@ async fn root_reconciliation_reuses_pending_apps_startup() -> Result<()> {
windows_sandbox_type: test.config.permissions.windows_sandbox_type,
use_legacy_landlock: test.config.features.use_legacy_landlock(),
exec_policy: None,
plugins: Default::default(),
mcp_policy: None,
network_policy: None,
selected_capability_roots: vec![SelectedCapabilityRoot {
@@ -1925,6 +1925,7 @@ async fn unattributed_network_request_uses_active_turn_environment_fallback(
windows_sandbox_type: test.config.permissions.windows_sandbox_type,
use_legacy_landlock: test.config.features.use_legacy_landlock(),
exec_policy: None,
plugins: Default::default(),
mcp_policy: None,
network_policy: None,
selected_capability_roots: vec![root.clone()],
@@ -2897,6 +2898,7 @@ async fn owner_network_policy_follows_the_selected_remote_command() -> Result<()
windows_sandbox_type: test.config.permissions.windows_sandbox_type,
use_legacy_landlock: test.config.features.use_legacy_landlock(),
exec_policy: None,
plugins: Default::default(),
mcp_policy: None,
network_policy: Some(environment_policy_from_config(
&proxy_config,
@@ -3123,6 +3125,7 @@ async fn escalated_owner_network_terminal_requires_stdin_approval(
windows_sandbox_type: test.config.permissions.windows_sandbox_type,
use_legacy_landlock: test.config.features.use_legacy_landlock(),
exec_policy: None,
plugins: Default::default(),
mcp_policy: None,
network_policy: Some(environment_policy_from_config(
&proxy, /*managed_allowed_domains_only*/ true,
+9
View File
@@ -638,6 +638,7 @@ async fn environment_permissions_follow_configuration_ownership() -> Result<()>
windows_sandbox_type: test.config.permissions.windows_sandbox_type,
use_legacy_landlock: test.config.features.use_legacy_landlock(),
exec_policy: None,
plugins: Default::default(),
mcp_policy: None,
network_policy: None,
selected_capability_roots: Vec::new(),
@@ -1706,6 +1707,7 @@ async fn shared_executor_keeps_ready_capability_roots_scoped_to_each_attachment(
windows_sandbox_type: test.config.permissions.windows_sandbox_type,
use_legacy_landlock: test.config.features.use_legacy_landlock(),
exec_policy: None,
plugins: Default::default(),
mcp_policy: None,
network_policy: None,
selected_capability_roots: vec![root("duplicate"), root("duplicate")],
@@ -1749,6 +1751,7 @@ async fn shared_executor_keeps_ready_capability_roots_scoped_to_each_attachment(
windows_sandbox_type: test.config.permissions.windows_sandbox_type,
use_legacy_landlock: test.config.features.use_legacy_landlock(),
exec_policy: None,
plugins: Default::default(),
mcp_policy: None,
network_policy: None,
selected_capability_roots: vec![root("startup-root"), root("second-root")],
@@ -1776,6 +1779,7 @@ async fn shared_executor_keeps_ready_capability_roots_scoped_to_each_attachment(
windows_sandbox_type: test.config.permissions.windows_sandbox_type,
use_legacy_landlock: test.config.features.use_legacy_landlock(),
exec_policy: None,
plugins: Default::default(),
mcp_policy: None,
network_policy: None,
selected_capability_roots: vec![root("first-root")],
@@ -1838,6 +1842,7 @@ async fn shared_executor_keeps_ready_capability_roots_scoped_to_each_attachment(
windows_sandbox_type: test.config.permissions.windows_sandbox_type,
use_legacy_landlock: test.config.features.use_legacy_landlock(),
exec_policy: None,
plugins: Default::default(),
mcp_policy: None,
network_policy: None,
selected_capability_roots: vec![root("first-updated-root")],
@@ -1899,6 +1904,7 @@ async fn owner_network_policy_rejects_unsupported_environment_authority() -> Res
windows_sandbox_type: test.config.permissions.windows_sandbox_type,
use_legacy_landlock: test.config.features.use_legacy_landlock(),
exec_policy: None,
plugins: Default::default(),
mcp_policy: None,
network_policy: Some(environment_policy_from_config(
&NetworkProxyConfig::default(),
@@ -2001,6 +2007,7 @@ async fn pending_attachment_installs_configuration_before_waiting_turn_resumes()
windows_sandbox_type: test.config.permissions.windows_sandbox_type,
use_legacy_landlock: test.config.features.use_legacy_landlock(),
exec_policy: None,
plugins: Default::default(),
mcp_policy: None,
network_policy: None,
selected_capability_roots: vec![root(id)],
@@ -2453,6 +2460,7 @@ async fn future_pending_environment_can_finish_without_retargeting_the_active_tu
windows_sandbox_type: test.config.permissions.windows_sandbox_type,
use_legacy_landlock: test.config.features.use_legacy_landlock(),
exec_policy: None,
plugins: Default::default(),
mcp_policy: None,
network_policy: None,
selected_capability_roots: vec![SelectedCapabilityRoot {
@@ -3161,6 +3169,7 @@ async fn deferred_executor_spawn_agent_inherits_ready_step_environments(
windows_sandbox_type: test.config.permissions.windows_sandbox_type,
use_legacy_landlock: test.config.features.use_legacy_landlock(),
exec_policy: None,
plugins: Default::default(),
mcp_policy: None,
network_policy: None,
selected_capability_roots: Vec::new(),
+3
View File
@@ -937,6 +937,7 @@ async fn environment_mcp_policy_filters_runtime_config_and_model_tools(
windows_sandbox_type: fixture.config.permissions.windows_sandbox_type,
use_legacy_landlock: fixture.config.features.use_legacy_landlock(),
exec_policy: None,
plugins: Default::default(),
mcp_policy: Some(mcp_policy),
network_policy: None,
selected_capability_roots: Vec::new(),
@@ -1056,6 +1057,7 @@ async fn future_environment_mcp_policy_applies_on_the_next_turn() -> anyhow::Res
windows_sandbox_type: fixture.config.permissions.windows_sandbox_type,
use_legacy_landlock: fixture.config.features.use_legacy_landlock(),
exec_policy: None,
plugins: Default::default(),
mcp_policy: Some(EnvironmentMcpPolicy {
servers: Some(BTreeMap::from([(
"environment_policy".to_string(),
@@ -2700,6 +2702,7 @@ async fn stdio_mcp_tool_call_includes_sandbox_state_meta(
windows_sandbox_type: fixture.config.permissions.windows_sandbox_type,
use_legacy_landlock: fixture.config.features.use_legacy_landlock(),
exec_policy: None,
plugins: Default::default(),
mcp_policy: None,
network_policy: None,
selected_capability_roots: Vec::new(),
@@ -775,6 +775,7 @@ async fn shell_snapshot_v2_guardian_uses_its_resolved_permissions_and_tools(
windows_sandbox_type: test.config.permissions.windows_sandbox_type,
use_legacy_landlock: test.config.features.use_legacy_landlock(),
exec_policy: None,
plugins: Default::default(),
mcp_policy: None,
network_policy: None,
selected_capability_roots: Vec::new(),
@@ -582,6 +582,7 @@ async fn exec_command_uses_installed_environment_shell_policy_with_explicit_over
windows_sandbox_type: harness.test().config.permissions.windows_sandbox_type,
use_legacy_landlock: harness.test().config.features.use_legacy_landlock(),
exec_policy: None,
plugins: Default::default(),
mcp_policy: None,
network_policy: None,
selected_capability_roots: Vec::new(),
@@ -282,6 +282,7 @@ async fn workspace_roots_allow_file_and_command_writes_in_secondary_root(
windows_sandbox_type: SandboxType::WindowsRestrictedToken,
use_legacy_landlock: test.config.features.use_legacy_landlock(),
exec_policy: None,
plugins: Default::default(),
mcp_policy: None,
network_policy: None,
selected_capability_roots: Vec::new(),
@@ -34,6 +34,7 @@ pub use approval_review::SynchronousApprovalReviewer;
pub use context::TurnContextContributionInput;
pub use mcp::McpServerContribution;
pub use mcp::McpServerContributionContext;
pub use mcp::PluginEnablement;
pub use mcp::SelectedPlugin;
pub use mcp::SelectedPluginContribution;
pub use mcp::SelectedPluginIdentity;
@@ -212,6 +212,16 @@ pub struct SelectedPluginIdentity {
pub plugin_id: PluginIdentity,
}
/// Whether a discovered plugin is enabled and how broadly a disable applies.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PluginEnablement {
Enabled,
/// The source or executor excluded this installation. Other copies remain eligible.
DisabledForInstallation,
/// Suppress the shared plugin ID as well as this installation.
DisabledForThread,
}
/// An executor plugin and its deferred MCP data. Callers that only need the identity can drop
/// `mcp` without loading server or connector configuration. A plugin still owns its skills when
/// it has no MCP data.
@@ -219,7 +229,7 @@ pub struct SelectedPlugin<'a> {
pub selected_root_id: String,
pub plugin_id: String,
pub identity: PluginIdentity,
pub enabled: bool,
pub enabled: PluginEnablement,
pub mcp: ExtensionFuture<'a, SelectedPluginContribution>,
}
+1
View File
@@ -74,6 +74,7 @@ pub use contributors::McpServerContributor;
pub use contributors::McpToolContext;
pub use contributors::McpToolResultInput;
pub use contributors::McpToolSource;
pub use contributors::PluginEnablement;
pub use contributors::PreviousWorldStateSection;
pub use contributors::PromptFragment;
pub use contributors::PromptSlot;
+42 -20
View File
@@ -2,10 +2,9 @@ use codex_config::types::PluginsConfigToml;
use codex_connectors_extension::PluginAppProvider;
use codex_core::config::Config;
use codex_core_plugins::ExecutorPluginProviderError;
use codex_core_plugins::PluginCatalogConfig;
use codex_core_plugins::PluginIdentity;
use codex_core_plugins::PluginRootOwnership;
use codex_core_plugins::PluginSourceLocation;
use codex_core_plugins::configured_plugins_from_stack;
use codex_core_plugins::loader::apply_configured_plugin_mcp_server_policies;
use codex_core_plugins::merge_catalogs;
use codex_exec_server::CapabilityRootDiscovery;
@@ -14,12 +13,15 @@ use codex_extension_api::ExtensionFuture;
use codex_extension_api::McpServerContribution;
use codex_extension_api::McpServerContributionContext;
use codex_extension_api::McpServerContributor;
use codex_extension_api::PluginEnablement;
use codex_extension_api::SelectedPlugin;
use codex_extension_api::SelectedPluginContribution;
use codex_features::Feature;
use codex_protocol::capabilities::CapabilityRootLocation;
use codex_protocol::capabilities::SelectedCapabilityRoot;
use codex_protocol::protocol::EnvironmentConfigState;
use std::collections::HashMap;
use std::sync::Arc;
use self::provider::PluginMcpProvider;
use crate::PluginsThreadState;
@@ -275,32 +277,52 @@ impl McpServerContributor<Config> for PluginContributor {
for warning in &merged.warnings {
tracing::warn!(%warning, "plugin catalog merge reported a warning");
}
let configured = configured_plugins_from_stack(
let environments = context.selected_environments().unwrap_or_default();
let executor_plugin_configs = environments.iter().filter_map(|selection| {
let EnvironmentConfigState::Ready(config) = &selection.config else {
return None;
};
Some((selection.environment_id.as_str(), &config.plugins))
});
let catalog_config = PluginCatalogConfig::from_thread_and_executors(
&context.config().config_layer_stack,
context.config().codex_home.as_path(),
executor_plugin_configs,
);
for entry in merged.entries {
for location in &entry.locations {
let PluginSourceLocation::Executor {
environment_id,
plugin_id,
..
} = location
else {
continue;
};
for mut entry in merged.entries {
let allowed_by_catalog = entry.is_allowed_by(&catalog_config);
let all_installations = discovery::filter_plugin_locations_for_mcp(
&mut entry,
plugins_config,
environments,
allowed_by_catalog,
);
let entry = Arc::new(entry);
for (environment_id, plugin_id, enabled) in all_installations {
let selected_root_id = format!("{environment_id}:{plugin_id}");
let root_id = selected_root_id.clone();
let plugin_id = plugin_id.clone();
let metadata_plugin_id = plugin_id.clone();
let environment_id = environment_id.clone();
let captured = entry.clone();
let captured = Arc::clone(&entry);
plugins.push(SelectedPlugin {
selected_root_id,
plugin_id,
identity: entry.id.clone(),
enabled: entry.is_enabled(&configured),
enabled,
mcp: Box::pin(async move {
// Disabled locations are absent from the server projection.
// Eligible plugins still identify connectors that Apps must hide.
if enabled != PluginEnablement::Enabled {
return SelectedPluginContribution {
plugin_display_name: captured.display_name.clone(),
source_environment_id: environment_id,
connector_ids: if allowed_by_catalog {
captured.connector_ids.clone()
} else {
Vec::new()
},
servers: Vec::new(),
};
}
let metadata = discovery::v2_metadata_from_catalog(
&captured,
&context.config().features,
@@ -376,7 +398,7 @@ impl McpServerContributor<Config> for PluginContributor {
identity: PluginIdentity::Local {
plugin_id: root.selected_root.id.clone(),
},
enabled: true,
enabled: PluginEnablement::Enabled,
mcp: Box::pin(async move {
let metadata = discovery::metadata_from_discovery(
&root.selected_root,
@@ -421,7 +443,7 @@ impl McpServerContributor<Config> for PluginContributor {
identity: PluginIdentity::Local {
plugin_id: selected_root.id.clone(),
},
enabled: true,
enabled: PluginEnablement::Enabled,
mcp: Box::pin(async move {
project_metadata(
context.config(),
@@ -452,7 +474,7 @@ fn denied_plugin(selected_root: &SelectedCapabilityRoot) -> SelectedPlugin<'stat
identity: PluginIdentity::Local {
plugin_id: selected_root.id.clone(),
},
enabled: false,
enabled: PluginEnablement::DisabledForThread,
mcp: Box::pin(async move { metadata }),
}
}
+86 -1
View File
@@ -1,6 +1,7 @@
use crate::cloud_plugin::MAX_CONNECTOR_IDS_PER_PLUGIN;
use crate::cloud_plugin::MAX_PLUGIN_DISPLAY_NAME_CHARS;
use crate::plugin_contributor_state::SelectedPluginMetadata;
use codex_config::types::PluginsConfigToml;
use codex_connectors::parse_plugin_app_config;
use codex_core_plugins::PluginCatalogEntry;
use codex_core_plugins::PluginSourceLocation;
@@ -8,6 +9,7 @@ use codex_core_plugins::manifest::UriPluginManifest;
use codex_core_plugins::manifest::parse_plugin_manifest_uri;
use codex_exec_server::CapabilityRootDiscovery;
use codex_exec_server::DiscoveredPluginFiles;
use codex_extension_api::PluginEnablement;
use codex_extension_api::SelectedPluginContribution;
use codex_features::Feature;
use codex_features::Features;
@@ -17,8 +19,91 @@ use codex_mcp::parse_executor_plugin_mcp_config;
use codex_plugin::manifest::PluginManifestMcpServers;
use codex_protocol::capabilities::CapabilityRootLocation;
use codex_protocol::capabilities::SelectedCapabilityRoot;
use codex_protocol::protocol::EnvironmentConfigState;
use codex_protocol::protocol::TurnEnvironmentSelection;
use std::collections::HashSet;
/// Record every installation for Core, retaining only enabled locations for deferred MCP setup.
pub(super) fn filter_plugin_locations_for_mcp(
entry: &mut PluginCatalogEntry,
thread: &PluginsConfigToml,
environments: &[TurnEnvironmentSelection],
allowed_by_catalog: bool,
) -> Vec<(String, String, PluginEnablement)> {
let mut all_installations = Vec::new();
entry.locations.retain(|location| {
let PluginSourceLocation::Executor {
environment_id,
plugin_id,
..
} = location
else {
return true;
};
let enabled = plugin_enabled(
thread,
environments,
environment_id,
plugin_id,
allowed_by_catalog,
);
all_installations.push((environment_id.clone(), plugin_id.clone(), enabled));
enabled == PluginEnablement::Enabled
});
all_installations
}
/// A thread denial applies even when the source also rejects the installation.
fn plugin_enabled(
thread: &PluginsConfigToml,
environments: &[TurnEnvironmentSelection],
environment_id: &str,
plugin_id: &str,
allowed_by_catalog: bool,
) -> PluginEnablement {
let thread_enabled = thread
.plugins
.get(plugin_id)
.and_then(|plugin| plugin.enabled)
.or_else(|| thread.default.as_ref().map(|default| default.enabled));
if thread_enabled == Some(false) {
return PluginEnablement::DisabledForThread;
}
if !allowed_by_catalog {
return PluginEnablement::DisabledForInstallation;
}
let Some(EnvironmentConfigState::Ready(config)) = environments
.iter()
.find(|selection| selection.environment_id == environment_id)
.map(|selection| &selection.config)
else {
return PluginEnablement::Enabled;
};
if config.plugins.invalid_plugin_ids.contains(plugin_id) {
return PluginEnablement::DisabledForInstallation;
}
if thread_enabled == Some(true) {
return PluginEnablement::Enabled;
}
let executor_enabled = config
.plugins
.plugins
.get(plugin_id)
.and_then(|plugin| plugin.enabled)
.or_else(|| {
config
.plugins
.default
.as_ref()
.map(|default| default.enabled)
});
if executor_enabled == Some(false) {
PluginEnablement::DisabledForInstallation
} else {
PluginEnablement::Enabled
}
}
pub(super) fn manifest_from_discovery<'a>(
selected_root: &SelectedCapabilityRoot,
discovery: &'a CapabilityRootDiscovery,
@@ -175,7 +260,7 @@ pub(super) fn v2_metadata_from_catalog(
let mut projections = Vec::new();
for (index, (environment_id, plugin_id, root)) in installations.enumerate() {
let root_id = format!("{environment_id}:{plugin_id}");
// Keep only the first installation's servers until environment-qualified names are enabled.
// Keep only the first enabled installation's servers until environment-qualified names are enabled.
let servers = if index == 0 || features.enabled(Feature::MultiEnvironmentMcp) {
let parsed = normalize_executor_plugin_mcp_declarations(
root,
+40 -1
View File
@@ -2,7 +2,6 @@
use super::*;
use codex_config::McpServerTransportConfig;
use codex_config::types::PluginsConfigToml;
use codex_core::config::ConfigBuilder;
use codex_core_plugins::PluginIdentity;
use codex_extension_api::SelectedPluginContribution;
@@ -66,6 +65,31 @@ async fn merged_mcp_declarations_require_an_executor_location() -> anyhow::Resul
vec![1, 0, 0]
);
// Opting out the first copy must leave the next eligible copy usable.
let mut executor = TurnEnvironmentSelection {
environment_id: "executor-b".to_string(),
cwd: PathUri::parse("file:///workspace")?,
workspace_roots: Vec::new(),
config: EnvironmentConfigState::FromThread,
selected_capability_roots: Default::default(),
};
let mut attachment =
core_test_support::test_codex::environment_config_for_selection(&config, &executor);
attachment.plugins = serde_json::from_value(serde_json::json!({
"example@acme": { "enabled": false }
}))?;
executor.config = EnvironmentConfigState::Ready(attachment);
let mut selected = entry.clone();
filter_plugin_locations_for_mcp(
&mut selected,
&config.plugins,
&[executor],
/*allowed_by_catalog*/ true,
);
let projections = v2_metadata_from_catalog(&selected, &config.features);
assert_eq!(projections[0].0, "executor-a:example@acme");
assert_eq!(projections[0].1.servers.len(), 1);
// Qualified server names let both installations contribute their own executor paths.
config.features.enable(Feature::MultiEnvironmentMcp)?;
let projections = v2_metadata_from_catalog(&entry, &config.features);
@@ -140,3 +164,18 @@ async fn merged_mcp_declarations_require_an_executor_location() -> anyhow::Resul
);
Ok(())
}
/// An explicit thread disable must also cover installations whose source supplies membership.
#[test]
fn explicit_thread_disable_without_default_denies_executor_plugin() -> anyhow::Result<()> {
let thread = serde_json::from_value(serde_json::json!({
"notes@market": { "enabled": false }
}))?;
for allowed_by_catalog in [true, false] {
assert_eq!(
plugin_enabled(&thread, &[], "local", "notes@market", allowed_by_catalog),
PluginEnablement::DisabledForThread,
);
}
Ok(())
}
@@ -36,7 +36,7 @@ async fn contribution_labels(
let mut labels = Vec::new();
let policy = codex_config::types::PluginsConfigToml::default();
for plugin in contributor.selected_plugins(context, &policy).await {
if !plugin.enabled {
if plugin.enabled != codex_extension_api::PluginEnablement::Enabled {
labels.push(format!("disabled:{}", plugin.plugin_id));
continue;
}
+159
View File
@@ -836,6 +836,7 @@ async fn run_cloud_plugin_projection_scenarios() -> anyhow::Result<()> {
windows_sandbox_type: test.config.permissions.windows_sandbox_type,
use_legacy_landlock: test.config.features.use_legacy_landlock(),
exec_policy: None,
plugins: Default::default(),
mcp_policy: None,
network_policy: None,
selected_capability_roots: vec![SelectedCapabilityRoot {
@@ -941,3 +942,161 @@ async fn run_cloud_plugin_projection_scenarios() -> anyhow::Result<()> {
}
Ok(())
}
/// An empty entry lists only this executor's installation and inherits its default.
/// A thread preference wins for listed installations. A default alone lists nothing.
#[tokio::test]
async fn executor_plugin_enablement_is_scoped_and_overridable() -> TestResult {
use codex_exec_server::ExecutorCapabilityDiscoveryV2Snapshot;
use codex_extension_api::PluginEnablement::DisabledForInstallation;
use codex_extension_api::PluginEnablement::DisabledForThread;
use codex_extension_api::PluginEnablement::Enabled;
use codex_protocol::protocol::EnvironmentConfigState;
use codex_protocol::protocol::TurnEnvironmentSelection;
use core_test_support::test_codex::environment_config_for_selection;
let home = tempfile::tempdir()?;
let mut builder = ExtensionRegistryBuilder::new();
codex_mcp_extension::install_plugins(
&mut builder,
Arc::new(EnvironmentManager::default_for_tests()),
);
let registry = builder.build();
let init = ExtensionDataInit::new();
let store = ExtensionData::new_with_init("test-thread", init.clone());
let inventory = Arc::new(serde_json::from_value(json!({
"plugins": [{
"id": "notes@market", "displayName": "Notes", "version": "1",
"root": "file:///notes", "remotePluginId": null,
"files": {"manifest": {"path": "file:///notes/.codex-plugin/plugin.json",
"contents": "{\"name\":\"notes\"}"}, "mcpConfig": null, "appsConfig": null},
"skills": []
}],
"skills": [], "warnings": []
}))?);
let executors = [
(
"opt-in",
json!({"_default": {"enabled": false}, "notes@market": {"enabled": true}}),
),
(
"opt-out",
json!({"_default": {"enabled": true}, "notes@market": {"enabled": false}}),
),
("default-only", json!({"_default": {"enabled": true}})),
("empty-entry", json!({"_default": {}, "notes@market": {}})),
(
"inherit-off",
json!({"_default": {"enabled": false}, "notes@market": {}}),
),
("no-default", json!({"notes@market": {}})),
("invalid", json!({"_default": {}})),
];
let snapshots = executors
.each_ref()
.map(|(id, _)| ExecutorCapabilityDiscoveryV2Snapshot {
environment_id: (*id).to_owned(),
result: Ok(Arc::clone(&inventory)),
});
for (thread, expected) in [
(
"",
[
Enabled,
DisabledForInstallation,
DisabledForInstallation,
Enabled,
DisabledForInstallation,
Enabled,
DisabledForInstallation,
],
),
(
r#"plugins."notes@market".enabled = true"#,
[
Enabled,
Enabled,
Enabled,
Enabled,
Enabled,
Enabled,
DisabledForInstallation,
],
),
(
r#"plugins."notes@market".enabled = false"#,
[DisabledForThread; 7],
),
(
r#"plugins."notes@market".mcp_servers.notes.enabled = true"#,
[
Enabled,
DisabledForInstallation,
Enabled,
Enabled,
DisabledForInstallation,
Enabled,
DisabledForInstallation,
],
),
(
"plugins._default = {}",
[
Enabled,
Enabled,
DisabledForInstallation,
Enabled,
Enabled,
Enabled,
DisabledForInstallation,
],
),
("plugins._default.enabled = false", [DisabledForThread; 7]),
] {
fs::write(home.path().join("config.toml"), thread)?;
let config = ConfigBuilder::default()
.codex_home(home.path().to_path_buf())
.fallback_cwd(Some(home.path().to_path_buf()))
.build()
.await?;
let mut environments = Vec::new();
for (id, plugins) in &executors {
let mut selection = TurnEnvironmentSelection {
environment_id: (*id).to_owned(),
cwd: PathUri::parse("file:///workspace")?,
workspace_roots: Vec::new(),
config: EnvironmentConfigState::FromThread,
selected_capability_roots: Default::default(),
};
let mut attachment = environment_config_for_selection(&config, &selection);
attachment.plugins = serde_json::from_value(plugins.clone())?;
if *id == "invalid" {
attachment
.plugins
.invalid_plugin_ids
.insert("notes@market".to_owned());
}
selection.config = EnvironmentConfigState::Ready(attachment);
environments.push(selection);
}
let context = McpServerContributionContext::for_step(
&config,
&init,
&store,
"test",
&[],
/*executor_capability_discovery*/ None,
Some(&snapshots),
)
.with_selected_environments(&environments);
let plugins = registry.mcp_server_contributors()[0]
.selected_plugins(context, &config.plugins)
.await;
assert_eq!(
plugins.iter().map(|p| p.enabled).collect::<Vec<_>>(),
expected,
"{thread}"
);
}
Ok(())
}
+12
View File
@@ -22,6 +22,18 @@ use wildmatch::WildMatchPattern;
use crate::openai_models::ReasoningEffort;
/// Default activation settings for installed plugins.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct PluginsDefaultConfig {
#[serde(default = "default_enabled")]
pub enabled: bool,
}
const fn default_enabled() -> bool {
true
}
/// Limit for the text included in `codex.tool_result` log records.
/// This does not affect model-visible output. Raising it can expose more tool data to logs.
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, JsonSchema)]
+28
View File
@@ -3,6 +3,7 @@
use crate::capabilities::EnvironmentCapabilityRoots;
use crate::capabilities::SelectedCapabilityRoot;
use crate::config_types::PluginsDefaultConfig;
use crate::config_types::ShellEnvironmentPolicy;
use crate::config_types::WindowsSandboxLevel;
use crate::mcp_policy::EnvironmentMcpPolicy;
@@ -14,6 +15,10 @@ use codex_execpolicy_rules::RequirementsExecPolicy;
use codex_network_policy_types::EnvironmentNetworkPolicy;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::PathUri;
use serde::Deserialize;
use serde::Serialize;
use std::collections::BTreeMap;
use std::collections::BTreeSet;
/// An environment requested by a caller, before attaching the receiving thread's roots.
///
@@ -187,6 +192,26 @@ pub fn has_full_access<'a>(
}
}
/// Activation preferences for installations on one executor.
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]
pub struct EnvironmentPluginsConfig {
#[serde(default, rename = "_default", skip_serializing_if = "Option::is_none")]
pub default: Option<PluginsDefaultConfig>,
#[serde(default, flatten)]
pub plugins: BTreeMap<String, EnvironmentPluginConfig>,
/// Rejected entries on this attachment. Thread preferences cannot enable these installations.
#[serde(skip)]
pub invalid_plugin_ids: BTreeSet<String>,
}
/// Naming a plugin lists this installation. An omitted flag inherits the default.
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct EnvironmentPluginConfig {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub enabled: Option<bool>,
}
/// Resolved configuration for a thread/environment attachment.
#[derive(Clone, PartialEq)]
pub struct EnvironmentConfig {
@@ -208,6 +233,8 @@ pub struct EnvironmentConfig {
pub use_legacy_landlock: bool,
/// Additional managed command restrictions for this environment attachment.
pub exec_policy: Option<RequirementsExecPolicy>,
/// Executor-local activation preferences. Thread settings take precedence.
pub plugins: EnvironmentPluginsConfig,
/// Additional managed MCP restrictions for this environment attachment.
pub mcp_policy: Option<EnvironmentMcpPolicy>,
/// Owner-provided traffic restrictions. `None` keeps the existing controller policy.
@@ -229,6 +256,7 @@ impl std::fmt::Debug for EnvironmentConfig {
.field("windows_sandbox_type", &self.windows_sandbox_type)
.field("use_legacy_landlock", &self.use_legacy_landlock)
.field("exec_policy", &self.exec_policy)
.field("plugins", &self.plugins.plugins.len())
.field("mcp_policy", &self.mcp_policy)
.field("network_policy", &self.network_policy)
.field("selected_capability_roots", &self.selected_capability_roots)
+2
View File
@@ -106,6 +106,8 @@ pub use crate::approvals::NetworkPolicyAmendment;
pub use crate::approvals::NetworkPolicyRuleAction;
pub use crate::environment::EnvironmentConfig;
pub use crate::environment::EnvironmentConfigState;
pub use crate::environment::EnvironmentPluginConfig;
pub use crate::environment::EnvironmentPluginsConfig;
pub use crate::environment::TurnEnvironmentRequest;
pub use crate::environment::TurnEnvironmentRequests;
pub use crate::environment::TurnEnvironmentSelection;