From f63a882f73525b56994995634492972cd1974246 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 13 May 2026 12:19:55 +0100 Subject: [PATCH] Disable Codex import and plugin config surfaces --- notes/fresh-workspace-handoff.md | 13 +- state/ledgers.msgpack | Bin 92856 -> 93320 bytes state/map.yaml | 2 +- vendor/codex/codex-rs/Cargo.lock | 2 - vendor/codex/codex-rs/app-server/Cargo.toml | 2 - .../src/config/external_agent_config.rs | 1185 ------------ .../src/config/external_agent_config_tests.rs | 1622 ----------------- .../codex-rs/app-server/src/config/mod.rs | 1 - .../codex-rs/app-server/src/config_api.rs | 56 - .../src/external_agent_config_api.rs | 152 -- vendor/codex/codex-rs/app-server/src/lib.rs | 2 - .../app-server/src/message_processor.rs | 188 +- .../suite/v2/experimental_feature_list.rs | 54 +- .../tests/suite/v2/external_agent_config.rs | 183 -- .../codex-rs/app-server/tests/suite/v2/mod.rs | 1 - 15 files changed, 54 insertions(+), 3409 deletions(-) delete mode 100644 vendor/codex/codex-rs/app-server/src/config/external_agent_config.rs delete mode 100644 vendor/codex/codex-rs/app-server/src/config/external_agent_config_tests.rs delete mode 100644 vendor/codex/codex-rs/app-server/src/config/mod.rs delete mode 100644 vendor/codex/codex-rs/app-server/src/external_agent_config_api.rs delete mode 100644 vendor/codex/codex-rs/app-server/tests/suite/v2/external_agent_config.rs diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index 5568718f..e36f92c9 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -746,12 +746,19 @@ boundary while Codex survives only as subscription auth/model routing. Do not resume Rider, Unity, Aquarium, Face, dogfood, planning, app, skill, marketplace, or bridge expansion until this organ is being cut cleanly. -The first Codex product-surface starvation cut is landed too. App-server +The Codex product-surface starvation cuts are landed too. App-server apps/skills/plugin/marketplace list routes are inert, mutation/detail routes return explicit disabled errors, the helper modules and stale v2 endpoint tests were deleted, and the broken private `processor_tests.rs` implementation-shape -suite is gone. `codex_message_processor.rs` is still too large, but it is no -longer carrying the plugin marketplace altar in its chest cavity. +suite is gone. `externalAgentConfig/*` is now a compatibility husk: detect +returns no imports, import is disabled, and the Claude/app/skill/plugin import +machinery plus tests were deleted. Config no longer treats `apps` or `plugins` +as supported runtime feature enablement, no longer refreshes app lists after +feature writes, no longer starts plugin warmups at app-server startup, and no +longer emits plugin-toggle analytics from config writes. App-server no longer +depends directly on `codex-chatgpt`, `codex-core-plugins`, or `codex-plugin`. +`codex_message_processor.rs` is still too large, but it is no longer carrying +the plugin marketplace altar in its chest cavity. The Phase 6 freshness slice is landed. It exposes read-only `thread/epiphany/freshness` from live retrieval summaries plus graph diff --git a/state/ledgers.msgpack b/state/ledgers.msgpack index bec3590d435e137b28fcd430a912de5b7ea073a0..73be69db072f3192cb2beb0446b8d6807dd6d181 100644 GIT binary patch delta 433 zcmX|;Jx&8L5QSx=h?XOagb+EI4uzTmQPDZOvl~nP)7Tr5Do8XG6jbC4lt@UV z$TcV^Xt@9vz|JNq$C~%v_r}Yw*3)7ApDV_G$BVZ!cCepigY06^ zTV#FKo|uI zj%-oqA?}n4r|1VzV8Hc5sL6Oh?ZT|RwL>CHbHAH)R4eqIfIj#rRZ(2DQ;y#R`4n#_ zk+meNfoc<^MkrB4e*`qCh>qNARpKD@<1OXAAYE^nd9YQb5N<^5Itw!Qkk?5UJH|xr zktRq`NJ<6rbQ+$IMW|fpY$i*{n*$_Tw}V^!jM#DG#CcPOb7OhLJ$d-(b$fl@J?Gi! J?dBi)cmG}Yo&o>> delta 49 zcmeCU$-3hz>jY({th$Y=(-;{)HSb~EzK4>, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(crate) enum ExternalAgentConfigMigrationItemType { - Config, - Skills, - AgentsMd, - Plugins, - McpServerConfig, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub(crate) struct PluginsMigration { - pub marketplace_name: String, - pub plugin_names: Vec, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub(crate) struct MigrationDetails { - pub plugins: Vec, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub(crate) struct PendingPluginImport { - pub cwd: Option, - pub details: MigrationDetails, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq)] -pub(crate) struct PluginImportOutcome { - pub succeeded_marketplaces: Vec, - pub succeeded_plugin_ids: Vec, - pub failed_marketplaces: Vec, - pub failed_plugin_ids: Vec, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub(crate) struct ExternalAgentConfigMigrationItem { - pub item_type: ExternalAgentConfigMigrationItemType, - pub description: String, - pub cwd: Option, - pub details: Option, -} - -#[derive(Clone)] -pub(crate) struct ExternalAgentConfigService { - codex_home: PathBuf, - external_agent_home: PathBuf, -} - -impl ExternalAgentConfigService { - pub(crate) fn new(codex_home: PathBuf) -> Self { - let external_agent_home = default_external_agent_home(); - Self { - codex_home, - external_agent_home, - } - } - - #[cfg(test)] - fn new_for_test(codex_home: PathBuf, external_agent_home: PathBuf) -> Self { - Self { - codex_home, - external_agent_home, - } - } - - pub(crate) async fn detect( - &self, - params: ExternalAgentConfigDetectOptions, - ) -> io::Result> { - let mut items = Vec::new(); - if params.include_home { - self.detect_migrations(/*repo_root*/ None, &mut items) - .await?; - } - - for cwd in params.cwds.as_deref().unwrap_or(&[]) { - let Some(repo_root) = find_repo_root(Some(cwd))? else { - continue; - }; - self.detect_migrations(Some(&repo_root), &mut items).await?; - } - - Ok(items) - } - - pub(crate) async fn import( - &self, - migration_items: Vec, - ) -> io::Result> { - let mut pending_plugin_imports = Vec::new(); - for migration_item in migration_items { - match migration_item.item_type { - ExternalAgentConfigMigrationItemType::Config => { - self.import_config(migration_item.cwd.as_deref())?; - emit_migration_metric( - EXTERNAL_AGENT_CONFIG_IMPORT_METRIC, - ExternalAgentConfigMigrationItemType::Config, - /*skills_count*/ None, - ); - } - ExternalAgentConfigMigrationItemType::Skills => { - let skills_count = self.import_skills(migration_item.cwd.as_deref())?; - emit_migration_metric( - EXTERNAL_AGENT_CONFIG_IMPORT_METRIC, - ExternalAgentConfigMigrationItemType::Skills, - Some(skills_count), - ); - } - ExternalAgentConfigMigrationItemType::AgentsMd => { - self.import_agents_md(migration_item.cwd.as_deref())?; - emit_migration_metric( - EXTERNAL_AGENT_CONFIG_IMPORT_METRIC, - ExternalAgentConfigMigrationItemType::AgentsMd, - /*skills_count*/ None, - ); - } - ExternalAgentConfigMigrationItemType::Plugins => { - let cwd = migration_item.cwd; - let details = migration_item.details.ok_or_else(|| { - invalid_data_error("plugins migration item is missing details".to_string()) - })?; - let (local_details, remote_details) = - self.partition_plugin_migration_details(cwd.as_deref(), details)?; - - if let Some(local_details) = local_details { - self.import_plugins(cwd.as_deref(), Some(local_details)) - .await?; - } - if let Some(remote_details) = remote_details { - pending_plugin_imports.push(PendingPluginImport { - cwd, - details: remote_details, - }); - } - emit_migration_metric( - EXTERNAL_AGENT_CONFIG_IMPORT_METRIC, - ExternalAgentConfigMigrationItemType::Plugins, - /*skills_count*/ None, - ); - } - ExternalAgentConfigMigrationItemType::McpServerConfig => {} - } - } - - Ok(pending_plugin_imports) - } - - async fn detect_migrations( - &self, - repo_root: Option<&Path>, - items: &mut Vec, - ) -> io::Result<()> { - let cwd = repo_root.map(Path::to_path_buf); - let source_settings = repo_root.map_or_else( - || self.external_agent_home.join("settings.json"), - |repo_root| repo_root.join(EXTERNAL_AGENT_DIR).join("settings.json"), - ); - let settings = read_external_settings(&source_settings)?; - let target_config = repo_root.map_or_else( - || self.codex_home.join("config.toml"), - |repo_root| repo_root.join(".codex").join("config.toml"), - ); - if let Some(settings) = settings.as_ref() { - let migrated = build_config_from_external(settings)?; - if !is_empty_toml_table(&migrated) { - let mut should_include = true; - if target_config.exists() { - let existing_raw = fs::read_to_string(&target_config)?; - let mut existing = if existing_raw.trim().is_empty() { - TomlValue::Table(Default::default()) - } else { - toml::from_str::(&existing_raw).map_err(|err| { - invalid_data_error(format!("invalid existing config.toml: {err}")) - })? - }; - should_include = merge_missing_toml_values(&mut existing, &migrated)?; - } - - if should_include { - items.push(ExternalAgentConfigMigrationItem { - item_type: ExternalAgentConfigMigrationItemType::Config, - description: format!( - "Migrate {} into {}", - source_settings.display(), - target_config.display() - ), - cwd: cwd.clone(), - details: None, - }); - emit_migration_metric( - EXTERNAL_AGENT_CONFIG_DETECT_METRIC, - ExternalAgentConfigMigrationItemType::Config, - /*skills_count*/ None, - ); - } - } - } - - let source_skills = repo_root.map_or_else( - || self.external_agent_home.join("skills"), - |repo_root| repo_root.join(EXTERNAL_AGENT_DIR).join("skills"), - ); - let target_skills = repo_root.map_or_else( - || self.home_target_skills_dir(), - |repo_root| repo_root.join(".agents").join("skills"), - ); - let skills_count = count_missing_subdirectories(&source_skills, &target_skills)?; - if skills_count > 0 { - items.push(ExternalAgentConfigMigrationItem { - item_type: ExternalAgentConfigMigrationItemType::Skills, - description: format!( - "Migrate skills from {} to {}", - source_skills.display(), - target_skills.display() - ), - cwd: cwd.clone(), - details: None, - }); - emit_migration_metric( - EXTERNAL_AGENT_CONFIG_DETECT_METRIC, - ExternalAgentConfigMigrationItemType::Skills, - Some(skills_count), - ); - } - - let source_agents_md = if let Some(repo_root) = repo_root { - find_repo_agents_md_source(repo_root)? - } else { - let path = self.external_agent_home.join(EXTERNAL_AGENT_CONFIG_MD); - is_non_empty_text_file(&path)?.then_some(path) - }; - let target_agents_md = repo_root.map_or_else( - || self.codex_home.join("AGENTS.md"), - |repo_root| repo_root.join("AGENTS.md"), - ); - if let Some(source_agents_md) = source_agents_md - && is_missing_or_empty_text_file(&target_agents_md)? - { - items.push(ExternalAgentConfigMigrationItem { - item_type: ExternalAgentConfigMigrationItemType::AgentsMd, - description: format!( - "Migrate {} to {}", - source_agents_md.display(), - target_agents_md.display() - ), - cwd: cwd.clone(), - details: None, - }); - emit_migration_metric( - EXTERNAL_AGENT_CONFIG_DETECT_METRIC, - ExternalAgentConfigMigrationItemType::AgentsMd, - /*skills_count*/ None, - ); - } - - if let Some(settings) = settings.as_ref() { - match ConfigBuilder::default() - .codex_home(self.codex_home.clone()) - .fallback_cwd(Some(self.codex_home.clone())) - .build() - .await - { - Ok(config) => { - let configured_plugin_ids = config - .config_layer_stack - .get_user_layer() - .and_then(|user_layer| user_layer.config.get("plugins")) - .and_then(|plugins| { - match plugins.clone().try_into::>() { - Ok(plugins) => Some(plugins), - Err(err) => { - tracing::warn!("invalid plugins config: {err}"); - None - } - } - }) - .map(|plugins| plugins.into_keys().collect::>()) - .unwrap_or_default(); - let configured_marketplace_plugins = configured_marketplace_plugins( - &config, - &PluginsManager::new(self.codex_home.clone()), - )?; - if let Some(item) = self.detect_plugin_migration( - source_settings.as_path(), - repo_root.unwrap_or(self.external_agent_home.as_path()), - cwd.clone(), - settings, - &configured_plugin_ids, - &configured_marketplace_plugins, - ) { - items.push(item); - } - } - Err(err) => { - tracing::warn!( - error = %err, - settings_path = %source_settings.display(), - "skipping external agent plugin migration detection because config load failed" - ); - } - } - } - - Ok(()) - } - - fn home_target_skills_dir(&self) -> PathBuf { - self.codex_home - .parent() - .map(|parent| parent.join(".agents").join("skills")) - .unwrap_or_else(|| PathBuf::from(".agents").join("skills")) - } - - fn detect_plugin_migration( - &self, - source_settings: &Path, - source_root: &Path, - cwd: Option, - settings: &JsonValue, - configured_plugin_ids: &HashSet, - configured_marketplace_plugins: &BTreeMap>, - ) -> Option { - let plugin_details = extract_plugin_migration_details( - settings, - source_root, - configured_plugin_ids, - configured_marketplace_plugins, - )?; - emit_migration_metric( - EXTERNAL_AGENT_CONFIG_DETECT_METRIC, - ExternalAgentConfigMigrationItemType::Plugins, - /*skills_count*/ None, - ); - - Some(ExternalAgentConfigMigrationItem { - item_type: ExternalAgentConfigMigrationItemType::Plugins, - description: format!("Migrate enabled plugins from {}", source_settings.display()), - cwd, - details: Some(plugin_details), - }) - } - - fn partition_plugin_migration_details( - &self, - cwd: Option<&Path>, - details: MigrationDetails, - ) -> io::Result<(Option, Option)> { - let source_settings = cwd.map_or_else( - || self.external_agent_home.join("settings.json"), - |cwd| cwd.join(EXTERNAL_AGENT_DIR).join("settings.json"), - ); - let source_root = cwd.unwrap_or(self.external_agent_home.as_path()); - let import_sources = read_external_settings(&source_settings)? - .map(|settings| collect_marketplace_import_sources(&settings, source_root)) - .unwrap_or_default(); - - let mut local_plugins = Vec::new(); - let mut remote_plugins = Vec::new(); - for plugin_group in details.plugins { - let is_local = import_sources - .get(&plugin_group.marketplace_name) - .and_then(|import_source| { - is_local_marketplace_source( - &import_source.source, - import_source.ref_name.clone(), - ) - .ok() - }) - .unwrap_or(false); - - if is_local { - local_plugins.push(plugin_group); - } else { - remote_plugins.push(plugin_group); - } - } - - let local_details = (!local_plugins.is_empty()).then_some(MigrationDetails { - plugins: local_plugins, - }); - let remote_details = (!remote_plugins.is_empty()).then_some(MigrationDetails { - plugins: remote_plugins, - }); - - Ok((local_details, remote_details)) - } - - pub(crate) async fn import_plugins( - &self, - cwd: Option<&Path>, - details: Option, - ) -> io::Result { - let Some(MigrationDetails { plugins }) = details else { - return Err(invalid_data_error( - "plugins migration item is missing details".to_string(), - )); - }; - let mut outcome = PluginImportOutcome::default(); - let plugins_manager = PluginsManager::new(self.codex_home.clone()); - for plugin_group in plugins { - let marketplace_name = plugin_group.marketplace_name.clone(); - let plugin_names = plugin_group.plugin_names; - let plugin_ids = plugin_names - .iter() - .map(|plugin_name| format!("{plugin_name}@{marketplace_name}")) - .collect::>(); - let source_settings = cwd.map_or_else( - || self.external_agent_home.join("settings.json"), - |cwd| cwd.join(EXTERNAL_AGENT_DIR).join("settings.json"), - ); - let source_root = cwd.unwrap_or(self.external_agent_home.as_path()); - let import_source = read_external_settings(&source_settings)?.and_then(|settings| { - collect_marketplace_import_sources(&settings, source_root).remove(&marketplace_name) - }); - let Some(import_source) = import_source else { - outcome.failed_marketplaces.push(marketplace_name); - outcome.failed_plugin_ids.extend(plugin_ids); - continue; - }; - let request = MarketplaceAddRequest { - source: import_source.source, - ref_name: import_source.ref_name, - sparse_paths: Vec::new(), - }; - let add_marketplace_outcome = add_marketplace(self.codex_home.clone(), request).await; - let marketplace_path = match add_marketplace_outcome { - Ok(add_marketplace_outcome) => { - let Some(marketplace_path) = find_marketplace_manifest_path( - add_marketplace_outcome.installed_root.as_path(), - ) else { - outcome.failed_marketplaces.push(marketplace_name); - outcome.failed_plugin_ids.extend(plugin_ids); - continue; - }; - outcome - .succeeded_marketplaces - .push(marketplace_name.clone()); - marketplace_path - } - Err(_) => { - outcome.failed_marketplaces.push(marketplace_name); - outcome.failed_plugin_ids.extend(plugin_ids); - continue; - } - }; - for plugin_name in plugin_names { - match plugins_manager - .install_plugin(PluginInstallRequest { - plugin_name: plugin_name.clone(), - marketplace_path: marketplace_path.clone(), - }) - .await - { - Ok(_) => outcome - .succeeded_plugin_ids - .push(format!("{plugin_name}@{marketplace_name}")), - Err(_) => outcome - .failed_plugin_ids - .push(format!("{plugin_name}@{marketplace_name}")), - } - } - } - - Ok(outcome) - } - - fn import_config(&self, cwd: Option<&Path>) -> io::Result<()> { - let (source_settings, target_config) = if let Some(repo_root) = find_repo_root(cwd)? { - ( - repo_root.join(EXTERNAL_AGENT_DIR).join("settings.json"), - repo_root.join(".codex").join("config.toml"), - ) - } else if cwd.is_some_and(|cwd| !cwd.as_os_str().is_empty()) { - return Ok(()); - } else { - ( - self.external_agent_home.join("settings.json"), - self.codex_home.join("config.toml"), - ) - }; - if !source_settings.is_file() { - return Ok(()); - } - - let raw_settings = fs::read_to_string(&source_settings)?; - let settings: JsonValue = serde_json::from_str(&raw_settings) - .map_err(|err| invalid_data_error(err.to_string()))?; - let migrated = build_config_from_external(&settings)?; - if is_empty_toml_table(&migrated) { - return Ok(()); - } - - let Some(target_parent) = target_config.parent() else { - return Err(invalid_data_error("config target path has no parent")); - }; - fs::create_dir_all(target_parent)?; - if !target_config.exists() { - write_toml_file(&target_config, &migrated)?; - return Ok(()); - } - - let existing_raw = fs::read_to_string(&target_config)?; - let mut existing = if existing_raw.trim().is_empty() { - TomlValue::Table(Default::default()) - } else { - toml::from_str::(&existing_raw) - .map_err(|err| invalid_data_error(format!("invalid existing config.toml: {err}")))? - }; - - let changed = merge_missing_toml_values(&mut existing, &migrated)?; - if !changed { - return Ok(()); - } - - write_toml_file(&target_config, &existing)?; - Ok(()) - } - - fn import_skills(&self, cwd: Option<&Path>) -> io::Result { - let (source_skills, target_skills) = if let Some(repo_root) = find_repo_root(cwd)? { - ( - repo_root.join(EXTERNAL_AGENT_DIR).join("skills"), - repo_root.join(".agents").join("skills"), - ) - } else if cwd.is_some_and(|cwd| !cwd.as_os_str().is_empty()) { - return Ok(0); - } else { - ( - self.external_agent_home.join("skills"), - self.home_target_skills_dir(), - ) - }; - if !source_skills.is_dir() { - return Ok(0); - } - - fs::create_dir_all(&target_skills)?; - let mut copied_count = 0usize; - - for entry in fs::read_dir(&source_skills)? { - let entry = entry?; - let file_type = entry.file_type()?; - if !file_type.is_dir() { - continue; - } - - let target = target_skills.join(entry.file_name()); - if target.exists() { - continue; - } - - copy_dir_recursive(&entry.path(), &target)?; - copied_count += 1; - } - - Ok(copied_count) - } - - fn import_agents_md(&self, cwd: Option<&Path>) -> io::Result<()> { - let (source_agents_md, target_agents_md) = if let Some(repo_root) = find_repo_root(cwd)? { - let Some(source_agents_md) = find_repo_agents_md_source(&repo_root)? else { - return Ok(()); - }; - (source_agents_md, repo_root.join("AGENTS.md")) - } else if cwd.is_some_and(|cwd| !cwd.as_os_str().is_empty()) { - return Ok(()); - } else { - ( - self.external_agent_home.join(EXTERNAL_AGENT_CONFIG_MD), - self.codex_home.join("AGENTS.md"), - ) - }; - if !is_non_empty_text_file(&source_agents_md)? - || !is_missing_or_empty_text_file(&target_agents_md)? - { - return Ok(()); - } - - let Some(target_parent) = target_agents_md.parent() else { - return Err(invalid_data_error("AGENTS.md target path has no parent")); - }; - fs::create_dir_all(target_parent)?; - - rewrite_and_copy_text_file(&source_agents_md, &target_agents_md) - } -} - -fn default_external_agent_home() -> PathBuf { - if let Some(home) = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")) { - return PathBuf::from(home).join(EXTERNAL_AGENT_DIR); - } - - PathBuf::from(EXTERNAL_AGENT_DIR) -} - -fn read_external_settings(path: &Path) -> io::Result> { - if !path.is_file() { - return Ok(None); - } - - let raw_settings = fs::read_to_string(path)?; - let settings = - serde_json::from_str(&raw_settings).map_err(|err| invalid_data_error(err.to_string()))?; - Ok(Some(settings)) -} - -fn extract_plugin_migration_details( - settings: &JsonValue, - source_root: &Path, - configured_plugin_ids: &HashSet, - configured_marketplace_plugins: &BTreeMap>, -) -> Option { - let loadable_marketplaces = collect_marketplace_import_sources(settings, source_root) - .into_iter() - .filter_map(|(marketplace_name, source)| { - is_local_marketplace_source(&source.source, source.ref_name) - .ok() - .map(|_| marketplace_name) - }) - .collect::>(); - let mut plugins = BTreeMap::new(); - for plugin_id in collect_enabled_plugins(settings) - .into_iter() - .filter(|plugin_id| !configured_plugin_ids.contains(plugin_id)) - { - let Ok(plugin_id) = PluginId::parse(&plugin_id) else { - continue; - }; - if let Some(installable_plugins) = - configured_marketplace_plugins.get(&plugin_id.marketplace_name) - { - if !installable_plugins.contains(&plugin_id.plugin_name) { - continue; - } - } else if !loadable_marketplaces.contains(&plugin_id.marketplace_name) { - continue; - } - let plugin_group = plugins - .entry(plugin_id.marketplace_name.clone()) - .or_insert_with(|| PluginsMigration { - marketplace_name: plugin_id.marketplace_name.clone(), - plugin_names: Vec::new(), - }); - plugin_group.plugin_names.push(plugin_id.plugin_name); - } - - let plugins = plugins - .into_values() - .filter_map(|mut plugin_group| { - if plugin_group.plugin_names.is_empty() { - return None; - } - plugin_group.plugin_names.sort(); - Some(plugin_group) - }) - .collect::>(); - if plugins.is_empty() { - return None; - } - - Some(MigrationDetails { plugins }) -} - -fn collect_enabled_plugins(settings: &JsonValue) -> Vec { - let Some(enabled_plugins) = settings - .as_object() - .and_then(|settings| settings.get("enabledPlugins")) - .and_then(JsonValue::as_object) - else { - return Vec::new(); - }; - - enabled_plugins - .iter() - .filter_map(|(plugin_key, enabled)| { - if !enabled.as_bool().unwrap_or(false) { - return None; - } - PluginId::parse(plugin_key) - .ok() - .map(|plugin_id| plugin_id.as_key()) - }) - .collect() -} - -fn has_enabled_plugin_for_marketplace(settings: &JsonValue, marketplace_name: &str) -> bool { - collect_enabled_plugins(settings) - .into_iter() - .any(|plugin_id| { - PluginId::parse(&plugin_id) - .map(|plugin_id| plugin_id.marketplace_name == marketplace_name) - .unwrap_or(false) - }) -} - -fn configured_marketplace_plugins( - config: &Config, - plugins_manager: &PluginsManager, -) -> io::Result>> { - let marketplaces = plugins_manager - .list_marketplaces_for_config(config, &[]) - .map_err(|err| { - invalid_data_error(format!("failed to list configured marketplaces: {err}")) - })?; - let mut marketplace_plugins = BTreeMap::new(); - for marketplace in marketplaces.marketplaces { - let plugins = marketplace - .plugins - .into_iter() - .filter(|plugin| { - plugin.policy.installation != MarketplacePluginInstallPolicy::NotAvailable - }) - .filter(|plugin| { - plugin - .policy - .products - .as_deref() - .is_none_or(|products| Product::Codex.matches_product_restriction(products)) - }) - .map(|plugin| plugin.name) - .collect::>(); - marketplace_plugins.insert(marketplace.name, plugins); - } - Ok(marketplace_plugins) -} - -fn collect_marketplace_import_sources( - settings: &JsonValue, - source_root: &Path, -) -> BTreeMap { - let mut import_sources: BTreeMap = settings - .as_object() - .and_then(|settings| settings.get("extraKnownMarketplaces")) - .and_then(JsonValue::as_object) - .map(|extra_known_marketplaces| { - extra_known_marketplaces - .iter() - .filter_map(|(name, value)| { - let source_fields = if let Some(source) = value.get("source") - && source.is_object() - { - source.as_object()? - } else { - value.as_object()? - }; - let source = source_fields - .get("repo") - .or_else(|| source_fields.get("url")) - .or_else(|| source_fields.get("path")) - .or_else(|| value.get("source"))? - .as_str()? - .trim() - .to_string(); - if source.is_empty() { - return None; - } - let source = resolve_external_marketplace_source(&source, source_root); - - let ref_name = source_fields - .get("ref") - .or_else(|| value.get("ref")) - .and_then(JsonValue::as_str) - .map(str::trim) - .filter(|value| !value.is_empty()) - .map(ToOwned::to_owned); - - Some((name.clone(), MarketplaceImportSource { source, ref_name })) - }) - .collect() - }) - .unwrap_or_default(); - - if has_enabled_plugin_for_marketplace(settings, EXTERNAL_OFFICIAL_MARKETPLACE_NAME) - && !import_sources.contains_key(EXTERNAL_OFFICIAL_MARKETPLACE_NAME) - { - import_sources.insert( - EXTERNAL_OFFICIAL_MARKETPLACE_NAME.to_string(), - MarketplaceImportSource { - source: EXTERNAL_OFFICIAL_MARKETPLACE_SOURCE.to_string(), - ref_name: None, - }, - ); - } - - import_sources -} - -#[derive(Debug, Clone, PartialEq, Eq)] -struct MarketplaceImportSource { - source: String, - ref_name: Option, -} - -fn resolve_external_marketplace_source(source: &str, source_root: &Path) -> String { - if !looks_like_relative_local_path(source) { - return source.to_string(); - } - - source_root.join(source).display().to_string() -} - -fn looks_like_relative_local_path(source: &str) -> bool { - source.starts_with("./") || source.starts_with("../") || source == "." || source == ".." -} - -fn find_repo_root(cwd: Option<&Path>) -> io::Result> { - let Some(cwd) = cwd.filter(|cwd| !cwd.as_os_str().is_empty()) else { - return Ok(None); - }; - - let mut current = if cwd.is_absolute() { - cwd.to_path_buf() - } else { - std::env::current_dir()?.join(cwd) - }; - - if !current.exists() { - return Ok(None); - } - - if current.is_file() { - let Some(parent) = current.parent() else { - return Ok(None); - }; - current = parent.to_path_buf(); - } - - let fallback = current.clone(); - loop { - let git_path = current.join(".git"); - if git_path.is_dir() || git_path.is_file() { - return Ok(Some(current)); - } - if !current.pop() { - break; - } - } - - Ok(Some(fallback)) -} - -fn collect_subdirectory_names(path: &Path) -> io::Result> { - let mut names = HashSet::new(); - if !path.is_dir() { - return Ok(names); - } - - for entry in fs::read_dir(path)? { - let entry = entry?; - if entry.file_type()?.is_dir() { - names.insert(entry.file_name()); - } - } - - Ok(names) -} - -fn count_missing_subdirectories(source: &Path, target: &Path) -> io::Result { - let source_names = collect_subdirectory_names(source)?; - let target_names = collect_subdirectory_names(target)?; - Ok(source_names - .iter() - .filter(|name| !target_names.contains(*name)) - .count()) -} - -fn is_missing_or_empty_text_file(path: &Path) -> io::Result { - if !path.exists() { - return Ok(true); - } - if !path.is_file() { - return Ok(false); - } - - Ok(fs::read_to_string(path)?.trim().is_empty()) -} - -fn is_non_empty_text_file(path: &Path) -> io::Result { - if !path.is_file() { - return Ok(false); - } - - Ok(!fs::read_to_string(path)?.trim().is_empty()) -} - -fn find_repo_agents_md_source(repo_root: &Path) -> io::Result> { - for candidate in [ - repo_root.join(EXTERNAL_AGENT_CONFIG_MD), - repo_root - .join(EXTERNAL_AGENT_DIR) - .join(EXTERNAL_AGENT_CONFIG_MD), - ] { - if is_non_empty_text_file(&candidate)? { - return Ok(Some(candidate)); - } - } - - Ok(None) -} - -fn copy_dir_recursive(source: &Path, target: &Path) -> io::Result<()> { - fs::create_dir_all(target)?; - - for entry in fs::read_dir(source)? { - let entry = entry?; - let source_path = entry.path(); - let target_path = target.join(entry.file_name()); - let file_type = entry.file_type()?; - - if file_type.is_dir() { - copy_dir_recursive(&source_path, &target_path)?; - continue; - } - - if file_type.is_file() { - if is_skill_md(&source_path) { - rewrite_and_copy_text_file(&source_path, &target_path)?; - } else { - fs::copy(source_path, target_path)?; - } - } - } - - Ok(()) -} - -fn is_skill_md(path: &Path) -> bool { - path.file_name() - .and_then(|name| name.to_str()) - .is_some_and(|name| name.eq_ignore_ascii_case("SKILL.md")) -} - -fn rewrite_and_copy_text_file(source: &Path, target: &Path) -> io::Result<()> { - let source_contents = fs::read_to_string(source)?; - let rewritten = rewrite_external_agent_terms(&source_contents); - fs::write(target, rewritten) -} - -fn rewrite_external_agent_terms(content: &str) -> String { - let mut rewritten = replace_case_insensitive_with_boundaries( - content, - &EXTERNAL_AGENT_CONFIG_MD.to_ascii_lowercase(), - "AGENTS.md", - ); - for from in [ - "claude code", - "claude-code", - "claude_code", - "claudecode", - "claude", - ] { - rewritten = replace_case_insensitive_with_boundaries(&rewritten, from, "Codex"); - } - rewritten -} - -fn replace_case_insensitive_with_boundaries( - input: &str, - needle: &str, - replacement: &str, -) -> String { - let needle_lower = needle.to_ascii_lowercase(); - if needle_lower.is_empty() { - return input.to_string(); - } - - let haystack_lower = input.to_ascii_lowercase(); - let bytes = input.as_bytes(); - let mut output = String::with_capacity(input.len()); - let mut last_emitted = 0usize; - let mut search_start = 0usize; - - while let Some(relative_pos) = haystack_lower[search_start..].find(&needle_lower) { - let start = search_start + relative_pos; - let end = start + needle_lower.len(); - let boundary_before = start == 0 || !is_word_byte(bytes[start - 1]); - let boundary_after = end == bytes.len() || !is_word_byte(bytes[end]); - - if boundary_before && boundary_after { - output.push_str(&input[last_emitted..start]); - output.push_str(replacement); - last_emitted = end; - } - - search_start = start + 1; - } - - if last_emitted == 0 { - return input.to_string(); - } - - output.push_str(&input[last_emitted..]); - output -} - -fn is_word_byte(byte: u8) -> bool { - byte.is_ascii_alphanumeric() || byte == b'_' -} - -fn build_config_from_external(settings: &JsonValue) -> io::Result { - let Some(settings_obj) = settings.as_object() else { - return Err(invalid_data_error( - "external agent settings root must be an object", - )); - }; - - let mut root = toml::map::Map::new(); - - if let Some(env) = settings_obj.get("env").and_then(JsonValue::as_object) - && !env.is_empty() - { - let mut shell_policy = toml::map::Map::new(); - shell_policy.insert("inherit".to_string(), TomlValue::String("core".to_string())); - shell_policy.insert( - "set".to_string(), - TomlValue::Table(json_object_to_env_toml_table(env)), - ); - root.insert( - "shell_environment_policy".to_string(), - TomlValue::Table(shell_policy), - ); - } - - if let Some(sandbox_enabled) = settings_obj - .get("sandbox") - .and_then(JsonValue::as_object) - .and_then(|sandbox| sandbox.get("enabled")) - .and_then(JsonValue::as_bool) - && sandbox_enabled - { - root.insert( - "sandbox_mode".to_string(), - TomlValue::String("workspace-write".to_string()), - ); - } - - Ok(TomlValue::Table(root)) -} - -fn json_object_to_env_toml_table( - object: &serde_json::Map, -) -> toml::map::Map { - let mut table = toml::map::Map::new(); - for (key, value) in object { - if let Some(value) = json_env_value_to_string(value) { - table.insert(key.clone(), TomlValue::String(value)); - } - } - table -} - -fn json_env_value_to_string(value: &JsonValue) -> Option { - match value { - JsonValue::String(value) => Some(value.clone()), - JsonValue::Null => None, - JsonValue::Bool(value) => Some(value.to_string()), - JsonValue::Number(value) => Some(value.to_string()), - JsonValue::Array(_) | JsonValue::Object(_) => None, - } -} - -fn merge_missing_toml_values(existing: &mut TomlValue, incoming: &TomlValue) -> io::Result { - match (existing, incoming) { - (TomlValue::Table(existing_table), TomlValue::Table(incoming_table)) => { - let mut changed = false; - for (key, incoming_value) in incoming_table { - match existing_table.get_mut(key) { - Some(existing_value) => { - if matches!( - (&*existing_value, incoming_value), - (TomlValue::Table(_), TomlValue::Table(_)) - ) && merge_missing_toml_values(existing_value, incoming_value)? - { - changed = true; - } - } - None => { - existing_table.insert(key.clone(), incoming_value.clone()); - changed = true; - } - } - } - Ok(changed) - } - _ => Err(invalid_data_error( - "expected TOML table while merging migrated config values", - )), - } -} - -fn write_toml_file(path: &Path, value: &TomlValue) -> io::Result<()> { - let serialized = toml::to_string_pretty(value) - .map_err(|err| invalid_data_error(format!("failed to serialize config.toml: {err}")))?; - fs::write(path, format!("{}\n", serialized.trim_end())) -} - -fn is_empty_toml_table(value: &TomlValue) -> bool { - match value { - TomlValue::Table(table) => table.is_empty(), - TomlValue::String(_) - | TomlValue::Integer(_) - | TomlValue::Float(_) - | TomlValue::Boolean(_) - | TomlValue::Datetime(_) - | TomlValue::Array(_) => false, - } -} - -fn invalid_data_error(message: impl Into) -> io::Error { - io::Error::new(io::ErrorKind::InvalidData, message.into()) -} - -fn migration_metric_tags( - item_type: ExternalAgentConfigMigrationItemType, - skills_count: Option, -) -> Vec<(&'static str, String)> { - let migration_type = match item_type { - ExternalAgentConfigMigrationItemType::Config => "config", - ExternalAgentConfigMigrationItemType::Skills => "skills", - ExternalAgentConfigMigrationItemType::AgentsMd => "agents_md", - ExternalAgentConfigMigrationItemType::Plugins => "plugins", - ExternalAgentConfigMigrationItemType::McpServerConfig => "mcp_server_config", - }; - let mut tags = vec![("migration_type", migration_type.to_string())]; - if item_type == ExternalAgentConfigMigrationItemType::Skills { - tags.push(("skills_count", skills_count.unwrap_or(0).to_string())); - } - tags -} - -fn emit_migration_metric( - metric_name: &str, - item_type: ExternalAgentConfigMigrationItemType, - skills_count: Option, -) { - let Some(metrics) = codex_otel::global() else { - return; - }; - let tags = migration_metric_tags(item_type, skills_count); - let tag_refs = tags - .iter() - .map(|(key, value)| (*key, value.as_str())) - .collect::>(); - let _ = metrics.counter(metric_name, /*inc*/ 1, &tag_refs); -} - -#[cfg(test)] -#[path = "external_agent_config_tests.rs"] -mod tests; diff --git a/vendor/codex/codex-rs/app-server/src/config/external_agent_config_tests.rs b/vendor/codex/codex-rs/app-server/src/config/external_agent_config_tests.rs deleted file mode 100644 index b900498c..00000000 --- a/vendor/codex/codex-rs/app-server/src/config/external_agent_config_tests.rs +++ /dev/null @@ -1,1622 +0,0 @@ -use super::*; -use pretty_assertions::assert_eq; -use std::io; -use tempfile::TempDir; - -fn fixture_paths() -> (TempDir, PathBuf, PathBuf) { - let root = TempDir::new().expect("create tempdir"); - let external_agent_home = root.path().join(".claude"); - let codex_home = root.path().join(".codex"); - (root, external_agent_home, codex_home) -} - -fn service_for_paths( - external_agent_home: PathBuf, - codex_home: PathBuf, -) -> ExternalAgentConfigService { - ExternalAgentConfigService::new_for_test(codex_home, external_agent_home) -} - -fn github_plugin_details() -> MigrationDetails { - MigrationDetails { - plugins: vec![PluginsMigration { - marketplace_name: "acme-tools".to_string(), - plugin_names: vec!["formatter".to_string()], - }], - } -} - -#[tokio::test] -async fn detect_home_lists_config_skills_and_agents_md() { - let (_root, external_agent_home, codex_home) = fixture_paths(); - let agents_skills = codex_home - .parent() - .map(|parent| parent.join(".agents").join("skills")) - .unwrap_or_else(|| PathBuf::from(".agents").join("skills")); - fs::create_dir_all(external_agent_home.join("skills").join("skill-a")).expect("create skills"); - fs::write(external_agent_home.join("CLAUDE.md"), "claude rules") - .expect("write external agent md"); - fs::write( - external_agent_home.join("settings.json"), - r#"{"model":"claude","env":{"FOO":"bar"}}"#, - ) - .expect("write settings"); - - let items = service_for_paths(external_agent_home.clone(), codex_home.clone()) - .detect(ExternalAgentConfigDetectOptions { - include_home: true, - cwds: None, - }) - .await - .expect("detect"); - - let expected = vec![ - ExternalAgentConfigMigrationItem { - item_type: ExternalAgentConfigMigrationItemType::Config, - description: format!( - "Migrate {} into {}", - external_agent_home.join("settings.json").display(), - codex_home.join("config.toml").display() - ), - cwd: None, - details: None, - }, - ExternalAgentConfigMigrationItem { - item_type: ExternalAgentConfigMigrationItemType::Skills, - description: format!( - "Migrate skills from {} to {}", - external_agent_home.join("skills").display(), - agents_skills.display() - ), - cwd: None, - details: None, - }, - ExternalAgentConfigMigrationItem { - item_type: ExternalAgentConfigMigrationItemType::AgentsMd, - description: format!( - "Migrate {} to {}", - external_agent_home.join("CLAUDE.md").display(), - codex_home.join("AGENTS.md").display() - ), - cwd: None, - details: None, - }, - ]; - - assert_eq!(items, expected); -} - -#[tokio::test] -async fn detect_repo_lists_agents_md_for_each_cwd() { - let root = TempDir::new().expect("create tempdir"); - let repo_root = root.path().join("repo"); - let nested = repo_root.join("nested").join("child"); - fs::create_dir_all(repo_root.join(".git")).expect("create git dir"); - fs::create_dir_all(&nested).expect("create nested"); - fs::write(repo_root.join("CLAUDE.md"), "Claude code guidance").expect("write source"); - - let items = service_for_paths(root.path().join(".claude"), root.path().join(".codex")) - .detect(ExternalAgentConfigDetectOptions { - include_home: false, - cwds: Some(vec![nested, repo_root.clone()]), - }) - .await - .expect("detect"); - - let expected = vec![ - ExternalAgentConfigMigrationItem { - item_type: ExternalAgentConfigMigrationItemType::AgentsMd, - description: format!( - "Migrate {} to {}", - repo_root.join("CLAUDE.md").display(), - repo_root.join("AGENTS.md").display(), - ), - cwd: Some(repo_root.clone()), - details: None, - }, - ExternalAgentConfigMigrationItem { - item_type: ExternalAgentConfigMigrationItemType::AgentsMd, - description: format!( - "Migrate {} to {}", - repo_root.join("CLAUDE.md").display(), - repo_root.join("AGENTS.md").display(), - ), - cwd: Some(repo_root), - details: None, - }, - ]; - - assert_eq!(items, expected); -} - -#[tokio::test] -async fn detect_repo_still_reports_non_plugin_items_when_home_config_is_invalid() { - let root = TempDir::new().expect("create tempdir"); - let repo_root = root.path().join("repo"); - let codex_home = root.path().join(".codex"); - fs::create_dir_all(repo_root.join(".git")).expect("create git dir"); - fs::create_dir_all(repo_root.join(".claude").join("skills").join("skill-a")) - .expect("create repo skills"); - fs::create_dir_all(&codex_home).expect("create codex home"); - fs::write(codex_home.join("config.toml"), "this is not valid = [toml") - .expect("write invalid codex config"); - fs::write( - repo_root.join(".claude").join("settings.json"), - r#"{"env":{"FOO":"bar"}}"#, - ) - .expect("write settings"); - fs::write( - repo_root - .join(".claude") - .join("skills") - .join("skill-a") - .join("SKILL.md"), - "Use Claude Code and CLAUDE utilities.", - ) - .expect("write skill"); - fs::write( - repo_root.join(".claude").join("CLAUDE.md"), - "Claude code guidance", - ) - .expect("write agents"); - - let items = service_for_paths(root.path().join(".claude"), codex_home) - .detect(ExternalAgentConfigDetectOptions { - include_home: false, - cwds: Some(vec![repo_root.clone()]), - }) - .await - .expect("detect"); - - assert_eq!( - items, - vec![ - ExternalAgentConfigMigrationItem { - item_type: ExternalAgentConfigMigrationItemType::Config, - description: format!( - "Migrate {} into {}", - repo_root.join(".claude").join("settings.json").display(), - repo_root.join(".codex").join("config.toml").display() - ), - cwd: Some(repo_root.clone()), - details: None, - }, - ExternalAgentConfigMigrationItem { - item_type: ExternalAgentConfigMigrationItemType::Skills, - description: format!( - "Migrate skills from {} to {}", - repo_root.join(".claude").join("skills").display(), - repo_root.join(".agents").join("skills").display() - ), - cwd: Some(repo_root.clone()), - details: None, - }, - ExternalAgentConfigMigrationItem { - item_type: ExternalAgentConfigMigrationItemType::AgentsMd, - description: format!( - "Migrate {} to {}", - repo_root.join(".claude").join("CLAUDE.md").display(), - repo_root.join("AGENTS.md").display(), - ), - cwd: Some(repo_root), - details: None, - }, - ] - ); -} - -#[tokio::test] -async fn import_home_migrates_supported_config_fields_skills_and_agents_md() { - let (_root, external_agent_home, codex_home) = fixture_paths(); - let agents_skills = codex_home - .parent() - .map(|parent| parent.join(".agents").join("skills")) - .unwrap_or_else(|| PathBuf::from(".agents").join("skills")); - fs::create_dir_all(external_agent_home.join("skills").join("skill-a")).expect("create skills"); - fs::write( - external_agent_home.join("settings.json"), - r#"{"model":"claude","permissions":{"ask":["git push"]},"env":{"FOO":"bar","CI":false,"MAX_RETRIES":3,"MY_TEAM":"codex","IGNORED":null,"LIST":["a","b"],"MAP":{"x":1}},"sandbox":{"enabled":true,"network":{"allowLocalBinding":true}}}"#, - ) - .expect("write settings"); - fs::write( - external_agent_home - .join("skills") - .join("skill-a") - .join("SKILL.md"), - "Use Claude Code and CLAUDE utilities.", - ) - .expect("write skill"); - fs::write( - external_agent_home.join("CLAUDE.md"), - "Claude code guidance", - ) - .expect("write agents"); - - service_for_paths(external_agent_home, codex_home.clone()) - .import(vec![ - ExternalAgentConfigMigrationItem { - item_type: ExternalAgentConfigMigrationItemType::AgentsMd, - description: String::new(), - cwd: None, - details: None, - }, - ExternalAgentConfigMigrationItem { - item_type: ExternalAgentConfigMigrationItemType::Config, - description: String::new(), - cwd: None, - details: None, - }, - ExternalAgentConfigMigrationItem { - item_type: ExternalAgentConfigMigrationItemType::Skills, - description: String::new(), - cwd: None, - details: None, - }, - ]) - .await - .expect("import"); - - assert_eq!( - fs::read_to_string(codex_home.join("AGENTS.md")).expect("read agents"), - "Codex guidance" - ); - - assert_eq!( - fs::read_to_string(codex_home.join("config.toml")).expect("read config"), - "sandbox_mode = \"workspace-write\"\n\n[shell_environment_policy]\ninherit = \"core\"\n\n[shell_environment_policy.set]\nCI = \"false\"\nFOO = \"bar\"\nMAX_RETRIES = \"3\"\nMY_TEAM = \"codex\"\n" - ); - assert_eq!( - fs::read_to_string(agents_skills.join("skill-a").join("SKILL.md")) - .expect("read copied skill"), - "Use Codex and Codex utilities." - ); -} - -#[tokio::test] -async fn import_home_skips_empty_config_migration() { - let (_root, external_agent_home, codex_home) = fixture_paths(); - fs::create_dir_all(&external_agent_home).expect("create external agent home"); - fs::write( - external_agent_home.join("settings.json"), - r#"{"model":"claude","sandbox":{"enabled":false}}"#, - ) - .expect("write settings"); - - service_for_paths(external_agent_home, codex_home.clone()) - .import(vec![ExternalAgentConfigMigrationItem { - item_type: ExternalAgentConfigMigrationItemType::Config, - description: String::new(), - cwd: None, - details: None, - }]) - .await - .expect("import"); - - assert!(!codex_home.join("config.toml").exists()); -} - -#[tokio::test] -async fn import_local_plugins_returns_completed_status() { - let (_root, external_agent_home, codex_home) = fixture_paths(); - let marketplace_root = external_agent_home.join("my-marketplace"); - let plugin_root = marketplace_root.join("plugins").join("cloudflare"); - fs::create_dir_all(marketplace_root.join(".claude-plugin")) - .expect("create marketplace manifest dir"); - fs::create_dir_all(plugin_root.join(".codex-plugin")).expect("create plugin manifest dir"); - fs::create_dir_all(&codex_home).expect("create codex home"); - - fs::write( - external_agent_home.join("settings.json"), - serde_json::to_string_pretty(&serde_json::json!({ - "enabledPlugins": { - "cloudflare@my-plugins": true - }, - "extraKnownMarketplaces": { - "my-plugins": { - "source": "local", - "path": marketplace_root - } - } - })) - .expect("serialize settings"), - ) - .expect("write settings"); - fs::write( - marketplace_root - .join(".claude-plugin") - .join("marketplace.json"), - r#"{ - "name": "my-plugins", - "plugins": [ - { - "name": "cloudflare", - "source": "./plugins/cloudflare" - } - ] - }"#, - ) - .expect("write marketplace manifest"); - fs::write( - plugin_root.join(".codex-plugin").join("plugin.json"), - r#"{"name":"cloudflare","version":"0.1.0"}"#, - ) - .expect("write plugin manifest"); - - let outcome = service_for_paths(external_agent_home, codex_home.clone()) - .import(vec![ExternalAgentConfigMigrationItem { - item_type: ExternalAgentConfigMigrationItemType::Plugins, - description: String::new(), - cwd: None, - details: Some(MigrationDetails { - plugins: vec![PluginsMigration { - marketplace_name: "my-plugins".to_string(), - plugin_names: vec!["cloudflare".to_string()], - }], - }), - }]) - .await - .expect("import"); - - assert_eq!(outcome, Vec::::new()); - let config = fs::read_to_string(codex_home.join("config.toml")).expect("read config"); - assert!(config.contains(r#"[plugins."cloudflare@my-plugins"]"#)); - assert!(config.contains("enabled = true")); -} - -#[tokio::test] -async fn import_git_plugins_returns_pending_async_status() { - let (_root, external_agent_home, codex_home) = fixture_paths(); - fs::create_dir_all(&external_agent_home).expect("create external agent home"); - fs::write( - external_agent_home.join("settings.json"), - r#"{ - "enabledPlugins": { - "formatter@acme-tools": true - }, - "extraKnownMarketplaces": { - "acme-tools": { - "source": "owner/debug-marketplace" - } - } - }"#, - ) - .expect("write settings"); - - let outcome = service_for_paths(external_agent_home, codex_home.clone()) - .import(vec![ExternalAgentConfigMigrationItem { - item_type: ExternalAgentConfigMigrationItemType::Plugins, - description: String::new(), - cwd: None, - details: Some(MigrationDetails { - plugins: vec![PluginsMigration { - marketplace_name: "acme-tools".to_string(), - plugin_names: vec!["formatter".to_string()], - }], - }), - }]) - .await - .expect("import"); - - assert_eq!( - outcome, - vec![PendingPluginImport { - cwd: None, - details: MigrationDetails { - plugins: vec![PluginsMigration { - marketplace_name: "acme-tools".to_string(), - plugin_names: vec!["formatter".to_string()], - }], - }, - }] - ); - assert!(!codex_home.join("config.toml").exists()); -} - -#[tokio::test] -async fn detect_home_skips_config_when_target_already_has_supported_fields() { - let (_root, external_agent_home, codex_home) = fixture_paths(); - fs::create_dir_all(&external_agent_home).expect("create external agent home"); - fs::create_dir_all(&codex_home).expect("create codex home"); - fs::write( - external_agent_home.join("settings.json"), - r#"{"env":{"FOO":"bar"},"sandbox":{"enabled":true}}"#, - ) - .expect("write settings"); - fs::write( - codex_home.join("config.toml"), - r#" - sandbox_mode = "workspace-write" - - [shell_environment_policy] - inherit = "core" - - [shell_environment_policy.set] - FOO = "bar" - "#, - ) - .expect("write config"); - - let items = service_for_paths(external_agent_home, codex_home) - .detect(ExternalAgentConfigDetectOptions { - include_home: true, - cwds: None, - }) - .await - .expect("detect"); - - assert_eq!(items, Vec::::new()); -} - -#[tokio::test] -async fn detect_home_skips_skills_when_all_skill_directories_exist() { - let (_root, external_agent_home, codex_home) = fixture_paths(); - let agents_skills = codex_home - .parent() - .map(|parent| parent.join(".agents").join("skills")) - .unwrap_or_else(|| PathBuf::from(".agents").join("skills")); - fs::create_dir_all(external_agent_home.join("skills").join("skill-a")).expect("create source"); - fs::create_dir_all(agents_skills.join("skill-a")).expect("create target"); - - let items = service_for_paths(external_agent_home, codex_home) - .detect(ExternalAgentConfigDetectOptions { - include_home: true, - cwds: None, - }) - .await - .expect("detect"); - - assert_eq!(items, Vec::::new()); -} - -#[tokio::test] -async fn import_repo_agents_md_rewrites_terms_and_skips_non_empty_targets() { - let root = TempDir::new().expect("create tempdir"); - let repo_root = root.path().join("repo-a"); - let repo_with_existing_target = root.path().join("repo-b"); - fs::create_dir_all(repo_root.join(".git")).expect("create git"); - fs::create_dir_all(repo_with_existing_target.join(".git")).expect("create git"); - fs::write( - repo_root.join("CLAUDE.md"), - "Claude code\nclaude\nCLAUDE-CODE\nSee CLAUDE.md\n", - ) - .expect("write source"); - fs::write(repo_with_existing_target.join("CLAUDE.md"), "new source").expect("write source"); - fs::write( - repo_with_existing_target.join("AGENTS.md"), - "keep existing target", - ) - .expect("write target"); - - service_for_paths(root.path().join(".claude"), root.path().join(".codex")) - .import(vec![ - ExternalAgentConfigMigrationItem { - item_type: ExternalAgentConfigMigrationItemType::AgentsMd, - description: String::new(), - cwd: Some(repo_root.clone()), - details: None, - }, - ExternalAgentConfigMigrationItem { - item_type: ExternalAgentConfigMigrationItemType::AgentsMd, - description: String::new(), - cwd: Some(repo_with_existing_target.clone()), - details: None, - }, - ]) - .await - .expect("import"); - - assert_eq!( - fs::read_to_string(repo_root.join("AGENTS.md")).expect("read target"), - "Codex\nCodex\nCodex\nSee AGENTS.md\n" - ); - assert_eq!( - fs::read_to_string(repo_with_existing_target.join("AGENTS.md")) - .expect("read existing target"), - "keep existing target" - ); -} - -#[tokio::test] -async fn import_repo_agents_md_overwrites_empty_targets() { - let root = TempDir::new().expect("create tempdir"); - let repo_root = root.path().join("repo"); - fs::create_dir_all(repo_root.join(".git")).expect("create git"); - fs::write(repo_root.join("CLAUDE.md"), "Claude code guidance").expect("write source"); - fs::write(repo_root.join("AGENTS.md"), " \n\t").expect("write empty target"); - - service_for_paths(root.path().join(".claude"), root.path().join(".codex")) - .import(vec![ExternalAgentConfigMigrationItem { - item_type: ExternalAgentConfigMigrationItemType::AgentsMd, - description: String::new(), - cwd: Some(repo_root.clone()), - details: None, - }]) - .await - .expect("import"); - - assert_eq!( - fs::read_to_string(repo_root.join("AGENTS.md")).expect("read target"), - "Codex guidance" - ); -} - -#[tokio::test] -async fn detect_repo_prefers_non_empty_external_agent_agents_source() { - let root = TempDir::new().expect("create tempdir"); - let repo_root = root.path().join("repo"); - fs::create_dir_all(repo_root.join(".git")).expect("create git"); - fs::create_dir_all(repo_root.join(".claude")).expect("create dot claude"); - fs::write(repo_root.join("CLAUDE.md"), " \n\t").expect("write empty root source"); - fs::write( - repo_root.join(".claude").join("CLAUDE.md"), - "Claude code guidance", - ) - .expect("write dot claude source"); - - let items = service_for_paths(root.path().join(".claude"), root.path().join(".codex")) - .detect(ExternalAgentConfigDetectOptions { - include_home: false, - cwds: Some(vec![repo_root.clone()]), - }) - .await - .expect("detect"); - - assert_eq!( - items, - vec![ExternalAgentConfigMigrationItem { - item_type: ExternalAgentConfigMigrationItemType::AgentsMd, - description: format!( - "Migrate {} to {}", - repo_root.join(".claude").join("CLAUDE.md").display(), - repo_root.join("AGENTS.md").display(), - ), - cwd: Some(repo_root), - details: None, - }] - ); -} - -#[tokio::test] -async fn import_repo_uses_non_empty_external_agent_agents_source() { - let root = TempDir::new().expect("create tempdir"); - let repo_root = root.path().join("repo"); - fs::create_dir_all(repo_root.join(".git")).expect("create git"); - fs::create_dir_all(repo_root.join(".claude")).expect("create dot claude"); - fs::write(repo_root.join("CLAUDE.md"), "").expect("write empty root source"); - fs::write( - repo_root.join(".claude").join("CLAUDE.md"), - "Claude code guidance", - ) - .expect("write dot claude source"); - - service_for_paths(root.path().join(".claude"), root.path().join(".codex")) - .import(vec![ExternalAgentConfigMigrationItem { - item_type: ExternalAgentConfigMigrationItemType::AgentsMd, - description: String::new(), - cwd: Some(repo_root.clone()), - details: None, - }]) - .await - .expect("import"); - - assert_eq!( - fs::read_to_string(repo_root.join("AGENTS.md")).expect("read target"), - "Codex guidance" - ); -} - -#[test] -fn migration_metric_tags_for_skills_include_skills_count() { - assert_eq!( - migration_metric_tags(ExternalAgentConfigMigrationItemType::Skills, Some(3)), - vec![ - ("migration_type", "skills".to_string()), - ("skills_count", "3".to_string()), - ] - ); -} - -#[tokio::test] -async fn detect_home_lists_enabled_plugins_from_settings() { - let (_root, external_agent_home, codex_home) = fixture_paths(); - fs::create_dir_all(&external_agent_home).expect("create external agent home"); - fs::write( - external_agent_home.join("settings.json"), - r#"{ - "enabledPlugins": { - "formatter@acme-tools": true, - "deployer@acme-tools": true, - "analyzer@security-plugins": false - }, - "extraKnownMarketplaces": { - "acme-tools": { - "source": "acme-corp/claude-plugins" - } - } - }"#, - ) - .expect("write settings"); - - let items = service_for_paths(external_agent_home.clone(), codex_home) - .detect(ExternalAgentConfigDetectOptions { - include_home: true, - cwds: None, - }) - .await - .expect("detect"); - - assert_eq!( - items, - vec![ExternalAgentConfigMigrationItem { - item_type: ExternalAgentConfigMigrationItemType::Plugins, - description: format!( - "Migrate enabled plugins from {}", - external_agent_home.join("settings.json").display() - ), - cwd: None, - details: Some(MigrationDetails { - plugins: vec![PluginsMigration { - marketplace_name: "acme-tools".to_string(), - plugin_names: vec!["deployer".to_string(), "formatter".to_string()], - }], - }), - }] - ); -} - -#[tokio::test] -async fn detect_repo_skips_plugins_that_are_already_configured_in_codex() { - let root = TempDir::new().expect("create tempdir"); - let external_agent_home = root.path().join(".claude"); - let codex_home = root.path().join(".codex"); - let repo_root = root.path().join("repo"); - fs::create_dir_all(repo_root.join(".git")).expect("create git dir"); - fs::create_dir_all(repo_root.join(".claude")).expect("create repo external agent dir"); - fs::create_dir_all(&codex_home).expect("create codex home"); - fs::write( - repo_root.join(".claude").join("settings.json"), - r#"{ - "enabledPlugins": { - "formatter@acme-tools": true, - "deployer@acme-tools": true - }, - "extraKnownMarketplaces": { - "acme-tools": { - "source": "acme-corp/claude-plugins" - } - } - }"#, - ) - .expect("write repo settings"); - fs::write( - codex_home.join("config.toml"), - r#" -[plugins."formatter@acme-tools"] -enabled = true -"#, - ) - .expect("write codex config"); - - let items = service_for_paths(external_agent_home, codex_home) - .detect(ExternalAgentConfigDetectOptions { - include_home: false, - cwds: Some(vec![repo_root.clone()]), - }) - .await - .expect("detect"); - - assert_eq!( - items, - vec![ExternalAgentConfigMigrationItem { - item_type: ExternalAgentConfigMigrationItemType::Plugins, - description: format!( - "Migrate enabled plugins from {}", - repo_root.join(".claude").join("settings.json").display() - ), - cwd: Some(repo_root), - details: Some(MigrationDetails { - plugins: vec![PluginsMigration { - marketplace_name: "acme-tools".to_string(), - plugin_names: vec!["deployer".to_string()], - }], - }), - }] - ); -} - -#[tokio::test] -async fn detect_repo_skips_plugins_that_are_disabled_in_codex() { - let root = TempDir::new().expect("create tempdir"); - let external_agent_home = root.path().join(".claude"); - let codex_home = root.path().join(".codex"); - let repo_root = root.path().join("repo"); - fs::create_dir_all(repo_root.join(".git")).expect("create git dir"); - fs::create_dir_all(repo_root.join(".claude")).expect("create repo external agent dir"); - fs::create_dir_all(&codex_home).expect("create codex home"); - fs::write( - repo_root.join(".claude").join("settings.json"), - r#"{ - "enabledPlugins": { - "formatter@acme-tools": true - }, - "extraKnownMarketplaces": { - "acme-tools": { - "source": "acme-corp/claude-plugins" - } - } - }"#, - ) - .expect("write repo settings"); - fs::write( - codex_home.join("config.toml"), - r#" -[plugins."formatter@acme-tools"] -enabled = false -"#, - ) - .expect("write codex config"); - - let items = service_for_paths(external_agent_home, codex_home) - .detect(ExternalAgentConfigDetectOptions { - include_home: false, - cwds: Some(vec![repo_root]), - }) - .await - .expect("detect"); - - assert_eq!(items, Vec::::new()); -} - -#[tokio::test] -async fn detect_repo_skips_plugins_without_explicit_enabled_in_codex() { - let root = TempDir::new().expect("create tempdir"); - let external_agent_home = root.path().join(".claude"); - let codex_home = root.path().join(".codex"); - let repo_root = root.path().join("repo"); - fs::create_dir_all(repo_root.join(".git")).expect("create git dir"); - fs::create_dir_all(repo_root.join(".claude")).expect("create repo external agent dir"); - fs::create_dir_all(&codex_home).expect("create codex home"); - fs::write( - repo_root.join(".claude").join("settings.json"), - r#"{ - "enabledPlugins": { - "formatter@acme-tools": true - }, - "extraKnownMarketplaces": { - "acme-tools": { - "source": "acme-corp/claude-plugins" - } - } - }"#, - ) - .expect("write repo settings"); - fs::write( - codex_home.join("config.toml"), - r#" -[plugins."formatter@acme-tools"] -"#, - ) - .expect("write codex config"); - - let items = service_for_paths(external_agent_home, codex_home) - .detect(ExternalAgentConfigDetectOptions { - include_home: false, - cwds: Some(vec![repo_root]), - }) - .await - .expect("detect"); - - assert_eq!(items, Vec::::new()); -} - -#[tokio::test] -async fn import_plugins_requires_details() { - let (_root, external_agent_home, codex_home) = fixture_paths(); - - let err = service_for_paths(external_agent_home, codex_home) - .import_plugins(/*cwd*/ None, /*details*/ None) - .await - .expect_err("expected missing details error"); - - assert_eq!(err.kind(), io::ErrorKind::InvalidData); - assert_eq!(err.to_string(), "plugins migration item is missing details"); -} - -#[tokio::test] -async fn detect_repo_does_not_skip_plugins_only_configured_in_project_codex() { - let root = TempDir::new().expect("create tempdir"); - let external_agent_home = root.path().join(".claude"); - let codex_home = root.path().join(".codex"); - let repo_root = root.path().join("repo"); - fs::create_dir_all(repo_root.join(".git")).expect("create git dir"); - fs::create_dir_all(repo_root.join(".claude")).expect("create repo external agent dir"); - fs::create_dir_all(repo_root.join(".codex")).expect("create repo codex dir"); - fs::create_dir_all(&codex_home).expect("create codex home"); - fs::write( - repo_root.join(".claude").join("settings.json"), - r#"{ - "enabledPlugins": { - "formatter@acme-tools": true - }, - "extraKnownMarketplaces": { - "acme-tools": { - "source": "acme-corp/claude-plugins" - } - } - }"#, - ) - .expect("write repo settings"); - fs::write( - repo_root.join(".codex").join("config.toml"), - r#" -[plugins."formatter@acme-tools"] -enabled = true -"#, - ) - .expect("write project codex config"); - - let items = service_for_paths(external_agent_home, codex_home) - .detect(ExternalAgentConfigDetectOptions { - include_home: false, - cwds: Some(vec![repo_root.clone()]), - }) - .await - .expect("detect"); - - assert_eq!( - items, - vec![ExternalAgentConfigMigrationItem { - item_type: ExternalAgentConfigMigrationItemType::Plugins, - description: format!( - "Migrate enabled plugins from {}", - repo_root.join(".claude").join("settings.json").display() - ), - cwd: Some(repo_root), - details: Some(MigrationDetails { - plugins: vec![PluginsMigration { - marketplace_name: "acme-tools".to_string(), - plugin_names: vec!["formatter".to_string()], - }], - }), - }] - ); -} - -#[tokio::test] -async fn detect_home_skips_plugins_without_marketplace_source() { - let (_root, external_agent_home, codex_home) = fixture_paths(); - fs::create_dir_all(&external_agent_home).expect("create external agent home"); - fs::write( - external_agent_home.join("settings.json"), - r#"{ - "enabledPlugins": { - "formatter@acme-tools": true - } - }"#, - ) - .expect("write settings"); - - let items = service_for_paths(external_agent_home, codex_home) - .detect(ExternalAgentConfigDetectOptions { - include_home: true, - cwds: None, - }) - .await - .expect("detect"); - - assert_eq!(items, Vec::::new()); -} - -#[tokio::test] -async fn detect_home_skips_plugins_with_invalid_marketplace_source() { - let (_root, external_agent_home, codex_home) = fixture_paths(); - fs::create_dir_all(&external_agent_home).expect("create external agent home"); - fs::write( - external_agent_home.join("settings.json"), - r#"{ - "enabledPlugins": { - "formatter@acme-tools": true - }, - "extraKnownMarketplaces": { - "acme-tools": { - "source": "github" - } - } - }"#, - ) - .expect("write settings"); - - let items = service_for_paths(external_agent_home, codex_home) - .detect(ExternalAgentConfigDetectOptions { - include_home: true, - cwds: None, - }) - .await - .expect("detect"); - - assert_eq!(items, Vec::::new()); -} - -#[tokio::test] -async fn detect_repo_filters_plugins_against_installed_marketplace() { - let root = TempDir::new().expect("create tempdir"); - let external_agent_home = root.path().join(".claude"); - let codex_home = root.path().join(".codex"); - let repo_root = root.path().join("repo"); - let marketplace_root = codex_home.join(".tmp").join("marketplaces").join("debug"); - fs::create_dir_all(repo_root.join(".git")).expect("create git dir"); - fs::create_dir_all(repo_root.join(".claude")).expect("create repo external agent dir"); - fs::create_dir_all(marketplace_root.join(".agents").join("plugins")) - .expect("create marketplace manifest dir"); - fs::create_dir_all( - marketplace_root - .join("plugins") - .join("sample") - .join(".codex-plugin"), - ) - .expect("create sample plugin"); - fs::create_dir_all( - marketplace_root - .join("plugins") - .join("available") - .join(".codex-plugin"), - ) - .expect("create available plugin"); - fs::write( - repo_root.join(".claude").join("settings.json"), - r#"{ - "enabledPlugins": { - "sample@debug": true, - "available@debug": true, - "missing@debug": true - }, - "extraKnownMarketplaces": { - "debug": { - "source": "owner/debug-marketplace" - } - } - }"#, - ) - .expect("write repo settings"); - fs::write( - codex_home.join("config.toml"), - r#" -[marketplaces.debug] -source_type = "git" -source = "owner/debug-marketplace" -"#, - ) - .expect("write codex config"); - fs::write( - marketplace_root - .join(".agents") - .join("plugins") - .join("marketplace.json"), - r#"{ - "name": "debug", - "plugins": [ - { - "name": "sample", - "source": { - "source": "local", - "path": "./plugins/sample" - }, - "policy": { - "installation": "NOT_AVAILABLE" - } - }, - { - "name": "available", - "source": { - "source": "local", - "path": "./plugins/available" - } - } - ] -}"#, - ) - .expect("write marketplace manifest"); - fs::write( - marketplace_root - .join("plugins") - .join("sample") - .join(".codex-plugin") - .join("plugin.json"), - r#"{"name":"sample"}"#, - ) - .expect("write sample plugin manifest"); - fs::write( - marketplace_root - .join("plugins") - .join("available") - .join(".codex-plugin") - .join("plugin.json"), - r#"{"name":"available"}"#, - ) - .expect("write available plugin manifest"); - - let items = service_for_paths(external_agent_home, codex_home) - .detect(ExternalAgentConfigDetectOptions { - include_home: false, - cwds: Some(vec![repo_root.clone()]), - }) - .await - .expect("detect"); - - assert_eq!( - items, - vec![ExternalAgentConfigMigrationItem { - item_type: ExternalAgentConfigMigrationItemType::Plugins, - description: format!( - "Migrate enabled plugins from {}", - repo_root.join(".claude").join("settings.json").display() - ), - cwd: Some(repo_root), - details: Some(MigrationDetails { - plugins: vec![PluginsMigration { - marketplace_name: "debug".to_string(), - plugin_names: vec!["available".to_string()], - }], - }), - }] - ); -} - -#[tokio::test] -async fn import_plugins_requires_source_marketplace_details() { - let (_root, external_agent_home, codex_home) = fixture_paths(); - fs::create_dir_all(&external_agent_home).expect("create external agent home"); - fs::write( - external_agent_home.join("settings.json"), - r#"{ - "enabledPlugins": { - "formatter@acme-tools": true - }, - "extraKnownMarketplaces": { - "acme-tools": { - "source": "github", - "repo": "acme-corp/claude-plugins" - } - } - }"#, - ) - .expect("write settings"); - - let outcome = service_for_paths(external_agent_home, codex_home) - .import_plugins( - /*cwd*/ None, - Some(MigrationDetails { - plugins: vec![PluginsMigration { - marketplace_name: "other-tools".to_string(), - plugin_names: github_plugin_details().plugins[0].plugin_names.clone(), - }], - }), - ) - .await - .expect("import plugins"); - - assert_eq!( - outcome, - PluginImportOutcome { - succeeded_marketplaces: Vec::new(), - succeeded_plugin_ids: Vec::new(), - failed_marketplaces: vec!["other-tools".to_string()], - failed_plugin_ids: vec!["formatter@other-tools".to_string()], - } - ); -} - -#[tokio::test] -async fn import_plugins_defers_marketplace_source_validation_to_add_marketplace() { - let (_root, external_agent_home, codex_home) = fixture_paths(); - fs::create_dir_all(&external_agent_home).expect("create external agent home"); - fs::write( - external_agent_home.join("settings.json"), - r#"{ - "enabledPlugins": { - "formatter@acme-tools": true - }, - "extraKnownMarketplaces": { - "acme-tools": { - "source": "local", - "path": "./external_plugins/acme-tools" - } - } - }"#, - ) - .expect("write settings"); - - let outcome = service_for_paths(external_agent_home, codex_home) - .import_plugins(/*cwd*/ None, Some(github_plugin_details())) - .await - .expect("import plugins"); - - assert_eq!( - outcome, - PluginImportOutcome { - succeeded_marketplaces: Vec::new(), - succeeded_plugin_ids: Vec::new(), - failed_marketplaces: vec!["acme-tools".to_string()], - failed_plugin_ids: vec!["formatter@acme-tools".to_string()], - } - ); -} - -#[tokio::test] -async fn import_plugins_supports_external_agent_plugin_marketplace_layout() { - let (_root, external_agent_home, codex_home) = fixture_paths(); - let marketplace_root = external_agent_home.join("my-marketplace"); - let plugin_root = marketplace_root.join("plugins").join("cloudflare"); - fs::create_dir_all(marketplace_root.join(".claude-plugin")) - .expect("create marketplace manifest dir"); - fs::create_dir_all(plugin_root.join(".codex-plugin")).expect("create plugin manifest dir"); - fs::create_dir_all(&codex_home).expect("create codex home"); - - fs::write( - external_agent_home.join("settings.json"), - serde_json::to_string_pretty(&serde_json::json!({ - "enabledPlugins": { - "cloudflare@my-plugins": true - }, - "extraKnownMarketplaces": { - "my-plugins": { - "source": "local", - "path": marketplace_root - } - } - })) - .expect("serialize settings"), - ) - .expect("write settings"); - fs::write( - marketplace_root - .join(".claude-plugin") - .join("marketplace.json"), - r#"{ - "name": "my-plugins", - "plugins": [ - { - "name": "cloudflare", - "source": "./plugins/cloudflare" - } - ] - }"#, - ) - .expect("write marketplace manifest"); - fs::write( - plugin_root.join(".codex-plugin").join("plugin.json"), - r#"{"name":"cloudflare","version":"0.1.0"}"#, - ) - .expect("write plugin manifest"); - - let outcome = service_for_paths(external_agent_home, codex_home.clone()) - .import_plugins( - /*cwd*/ None, - Some(MigrationDetails { - plugins: vec![PluginsMigration { - marketplace_name: "my-plugins".to_string(), - plugin_names: vec!["cloudflare".to_string()], - }], - }), - ) - .await - .expect("import plugins"); - - assert_eq!( - outcome, - PluginImportOutcome { - succeeded_marketplaces: vec!["my-plugins".to_string()], - succeeded_plugin_ids: vec!["cloudflare@my-plugins".to_string()], - failed_marketplaces: Vec::new(), - failed_plugin_ids: Vec::new(), - } - ); - let config = fs::read_to_string(codex_home.join("config.toml")).expect("read config"); - assert!(config.contains(r#"[plugins."cloudflare@my-plugins"]"#)); - assert!(config.contains("enabled = true")); -} - -#[tokio::test] -async fn detect_home_supports_relative_external_agent_plugin_marketplace_path() { - let (_root, external_agent_home, codex_home) = fixture_paths(); - let marketplace_root = external_agent_home.join("my-marketplace"); - let plugin_root = marketplace_root.join("plugins").join("cloudflare"); - fs::create_dir_all(marketplace_root.join(".claude-plugin")) - .expect("create marketplace manifest dir"); - fs::create_dir_all(plugin_root.join(".codex-plugin")).expect("create plugin manifest dir"); - fs::create_dir_all(&codex_home).expect("create codex home"); - - fs::write( - external_agent_home.join("settings.json"), - r#"{ - "enabledPlugins": { - "cloudflare@my-plugins": true - }, - "extraKnownMarketplaces": { - "my-plugins": { - "source": "directory", - "path": "./my-marketplace" - } - } - }"#, - ) - .expect("write settings"); - fs::write( - marketplace_root - .join(".claude-plugin") - .join("marketplace.json"), - r#"{ - "name": "my-plugins", - "plugins": [ - { - "name": "cloudflare", - "source": "./plugins/cloudflare" - } - ] - }"#, - ) - .expect("write marketplace manifest"); - fs::write( - plugin_root.join(".codex-plugin").join("plugin.json"), - r#"{"name":"cloudflare","version":"0.1.0"}"#, - ) - .expect("write plugin manifest"); - - let items = service_for_paths(external_agent_home.clone(), codex_home) - .detect(ExternalAgentConfigDetectOptions { - include_home: true, - cwds: None, - }) - .await - .expect("detect"); - - assert_eq!( - items, - vec![ExternalAgentConfigMigrationItem { - item_type: ExternalAgentConfigMigrationItemType::Plugins, - description: format!( - "Migrate enabled plugins from {}", - external_agent_home.join("settings.json").display() - ), - cwd: None, - details: Some(MigrationDetails { - plugins: vec![PluginsMigration { - marketplace_name: "my-plugins".to_string(), - plugin_names: vec!["cloudflare".to_string()], - }], - }), - }] - ); -} - -#[tokio::test] -async fn detect_home_infers_claude_official_marketplace_when_missing_from_settings() { - let (_root, external_agent_home, codex_home) = fixture_paths(); - fs::create_dir_all(&external_agent_home).expect("create external agent home"); - fs::create_dir_all(&codex_home).expect("create codex home"); - - fs::write( - external_agent_home.join("settings.json"), - r#"{ - "enabledPlugins": { - "sample@claude-plugins-official": true - } - }"#, - ) - .expect("write settings"); - - let items = service_for_paths(external_agent_home.clone(), codex_home) - .detect(ExternalAgentConfigDetectOptions { - include_home: true, - cwds: None, - }) - .await - .expect("detect"); - - assert_eq!( - items, - vec![ExternalAgentConfigMigrationItem { - item_type: ExternalAgentConfigMigrationItemType::Plugins, - description: format!( - "Migrate enabled plugins from {}", - external_agent_home.join("settings.json").display() - ), - cwd: None, - details: Some(MigrationDetails { - plugins: vec![PluginsMigration { - marketplace_name: "claude-plugins-official".to_string(), - plugin_names: vec!["sample".to_string()], - }], - }), - }] - ); -} - -#[tokio::test] -async fn import_plugins_supports_relative_external_agent_plugin_marketplace_path() { - let (_root, external_agent_home, codex_home) = fixture_paths(); - let marketplace_root = external_agent_home.join("my-marketplace"); - let plugin_root = marketplace_root.join("plugins").join("cloudflare"); - fs::create_dir_all(marketplace_root.join(".claude-plugin")) - .expect("create marketplace manifest dir"); - fs::create_dir_all(plugin_root.join(".codex-plugin")).expect("create plugin manifest dir"); - fs::create_dir_all(&codex_home).expect("create codex home"); - - fs::write( - external_agent_home.join("settings.json"), - r#"{ - "enabledPlugins": { - "cloudflare@my-plugins": true - }, - "extraKnownMarketplaces": { - "my-plugins": { - "source": "directory", - "path": "./my-marketplace" - } - } - }"#, - ) - .expect("write settings"); - fs::write( - marketplace_root - .join(".claude-plugin") - .join("marketplace.json"), - r#"{ - "name": "my-plugins", - "plugins": [ - { - "name": "cloudflare", - "source": "./plugins/cloudflare" - } - ] - }"#, - ) - .expect("write marketplace manifest"); - fs::write( - plugin_root.join(".codex-plugin").join("plugin.json"), - r#"{"name":"cloudflare","version":"0.1.0"}"#, - ) - .expect("write plugin manifest"); - - let outcome = service_for_paths(external_agent_home, codex_home.clone()) - .import_plugins( - /*cwd*/ None, - Some(MigrationDetails { - plugins: vec![PluginsMigration { - marketplace_name: "my-plugins".to_string(), - plugin_names: vec!["cloudflare".to_string()], - }], - }), - ) - .await - .expect("import plugins"); - - assert_eq!( - outcome, - PluginImportOutcome { - succeeded_marketplaces: vec!["my-plugins".to_string()], - succeeded_plugin_ids: vec!["cloudflare@my-plugins".to_string()], - failed_marketplaces: Vec::new(), - failed_plugin_ids: Vec::new(), - } - ); - let config = fs::read_to_string(codex_home.join("config.toml")).expect("read config"); - assert!(config.contains(r#"[plugins."cloudflare@my-plugins"]"#)); - assert!(config.contains("enabled = true")); -} - -#[tokio::test] -async fn import_plugins_infers_claude_official_marketplace_when_missing_from_settings() { - let (_root, external_agent_home, codex_home) = fixture_paths(); - fs::create_dir_all(&external_agent_home).expect("create external agent home"); - fs::create_dir_all(&codex_home).expect("create codex home"); - - fs::write( - external_agent_home.join("settings.json"), - r#"{ - "enabledPlugins": { - "sample@claude-plugins-official": true - } - }"#, - ) - .expect("write settings"); - - let outcome = service_for_paths(external_agent_home, codex_home) - .import_plugins( - /*cwd*/ None, - Some(MigrationDetails { - plugins: vec![PluginsMigration { - marketplace_name: "claude-plugins-official".to_string(), - plugin_names: vec!["sample".to_string()], - }], - }), - ) - .await - .expect("import plugins"); - - assert_eq!( - outcome, - PluginImportOutcome { - succeeded_marketplaces: vec!["claude-plugins-official".to_string()], - succeeded_plugin_ids: Vec::new(), - failed_marketplaces: Vec::new(), - failed_plugin_ids: vec!["sample@claude-plugins-official".to_string()], - } - ); -} - -#[tokio::test] -async fn detect_repo_supports_project_relative_external_agent_plugin_marketplace_path() { - let root = TempDir::new().expect("create tempdir"); - let external_agent_home = root.path().join(".claude"); - let codex_home = root.path().join(".codex"); - let repo_root = root.path().join("repo"); - let marketplace_root = repo_root.join("my-marketplace"); - let plugin_root = marketplace_root.join("plugins").join("cloudflare"); - fs::create_dir_all(repo_root.join(".git")).expect("create git dir"); - fs::create_dir_all(repo_root.join(".claude")).expect("create repo external agent dir"); - fs::create_dir_all(marketplace_root.join(".claude-plugin")) - .expect("create marketplace manifest dir"); - fs::create_dir_all(plugin_root.join(".codex-plugin")).expect("create plugin manifest dir"); - fs::create_dir_all(&codex_home).expect("create codex home"); - - fs::write( - repo_root.join(".claude").join("settings.json"), - r#"{ - "enabledPlugins": { - "cloudflare@my-plugins": true - }, - "extraKnownMarketplaces": { - "my-plugins": { - "source": "directory", - "path": "./my-marketplace" - } - } - }"#, - ) - .expect("write settings"); - fs::write( - marketplace_root - .join(".claude-plugin") - .join("marketplace.json"), - r#"{ - "name": "my-plugins", - "plugins": [ - { - "name": "cloudflare", - "source": "./plugins/cloudflare" - } - ] - }"#, - ) - .expect("write marketplace manifest"); - fs::write( - plugin_root.join(".codex-plugin").join("plugin.json"), - r#"{"name":"cloudflare","version":"0.1.0"}"#, - ) - .expect("write plugin manifest"); - - let items = service_for_paths(external_agent_home, codex_home) - .detect(ExternalAgentConfigDetectOptions { - include_home: false, - cwds: Some(vec![repo_root.clone()]), - }) - .await - .expect("detect"); - - assert_eq!( - items, - vec![ExternalAgentConfigMigrationItem { - item_type: ExternalAgentConfigMigrationItemType::Plugins, - description: format!( - "Migrate enabled plugins from {}", - repo_root.join(".claude").join("settings.json").display() - ), - cwd: Some(repo_root), - details: Some(MigrationDetails { - plugins: vec![PluginsMigration { - marketplace_name: "my-plugins".to_string(), - plugin_names: vec!["cloudflare".to_string()], - }], - }), - }] - ); -} - -#[tokio::test] -async fn import_plugins_supports_project_relative_external_agent_plugin_marketplace_path() { - let root = TempDir::new().expect("create tempdir"); - let external_agent_home = root.path().join(".claude"); - let codex_home = root.path().join(".codex"); - let repo_root = root.path().join("repo"); - let marketplace_root = repo_root.join("my-marketplace"); - let plugin_root = marketplace_root.join("plugins").join("cloudflare"); - fs::create_dir_all(repo_root.join(".git")).expect("create git dir"); - fs::create_dir_all(repo_root.join(".claude")).expect("create repo external agent dir"); - fs::create_dir_all(marketplace_root.join(".claude-plugin")) - .expect("create marketplace manifest dir"); - fs::create_dir_all(plugin_root.join(".codex-plugin")).expect("create plugin manifest dir"); - fs::create_dir_all(&codex_home).expect("create codex home"); - - fs::write( - repo_root.join(".claude").join("settings.json"), - r#"{ - "enabledPlugins": { - "cloudflare@my-plugins": true - }, - "extraKnownMarketplaces": { - "my-plugins": { - "source": "directory", - "path": "./my-marketplace" - } - } - }"#, - ) - .expect("write settings"); - fs::write( - marketplace_root - .join(".claude-plugin") - .join("marketplace.json"), - r#"{ - "name": "my-plugins", - "plugins": [ - { - "name": "cloudflare", - "source": "./plugins/cloudflare" - } - ] - }"#, - ) - .expect("write marketplace manifest"); - fs::write( - plugin_root.join(".codex-plugin").join("plugin.json"), - r#"{"name":"cloudflare","version":"0.1.0"}"#, - ) - .expect("write plugin manifest"); - - let outcome = service_for_paths(external_agent_home, codex_home.clone()) - .import_plugins( - Some(repo_root.as_path()), - Some(MigrationDetails { - plugins: vec![PluginsMigration { - marketplace_name: "my-plugins".to_string(), - plugin_names: vec!["cloudflare".to_string()], - }], - }), - ) - .await - .expect("import plugins"); - - assert_eq!( - outcome, - PluginImportOutcome { - succeeded_marketplaces: vec!["my-plugins".to_string()], - succeeded_plugin_ids: vec!["cloudflare@my-plugins".to_string()], - failed_marketplaces: Vec::new(), - failed_plugin_ids: Vec::new(), - } - ); - let config = fs::read_to_string(codex_home.join("config.toml")).expect("read config"); - assert!(config.contains(r#"[plugins."cloudflare@my-plugins"]"#)); - assert!(config.contains("enabled = true")); -} - -#[test] -fn import_skills_returns_only_new_skill_directory_count() { - let (_root, external_agent_home, codex_home) = fixture_paths(); - let agents_skills = codex_home - .parent() - .map(|parent| parent.join(".agents").join("skills")) - .unwrap_or_else(|| PathBuf::from(".agents").join("skills")); - fs::create_dir_all(external_agent_home.join("skills").join("skill-a")) - .expect("create source a"); - fs::create_dir_all(external_agent_home.join("skills").join("skill-b")) - .expect("create source b"); - fs::create_dir_all(agents_skills.join("skill-a")).expect("create existing target"); - - let copied_count = service_for_paths(external_agent_home, codex_home) - .import_skills(/*cwd*/ None) - .expect("import skills"); - - assert_eq!(copied_count, 1); -} diff --git a/vendor/codex/codex-rs/app-server/src/config/mod.rs b/vendor/codex/codex-rs/app-server/src/config/mod.rs deleted file mode 100644 index 95d64d15..00000000 --- a/vendor/codex/codex-rs/app-server/src/config/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub(crate) mod external_agent_config; diff --git a/vendor/codex/codex-rs/app-server/src/config_api.rs b/vendor/codex/codex-rs/app-server/src/config_api.rs index a1df875c..39672e1d 100644 --- a/vendor/codex/codex-rs/app-server/src/config_api.rs +++ b/vendor/codex/codex-rs/app-server/src/config_api.rs @@ -3,7 +3,6 @@ use crate::config_manager_service::ConfigManagerError; use crate::error_code::INTERNAL_ERROR_CODE; use crate::error_code::INVALID_REQUEST_ERROR_CODE; use async_trait::async_trait; -use codex_analytics::AnalyticsEventsClient; use codex_app_server_protocol::ConfigBatchWriteParams; use codex_app_server_protocol::ConfigReadParams; use codex_app_server_protocol::ConfigReadResponse; @@ -24,9 +23,6 @@ use codex_core::config::Config; use codex_core::config_loader::ConfigRequirementsToml; use codex_core::config_loader::ResidencyRequirement as CoreResidencyRequirement; use codex_core::config_loader::SandboxModeRequirement as CoreSandboxModeRequirement; -use codex_core::plugins::PluginId; -use codex_core_plugins::loader::installed_plugin_telemetry_metadata; -use codex_core_plugins::toggles::collect_plugin_enabled_candidates; use codex_features::canonical_feature_for_key; use codex_features::feature_for_key; use codex_protocol::config_types::WebSearchMode; @@ -37,9 +33,7 @@ use std::sync::Arc; use tracing::warn; const SUPPORTED_EXPERIMENTAL_FEATURE_ENABLEMENT: &[&str] = &[ - "apps", "memories", - "plugins", "tool_search", "tool_suggest", "tool_call_mcp_elicitation", @@ -69,19 +63,16 @@ impl UserConfigReloader for ThreadManager { pub(crate) struct ConfigApi { config_manager: ConfigManager, user_config_reloader: Arc, - analytics_events_client: AnalyticsEventsClient, } impl ConfigApi { pub(crate) fn new( config_manager: ConfigManager, user_config_reloader: Arc, - analytics_events_client: AnalyticsEventsClient, ) -> Self { Self { config_manager, user_config_reloader, - analytics_events_client, } } @@ -145,14 +136,11 @@ impl ConfigApi { &self, params: ConfigValueWriteParams, ) -> Result { - let pending_changes = - collect_plugin_enabled_candidates([(¶ms.key_path, ¶ms.value)].into_iter()); let response = self .config_manager .write_value(params) .await .map_err(map_error)?; - self.emit_plugin_toggle_events(pending_changes).await; Ok(response) } @@ -161,18 +149,11 @@ impl ConfigApi { params: ConfigBatchWriteParams, ) -> Result { let reload_user_config = params.reload_user_config; - let pending_changes = collect_plugin_enabled_candidates( - params - .edits - .iter() - .map(|edit| (&edit.key_path, &edit.value)), - ); let response = self .config_manager .batch_write(params) .await .map_err(map_error)?; - self.emit_plugin_toggle_events(pending_changes).await; if reload_user_config { self.user_config_reloader.reload_user_config().await; } @@ -236,25 +217,6 @@ impl ConfigApi { Ok(ExperimentalFeatureEnablementSetResponse { enablement }) } - - async fn emit_plugin_toggle_events( - &self, - pending_changes: std::collections::BTreeMap, - ) { - for (plugin_id, enabled) in pending_changes { - let Ok(plugin_id) = PluginId::parse(&plugin_id) else { - continue; - }; - let metadata = - installed_plugin_telemetry_metadata(self.config_manager.codex_home(), &plugin_id) - .await; - if enabled { - self.analytics_events_client.track_plugin_enabled(metadata); - } else { - self.analytics_events_client.track_plugin_disabled(metadata); - } - } - } } fn map_requirements_toml_to_api(requirements: ConfigRequirementsToml) -> ConfigRequirements { @@ -416,7 +378,6 @@ fn config_write_error(code: ConfigWriteErrorCode, message: impl Into) -> mod tests { use super::*; use crate::config_manager::apply_runtime_feature_enablement; - use codex_analytics::AnalyticsEventsClient; use codex_arg0::Arg0DispatchPaths; use codex_core::config_loader::CloudRequirementsLoader; use codex_core::config_loader::LoaderOverrides; @@ -426,8 +387,6 @@ mod tests { use codex_core::config_loader::NetworkUnixSocketPermissionToml as CoreNetworkUnixSocketPermissionToml; use codex_core::config_loader::NetworkUnixSocketPermissionsToml as CoreNetworkUnixSocketPermissionsToml; use codex_features::Feature; - use codex_login::AuthManager; - use codex_login::CodexAuth; use codex_protocol::config_types::ApprovalsReviewer as CoreApprovalsReviewer; use codex_protocol::protocol::AskForApproval as CoreAskForApproval; use pretty_assertions::assert_eq; @@ -723,13 +682,6 @@ mod tests { let user_config_path = codex_home.path().join("config.toml"); std::fs::write(&user_config_path, "").expect("write config"); let reloader = Arc::new(RecordingUserConfigReloader::default()); - let analytics_config = Arc::new( - codex_core::config::ConfigBuilder::default() - .build() - .await - .expect("load analytics config"), - ); - let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("test")); let config_api = ConfigApi::new( ConfigManager::new( codex_home.path().to_path_buf(), @@ -740,14 +692,6 @@ mod tests { Arc::new(codex_config::NoopThreadConfigLoader), ), reloader.clone(), - AnalyticsEventsClient::new( - auth_manager, - analytics_config - .chatgpt_base_url - .trim_end_matches('/') - .to_string(), - analytics_config.analytics_enabled, - ), ); let response = config_api diff --git a/vendor/codex/codex-rs/app-server/src/external_agent_config_api.rs b/vendor/codex/codex-rs/app-server/src/external_agent_config_api.rs deleted file mode 100644 index 0741ad5b..00000000 --- a/vendor/codex/codex-rs/app-server/src/external_agent_config_api.rs +++ /dev/null @@ -1,152 +0,0 @@ -use crate::config::external_agent_config::ExternalAgentConfigDetectOptions; -use crate::config::external_agent_config::ExternalAgentConfigMigrationItem as CoreMigrationItem; -use crate::config::external_agent_config::ExternalAgentConfigMigrationItemType as CoreMigrationItemType; -use crate::config::external_agent_config::ExternalAgentConfigService; -use crate::config::external_agent_config::PendingPluginImport; -use crate::error_code::INTERNAL_ERROR_CODE; -use codex_app_server_protocol::ExternalAgentConfigDetectParams; -use codex_app_server_protocol::ExternalAgentConfigDetectResponse; -use codex_app_server_protocol::ExternalAgentConfigImportParams; -use codex_app_server_protocol::ExternalAgentConfigMigrationItem; -use codex_app_server_protocol::ExternalAgentConfigMigrationItemType; -use codex_app_server_protocol::JSONRPCErrorError; -use codex_app_server_protocol::MigrationDetails; -use codex_app_server_protocol::PluginsMigration; -use std::io; -use std::path::PathBuf; - -#[derive(Clone)] -pub(crate) struct ExternalAgentConfigApi { - migration_service: ExternalAgentConfigService, -} - -impl ExternalAgentConfigApi { - pub(crate) fn new(codex_home: PathBuf) -> Self { - Self { - migration_service: ExternalAgentConfigService::new(codex_home), - } - } - - pub(crate) async fn detect( - &self, - params: ExternalAgentConfigDetectParams, - ) -> Result { - let items = self - .migration_service - .detect(ExternalAgentConfigDetectOptions { - include_home: params.include_home, - cwds: params.cwds, - }) - .await - .map_err(map_io_error)?; - - Ok(ExternalAgentConfigDetectResponse { - items: items - .into_iter() - .map(|migration_item| ExternalAgentConfigMigrationItem { - item_type: match migration_item.item_type { - CoreMigrationItemType::Config => { - ExternalAgentConfigMigrationItemType::Config - } - CoreMigrationItemType::Skills => { - ExternalAgentConfigMigrationItemType::Skills - } - CoreMigrationItemType::AgentsMd => { - ExternalAgentConfigMigrationItemType::AgentsMd - } - CoreMigrationItemType::Plugins => { - ExternalAgentConfigMigrationItemType::Plugins - } - CoreMigrationItemType::McpServerConfig => { - ExternalAgentConfigMigrationItemType::McpServerConfig - } - }, - description: migration_item.description, - cwd: migration_item.cwd, - details: migration_item.details.map(|details| MigrationDetails { - plugins: details - .plugins - .into_iter() - .map(|plugin| PluginsMigration { - marketplace_name: plugin.marketplace_name, - plugin_names: plugin.plugin_names, - }) - .collect(), - }), - }) - .collect(), - }) - } - - pub(crate) async fn import( - &self, - params: ExternalAgentConfigImportParams, - ) -> Result, JSONRPCErrorError> { - self.migration_service - .import( - params - .migration_items - .into_iter() - .map(|migration_item| CoreMigrationItem { - item_type: match migration_item.item_type { - ExternalAgentConfigMigrationItemType::Config => { - CoreMigrationItemType::Config - } - ExternalAgentConfigMigrationItemType::Skills => { - CoreMigrationItemType::Skills - } - ExternalAgentConfigMigrationItemType::AgentsMd => { - CoreMigrationItemType::AgentsMd - } - ExternalAgentConfigMigrationItemType::Plugins => { - CoreMigrationItemType::Plugins - } - ExternalAgentConfigMigrationItemType::McpServerConfig => { - CoreMigrationItemType::McpServerConfig - } - }, - description: migration_item.description, - cwd: migration_item.cwd, - details: migration_item.details.map(|details| { - crate::config::external_agent_config::MigrationDetails { - plugins: details - .plugins - .into_iter() - .map(|plugin| { - crate::config::external_agent_config::PluginsMigration { - marketplace_name: plugin.marketplace_name, - plugin_names: plugin.plugin_names, - } - }) - .collect(), - } - }), - }) - .collect(), - ) - .await - .map_err(map_io_error) - } - - pub(crate) async fn complete_pending_plugin_import( - &self, - pending_plugin_import: PendingPluginImport, - ) -> Result<(), JSONRPCErrorError> { - self.migration_service - .import_plugins( - pending_plugin_import.cwd.as_deref(), - Some(pending_plugin_import.details), - ) - .await - .map(|_| ()) - .map_err(map_io_error) - } -} - -fn map_io_error(err: io::Error) -> JSONRPCErrorError { - JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: err.to_string(), - data: None, - } -} diff --git a/vendor/codex/codex-rs/app-server/src/lib.rs b/vendor/codex/codex-rs/app-server/src/lib.rs index 0e972ffa..bd6caebe 100644 --- a/vendor/codex/codex-rs/app-server/src/lib.rs +++ b/vendor/codex/codex-rs/app-server/src/lib.rs @@ -69,7 +69,6 @@ mod app_server_tracing; mod bespoke_event_handling; mod codex_message_processor; mod command_exec; -mod config; mod config_api; mod config_manager; mod config_manager_service; @@ -77,7 +76,6 @@ mod device_key_api; mod dynamic_tools; mod epiphany_invalidation; mod error_code; -mod external_agent_config_api; mod filters; mod fs_api; mod fs_watch; diff --git a/vendor/codex/codex-rs/app-server/src/message_processor.rs b/vendor/codex/codex-rs/app-server/src/message_processor.rs index 57fa6e21..bdf989dd 100644 --- a/vendor/codex/codex-rs/app-server/src/message_processor.rs +++ b/vendor/codex/codex-rs/app-server/src/message_processor.rs @@ -11,7 +11,6 @@ use crate::config_api::ConfigApi; use crate::config_manager::ConfigManager; use crate::device_key_api::DeviceKeyApi; use crate::error_code::INVALID_REQUEST_ERROR_CODE; -use crate::external_agent_config_api::ExternalAgentConfigApi; use crate::fs_api::FsApi; use crate::fs_watch::FsWatchManager; use crate::outgoing_message::ConnectionId; @@ -25,7 +24,6 @@ use async_trait::async_trait; use axum::http::HeaderValue; use codex_analytics::AnalyticsEventsClient; use codex_analytics::AppServerRpcTransport; -use codex_app_server_protocol::AppListUpdatedNotification; use codex_app_server_protocol::AuthMode as LoginAuthMode; use codex_app_server_protocol::ChatgptAuthTokensRefreshParams; use codex_app_server_protocol::ChatgptAuthTokensRefreshReason; @@ -43,10 +41,8 @@ use codex_app_server_protocol::DeviceKeySignParams; use codex_app_server_protocol::ExperimentalApi; use codex_app_server_protocol::ExperimentalFeatureEnablementSetParams; use codex_app_server_protocol::ExternalAgentConfigDetectParams; -use codex_app_server_protocol::ExternalAgentConfigImportCompletedNotification; +use codex_app_server_protocol::ExternalAgentConfigDetectResponse; use codex_app_server_protocol::ExternalAgentConfigImportParams; -use codex_app_server_protocol::ExternalAgentConfigImportResponse; -use codex_app_server_protocol::ExternalAgentConfigMigrationItemType; use codex_app_server_protocol::FsCopyParams; use codex_app_server_protocol::FsCreateDirectoryParams; use codex_app_server_protocol::FsGetMetadataParams; @@ -66,7 +62,6 @@ use codex_app_server_protocol::ServerNotification; use codex_app_server_protocol::ServerRequestPayload; use codex_app_server_protocol::experimental_required_message; use codex_arg0::Arg0DispatchPaths; -use codex_chatgpt::connectors; use codex_core::ThreadManager; use codex_core::config::Config; use codex_exec_server::EnvironmentManager; @@ -167,10 +162,8 @@ impl ExternalAuth for ExternalAuthRefreshBridge { pub(crate) struct MessageProcessor { outgoing: Arc, codex_message_processor: CodexMessageProcessor, - thread_manager: Arc, config_api: ConfigApi, device_key_api: DeviceKeyApi, - external_agent_config_api: ExternalAgentConfigApi, fs_api: FsApi, auth_manager: Arc, analytics_events_client: AnalyticsEventsClient, @@ -300,10 +293,6 @@ impl MessageProcessor { environment_manager, Some(analytics_events_client.clone()), )); - thread_manager - .plugins_manager() - .set_analytics_events_client(analytics_events_client.clone()); - let codex_message_processor = CodexMessageProcessor::new(CodexMessageProcessorArgs { auth_manager: auth_manager.clone(), thread_manager: Arc::clone(&thread_manager), @@ -315,19 +304,8 @@ impl MessageProcessor { feedback, log_db, }); - // Keep plugin startup warmups aligned at app-server startup. - // TODO(xl): Move into PluginManager once this no longer depends on config feature gating. - thread_manager - .plugins_manager() - .maybe_start_plugin_startup_tasks_for_config(&config, auth_manager.clone()); - let config_api = ConfigApi::new( - config_manager, - thread_manager.clone(), - analytics_events_client.clone(), - ); + let config_api = ConfigApi::new(config_manager, thread_manager.clone()); let device_key_api = DeviceKeyApi::default(); - let external_agent_config_api = - ExternalAgentConfigApi::new(config.codex_home.to_path_buf()); let fs_api = FsApi::new( thread_manager .environment_manager() @@ -339,10 +317,8 @@ impl MessageProcessor { Self { outgoing, codex_message_processor, - thread_manager: Arc::clone(&thread_manager), config_api, device_key_api, - external_agent_config_api, fs_api, auth_manager, analytics_events_client, @@ -1047,86 +1023,11 @@ impl MessageProcessor { request_id: ConnectionRequestId, params: ExperimentalFeatureEnablementSetParams, ) { - let should_refresh_apps_list = params.enablement.get("apps").copied() == Some(true); let result = self .config_api .set_experimental_feature_enablement(params) .await; - let is_ok = result.is_ok(); self.handle_config_mutation_result(request_id, result).await; - if should_refresh_apps_list && is_ok { - self.refresh_apps_list_after_experimental_feature_enablement_set() - .await; - } - } - - async fn refresh_apps_list_after_experimental_feature_enablement_set(&self) { - let config = match self - .config_api - .load_latest_config(/*fallback_cwd*/ None) - .await - { - Ok(config) => config, - Err(error) => { - tracing::warn!( - "failed to load config for apps list refresh after experimental feature enablement: {}", - error.message - ); - return; - } - }; - let auth = self.auth_manager.auth().await; - if !config.features.apps_enabled_for_auth( - auth.as_ref() - .is_some_and(codex_login::CodexAuth::is_chatgpt_auth), - ) { - return; - } - - let outgoing = Arc::clone(&self.outgoing); - let environment_manager = self.thread_manager.environment_manager(); - tokio::spawn(async move { - let (all_connectors_result, accessible_connectors_result) = tokio::join!( - connectors::list_all_connectors_with_options(&config, /*force_refetch*/ true), - connectors::list_accessible_connectors_from_mcp_tools_with_environment_manager( - &config, - /*force_refetch*/ true, - &environment_manager, - ), - ); - let all_connectors = match all_connectors_result { - Ok(connectors) => connectors, - Err(err) => { - tracing::warn!( - "failed to force-refresh directory apps after experimental feature enablement: {err:#}" - ); - return; - } - }; - let accessible_connectors = match accessible_connectors_result { - Ok(status) => status.connectors, - Err(err) => { - tracing::warn!( - "failed to force-refresh accessible apps after experimental feature enablement: {err:#}" - ); - return; - } - }; - - let data = connectors::with_app_enabled_state( - connectors::merge_connectors_with_accessible( - all_connectors, - accessible_connectors, - /*all_connectors_loaded*/ true, - ), - &config, - ); - outgoing - .send_server_notification(ServerNotification::AppListUpdated( - AppListUpdatedNotification { data }, - )) - .await; - }); } async fn handle_config_mutation_result( @@ -1268,80 +1169,33 @@ impl MessageProcessor { async fn handle_external_agent_config_detect( &self, request_id: ConnectionRequestId, - params: ExternalAgentConfigDetectParams, + _params: ExternalAgentConfigDetectParams, ) { - match self.external_agent_config_api.detect(params).await { - Ok(response) => self.outgoing.send_response(request_id, response).await, - Err(error) => self.outgoing.send_error(request_id, error).await, - } + self.outgoing + .send_response( + request_id, + ExternalAgentConfigDetectResponse { items: Vec::new() }, + ) + .await; } async fn handle_external_agent_config_import( &self, request_id: ConnectionRequestId, - params: ExternalAgentConfigImportParams, + _params: ExternalAgentConfigImportParams, ) { - let has_plugin_imports = params.migration_items.iter().any(|item| { - matches!( - item.item_type, - ExternalAgentConfigMigrationItemType::Plugins + self.outgoing + .send_error( + request_id, + JSONRPCErrorError { + code: INVALID_REQUEST_ERROR_CODE, + message: + "externalAgentConfig/import is disabled in Epiphany's vestigial Codex organ" + .to_string(), + data: None, + }, ) - }); - match self.external_agent_config_api.import(params).await { - Ok(pending_plugin_imports) => { - if has_plugin_imports { - self.handle_config_mutation().await; - } - self.outgoing - .send_response(request_id, ExternalAgentConfigImportResponse {}) - .await; - - if !has_plugin_imports { - return; - } - - if pending_plugin_imports.is_empty() { - self.outgoing - .send_server_notification( - ServerNotification::ExternalAgentConfigImportCompleted( - ExternalAgentConfigImportCompletedNotification {}, - ), - ) - .await; - return; - } - - let external_agent_config_api = self.external_agent_config_api.clone(); - let outgoing = Arc::clone(&self.outgoing); - let thread_manager = Arc::clone(&self.thread_manager); - tokio::spawn(async move { - for pending_plugin_import in pending_plugin_imports { - match external_agent_config_api - .complete_pending_plugin_import(pending_plugin_import) - .await - { - Ok(()) => {} - Err(error) => { - tracing::warn!( - error = %error.message, - "external agent config plugin import failed" - ); - } - } - } - thread_manager.plugins_manager().clear_cache(); - thread_manager.skills_manager().clear_cache(); - outgoing - .send_server_notification( - ServerNotification::ExternalAgentConfigImportCompleted( - ExternalAgentConfigImportCompletedNotification {}, - ), - ) - .await; - }); - } - Err(error) => self.outgoing.send_error(request_id, error).await, - } + .await; } async fn handle_fs_read_file(&self, request_id: ConnectionRequestId, params: FsReadFileParams) { diff --git a/vendor/codex/codex-rs/app-server/tests/suite/v2/experimental_feature_list.rs b/vendor/codex/codex-rs/app-server/tests/suite/v2/experimental_feature_list.rs index 0c681e7f..656c3130 100644 --- a/vendor/codex/codex-rs/app-server/tests/suite/v2/experimental_feature_list.rs +++ b/vendor/codex/codex-rs/app-server/tests/suite/v2/experimental_feature_list.rs @@ -99,13 +99,15 @@ async fn experimental_feature_enablement_set_applies_to_global_and_thread_config let mut mcp = McpProcess::new(codex_home.path()).await?; timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - let actual = - set_experimental_feature_enablement(&mut mcp, BTreeMap::from([("apps".to_string(), true)])) - .await?; + let actual = set_experimental_feature_enablement( + &mut mcp, + BTreeMap::from([("tool_search".to_string(), true)]), + ) + .await?; assert_eq!( actual, ExperimentalFeatureEnablementSetResponse { - enablement: BTreeMap::from([("apps".to_string(), true)]), + enablement: BTreeMap::from([("tool_search".to_string(), true)]), } ); @@ -116,7 +118,7 @@ async fn experimental_feature_enablement_set_applies_to_global_and_thread_config config .additional .get("features") - .and_then(|features| features.get("apps")), + .and_then(|features| features.get("tool_search")), Some(&json!(true)) ); } @@ -165,14 +167,15 @@ async fn experimental_feature_enablement_set_only_updates_named_features() -> Re let mut mcp = McpProcess::new(codex_home.path()).await?; timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - set_experimental_feature_enablement(&mut mcp, BTreeMap::from([("apps".to_string(), true)])) - .await?; + set_experimental_feature_enablement( + &mut mcp, + BTreeMap::from([("tool_search".to_string(), true)]), + ) + .await?; let actual = set_experimental_feature_enablement( &mut mcp, BTreeMap::from([ ("memories".to_string(), true), - ("plugins".to_string(), true), - ("tool_search".to_string(), true), ("tool_suggest".to_string(), true), ("tool_call_mcp_elicitation".to_string(), false), ]), @@ -184,8 +187,6 @@ async fn experimental_feature_enablement_set_only_updates_named_features() -> Re ExperimentalFeatureEnablementSetResponse { enablement: BTreeMap::from([ ("memories".to_string(), true), - ("plugins".to_string(), true), - ("tool_search".to_string(), true), ("tool_suggest".to_string(), true), ("tool_call_mcp_elicitation".to_string(), false), ]), @@ -198,7 +199,7 @@ async fn experimental_feature_enablement_set_only_updates_named_features() -> Re config .additional .get("features") - .and_then(|features| features.get("apps")), + .and_then(|features| features.get("tool_search")), Some(&json!(true)) ); assert_eq!( @@ -208,20 +209,6 @@ async fn experimental_feature_enablement_set_only_updates_named_features() -> Re .and_then(|features| features.get("memories")), Some(&json!(true)) ); - assert_eq!( - config - .additional - .get("features") - .and_then(|features| features.get("plugins")), - Some(&json!(true)) - ); - assert_eq!( - config - .additional - .get("features") - .and_then(|features| features.get("tool_search")), - Some(&json!(true)) - ); assert_eq!( config .additional @@ -246,8 +233,11 @@ async fn experimental_feature_enablement_set_empty_map_is_no_op() -> Result<()> let mut mcp = McpProcess::new(codex_home.path()).await?; timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - set_experimental_feature_enablement(&mut mcp, BTreeMap::from([("apps".to_string(), true)])) - .await?; + set_experimental_feature_enablement( + &mut mcp, + BTreeMap::from([("tool_search".to_string(), true)]), + ) + .await?; let actual = set_experimental_feature_enablement(&mut mcp, BTreeMap::new()).await?; assert_eq!( @@ -263,7 +253,7 @@ async fn experimental_feature_enablement_set_empty_map_is_no_op() -> Result<()> config .additional .get("features") - .and_then(|features| features.get("apps")), + .and_then(|features| features.get("tool_search")), Some(&json!(true)) ); @@ -296,9 +286,9 @@ async fn experimental_feature_enablement_set_rejects_non_allowlisted_feature() - error.message ); assert!( - error.message.contains( - "apps, memories, plugins, tool_search, tool_suggest, tool_call_mcp_elicitation" - ), + error + .message + .contains("memories, tool_search, tool_suggest, tool_call_mcp_elicitation"), "{}", error.message ); diff --git a/vendor/codex/codex-rs/app-server/tests/suite/v2/external_agent_config.rs b/vendor/codex/codex-rs/app-server/tests/suite/v2/external_agent_config.rs deleted file mode 100644 index 049256b6..00000000 --- a/vendor/codex/codex-rs/app-server/tests/suite/v2/external_agent_config.rs +++ /dev/null @@ -1,183 +0,0 @@ -use std::time::Duration; - -use anyhow::Result; -use app_test_support::McpProcess; -use app_test_support::to_response; -use codex_app_server_protocol::ExternalAgentConfigImportResponse; -use codex_app_server_protocol::JSONRPCResponse; -use codex_app_server_protocol::PluginListParams; -use codex_app_server_protocol::PluginListResponse; -use codex_app_server_protocol::RequestId; -use pretty_assertions::assert_eq; -use tempfile::TempDir; -use tokio::time::timeout; - -const DEFAULT_TIMEOUT: Duration = Duration::from_secs(60); - -#[tokio::test] -async fn external_agent_config_import_sends_completion_notification_for_local_plugins() -> Result<()> -{ - let codex_home = TempDir::new()?; - let marketplace_root = codex_home.path().join("marketplace"); - let plugin_root = marketplace_root.join("plugins").join("sample"); - std::fs::create_dir_all(marketplace_root.join(".agents/plugins"))?; - std::fs::create_dir_all(plugin_root.join(".codex-plugin"))?; - std::fs::write( - marketplace_root.join(".agents/plugins/marketplace.json"), - r#"{ - "name": "debug", - "plugins": [ - { - "name": "sample", - "source": { - "source": "local", - "path": "./plugins/sample" - } - } - ] -}"#, - )?; - std::fs::write( - plugin_root.join(".codex-plugin/plugin.json"), - r#"{"name":"sample","version":"0.1.0"}"#, - )?; - std::fs::create_dir_all(codex_home.path().join(".claude"))?; - let settings = serde_json::json!({ - "enabledPlugins": { - "sample@debug": true - }, - "extraKnownMarketplaces": { - "debug": { - "source": "local", - "path": marketplace_root, - } - } - }); - std::fs::write( - codex_home.path().join(".claude").join("settings.json"), - serde_json::to_string_pretty(&settings)?, - )?; - - let home_dir = codex_home.path().display().to_string(); - let mut mcp = - McpProcess::new_with_env(codex_home.path(), &[("HOME", Some(home_dir.as_str()))]).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_raw_request( - "externalAgentConfig/import", - Some(serde_json::json!({ - "migrationItems": [{ - "itemType": "PLUGINS", - "description": "Import plugins", - "cwd": null, - "details": { - "plugins": [{ - "marketplaceName": "debug", - "pluginNames": ["sample"] - }] - } - }] - })), - ) - .await?; - - let response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - let response: ExternalAgentConfigImportResponse = to_response(response)?; - - assert_eq!(response, ExternalAgentConfigImportResponse {}); - let notification = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_notification_message("externalAgentConfig/import/completed"), - ) - .await??; - assert_eq!(notification.method, "externalAgentConfig/import/completed"); - - let request_id = mcp - .send_plugin_list_request(PluginListParams { cwds: None }) - .await?; - let response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - let response: PluginListResponse = to_response(response)?; - let plugin = response - .marketplaces - .iter() - .find(|marketplace| marketplace.name == "debug") - .and_then(|marketplace| { - marketplace - .plugins - .iter() - .find(|plugin| plugin.name == "sample") - }) - .expect("expected imported plugin to be listed"); - assert!(plugin.installed); - assert!(plugin.enabled); - Ok(()) -} - -#[tokio::test] -async fn external_agent_config_import_sends_completion_notification_after_pending_plugins_finish() --> Result<()> { - let codex_home = TempDir::new()?; - std::fs::create_dir_all(codex_home.path().join(".claude"))?; - std::fs::write( - codex_home.path().join(".claude").join("settings.json"), - r#"{ - "enabledPlugins": { - "formatter@acme-tools": true - }, - "extraKnownMarketplaces": { - "acme-tools": { - "source": "owner/debug-marketplace" - } - } -}"#, - )?; - - let home_dir = codex_home.path().display().to_string(); - let mut mcp = - McpProcess::new_with_env(codex_home.path(), &[("HOME", Some(home_dir.as_str()))]).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_raw_request( - "externalAgentConfig/import", - Some(serde_json::json!({ - "migrationItems": [{ - "itemType": "PLUGINS", - "description": "Import plugins", - "cwd": null, - "details": { - "plugins": [{ - "marketplaceName": "acme-tools", - "pluginNames": ["formatter"] - }] - } - }] - })), - ) - .await?; - - let response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - let response: ExternalAgentConfigImportResponse = to_response(response)?; - assert_eq!(response, ExternalAgentConfigImportResponse {}); - let notification = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_notification_message("externalAgentConfig/import/completed"), - ) - .await??; - assert_eq!(notification.method, "externalAgentConfig/import/completed"); - - Ok(()) -} diff --git a/vendor/codex/codex-rs/app-server/tests/suite/v2/mod.rs b/vendor/codex/codex-rs/app-server/tests/suite/v2/mod.rs index 572df2c4..73ebbdff 100644 --- a/vendor/codex/codex-rs/app-server/tests/suite/v2/mod.rs +++ b/vendor/codex/codex-rs/app-server/tests/suite/v2/mod.rs @@ -13,7 +13,6 @@ mod device_key; mod dynamic_tools; mod experimental_api; mod experimental_feature_list; -mod external_agent_config; mod fs; mod initialize; mod mcp_resource;