diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index 21d3512e..72a6e8da 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -819,6 +819,15 @@ served app/plugin suggestion bookkeeping. The remaining plugin code is now a public Codex product library/CLI surface, not a live session organ; judge it as the next removable husk, not as keeper spine. +That husk has now been cut from `codex-core`. The root core crate no longer +exports `plugins`, no longer depends on `codex-core-plugins` or `codex-plugin`, +and the core plugin manager / marketplace add-remove-sync modules and tests +were deleted. CLI marketplace commands are disabled compatibility shells; MCP +CLI construction no longer creates plugin managers; ChatGPT connector listing +no longer merges plugin-provided apps; TUI plugin mentions no longer scan core +plugins. Remaining `codex-plugin` references live in other Codex product crates +or prompt/snapshot fixtures, not in the core runtime spine. + The Phase 6 freshness slice is landed. It exposes read-only `thread/epiphany/freshness` from live retrieval summaries plus graph frontier/churn state and, for loaded threads, watcher-backed invalidation diff --git a/state/ledgers.msgpack b/state/ledgers.msgpack index 5c06fb44..0ccc8ed6 100644 Binary files a/state/ledgers.msgpack and b/state/ledgers.msgpack differ diff --git a/state/map.yaml b/state/map.yaml index 1ff2884a..e938e390 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -287,6 +287,11 @@ current_status: discoverable-plugin scan were deleted, MCP startup/refresh uses empty plugin provenance, session/thread state no longer carries `PluginsManager`, and the explicit connector-selection cache was removed because it only served - app/plugin suggestion bookkeeping. The remaining plugin module is now a - public Codex product/CLI husk to judge next, not live session machinery. + app/plugin suggestion bookkeeping. The core plugin husk was then deleted: + `codex-core` no longer exports `plugins` or depends on `codex-core-plugins` + / `codex-plugin`, the core plugin manager and marketplace add/remove/sync + modules/tests are gone, CLI marketplace commands are disabled compatibility + shells, MCP CLI setup no longer creates plugin managers, ChatGPT connector + listing no longer merges plugin-provided apps, and TUI plugin mentions no + longer scan core plugins. next_action: Continue starving coordinator/runtime execution and operator surfaces off app-server JSON-RPC and out of `codex_message_processor.rs`; keep the vestigial Codex organ narrowed to subscription auth/model transport. diff --git a/vendor/codex/codex-rs/Cargo.lock b/vendor/codex/codex-rs/Cargo.lock index 3f1c6c54..c267c6b1 100644 --- a/vendor/codex/codex-rs/Cargo.lock +++ b/vendor/codex/codex-rs/Cargo.lock @@ -2381,7 +2381,6 @@ dependencies = [ "codex-code-mode", "codex-config", "codex-connectors", - "codex-core-plugins", "codex-core-skills", "codex-exec-server", "codex-execpolicy", @@ -2397,7 +2396,6 @@ dependencies = [ "codex-models-manager", "codex-network-proxy", "codex-otel", - "codex-plugin", "codex-protocol", "codex-response-debug-context", "codex-rmcp-client", diff --git a/vendor/codex/codex-rs/app-server-client/src/lib.rs b/vendor/codex/codex-rs/app-server-client/src/lib.rs index 1c3de120..850b0fbb 100644 --- a/vendor/codex/codex-rs/app-server-client/src/lib.rs +++ b/vendor/codex/codex-rs/app-server-client/src/lib.rs @@ -97,10 +97,6 @@ pub mod legacy_core { pub use codex_core::personality_migration::*; } - pub mod plugins { - pub use codex_core::plugins::*; - } - pub mod review_format { pub use codex_core::review_format::*; } diff --git a/vendor/codex/codex-rs/chatgpt/src/connectors.rs b/vendor/codex/codex-rs/chatgpt/src/connectors.rs index 4c6f05a6..beeccbfe 100644 --- a/vendor/codex/codex-rs/chatgpt/src/connectors.rs +++ b/vendor/codex/codex-rs/chatgpt/src/connectors.rs @@ -18,8 +18,6 @@ pub use codex_core::connectors::list_accessible_connectors_from_mcp_tools_with_o pub use codex_core::connectors::list_accessible_connectors_from_mcp_tools_with_options_and_status; pub use codex_core::connectors::list_cached_accessible_connectors_from_mcp_tools; pub use codex_core::connectors::with_app_enabled_state; -use codex_core::plugins::AppConnectorId; -use codex_core::plugins::PluginsManager; use codex_login::AuthManager; use codex_login::CodexAuth; use codex_login::default_client::originator; @@ -75,13 +73,7 @@ pub async fn list_cached_all_connectors(config: &Config) -> Option> let token_data = get_chatgpt_token_data()?; let cache_key = all_connectors_cache_key(config, &token_data); let connectors = codex_connectors::cached_all_connectors(&cache_key)?; - let connectors = merge_plugin_connectors( - connectors, - plugin_apps_for_config(config) - .await - .into_iter() - .map(|connector_id| connector_id.0), - ); + let connectors = merge_plugin_connectors(connectors, plugin_apps_for_config(config).await); Some(filter_disallowed_connectors( connectors, originator().value.as_str(), @@ -115,13 +107,7 @@ pub async fn list_all_connectors_with_options( }, ) .await?; - let connectors = merge_plugin_connectors( - connectors, - plugin_apps_for_config(config) - .await - .into_iter() - .map(|connector_id| connector_id.0), - ); + let connectors = merge_plugin_connectors(connectors, plugin_apps_for_config(config).await); Ok(filter_disallowed_connectors( connectors, originator().value.as_str(), @@ -137,28 +123,20 @@ fn all_connectors_cache_key(config: &Config, token_data: &TokenData) -> AllConne ) } -async fn plugin_apps_for_config(config: &Config) -> Vec { - PluginsManager::new(config.codex_home.to_path_buf()) - .plugins_for_config(config) - .await - .effective_apps() +async fn plugin_apps_for_config(_config: &Config) -> Vec { + Vec::new() } pub fn connectors_for_plugin_apps( connectors: Vec, - plugin_apps: &[AppConnectorId], + plugin_apps: &[String], ) -> Vec { let plugin_app_ids = plugin_apps .iter() - .map(|connector_id| connector_id.0.as_str()) + .map(String::as_str) .collect::>(); - let connectors = merge_plugin_connectors( - connectors, - plugin_apps - .iter() - .map(|connector_id| connector_id.0.clone()), - ); + let connectors = merge_plugin_connectors(connectors, plugin_apps.iter().cloned()); filter_disallowed_connectors(connectors, originator().value.as_str()) .into_iter() .filter(|connector| plugin_app_ids.contains(connector.id.as_str())) @@ -190,7 +168,6 @@ pub fn merge_connectors_with_accessible( mod tests { use super::*; use codex_connectors::metadata::connector_install_url; - use codex_core::plugins::AppConnectorId; use pretty_assertions::assert_eq; fn app(id: &str) -> AppInfo { @@ -259,10 +236,7 @@ mod tests { fn connectors_for_plugin_apps_returns_only_requested_plugin_apps() { let connectors = connectors_for_plugin_apps( vec![app("alpha"), app("beta")], - &[ - AppConnectorId("alpha".to_string()), - AppConnectorId("gmail".to_string()), - ], + &["alpha".to_string(), "gmail".to_string()], ); assert_eq!( connectors, @@ -274,9 +248,7 @@ mod tests { fn connectors_for_plugin_apps_filters_disallowed_plugin_apps() { let connectors = connectors_for_plugin_apps( Vec::new(), - &[AppConnectorId( - "asdk_app_6938a94a61d881918ef32cb999ff937c".to_string(), - )], + &["asdk_app_6938a94a61d881918ef32cb999ff937c".to_string()], ); assert_eq!(connectors, Vec::::new()); } diff --git a/vendor/codex/codex-rs/cli/src/marketplace_cmd.rs b/vendor/codex/codex-rs/cli/src/marketplace_cmd.rs index a29f9ba7..c2b943ae 100644 --- a/vendor/codex/codex-rs/cli/src/marketplace_cmd.rs +++ b/vendor/codex/codex-rs/cli/src/marketplace_cmd.rs @@ -1,15 +1,6 @@ -use anyhow::Context; use anyhow::Result; use anyhow::bail; use clap::Parser; -use codex_core::config::Config; -use codex_core::config::find_codex_home; -use codex_core::plugins::MarketplaceAddRequest; -use codex_core::plugins::MarketplaceRemoveRequest; -use codex_core::plugins::PluginMarketplaceUpgradeOutcome; -use codex_core::plugins::PluginsManager; -use codex_core::plugins::add_marketplace; -use codex_core::plugins::remove_marketplace; use codex_utils_cli::CliConfigOverrides; #[derive(Debug, Parser)] @@ -23,218 +14,22 @@ pub struct MarketplaceCli { #[derive(Debug, clap::Subcommand)] enum MarketplaceSubcommand { - Add(AddMarketplaceArgs), - Upgrade(UpgradeMarketplaceArgs), - Remove(RemoveMarketplaceArgs), + Add(DisabledMarketplaceArgs), + Upgrade(DisabledMarketplaceArgs), + Remove(DisabledMarketplaceArgs), } #[derive(Debug, Parser)] -struct AddMarketplaceArgs { - /// Marketplace source. Supports owner/repo[@ref], HTTP(S) Git URLs, SSH URLs, - /// or local marketplace root directories. - source: String, - - #[arg(long = "ref", value_name = "REF")] - ref_name: Option, - - #[arg( - long = "sparse", - value_name = "PATH", - action = clap::ArgAction::Append - )] - sparse_paths: Vec, -} - -#[derive(Debug, Parser)] -struct UpgradeMarketplaceArgs { - marketplace_name: Option, -} - -#[derive(Debug, Parser)] -struct RemoveMarketplaceArgs { - /// Configured marketplace name to remove. - marketplace_name: String, +struct DisabledMarketplaceArgs { + #[arg(trailing_var_arg = true, allow_hyphen_values = true)] + _args: Vec, } impl MarketplaceCli { pub async fn run(self) -> Result<()> { - let MarketplaceCli { - config_overrides, - subcommand, - } = self; - - let overrides = config_overrides - .parse_overrides() - .map_err(anyhow::Error::msg)?; - - match subcommand { - MarketplaceSubcommand::Add(args) => run_add(args).await?, - MarketplaceSubcommand::Upgrade(args) => run_upgrade(overrides, args).await?, - MarketplaceSubcommand::Remove(args) => run_remove(args).await?, - } - - Ok(()) - } -} - -async fn run_add(args: AddMarketplaceArgs) -> Result<()> { - let AddMarketplaceArgs { - source, - ref_name, - sparse_paths, - } = args; - - let codex_home = find_codex_home().context("failed to resolve CODEX_HOME")?; - let outcome = add_marketplace( - codex_home.to_path_buf(), - MarketplaceAddRequest { - source, - ref_name, - sparse_paths, - }, - ) - .await?; - - if outcome.already_added { - println!( - "Marketplace `{}` is already added from {}.", - outcome.marketplace_name, outcome.source_display - ); - } else { - println!( - "Added marketplace `{}` from {}.", - outcome.marketplace_name, outcome.source_display - ); - } - println!( - "Installed marketplace root: {}", - outcome.installed_root.as_path().display() - ); - - Ok(()) -} - -async fn run_upgrade( - overrides: Vec<(String, toml::Value)>, - args: UpgradeMarketplaceArgs, -) -> Result<()> { - let UpgradeMarketplaceArgs { marketplace_name } = args; - let config = Config::load_with_cli_overrides(overrides) - .await - .context("failed to load configuration")?; - let codex_home = find_codex_home().context("failed to resolve CODEX_HOME")?; - let manager = PluginsManager::new(codex_home.to_path_buf()); - let outcome = manager - .upgrade_configured_marketplaces_for_config(&config, marketplace_name.as_deref()) - .map_err(anyhow::Error::msg)?; - print_upgrade_outcome(&outcome, marketplace_name.as_deref()) -} - -async fn run_remove(args: RemoveMarketplaceArgs) -> Result<()> { - let RemoveMarketplaceArgs { marketplace_name } = args; - let codex_home = find_codex_home().context("failed to resolve CODEX_HOME")?; - let outcome = remove_marketplace( - codex_home.to_path_buf(), - MarketplaceRemoveRequest { marketplace_name }, - ) - .await?; - - println!("Removed marketplace `{}`.", outcome.marketplace_name); - if let Some(installed_root) = outcome.removed_installed_root { - println!( - "Removed installed marketplace root: {}", - installed_root.as_path().display() - ); - } - - Ok(()) -} - -fn print_upgrade_outcome( - outcome: &PluginMarketplaceUpgradeOutcome, - marketplace_name: Option<&str>, -) -> Result<()> { - for error in &outcome.errors { - eprintln!( - "Failed to upgrade marketplace `{}`: {}", - error.marketplace_name, error.message - ); - } - if !outcome.all_succeeded() { - bail!("{} upgrade failure(s) occurred.", outcome.errors.len()); - } - - let selection_label = marketplace_name.unwrap_or("all configured Git marketplaces"); - if outcome.selected_marketplaces.is_empty() { - println!("No configured Git marketplaces to upgrade."); - } else if outcome.upgraded_roots.is_empty() { - if marketplace_name.is_some() { - println!("Marketplace `{selection_label}` is already up to date."); - } else { - println!("All configured Git marketplaces are already up to date."); - } - } else if marketplace_name.is_some() { - println!("Upgraded marketplace `{selection_label}` to the latest configured revision."); - for root in &outcome.upgraded_roots { - println!("Installed marketplace root: {}", root.display()); - } - } else { - println!("Upgraded {} marketplace(s).", outcome.upgraded_roots.len()); - for root in &outcome.upgraded_roots { - println!("Installed marketplace root: {}", root.display()); - } - } - - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - use pretty_assertions::assert_eq; - - #[test] - fn sparse_paths_parse_before_or_after_source() { - let sparse_before_source = - AddMarketplaceArgs::try_parse_from(["add", "--sparse", "plugins/foo", "owner/repo"]) - .unwrap(); - assert_eq!(sparse_before_source.source, "owner/repo"); - assert_eq!(sparse_before_source.sparse_paths, vec!["plugins/foo"]); - - let sparse_after_source = - AddMarketplaceArgs::try_parse_from(["add", "owner/repo", "--sparse", "plugins/foo"]) - .unwrap(); - assert_eq!(sparse_after_source.source, "owner/repo"); - assert_eq!(sparse_after_source.sparse_paths, vec!["plugins/foo"]); - - let repeated_sparse = AddMarketplaceArgs::try_parse_from([ - "add", - "--sparse", - "plugins/foo", - "--sparse", - "skills/bar", - "owner/repo", - ]) - .unwrap(); - assert_eq!(repeated_sparse.source, "owner/repo"); - assert_eq!( - repeated_sparse.sparse_paths, - vec!["plugins/foo", "skills/bar"] - ); - } - - #[test] - fn upgrade_subcommand_parses_optional_marketplace_name() { - let upgrade_all = UpgradeMarketplaceArgs::try_parse_from(["upgrade"]).unwrap(); - assert_eq!(upgrade_all.marketplace_name, None); - - let upgrade_one = UpgradeMarketplaceArgs::try_parse_from(["upgrade", "debug"]).unwrap(); - assert_eq!(upgrade_one.marketplace_name.as_deref(), Some("debug")); - } - - #[test] - fn remove_subcommand_parses_marketplace_name() { - let remove = RemoveMarketplaceArgs::try_parse_from(["remove", "debug"]).unwrap(); - assert_eq!(remove.marketplace_name, "debug"); + let _ = self; + bail!( + "Codex plugin marketplace commands are disabled in Epiphany; the Codex organ is limited to OpenAI auth and model routing." + ) } } diff --git a/vendor/codex/codex-rs/cli/src/mcp_cmd.rs b/vendor/codex/codex-rs/cli/src/mcp_cmd.rs index d413f72d..03d9a384 100644 --- a/vendor/codex/codex-rs/cli/src/mcp_cmd.rs +++ b/vendor/codex/codex-rs/cli/src/mcp_cmd.rs @@ -1,5 +1,4 @@ use std::collections::HashMap; -use std::sync::Arc; use anyhow::Context; use anyhow::Result; @@ -14,7 +13,6 @@ use codex_core::config::Config; use codex_core::config::edit::ConfigEditsBuilder; use codex_core::config::find_codex_home; use codex_core::config::load_global_mcp_servers; -use codex_core::plugins::PluginsManager; use codex_mcp::McpOAuthLoginSupport; use codex_mcp::ResolvedMcpOAuthScopes; use codex_mcp::compute_auth_statuses; @@ -394,9 +392,7 @@ async fn run_login(config_overrides: &CliConfigOverrides, login_args: LoginArgs) let config = Config::load_with_cli_overrides(overrides) .await .context("failed to load configuration")?; - let mcp_manager = McpManager::new(Arc::new(PluginsManager::new( - config.codex_home.to_path_buf(), - ))); + let mcp_manager = McpManager::new(); let mcp_servers = mcp_manager.effective_servers(&config, /*auth*/ None).await; let LoginArgs { name, scopes } = login_args; @@ -447,9 +443,7 @@ async fn run_logout(config_overrides: &CliConfigOverrides, logout_args: LogoutAr let config = Config::load_with_cli_overrides(overrides) .await .context("failed to load configuration")?; - let mcp_manager = McpManager::new(Arc::new(PluginsManager::new( - config.codex_home.to_path_buf(), - ))); + let mcp_manager = McpManager::new(); let mcp_servers = mcp_manager.effective_servers(&config, /*auth*/ None).await; let LogoutArgs { name } = logout_args; @@ -479,9 +473,7 @@ async fn run_list(config_overrides: &CliConfigOverrides, list_args: ListArgs) -> let config = Config::load_with_cli_overrides(overrides) .await .context("failed to load configuration")?; - let mcp_manager = McpManager::new(Arc::new(PluginsManager::new( - config.codex_home.to_path_buf(), - ))); + let mcp_manager = McpManager::new(); let mcp_servers = mcp_manager.effective_servers(&config, /*auth*/ None).await; let mut entries: Vec<_> = mcp_servers.iter().collect(); @@ -730,9 +722,7 @@ async fn run_get(config_overrides: &CliConfigOverrides, get_args: GetArgs) -> Re let config = Config::load_with_cli_overrides(overrides) .await .context("failed to load configuration")?; - let mcp_manager = McpManager::new(Arc::new(PluginsManager::new( - config.codex_home.to_path_buf(), - ))); + let mcp_manager = McpManager::new(); let mcp_servers = mcp_manager.effective_servers(&config, /*auth*/ None).await; let Some(server) = mcp_servers.get(&get_args.name) else { diff --git a/vendor/codex/codex-rs/core/Cargo.toml b/vendor/codex/codex-rs/core/Cargo.toml index ddf41737..f9cbfff0 100644 --- a/vendor/codex/codex-rs/core/Cargo.toml +++ b/vendor/codex/codex-rs/core/Cargo.toml @@ -33,7 +33,6 @@ codex-async-utils = { workspace = true } codex-code-mode = { workspace = true } codex-connectors = { workspace = true } codex-config = { workspace = true } -codex-core-plugins = { workspace = true } codex-core-skills = { workspace = true } codex-exec-server = { workspace = true } codex-features = { workspace = true } @@ -49,7 +48,6 @@ codex-git-utils = { workspace = true } codex-hooks = { workspace = true } codex-network-proxy = { workspace = true } codex-otel = { workspace = true } -codex-plugin = { workspace = true } codex-model-provider = { workspace = true } codex-protocol = { workspace = true } codex-response-debug-context = { workspace = true } diff --git a/vendor/codex/codex-rs/core/src/lib.rs b/vendor/codex/codex-rs/core/src/lib.rs index 00d02305..584c3223 100644 --- a/vendor/codex/codex-rs/core/src/lib.rs +++ b/vendor/codex/codex-rs/core/src/lib.rs @@ -88,7 +88,6 @@ pub use message_history::history_metadata as message_history_metadata; pub use message_history::lookup as lookup_message_history_entry; pub use utils::path_utils; pub mod personality_migration; -pub mod plugins; #[doc(hidden)] pub(crate) mod prompt_debug; #[doc(hidden)] @@ -100,7 +99,6 @@ mod session_startup_prewarm; mod shell_detect; pub mod skills; pub(crate) use skills::SkillLoadOutcome; -pub(crate) use skills::SkillMetadata; pub(crate) use skills::SkillsManager; pub(crate) use skills::manager; mod skills_watcher; diff --git a/vendor/codex/codex-rs/core/src/plugins/installed_marketplaces.rs b/vendor/codex/codex-rs/core/src/plugins/installed_marketplaces.rs deleted file mode 100644 index a6f80139..00000000 --- a/vendor/codex/codex-rs/core/src/plugins/installed_marketplaces.rs +++ /dev/null @@ -1,75 +0,0 @@ -use crate::config::Config; -use codex_core_plugins::marketplace::find_marketplace_manifest_path; -use codex_utils_absolute_path::AbsolutePathBuf; -use std::path::Path; -use std::path::PathBuf; -use tracing::warn; - -use super::validate_plugin_segment; - -pub const INSTALLED_MARKETPLACES_DIR: &str = ".tmp/marketplaces"; - -pub fn marketplace_install_root(codex_home: &Path) -> PathBuf { - codex_home.join(INSTALLED_MARKETPLACES_DIR) -} - -pub(crate) fn installed_marketplace_roots_from_config( - config: &Config, - codex_home: &Path, -) -> Vec { - let Some(user_layer) = config.config_layer_stack.get_user_layer() else { - return Vec::new(); - }; - let Some(marketplaces_value) = user_layer.config.get("marketplaces") else { - return Vec::new(); - }; - let Some(marketplaces) = marketplaces_value.as_table() else { - warn!("invalid marketplaces config: expected table"); - return Vec::new(); - }; - let default_install_root = marketplace_install_root(codex_home); - let mut roots = marketplaces - .iter() - .filter_map(|(marketplace_name, marketplace)| { - if !marketplace.is_table() { - warn!( - marketplace_name, - "ignoring invalid configured marketplace entry" - ); - return None; - } - if let Err(err) = validate_plugin_segment(marketplace_name, "marketplace name") { - warn!( - marketplace_name, - error = %err, - "ignoring invalid configured marketplace name" - ); - return None; - } - let path = resolve_configured_marketplace_root( - marketplace_name, - marketplace, - &default_install_root, - )?; - find_marketplace_manifest_path(&path).map(|_| path) - }) - .filter_map(|path| AbsolutePathBuf::try_from(path).ok()) - .collect::>(); - roots.sort_unstable_by(|left, right| left.as_path().cmp(right.as_path())); - roots -} - -pub(crate) fn resolve_configured_marketplace_root( - marketplace_name: &str, - marketplace: &toml::Value, - default_install_root: &Path, -) -> Option { - match marketplace.get("source_type").and_then(toml::Value::as_str) { - Some("local") => marketplace - .get("source") - .and_then(toml::Value::as_str) - .filter(|source| !source.is_empty()) - .map(PathBuf::from), - _ => Some(default_install_root.join(marketplace_name)), - } -} diff --git a/vendor/codex/codex-rs/core/src/plugins/manager.rs b/vendor/codex/codex-rs/core/src/plugins/manager.rs deleted file mode 100644 index 7d9b426b..00000000 --- a/vendor/codex/codex-rs/core/src/plugins/manager.rs +++ /dev/null @@ -1,1605 +0,0 @@ -use super::PluginLoadOutcome; -use super::curated_plugins_repo_path; -use super::installed_marketplaces::installed_marketplace_roots_from_config; -use super::read_curated_plugins_sha; -use super::startup_sync::start_startup_remote_plugin_sync_once; -use super::sync_openai_plugins_repo; -use crate::SkillMetadata; -use crate::config::Config; -use crate::config::edit::ConfigEdit; -use crate::config::edit::ConfigEditsBuilder; -use crate::config_loader::ConfigLayerStack; -use codex_analytics::AnalyticsEventsClient; -use codex_config::types::PluginConfig; -use codex_core_plugins::loader::configured_curated_plugin_ids_from_codex_home; -use codex_core_plugins::loader::installed_plugin_telemetry_metadata; -use codex_core_plugins::loader::load_plugin_apps; -use codex_core_plugins::loader::load_plugin_mcp_servers; -use codex_core_plugins::loader::load_plugin_skills; -use codex_core_plugins::loader::load_plugins_from_layer_stack; -use codex_core_plugins::loader::log_plugin_load_errors; -use codex_core_plugins::loader::materialize_marketplace_plugin_source; -use codex_core_plugins::loader::plugin_telemetry_metadata_from_root; -use codex_core_plugins::loader::refresh_curated_plugin_cache; -use codex_core_plugins::loader::refresh_non_curated_plugin_cache; -use codex_core_plugins::loader::refresh_non_curated_plugin_cache_force_reinstall; -use codex_core_plugins::manifest::PluginManifestInterface; -use codex_core_plugins::manifest::load_plugin_manifest; -use codex_core_plugins::marketplace::MarketplaceError; -use codex_core_plugins::marketplace::MarketplaceInterface; -use codex_core_plugins::marketplace::MarketplaceListError; -use codex_core_plugins::marketplace::MarketplacePluginAuthPolicy; -use codex_core_plugins::marketplace::MarketplacePluginPolicy; -use codex_core_plugins::marketplace::MarketplacePluginSource; -use codex_core_plugins::marketplace::ResolvedMarketplacePlugin; -use codex_core_plugins::marketplace::find_installable_marketplace_plugin; -use codex_core_plugins::marketplace::find_marketplace_plugin; -use codex_core_plugins::marketplace::list_marketplaces; -use codex_core_plugins::marketplace::load_marketplace; -use codex_core_plugins::marketplace::plugin_interface_with_marketplace_category; -use codex_core_plugins::marketplace_upgrade::ConfiguredMarketplaceUpgradeError; -use codex_core_plugins::marketplace_upgrade::ConfiguredMarketplaceUpgradeOutcome; -use codex_core_plugins::marketplace_upgrade::configured_git_marketplace_names; -use codex_core_plugins::marketplace_upgrade::upgrade_configured_git_marketplaces; -use codex_core_plugins::remote::RemotePluginServiceConfig; -use codex_core_plugins::remote_legacy::RemotePluginFetchError; -use codex_core_plugins::remote_legacy::RemotePluginMutationError; -use codex_core_plugins::store::PluginInstallResult as StorePluginInstallResult; -use codex_core_plugins::store::PluginStore; -use codex_core_plugins::store::PluginStoreError; -use codex_features::Feature; -use codex_login::AuthManager; -use codex_login::CodexAuth; -use codex_plugin::AppConnectorId; -use codex_plugin::PluginCapabilitySummary; -use codex_plugin::PluginId; -use codex_plugin::PluginIdError; -use codex_plugin::prompt_safe_plugin_description; -use codex_protocol::protocol::Product; -use codex_utils_absolute_path::AbsolutePathBuf; -use std::collections::HashMap; -use std::collections::HashSet; -use std::path::PathBuf; -use std::sync::Arc; -use std::sync::RwLock; -use std::sync::atomic::AtomicBool; -use std::sync::atomic::Ordering; -use std::time::Instant; -use tokio::sync::Semaphore; -use toml_edit::value; -use tracing::info; -use tracing::warn; - -pub const OPENAI_CURATED_MARKETPLACE_NAME: &str = "openai-curated"; -pub const OPENAI_BUNDLED_MARKETPLACE_NAME: &str = "openai-bundled"; -static CURATED_REPO_SYNC_STARTED: AtomicBool = AtomicBool::new(false); -const FEATURED_PLUGIN_IDS_CACHE_TTL: std::time::Duration = - std::time::Duration::from_secs(60 * 60 * 3); - -#[derive(Clone, PartialEq, Eq)] -struct FeaturedPluginIdsCacheKey { - chatgpt_base_url: String, - account_id: Option, - chatgpt_user_id: Option, - is_workspace_account: bool, -} - -#[derive(Clone)] -struct CachedFeaturedPluginIds { - key: FeaturedPluginIdsCacheKey, - expires_at: Instant, - featured_plugin_ids: Vec, -} - -#[derive(Clone, PartialEq, Eq)] -struct NonCuratedCacheRefreshRequest { - roots: Vec, - mode: NonCuratedCacheRefreshMode, -} - -#[derive(Clone, Copy, PartialEq, Eq)] -enum NonCuratedCacheRefreshMode { - IfVersionChanged, - ForceReinstall, -} - -#[derive(Default)] -struct NonCuratedCacheRefreshState { - requested: Option, - last_refreshed: Option, - in_flight: bool, -} - -#[derive(Default)] -struct ConfiguredMarketplaceUpgradeState { - in_flight: bool, -} - -fn remote_plugin_service_config(config: &Config) -> RemotePluginServiceConfig { - RemotePluginServiceConfig { - chatgpt_base_url: config.chatgpt_base_url.clone(), - } -} - -fn featured_plugin_ids_cache_key( - config: &Config, - auth: Option<&CodexAuth>, -) -> FeaturedPluginIdsCacheKey { - let token_data = auth.and_then(|auth| auth.get_token_data().ok()); - let account_id = token_data - .as_ref() - .and_then(|token_data| token_data.account_id.clone()); - let chatgpt_user_id = token_data - .as_ref() - .and_then(|token_data| token_data.id_token.chatgpt_user_id.clone()); - let is_workspace_account = token_data - .as_ref() - .is_some_and(|token_data| token_data.id_token.is_workspace_account()); - FeaturedPluginIdsCacheKey { - chatgpt_base_url: config.chatgpt_base_url.clone(), - account_id, - chatgpt_user_id, - is_workspace_account, - } -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct PluginInstallRequest { - pub plugin_name: String, - pub marketplace_path: AbsolutePathBuf, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct PluginReadRequest { - pub plugin_name: String, - pub marketplace_path: AbsolutePathBuf, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct PluginInstallOutcome { - pub plugin_id: PluginId, - pub plugin_version: String, - pub installed_path: AbsolutePathBuf, - pub auth_policy: MarketplacePluginAuthPolicy, -} - -#[derive(Debug, Clone, PartialEq)] -pub struct PluginReadOutcome { - pub marketplace_name: String, - pub marketplace_path: Option, - pub plugin: PluginDetail, -} - -#[derive(Debug, Clone, PartialEq)] -pub struct PluginDetail { - pub id: String, - pub name: String, - pub description: Option, - pub source: MarketplacePluginSource, - pub policy: MarketplacePluginPolicy, - pub interface: Option, - pub installed: bool, - pub enabled: bool, - pub skills: Vec, - pub disabled_skill_paths: HashSet, - pub apps: Vec, - pub mcp_server_names: Vec, - pub details_unavailable_reason: Option, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum PluginDetailsUnavailableReason { - InstallRequiredForRemoteSource, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct ConfiguredMarketplace { - pub name: String, - pub path: AbsolutePathBuf, - pub interface: Option, - pub plugins: Vec, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct ConfiguredMarketplacePlugin { - pub id: String, - pub name: String, - pub source: MarketplacePluginSource, - pub policy: MarketplacePluginPolicy, - pub interface: Option, - pub installed: bool, - pub enabled: bool, -} - -#[derive(Debug, Clone, Default, PartialEq, Eq)] -pub struct ConfiguredMarketplaceListOutcome { - pub marketplaces: Vec, - pub errors: Vec, -} - -impl From for PluginCapabilitySummary { - fn from(value: PluginDetail) -> Self { - let has_skills = value.skills.iter().any(|skill| { - !value - .disabled_skill_paths - .contains(&skill.path_to_skills_md) - }); - Self { - config_name: value.id, - display_name: value.name, - description: prompt_safe_plugin_description(value.description.as_deref()), - has_skills, - mcp_server_names: value.mcp_server_names, - app_connector_ids: value.apps, - } - } -} - -#[derive(Debug, Clone, Default, PartialEq, Eq)] -pub struct RemotePluginSyncResult { - /// Plugin ids newly installed into the local plugin cache. - pub installed_plugin_ids: Vec, - /// Plugin ids whose local config was changed to enabled. - pub enabled_plugin_ids: Vec, - /// Plugin ids whose local config was changed to disabled. - /// This is not populated by `sync_plugins_from_remote`. - pub disabled_plugin_ids: Vec, - /// Plugin ids removed from local cache or plugin config. - pub uninstalled_plugin_ids: Vec, -} - -#[derive(Debug, thiserror::Error)] -pub enum PluginRemoteSyncError { - #[error("chatgpt authentication required to sync remote plugins")] - AuthRequired, - - #[error( - "chatgpt authentication required to sync remote plugins; api key auth is not supported" - )] - UnsupportedAuthMode, - - #[error("failed to read auth token for remote plugin sync: {0}")] - AuthToken(#[source] std::io::Error), - - #[error("failed to send remote plugin sync request to {url}: {source}")] - Request { - url: String, - #[source] - source: reqwest::Error, - }, - - #[error("remote plugin sync request to {url} failed with status {status}: {body}")] - UnexpectedStatus { - url: String, - status: reqwest::StatusCode, - body: String, - }, - - #[error("failed to parse remote plugin sync response from {url}: {source}")] - Decode { - url: String, - #[source] - source: serde_json::Error, - }, - - #[error("local curated marketplace is not available")] - LocalMarketplaceNotFound, - - #[error("remote marketplace `{marketplace_name}` is not available locally")] - UnknownRemoteMarketplace { marketplace_name: String }, - - #[error("duplicate remote plugin `{plugin_name}` in sync response")] - DuplicateRemotePlugin { plugin_name: String }, - - #[error( - "remote plugin `{plugin_name}` was not found in local marketplace `{marketplace_name}`" - )] - UnknownRemotePlugin { - plugin_name: String, - marketplace_name: String, - }, - - #[error("{0}")] - InvalidPluginId(#[from] PluginIdError), - - #[error("{0}")] - Marketplace(#[from] MarketplaceError), - - #[error("{0}")] - Store(#[from] PluginStoreError), - - #[error("{0}")] - Config(#[from] anyhow::Error), - - #[error("failed to join remote plugin sync task: {0}")] - Join(#[from] tokio::task::JoinError), -} - -impl PluginRemoteSyncError { - fn join(source: tokio::task::JoinError) -> Self { - Self::Join(source) - } -} - -impl From for PluginRemoteSyncError { - fn from(value: RemotePluginFetchError) -> Self { - match value { - RemotePluginFetchError::AuthRequired => Self::AuthRequired, - RemotePluginFetchError::UnsupportedAuthMode => Self::UnsupportedAuthMode, - RemotePluginFetchError::AuthToken(source) => Self::AuthToken(source), - RemotePluginFetchError::Request { url, source } => Self::Request { url, source }, - RemotePluginFetchError::UnexpectedStatus { url, status, body } => { - Self::UnexpectedStatus { url, status, body } - } - RemotePluginFetchError::Decode { url, source } => Self::Decode { url, source }, - } - } -} - -pub struct PluginsManager { - codex_home: PathBuf, - store: PluginStore, - featured_plugin_ids_cache: RwLock>, - configured_marketplace_upgrade_state: RwLock, - non_curated_cache_refresh_state: RwLock, - cached_enabled_outcome: RwLock>, - remote_sync_lock: Semaphore, - restriction_product: Option, - analytics_events_client: RwLock>, -} - -impl PluginsManager { - pub fn new(codex_home: PathBuf) -> Self { - Self::new_with_restriction_product(codex_home, Some(Product::Codex)) - } - - pub fn new_with_restriction_product( - codex_home: PathBuf, - restriction_product: Option, - ) -> Self { - // Product restrictions are enforced at marketplace admission time for a given CODEX_HOME: - // listing, install, and curated refresh all consult this restriction context before new - // plugins enter local config or cache. After admission, runtime plugin loading trusts the - // contents of that CODEX_HOME and does not re-filter configured plugins by product, so - // already-admitted plugins may continue exposing MCP servers/tools from shared local state. - // - // This assumes a single CODEX_HOME is only used by one product. - Self { - codex_home: codex_home.clone(), - store: PluginStore::new(codex_home), - featured_plugin_ids_cache: RwLock::new(None), - configured_marketplace_upgrade_state: RwLock::new( - ConfiguredMarketplaceUpgradeState::default(), - ), - non_curated_cache_refresh_state: RwLock::new(NonCuratedCacheRefreshState::default()), - cached_enabled_outcome: RwLock::new(None), - remote_sync_lock: Semaphore::new(/*permits*/ 1), - restriction_product, - analytics_events_client: RwLock::new(None), - } - } - - pub fn set_analytics_events_client(&self, analytics_events_client: AnalyticsEventsClient) { - let mut stored_client = match self.analytics_events_client.write() { - Ok(client_guard) => client_guard, - Err(err) => err.into_inner(), - }; - *stored_client = Some(analytics_events_client); - } - - fn restriction_product_matches(&self, products: Option<&[Product]>) -> bool { - match products { - None => true, - Some([]) => false, - Some(products) => self - .restriction_product - .is_some_and(|product| product.matches_product_restriction(products)), - } - } - - pub async fn plugins_for_config(&self, config: &Config) -> PluginLoadOutcome { - self.plugins_for_config_with_force_reload(config, /*force_reload*/ false) - .await - } - - pub(crate) async fn plugins_for_config_with_force_reload( - &self, - config: &Config, - force_reload: bool, - ) -> PluginLoadOutcome { - if !config.features.enabled(Feature::Plugins) { - return PluginLoadOutcome::default(); - } - - if !force_reload && let Some(outcome) = self.cached_enabled_outcome() { - return outcome; - } - - let outcome = load_plugins_from_layer_stack( - &config.config_layer_stack, - &self.store, - self.restriction_product, - ) - .await; - log_plugin_load_errors(&outcome); - let mut cache = match self.cached_enabled_outcome.write() { - Ok(cache) => cache, - Err(err) => err.into_inner(), - }; - *cache = Some(outcome.clone()); - outcome - } - - pub fn clear_cache(&self) { - let mut cached_enabled_outcome = match self.cached_enabled_outcome.write() { - Ok(cache) => cache, - Err(err) => err.into_inner(), - }; - let mut featured_plugin_ids_cache = match self.featured_plugin_ids_cache.write() { - Ok(cache) => cache, - Err(err) => err.into_inner(), - }; - *featured_plugin_ids_cache = None; - *cached_enabled_outcome = None; - } - - /// Resolve plugin skill roots for a config layer stack without touching the plugins cache. - pub async fn effective_skill_roots_for_layer_stack( - &self, - config_layer_stack: &ConfigLayerStack, - plugins_feature_enabled: bool, - ) -> Vec { - if !plugins_feature_enabled { - return Vec::new(); - } - load_plugins_from_layer_stack(config_layer_stack, &self.store, self.restriction_product) - .await - .effective_skill_roots() - } - - fn cached_enabled_outcome(&self) -> Option { - match self.cached_enabled_outcome.read() { - Ok(cache) => cache.clone(), - Err(err) => err.into_inner().clone(), - } - } - - fn cached_featured_plugin_ids( - &self, - cache_key: &FeaturedPluginIdsCacheKey, - ) -> Option> { - { - let cache = match self.featured_plugin_ids_cache.read() { - Ok(cache) => cache, - Err(err) => err.into_inner(), - }; - let now = Instant::now(); - if let Some(cached) = cache.as_ref() - && now < cached.expires_at - && cached.key == *cache_key - { - return Some(cached.featured_plugin_ids.clone()); - } - } - - let mut cache = match self.featured_plugin_ids_cache.write() { - Ok(cache) => cache, - Err(err) => err.into_inner(), - }; - let now = Instant::now(); - if cache - .as_ref() - .is_some_and(|cached| now >= cached.expires_at || cached.key != *cache_key) - { - *cache = None; - } - None - } - - fn write_featured_plugin_ids_cache( - &self, - cache_key: FeaturedPluginIdsCacheKey, - featured_plugin_ids: &[String], - ) { - let mut cache = match self.featured_plugin_ids_cache.write() { - Ok(cache) => cache, - Err(err) => err.into_inner(), - }; - *cache = Some(CachedFeaturedPluginIds { - key: cache_key, - expires_at: Instant::now() + FEATURED_PLUGIN_IDS_CACHE_TTL, - featured_plugin_ids: featured_plugin_ids.to_vec(), - }); - } - - pub async fn featured_plugin_ids_for_config( - &self, - config: &Config, - auth: Option<&CodexAuth>, - ) -> Result, RemotePluginFetchError> { - if !config.features.enabled(Feature::Plugins) { - return Ok(Vec::new()); - } - - let cache_key = featured_plugin_ids_cache_key(config, auth); - if let Some(featured_plugin_ids) = self.cached_featured_plugin_ids(&cache_key) { - return Ok(featured_plugin_ids); - } - let featured_plugin_ids = - codex_core_plugins::remote_legacy::fetch_remote_featured_plugin_ids( - &remote_plugin_service_config(config), - auth, - self.restriction_product, - ) - .await?; - self.write_featured_plugin_ids_cache(cache_key, &featured_plugin_ids); - Ok(featured_plugin_ids) - } - - pub async fn install_plugin( - &self, - request: PluginInstallRequest, - ) -> Result { - let resolved = find_installable_marketplace_plugin( - &request.marketplace_path, - &request.plugin_name, - self.restriction_product, - )?; - self.install_resolved_plugin(resolved).await - } - - pub async fn install_plugin_with_remote_sync( - &self, - config: &Config, - auth: Option<&CodexAuth>, - request: PluginInstallRequest, - ) -> Result { - let resolved = find_installable_marketplace_plugin( - &request.marketplace_path, - &request.plugin_name, - self.restriction_product, - )?; - let plugin_id = resolved.plugin_id.as_key(); - // This only forwards the backend mutation before the local install flow. - codex_core_plugins::remote_legacy::enable_remote_plugin( - &remote_plugin_service_config(config), - auth, - &plugin_id, - ) - .await - .map_err(PluginInstallError::from)?; - self.install_resolved_plugin(resolved).await - } - - async fn install_resolved_plugin( - &self, - resolved: ResolvedMarketplacePlugin, - ) -> Result { - let auth_policy = resolved.policy.authentication; - let plugin_version = - if resolved.plugin_id.marketplace_name == OPENAI_CURATED_MARKETPLACE_NAME { - Some( - read_curated_plugins_sha(self.codex_home.as_path()).ok_or_else(|| { - PluginStoreError::Invalid( - "local curated marketplace sha is not available".to_string(), - ) - })?, - ) - } else { - None - }; - let store = self.store.clone(); - let codex_home = self.codex_home.clone(); - let result: StorePluginInstallResult = tokio::task::spawn_blocking(move || { - let materialized = - materialize_marketplace_plugin_source(codex_home.as_path(), &resolved.source) - .map_err(PluginStoreError::Invalid)?; - let source_path = materialized.path; - if let Some(plugin_version) = plugin_version { - store.install_with_version(source_path, resolved.plugin_id, plugin_version) - } else { - store.install(source_path, resolved.plugin_id) - } - }) - .await - .map_err(PluginInstallError::join)??; - - ConfigEditsBuilder::new(&self.codex_home) - .with_edits([ConfigEdit::SetPath { - segments: vec![ - "plugins".to_string(), - result.plugin_id.as_key(), - "enabled".to_string(), - ], - value: value(true), - }]) - .apply() - .await - .map_err(PluginInstallError::from)?; - - let analytics_events_client = match self.analytics_events_client.read() { - Ok(client) => client.clone(), - Err(err) => err.into_inner().clone(), - }; - if let Some(analytics_events_client) = analytics_events_client { - analytics_events_client.track_plugin_installed( - plugin_telemetry_metadata_from_root(&result.plugin_id, &result.installed_path) - .await, - ); - } - - Ok(PluginInstallOutcome { - plugin_id: result.plugin_id, - plugin_version: result.plugin_version, - installed_path: result.installed_path, - auth_policy, - }) - } - - pub async fn uninstall_plugin(&self, plugin_id: String) -> Result<(), PluginUninstallError> { - let plugin_id = PluginId::parse(&plugin_id)?; - self.uninstall_plugin_id(plugin_id).await - } - - pub async fn uninstall_plugin_with_remote_sync( - &self, - config: &Config, - auth: Option<&CodexAuth>, - plugin_id: String, - ) -> Result<(), PluginUninstallError> { - // TODO: Remove this legacy remote-sync path once remote plugins have - // their own manager and installed-state API. - let plugin_id = PluginId::parse(&plugin_id)?; - let plugin_key = plugin_id.as_key(); - // This only forwards the backend mutation before the local uninstall flow. - codex_core_plugins::remote_legacy::uninstall_remote_plugin( - &remote_plugin_service_config(config), - auth, - &plugin_key, - ) - .await - .map_err(PluginUninstallError::from)?; - self.uninstall_plugin_id(plugin_id).await - } - - async fn uninstall_plugin_id(&self, plugin_id: PluginId) -> Result<(), PluginUninstallError> { - let plugin_telemetry = if self.store.active_plugin_root(&plugin_id).is_some() { - Some(installed_plugin_telemetry_metadata(self.codex_home.as_path(), &plugin_id).await) - } else { - None - }; - let store = self.store.clone(); - let plugin_id_for_store = plugin_id.clone(); - tokio::task::spawn_blocking(move || store.uninstall(&plugin_id_for_store)) - .await - .map_err(PluginUninstallError::join)??; - - ConfigEditsBuilder::new(&self.codex_home) - .with_edits([ConfigEdit::ClearPath { - segments: vec!["plugins".to_string(), plugin_id.as_key()], - }]) - .apply() - .await?; - - let analytics_events_client = match self.analytics_events_client.read() { - Ok(client) => client.clone(), - Err(err) => err.into_inner().clone(), - }; - if let Some(plugin_telemetry) = plugin_telemetry - && let Some(analytics_events_client) = analytics_events_client - { - analytics_events_client.track_plugin_uninstalled(plugin_telemetry); - } - - Ok(()) - } - - pub async fn sync_plugins_from_remote( - &self, - config: &Config, - auth: Option<&CodexAuth>, - additive_only: bool, - ) -> Result { - let _remote_sync_guard = self.remote_sync_lock.acquire().await.map_err(|_| { - PluginRemoteSyncError::Config(anyhow::anyhow!("remote plugin sync semaphore closed")) - })?; - - if !config.features.enabled(Feature::Plugins) { - return Ok(RemotePluginSyncResult::default()); - } - - info!("starting remote plugin sync"); - let remote_plugins = codex_core_plugins::remote_legacy::fetch_remote_plugin_status( - &remote_plugin_service_config(config), - auth, - ) - .await - .map_err(PluginRemoteSyncError::from)?; - let configured_plugins = configured_plugins_from_stack(&config.config_layer_stack); - let curated_marketplace_root = curated_plugins_repo_path(self.codex_home.as_path()); - let curated_marketplace_path = AbsolutePathBuf::try_from( - curated_marketplace_root.join(".agents/plugins/marketplace.json"), - ) - .map_err(|_| PluginRemoteSyncError::LocalMarketplaceNotFound)?; - let curated_marketplace = match load_marketplace(&curated_marketplace_path) { - Ok(marketplace) => marketplace, - Err(MarketplaceError::MarketplaceNotFound { .. }) => { - return Err(PluginRemoteSyncError::LocalMarketplaceNotFound); - } - Err(err) => return Err(err.into()), - }; - - let marketplace_name = curated_marketplace.name.clone(); - let curated_plugin_version = read_curated_plugins_sha(self.codex_home.as_path()) - .ok_or_else(|| { - PluginStoreError::Invalid( - "local curated marketplace sha is not available".to_string(), - ) - })?; - let mut local_plugins = Vec::<( - String, - PluginId, - AbsolutePathBuf, - Option, - Option, - bool, - )>::new(); - let mut local_plugin_names = HashSet::new(); - for plugin in curated_marketplace.plugins { - let plugin_name = plugin.name; - if !local_plugin_names.insert(plugin_name.clone()) { - warn!( - plugin = plugin_name, - marketplace = %marketplace_name, - "ignoring duplicate local plugin entry during remote sync" - ); - continue; - } - - let plugin_id = PluginId::new(plugin_name.clone(), marketplace_name.clone())?; - let plugin_key = plugin_id.as_key(); - let source_path = match plugin.source { - MarketplacePluginSource::Local { path } => path, - MarketplacePluginSource::Git { .. } => { - warn!( - plugin = plugin_name, - marketplace = %marketplace_name, - "skipping remote plugin source during remote sync" - ); - continue; - } - }; - let current_enabled = configured_plugins - .get(&plugin_key) - .map(|plugin| plugin.enabled); - let installed_version = self.store.active_plugin_version(&plugin_id); - let product_allowed = - self.restriction_product_matches(plugin.policy.products.as_deref()); - local_plugins.push(( - plugin_name, - plugin_id, - source_path, - current_enabled, - installed_version, - product_allowed, - )); - } - - let mut missing_remote_plugins = Vec::::new(); - let mut remote_installed_plugin_names = HashSet::::new(); - for plugin in remote_plugins { - if plugin.marketplace_name != marketplace_name { - return Err(PluginRemoteSyncError::UnknownRemoteMarketplace { - marketplace_name: plugin.marketplace_name, - }); - } - if !local_plugin_names.contains(&plugin.name) { - missing_remote_plugins.push(plugin.name); - continue; - } - // For now, sync treats remote `enabled = false` as uninstall rather than a distinct - // disabled state. - // TODO: Switch sync to `plugins/installed` so install and enable states stay distinct. - if !plugin.enabled { - continue; - } - if !remote_installed_plugin_names.insert(plugin.name.clone()) { - return Err(PluginRemoteSyncError::DuplicateRemotePlugin { - plugin_name: plugin.name, - }); - } - } - - let mut config_edits = Vec::new(); - let mut installs = Vec::new(); - let mut uninstalls = Vec::new(); - let mut result = RemotePluginSyncResult::default(); - let remote_plugin_count = remote_installed_plugin_names.len(); - let local_plugin_count = local_plugins.len(); - if !missing_remote_plugins.is_empty() { - let sample_missing_plugins = missing_remote_plugins - .iter() - .take(10) - .cloned() - .collect::>(); - warn!( - marketplace = %marketplace_name, - missing_remote_plugin_count = missing_remote_plugins.len(), - missing_remote_plugin_examples = ?sample_missing_plugins, - "ignoring remote plugins missing from local marketplace during sync" - ); - } - - for ( - plugin_name, - plugin_id, - source_path, - current_enabled, - installed_version, - product_allowed, - ) in local_plugins - { - let plugin_key = plugin_id.as_key(); - let is_installed = installed_version.is_some(); - if !product_allowed { - continue; - } - if remote_installed_plugin_names.contains(&plugin_name) { - if !is_installed { - installs.push(( - source_path, - plugin_id.clone(), - curated_plugin_version.clone(), - )); - } - if !is_installed { - result.installed_plugin_ids.push(plugin_key.clone()); - } - - if current_enabled != Some(true) { - result.enabled_plugin_ids.push(plugin_key.clone()); - config_edits.push(ConfigEdit::SetPath { - segments: vec!["plugins".to_string(), plugin_key, "enabled".to_string()], - value: value(true), - }); - } - } else if !additive_only { - if is_installed { - uninstalls.push(plugin_id); - } - if is_installed || current_enabled.is_some() { - result.uninstalled_plugin_ids.push(plugin_key.clone()); - } - if current_enabled.is_some() { - config_edits.push(ConfigEdit::ClearPath { - segments: vec!["plugins".to_string(), plugin_key], - }); - } - } - } - - let store = self.store.clone(); - let store_result = tokio::task::spawn_blocking(move || { - for (source_path, plugin_id, plugin_version) in installs { - store.install_with_version(source_path, plugin_id, plugin_version)?; - } - for plugin_id in uninstalls { - store.uninstall(&plugin_id)?; - } - Ok::<(), PluginStoreError>(()) - }) - .await - .map_err(PluginRemoteSyncError::join)?; - if let Err(err) = store_result { - self.clear_cache(); - return Err(err.into()); - } - - let config_result = if config_edits.is_empty() { - Ok(()) - } else { - ConfigEditsBuilder::new(&self.codex_home) - .with_edits(config_edits) - .apply() - .await - }; - self.clear_cache(); - config_result?; - - info!( - marketplace = %marketplace_name, - remote_plugin_count, - local_plugin_count, - installed_plugin_ids = ?result.installed_plugin_ids, - enabled_plugin_ids = ?result.enabled_plugin_ids, - disabled_plugin_ids = ?result.disabled_plugin_ids, - uninstalled_plugin_ids = ?result.uninstalled_plugin_ids, - "completed remote plugin sync" - ); - - Ok(result) - } - - pub fn list_marketplaces_for_config( - &self, - config: &Config, - additional_roots: &[AbsolutePathBuf], - ) -> Result { - if !config.features.enabled(Feature::Plugins) { - return Ok(ConfiguredMarketplaceListOutcome::default()); - } - - let (installed_plugins, enabled_plugins) = self.configured_plugin_states(config); - let marketplace_outcome = - list_marketplaces(&self.marketplace_roots(config, additional_roots))?; - let mut seen_plugin_keys = HashSet::new(); - let marketplaces = marketplace_outcome - .marketplaces - .into_iter() - .filter_map(|marketplace| { - let marketplace_name = marketplace.name.clone(); - let plugins = marketplace - .plugins - .into_iter() - .filter_map(|plugin| { - let plugin_key = format!("{}@{marketplace_name}", plugin.name); - if !seen_plugin_keys.insert(plugin_key.clone()) { - return None; - } - if !self.restriction_product_matches(plugin.policy.products.as_deref()) { - return None; - } - - Some(ConfiguredMarketplacePlugin { - // Enabled state is keyed by `@`, so duplicate - // plugin entries from duplicate marketplace files intentionally - // resolve to the first discovered source. - id: plugin_key.clone(), - installed: installed_plugins.contains(&plugin_key), - enabled: enabled_plugins.contains(&plugin_key), - name: plugin.name, - source: plugin.source, - policy: plugin.policy, - interface: plugin.interface, - }) - }) - .collect::>(); - - (!plugins.is_empty()).then_some(ConfiguredMarketplace { - name: marketplace.name, - path: marketplace.path, - interface: marketplace.interface, - plugins, - }) - }) - .collect(); - - Ok(ConfiguredMarketplaceListOutcome { - marketplaces, - errors: marketplace_outcome.errors, - }) - } - - pub async fn read_plugin_for_config( - &self, - config: &Config, - request: &PluginReadRequest, - ) -> Result { - if !config.features.enabled(Feature::Plugins) { - return Err(MarketplaceError::PluginsDisabled); - } - - let plugin = find_marketplace_plugin(&request.marketplace_path, &request.plugin_name)?; - if !self.restriction_product_matches(plugin.policy.products.as_deref()) { - return Err(MarketplaceError::PluginNotFound { - plugin_name: plugin.plugin_id.plugin_name, - marketplace_name: plugin.plugin_id.marketplace_name, - }); - } - - let marketplace_name = plugin.plugin_id.marketplace_name.clone(); - let plugin_key = plugin.plugin_id.as_key(); - let (installed_plugins, enabled_plugins) = self.configured_plugin_states(config); - let plugin = self - .read_plugin_detail_for_marketplace_plugin( - config, - &marketplace_name, - ConfiguredMarketplacePlugin { - id: plugin_key.clone(), - name: plugin.plugin_id.plugin_name, - source: plugin.source, - policy: plugin.policy, - interface: plugin.interface, - installed: installed_plugins.contains(&plugin_key), - enabled: enabled_plugins.contains(&plugin_key), - }, - ) - .await?; - - Ok(PluginReadOutcome { - marketplace_name, - marketplace_path: Some(request.marketplace_path.clone()), - plugin, - }) - } - - pub(crate) async fn read_plugin_detail_for_marketplace_plugin( - &self, - config: &Config, - marketplace_name: &str, - plugin: ConfiguredMarketplacePlugin, - ) -> Result { - if !self.restriction_product_matches(plugin.policy.products.as_deref()) { - return Err(MarketplaceError::PluginNotFound { - plugin_name: plugin.name, - marketplace_name: marketplace_name.to_string(), - }); - } - - let plugin_id = - PluginId::new(plugin.name.clone(), marketplace_name.to_string()).map_err(|err| { - match err { - PluginIdError::Invalid(message) => MarketplaceError::InvalidPlugin(message), - } - })?; - let plugin_key = plugin_id.as_key(); - if matches!(plugin.source, MarketplacePluginSource::Git { .. }) && !plugin.installed { - let description = remote_plugin_install_required_description(&plugin.source); - return Ok(PluginDetail { - id: plugin_key, - name: plugin.name, - description: Some(description), - source: plugin.source, - policy: plugin.policy, - interface: plugin.interface, - installed: plugin.installed, - enabled: plugin.enabled, - skills: Vec::new(), - disabled_skill_paths: HashSet::new(), - apps: Vec::new(), - mcp_server_names: Vec::new(), - details_unavailable_reason: Some( - PluginDetailsUnavailableReason::InstallRequiredForRemoteSource, - ), - }); - } - - let source_path = - if matches!(plugin.source, MarketplacePluginSource::Git { .. }) && plugin.installed { - self.store.active_plugin_root(&plugin_id).ok_or_else(|| { - MarketplaceError::InvalidPlugin(format!( - "installed plugin cache entry is missing for {plugin_key}" - )) - })? - } else { - let codex_home = self.codex_home.clone(); - let source = plugin.source.clone(); - let materialized = tokio::task::spawn_blocking(move || { - materialize_marketplace_plugin_source(codex_home.as_path(), &source) - }) - .await - .map_err(|err| { - MarketplaceError::InvalidPlugin(format!( - "failed to materialize plugin source: {err}" - )) - })? - .map_err(MarketplaceError::InvalidPlugin)?; - materialized.path.clone() - }; - if !source_path.as_path().is_dir() { - return Err(MarketplaceError::InvalidPlugin( - "path does not exist or is not a directory".to_string(), - )); - } - let manifest = load_plugin_manifest(source_path.as_path()).ok_or_else(|| { - MarketplaceError::InvalidPlugin("missing or invalid plugin.json".to_string()) - })?; - let description = manifest.description.clone(); - let marketplace_category = plugin - .interface - .as_ref() - .and_then(|interface| interface.category.clone()); - let interface = plugin_interface_with_marketplace_category( - manifest.interface.clone(), - marketplace_category, - ); - let resolved_skills = load_plugin_skills( - &source_path, - &manifest.paths, - self.restriction_product, - &codex_core_skills::config_rules::skill_config_rules_from_stack( - &config.config_layer_stack, - ), - ) - .await; - let apps = load_plugin_apps(source_path.as_path()).await; - let mut mcp_server_names = load_plugin_mcp_servers(source_path.as_path()) - .await - .into_keys() - .collect::>(); - mcp_server_names.sort_unstable(); - mcp_server_names.dedup(); - - Ok(PluginDetail { - id: plugin.id, - name: plugin.name, - description, - source: plugin.source, - policy: plugin.policy, - interface, - installed: plugin.installed, - enabled: plugin.enabled, - skills: resolved_skills.skills, - disabled_skill_paths: resolved_skills.disabled_skill_paths, - apps, - mcp_server_names, - details_unavailable_reason: None, - }) - } - - pub fn maybe_start_plugin_startup_tasks_for_config( - self: &Arc, - config: &Config, - auth_manager: Arc, - ) { - if config.features.enabled(Feature::Plugins) { - self.start_curated_repo_sync(); - let should_spawn_marketplace_auto_upgrade = { - let mut state = match self.configured_marketplace_upgrade_state.write() { - Ok(state) => state, - Err(err) => err.into_inner(), - }; - if state.in_flight { - false - } else { - state.in_flight = true; - true - } - }; - if should_spawn_marketplace_auto_upgrade { - let manager = Arc::clone(self); - let config = config.clone(); - if let Err(err) = std::thread::Builder::new() - .name("plugins-marketplace-auto-upgrade".to_string()) - .spawn(move || { - let outcome = manager.upgrade_configured_marketplaces_for_config( - &config, /*marketplace_name*/ None, - ); - match outcome { - Ok(outcome) => { - for error in outcome.errors { - warn!( - marketplace = error.marketplace_name, - error = %error.message, - "failed to auto-upgrade configured marketplace" - ); - } - } - Err(err) => { - warn!("failed to auto-upgrade configured marketplaces: {err}"); - } - } - - let mut state = match manager.configured_marketplace_upgrade_state.write() { - Ok(state) => state, - Err(err) => err.into_inner(), - }; - state.in_flight = false; - }) - { - let mut state = match self.configured_marketplace_upgrade_state.write() { - Ok(state) => state, - Err(err) => err.into_inner(), - }; - state.in_flight = false; - warn!("failed to start configured marketplace auto-upgrade task: {err}"); - } - } - start_startup_remote_plugin_sync_once( - Arc::clone(self), - self.codex_home.clone(), - config.clone(), - auth_manager.clone(), - ); - - let config = config.clone(); - let manager = Arc::clone(self); - tokio::spawn(async move { - let auth = auth_manager.auth().await; - if let Err(err) = manager - .featured_plugin_ids_for_config(&config, auth.as_ref()) - .await - { - warn!( - error = %err, - "failed to warm featured plugin ids cache" - ); - } - }); - } - } - - pub fn upgrade_configured_marketplaces_for_config( - &self, - config: &Config, - marketplace_name: Option<&str>, - ) -> Result { - if let Some(marketplace_name) = marketplace_name - && !configured_git_marketplace_names(&config.config_layer_stack) - .iter() - .any(|name| name == marketplace_name) - { - return Err(format!( - "marketplace `{marketplace_name}` is not configured as a Git marketplace" - )); - } - - let mut outcome = upgrade_configured_git_marketplaces( - self.codex_home.as_path(), - &config.config_layer_stack, - marketplace_name, - ); - if !outcome.upgraded_roots.is_empty() { - match refresh_non_curated_plugin_cache_force_reinstall( - self.codex_home.as_path(), - &outcome.upgraded_roots, - ) { - Ok(cache_refreshed) => { - if cache_refreshed { - self.clear_cache(); - } - } - Err(err) => { - self.clear_cache(); - outcome.errors.push(ConfiguredMarketplaceUpgradeError { - marketplace_name: marketplace_name - .unwrap_or("all configured marketplaces") - .to_string(), - message: format!( - "failed to refresh installed plugin cache after marketplace upgrade: {err}" - ), - }); - } - } - } - Ok(outcome) - } - - pub fn maybe_start_non_curated_plugin_cache_refresh( - self: &Arc, - roots: &[AbsolutePathBuf], - ) { - self.schedule_non_curated_plugin_cache_refresh( - roots, - NonCuratedCacheRefreshMode::IfVersionChanged, - ); - } - - fn schedule_non_curated_plugin_cache_refresh( - self: &Arc, - roots: &[AbsolutePathBuf], - mode: NonCuratedCacheRefreshMode, - ) { - let mut roots = roots.to_vec(); - roots.sort_unstable(); - roots.dedup(); - if roots.is_empty() { - return; - } - let request = NonCuratedCacheRefreshRequest { roots, mode }; - - let should_spawn = { - let mut state = match self.non_curated_cache_refresh_state.write() { - Ok(state) => state, - Err(err) => err.into_inner(), - }; - // Collapse repeated plugin/list requests onto one worker and only queue another pass - // when the requested roots set actually changes. Forced reinstall requests are not - // deduped against the last completed pass because the same marketplace root path can - // point at newly activated files after an auto-upgrade. - if state.requested.as_ref() == Some(&request) - || (mode == NonCuratedCacheRefreshMode::IfVersionChanged - && !state.in_flight - && state.last_refreshed.as_ref() == Some(&request)) - { - return; - } - if mode == NonCuratedCacheRefreshMode::IfVersionChanged - && state.requested.as_ref().is_some_and(|requested| { - requested.mode == NonCuratedCacheRefreshMode::ForceReinstall - && requested.roots == request.roots - }) - { - return; - } - state.requested = Some(request); - if state.in_flight { - false - } else { - state.in_flight = true; - true - } - }; - if !should_spawn { - return; - } - - let manager = Arc::clone(self); - if let Err(err) = std::thread::Builder::new() - .name("plugins-non-curated-cache-refresh".to_string()) - .spawn(move || manager.run_non_curated_plugin_cache_refresh_loop()) - { - let mut state = match self.non_curated_cache_refresh_state.write() { - Ok(state) => state, - Err(err) => err.into_inner(), - }; - state.in_flight = false; - state.requested = None; - warn!("failed to start non-curated plugin cache refresh task: {err}"); - } - } - - fn start_curated_repo_sync(self: &Arc) { - if CURATED_REPO_SYNC_STARTED.swap(true, Ordering::SeqCst) { - return; - } - let manager = Arc::clone(self); - let codex_home = self.codex_home.clone(); - if let Err(err) = std::thread::Builder::new() - .name("plugins-curated-repo-sync".to_string()) - .spawn( - move || match sync_openai_plugins_repo(codex_home.as_path()) { - Ok(curated_plugin_version) => { - let configured_curated_plugin_ids = - configured_curated_plugin_ids_from_codex_home(codex_home.as_path()); - match refresh_curated_plugin_cache( - codex_home.as_path(), - &curated_plugin_version, - &configured_curated_plugin_ids, - ) { - Ok(cache_refreshed) => { - if cache_refreshed { - manager.clear_cache(); - } - } - Err(err) => { - manager.clear_cache(); - CURATED_REPO_SYNC_STARTED.store(false, Ordering::SeqCst); - warn!("failed to refresh curated plugin cache after sync: {err}"); - } - } - } - Err(err) => { - CURATED_REPO_SYNC_STARTED.store(false, Ordering::SeqCst); - warn!("failed to sync curated plugins repo: {err}"); - } - }, - ) - { - CURATED_REPO_SYNC_STARTED.store(false, Ordering::SeqCst); - warn!("failed to start curated plugins repo sync task: {err}"); - } - } - - fn run_non_curated_plugin_cache_refresh_loop(self: Arc) { - loop { - let request = { - let state = match self.non_curated_cache_refresh_state.read() { - Ok(state) => state, - Err(err) => err.into_inner(), - }; - state.requested.clone() - }; - - let Some(request) = request else { - let mut state = match self.non_curated_cache_refresh_state.write() { - Ok(state) => state, - Err(err) => err.into_inner(), - }; - state.in_flight = false; - return; - }; - - let refresh_result = match request.mode { - NonCuratedCacheRefreshMode::IfVersionChanged => { - refresh_non_curated_plugin_cache(self.codex_home.as_path(), &request.roots) - } - NonCuratedCacheRefreshMode::ForceReinstall => { - refresh_non_curated_plugin_cache_force_reinstall( - self.codex_home.as_path(), - &request.roots, - ) - } - }; - let refreshed = match refresh_result { - Ok(cache_refreshed) => { - if cache_refreshed { - self.clear_cache(); - } - true - } - Err(err) => { - self.clear_cache(); - warn!("failed to refresh non-curated plugin cache: {err}"); - false - } - }; - - let mut state = match self.non_curated_cache_refresh_state.write() { - Ok(state) => state, - Err(err) => err.into_inner(), - }; - if refreshed { - state.last_refreshed = Some(request.clone()); - } - if state.requested.as_ref() == Some(&request) { - state.requested = None; - state.in_flight = false; - return; - } - } - } - - fn configured_plugin_states(&self, config: &Config) -> (HashSet, HashSet) { - let configured_plugins = configured_plugins_from_stack(&config.config_layer_stack); - let installed_plugins = configured_plugins - .keys() - .filter(|plugin_key| { - PluginId::parse(plugin_key) - .ok() - .is_some_and(|plugin_id| self.store.is_installed(&plugin_id)) - }) - .cloned() - .collect::>(); - let enabled_plugins = configured_plugins - .into_iter() - .filter_map(|(plugin_key, plugin)| plugin.enabled.then_some(plugin_key)) - .collect::>(); - (installed_plugins, enabled_plugins) - } - - fn marketplace_roots( - &self, - config: &Config, - additional_roots: &[AbsolutePathBuf], - ) -> Vec { - // Treat the curated catalog as an extra marketplace root so plugin listing can surface it - // without requiring every caller to know where it is stored. - let mut roots = additional_roots.to_vec(); - roots.extend(installed_marketplace_roots_from_config( - config, - self.codex_home.as_path(), - )); - let curated_repo_root = curated_plugins_repo_path(self.codex_home.as_path()); - if curated_repo_root.is_dir() - && let Ok(curated_repo_root) = AbsolutePathBuf::try_from(curated_repo_root) - { - roots.push(curated_repo_root); - } - roots.sort_unstable(); - roots.dedup(); - roots - } -} - -fn remote_plugin_install_required_description(source: &MarketplacePluginSource) -> String { - let source_description = match source { - MarketplacePluginSource::Git { - url, - path, - ref_name, - sha, - } => { - let mut parts = vec![url.clone()]; - if let Some(path) = path { - parts.push(format!("path `{path}`")); - } - if let Some(ref_name) = ref_name { - parts.push(format!("ref `{ref_name}`")); - } - if let Some(sha) = sha { - parts.push(format!("sha `{sha}`")); - } - parts.join(", ") - } - MarketplacePluginSource::Local { path } => path.as_path().display().to_string(), - }; - - format!( - "This is a cross-repo plugin. Install it to view more detailed information. The source of the plugin is {source_description}." - ) -} - -#[derive(Debug, thiserror::Error)] -pub enum PluginInstallError { - #[error("{0}")] - Marketplace(#[from] MarketplaceError), - - #[error("{0}")] - Remote(#[from] RemotePluginMutationError), - - #[error("{0}")] - Store(#[from] PluginStoreError), - - #[error("{0}")] - Config(#[from] anyhow::Error), - - #[error("failed to join plugin install task: {0}")] - Join(#[from] tokio::task::JoinError), -} - -impl PluginInstallError { - fn join(source: tokio::task::JoinError) -> Self { - Self::Join(source) - } - - pub fn is_invalid_request(&self) -> bool { - matches!( - self, - Self::Marketplace( - MarketplaceError::MarketplaceNotFound { .. } - | MarketplaceError::InvalidMarketplaceFile { .. } - | MarketplaceError::PluginNotFound { .. } - | MarketplaceError::PluginNotAvailable { .. } - | MarketplaceError::InvalidPlugin(_) - ) | Self::Store(PluginStoreError::Invalid(_)) - ) - } -} - -#[derive(Debug, thiserror::Error)] -pub enum PluginUninstallError { - #[error("{0}")] - InvalidPluginId(#[from] PluginIdError), - - #[error("{0}")] - Remote(#[from] RemotePluginMutationError), - - #[error("{0}")] - Store(#[from] PluginStoreError), - - #[error("{0}")] - Config(#[from] anyhow::Error), - - #[error("failed to join plugin uninstall task: {0}")] - Join(#[from] tokio::task::JoinError), -} - -impl PluginUninstallError { - fn join(source: tokio::task::JoinError) -> Self { - Self::Join(source) - } - - pub fn is_invalid_request(&self) -> bool { - matches!(self, Self::InvalidPluginId(_)) - } -} - -pub(crate) fn configured_plugins_from_stack( - config_layer_stack: &ConfigLayerStack, -) -> HashMap { - // Plugin entries remain persisted user config only. - let Some(user_layer) = config_layer_stack.get_user_layer() else { - return HashMap::new(); - }; - configured_plugins_from_user_config_value(&user_layer.config) -} - -fn configured_plugins_from_user_config_value( - user_config: &toml::Value, -) -> HashMap { - let Some(plugins_value) = user_config.get("plugins") else { - return HashMap::new(); - }; - match plugins_value.clone().try_into() { - Ok(plugins) => plugins, - Err(err) => { - warn!("invalid plugins config: {err}"); - HashMap::new() - } - } -} - -#[cfg(test)] -#[path = "manager_tests.rs"] -mod tests; diff --git a/vendor/codex/codex-rs/core/src/plugins/manager_tests.rs b/vendor/codex/codex-rs/core/src/plugins/manager_tests.rs deleted file mode 100644 index c455b088..00000000 --- a/vendor/codex/codex-rs/core/src/plugins/manager_tests.rs +++ /dev/null @@ -1,3229 +0,0 @@ -use super::*; -use crate::config::CONFIG_TOML_FILE; -use crate::config::ConfigBuilder; -use crate::config_loader::ConfigLayerEntry; -use crate::config_loader::ConfigLayerStack; -use crate::config_loader::ConfigRequirements; -use crate::config_loader::ConfigRequirementsToml; -use crate::plugins::LoadedPlugin; -use crate::plugins::PluginLoadOutcome; -use crate::plugins::marketplace_install_root; -use crate::plugins::test_support::TEST_CURATED_PLUGIN_SHA; -use crate::plugins::test_support::write_curated_plugin_sha_with as write_curated_plugin_sha; -use crate::plugins::test_support::write_file; -use crate::plugins::test_support::write_openai_curated_marketplace; -use codex_app_server_protocol::ConfigLayerSource; -use codex_config::McpServerConfig; -use codex_config::types::McpServerTransportConfig; -use codex_core_plugins::loader::refresh_non_curated_plugin_cache; -use codex_core_plugins::loader::refresh_non_curated_plugin_cache_force_reinstall; -use codex_core_plugins::marketplace::MarketplacePluginInstallPolicy; -use codex_login::CodexAuth; -use codex_protocol::protocol::Product; -use codex_utils_absolute_path::test_support::PathBufExt; -use pretty_assertions::assert_eq; -use std::fs; -use std::path::Path; -use tempfile::TempDir; -use toml::Value; -use wiremock::Mock; -use wiremock::MockServer; -use wiremock::ResponseTemplate; -use wiremock::matchers::header; -use wiremock::matchers::method; -use wiremock::matchers::path; -use wiremock::matchers::query_param; - -const MAX_CAPABILITY_SUMMARY_DESCRIPTION_LEN: usize = 1024; - -fn write_plugin_with_version( - root: &Path, - dir_name: &str, - manifest_name: &str, - manifest_version: Option<&str>, -) { - let plugin_root = root.join(dir_name); - fs::create_dir_all(plugin_root.join(".codex-plugin")).unwrap(); - fs::create_dir_all(plugin_root.join("skills")).unwrap(); - let version = manifest_version - .map(|manifest_version| format!(r#","version":"{manifest_version}""#)) - .unwrap_or_default(); - fs::write( - plugin_root.join(".codex-plugin/plugin.json"), - format!(r#"{{"name":"{manifest_name}"{version}}}"#), - ) - .unwrap(); - fs::write(plugin_root.join("skills/SKILL.md"), "skill").unwrap(); - fs::write(plugin_root.join(".mcp.json"), r#"{"mcpServers":{}}"#).unwrap(); -} - -fn write_plugin(root: &Path, dir_name: &str, manifest_name: &str) { - write_plugin_with_version( - root, - dir_name, - manifest_name, - /*manifest_version*/ None, - ); -} - -fn init_git_repo(repo: &Path) { - run_git(repo, &["init"]); - run_git(repo, &["config", "user.email", "codex-test@example.com"]); - run_git(repo, &["config", "user.name", "Codex Test"]); - run_git(repo, &["add", "."]); - run_git(repo, &["commit", "-m", "initial"]); -} - -fn run_git(repo: &Path, args: &[&str]) { - let output = std::process::Command::new("git") - .arg("-C") - .arg(repo) - .args(args) - .output() - .unwrap_or_else(|err| panic!("git should run: {err}")); - assert!( - output.status.success(), - "git -C {} {} failed\nstdout:\n{}\nstderr:\n{}", - repo.display(), - args.join(" "), - String::from_utf8_lossy(&output.stdout), - String::from_utf8_lossy(&output.stderr) - ); -} - -fn plugin_config_toml(enabled: bool, plugins_feature_enabled: bool) -> String { - let mut root = toml::map::Map::new(); - - let mut features = toml::map::Map::new(); - features.insert( - "plugins".to_string(), - Value::Boolean(plugins_feature_enabled), - ); - root.insert("features".to_string(), Value::Table(features)); - - let mut plugin = toml::map::Map::new(); - plugin.insert("enabled".to_string(), Value::Boolean(enabled)); - - let mut plugins = toml::map::Map::new(); - plugins.insert("sample@test".to_string(), Value::Table(plugin)); - root.insert("plugins".to_string(), Value::Table(plugins)); - - toml::to_string(&Value::Table(root)).expect("plugin test config should serialize") -} - -async fn load_plugins_from_config(config_toml: &str, codex_home: &Path) -> PluginLoadOutcome { - write_file(&codex_home.join(CONFIG_TOML_FILE), config_toml); - let config = load_config(codex_home, codex_home).await; - PluginsManager::new(codex_home.to_path_buf()) - .plugins_for_config(&config) - .await -} - -async fn load_config(codex_home: &Path, cwd: &Path) -> crate::config::Config { - ConfigBuilder::default() - .codex_home(codex_home.to_path_buf()) - .fallback_cwd(Some(cwd.to_path_buf())) - .build() - .await - .expect("config should load") -} - -#[tokio::test] -async fn load_plugins_loads_default_skills_and_mcp_servers() { - let codex_home = TempDir::new().unwrap(); - let plugin_root = codex_home - .path() - .join("plugins/cache") - .join("test/sample/local"); - - write_file( - &plugin_root.join(".codex-plugin/plugin.json"), - r#"{ - "name": "sample", - "description": "Plugin that includes the sample MCP server and Skills" -}"#, - ); - write_file( - &plugin_root.join("skills/sample-search/SKILL.md"), - "---\nname: sample-search\ndescription: search sample data\n---\n", - ); - write_file( - &plugin_root.join(".mcp.json"), - r#"{ - "mcpServers": { - "sample": { - "type": "http", - "url": "https://sample.example/mcp", - "oauth": { - "clientId": "client-id", - "callbackPort": 3118 - } - } - } -}"#, - ); - write_file( - &plugin_root.join(".app.json"), - r#"{ - "apps": { - "example": { - "id": "connector_example" - } - } -}"#, - ); - - let outcome = load_plugins_from_config( - &plugin_config_toml(/*enabled*/ true, /*plugins_feature_enabled*/ true), - codex_home.path(), - ) - .await; - - assert_eq!( - outcome.plugins(), - vec![LoadedPlugin { - config_name: "sample@test".to_string(), - manifest_name: Some("sample".to_string()), - manifest_description: Some( - "Plugin that includes the sample MCP server and Skills".to_string(), - ), - root: AbsolutePathBuf::try_from(plugin_root.clone()).unwrap(), - enabled: true, - skill_roots: vec![plugin_root.join("skills").abs()], - disabled_skill_paths: HashSet::new(), - has_enabled_skills: true, - mcp_servers: HashMap::from([( - "sample".to_string(), - McpServerConfig { - transport: McpServerTransportConfig::StreamableHttp { - url: "https://sample.example/mcp".to_string(), - bearer_token_env_var: None, - http_headers: None, - env_http_headers: None, - }, - experimental_environment: None, - enabled: true, - required: false, - supports_parallel_tool_calls: false, - disabled_reason: None, - startup_timeout_sec: None, - tool_timeout_sec: None, - default_tools_approval_mode: None, - enabled_tools: None, - disabled_tools: None, - scopes: None, - oauth_resource: None, - tools: HashMap::new(), - }, - )]), - apps: vec![AppConnectorId("connector_example".to_string())], - error: None, - }] - ); - assert_eq!( - outcome.capability_summaries(), - &[PluginCapabilitySummary { - config_name: "sample@test".to_string(), - display_name: "sample".to_string(), - description: Some("Plugin that includes the sample MCP server and Skills".to_string(),), - has_skills: true, - mcp_server_names: vec!["sample".to_string()], - app_connector_ids: vec![AppConnectorId("connector_example".to_string())], - }] - ); - assert_eq!( - outcome.effective_skill_roots(), - vec![plugin_root.join("skills").abs()] - ); - assert_eq!(outcome.effective_mcp_servers().len(), 1); - assert_eq!( - outcome.effective_apps(), - vec![AppConnectorId("connector_example".to_string())] - ); -} - -#[tokio::test] -async fn load_plugins_resolves_disabled_skill_names_against_loaded_plugin_skills() { - let codex_home = TempDir::new().unwrap(); - let plugin_root = codex_home - .path() - .join("plugins/cache") - .join("test/sample/local"); - let skill_path = plugin_root.join("skills/sample-search/SKILL.md"); - - write_file( - &plugin_root.join(".codex-plugin/plugin.json"), - r#"{"name":"sample"}"#, - ); - write_file( - &skill_path, - "---\nname: sample-search\ndescription: search sample data\n---\n", - ); - - let config_toml = r#"[features] -plugins = true - -[[skills.config]] -name = "sample:sample-search" -enabled = false - -[plugins."sample@test"] -enabled = true -"#; - let outcome = load_plugins_from_config(config_toml, codex_home.path()).await; - let skill_path = dunce::canonicalize(skill_path) - .expect("skill path should canonicalize") - .abs(); - - assert_eq!( - outcome.plugins()[0].disabled_skill_paths, - HashSet::from([skill_path]) - ); - assert!(!outcome.plugins()[0].has_enabled_skills); - assert!(outcome.capability_summaries().is_empty()); -} - -#[tokio::test] -async fn load_plugins_ignores_unknown_disabled_skill_names() { - let codex_home = TempDir::new().unwrap(); - let plugin_root = codex_home - .path() - .join("plugins/cache") - .join("test/sample/local"); - - write_file( - &plugin_root.join(".codex-plugin/plugin.json"), - r#"{"name":"sample"}"#, - ); - write_file( - &plugin_root.join("skills/sample-search/SKILL.md"), - "---\nname: sample-search\ndescription: search sample data\n---\n", - ); - - let config_toml = r#"[features] -plugins = true - -[[skills.config]] -name = "sample:missing-skill" -enabled = false - -[plugins."sample@test"] -enabled = true -"#; - let outcome = load_plugins_from_config(config_toml, codex_home.path()).await; - - assert!(outcome.plugins()[0].disabled_skill_paths.is_empty()); - assert!(outcome.plugins()[0].has_enabled_skills); - assert_eq!( - outcome.capability_summaries(), - &[PluginCapabilitySummary { - config_name: "sample@test".to_string(), - display_name: "sample".to_string(), - description: None, - has_skills: true, - mcp_server_names: Vec::new(), - app_connector_ids: Vec::new(), - }] - ); -} - -#[tokio::test] -async fn plugin_telemetry_metadata_uses_default_mcp_config_path() { - let codex_home = TempDir::new().unwrap(); - let plugin_root = codex_home - .path() - .join("plugins/cache") - .join("test/sample/local"); - - write_file( - &plugin_root.join(".codex-plugin/plugin.json"), - r#"{ - "name": "sample" -}"#, - ); - write_file( - &plugin_root.join(".mcp.json"), - r#"{ - "mcpServers": { - "sample": { - "type": "http", - "url": "https://sample.example/mcp" - } - } -}"#, - ); - - let metadata = plugin_telemetry_metadata_from_root( - &PluginId::parse("sample@test").expect("plugin id should parse"), - &plugin_root.abs(), - ) - .await; - - assert_eq!( - metadata.capability_summary, - Some(PluginCapabilitySummary { - config_name: "sample@test".to_string(), - display_name: "sample".to_string(), - description: None, - has_skills: false, - mcp_server_names: vec!["sample".to_string()], - app_connector_ids: Vec::new(), - }) - ); -} - -#[tokio::test] -async fn capability_summary_sanitizes_plugin_descriptions_to_one_line() { - let codex_home = TempDir::new().unwrap(); - let plugin_root = codex_home - .path() - .join("plugins/cache") - .join("test/sample/local"); - - write_file( - &plugin_root.join(".codex-plugin/plugin.json"), - r#"{ - "name": "sample", - "description": "Plugin that\n includes the sample\tserver" -}"#, - ); - write_file( - &plugin_root.join("skills/sample-search/SKILL.md"), - "---\nname: sample-search\ndescription: search sample data\n---\n", - ); - - let outcome = load_plugins_from_config( - &plugin_config_toml(/*enabled*/ true, /*plugins_feature_enabled*/ true), - codex_home.path(), - ) - .await; - - assert_eq!( - outcome.plugins()[0].manifest_description.as_deref(), - Some("Plugin that\n includes the sample\tserver") - ); - assert_eq!( - outcome.capability_summaries()[0].description.as_deref(), - Some("Plugin that includes the sample server") - ); -} - -#[tokio::test] -async fn capability_summary_truncates_overlong_plugin_descriptions() { - let codex_home = TempDir::new().unwrap(); - let plugin_root = codex_home - .path() - .join("plugins/cache") - .join("test/sample/local"); - let too_long = "x".repeat(MAX_CAPABILITY_SUMMARY_DESCRIPTION_LEN + 1); - - write_file( - &plugin_root.join(".codex-plugin/plugin.json"), - &format!( - r#"{{ - "name": "sample", - "description": "{too_long}" -}}"# - ), - ); - write_file( - &plugin_root.join("skills/sample-search/SKILL.md"), - "---\nname: sample-search\ndescription: search sample data\n---\n", - ); - - let outcome = load_plugins_from_config( - &plugin_config_toml(/*enabled*/ true, /*plugins_feature_enabled*/ true), - codex_home.path(), - ) - .await; - - assert_eq!( - outcome.plugins()[0].manifest_description.as_deref(), - Some(too_long.as_str()) - ); - assert_eq!( - outcome.capability_summaries()[0].description, - Some("x".repeat(MAX_CAPABILITY_SUMMARY_DESCRIPTION_LEN)) - ); -} - -#[tokio::test] -async fn load_plugins_uses_manifest_configured_component_paths() { - let codex_home = TempDir::new().unwrap(); - let plugin_root = codex_home - .path() - .join("plugins/cache") - .join("test/sample/local"); - - write_file( - &plugin_root.join(".codex-plugin/plugin.json"), - r#"{ - "name": "sample", - "skills": "./custom-skills/", - "mcpServers": "./config/custom.mcp.json", - "apps": "./config/custom.app.json" -}"#, - ); - write_file( - &plugin_root.join("skills/default-skill/SKILL.md"), - "---\nname: default-skill\ndescription: default skill\n---\n", - ); - write_file( - &plugin_root.join("custom-skills/custom-skill/SKILL.md"), - "---\nname: custom-skill\ndescription: custom skill\n---\n", - ); - write_file( - &plugin_root.join(".mcp.json"), - r#"{ - "mcpServers": { - "default": { - "type": "http", - "url": "https://default.example/mcp" - } - } -}"#, - ); - write_file( - &plugin_root.join("config/custom.mcp.json"), - r#"{ - "mcpServers": { - "custom": { - "type": "http", - "url": "https://custom.example/mcp" - } - } -}"#, - ); - write_file( - &plugin_root.join(".app.json"), - r#"{ - "apps": { - "default": { - "id": "connector_default" - } - } -}"#, - ); - write_file( - &plugin_root.join("config/custom.app.json"), - r#"{ - "apps": { - "custom": { - "id": "connector_custom" - } - } -}"#, - ); - - let outcome = load_plugins_from_config( - &plugin_config_toml(/*enabled*/ true, /*plugins_feature_enabled*/ true), - codex_home.path(), - ) - .await; - - assert_eq!( - outcome.plugins()[0].skill_roots, - vec![ - plugin_root.join("custom-skills").abs(), - plugin_root.join("skills").abs() - ] - ); - assert_eq!( - outcome.plugins()[0].mcp_servers, - HashMap::from([( - "custom".to_string(), - McpServerConfig { - transport: McpServerTransportConfig::StreamableHttp { - url: "https://custom.example/mcp".to_string(), - bearer_token_env_var: None, - http_headers: None, - env_http_headers: None, - }, - experimental_environment: None, - enabled: true, - required: false, - supports_parallel_tool_calls: false, - disabled_reason: None, - startup_timeout_sec: None, - tool_timeout_sec: None, - default_tools_approval_mode: None, - enabled_tools: None, - disabled_tools: None, - scopes: None, - oauth_resource: None, - tools: HashMap::new(), - }, - )]) - ); - assert_eq!( - outcome.plugins()[0].apps, - vec![AppConnectorId("connector_custom".to_string())] - ); -} - -#[tokio::test] -async fn load_plugins_ignores_manifest_component_paths_without_dot_slash() { - let codex_home = TempDir::new().unwrap(); - let plugin_root = codex_home - .path() - .join("plugins/cache") - .join("test/sample/local"); - - write_file( - &plugin_root.join(".codex-plugin/plugin.json"), - r#"{ - "name": "sample", - "skills": "custom-skills", - "mcpServers": "config/custom.mcp.json", - "apps": "config/custom.app.json" -}"#, - ); - write_file( - &plugin_root.join("skills/default-skill/SKILL.md"), - "---\nname: default-skill\ndescription: default skill\n---\n", - ); - write_file( - &plugin_root.join("custom-skills/custom-skill/SKILL.md"), - "---\nname: custom-skill\ndescription: custom skill\n---\n", - ); - write_file( - &plugin_root.join(".mcp.json"), - r#"{ - "mcpServers": { - "default": { - "type": "http", - "url": "https://default.example/mcp" - } - } -}"#, - ); - write_file( - &plugin_root.join("config/custom.mcp.json"), - r#"{ - "mcpServers": { - "custom": { - "type": "http", - "url": "https://custom.example/mcp" - } - } -}"#, - ); - write_file( - &plugin_root.join(".app.json"), - r#"{ - "apps": { - "default": { - "id": "connector_default" - } - } -}"#, - ); - write_file( - &plugin_root.join("config/custom.app.json"), - r#"{ - "apps": { - "custom": { - "id": "connector_custom" - } - } -}"#, - ); - - let outcome = load_plugins_from_config( - &plugin_config_toml(/*enabled*/ true, /*plugins_feature_enabled*/ true), - codex_home.path(), - ) - .await; - - assert_eq!( - outcome.plugins()[0].skill_roots, - vec![plugin_root.join("skills").abs()] - ); - assert_eq!( - outcome.plugins()[0].mcp_servers, - HashMap::from([( - "default".to_string(), - McpServerConfig { - transport: McpServerTransportConfig::StreamableHttp { - url: "https://default.example/mcp".to_string(), - bearer_token_env_var: None, - http_headers: None, - env_http_headers: None, - }, - experimental_environment: None, - enabled: true, - required: false, - supports_parallel_tool_calls: false, - disabled_reason: None, - startup_timeout_sec: None, - tool_timeout_sec: None, - default_tools_approval_mode: None, - enabled_tools: None, - disabled_tools: None, - scopes: None, - oauth_resource: None, - tools: HashMap::new(), - }, - )]) - ); - assert_eq!( - outcome.plugins()[0].apps, - vec![AppConnectorId("connector_default".to_string())] - ); -} - -#[tokio::test] -async fn load_plugins_preserves_disabled_plugins_without_effective_contributions() { - let codex_home = TempDir::new().unwrap(); - let plugin_root = codex_home - .path() - .join("plugins/cache") - .join("test/sample/local"); - - write_file( - &plugin_root.join(".codex-plugin/plugin.json"), - r#"{"name":"sample"}"#, - ); - write_file( - &plugin_root.join(".mcp.json"), - r#"{ - "mcpServers": { - "sample": { - "type": "http", - "url": "https://sample.example/mcp" - } - } -}"#, - ); - - let outcome = load_plugins_from_config( - &plugin_config_toml( - /*enabled*/ false, /*plugins_feature_enabled*/ true, - ), - codex_home.path(), - ) - .await; - - assert_eq!( - outcome.plugins(), - vec![LoadedPlugin { - config_name: "sample@test".to_string(), - manifest_name: None, - manifest_description: None, - root: AbsolutePathBuf::try_from(plugin_root).unwrap(), - enabled: false, - skill_roots: Vec::new(), - disabled_skill_paths: HashSet::new(), - has_enabled_skills: false, - mcp_servers: HashMap::new(), - apps: Vec::new(), - error: None, - }] - ); - assert!(outcome.effective_skill_roots().is_empty()); - assert!(outcome.effective_mcp_servers().is_empty()); -} - -#[tokio::test] -async fn effective_apps_dedupes_connector_ids_across_plugins() { - let codex_home = TempDir::new().unwrap(); - let plugin_a_root = codex_home - .path() - .join("plugins/cache") - .join("test/plugin-a/local"); - let plugin_b_root = codex_home - .path() - .join("plugins/cache") - .join("test/plugin-b/local"); - - write_file( - &plugin_a_root.join(".codex-plugin/plugin.json"), - r#"{"name":"plugin-a"}"#, - ); - write_file( - &plugin_a_root.join(".app.json"), - r#"{ - "apps": { - "example": { - "id": "connector_example" - } - } -}"#, - ); - write_file( - &plugin_b_root.join(".codex-plugin/plugin.json"), - r#"{"name":"plugin-b"}"#, - ); - write_file( - &plugin_b_root.join(".app.json"), - r#"{ - "apps": { - "chat": { - "id": "connector_example" - }, - "gmail": { - "id": "connector_gmail" - } - } -}"#, - ); - - let mut root = toml::map::Map::new(); - let mut features = toml::map::Map::new(); - features.insert("plugins".to_string(), Value::Boolean(true)); - root.insert("features".to_string(), Value::Table(features)); - - let mut plugins = toml::map::Map::new(); - - let mut plugin_a = toml::map::Map::new(); - plugin_a.insert("enabled".to_string(), Value::Boolean(true)); - plugins.insert("plugin-a@test".to_string(), Value::Table(plugin_a)); - - let mut plugin_b = toml::map::Map::new(); - plugin_b.insert("enabled".to_string(), Value::Boolean(true)); - plugins.insert("plugin-b@test".to_string(), Value::Table(plugin_b)); - - root.insert("plugins".to_string(), Value::Table(plugins)); - let config_toml = - toml::to_string(&Value::Table(root)).expect("plugin test config should serialize"); - - let outcome = load_plugins_from_config(&config_toml, codex_home.path()).await; - - assert_eq!( - outcome.effective_apps(), - vec![ - AppConnectorId("connector_example".to_string()), - AppConnectorId("connector_gmail".to_string()), - ] - ); -} - -#[test] -fn capability_index_filters_inactive_and_zero_capability_plugins() { - let codex_home = TempDir::new().unwrap(); - let connector = |id: &str| AppConnectorId(id.to_string()); - let http_server = |url: &str| McpServerConfig { - transport: McpServerTransportConfig::StreamableHttp { - url: url.to_string(), - bearer_token_env_var: None, - http_headers: None, - env_http_headers: None, - }, - experimental_environment: None, - enabled: true, - required: false, - supports_parallel_tool_calls: false, - disabled_reason: None, - startup_timeout_sec: None, - tool_timeout_sec: None, - default_tools_approval_mode: None, - enabled_tools: None, - disabled_tools: None, - scopes: None, - oauth_resource: None, - tools: HashMap::new(), - }; - let plugin = |config_name: &str, dir_name: &str, manifest_name: &str| LoadedPlugin { - config_name: config_name.to_string(), - manifest_name: Some(manifest_name.to_string()), - manifest_description: None, - root: AbsolutePathBuf::try_from(codex_home.path().join(dir_name)).unwrap(), - enabled: true, - skill_roots: Vec::new(), - disabled_skill_paths: HashSet::new(), - has_enabled_skills: false, - mcp_servers: HashMap::new(), - apps: Vec::new(), - error: None, - }; - let summary = |config_name: &str, display_name: &str| PluginCapabilitySummary { - config_name: config_name.to_string(), - display_name: display_name.to_string(), - description: None, - ..PluginCapabilitySummary::default() - }; - let outcome = PluginLoadOutcome::from_plugins(vec![ - LoadedPlugin { - skill_roots: vec![codex_home.path().join("skills-plugin/skills").abs()], - has_enabled_skills: true, - ..plugin("skills@test", "skills-plugin", "skills-plugin") - }, - LoadedPlugin { - mcp_servers: HashMap::from([("alpha".to_string(), http_server("https://alpha"))]), - apps: vec![connector("connector_example")], - ..plugin("alpha@test", "alpha-plugin", "alpha-plugin") - }, - LoadedPlugin { - mcp_servers: HashMap::from([("beta".to_string(), http_server("https://beta"))]), - apps: vec![connector("connector_example"), connector("connector_gmail")], - ..plugin("beta@test", "beta-plugin", "beta-plugin") - }, - plugin("empty@test", "empty-plugin", "empty-plugin"), - LoadedPlugin { - enabled: false, - skill_roots: vec![codex_home.path().join("disabled-plugin/skills").abs()], - apps: vec![connector("connector_hidden")], - ..plugin("disabled@test", "disabled-plugin", "disabled-plugin") - }, - LoadedPlugin { - apps: vec![connector("connector_broken")], - error: Some("failed to load".to_string()), - ..plugin("broken@test", "broken-plugin", "broken-plugin") - }, - ]); - - assert_eq!( - outcome.capability_summaries(), - &[ - PluginCapabilitySummary { - has_skills: true, - ..summary("skills@test", "skills-plugin") - }, - PluginCapabilitySummary { - mcp_server_names: vec!["alpha".to_string()], - app_connector_ids: vec![connector("connector_example")], - ..summary("alpha@test", "alpha-plugin") - }, - PluginCapabilitySummary { - mcp_server_names: vec!["beta".to_string()], - app_connector_ids: vec![ - connector("connector_example"), - connector("connector_gmail"), - ], - ..summary("beta@test", "beta-plugin") - }, - ] - ); -} - -#[tokio::test] -async fn load_plugins_returns_empty_when_feature_disabled() { - let codex_home = TempDir::new().unwrap(); - let plugin_root = codex_home - .path() - .join("plugins/cache") - .join("test/sample/local"); - - write_file( - &plugin_root.join(".codex-plugin/plugin.json"), - r#"{"name":"sample"}"#, - ); - write_file( - &plugin_root.join("skills/sample-search/SKILL.md"), - "---\nname: sample-search\ndescription: search sample data\n---\n", - ); - write_file( - &codex_home.path().join(CONFIG_TOML_FILE), - &plugin_config_toml( - /*enabled*/ true, /*plugins_feature_enabled*/ false, - ), - ); - - let config = load_config(codex_home.path(), codex_home.path()).await; - let outcome = PluginsManager::new(codex_home.path().to_path_buf()) - .plugins_for_config(&config) - .await; - - assert_eq!(outcome, PluginLoadOutcome::default()); -} - -#[tokio::test] -async fn load_plugins_rejects_invalid_plugin_keys() { - let codex_home = TempDir::new().unwrap(); - let plugin_root = codex_home - .path() - .join("plugins/cache") - .join("test/sample/local"); - - write_file( - &plugin_root.join(".codex-plugin/plugin.json"), - r#"{"name":"sample"}"#, - ); - - let mut root = toml::map::Map::new(); - let mut features = toml::map::Map::new(); - features.insert("plugins".to_string(), Value::Boolean(true)); - root.insert("features".to_string(), Value::Table(features)); - - let mut plugin = toml::map::Map::new(); - plugin.insert("enabled".to_string(), Value::Boolean(true)); - - let mut plugins = toml::map::Map::new(); - plugins.insert("sample".to_string(), Value::Table(plugin)); - root.insert("plugins".to_string(), Value::Table(plugins)); - - let outcome = load_plugins_from_config( - &toml::to_string(&Value::Table(root)).expect("plugin test config should serialize"), - codex_home.path(), - ) - .await; - - assert_eq!(outcome.plugins().len(), 1); - assert_eq!( - outcome.plugins()[0].error.as_deref(), - Some("invalid plugin key `sample`; expected @") - ); - assert!(outcome.effective_skill_roots().is_empty()); - assert!(outcome.effective_mcp_servers().is_empty()); -} - -#[tokio::test] -async fn install_plugin_updates_config_with_relative_path_and_plugin_key() { - let tmp = tempfile::tempdir().unwrap(); - let repo_root = tmp.path().join("repo"); - fs::create_dir_all(repo_root.join(".git")).unwrap(); - fs::create_dir_all(repo_root.join(".agents/plugins")).unwrap(); - write_plugin(&repo_root, "sample-plugin", "sample-plugin"); - fs::write( - repo_root.join(".agents/plugins/marketplace.json"), - r#"{ - "name": "debug", - "plugins": [ - { - "name": "sample-plugin", - "source": { - "source": "local", - "path": "./sample-plugin" - }, - "policy": { - "authentication": "ON_USE" - } - } - ] -}"#, - ) - .unwrap(); - - let result = PluginsManager::new(tmp.path().to_path_buf()) - .install_plugin(PluginInstallRequest { - plugin_name: "sample-plugin".to_string(), - marketplace_path: AbsolutePathBuf::try_from( - repo_root.join(".agents/plugins/marketplace.json"), - ) - .unwrap(), - }) - .await - .unwrap(); - - let installed_path = tmp.path().join("plugins/cache/debug/sample-plugin/local"); - assert_eq!( - result, - PluginInstallOutcome { - plugin_id: PluginId::new("sample-plugin".to_string(), "debug".to_string()).unwrap(), - plugin_version: "local".to_string(), - installed_path: AbsolutePathBuf::try_from(installed_path).unwrap(), - auth_policy: MarketplacePluginAuthPolicy::OnUse, - } - ); - - let config = fs::read_to_string(tmp.path().join("config.toml")).unwrap(); - assert!(config.contains(r#"[plugins."sample-plugin@debug"]"#)); - assert!(config.contains("enabled = true")); -} - -#[tokio::test] -async fn install_plugin_uses_manifest_version_for_non_curated_plugins() { - let tmp = tempfile::tempdir().unwrap(); - let repo_root = tmp.path().join("repo"); - fs::create_dir_all(repo_root.join(".git")).unwrap(); - fs::create_dir_all(repo_root.join(".agents/plugins")).unwrap(); - write_plugin_with_version( - &repo_root, - "sample-plugin", - "sample-plugin", - Some("1.2.3-beta+7"), - ); - fs::write( - repo_root.join(".agents/plugins/marketplace.json"), - r#"{ - "name": "debug", - "plugins": [ - { - "name": "sample-plugin", - "source": { - "source": "local", - "path": "./sample-plugin" - } - } - ] -}"#, - ) - .unwrap(); - - let result = PluginsManager::new(tmp.path().to_path_buf()) - .install_plugin(PluginInstallRequest { - plugin_name: "sample-plugin".to_string(), - marketplace_path: AbsolutePathBuf::try_from( - repo_root.join(".agents/plugins/marketplace.json"), - ) - .unwrap(), - }) - .await - .unwrap(); - - let installed_path = tmp - .path() - .join("plugins/cache/debug/sample-plugin/1.2.3-beta+7"); - assert_eq!( - result, - PluginInstallOutcome { - plugin_id: PluginId::new("sample-plugin".to_string(), "debug".to_string()).unwrap(), - plugin_version: "1.2.3-beta+7".to_string(), - installed_path: AbsolutePathBuf::try_from(installed_path).unwrap(), - auth_policy: MarketplacePluginAuthPolicy::OnInstall, - } - ); -} - -#[tokio::test] -async fn install_plugin_supports_git_subdir_marketplace_sources() { - let tmp = tempfile::tempdir().unwrap(); - let repo_root = tmp.path().join("marketplace"); - let remote_repo = tmp.path().join("remote-plugin-repo"); - let remote_repo_url = url::Url::from_directory_path(&remote_repo) - .unwrap() - .to_string(); - fs::create_dir_all(repo_root.join(".git")).unwrap(); - fs::create_dir_all(repo_root.join(".agents/plugins")).unwrap(); - write_plugin(&remote_repo, "plugins/toolkit", "toolkit"); - init_git_repo(&remote_repo); - fs::write( - repo_root.join(".agents/plugins/marketplace.json"), - format!( - r#"{{ - "name": "debug", - "plugins": [ - {{ - "name": "toolkit", - "source": {{ - "source": "git-subdir", - "url": "{remote_repo_url}", - "path": "plugins/toolkit" - }} - }} - ] -}}"# - ), - ) - .unwrap(); - - let result = PluginsManager::new(tmp.path().to_path_buf()) - .install_plugin(PluginInstallRequest { - plugin_name: "toolkit".to_string(), - marketplace_path: AbsolutePathBuf::try_from( - repo_root.join(".agents/plugins/marketplace.json"), - ) - .unwrap(), - }) - .await - .unwrap(); - - let installed_path = tmp.path().join("plugins/cache/debug/toolkit/local"); - assert_eq!( - result, - PluginInstallOutcome { - plugin_id: PluginId::new("toolkit".to_string(), "debug".to_string()).unwrap(), - plugin_version: "local".to_string(), - installed_path: AbsolutePathBuf::try_from(installed_path.clone()).unwrap(), - auth_policy: MarketplacePluginAuthPolicy::OnInstall, - } - ); - assert!(installed_path.join(".codex-plugin/plugin.json").is_file()); -} - -#[tokio::test] -async fn install_plugin_supports_relative_git_subdir_marketplace_sources() { - let tmp = tempfile::tempdir().unwrap(); - let repo_root = tmp.path().join("marketplace"); - let remote_repo = repo_root.join("remote-plugin-repo"); - fs::create_dir_all(repo_root.join(".git")).unwrap(); - fs::create_dir_all(repo_root.join(".agents/plugins")).unwrap(); - write_plugin(&remote_repo, "plugins/toolkit", "toolkit"); - init_git_repo(&remote_repo); - fs::write( - repo_root.join(".agents/plugins/marketplace.json"), - r#"{ - "name": "debug", - "plugins": [ - { - "name": "toolkit", - "source": { - "source": "git-subdir", - "url": "./remote-plugin-repo", - "path": "plugins/toolkit" - } - } - ] -}"#, - ) - .unwrap(); - - let result = PluginsManager::new(tmp.path().to_path_buf()) - .install_plugin(PluginInstallRequest { - plugin_name: "toolkit".to_string(), - marketplace_path: AbsolutePathBuf::try_from( - repo_root.join(".agents/plugins/marketplace.json"), - ) - .unwrap(), - }) - .await - .unwrap(); - - let installed_path = tmp.path().join("plugins/cache/debug/toolkit/local"); - assert_eq!( - result, - PluginInstallOutcome { - plugin_id: PluginId::new("toolkit".to_string(), "debug".to_string()).unwrap(), - plugin_version: "local".to_string(), - installed_path: AbsolutePathBuf::try_from(installed_path.clone()).unwrap(), - auth_policy: MarketplacePluginAuthPolicy::OnInstall, - } - ); - assert!(installed_path.join(".codex-plugin/plugin.json").is_file()); -} - -#[tokio::test] -async fn uninstall_plugin_removes_cache_and_config_entry() { - let tmp = tempfile::tempdir().unwrap(); - write_plugin( - &tmp.path().join("plugins/cache/debug"), - "sample-plugin/local", - "sample-plugin", - ); - write_file( - &tmp.path().join(CONFIG_TOML_FILE), - r#"[features] -plugins = true - -[plugins."sample-plugin@debug"] -enabled = true -"#, - ); - - let manager = PluginsManager::new(tmp.path().to_path_buf()); - manager - .uninstall_plugin("sample-plugin@debug".to_string()) - .await - .unwrap(); - manager - .uninstall_plugin("sample-plugin@debug".to_string()) - .await - .unwrap(); - - assert!( - !tmp.path() - .join("plugins/cache/debug/sample-plugin") - .exists() - ); - let config = fs::read_to_string(tmp.path().join(CONFIG_TOML_FILE)).unwrap(); - assert!(!config.contains(r#"[plugins."sample-plugin@debug"]"#)); -} - -#[tokio::test] -async fn list_marketplaces_includes_enabled_state() { - let tmp = tempfile::tempdir().unwrap(); - let repo_root = tmp.path().join("repo"); - fs::create_dir_all(repo_root.join(".git")).unwrap(); - fs::create_dir_all(repo_root.join(".agents/plugins")).unwrap(); - write_plugin( - &tmp.path().join("plugins/cache/debug"), - "enabled-plugin/local", - "enabled-plugin", - ); - write_plugin( - &tmp.path().join("plugins/cache/debug"), - "disabled-plugin/local", - "disabled-plugin", - ); - fs::write( - repo_root.join(".agents/plugins/marketplace.json"), - r#"{ - "name": "debug", - "plugins": [ - { - "name": "enabled-plugin", - "source": { - "source": "local", - "path": "./enabled-plugin" - } - }, - { - "name": "disabled-plugin", - "source": { - "source": "local", - "path": "./disabled-plugin" - } - } - ] -}"#, - ) - .unwrap(); - write_file( - &tmp.path().join(CONFIG_TOML_FILE), - r#"[features] -plugins = true - -[plugins."enabled-plugin@debug"] -enabled = true - -[plugins."disabled-plugin@debug"] -enabled = false -"#, - ); - - let config = load_config(tmp.path(), &repo_root).await; - let marketplaces = PluginsManager::new(tmp.path().to_path_buf()) - .list_marketplaces_for_config(&config, &[AbsolutePathBuf::try_from(repo_root).unwrap()]) - .unwrap() - .marketplaces; - - let marketplace = marketplaces - .into_iter() - .find(|marketplace| { - marketplace.path - == AbsolutePathBuf::try_from( - tmp.path().join("repo/.agents/plugins/marketplace.json"), - ) - .unwrap() - }) - .expect("expected repo marketplace entry"); - - assert_eq!( - marketplace, - ConfiguredMarketplace { - name: "debug".to_string(), - path: AbsolutePathBuf::try_from( - tmp.path().join("repo/.agents/plugins/marketplace.json"), - ) - .unwrap(), - interface: None, - plugins: vec![ - ConfiguredMarketplacePlugin { - id: "enabled-plugin@debug".to_string(), - name: "enabled-plugin".to_string(), - source: MarketplacePluginSource::Local { - path: AbsolutePathBuf::try_from(tmp.path().join("repo/enabled-plugin")) - .unwrap(), - }, - policy: MarketplacePluginPolicy { - installation: MarketplacePluginInstallPolicy::Available, - authentication: MarketplacePluginAuthPolicy::OnInstall, - products: None, - }, - interface: None, - installed: true, - enabled: true, - }, - ConfiguredMarketplacePlugin { - id: "disabled-plugin@debug".to_string(), - name: "disabled-plugin".to_string(), - source: MarketplacePluginSource::Local { - path: AbsolutePathBuf::try_from(tmp.path().join("repo/disabled-plugin"),) - .unwrap(), - }, - policy: MarketplacePluginPolicy { - installation: MarketplacePluginInstallPolicy::Available, - authentication: MarketplacePluginAuthPolicy::OnInstall, - products: None, - }, - interface: None, - installed: true, - enabled: false, - }, - ], - } - ); -} - -#[tokio::test] -async fn list_marketplaces_returns_empty_when_feature_disabled() { - let tmp = tempfile::tempdir().unwrap(); - let repo_root = tmp.path().join("repo"); - fs::create_dir_all(repo_root.join(".git")).unwrap(); - fs::create_dir_all(repo_root.join(".agents/plugins")).unwrap(); - fs::write( - repo_root.join(".agents/plugins/marketplace.json"), - r#"{ - "name": "debug", - "plugins": [ - { - "name": "enabled-plugin", - "source": { - "source": "local", - "path": "./enabled-plugin" - } - } - ] -}"#, - ) - .unwrap(); - write_file( - &tmp.path().join(CONFIG_TOML_FILE), - r#"[features] -plugins = false - -[plugins."enabled-plugin@debug"] -enabled = true -"#, - ); - - let config = load_config(tmp.path(), &repo_root).await; - let marketplaces = PluginsManager::new(tmp.path().to_path_buf()) - .list_marketplaces_for_config(&config, &[AbsolutePathBuf::try_from(repo_root).unwrap()]) - .unwrap() - .marketplaces; - - assert_eq!(marketplaces, Vec::new()); -} - -#[tokio::test] -async fn list_marketplaces_excludes_plugins_with_explicit_empty_products() { - let tmp = tempfile::tempdir().unwrap(); - let repo_root = tmp.path().join("repo"); - fs::create_dir_all(repo_root.join(".git")).unwrap(); - fs::create_dir_all(repo_root.join(".agents/plugins")).unwrap(); - fs::write( - repo_root.join(".agents/plugins/marketplace.json"), - r#"{ - "name": "debug", - "plugins": [ - { - "name": "disabled-plugin", - "source": { - "source": "local", - "path": "./disabled-plugin" - }, - "policy": { - "products": [] - } - }, - { - "name": "default-plugin", - "source": { - "source": "local", - "path": "./default-plugin" - } - } - ] -}"#, - ) - .unwrap(); - write_file( - &tmp.path().join(CONFIG_TOML_FILE), - r#"[features] -plugins = true -"#, - ); - - let config = load_config(tmp.path(), &repo_root).await; - let marketplaces = PluginsManager::new(tmp.path().to_path_buf()) - .list_marketplaces_for_config(&config, &[AbsolutePathBuf::try_from(repo_root).unwrap()]) - .unwrap() - .marketplaces; - - let marketplace = marketplaces - .into_iter() - .find(|marketplace| { - marketplace.path - == AbsolutePathBuf::try_from( - tmp.path().join("repo/.agents/plugins/marketplace.json"), - ) - .unwrap() - }) - .expect("expected repo marketplace entry"); - assert_eq!( - marketplace.plugins, - vec![ConfiguredMarketplacePlugin { - id: "default-plugin@debug".to_string(), - name: "default-plugin".to_string(), - source: MarketplacePluginSource::Local { - path: AbsolutePathBuf::try_from(tmp.path().join("repo/default-plugin")).unwrap(), - }, - policy: MarketplacePluginPolicy { - installation: MarketplacePluginInstallPolicy::Available, - authentication: MarketplacePluginAuthPolicy::OnInstall, - products: None, - }, - interface: None, - installed: false, - enabled: false, - }] - ); -} - -#[tokio::test] -async fn read_plugin_for_config_returns_plugins_disabled_when_feature_disabled() { - let tmp = tempfile::tempdir().unwrap(); - let repo_root = tmp.path().join("repo"); - fs::create_dir_all(repo_root.join(".git")).unwrap(); - fs::create_dir_all(repo_root.join(".agents/plugins")).unwrap(); - let marketplace_path = - AbsolutePathBuf::try_from(repo_root.join(".agents/plugins/marketplace.json")).unwrap(); - fs::write( - marketplace_path.as_path(), - r#"{ - "name": "debug", - "plugins": [ - { - "name": "enabled-plugin", - "source": { - "source": "local", - "path": "./enabled-plugin" - } - } - ] -}"#, - ) - .unwrap(); - write_file( - &tmp.path().join(CONFIG_TOML_FILE), - r#"[features] -plugins = false - -[plugins."enabled-plugin@debug"] -enabled = true -"#, - ); - - let config = load_config(tmp.path(), &repo_root).await; - let err = PluginsManager::new(tmp.path().to_path_buf()) - .read_plugin_for_config( - &config, - &PluginReadRequest { - plugin_name: "enabled-plugin".to_string(), - marketplace_path, - }, - ) - .await - .unwrap_err(); - - assert!(matches!(err, MarketplaceError::PluginsDisabled)); -} - -#[tokio::test] -async fn read_plugin_for_config_uses_user_layer_skill_settings_only() { - let tmp = tempfile::tempdir().unwrap(); - let repo_root = tmp.path().join("repo"); - let plugin_root = repo_root.join("enabled-plugin"); - fs::create_dir_all(repo_root.join(".git")).unwrap(); - fs::create_dir_all(repo_root.join(".agents/plugins")).unwrap(); - write_file( - &repo_root.join(".agents/plugins/marketplace.json"), - r#"{ - "name": "debug", - "plugins": [ - { - "name": "enabled-plugin", - "source": { - "source": "local", - "path": "./enabled-plugin" - } - } - ] -}"#, - ); - write_file( - &plugin_root.join(".codex-plugin/plugin.json"), - r#"{"name":"enabled-plugin"}"#, - ); - write_file( - &plugin_root.join("skills/sample-search/SKILL.md"), - "---\nname: sample-search\ndescription: search sample data\n---\n", - ); - write_file( - &tmp.path().join(CONFIG_TOML_FILE), - r#"[features] -plugins = true - -[plugins."enabled-plugin@debug"] -enabled = true -"#, - ); - write_file( - &repo_root.join(".codex/config.toml"), - r#"[[skills.config]] -name = "enabled-plugin:sample-search" -enabled = false -"#, - ); - - let config = load_config(tmp.path(), &repo_root).await; - let outcome = PluginsManager::new(tmp.path().to_path_buf()) - .read_plugin_for_config( - &config, - &PluginReadRequest { - plugin_name: "enabled-plugin".to_string(), - marketplace_path: AbsolutePathBuf::try_from( - repo_root.join(".agents/plugins/marketplace.json"), - ) - .unwrap(), - }, - ) - .await - .unwrap(); - - assert!(outcome.plugin.disabled_skill_paths.is_empty()); -} - -#[tokio::test] -async fn read_plugin_for_config_uninstalled_git_source_requires_install_without_cloning() { - let tmp = tempfile::tempdir().unwrap(); - let repo_root = tmp.path().join("repo"); - let missing_remote_repo = tmp.path().join("missing-remote-plugin-repo"); - let missing_remote_repo_url = url::Url::from_directory_path(&missing_remote_repo) - .unwrap() - .to_string(); - fs::create_dir_all(repo_root.join(".git")).unwrap(); - write_file( - &repo_root.join(".agents/plugins/marketplace.json"), - &format!( - r#"{{ - "name": "debug", - "plugins": [ - {{ - "name": "toolkit", - "source": {{ - "source": "git-subdir", - "url": "{missing_remote_repo_url}", - "path": "plugins/toolkit" - }}, - "policy": {{ - "installation": "AVAILABLE", - "authentication": "ON_INSTALL" - }} - }} - ] -}}"# - ), - ); - write_file( - &tmp.path().join(CONFIG_TOML_FILE), - r#"[features] -plugins = true -"#, - ); - - let config = load_config(tmp.path(), &repo_root).await; - let outcome = PluginsManager::new(tmp.path().to_path_buf()) - .read_plugin_for_config( - &config, - &PluginReadRequest { - plugin_name: "toolkit".to_string(), - marketplace_path: AbsolutePathBuf::try_from( - repo_root.join(".agents/plugins/marketplace.json"), - ) - .unwrap(), - }, - ) - .await - .unwrap(); - - assert_eq!( - outcome.plugin.details_unavailable_reason, - Some(PluginDetailsUnavailableReason::InstallRequiredForRemoteSource) - ); - assert!(!outcome.plugin.installed); - let expected_description = format!( - "This is a cross-repo plugin. Install it to view more detailed information. The source of the plugin is {missing_remote_repo_url}, path `plugins/toolkit`." - ); - assert_eq!( - outcome.plugin.description.as_deref(), - Some(expected_description.as_str()) - ); - assert!(outcome.plugin.skills.is_empty()); - assert!(outcome.plugin.apps.is_empty()); - assert!(outcome.plugin.mcp_server_names.is_empty()); - assert!( - !tmp.path() - .join("plugins/.marketplace-plugin-source-staging") - .exists() - ); -} - -#[tokio::test] -async fn read_plugin_for_config_installed_git_source_reads_from_cache_without_cloning() { - let tmp = tempfile::tempdir().unwrap(); - let repo_root = tmp.path().join("repo"); - let missing_remote_repo = tmp.path().join("missing-remote-plugin-repo"); - let missing_remote_repo_url = url::Url::from_directory_path(&missing_remote_repo) - .unwrap() - .to_string(); - fs::create_dir_all(repo_root.join(".git")).unwrap(); - write_file( - &repo_root.join(".agents/plugins/marketplace.json"), - &format!( - r#"{{ - "name": "debug", - "plugins": [ - {{ - "name": "toolkit", - "source": {{ - "source": "git-subdir", - "url": "{missing_remote_repo_url}", - "path": "plugins/toolkit" - }}, - "category": "Developer Tools" - }} - ] -}}"# - ), - ); - let cached_plugin_root = tmp.path().join("plugins/cache/debug/toolkit/local"); - write_file( - &cached_plugin_root.join(".codex-plugin/plugin.json"), - r#"{ - "name": "toolkit", - "description": "Cached toolkit plugin", - "interface": { - "displayName": "Toolkit" - } -}"#, - ); - write_file( - &cached_plugin_root.join("skills/search/SKILL.md"), - "---\nname: search\ndescription: search cached data\n---\n", - ); - write_file( - &cached_plugin_root.join(".app.json"), - r#"{"apps":{"calendar":{"id":"connector_calendar"}}}"#, - ); - write_file( - &cached_plugin_root.join(".mcp.json"), - r#"{"mcpServers":{"toolkit":{"command":"toolkit-mcp"}}}"#, - ); - write_file( - &tmp.path().join(CONFIG_TOML_FILE), - r#"[features] -plugins = true - -[plugins."toolkit@debug"] -enabled = true -"#, - ); - - let config = load_config(tmp.path(), &repo_root).await; - let outcome = PluginsManager::new(tmp.path().to_path_buf()) - .read_plugin_for_config( - &config, - &PluginReadRequest { - plugin_name: "toolkit".to_string(), - marketplace_path: AbsolutePathBuf::try_from( - repo_root.join(".agents/plugins/marketplace.json"), - ) - .unwrap(), - }, - ) - .await - .unwrap(); - - assert_eq!(outcome.plugin.details_unavailable_reason, None); - assert_eq!( - outcome.plugin.description.as_deref(), - Some("Cached toolkit plugin") - ); - assert_eq!( - outcome.plugin.interface, - Some(PluginManifestInterface { - display_name: Some("Toolkit".to_string()), - category: Some("Developer Tools".to_string()), - ..Default::default() - }) - ); - assert!(outcome.plugin.installed); - assert_eq!(outcome.plugin.skills.len(), 1); - assert_eq!(outcome.plugin.skills[0].name, "toolkit:search"); - assert_eq!( - outcome.plugin.apps, - vec![AppConnectorId("connector_calendar".to_string())] - ); - assert_eq!(outcome.plugin.mcp_server_names, vec!["toolkit".to_string()]); - assert!( - !tmp.path() - .join("plugins/.marketplace-plugin-source-staging") - .exists() - ); -} - -#[tokio::test] -async fn sync_plugins_from_remote_returns_default_when_feature_disabled() { - let tmp = tempfile::tempdir().unwrap(); - write_file( - &tmp.path().join(CONFIG_TOML_FILE), - r#"[features] -plugins = false -"#, - ); - - let config = load_config(tmp.path(), tmp.path()).await; - let outcome = PluginsManager::new(tmp.path().to_path_buf()) - .sync_plugins_from_remote(&config, /*auth*/ None, /*additive_only*/ false) - .await - .unwrap(); - - assert_eq!(outcome, RemotePluginSyncResult::default()); -} - -#[tokio::test] -async fn list_marketplaces_includes_curated_repo_marketplace() { - let tmp = tempfile::tempdir().unwrap(); - let curated_root = curated_plugins_repo_path(tmp.path()); - let plugin_root = curated_root.join("plugins/linear"); - - write_file( - &tmp.path().join(CONFIG_TOML_FILE), - r#"[features] -plugins = true -"#, - ); - fs::create_dir_all(curated_root.join(".agents/plugins")).unwrap(); - fs::create_dir_all(plugin_root.join(".codex-plugin")).unwrap(); - fs::write( - curated_root.join(".agents/plugins/marketplace.json"), - r#"{ - "name": "openai-curated", - "plugins": [ - { - "name": "linear", - "source": { - "source": "local", - "path": "./plugins/linear" - } - } - ] -}"#, - ) - .unwrap(); - fs::write( - plugin_root.join(".codex-plugin/plugin.json"), - r#"{"name":"linear"}"#, - ) - .unwrap(); - - let config = load_config(tmp.path(), tmp.path()).await; - let marketplaces = PluginsManager::new(tmp.path().to_path_buf()) - .list_marketplaces_for_config(&config, &[]) - .unwrap() - .marketplaces; - - let curated_marketplace = marketplaces - .into_iter() - .find(|marketplace| marketplace.name == "openai-curated") - .expect("curated marketplace should be listed"); - - assert_eq!( - curated_marketplace, - ConfiguredMarketplace { - name: "openai-curated".to_string(), - path: AbsolutePathBuf::try_from(curated_root.join(".agents/plugins/marketplace.json")) - .unwrap(), - interface: None, - plugins: vec![ConfiguredMarketplacePlugin { - id: "linear@openai-curated".to_string(), - name: "linear".to_string(), - source: MarketplacePluginSource::Local { - path: AbsolutePathBuf::try_from(curated_root.join("plugins/linear")).unwrap(), - }, - policy: MarketplacePluginPolicy { - installation: MarketplacePluginInstallPolicy::Available, - authentication: MarketplacePluginAuthPolicy::OnInstall, - products: None, - }, - interface: None, - installed: false, - enabled: false, - }], - } - ); -} - -#[tokio::test] -async fn list_marketplaces_includes_installed_marketplace_roots() { - let tmp = tempfile::tempdir().unwrap(); - let marketplace_root = marketplace_install_root(tmp.path()).join("debug"); - let plugin_root = marketplace_root.join("plugins/sample"); - - write_file( - &tmp.path().join(CONFIG_TOML_FILE), - r#"[features] -plugins = true - -[marketplaces.debug] -last_updated = "2026-04-10T12:34:56Z" -source_type = "git" -source = "/tmp/debug" -"#, - ); - fs::create_dir_all(marketplace_root.join(".agents/plugins")).unwrap(); - fs::create_dir_all(plugin_root.join(".codex-plugin")).unwrap(); - fs::write( - marketplace_root.join(".agents/plugins/marketplace.json"), - r#"{ - "name": "debug", - "plugins": [ - { - "name": "sample", - "source": { - "source": "local", - "path": "./plugins/sample" - } - } - ] -}"#, - ) - .unwrap(); - fs::write( - plugin_root.join(".codex-plugin/plugin.json"), - r#"{"name":"sample"}"#, - ) - .unwrap(); - let config = load_config(tmp.path(), tmp.path()).await; - let marketplaces = PluginsManager::new(tmp.path().to_path_buf()) - .list_marketplaces_for_config(&config, &[]) - .unwrap() - .marketplaces; - - let marketplace = marketplaces - .into_iter() - .find(|marketplace| { - marketplace.path - == AbsolutePathBuf::try_from( - marketplace_root.join(".agents/plugins/marketplace.json"), - ) - .unwrap() - }) - .expect("installed marketplace should be listed"); - - assert_eq!( - marketplace.path, - AbsolutePathBuf::try_from(marketplace_root.join(".agents/plugins/marketplace.json")) - .unwrap() - ); - assert_eq!(marketplace.plugins.len(), 1); - assert_eq!(marketplace.plugins[0].id, "sample@debug"); - assert_eq!( - marketplace.plugins[0].source, - MarketplacePluginSource::Local { - path: AbsolutePathBuf::try_from(plugin_root).unwrap(), - } - ); -} - -#[tokio::test] -async fn list_marketplaces_uses_config_when_known_registry_is_malformed() { - let tmp = tempfile::tempdir().unwrap(); - let marketplace_root = marketplace_install_root(tmp.path()).join("debug"); - let plugin_root = marketplace_root.join("plugins/sample"); - let registry_path = tmp.path().join(".tmp/known_marketplaces.json"); - - write_file( - &tmp.path().join(CONFIG_TOML_FILE), - r#"[features] -plugins = true - -[marketplaces.debug] -last_updated = "2026-04-10T12:34:56Z" -source_type = "git" -source = "/tmp/debug" -"#, - ); - fs::create_dir_all(marketplace_root.join(".agents/plugins")).unwrap(); - fs::create_dir_all(plugin_root.join(".codex-plugin")).unwrap(); - fs::write( - marketplace_root.join(".agents/plugins/marketplace.json"), - r#"{ - "name": "debug", - "plugins": [ - { - "name": "sample", - "source": { - "source": "local", - "path": "./plugins/sample" - } - } - ] -}"#, - ) - .unwrap(); - fs::write( - plugin_root.join(".codex-plugin/plugin.json"), - r#"{"name":"sample"}"#, - ) - .unwrap(); - fs::create_dir_all(registry_path.parent().unwrap()).unwrap(); - fs::write(registry_path, "{not valid json").unwrap(); - - let config = load_config(tmp.path(), tmp.path()).await; - let marketplaces = PluginsManager::new(tmp.path().to_path_buf()) - .list_marketplaces_for_config(&config, &[]) - .unwrap() - .marketplaces; - - let marketplace = marketplaces - .into_iter() - .find(|marketplace| { - marketplace.path - == AbsolutePathBuf::try_from( - marketplace_root.join(".agents/plugins/marketplace.json"), - ) - .unwrap() - }) - .expect("configured marketplace should be discovered"); - - assert_eq!(marketplace.plugins[0].id, "sample@debug"); -} - -#[tokio::test] -async fn list_marketplaces_ignores_installed_roots_missing_from_config() { - let tmp = tempfile::tempdir().unwrap(); - let marketplace_root = marketplace_install_root(tmp.path()).join("debug"); - let plugin_root = marketplace_root.join("plugins/sample"); - - write_file( - &tmp.path().join(CONFIG_TOML_FILE), - r#"[features] -plugins = true -"#, - ); - fs::create_dir_all(marketplace_root.join(".agents/plugins")).unwrap(); - fs::create_dir_all(plugin_root.join(".codex-plugin")).unwrap(); - fs::write( - marketplace_root.join(".agents/plugins/marketplace.json"), - r#"{ - "name": "debug", - "plugins": [ - { - "name": "sample", - "source": { - "source": "local", - "path": "./plugins/sample" - } - } - ] -}"#, - ) - .unwrap(); - fs::write( - plugin_root.join(".codex-plugin/plugin.json"), - r#"{"name":"sample"}"#, - ) - .unwrap(); - let config = load_config(tmp.path(), tmp.path()).await; - let marketplaces = PluginsManager::new(tmp.path().to_path_buf()) - .list_marketplaces_for_config(&config, &[]) - .unwrap() - .marketplaces; - - assert!( - marketplaces.iter().all(|marketplace| { - marketplace.path - != AbsolutePathBuf::try_from( - marketplace_root.join(".agents/plugins/marketplace.json"), - ) - .unwrap() - }), - "installed marketplace root missing from config should not be listed" - ); -} - -#[tokio::test] -async fn list_marketplaces_uses_first_duplicate_plugin_entry() { - let tmp = tempfile::tempdir().unwrap(); - let repo_a_root = tmp.path().join("repo-a"); - let repo_b_root = tmp.path().join("repo-b"); - fs::create_dir_all(repo_a_root.join(".git")).unwrap(); - fs::create_dir_all(repo_b_root.join(".git")).unwrap(); - fs::create_dir_all(repo_a_root.join(".agents/plugins")).unwrap(); - fs::create_dir_all(repo_b_root.join(".agents/plugins")).unwrap(); - fs::write( - repo_a_root.join(".agents/plugins/marketplace.json"), - r#"{ - "name": "debug", - "plugins": [ - { - "name": "dup-plugin", - "source": { - "source": "local", - "path": "./from-a" - } - } - ] -}"#, - ) - .unwrap(); - fs::write( - repo_b_root.join(".agents/plugins/marketplace.json"), - r#"{ - "name": "debug", - "plugins": [ - { - "name": "dup-plugin", - "source": { - "source": "local", - "path": "./from-b" - } - }, - { - "name": "b-only-plugin", - "source": { - "source": "local", - "path": "./from-b-only" - } - } - ] -}"#, - ) - .unwrap(); - write_file( - &tmp.path().join(CONFIG_TOML_FILE), - r#"[features] -plugins = true - -[plugins."dup-plugin@debug"] -enabled = true - -[plugins."b-only-plugin@debug"] -enabled = false -"#, - ); - - let config = load_config(tmp.path(), &repo_a_root).await; - let marketplaces = PluginsManager::new(tmp.path().to_path_buf()) - .list_marketplaces_for_config( - &config, - &[ - AbsolutePathBuf::try_from(repo_a_root).unwrap(), - AbsolutePathBuf::try_from(repo_b_root).unwrap(), - ], - ) - .unwrap() - .marketplaces; - - let repo_a_marketplace = marketplaces - .iter() - .find(|marketplace| { - marketplace.path - == AbsolutePathBuf::try_from( - tmp.path().join("repo-a/.agents/plugins/marketplace.json"), - ) - .unwrap() - }) - .expect("repo-a marketplace should be listed"); - assert_eq!( - repo_a_marketplace.plugins, - vec![ConfiguredMarketplacePlugin { - id: "dup-plugin@debug".to_string(), - name: "dup-plugin".to_string(), - source: MarketplacePluginSource::Local { - path: AbsolutePathBuf::try_from(tmp.path().join("repo-a/from-a")).unwrap(), - }, - policy: MarketplacePluginPolicy { - installation: MarketplacePluginInstallPolicy::Available, - authentication: MarketplacePluginAuthPolicy::OnInstall, - products: None, - }, - interface: None, - installed: false, - enabled: true, - }] - ); - - let repo_b_marketplace = marketplaces - .iter() - .find(|marketplace| { - marketplace.path - == AbsolutePathBuf::try_from( - tmp.path().join("repo-b/.agents/plugins/marketplace.json"), - ) - .unwrap() - }) - .expect("repo-b marketplace should be listed"); - assert_eq!( - repo_b_marketplace.plugins, - vec![ConfiguredMarketplacePlugin { - id: "b-only-plugin@debug".to_string(), - name: "b-only-plugin".to_string(), - source: MarketplacePluginSource::Local { - path: AbsolutePathBuf::try_from(tmp.path().join("repo-b/from-b-only")).unwrap(), - }, - policy: MarketplacePluginPolicy { - installation: MarketplacePluginInstallPolicy::Available, - authentication: MarketplacePluginAuthPolicy::OnInstall, - products: None, - }, - interface: None, - installed: false, - enabled: false, - }] - ); - - let duplicate_plugin_count = marketplaces - .iter() - .flat_map(|marketplace| marketplace.plugins.iter()) - .filter(|plugin| plugin.name == "dup-plugin") - .count(); - assert_eq!(duplicate_plugin_count, 1); -} - -#[tokio::test] -async fn list_marketplaces_marks_configured_plugin_uninstalled_when_cache_is_missing() { - let tmp = tempfile::tempdir().unwrap(); - let repo_root = tmp.path().join("repo"); - fs::create_dir_all(repo_root.join(".git")).unwrap(); - fs::create_dir_all(repo_root.join(".agents/plugins")).unwrap(); - fs::write( - repo_root.join(".agents/plugins/marketplace.json"), - r#"{ - "name": "debug", - "plugins": [ - { - "name": "sample-plugin", - "source": { - "source": "local", - "path": "./sample-plugin" - } - } - ] -}"#, - ) - .unwrap(); - write_file( - &tmp.path().join(CONFIG_TOML_FILE), - r#"[features] -plugins = true - -[plugins."sample-plugin@debug"] -enabled = true -"#, - ); - - let config = load_config(tmp.path(), &repo_root).await; - let marketplaces = PluginsManager::new(tmp.path().to_path_buf()) - .list_marketplaces_for_config(&config, &[AbsolutePathBuf::try_from(repo_root).unwrap()]) - .unwrap() - .marketplaces; - - let marketplace = marketplaces - .into_iter() - .find(|marketplace| { - marketplace.path - == AbsolutePathBuf::try_from( - tmp.path().join("repo/.agents/plugins/marketplace.json"), - ) - .unwrap() - }) - .expect("expected repo marketplace entry"); - - assert_eq!( - marketplace, - ConfiguredMarketplace { - name: "debug".to_string(), - path: AbsolutePathBuf::try_from( - tmp.path().join("repo/.agents/plugins/marketplace.json"), - ) - .unwrap(), - interface: None, - plugins: vec![ConfiguredMarketplacePlugin { - id: "sample-plugin@debug".to_string(), - name: "sample-plugin".to_string(), - source: MarketplacePluginSource::Local { - path: AbsolutePathBuf::try_from(tmp.path().join("repo/sample-plugin")).unwrap(), - }, - policy: MarketplacePluginPolicy { - installation: MarketplacePluginInstallPolicy::Available, - authentication: MarketplacePluginAuthPolicy::OnInstall, - products: None, - }, - interface: None, - installed: false, - enabled: true, - }], - } - ); -} - -#[tokio::test] -async fn sync_plugins_from_remote_reconciles_cache_and_config() { - let tmp = tempfile::tempdir().unwrap(); - let curated_root = curated_plugins_repo_path(tmp.path()); - write_openai_curated_marketplace(&curated_root, &["linear", "gmail", "calendar"]); - write_curated_plugin_sha(tmp.path(), TEST_CURATED_PLUGIN_SHA); - write_plugin( - &tmp.path().join("plugins/cache/openai-curated"), - "linear/local", - "linear", - ); - write_plugin( - &tmp.path().join("plugins/cache/openai-curated"), - "gmail/local", - "gmail", - ); - write_plugin( - &tmp.path().join("plugins/cache/openai-curated"), - "calendar/local", - "calendar", - ); - write_file( - &tmp.path().join(CONFIG_TOML_FILE), - r#"[features] -plugins = true - -[plugins."linear@openai-curated"] -enabled = false - -[plugins."gmail@openai-curated"] -enabled = false - -[plugins."calendar@openai-curated"] -enabled = true -"#, - ); - - let server = MockServer::start().await; - Mock::given(method("GET")) - .and(path("/backend-api/plugins/list")) - .and(header("authorization", "Bearer Access Token")) - .and(header("chatgpt-account-id", "account_id")) - .respond_with(ResponseTemplate::new(200).set_body_string( - r#"[ - {"id":"1","name":"linear","marketplace_name":"openai-curated","version":"1.0.0","enabled":true}, - {"id":"2","name":"gmail","marketplace_name":"openai-curated","version":"1.0.0","enabled":false} -]"#, - )) - .mount(&server) - .await; - - let mut config = load_config(tmp.path(), tmp.path()).await; - config.chatgpt_base_url = format!("{}/backend-api/", server.uri()); - let manager = PluginsManager::new(tmp.path().to_path_buf()); - let result = manager - .sync_plugins_from_remote( - &config, - Some(&CodexAuth::create_dummy_chatgpt_auth_for_testing()), - /*additive_only*/ false, - ) - .await - .unwrap(); - - assert_eq!( - result, - RemotePluginSyncResult { - installed_plugin_ids: Vec::new(), - enabled_plugin_ids: vec!["linear@openai-curated".to_string()], - disabled_plugin_ids: Vec::new(), - uninstalled_plugin_ids: vec![ - "gmail@openai-curated".to_string(), - "calendar@openai-curated".to_string(), - ], - } - ); - - assert!( - tmp.path() - .join("plugins/cache/openai-curated/linear/local") - .is_dir() - ); - assert!( - !tmp.path() - .join("plugins/cache/openai-curated/gmail") - .exists() - ); - assert!( - !tmp.path() - .join("plugins/cache/openai-curated/calendar") - .exists() - ); - - let config = fs::read_to_string(tmp.path().join(CONFIG_TOML_FILE)).unwrap(); - assert!(config.contains(r#"[plugins."linear@openai-curated"]"#)); - assert!(config.contains("enabled = true")); - assert!(!config.contains(r#"[plugins."gmail@openai-curated"]"#)); - assert!(!config.contains(r#"[plugins."calendar@openai-curated"]"#)); - - let synced_config = load_config(tmp.path(), tmp.path()).await; - let curated_marketplace = manager - .list_marketplaces_for_config(&synced_config, &[]) - .unwrap() - .marketplaces - .into_iter() - .find(|marketplace| marketplace.name == OPENAI_CURATED_MARKETPLACE_NAME) - .unwrap(); - assert_eq!( - curated_marketplace - .plugins - .into_iter() - .map(|plugin| (plugin.id, plugin.installed, plugin.enabled)) - .collect::>(), - vec![ - ("linear@openai-curated".to_string(), true, true), - ("gmail@openai-curated".to_string(), false, false), - ("calendar@openai-curated".to_string(), false, false), - ] - ); -} - -#[tokio::test] -async fn sync_plugins_from_remote_additive_only_keeps_existing_plugins() { - let tmp = tempfile::tempdir().unwrap(); - let curated_root = curated_plugins_repo_path(tmp.path()); - write_openai_curated_marketplace(&curated_root, &["linear", "gmail", "calendar"]); - write_curated_plugin_sha(tmp.path(), TEST_CURATED_PLUGIN_SHA); - write_plugin( - &tmp.path().join("plugins/cache/openai-curated"), - "linear/local", - "linear", - ); - write_plugin( - &tmp.path().join("plugins/cache/openai-curated"), - "gmail/local", - "gmail", - ); - write_plugin( - &tmp.path().join("plugins/cache/openai-curated"), - "calendar/local", - "calendar", - ); - write_file( - &tmp.path().join(CONFIG_TOML_FILE), - r#"[features] -plugins = true - -[plugins."linear@openai-curated"] -enabled = false - -[plugins."gmail@openai-curated"] -enabled = false - -[plugins."calendar@openai-curated"] -enabled = true -"#, - ); - - let server = MockServer::start().await; - Mock::given(method("GET")) - .and(path("/backend-api/plugins/list")) - .and(header("authorization", "Bearer Access Token")) - .and(header("chatgpt-account-id", "account_id")) - .respond_with(ResponseTemplate::new(200).set_body_string( - r#"[ - {"id":"1","name":"linear","marketplace_name":"openai-curated","version":"1.0.0","enabled":true}, - {"id":"2","name":"gmail","marketplace_name":"openai-curated","version":"1.0.0","enabled":false} -]"#, - )) - .mount(&server) - .await; - - let mut config = load_config(tmp.path(), tmp.path()).await; - config.chatgpt_base_url = format!("{}/backend-api/", server.uri()); - let manager = PluginsManager::new(tmp.path().to_path_buf()); - let result = manager - .sync_plugins_from_remote( - &config, - Some(&CodexAuth::create_dummy_chatgpt_auth_for_testing()), - /*additive_only*/ true, - ) - .await - .unwrap(); - - assert_eq!( - result, - RemotePluginSyncResult { - installed_plugin_ids: Vec::new(), - enabled_plugin_ids: vec!["linear@openai-curated".to_string()], - disabled_plugin_ids: Vec::new(), - uninstalled_plugin_ids: Vec::new(), - } - ); - - assert!( - tmp.path() - .join("plugins/cache/openai-curated/linear/local") - .is_dir() - ); - assert!( - tmp.path() - .join("plugins/cache/openai-curated/gmail/local") - .is_dir() - ); - assert!( - tmp.path() - .join("plugins/cache/openai-curated/calendar/local") - .is_dir() - ); - - let config = fs::read_to_string(tmp.path().join(CONFIG_TOML_FILE)).unwrap(); - assert!(config.contains(r#"[plugins."linear@openai-curated"]"#)); - assert!(config.contains(r#"[plugins."gmail@openai-curated"]"#)); - assert!(config.contains(r#"[plugins."calendar@openai-curated"]"#)); - assert!(config.contains("enabled = true")); -} - -#[tokio::test] -async fn sync_plugins_from_remote_ignores_unknown_remote_plugins() { - let tmp = tempfile::tempdir().unwrap(); - let curated_root = curated_plugins_repo_path(tmp.path()); - write_openai_curated_marketplace(&curated_root, &["linear"]); - write_curated_plugin_sha(tmp.path(), TEST_CURATED_PLUGIN_SHA); - write_file( - &tmp.path().join(CONFIG_TOML_FILE), - r#"[features] -plugins = true - -[plugins."linear@openai-curated"] -enabled = false -"#, - ); - - let server = MockServer::start().await; - Mock::given(method("GET")) - .and(path("/backend-api/plugins/list")) - .respond_with(ResponseTemplate::new(200).set_body_string( - r#"[ - {"id":"1","name":"plugin-one","marketplace_name":"openai-curated","version":"1.0.0","enabled":true} -]"#, - )) - .mount(&server) - .await; - - let mut config = load_config(tmp.path(), tmp.path()).await; - config.chatgpt_base_url = format!("{}/backend-api/", server.uri()); - let manager = PluginsManager::new(tmp.path().to_path_buf()); - let result = manager - .sync_plugins_from_remote( - &config, - Some(&CodexAuth::create_dummy_chatgpt_auth_for_testing()), - /*additive_only*/ false, - ) - .await - .unwrap(); - - assert_eq!( - result, - RemotePluginSyncResult { - installed_plugin_ids: Vec::new(), - enabled_plugin_ids: Vec::new(), - disabled_plugin_ids: Vec::new(), - uninstalled_plugin_ids: vec!["linear@openai-curated".to_string()], - } - ); - let config = fs::read_to_string(tmp.path().join(CONFIG_TOML_FILE)).unwrap(); - assert!(!config.contains(r#"[plugins."linear@openai-curated"]"#)); - assert!( - !tmp.path() - .join("plugins/cache/openai-curated/linear") - .exists() - ); -} - -#[tokio::test] -async fn sync_plugins_from_remote_keeps_existing_plugins_when_install_fails() { - let tmp = tempfile::tempdir().unwrap(); - let curated_root = curated_plugins_repo_path(tmp.path()); - write_openai_curated_marketplace(&curated_root, &["linear", "gmail"]); - write_curated_plugin_sha(tmp.path(), TEST_CURATED_PLUGIN_SHA); - fs::remove_dir_all(curated_root.join("plugins/gmail")).unwrap(); - write_plugin( - &tmp.path().join("plugins/cache/openai-curated"), - "linear/local", - "linear", - ); - write_file( - &tmp.path().join(CONFIG_TOML_FILE), - r#"[features] -plugins = true - -[plugins."linear@openai-curated"] -enabled = false -"#, - ); - - let server = MockServer::start().await; - Mock::given(method("GET")) - .and(path("/backend-api/plugins/list")) - .respond_with(ResponseTemplate::new(200).set_body_string( - r#"[ - {"id":"1","name":"gmail","marketplace_name":"openai-curated","version":"1.0.0","enabled":true} -]"#, - )) - .mount(&server) - .await; - - let mut config = load_config(tmp.path(), tmp.path()).await; - config.chatgpt_base_url = format!("{}/backend-api/", server.uri()); - let manager = PluginsManager::new(tmp.path().to_path_buf()); - let err = manager - .sync_plugins_from_remote( - &config, - Some(&CodexAuth::create_dummy_chatgpt_auth_for_testing()), - /*additive_only*/ false, - ) - .await - .unwrap_err(); - - assert!(matches!( - err, - PluginRemoteSyncError::Store(PluginStoreError::Invalid(ref message)) - if message.contains("plugin source path is not a directory") - )); - assert!( - tmp.path() - .join("plugins/cache/openai-curated/linear/local") - .is_dir() - ); - assert!( - !tmp.path() - .join("plugins/cache/openai-curated/gmail") - .exists() - ); - - let config = fs::read_to_string(tmp.path().join(CONFIG_TOML_FILE)).unwrap(); - assert!(config.contains(r#"[plugins."linear@openai-curated"]"#)); - assert!(!config.contains(r#"[plugins."gmail@openai-curated"]"#)); - assert!(config.contains("enabled = false")); -} - -#[tokio::test] -async fn sync_plugins_from_remote_uses_first_duplicate_local_plugin_entry() { - let tmp = tempfile::tempdir().unwrap(); - let curated_root = curated_plugins_repo_path(tmp.path()); - write_curated_plugin_sha(tmp.path(), TEST_CURATED_PLUGIN_SHA); - fs::create_dir_all(curated_root.join(".agents/plugins")).unwrap(); - fs::write( - curated_root.join(".agents/plugins/marketplace.json"), - r#"{ - "name": "openai-curated", - "plugins": [ - { - "name": "gmail", - "source": { - "source": "local", - "path": "./plugins/gmail-first" - } - }, - { - "name": "gmail", - "source": { - "source": "local", - "path": "./plugins/gmail-second" - } - } - ] -}"#, - ) - .unwrap(); - write_plugin(&curated_root, "plugins/gmail-first", "gmail"); - write_plugin(&curated_root, "plugins/gmail-second", "gmail"); - fs::write(curated_root.join("plugins/gmail-first/marker.txt"), "first").unwrap(); - fs::write( - curated_root.join("plugins/gmail-second/marker.txt"), - "second", - ) - .unwrap(); - write_file( - &tmp.path().join(CONFIG_TOML_FILE), - r#"[features] -plugins = true -"#, - ); - - let server = MockServer::start().await; - Mock::given(method("GET")) - .and(path("/backend-api/plugins/list")) - .respond_with(ResponseTemplate::new(200).set_body_string( - r#"[ - {"id":"1","name":"gmail","marketplace_name":"openai-curated","version":"1.0.0","enabled":true} -]"#, - )) - .mount(&server) - .await; - - let mut config = load_config(tmp.path(), tmp.path()).await; - config.chatgpt_base_url = format!("{}/backend-api/", server.uri()); - let manager = PluginsManager::new(tmp.path().to_path_buf()); - let result = manager - .sync_plugins_from_remote( - &config, - Some(&CodexAuth::create_dummy_chatgpt_auth_for_testing()), - /*additive_only*/ false, - ) - .await - .unwrap(); - - assert_eq!( - result, - RemotePluginSyncResult { - installed_plugin_ids: vec!["gmail@openai-curated".to_string()], - enabled_plugin_ids: vec!["gmail@openai-curated".to_string()], - disabled_plugin_ids: Vec::new(), - uninstalled_plugin_ids: Vec::new(), - } - ); - assert_eq!( - fs::read_to_string(tmp.path().join(format!( - "plugins/cache/openai-curated/gmail/{TEST_CURATED_PLUGIN_SHA}/marker.txt" - ))) - .unwrap(), - "first" - ); -} - -#[tokio::test] -async fn featured_plugin_ids_for_config_uses_restriction_product_query_param() { - let tmp = tempfile::tempdir().unwrap(); - write_file( - &tmp.path().join(CONFIG_TOML_FILE), - r#"[features] -plugins = true -"#, - ); - - let server = MockServer::start().await; - Mock::given(method("GET")) - .and(path("/backend-api/plugins/featured")) - .and(query_param("platform", "chat")) - .and(header("authorization", "Bearer Access Token")) - .and(header("chatgpt-account-id", "account_id")) - .respond_with(ResponseTemplate::new(200).set_body_string(r#"["chat-plugin"]"#)) - .mount(&server) - .await; - - let mut config = load_config(tmp.path(), tmp.path()).await; - config.chatgpt_base_url = format!("{}/backend-api/", server.uri()); - let manager = PluginsManager::new_with_restriction_product( - tmp.path().to_path_buf(), - Some(Product::Chatgpt), - ); - - let featured_plugin_ids = manager - .featured_plugin_ids_for_config( - &config, - Some(&CodexAuth::create_dummy_chatgpt_auth_for_testing()), - ) - .await - .unwrap(); - - assert_eq!(featured_plugin_ids, vec!["chat-plugin".to_string()]); -} - -#[tokio::test] -async fn featured_plugin_ids_for_config_defaults_query_param_to_codex() { - let tmp = tempfile::tempdir().unwrap(); - write_file( - &tmp.path().join(CONFIG_TOML_FILE), - r#"[features] -plugins = true -"#, - ); - - let server = MockServer::start().await; - Mock::given(method("GET")) - .and(path("/backend-api/plugins/featured")) - .and(query_param("platform", "codex")) - .respond_with(ResponseTemplate::new(200).set_body_string(r#"["codex-plugin"]"#)) - .mount(&server) - .await; - - let mut config = load_config(tmp.path(), tmp.path()).await; - config.chatgpt_base_url = format!("{}/backend-api/", server.uri()); - let manager = PluginsManager::new_with_restriction_product( - tmp.path().to_path_buf(), - /*restriction_product*/ None, - ); - - let featured_plugin_ids = manager - .featured_plugin_ids_for_config(&config, /*auth*/ None) - .await - .unwrap(); - - assert_eq!(featured_plugin_ids, vec!["codex-plugin".to_string()]); -} - -#[test] -fn refresh_curated_plugin_cache_replaces_existing_local_version_with_sha() { - let tmp = tempfile::tempdir().unwrap(); - let curated_root = curated_plugins_repo_path(tmp.path()); - write_openai_curated_marketplace(&curated_root, &["slack"]); - write_curated_plugin_sha(tmp.path(), TEST_CURATED_PLUGIN_SHA); - let plugin_id = PluginId::new( - "slack".to_string(), - OPENAI_CURATED_MARKETPLACE_NAME.to_string(), - ) - .unwrap(); - write_plugin( - &tmp.path().join("plugins/cache/openai-curated"), - "slack/local", - "slack", - ); - - assert!( - refresh_curated_plugin_cache(tmp.path(), TEST_CURATED_PLUGIN_SHA, &[plugin_id]) - .expect("cache refresh should succeed") - ); - - assert!( - !tmp.path() - .join("plugins/cache/openai-curated/slack/local") - .exists() - ); - assert!( - tmp.path() - .join(format!( - "plugins/cache/openai-curated/slack/{TEST_CURATED_PLUGIN_SHA}" - )) - .is_dir() - ); -} - -#[test] -fn refresh_curated_plugin_cache_reinstalls_missing_configured_plugin_with_current_sha() { - let tmp = tempfile::tempdir().unwrap(); - let curated_root = curated_plugins_repo_path(tmp.path()); - write_openai_curated_marketplace(&curated_root, &["slack"]); - write_curated_plugin_sha(tmp.path(), TEST_CURATED_PLUGIN_SHA); - let plugin_id = PluginId::new( - "slack".to_string(), - OPENAI_CURATED_MARKETPLACE_NAME.to_string(), - ) - .unwrap(); - - assert!( - refresh_curated_plugin_cache(tmp.path(), TEST_CURATED_PLUGIN_SHA, &[plugin_id]) - .expect("cache refresh should recreate missing configured plugin") - ); - - assert!( - tmp.path() - .join(format!( - "plugins/cache/openai-curated/slack/{TEST_CURATED_PLUGIN_SHA}" - )) - .is_dir() - ); -} - -#[test] -fn curated_plugin_ids_from_config_keys_reads_latest_codex_home_user_config() { - let tmp = tempfile::tempdir().unwrap(); - write_file( - &tmp.path().join(CONFIG_TOML_FILE), - r#"[features] -plugins = true - -[plugins."slack@openai-curated"] -enabled = true - -[plugins."sample@debug"] -enabled = true -"#, - ); - - assert_eq!( - configured_curated_plugin_ids_from_codex_home(tmp.path()) - .into_iter() - .map(|plugin_id| plugin_id.as_key()) - .collect::>(), - vec!["slack@openai-curated".to_string()] - ); - - write_file( - &tmp.path().join(CONFIG_TOML_FILE), - r#"[features] -plugins = true -"#, - ); - - assert_eq!( - configured_curated_plugin_ids_from_codex_home(tmp.path()), - Vec::::new() - ); -} - -#[test] -fn refresh_curated_plugin_cache_returns_false_when_configured_plugins_are_current() { - let tmp = tempfile::tempdir().unwrap(); - let curated_root = curated_plugins_repo_path(tmp.path()); - write_openai_curated_marketplace(&curated_root, &["slack"]); - let plugin_id = PluginId::new( - "slack".to_string(), - OPENAI_CURATED_MARKETPLACE_NAME.to_string(), - ) - .unwrap(); - write_plugin( - &tmp.path().join("plugins/cache/openai-curated"), - &format!("slack/{TEST_CURATED_PLUGIN_SHA}"), - "slack", - ); - - assert!( - !refresh_curated_plugin_cache(tmp.path(), TEST_CURATED_PLUGIN_SHA, &[plugin_id]) - .expect("cache refresh should be a no-op when configured plugins are current") - ); -} - -#[test] -fn refresh_non_curated_plugin_cache_replaces_existing_local_version_with_manifest_version() { - let tmp = tempfile::tempdir().unwrap(); - let repo_root = tmp.path().join("repo"); - fs::create_dir_all(repo_root.join(".git")).unwrap(); - fs::create_dir_all(repo_root.join(".agents/plugins")).unwrap(); - write_plugin_with_version(&repo_root, "sample-plugin", "sample-plugin", Some("1.2.3")); - write_file( - &repo_root.join(".agents/plugins/marketplace.json"), - r#"{ - "name": "debug", - "plugins": [ - { - "name": "sample-plugin", - "source": { - "source": "local", - "path": "./sample-plugin" - } - } - ] -}"#, - ); - write_plugin( - &tmp.path().join("plugins/cache/debug"), - "sample-plugin/local", - "sample-plugin", - ); - write_file( - &tmp.path().join(CONFIG_TOML_FILE), - r#"[features] -plugins = true - -[plugins."sample-plugin@debug"] -enabled = true -"#, - ); - - assert!( - refresh_non_curated_plugin_cache( - tmp.path(), - &[AbsolutePathBuf::try_from(repo_root).unwrap()], - ) - .expect("cache refresh should succeed") - ); - - assert!( - !tmp.path() - .join("plugins/cache/debug/sample-plugin/local") - .exists() - ); - assert!( - tmp.path() - .join("plugins/cache/debug/sample-plugin/1.2.3") - .is_dir() - ); -} - -#[test] -fn refresh_non_curated_plugin_cache_reinstalls_missing_configured_plugin_with_manifest_version() { - let tmp = tempfile::tempdir().unwrap(); - let repo_root = tmp.path().join("repo"); - fs::create_dir_all(repo_root.join(".git")).unwrap(); - fs::create_dir_all(repo_root.join(".agents/plugins")).unwrap(); - write_plugin_with_version(&repo_root, "sample-plugin", "sample-plugin", Some("1.2.3")); - write_file( - &repo_root.join(".agents/plugins/marketplace.json"), - r#"{ - "name": "debug", - "plugins": [ - { - "name": "sample-plugin", - "source": { - "source": "local", - "path": "./sample-plugin" - } - } - ] -}"#, - ); - write_file( - &tmp.path().join(CONFIG_TOML_FILE), - r#"[features] -plugins = true - -[plugins."sample-plugin@debug"] -enabled = true -"#, - ); - - assert!( - refresh_non_curated_plugin_cache( - tmp.path(), - &[AbsolutePathBuf::try_from(repo_root).unwrap()], - ) - .expect("cache refresh should reinstall missing configured plugin") - ); - - assert!( - tmp.path() - .join("plugins/cache/debug/sample-plugin/1.2.3") - .is_dir() - ); -} - -#[test] -fn refresh_non_curated_plugin_cache_refreshes_configured_git_source() { - let tmp = tempfile::tempdir().unwrap(); - let repo_root = tmp.path().join("repo"); - let remote_repo = tmp.path().join("remote-plugin-repo"); - let remote_repo_url = url::Url::from_directory_path(&remote_repo) - .unwrap() - .to_string(); - fs::create_dir_all(repo_root.join(".git")).unwrap(); - write_plugin_with_version( - &remote_repo, - "plugins/sample-plugin", - "sample-plugin", - Some("1.2.3"), - ); - init_git_repo(&remote_repo); - write_file( - &repo_root.join(".agents/plugins/marketplace.json"), - &format!( - r#"{{ - "name": "debug", - "plugins": [ - {{ - "name": "sample-plugin", - "source": {{ - "source": "git-subdir", - "url": "{remote_repo_url}", - "path": "plugins/sample-plugin" - }} - }} - ] -}}"# - ), - ); - write_file( - &tmp.path().join(CONFIG_TOML_FILE), - r#"[features] -plugins = true - -[plugins."sample-plugin@debug"] -enabled = true -"#, - ); - - assert!( - refresh_non_curated_plugin_cache( - tmp.path(), - &[AbsolutePathBuf::try_from(repo_root).unwrap()], - ) - .expect("cache refresh should materialize configured Git plugin") - ); - - assert!( - tmp.path() - .join("plugins/cache/debug/sample-plugin/1.2.3") - .is_dir() - ); -} - -#[test] -fn refresh_non_curated_plugin_cache_returns_false_when_configured_plugins_are_current() { - let tmp = tempfile::tempdir().unwrap(); - let repo_root = tmp.path().join("repo"); - fs::create_dir_all(repo_root.join(".git")).unwrap(); - fs::create_dir_all(repo_root.join(".agents/plugins")).unwrap(); - write_plugin_with_version(&repo_root, "sample-plugin", "sample-plugin", Some("1.2.3")); - write_file( - &repo_root.join(".agents/plugins/marketplace.json"), - r#"{ - "name": "debug", - "plugins": [ - { - "name": "sample-plugin", - "source": { - "source": "local", - "path": "./sample-plugin" - } - } - ] -}"#, - ); - write_plugin_with_version( - &tmp.path().join("plugins/cache/debug"), - "sample-plugin/1.2.3", - "sample-plugin", - Some("1.2.3"), - ); - write_file( - &tmp.path().join(CONFIG_TOML_FILE), - r#"[features] -plugins = true - -[plugins."sample-plugin@debug"] -enabled = true -"#, - ); - - assert!( - !refresh_non_curated_plugin_cache( - tmp.path(), - &[AbsolutePathBuf::try_from(repo_root).unwrap()], - ) - .expect("cache refresh should be a no-op when configured plugins are current") - ); -} - -#[test] -fn refresh_non_curated_plugin_cache_force_reinstalls_current_local_version() { - let tmp = tempfile::tempdir().unwrap(); - let repo_root = tmp.path().join("repo"); - fs::create_dir_all(repo_root.join(".git")).unwrap(); - fs::create_dir_all(repo_root.join(".agents/plugins")).unwrap(); - write_plugin(&repo_root, "sample-plugin", "sample-plugin"); - fs::write(repo_root.join("sample-plugin/skills/SKILL.md"), "new skill").unwrap(); - write_file( - &repo_root.join(".agents/plugins/marketplace.json"), - r#"{ - "name": "debug", - "plugins": [ - { - "name": "sample-plugin", - "source": { - "source": "local", - "path": "./sample-plugin" - } - } - ] -}"#, - ); - write_plugin( - &tmp.path().join("plugins/cache/debug"), - "sample-plugin/local", - "sample-plugin", - ); - fs::write( - tmp.path() - .join("plugins/cache/debug/sample-plugin/local/skills/SKILL.md"), - "old skill", - ) - .unwrap(); - write_file( - &tmp.path().join(CONFIG_TOML_FILE), - r#"[features] -plugins = true - -[plugins."sample-plugin@debug"] -enabled = true -"#, - ); - - assert!( - refresh_non_curated_plugin_cache_force_reinstall( - tmp.path(), - &[AbsolutePathBuf::try_from(repo_root).unwrap()], - ) - .expect("cache refresh should reinstall unchanged local version") - ); - - assert_eq!( - fs::read_to_string( - tmp.path() - .join("plugins/cache/debug/sample-plugin/local/skills/SKILL.md") - ) - .unwrap(), - "new skill" - ); -} - -#[test] -fn refresh_non_curated_plugin_cache_ignores_invalid_unconfigured_plugin_versions() { - let tmp = tempfile::tempdir().unwrap(); - let repo_root = tmp.path().join("repo"); - fs::create_dir_all(repo_root.join(".git")).unwrap(); - fs::create_dir_all(repo_root.join(".agents/plugins")).unwrap(); - write_plugin_with_version(&repo_root, "sample-plugin", "sample-plugin", Some("1.2.3")); - write_plugin_with_version(&repo_root, "broken-plugin", "broken-plugin", Some(" ")); - write_file( - &repo_root.join(".agents/plugins/marketplace.json"), - r#"{ - "name": "debug", - "plugins": [ - { - "name": "sample-plugin", - "source": { - "source": "local", - "path": "./sample-plugin" - } - }, - { - "name": "broken-plugin", - "source": { - "source": "local", - "path": "./broken-plugin" - } - } - ] -}"#, - ); - write_file( - &tmp.path().join(CONFIG_TOML_FILE), - r#"[features] -plugins = true - -[plugins."sample-plugin@debug"] -enabled = true -"#, - ); - - assert!( - refresh_non_curated_plugin_cache( - tmp.path(), - &[AbsolutePathBuf::try_from(repo_root).unwrap()], - ) - .expect("cache refresh should ignore unrelated invalid plugin manifests") - ); - - assert!( - tmp.path() - .join("plugins/cache/debug/sample-plugin/1.2.3") - .is_dir() - ); -} - -#[tokio::test] -async fn load_plugins_ignores_project_config_files() { - let codex_home = TempDir::new().unwrap(); - let project_root = codex_home.path().join("project"); - let plugin_root = codex_home - .path() - .join("plugins/cache") - .join("test/sample/local"); - - write_file( - &plugin_root.join(".codex-plugin/plugin.json"), - r#"{"name":"sample"}"#, - ); - write_file( - &project_root.join(".codex/config.toml"), - &plugin_config_toml(/*enabled*/ true, /*plugins_feature_enabled*/ true), - ); - - let stack = ConfigLayerStack::new( - vec![ConfigLayerEntry::new( - ConfigLayerSource::Project { - dot_codex_folder: AbsolutePathBuf::try_from(project_root.join(".codex")).unwrap(), - }, - toml::from_str(&plugin_config_toml( - /*enabled*/ true, /*plugins_feature_enabled*/ true, - )) - .expect("project config should parse"), - )], - ConfigRequirements::default(), - ConfigRequirementsToml::default(), - ) - .expect("config layer stack should build"); - - let outcome = load_plugins_from_layer_stack( - &stack, - &PluginStore::new(codex_home.path().to_path_buf()), - Some(Product::Codex), - ) - .await; - - assert_eq!(outcome, PluginLoadOutcome::default()); -} diff --git a/vendor/codex/codex-rs/core/src/plugins/marketplace_add.rs b/vendor/codex/codex-rs/core/src/plugins/marketplace_add.rs deleted file mode 100644 index a03a2134..00000000 --- a/vendor/codex/codex-rs/core/src/plugins/marketplace_add.rs +++ /dev/null @@ -1,407 +0,0 @@ -use super::OPENAI_CURATED_MARKETPLACE_NAME; -use super::marketplace_install_root; -use codex_utils_absolute_path::AbsolutePathBuf; -use std::fs; -use std::path::Path; -use std::path::PathBuf; -use tempfile::Builder; - -mod install; -mod metadata; -mod source; - -use install::clone_git_source; -use install::ensure_marketplace_destination_is_inside_install_root; -use install::marketplace_staging_root; -use install::replace_marketplace_root; -use install::safe_marketplace_dir_name; -use metadata::MarketplaceInstallMetadata; -use metadata::find_marketplace_root_by_name; -use metadata::installed_marketplace_root_for_source; -use metadata::record_added_marketplace_entry; -use source::MarketplaceSource; -pub(crate) use source::parse_marketplace_source; -use source::stage_marketplace_source; -use source::validate_marketplace_source_root; - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct MarketplaceAddRequest { - pub source: String, - pub ref_name: Option, - pub sparse_paths: Vec, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct MarketplaceAddOutcome { - pub marketplace_name: String, - pub source_display: String, - pub installed_root: AbsolutePathBuf, - pub already_added: bool, -} - -#[derive(Debug, thiserror::Error)] -pub enum MarketplaceAddError { - #[error("{0}")] - InvalidRequest(String), - #[error("{0}")] - Internal(String), -} - -pub async fn add_marketplace( - codex_home: PathBuf, - request: MarketplaceAddRequest, -) -> Result { - tokio::task::spawn_blocking(move || add_marketplace_sync(codex_home.as_path(), request)) - .await - .map_err(|err| MarketplaceAddError::Internal(format!("failed to add marketplace: {err}")))? -} - -pub fn is_local_marketplace_source( - source: &str, - explicit_ref: Option, -) -> Result { - Ok(matches!( - parse_marketplace_source(source, explicit_ref)?, - source::MarketplaceSource::Local { .. } - )) -} - -fn add_marketplace_sync( - codex_home: &Path, - request: MarketplaceAddRequest, -) -> Result { - add_marketplace_sync_with_cloner(codex_home, request, clone_git_source) -} - -fn add_marketplace_sync_with_cloner( - codex_home: &Path, - request: MarketplaceAddRequest, - clone_source: F, -) -> Result -where - F: Fn(&str, Option<&str>, &[String], &Path) -> Result<(), MarketplaceAddError>, -{ - let MarketplaceAddRequest { - source, - ref_name, - sparse_paths, - } = request; - let source = parse_marketplace_source(&source, ref_name)?; - if !sparse_paths.is_empty() && !matches!(source, MarketplaceSource::Git { .. }) { - return Err(MarketplaceAddError::InvalidRequest( - "--sparse is only supported for git marketplace sources".to_string(), - )); - } - - let install_root = marketplace_install_root(codex_home); - fs::create_dir_all(&install_root).map_err(|err| { - MarketplaceAddError::Internal(format!( - "failed to create marketplace install directory {}: {err}", - install_root.display() - )) - })?; - - let install_metadata = MarketplaceInstallMetadata::from_source(&source, &sparse_paths); - if let Some(existing_root) = - installed_marketplace_root_for_source(codex_home, &install_root, &install_metadata)? - { - let marketplace_name = validate_marketplace_source_root(&existing_root)?; - record_added_marketplace_entry(codex_home, &marketplace_name, &install_metadata)?; - return Ok(MarketplaceAddOutcome { - marketplace_name, - source_display: source.display(), - installed_root: AbsolutePathBuf::try_from(existing_root).map_err(|err| { - MarketplaceAddError::Internal(format!( - "failed to resolve installed marketplace root: {err}" - )) - })?, - already_added: true, - }); - } - - if let MarketplaceSource::Local { path } = &source { - let marketplace_name = validate_marketplace_source_root(path)?; - if marketplace_name == OPENAI_CURATED_MARKETPLACE_NAME { - return Err(MarketplaceAddError::InvalidRequest(format!( - "marketplace '{OPENAI_CURATED_MARKETPLACE_NAME}' is reserved and cannot be added from {}", - source.display() - ))); - } - if find_marketplace_root_by_name(codex_home, &install_root, &marketplace_name)?.is_some() { - return Err(MarketplaceAddError::InvalidRequest(format!( - "marketplace '{marketplace_name}' is already added from a different source; remove it before adding {}", - source.display() - ))); - } - record_added_marketplace_entry(codex_home, &marketplace_name, &install_metadata)?; - return Ok(MarketplaceAddOutcome { - marketplace_name, - source_display: source.display(), - installed_root: AbsolutePathBuf::try_from(path.clone()).map_err(|err| { - MarketplaceAddError::Internal(format!( - "failed to resolve installed marketplace root: {err}" - )) - })?, - already_added: false, - }); - } - - let staging_root = marketplace_staging_root(&install_root); - fs::create_dir_all(&staging_root).map_err(|err| { - MarketplaceAddError::Internal(format!( - "failed to create marketplace staging directory {}: {err}", - staging_root.display() - )) - })?; - let staged_root = Builder::new() - .prefix("marketplace-add-") - .tempdir_in(&staging_root) - .map_err(|err| { - MarketplaceAddError::Internal(format!( - "failed to create temporary marketplace directory in {}: {err}", - staging_root.display() - )) - })?; - let staged_root = staged_root.keep(); - - stage_marketplace_source(&source, &sparse_paths, &staged_root, clone_source)?; - - let marketplace_name = validate_marketplace_source_root(&staged_root)?; - if marketplace_name == OPENAI_CURATED_MARKETPLACE_NAME { - return Err(MarketplaceAddError::InvalidRequest(format!( - "marketplace '{OPENAI_CURATED_MARKETPLACE_NAME}' is reserved and cannot be added from {}", - source.display() - ))); - } - - let destination = install_root.join(safe_marketplace_dir_name(&marketplace_name)?); - ensure_marketplace_destination_is_inside_install_root(&install_root, &destination)?; - if destination.exists() { - return Err(MarketplaceAddError::InvalidRequest(format!( - "marketplace '{marketplace_name}' is already added from a different source; remove it before adding {}", - source.display() - ))); - } - - replace_marketplace_root(&staged_root, &destination).map_err(|err| { - MarketplaceAddError::Internal(format!( - "failed to install marketplace at {}: {err}", - destination.display() - )) - })?; - if let Err(err) = - record_added_marketplace_entry(codex_home, &marketplace_name, &install_metadata) - { - if let Err(rollback_err) = fs::rename(&destination, &staged_root) { - return Err(MarketplaceAddError::Internal(format!( - "{err}; additionally failed to roll back installed marketplace at {}: {rollback_err}", - destination.display() - ))); - } - return Err(err); - } - - Ok(MarketplaceAddOutcome { - marketplace_name, - source_display: source.display(), - installed_root: AbsolutePathBuf::try_from(destination).map_err(|err| { - MarketplaceAddError::Internal(format!( - "failed to resolve installed marketplace root: {err}" - )) - })?, - already_added: false, - }) -} - -#[cfg(test)] -mod tests { - use super::*; - use anyhow::Result; - use pretty_assertions::assert_eq; - use tempfile::TempDir; - - #[test] - fn add_marketplace_sync_installs_marketplace_and_updates_config() -> Result<()> { - let codex_home = TempDir::new()?; - let source_root = TempDir::new()?; - write_marketplace_source(source_root.path(), "remote copy")?; - - let result = add_marketplace_sync_with_cloner( - codex_home.path(), - MarketplaceAddRequest { - source: "https://github.com/owner/repo.git".to_string(), - ref_name: None, - sparse_paths: Vec::new(), - }, - |_url, _ref_name, _sparse_paths, destination| { - copy_dir_all(source_root.path(), destination) - .map_err(|err| MarketplaceAddError::Internal(err.to_string())) - }, - )?; - - assert_eq!(result.marketplace_name, "debug"); - assert_eq!(result.source_display, "https://github.com/owner/repo.git"); - assert!(!result.already_added); - assert!( - result - .installed_root - .as_path() - .join(".agents/plugins/marketplace.json") - .is_file() - ); - - let config = fs::read_to_string(codex_home.path().join(codex_config::CONFIG_TOML_FILE))?; - assert!(config.contains("[marketplaces.debug]")); - assert!(config.contains("source_type = \"git\"")); - assert!(config.contains("source = \"https://github.com/owner/repo.git\"")); - Ok(()) - } - - #[test] - fn add_marketplace_sync_installs_local_directory_source_and_updates_config() -> Result<()> { - let codex_home = TempDir::new()?; - let source_root = TempDir::new()?; - write_marketplace_source(source_root.path(), "local copy")?; - - let result = add_marketplace_sync_with_cloner( - codex_home.path(), - MarketplaceAddRequest { - source: source_root.path().display().to_string(), - ref_name: None, - sparse_paths: Vec::new(), - }, - |_url, _ref_name, _sparse_paths, _destination| { - panic!("git cloner should not be called for local marketplace sources") - }, - )?; - - let expected_source = source_root.path().canonicalize()?.display().to_string(); - assert_eq!(result.marketplace_name, "debug"); - assert_eq!(result.source_display, expected_source); - assert_eq!( - result.installed_root.as_path(), - source_root.path().canonicalize()? - ); - assert!(!result.already_added); - assert!( - !marketplace_install_root(codex_home.path()) - .join("debug") - .exists() - ); - - let config = fs::read_to_string(codex_home.path().join(codex_config::CONFIG_TOML_FILE))?; - let config: toml::Value = toml::from_str(&config)?; - assert_eq!( - config["marketplaces"]["debug"]["source_type"].as_str(), - Some("local") - ); - assert_eq!( - config["marketplaces"]["debug"]["source"].as_str(), - Some(expected_source.as_str()) - ); - Ok(()) - } - - #[test] - fn add_marketplace_sync_rejects_sparse_checkout_for_local_directory_source() -> Result<()> { - let codex_home = TempDir::new()?; - let source_root = TempDir::new()?; - write_marketplace_source(source_root.path(), "local copy")?; - - let err = add_marketplace_sync_with_cloner( - codex_home.path(), - MarketplaceAddRequest { - source: source_root.path().display().to_string(), - ref_name: None, - sparse_paths: vec![".agents".to_string()], - }, - |_url, _ref_name, _sparse_paths, _destination| { - panic!("git cloner should not be called for local marketplace sources") - }, - ) - .unwrap_err(); - - assert_eq!( - err.to_string(), - "--sparse is only supported for git marketplace sources" - ); - assert!( - !codex_home - .path() - .join(codex_config::CONFIG_TOML_FILE) - .exists() - ); - Ok(()) - } - - #[test] - fn add_marketplace_sync_treats_existing_local_directory_source_as_already_added() -> Result<()> - { - let codex_home = TempDir::new()?; - let source_root = TempDir::new()?; - write_marketplace_source(source_root.path(), "local copy")?; - - let request = MarketplaceAddRequest { - source: source_root.path().display().to_string(), - ref_name: None, - sparse_paths: Vec::new(), - }; - let first_result = add_marketplace_sync_with_cloner(codex_home.path(), request.clone(), { - |_url, _ref_name, _sparse_paths, _destination| { - panic!("git cloner should not be called for local marketplace sources") - } - })?; - let second_result = add_marketplace_sync_with_cloner(codex_home.path(), request, { - |_url, _ref_name, _sparse_paths, _destination| { - panic!("git cloner should not be called for local marketplace sources") - } - })?; - - assert!(!first_result.already_added); - assert!(second_result.already_added); - assert_eq!(second_result.installed_root, first_result.installed_root); - - Ok(()) - } - - fn write_marketplace_source(source: &Path, marker: &str) -> std::io::Result<()> { - fs::create_dir_all(source.join(".agents/plugins"))?; - fs::create_dir_all(source.join("plugins/sample/.codex-plugin"))?; - fs::write( - source.join(".agents/plugins/marketplace.json"), - r#"{ - "name": "debug", - "plugins": [ - { - "name": "sample", - "source": { - "source": "local", - "path": "./plugins/sample" - } - } - ] -}"#, - )?; - fs::write( - source.join("plugins/sample/.codex-plugin/plugin.json"), - r#"{"name":"sample"}"#, - )?; - fs::write(source.join("plugins/sample/marker.txt"), marker)?; - Ok(()) - } - - fn copy_dir_all(source: &Path, destination: &Path) -> std::io::Result<()> { - fs::create_dir_all(destination)?; - for entry in fs::read_dir(source)? { - let entry = entry?; - let source_path = entry.path(); - let destination_path = destination.join(entry.file_name()); - if source_path.is_dir() { - copy_dir_all(&source_path, &destination_path)?; - } else { - fs::copy(&source_path, &destination_path)?; - } - } - Ok(()) - } -} diff --git a/vendor/codex/codex-rs/core/src/plugins/marketplace_add/install.rs b/vendor/codex/codex-rs/core/src/plugins/marketplace_add/install.rs deleted file mode 100644 index 1ecfa050..00000000 --- a/vendor/codex/codex-rs/core/src/plugins/marketplace_add/install.rs +++ /dev/null @@ -1,137 +0,0 @@ -use super::MarketplaceAddError; -use std::fs; -use std::path::Path; -use std::path::PathBuf; -use std::process::Command; - -pub(super) fn clone_git_source( - url: &str, - ref_name: Option<&str>, - sparse_paths: &[String], - destination: &Path, -) -> Result<(), MarketplaceAddError> { - let destination_string = destination.to_string_lossy().to_string(); - if sparse_paths.is_empty() { - run_git( - &["clone", url, destination_string.as_str()], - /*cwd*/ None, - )?; - if let Some(ref_name) = ref_name { - run_git( - &["checkout", ref_name], - Some(Path::new(&destination_string)), - )?; - } - return Ok(()); - } - - run_git( - &[ - "clone", - "--filter=blob:none", - "--no-checkout", - url, - destination_string.as_str(), - ], - /*cwd*/ None, - )?; - let mut sparse_args = vec!["sparse-checkout", "set"]; - sparse_args.extend(sparse_paths.iter().map(String::as_str)); - run_git(&sparse_args, Some(destination))?; - run_git(&["checkout", ref_name.unwrap_or("HEAD")], Some(destination))?; - Ok(()) -} - -pub(super) fn safe_marketplace_dir_name( - marketplace_name: &str, -) -> Result { - let safe = marketplace_name - .chars() - .map(|ch| { - if ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | '.') { - ch - } else { - '-' - } - }) - .collect::(); - let safe = safe.trim_matches('.').to_string(); - if safe.is_empty() || safe == ".." { - return Err(MarketplaceAddError::InvalidRequest(format!( - "marketplace name '{marketplace_name}' cannot be used as an install directory" - ))); - } - Ok(safe) -} - -pub(super) fn ensure_marketplace_destination_is_inside_install_root( - install_root: &Path, - destination: &Path, -) -> Result<(), MarketplaceAddError> { - let install_root = install_root.canonicalize().map_err(|err| { - MarketplaceAddError::Internal(format!( - "failed to resolve marketplace install root {}: {err}", - install_root.display() - )) - })?; - let destination_parent = destination - .parent() - .ok_or_else(|| { - MarketplaceAddError::Internal("marketplace destination has no parent".to_string()) - })? - .canonicalize() - .map_err(|err| { - MarketplaceAddError::Internal(format!( - "failed to resolve marketplace destination parent {}: {err}", - destination.display() - )) - })?; - if !destination_parent.starts_with(&install_root) { - return Err(MarketplaceAddError::InvalidRequest(format!( - "marketplace destination {} is outside install root {}", - destination.display(), - install_root.display() - ))); - } - Ok(()) -} - -pub(super) fn replace_marketplace_root( - staged_root: &Path, - destination: &Path, -) -> std::io::Result<()> { - if let Some(parent) = destination.parent() { - fs::create_dir_all(parent)?; - } - fs::rename(staged_root, destination) -} - -pub(super) fn marketplace_staging_root(install_root: &Path) -> PathBuf { - install_root.join(".staging") -} - -fn run_git(args: &[&str], cwd: Option<&Path>) -> Result<(), MarketplaceAddError> { - let mut command = Command::new("git"); - command.args(args); - command.env("GIT_TERMINAL_PROMPT", "0"); - if let Some(cwd) = cwd { - command.current_dir(cwd); - } - - let output = command.output().map_err(|err| { - MarketplaceAddError::Internal(format!("failed to run git {}: {err}", args.join(" "))) - })?; - if output.status.success() { - return Ok(()); - } - - let stderr = String::from_utf8_lossy(&output.stderr); - let stdout = String::from_utf8_lossy(&output.stdout); - Err(MarketplaceAddError::Internal(format!( - "git {} failed with status {}\nstdout:\n{}\nstderr:\n{}", - args.join(" "), - output.status, - stdout.trim(), - stderr.trim() - ))) -} diff --git a/vendor/codex/codex-rs/core/src/plugins/marketplace_add/metadata.rs b/vendor/codex/codex-rs/core/src/plugins/marketplace_add/metadata.rs deleted file mode 100644 index 06b5e395..00000000 --- a/vendor/codex/codex-rs/core/src/plugins/marketplace_add/metadata.rs +++ /dev/null @@ -1,315 +0,0 @@ -use super::MarketplaceAddError; -use super::source::MarketplaceSource; -use crate::plugins::installed_marketplaces::resolve_configured_marketplace_root; -use codex_config::CONFIG_TOML_FILE; -use codex_config::MarketplaceConfigUpdate; -use codex_config::record_user_marketplace; -use codex_core_plugins::marketplace::validate_marketplace_root; -use std::fs; -use std::io::ErrorKind; -use std::path::Path; -use std::path::PathBuf; -use std::time::SystemTime; -use std::time::UNIX_EPOCH; - -#[derive(Debug, Clone, PartialEq, Eq)] -pub(super) struct MarketplaceInstallMetadata { - source: InstalledMarketplaceSource, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -enum InstalledMarketplaceSource { - Git { - url: String, - ref_name: Option, - sparse_paths: Vec, - }, - Local { - path: String, - }, -} - -pub(super) fn record_added_marketplace_entry( - codex_home: &Path, - marketplace_name: &str, - install_metadata: &MarketplaceInstallMetadata, -) -> Result<(), MarketplaceAddError> { - let source = install_metadata.config_source(); - let timestamp = utc_timestamp_now()?; - let update = MarketplaceConfigUpdate { - last_updated: ×tamp, - last_revision: None, - source_type: install_metadata.config_source_type(), - source: &source, - ref_name: install_metadata.ref_name(), - sparse_paths: install_metadata.sparse_paths(), - }; - - record_user_marketplace(codex_home, marketplace_name, &update).map_err(|err| { - MarketplaceAddError::Internal(format!( - "failed to add marketplace '{marketplace_name}' to user config.toml: {err}" - )) - }) -} - -pub(super) fn installed_marketplace_root_for_source( - codex_home: &Path, - install_root: &Path, - install_metadata: &MarketplaceInstallMetadata, -) -> Result, MarketplaceAddError> { - let config_path = codex_home.join(CONFIG_TOML_FILE); - let config = match fs::read_to_string(&config_path) { - Ok(config) => config, - Err(err) if err.kind() == ErrorKind::NotFound => return Ok(None), - Err(err) => { - return Err(MarketplaceAddError::Internal(format!( - "failed to read user config {}: {err}", - config_path.display() - ))); - } - }; - let config: toml::Value = toml::from_str(&config).map_err(|err| { - MarketplaceAddError::Internal(format!( - "failed to parse user config {}: {err}", - config_path.display() - )) - })?; - let Some(marketplaces) = config.get("marketplaces").and_then(toml::Value::as_table) else { - return Ok(None); - }; - - for (marketplace_name, marketplace) in marketplaces { - if !install_metadata.matches_config(marketplace) { - continue; - } - let Some(root) = - resolve_configured_marketplace_root(marketplace_name, marketplace, install_root) - else { - continue; - }; - if validate_marketplace_root(&root).is_ok() { - return Ok(Some(root)); - } - } - - Ok(None) -} - -pub(super) fn find_marketplace_root_by_name( - codex_home: &Path, - install_root: &Path, - marketplace_name: &str, -) -> Result, MarketplaceAddError> { - let config_path = codex_home.join(CONFIG_TOML_FILE); - let config = match fs::read_to_string(&config_path) { - Ok(config) => config, - Err(err) if err.kind() == ErrorKind::NotFound => return Ok(None), - Err(err) => { - return Err(MarketplaceAddError::Internal(format!( - "failed to read user config {}: {err}", - config_path.display() - ))); - } - }; - let config: toml::Value = toml::from_str(&config).map_err(|err| { - MarketplaceAddError::Internal(format!( - "failed to parse user config {}: {err}", - config_path.display() - )) - })?; - let Some(marketplace) = config - .get("marketplaces") - .and_then(toml::Value::as_table) - .and_then(|marketplaces| marketplaces.get(marketplace_name)) - else { - return Ok(None); - }; - - let Some(root) = - resolve_configured_marketplace_root(marketplace_name, marketplace, install_root) - else { - return Ok(None); - }; - if validate_marketplace_root(&root).is_ok() { - Ok(Some(root)) - } else { - Ok(None) - } -} - -impl MarketplaceInstallMetadata { - pub(super) fn from_source(source: &MarketplaceSource, sparse_paths: &[String]) -> Self { - let source = match source { - MarketplaceSource::Git { url, ref_name } => InstalledMarketplaceSource::Git { - url: url.clone(), - ref_name: ref_name.clone(), - sparse_paths: sparse_paths.to_vec(), - }, - MarketplaceSource::Local { path } => InstalledMarketplaceSource::Local { - path: path.display().to_string(), - }, - }; - Self { source } - } - - fn config_source_type(&self) -> &'static str { - match &self.source { - InstalledMarketplaceSource::Git { .. } => "git", - InstalledMarketplaceSource::Local { .. } => "local", - } - } - - fn config_source(&self) -> String { - match &self.source { - InstalledMarketplaceSource::Git { url, .. } => url.clone(), - InstalledMarketplaceSource::Local { path } => path.clone(), - } - } - - fn ref_name(&self) -> Option<&str> { - match &self.source { - InstalledMarketplaceSource::Git { ref_name, .. } => ref_name.as_deref(), - InstalledMarketplaceSource::Local { .. } => None, - } - } - - fn sparse_paths(&self) -> &[String] { - match &self.source { - InstalledMarketplaceSource::Git { sparse_paths, .. } => sparse_paths, - InstalledMarketplaceSource::Local { .. } => &[], - } - } - - fn matches_config(&self, marketplace: &toml::Value) -> bool { - marketplace.get("source_type").and_then(toml::Value::as_str) - == Some(self.config_source_type()) - && marketplace.get("source").and_then(toml::Value::as_str) - == Some(self.config_source().as_str()) - && marketplace.get("ref").and_then(toml::Value::as_str) == self.ref_name() - && config_sparse_paths(marketplace) == self.sparse_paths() - } -} - -fn config_sparse_paths(marketplace: &toml::Value) -> Vec { - marketplace - .get("sparse_paths") - .and_then(toml::Value::as_array) - .map(|paths| { - paths - .iter() - .filter_map(toml::Value::as_str) - .map(str::to_string) - .collect() - }) - .unwrap_or_default() -} - -fn utc_timestamp_now() -> Result { - let duration = SystemTime::now() - .duration_since(UNIX_EPOCH) - .map_err(|err| { - MarketplaceAddError::Internal(format!("system clock is before Unix epoch: {err}")) - })?; - Ok(format_utc_timestamp(duration.as_secs() as i64)) -} - -fn format_utc_timestamp(seconds_since_epoch: i64) -> String { - const SECONDS_PER_DAY: i64 = 86_400; - let days = seconds_since_epoch.div_euclid(SECONDS_PER_DAY); - let seconds_of_day = seconds_since_epoch.rem_euclid(SECONDS_PER_DAY); - let (year, month, day) = civil_from_days(days); - let hour = seconds_of_day / 3_600; - let minute = (seconds_of_day % 3_600) / 60; - let second = seconds_of_day % 60; - format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}Z") -} - -fn civil_from_days(days_since_epoch: i64) -> (i64, i64, i64) { - let days = days_since_epoch + 719_468; - let era = if days >= 0 { days } else { days - 146_096 } / 146_097; - let day_of_era = days - era * 146_097; - let year_of_era = - (day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365; - let mut year = year_of_era + era * 400; - let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100); - let month_prime = (5 * day_of_year + 2) / 153; - let day = day_of_year - (153 * month_prime + 2) / 5 + 1; - let month = month_prime + if month_prime < 10 { 3 } else { -9 }; - year += if month <= 2 { 1 } else { 0 }; - (year, month, day) -} - -#[cfg(test)] -mod tests { - use super::*; - use pretty_assertions::assert_eq; - use tempfile::TempDir; - - #[test] - fn utc_timestamp_formats_unix_epoch_as_rfc3339_utc() { - assert_eq!( - format_utc_timestamp(/*seconds_since_epoch*/ 0), - "1970-01-01T00:00:00Z" - ); - assert_eq!( - format_utc_timestamp(/*seconds_since_epoch*/ 1_775_779_200), - "2026-04-10T00:00:00Z" - ); - } - - #[test] - fn installed_marketplace_root_for_source_propagates_config_read_errors() { - let codex_home = TempDir::new().unwrap(); - let config_path = codex_home.path().join(CONFIG_TOML_FILE); - fs::create_dir(&config_path).unwrap(); - - let install_root = codex_home.path().join("marketplaces"); - let source = MarketplaceSource::Git { - url: "https://github.com/owner/repo.git".to_string(), - ref_name: None, - }; - let install_metadata = MarketplaceInstallMetadata::from_source(&source, &[]); - - let err = installed_marketplace_root_for_source( - codex_home.path(), - &install_root, - &install_metadata, - ) - .unwrap_err(); - - assert!( - err.to_string().contains(&format!( - "failed to read user config {}:", - config_path.display() - )), - "unexpected error: {err}" - ); - } - - #[test] - fn installed_marketplace_root_for_source_uses_local_source_root() { - let codex_home = TempDir::new().unwrap(); - let install_root = codex_home.path().join("marketplaces"); - let source_root = codex_home.path().join("source"); - fs::create_dir_all(source_root.join(".agents/plugins")).unwrap(); - fs::write( - source_root.join(".agents/plugins/marketplace.json"), - r#"{"name":"debug","plugins":[]}"#, - ) - .unwrap(); - let source = MarketplaceSource::Local { - path: source_root.clone(), - }; - let install_metadata = MarketplaceInstallMetadata::from_source(&source, &[]); - record_added_marketplace_entry(codex_home.path(), "debug", &install_metadata).unwrap(); - - let root = installed_marketplace_root_for_source( - codex_home.path(), - &install_root, - &install_metadata, - ) - .unwrap(); - - assert_eq!(root, Some(source_root)); - } -} diff --git a/vendor/codex/codex-rs/core/src/plugins/marketplace_add/source.rs b/vendor/codex/codex-rs/core/src/plugins/marketplace_add/source.rs deleted file mode 100644 index e723c886..00000000 --- a/vendor/codex/codex-rs/core/src/plugins/marketplace_add/source.rs +++ /dev/null @@ -1,392 +0,0 @@ -use super::MarketplaceAddError; -use crate::plugins::validate_plugin_segment; -use codex_core_plugins::marketplace::validate_marketplace_root; -use std::path::Path; -use std::path::PathBuf; - -#[derive(Debug, Clone, PartialEq, Eq)] -pub(crate) enum MarketplaceSource { - Git { - url: String, - ref_name: Option, - }, - Local { - path: PathBuf, - }, -} - -pub(crate) fn parse_marketplace_source( - source: &str, - explicit_ref: Option, -) -> Result { - let source = source.trim(); - if source.is_empty() { - return Err(MarketplaceAddError::InvalidRequest( - "marketplace source must not be empty".to_string(), - )); - } - - let (base_source, parsed_ref) = split_source_ref(source); - let ref_name = explicit_ref.or(parsed_ref); - - if looks_like_local_path(&base_source) { - if ref_name.is_some() { - return Err(MarketplaceAddError::InvalidRequest( - "--ref is only supported for git marketplace sources".to_string(), - )); - } - let path = resolve_local_source_path(&base_source)?; - if path.is_file() { - return Err(MarketplaceAddError::InvalidRequest( - "local marketplace source must be a directory, not a file".to_string(), - )); - } - return Ok(MarketplaceSource::Local { path }); - } - - if is_ssh_git_url(&base_source) || is_git_url(&base_source) { - return Ok(MarketplaceSource::Git { - url: normalize_git_url(&base_source), - ref_name, - }); - } - - if looks_like_github_shorthand(&base_source) { - return Ok(MarketplaceSource::Git { - url: format!("https://github.com/{base_source}.git"), - ref_name, - }); - } - - Err(MarketplaceAddError::InvalidRequest(format!( - "invalid marketplace source format: {source}" - ))) -} - -pub(super) fn stage_marketplace_source( - source: &MarketplaceSource, - sparse_paths: &[String], - staged_root: &Path, - clone_source: F, -) -> Result<(), MarketplaceAddError> -where - F: Fn(&str, Option<&str>, &[String], &Path) -> Result<(), MarketplaceAddError>, -{ - if !sparse_paths.is_empty() && !matches!(source, MarketplaceSource::Git { .. }) { - return Err(MarketplaceAddError::InvalidRequest( - "--sparse is only supported for git marketplace sources".to_string(), - )); - } - - match source { - MarketplaceSource::Git { url, ref_name } => { - clone_source(url, ref_name.as_deref(), sparse_paths, staged_root) - } - MarketplaceSource::Local { .. } => unreachable!( - "local marketplace sources are added without staging a copied install root" - ), - } -} - -pub(super) fn validate_marketplace_source_root(root: &Path) -> Result { - let marketplace_name = validate_marketplace_root(root) - .map_err(|err| MarketplaceAddError::InvalidRequest(err.to_string()))?; - validate_plugin_segment(&marketplace_name, "marketplace name") - .map_err(MarketplaceAddError::InvalidRequest)?; - Ok(marketplace_name) -} - -fn split_source_ref(source: &str) -> (String, Option) { - if let Some((base, ref_name)) = source.rsplit_once('#') { - return (base.to_string(), non_empty_ref(ref_name)); - } - if !source.contains("://") - && !is_ssh_git_url(source) - && let Some((base, ref_name)) = source.rsplit_once('@') - { - return (base.to_string(), non_empty_ref(ref_name)); - } - (source.to_string(), None) -} - -fn non_empty_ref(ref_name: &str) -> Option { - let ref_name = ref_name.trim(); - (!ref_name.is_empty()).then(|| ref_name.to_string()) -} - -fn normalize_git_url(url: &str) -> String { - let url = url.trim_end_matches('/'); - if url.starts_with("https://github.com/") && !url.ends_with(".git") { - format!("{url}.git") - } else { - url.to_string() - } -} - -fn looks_like_local_path(source: &str) -> bool { - Path::new(source).is_absolute() - || looks_like_windows_absolute_path(source) - || source.starts_with("./") - || source.starts_with(".\\") - || source.starts_with("../") - || source.starts_with("..\\") - || source.starts_with("~/") - || source == "." - || source == ".." -} - -fn looks_like_windows_absolute_path(source: &str) -> bool { - let bytes = source.as_bytes(); - bytes.len() >= 3 - && bytes[0].is_ascii_alphabetic() - && bytes[1] == b':' - && matches!(bytes[2], b'\\' | b'/') - || source.starts_with(r"\\") -} - -fn resolve_local_source_path(source: &str) -> Result { - let path = expand_tilde_path(source); - let path = if path.is_absolute() { - path - } else { - std::env::current_dir() - .map_err(|err| { - MarketplaceAddError::Internal(format!( - "failed to read current working directory for local marketplace source: {err}" - )) - })? - .join(path) - }; - - path.canonicalize().map_err(|err| { - MarketplaceAddError::InvalidRequest(format!( - "failed to resolve local marketplace source {}: {err}", - path.display() - )) - }) -} - -fn expand_tilde_path(source: &str) -> PathBuf { - let Some(rest) = source.strip_prefix("~/") else { - return PathBuf::from(source); - }; - let Some(home) = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")) else { - return PathBuf::from(source); - }; - PathBuf::from(home).join(rest) -} - -fn is_ssh_git_url(source: &str) -> bool { - source.starts_with("ssh://") || source.starts_with("git@") && source.contains(':') -} - -fn is_git_url(source: &str) -> bool { - source.starts_with("http://") || source.starts_with("https://") -} - -fn looks_like_github_shorthand(source: &str) -> bool { - let mut segments = source.split('/'); - let owner = segments.next(); - let repo = segments.next(); - let extra = segments.next(); - owner.is_some_and(is_github_shorthand_segment) - && repo.is_some_and(is_github_shorthand_segment) - && extra.is_none() -} - -fn is_github_shorthand_segment(segment: &str) -> bool { - !segment.is_empty() - && segment - .chars() - .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | '.')) -} - -impl MarketplaceSource { - pub(super) fn display(&self) -> String { - match self { - Self::Git { url, ref_name } => match ref_name { - Some(ref_name) => format!("{url}#{ref_name}"), - None => url.clone(), - }, - Self::Local { path } => path.display().to_string(), - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use pretty_assertions::assert_eq; - use tempfile::TempDir; - - #[test] - fn github_shorthand_parses_ref_suffix() { - assert_eq!( - parse_marketplace_source("owner/repo@main", /*explicit_ref*/ None).unwrap(), - MarketplaceSource::Git { - url: "https://github.com/owner/repo.git".to_string(), - ref_name: Some("main".to_string()), - } - ); - } - - #[test] - fn git_url_parses_fragment_ref() { - assert_eq!( - parse_marketplace_source( - "https://example.com/team/repo.git#v1", - /*explicit_ref*/ None - ) - .unwrap(), - MarketplaceSource::Git { - url: "https://example.com/team/repo.git".to_string(), - ref_name: Some("v1".to_string()), - } - ); - } - - #[test] - fn explicit_ref_overrides_source_ref() { - assert_eq!( - parse_marketplace_source("owner/repo@main", Some("release".to_string())).unwrap(), - MarketplaceSource::Git { - url: "https://github.com/owner/repo.git".to_string(), - ref_name: Some("release".to_string()), - } - ); - } - - #[test] - fn github_shorthand_and_git_url_normalize_to_same_source() { - let shorthand = parse_marketplace_source("owner/repo", /*explicit_ref*/ None).unwrap(); - let git_url = parse_marketplace_source( - "https://github.com/owner/repo.git", - /*explicit_ref*/ None, - ) - .unwrap(); - - assert_eq!(shorthand, git_url); - assert_eq!( - shorthand, - MarketplaceSource::Git { - url: "https://github.com/owner/repo.git".to_string(), - ref_name: None, - } - ); - } - - #[test] - fn github_url_with_trailing_slash_normalizes_without_extra_path_segment() { - assert_eq!( - parse_marketplace_source("https://github.com/owner/repo/", /*explicit_ref*/ None) - .unwrap(), - MarketplaceSource::Git { - url: "https://github.com/owner/repo.git".to_string(), - ref_name: None, - } - ); - } - - #[test] - fn non_github_https_source_parses_as_git_url() { - assert_eq!( - parse_marketplace_source("https://gitlab.com/owner/repo", /*explicit_ref*/ None) - .unwrap(), - MarketplaceSource::Git { - url: "https://gitlab.com/owner/repo".to_string(), - ref_name: None, - } - ); - } - - #[test] - fn file_url_source_is_rejected() { - let err = - parse_marketplace_source("file:///tmp/marketplace.git", /*explicit_ref*/ None) - .unwrap_err(); - - assert!( - err.to_string() - .contains("invalid marketplace source format"), - "unexpected error: {err}" - ); - } - - #[test] - fn local_path_source_parses() { - let source = parse_marketplace_source(".", /*explicit_ref*/ None).unwrap(); - - let MarketplaceSource::Local { path } = source else { - panic!("expected local path source"); - }; - assert!(path.is_absolute()); - } - - #[test] - fn windows_absolute_paths_look_like_local_paths_on_every_host() { - assert!(looks_like_local_path(r"C:\Users\alice\marketplace")); - assert!(looks_like_local_path("C:/Users/alice/marketplace")); - assert!(looks_like_local_path(r"\\server\share\marketplace")); - assert!(!looks_like_local_path(r"C:relative\path")); - } - - #[test] - fn local_file_source_is_rejected() { - let tempdir = TempDir::new().unwrap(); - let file = tempdir.path().join("marketplace.json"); - std::fs::write(&file, "{}").unwrap(); - - let err = - parse_marketplace_source(file.to_str().unwrap(), /*explicit_ref*/ None).unwrap_err(); - - assert!( - err.to_string() - .contains("local marketplace source must be a directory, not a file"), - "unexpected error: {err}" - ); - } - - #[test] - fn non_git_sources_reject_ref_override() { - let err = parse_marketplace_source("./marketplace", Some("main".to_string())).unwrap_err(); - - assert!( - err.to_string() - .contains("--ref is only supported for git marketplace sources"), - "unexpected error: {err}" - ); - } - - #[test] - fn non_git_sources_reject_sparse_checkout() { - let path = std::env::current_dir().unwrap(); - let err = stage_marketplace_source( - &MarketplaceSource::Local { path }, - &["plugins/foo".to_string()], - Path::new("/tmp"), - |_url, _ref_name, _sparse_paths, _staged_root| Ok(()), - ) - .unwrap_err(); - - assert!( - err.to_string() - .contains("--sparse is only supported for git marketplace sources"), - "unexpected error: {err}" - ); - } - - #[test] - fn ssh_url_parses_as_git_url() { - assert_eq!( - parse_marketplace_source( - "ssh://git@github.com/owner/repo.git#main", - /*explicit_ref*/ None, - ) - .unwrap(), - MarketplaceSource::Git { - url: "ssh://git@github.com/owner/repo.git".to_string(), - ref_name: Some("main".to_string()), - } - ); - } -} diff --git a/vendor/codex/codex-rs/core/src/plugins/marketplace_remove.rs b/vendor/codex/codex-rs/core/src/plugins/marketplace_remove.rs deleted file mode 100644 index 490b16f9..00000000 --- a/vendor/codex/codex-rs/core/src/plugins/marketplace_remove.rs +++ /dev/null @@ -1,313 +0,0 @@ -use crate::plugins::marketplace_install_root; -use crate::plugins::validate_plugin_segment; -use codex_config::RemoveMarketplaceConfigOutcome; -use codex_config::remove_user_marketplace_config; -use codex_utils_absolute_path::AbsolutePathBuf; -use std::fs; -use std::path::Path; -use std::path::PathBuf; - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct MarketplaceRemoveRequest { - pub marketplace_name: String, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct MarketplaceRemoveOutcome { - pub marketplace_name: String, - pub removed_installed_root: Option, -} - -#[derive(Debug, thiserror::Error)] -pub enum MarketplaceRemoveError { - #[error("{0}")] - InvalidRequest(String), - #[error("{0}")] - Internal(String), -} - -pub async fn remove_marketplace( - codex_home: PathBuf, - request: MarketplaceRemoveRequest, -) -> Result { - tokio::task::spawn_blocking(move || remove_marketplace_sync(codex_home.as_path(), request)) - .await - .map_err(|err| { - MarketplaceRemoveError::Internal(format!("failed to remove marketplace: {err}")) - })? -} - -fn remove_marketplace_sync( - codex_home: &Path, - request: MarketplaceRemoveRequest, -) -> Result { - let marketplace_name = request.marketplace_name; - validate_plugin_segment(&marketplace_name, "marketplace name") - .map_err(MarketplaceRemoveError::InvalidRequest)?; - - let destination = marketplace_install_root(codex_home).join(&marketplace_name); - let config_outcome = - remove_user_marketplace_config(codex_home, &marketplace_name).map_err(|err| { - MarketplaceRemoveError::Internal(format!( - "failed to remove marketplace '{marketplace_name}' from user config.toml: {err}" - )) - })?; - if let RemoveMarketplaceConfigOutcome::NameCaseMismatch { configured_name } = &config_outcome { - return Err(MarketplaceRemoveError::InvalidRequest(format!( - "marketplace `{marketplace_name}` does not match configured marketplace `{configured_name}` exactly" - ))); - } - - let removed_config = config_outcome == RemoveMarketplaceConfigOutcome::Removed; - let removed_installed_root = remove_marketplace_root(&destination)?; - - if removed_installed_root.is_none() && !removed_config { - return Err(MarketplaceRemoveError::InvalidRequest(format!( - "marketplace `{marketplace_name}` is not configured or installed" - ))); - } - - Ok(MarketplaceRemoveOutcome { - marketplace_name, - removed_installed_root, - }) -} - -fn remove_marketplace_root(root: &Path) -> Result, MarketplaceRemoveError> { - if !root.exists() { - return Ok(None); - } - - let removed_root = AbsolutePathBuf::try_from(root.to_path_buf()).map_err(|err| { - MarketplaceRemoveError::Internal(format!( - "failed to resolve installed marketplace root {}: {err}", - root.display() - )) - })?; - let metadata = fs::symlink_metadata(root).map_err(|err| { - MarketplaceRemoveError::Internal(format!( - "failed to inspect installed marketplace root {}: {err}", - root.display() - )) - })?; - let remove_result = if metadata.is_dir() { - fs::remove_dir_all(root) - } else { - fs::remove_file(root) - }; - remove_result.map_err(|err| { - MarketplaceRemoveError::Internal(format!( - "failed to remove installed marketplace root {}: {err}", - root.display() - )) - })?; - Ok(Some(removed_root)) -} - -#[cfg(test)] -mod tests { - use super::*; - use codex_config::MarketplaceConfigUpdate; - use codex_config::record_user_marketplace; - use pretty_assertions::assert_eq; - use tempfile::TempDir; - - #[test] - fn remove_marketplace_sync_removes_config_and_installed_root() { - let codex_home = TempDir::new().unwrap(); - record_user_marketplace( - codex_home.path(), - "debug", - &MarketplaceConfigUpdate { - last_updated: "2026-04-13T00:00:00Z", - last_revision: None, - source_type: "git", - source: "https://github.com/owner/repo.git", - ref_name: Some("main"), - sparse_paths: &[], - }, - ) - .unwrap(); - let installed_root = marketplace_install_root(codex_home.path()).join("debug"); - fs::create_dir_all(installed_root.join(".agents/plugins")).unwrap(); - fs::write( - installed_root.join(".agents/plugins/marketplace.json"), - "{}", - ) - .unwrap(); - - let outcome = remove_marketplace_sync( - codex_home.path(), - MarketplaceRemoveRequest { - marketplace_name: "debug".to_string(), - }, - ) - .unwrap(); - - assert_eq!(outcome.marketplace_name, "debug"); - assert_eq!( - outcome.removed_installed_root, - Some(AbsolutePathBuf::try_from(installed_root.clone()).unwrap()) - ); - let config = - fs::read_to_string(codex_home.path().join(codex_config::CONFIG_TOML_FILE)).unwrap(); - assert!(!config.contains("[marketplaces.debug]")); - assert!(!installed_root.exists()); - } - - #[test] - fn remove_marketplace_sync_rejects_unknown_marketplace() { - let codex_home = TempDir::new().unwrap(); - - let err = remove_marketplace_sync( - codex_home.path(), - MarketplaceRemoveRequest { - marketplace_name: "debug".to_string(), - }, - ) - .unwrap_err(); - - assert_eq!( - err.to_string(), - "marketplace `debug` is not configured or installed" - ); - } - - #[test] - fn remove_marketplace_sync_rejects_case_mismatched_configured_name() { - let codex_home = TempDir::new().unwrap(); - record_user_marketplace( - codex_home.path(), - "debug", - &MarketplaceConfigUpdate { - last_updated: "2026-04-13T00:00:00Z", - last_revision: None, - source_type: "git", - source: "https://github.com/owner/repo.git", - ref_name: Some("main"), - sparse_paths: &[], - }, - ) - .unwrap(); - let installed_root = marketplace_install_root(codex_home.path()).join("debug"); - fs::create_dir_all(&installed_root).unwrap(); - - let err = remove_marketplace_sync( - codex_home.path(), - MarketplaceRemoveRequest { - marketplace_name: "Debug".to_string(), - }, - ) - .unwrap_err(); - - assert_eq!( - err.to_string(), - "marketplace `Debug` does not match configured marketplace `debug` exactly" - ); - assert!(installed_root.exists()); - let config = - fs::read_to_string(codex_home.path().join(codex_config::CONFIG_TOML_FILE)).unwrap(); - assert!(config.contains("[marketplaces.debug]")); - } - - #[test] - fn remove_marketplace_sync_keeps_installed_root_when_config_removal_fails() { - let codex_home = TempDir::new().unwrap(); - fs::write( - codex_home.path().join(codex_config::CONFIG_TOML_FILE), - "[marketplaces.debug\n", - ) - .unwrap(); - let installed_root = marketplace_install_root(codex_home.path()).join("debug"); - fs::create_dir_all(&installed_root).unwrap(); - - let err = remove_marketplace_sync( - codex_home.path(), - MarketplaceRemoveRequest { - marketplace_name: "debug".to_string(), - }, - ) - .unwrap_err(); - - assert!( - err.to_string() - .contains("failed to remove marketplace 'debug' from user config.toml") - ); - assert!(installed_root.exists()); - } - - #[test] - fn remove_marketplace_sync_removes_file_installed_root() { - let codex_home = TempDir::new().unwrap(); - record_user_marketplace( - codex_home.path(), - "debug", - &MarketplaceConfigUpdate { - last_updated: "2026-04-13T00:00:00Z", - last_revision: None, - source_type: "git", - source: "https://github.com/owner/repo.git", - ref_name: Some("main"), - sparse_paths: &[], - }, - ) - .unwrap(); - let installed_root = marketplace_install_root(codex_home.path()).join("debug"); - fs::create_dir_all(installed_root.parent().unwrap()).unwrap(); - fs::write(&installed_root, "corrupt install root").unwrap(); - - let outcome = remove_marketplace_sync( - codex_home.path(), - MarketplaceRemoveRequest { - marketplace_name: "debug".to_string(), - }, - ) - .unwrap(); - - assert_eq!( - outcome, - MarketplaceRemoveOutcome { - marketplace_name: "debug".to_string(), - removed_installed_root: Some( - AbsolutePathBuf::try_from(installed_root.clone()).unwrap() - ), - } - ); - assert!(!installed_root.exists()); - let config = - fs::read_to_string(codex_home.path().join(codex_config::CONFIG_TOML_FILE)).unwrap(); - assert!(!config.contains("[marketplaces.debug]")); - } - - #[test] - fn remove_marketplace_sync_removes_inline_config_entry() { - let codex_home = TempDir::new().unwrap(); - fs::write( - codex_home.path().join(codex_config::CONFIG_TOML_FILE), - r#" -marketplaces = { debug = { source_type = "git", source = "https://github.com/owner/repo.git" } } -"#, - ) - .unwrap(); - let installed_root = marketplace_install_root(codex_home.path()).join("debug"); - fs::create_dir_all(&installed_root).unwrap(); - - let outcome = remove_marketplace_sync( - codex_home.path(), - MarketplaceRemoveRequest { - marketplace_name: "debug".to_string(), - }, - ) - .unwrap(); - - assert_eq!(outcome.marketplace_name, "debug"); - assert_eq!( - outcome.removed_installed_root, - Some(AbsolutePathBuf::try_from(installed_root.clone()).unwrap()) - ); - assert!(!installed_root.exists()); - let config = - fs::read_to_string(codex_home.path().join(codex_config::CONFIG_TOML_FILE)).unwrap(); - assert!(!config.contains("debug")); - } -} diff --git a/vendor/codex/codex-rs/core/src/plugins/mod.rs b/vendor/codex/codex-rs/core/src/plugins/mod.rs deleted file mode 100644 index 5992b3f8..00000000 --- a/vendor/codex/codex-rs/core/src/plugins/mod.rs +++ /dev/null @@ -1,53 +0,0 @@ -use codex_config::types::McpServerConfig; - -mod installed_marketplaces; -mod manager; -mod marketplace_add; -mod marketplace_remove; -mod startup_sync; -#[cfg(test)] -pub(crate) mod test_support; - -pub use codex_core_plugins::marketplace_upgrade::ConfiguredMarketplaceUpgradeError as PluginMarketplaceUpgradeError; -pub use codex_core_plugins::marketplace_upgrade::ConfiguredMarketplaceUpgradeOutcome as PluginMarketplaceUpgradeOutcome; -pub use codex_plugin::AppConnectorId; -pub use codex_plugin::EffectiveSkillRoots; -pub use codex_plugin::PluginCapabilitySummary; -pub use codex_plugin::PluginId; -pub use codex_plugin::PluginIdError; -pub use codex_plugin::PluginTelemetryMetadata; -pub use codex_plugin::validate_plugin_segment; - -pub type LoadedPlugin = codex_plugin::LoadedPlugin; -pub type PluginLoadOutcome = codex_plugin::PluginLoadOutcome; - -pub use installed_marketplaces::INSTALLED_MARKETPLACES_DIR; -pub use installed_marketplaces::marketplace_install_root; -pub use manager::ConfiguredMarketplace; -pub use manager::ConfiguredMarketplaceListOutcome; -pub use manager::ConfiguredMarketplacePlugin; -pub use manager::OPENAI_BUNDLED_MARKETPLACE_NAME; -pub use manager::OPENAI_CURATED_MARKETPLACE_NAME; -pub use manager::PluginDetail; -pub use manager::PluginDetailsUnavailableReason; -pub use manager::PluginInstallError; -pub use manager::PluginInstallOutcome; -pub use manager::PluginInstallRequest; -pub use manager::PluginReadOutcome; -pub use manager::PluginReadRequest; -pub use manager::PluginRemoteSyncError; -pub use manager::PluginUninstallError; -pub use manager::PluginsManager; -pub use manager::RemotePluginSyncResult; -pub use marketplace_add::MarketplaceAddError; -pub use marketplace_add::MarketplaceAddOutcome; -pub use marketplace_add::MarketplaceAddRequest; -pub use marketplace_add::add_marketplace; -pub use marketplace_add::is_local_marketplace_source; -pub use marketplace_remove::MarketplaceRemoveError; -pub use marketplace_remove::MarketplaceRemoveOutcome; -pub use marketplace_remove::MarketplaceRemoveRequest; -pub use marketplace_remove::remove_marketplace; -pub(crate) use startup_sync::curated_plugins_repo_path; -pub(crate) use startup_sync::read_curated_plugins_sha; -pub(crate) use startup_sync::sync_openai_plugins_repo; diff --git a/vendor/codex/codex-rs/core/src/plugins/render_tests.rs b/vendor/codex/codex-rs/core/src/plugins/render_tests.rs deleted file mode 100644 index a0ec5312..00000000 --- a/vendor/codex/codex-rs/core/src/plugins/render_tests.rs +++ /dev/null @@ -1,23 +0,0 @@ -use super::*; -use pretty_assertions::assert_eq; - -#[test] -fn render_plugins_section_returns_none_for_empty_plugins() { - assert_eq!(render_plugins_section(&[]), None); -} - -#[test] -fn render_plugins_section_includes_descriptions_and_skill_naming_guidance() { - let rendered = render_plugins_section(&[PluginCapabilitySummary { - config_name: "sample@test".to_string(), - display_name: "sample".to_string(), - description: Some("inspect sample data".to_string()), - has_skills: true, - ..PluginCapabilitySummary::default() - }]) - .expect("plugin section should render"); - - let expected = "\n## Plugins\nA plugin is a local bundle of skills, MCP servers, and apps. Below is the list of plugins that are enabled and available in this session.\n### Available plugins\n- `sample`: inspect sample data\n### How to use plugins\n- Discovery: The list above is the plugins available in this session.\n- Skill naming: If a plugin contributes skills, those skill entries are prefixed with `plugin_name:` in the Skills list.\n- Trigger rules: If the user explicitly names a plugin, prefer capabilities associated with that plugin for that turn.\n- Relationship to capabilities: Plugins are not invoked directly. Use their underlying skills, MCP tools, and app tools to help solve the task.\n- Preference: When a relevant plugin is available, prefer using capabilities associated with that plugin over standalone capabilities that provide similar functionality.\n- Missing/blocked: If the user requests a plugin that is not listed above, or the plugin does not have relevant callable capabilities for the task, say so briefly and continue with the best fallback.\n"; - - assert_eq!(rendered, expected); -} diff --git a/vendor/codex/codex-rs/core/src/plugins/startup_sync.rs b/vendor/codex/codex-rs/core/src/plugins/startup_sync.rs deleted file mode 100644 index 5bca32de..00000000 --- a/vendor/codex/codex-rs/core/src/plugins/startup_sync.rs +++ /dev/null @@ -1,1028 +0,0 @@ -use std::path::Path; -use std::path::PathBuf; -use std::process::Command; -use std::process::Output; -use std::process::Stdio; -use std::sync::Arc; -use std::time::Duration; - -use codex_otel::CURATED_PLUGINS_STARTUP_SYNC_FINAL_METRIC; -use codex_otel::CURATED_PLUGINS_STARTUP_SYNC_METRIC; -use reqwest::Client; -use serde::Deserialize; -use tempfile::TempDir; -use tracing::info; -use tracing::warn; -use zip::ZipArchive; - -use crate::config::Config; -use codex_login::AuthManager; -use codex_login::default_client::build_reqwest_client; - -use super::PluginsManager; - -const GITHUB_API_BASE_URL: &str = "https://api.github.com"; -const GITHUB_API_ACCEPT_HEADER: &str = "application/vnd.github+json"; -const GITHUB_API_VERSION_HEADER: &str = "2022-11-28"; -const CURATED_PLUGINS_BACKUP_ARCHIVE_API_URL: &str = - "https://chatgpt.com/backend-api/plugins/export/curated"; -const OPENAI_PLUGINS_OWNER: &str = "openai"; -const OPENAI_PLUGINS_REPO: &str = "plugins"; -const CURATED_PLUGINS_RELATIVE_DIR: &str = ".tmp/plugins"; -const CURATED_PLUGINS_SHA_FILE: &str = ".tmp/plugins.sha"; -const CURATED_PLUGINS_BACKUP_ARCHIVE_FALLBACK_VERSION: &str = "export-backup"; -const CURATED_PLUGINS_GIT_TIMEOUT: Duration = Duration::from_secs(30); -const CURATED_PLUGINS_HTTP_TIMEOUT: Duration = Duration::from_secs(30); -const CURATED_PLUGINS_BACKUP_ARCHIVE_TIMEOUT: Duration = Duration::from_secs(30); -// Keep this comfortably above a normal sync attempt so we do not race another Codex process. -const CURATED_PLUGINS_STALE_TEMP_DIR_MAX_AGE: Duration = Duration::from_secs(10 * 60); -const STARTUP_REMOTE_PLUGIN_SYNC_MARKER_FILE: &str = ".tmp/app-server-remote-plugin-sync-v1"; -const STARTUP_REMOTE_PLUGIN_SYNC_PREREQUISITE_TIMEOUT: Duration = Duration::from_secs(10); - -#[derive(Debug, Deserialize)] -struct GitHubRepositorySummary { - default_branch: String, -} - -#[derive(Debug, Deserialize)] -struct GitHubGitRefSummary { - object: GitHubGitRefObject, -} - -#[derive(Debug, Deserialize)] -struct GitHubGitRefObject { - sha: String, -} - -#[derive(Debug, Deserialize)] -struct CuratedPluginsBackupArchiveResponse { - download_url: String, -} - -pub(crate) fn curated_plugins_repo_path(codex_home: &Path) -> PathBuf { - codex_home.join(CURATED_PLUGINS_RELATIVE_DIR) -} - -pub(crate) fn read_curated_plugins_sha(codex_home: &Path) -> Option { - read_sha_file(curated_plugins_sha_path(codex_home).as_path()) -} - -fn curated_plugins_sha_path(codex_home: &Path) -> PathBuf { - codex_home.join(CURATED_PLUGINS_SHA_FILE) -} - -pub(crate) fn sync_openai_plugins_repo(codex_home: &Path) -> Result { - sync_openai_plugins_repo_with_transport_overrides( - codex_home, - "git", - GITHUB_API_BASE_URL, - CURATED_PLUGINS_BACKUP_ARCHIVE_API_URL, - ) -} - -fn sync_openai_plugins_repo_with_transport_overrides( - codex_home: &Path, - git_binary: &str, - api_base_url: &str, - backup_archive_api_url: &str, -) -> Result { - match sync_openai_plugins_repo_via_git(codex_home, git_binary) { - Ok(remote_sha) => { - emit_curated_plugins_startup_sync_metric("git", "success"); - emit_curated_plugins_startup_sync_final_metric("git", "success"); - Ok(remote_sha) - } - Err(err) => { - emit_curated_plugins_startup_sync_metric("git", "failure"); - warn!( - error = %err, - git_binary, - "git sync failed for curated plugin sync; falling back to GitHub HTTP" - ); - match sync_openai_plugins_repo_via_http(codex_home, api_base_url) { - Ok(remote_sha) => { - emit_curated_plugins_startup_sync_metric("http", "success"); - emit_curated_plugins_startup_sync_final_metric("http", "success"); - Ok(remote_sha) - } - Err(http_err) => { - emit_curated_plugins_startup_sync_metric("http", "failure"); - if has_local_curated_plugins_snapshot(codex_home) { - emit_curated_plugins_startup_sync_final_metric("http", "failure"); - warn!( - error = %http_err, - "GitHub HTTP sync failed for curated plugin sync; skipping export archive fallback because a local curated plugins snapshot already exists" - ); - Err(format!( - "git sync failed for curated plugin sync: {err}; GitHub HTTP sync failed for curated plugin sync: {http_err}; export archive fallback skipped because a local curated plugins snapshot already exists" - )) - } else { - // The export archive is a lagging backup path. Only use it to bootstrap a - // missing local curated snapshot, never to refresh an existing one. - warn!( - error = %http_err, - backup_archive_api_url, - "GitHub HTTP sync failed for curated plugin sync; falling back to export archive" - ); - let result = sync_openai_plugins_repo_via_backup_archive( - codex_home, - backup_archive_api_url, - ); - let status = if result.is_ok() { "success" } else { "failure" }; - emit_curated_plugins_startup_sync_metric("export_archive", status); - emit_curated_plugins_startup_sync_final_metric("export_archive", status); - result.map_err(|export_err| { - format!( - "git sync failed for curated plugin sync: {err}; GitHub HTTP sync failed for curated plugin sync: {http_err}; export archive sync failed for curated plugin sync: {export_err}" - ) - }) - } - } - } - } - } -} - -fn sync_openai_plugins_repo_via_git(codex_home: &Path, git_binary: &str) -> Result { - let repo_path = curated_plugins_repo_path(codex_home); - let sha_path = codex_home.join(CURATED_PLUGINS_SHA_FILE); - let remote_sha = git_ls_remote_head_sha(git_binary)?; - let local_sha = read_local_git_or_sha_file(&repo_path, &sha_path, git_binary); - - if local_sha.as_deref() == Some(remote_sha.as_str()) && repo_path.join(".git").is_dir() { - return Ok(remote_sha); - } - - let staged_repo_dir = prepare_curated_repo_parent_and_temp_dir(&repo_path)?; - let clone_output = run_git_command_with_timeout( - Command::new(git_binary) - .env("GIT_OPTIONAL_LOCKS", "0") - .arg("clone") - .arg("--depth") - .arg("1") - .arg("https://github.com/openai/plugins.git") - .arg(staged_repo_dir.path()), - "git clone curated plugins repo", - CURATED_PLUGINS_GIT_TIMEOUT, - )?; - ensure_git_success(&clone_output, "git clone curated plugins repo")?; - - let cloned_sha = git_head_sha(staged_repo_dir.path(), git_binary)?; - if cloned_sha != remote_sha { - return Err(format!( - "curated plugins clone HEAD mismatch: expected {remote_sha}, got {cloned_sha}" - )); - } - - ensure_marketplace_manifest_exists(staged_repo_dir.path())?; - activate_curated_repo(&repo_path, staged_repo_dir)?; - write_curated_plugins_sha(&sha_path, &remote_sha)?; - Ok(remote_sha) -} - -fn sync_openai_plugins_repo_via_http( - codex_home: &Path, - api_base_url: &str, -) -> Result { - let repo_path = curated_plugins_repo_path(codex_home); - let sha_path = codex_home.join(CURATED_PLUGINS_SHA_FILE); - let runtime = tokio::runtime::Builder::new_current_thread() - .enable_all() - .build() - .map_err(|err| format!("failed to create curated plugins sync runtime: {err}"))?; - let remote_sha = runtime.block_on(fetch_curated_repo_remote_sha(api_base_url))?; - let local_sha = read_sha_file(&sha_path); - - if local_sha.as_deref() == Some(remote_sha.as_str()) && repo_path.is_dir() { - return Ok(remote_sha); - } - - let staged_repo_dir = prepare_curated_repo_parent_and_temp_dir(&repo_path)?; - let zipball_bytes = runtime.block_on(fetch_curated_repo_zipball(api_base_url, &remote_sha))?; - extract_zipball_to_dir(&zipball_bytes, staged_repo_dir.path())?; - ensure_marketplace_manifest_exists(staged_repo_dir.path())?; - activate_curated_repo(&repo_path, staged_repo_dir)?; - write_curated_plugins_sha(&sha_path, &remote_sha)?; - Ok(remote_sha) -} - -fn sync_openai_plugins_repo_via_backup_archive( - codex_home: &Path, - backup_archive_api_url: &str, -) -> Result { - let repo_path = curated_plugins_repo_path(codex_home); - let sha_path = curated_plugins_sha_path(codex_home); - let runtime = tokio::runtime::Builder::new_current_thread() - .enable_all() - .build() - .map_err(|err| format!("failed to create curated plugins sync runtime: {err}"))?; - let staged_repo_dir = prepare_curated_repo_parent_and_temp_dir(&repo_path)?; - let zipball_bytes = runtime.block_on(fetch_curated_repo_backup_archive_zip( - backup_archive_api_url, - ))?; - extract_zipball_to_dir(&zipball_bytes, staged_repo_dir.path())?; - ensure_marketplace_manifest_exists(staged_repo_dir.path())?; - let export_version = read_extracted_backup_archive_git_sha(staged_repo_dir.path())? - .unwrap_or_else(|| CURATED_PLUGINS_BACKUP_ARCHIVE_FALLBACK_VERSION.to_string()); - activate_curated_repo(&repo_path, staged_repo_dir)?; - write_curated_plugins_sha(&sha_path, &export_version)?; - Ok(export_version) -} - -pub(super) fn start_startup_remote_plugin_sync_once( - manager: Arc, - codex_home: PathBuf, - config: Config, - auth_manager: Arc, -) { - let marker_path = startup_remote_plugin_sync_marker_path(codex_home.as_path()); - if marker_path.is_file() { - return; - } - - tokio::spawn(async move { - if marker_path.is_file() { - return; - } - - if !wait_for_startup_remote_plugin_sync_prerequisites(codex_home.as_path()).await { - warn!( - codex_home = %codex_home.display(), - "skipping startup remote plugin sync because curated marketplace is not ready" - ); - return; - } - - let auth = auth_manager.auth().await; - match manager - .sync_plugins_from_remote(&config, auth.as_ref(), /*additive_only*/ true) - .await - { - Ok(sync_result) => { - info!( - installed_plugin_ids = ?sync_result.installed_plugin_ids, - enabled_plugin_ids = ?sync_result.enabled_plugin_ids, - disabled_plugin_ids = ?sync_result.disabled_plugin_ids, - uninstalled_plugin_ids = ?sync_result.uninstalled_plugin_ids, - "completed startup remote plugin sync" - ); - if let Err(err) = - write_startup_remote_plugin_sync_marker(codex_home.as_path()).await - { - warn!( - error = %err, - path = %marker_path.display(), - "failed to persist startup remote plugin sync marker" - ); - } - } - Err(err) => { - warn!( - error = %err, - "startup remote plugin sync failed; will retry on next app-server start" - ); - } - } - }); -} - -fn startup_remote_plugin_sync_marker_path(codex_home: &Path) -> PathBuf { - codex_home.join(STARTUP_REMOTE_PLUGIN_SYNC_MARKER_FILE) -} - -fn has_local_curated_plugins_snapshot(codex_home: &Path) -> bool { - curated_plugins_repo_path(codex_home) - .join(".agents/plugins/marketplace.json") - .is_file() - && codex_home.join(CURATED_PLUGINS_SHA_FILE).is_file() -} - -async fn wait_for_startup_remote_plugin_sync_prerequisites(codex_home: &Path) -> bool { - let deadline = tokio::time::Instant::now() + STARTUP_REMOTE_PLUGIN_SYNC_PREREQUISITE_TIMEOUT; - loop { - if has_local_curated_plugins_snapshot(codex_home) { - return true; - } - if tokio::time::Instant::now() >= deadline { - return false; - } - tokio::time::sleep(Duration::from_millis(50)).await; - } -} - -async fn write_startup_remote_plugin_sync_marker(codex_home: &Path) -> std::io::Result<()> { - let marker_path = startup_remote_plugin_sync_marker_path(codex_home); - if let Some(parent) = marker_path.parent() { - tokio::fs::create_dir_all(parent).await?; - } - tokio::fs::write(marker_path, b"ok\n").await -} - -fn prepare_curated_repo_parent_and_temp_dir(repo_path: &Path) -> Result { - let Some(parent) = repo_path.parent() else { - return Err(format!( - "failed to determine curated plugins parent directory for {}", - repo_path.display() - )); - }; - std::fs::create_dir_all(parent).map_err(|err| { - format!( - "failed to create curated plugins parent directory {}: {err}", - parent.display() - ) - })?; - remove_stale_curated_repo_temp_dirs(parent, CURATED_PLUGINS_STALE_TEMP_DIR_MAX_AGE); - - let clone_dir = tempfile::Builder::new() - .prefix("plugins-clone-") - .tempdir_in(parent) - .map_err(|err| { - format!( - "failed to create temporary curated plugins directory in {}: {err}", - parent.display() - ) - })?; - Ok(clone_dir) -} - -fn remove_stale_curated_repo_temp_dirs(parent: &Path, max_age: Duration) { - let entries = match std::fs::read_dir(parent) { - Ok(entries) => entries, - Err(err) => { - warn!( - error = %err, - parent = %parent.display(), - "failed to list curated plugins temp directory parent for stale cleanup" - ); - return; - } - }; - - for entry in entries.flatten() { - let file_type = match entry.file_type() { - Ok(file_type) => file_type, - Err(err) => { - warn!( - error = %err, - path = %entry.path().display(), - "failed to inspect curated plugins temp directory entry" - ); - continue; - } - }; - if !file_type.is_dir() { - continue; - } - - let path = entry.path(); - let is_plugins_clone_dir = path - .file_name() - .and_then(|name| name.to_str()) - .is_some_and(|name| name.starts_with("plugins-clone-")); - if !is_plugins_clone_dir { - continue; - } - - let metadata = match entry.metadata() { - Ok(metadata) => metadata, - Err(err) => { - warn!( - error = %err, - path = %path.display(), - "failed to read curated plugins temp directory metadata" - ); - continue; - } - }; - let modified = match metadata.modified() { - Ok(modified) => modified, - Err(err) => { - warn!( - error = %err, - path = %path.display(), - "failed to read curated plugins temp directory modification time" - ); - continue; - } - }; - let age = match modified.elapsed() { - Ok(age) => age, - Err(err) => { - warn!( - error = %err, - path = %path.display(), - "failed to compute curated plugins temp directory age" - ); - continue; - } - }; - if age < max_age { - continue; - } - - if let Err(err) = std::fs::remove_dir_all(&path) { - warn!( - error = %err, - path = %path.display(), - "failed to remove stale curated plugins temp directory" - ); - } - } -} - -fn emit_curated_plugins_startup_sync_metric(transport: &'static str, status: &'static str) { - emit_curated_plugins_startup_sync_counter( - CURATED_PLUGINS_STARTUP_SYNC_METRIC, - transport, - status, - ); -} - -fn emit_curated_plugins_startup_sync_final_metric(transport: &'static str, status: &'static str) { - emit_curated_plugins_startup_sync_counter( - CURATED_PLUGINS_STARTUP_SYNC_FINAL_METRIC, - transport, - status, - ); -} - -fn emit_curated_plugins_startup_sync_counter( - metric_name: &str, - transport: &'static str, - status: &'static str, -) { - let Some(metrics) = codex_otel::global() else { - return; - }; - let tags = [("transport", transport), ("status", status)]; - let _ = metrics.counter(metric_name, /*inc*/ 1, &tags); -} - -fn ensure_marketplace_manifest_exists(repo_path: &Path) -> Result<(), String> { - if repo_path.join(".agents/plugins/marketplace.json").is_file() { - return Ok(()); - } - Err(format!( - "curated plugins archive missing marketplace manifest at {}", - repo_path.join(".agents/plugins/marketplace.json").display() - )) -} - -fn activate_curated_repo(repo_path: &Path, staged_repo_dir: TempDir) -> Result<(), String> { - let staged_repo_path = staged_repo_dir.path(); - if repo_path.exists() { - let parent = repo_path.parent().ok_or_else(|| { - format!( - "failed to determine curated plugins parent directory for {}", - repo_path.display() - ) - })?; - let backup_dir = tempfile::Builder::new() - .prefix("plugins-backup-") - .tempdir_in(parent) - .map_err(|err| { - format!( - "failed to create curated plugins backup directory in {}: {err}", - parent.display() - ) - })?; - let backup_repo_path = backup_dir.path().join("repo"); - - std::fs::rename(repo_path, &backup_repo_path).map_err(|err| { - format!( - "failed to move previous curated plugins repo out of the way at {}: {err}", - repo_path.display() - ) - })?; - - if let Err(err) = std::fs::rename(staged_repo_path, repo_path) { - let rollback_result = std::fs::rename(&backup_repo_path, repo_path); - return match rollback_result { - Ok(()) => Err(format!( - "failed to activate new curated plugins repo at {}: {err}", - repo_path.display() - )), - Err(rollback_err) => { - let backup_path = backup_dir.keep().join("repo"); - Err(format!( - "failed to activate new curated plugins repo at {}: {err}; failed to restore previous repo (left at {}): {rollback_err}", - repo_path.display(), - backup_path.display() - )) - } - }; - } - } else { - std::fs::rename(staged_repo_path, repo_path).map_err(|err| { - format!( - "failed to activate curated plugins repo at {}: {err}", - repo_path.display() - ) - })?; - } - - Ok(()) -} - -fn write_curated_plugins_sha(sha_path: &Path, remote_sha: &str) -> Result<(), String> { - if let Some(parent) = sha_path.parent() { - std::fs::create_dir_all(parent).map_err(|err| { - format!( - "failed to create curated plugins sha directory {}: {err}", - parent.display() - ) - })?; - } - std::fs::write(sha_path, format!("{remote_sha}\n")).map_err(|err| { - format!( - "failed to write curated plugins sha file {}: {err}", - sha_path.display() - ) - }) -} - -fn read_local_git_or_sha_file( - repo_path: &Path, - sha_path: &Path, - git_binary: &str, -) -> Option { - if repo_path.join(".git").is_dir() - && let Ok(sha) = git_head_sha(repo_path, git_binary) - { - return Some(sha); - } - - read_sha_file(sha_path) -} - -fn git_ls_remote_head_sha(git_binary: &str) -> Result { - let output = run_git_command_with_timeout( - Command::new(git_binary) - .env("GIT_OPTIONAL_LOCKS", "0") - .arg("ls-remote") - .arg("https://github.com/openai/plugins.git") - .arg("HEAD"), - "git ls-remote curated plugins repo", - CURATED_PLUGINS_GIT_TIMEOUT, - )?; - ensure_git_success(&output, "git ls-remote curated plugins repo")?; - - let stdout = String::from_utf8_lossy(&output.stdout); - let Some(first_line) = stdout.lines().next() else { - return Err("git ls-remote returned empty output for curated plugins repo".to_string()); - }; - let Some((sha, _)) = first_line.split_once('\t') else { - return Err(format!( - "unexpected git ls-remote output for curated plugins repo: {first_line}" - )); - }; - if sha.is_empty() { - return Err("git ls-remote returned empty sha for curated plugins repo".to_string()); - } - Ok(sha.to_string()) -} - -fn git_head_sha(repo_path: &Path, git_binary: &str) -> Result { - let output = Command::new(git_binary) - .env("GIT_OPTIONAL_LOCKS", "0") - .arg("-C") - .arg(repo_path) - .arg("rev-parse") - .arg("HEAD") - .output() - .map_err(|err| { - format!( - "failed to run git rev-parse HEAD in {}: {err}", - repo_path.display() - ) - })?; - ensure_git_success(&output, "git rev-parse HEAD")?; - - let sha = String::from_utf8_lossy(&output.stdout).trim().to_string(); - if sha.is_empty() { - return Err(format!( - "git rev-parse HEAD returned empty output in {}", - repo_path.display() - )); - } - Ok(sha) -} - -fn run_git_command_with_timeout( - command: &mut Command, - context: &str, - timeout: Duration, -) -> Result { - let mut child = command - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn() - .map_err(|err| format!("failed to run {context}: {err}"))?; - - let start = std::time::Instant::now(); - loop { - match child.try_wait() { - Ok(Some(_)) => { - return child - .wait_with_output() - .map_err(|err| format!("failed to wait for {context}: {err}")); - } - Ok(None) => {} - Err(err) => return Err(format!("failed to poll {context}: {err}")), - } - - if start.elapsed() >= timeout { - match child.try_wait() { - Ok(Some(_)) => { - return child - .wait_with_output() - .map_err(|err| format!("failed to wait for {context}: {err}")); - } - Ok(None) => {} - Err(err) => return Err(format!("failed to poll {context}: {err}")), - } - - let _ = child.kill(); - let output = child - .wait_with_output() - .map_err(|err| format!("failed to wait for {context} after timeout: {err}"))?; - let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string(); - return if stderr.is_empty() { - Err(format!("{context} timed out after {}s", timeout.as_secs())) - } else { - Err(format!( - "{context} timed out after {}s: {stderr}", - timeout.as_secs() - )) - }; - } - - std::thread::sleep(Duration::from_millis(100)); - } -} - -fn ensure_git_success(output: &Output, context: &str) -> Result<(), String> { - if output.status.success() { - return Ok(()); - } - let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string(); - if stderr.is_empty() { - Err(format!("{context} failed with status {}", output.status)) - } else { - Err(format!( - "{context} failed with status {}: {stderr}", - output.status - )) - } -} - -async fn fetch_curated_repo_remote_sha(api_base_url: &str) -> Result { - let api_base_url = api_base_url.trim_end_matches('/'); - let repo_url = format!("{api_base_url}/repos/{OPENAI_PLUGINS_OWNER}/{OPENAI_PLUGINS_REPO}"); - let client = build_reqwest_client(); - let repo_body = fetch_github_text(&client, &repo_url, "get curated plugins repository").await?; - let repo_summary: GitHubRepositorySummary = - serde_json::from_str(&repo_body).map_err(|err| { - format!("failed to parse curated plugins repository response from {repo_url}: {err}") - })?; - if repo_summary.default_branch.is_empty() { - return Err(format!( - "curated plugins repository response from {repo_url} did not include a default branch" - )); - } - - let git_ref_url = format!("{repo_url}/git/ref/heads/{}", repo_summary.default_branch); - let git_ref_body = - fetch_github_text(&client, &git_ref_url, "get curated plugins HEAD ref").await?; - let git_ref: GitHubGitRefSummary = serde_json::from_str(&git_ref_body).map_err(|err| { - format!("failed to parse curated plugins ref response from {git_ref_url}: {err}") - })?; - if git_ref.object.sha.is_empty() { - return Err(format!( - "curated plugins ref response from {git_ref_url} did not include a HEAD sha" - )); - } - - Ok(git_ref.object.sha) -} - -async fn fetch_curated_repo_zipball( - api_base_url: &str, - remote_sha: &str, -) -> Result, String> { - let api_base_url = api_base_url.trim_end_matches('/'); - let repo_url = format!("{api_base_url}/repos/{OPENAI_PLUGINS_OWNER}/{OPENAI_PLUGINS_REPO}"); - let zipball_url = format!("{repo_url}/zipball/{remote_sha}"); - let client = build_reqwest_client(); - fetch_github_bytes(&client, &zipball_url, "download curated plugins archive").await -} - -async fn fetch_curated_repo_backup_archive_zip( - backup_archive_api_url: &str, -) -> Result, String> { - let client = build_reqwest_client(); - let export_body = fetch_public_text( - &client, - backup_archive_api_url, - "get curated plugins export archive metadata", - ) - .await?; - let export_response: CuratedPluginsBackupArchiveResponse = serde_json::from_str(&export_body) - .map_err(|err| { - format!( - "failed to parse curated plugins backup archive response from {backup_archive_api_url}: {err}" - ) - })?; - if export_response.download_url.is_empty() { - return Err(format!( - "curated plugins backup archive response from {backup_archive_api_url} did not include a download URL" - )); - } - - fetch_public_bytes( - &client, - &export_response.download_url, - "download curated plugins export archive", - ) - .await -} - -fn read_extracted_backup_archive_git_sha(repo_path: &Path) -> Result, String> { - let git_dir = repo_path.join(".git"); - if !git_dir.is_dir() { - return Ok(None); - } - - let head_path = git_dir.join("HEAD"); - let head = std::fs::read_to_string(&head_path).map_err(|err| { - format!( - "failed to read curated plugins backup archive git HEAD {}: {err}", - head_path.display() - ) - })?; - let head = head.trim(); - if head.is_empty() { - return Err(format!( - "curated plugins backup archive git HEAD is empty at {}", - head_path.display() - )); - } - - if let Some(reference) = head.strip_prefix("ref: ") { - let reference = validate_backup_archive_git_ref(reference.trim())?; - return read_git_ref_sha(&git_dir, reference).map(Some); - } - - Ok(Some(head.to_string())) -} - -fn validate_backup_archive_git_ref(reference: &str) -> Result<&str, String> { - if !reference.starts_with("refs/") { - return Err(format!( - "curated plugins backup archive git ref must stay under refs/: {reference}" - )); - } - - let path = Path::new(reference); - if path.is_absolute() { - return Err(format!( - "curated plugins backup archive git ref must be relative: {reference}" - )); - } - - for component in path.components() { - match component { - std::path::Component::Normal(_) => {} - _ => { - return Err(format!( - "curated plugins backup archive git ref contains invalid path components: {reference}" - )); - } - } - } - - Ok(reference) -} - -fn read_git_ref_sha(git_dir: &Path, reference: &str) -> Result { - let ref_path = git_dir.join(reference); - if let Ok(sha) = std::fs::read_to_string(&ref_path) { - let sha = sha.trim(); - if sha.is_empty() { - return Err(format!( - "curated plugins backup archive git ref {reference} is empty at {}", - ref_path.display() - )); - } - return Ok(sha.to_string()); - } - - let packed_refs_path = git_dir.join("packed-refs"); - if let Ok(packed_refs) = std::fs::read_to_string(&packed_refs_path) - && let Some(sha) = packed_refs.lines().find_map(|line| { - let trimmed = line.trim(); - if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with('^') { - return None; - } - let (sha, candidate_ref) = trimmed.split_once(' ')?; - (candidate_ref == reference).then_some(sha.to_string()) - }) - { - return Ok(sha); - } - - Err(format!( - "failed to resolve curated plugins backup archive git ref {reference} from {}", - git_dir.display() - )) -} - -async fn fetch_github_text(client: &Client, url: &str, context: &str) -> Result { - let response = github_request(client, url) - .send() - .await - .map_err(|err| format!("failed to {context} from {url}: {err}"))?; - let status = response.status(); - let body = response.text().await.unwrap_or_default(); - if !status.is_success() { - return Err(format!( - "{context} from {url} failed with status {status}: {body}" - )); - } - Ok(body) -} - -async fn fetch_github_bytes(client: &Client, url: &str, context: &str) -> Result, String> { - let response = github_request(client, url) - .send() - .await - .map_err(|err| format!("failed to {context} from {url}: {err}"))?; - let status = response.status(); - let body = response - .bytes() - .await - .map_err(|err| format!("failed to read {context} response from {url}: {err}"))?; - if !status.is_success() { - let body_text = String::from_utf8_lossy(&body); - return Err(format!( - "{context} from {url} failed with status {status}: {body_text}" - )); - } - Ok(body.to_vec()) -} - -async fn fetch_public_text(client: &Client, url: &str, context: &str) -> Result { - let response = client - .get(url) - .timeout(CURATED_PLUGINS_BACKUP_ARCHIVE_TIMEOUT) - .send() - .await - .map_err(|err| format!("failed to {context} from {url}: {err}"))?; - let status = response.status(); - let body = response.text().await.unwrap_or_default(); - if !status.is_success() { - return Err(format!( - "{context} from {url} failed with status {status}: {body}" - )); - } - Ok(body) -} - -async fn fetch_public_bytes(client: &Client, url: &str, context: &str) -> Result, String> { - let response = client - .get(url) - .timeout(CURATED_PLUGINS_BACKUP_ARCHIVE_TIMEOUT) - .send() - .await - .map_err(|err| format!("failed to {context} from {url}: {err}"))?; - let status = response.status(); - let body = response - .bytes() - .await - .map_err(|err| format!("failed to read {context} response from {url}: {err}"))?; - if !status.is_success() { - let body_text = String::from_utf8_lossy(&body); - return Err(format!( - "{context} from {url} failed with status {status}: {body_text}" - )); - } - Ok(body.to_vec()) -} - -fn github_request(client: &Client, url: &str) -> reqwest::RequestBuilder { - client - .get(url) - .timeout(CURATED_PLUGINS_HTTP_TIMEOUT) - .header("accept", GITHUB_API_ACCEPT_HEADER) - .header("x-github-api-version", GITHUB_API_VERSION_HEADER) -} - -fn read_sha_file(sha_path: &Path) -> Option { - std::fs::read_to_string(sha_path) - .ok() - .map(|sha| sha.trim().to_string()) - .filter(|sha| !sha.is_empty()) -} - -fn extract_zipball_to_dir(bytes: &[u8], destination: &Path) -> Result<(), String> { - std::fs::create_dir_all(destination).map_err(|err| { - format!( - "failed to create curated plugins extraction directory {}: {err}", - destination.display() - ) - })?; - - let cursor = std::io::Cursor::new(bytes); - let mut archive = ZipArchive::new(cursor) - .map_err(|err| format!("failed to open curated plugins zip archive: {err}"))?; - - for index in 0..archive.len() { - let mut entry = archive - .by_index(index) - .map_err(|err| format!("failed to read curated plugins zip entry: {err}"))?; - let Some(relative_path) = entry.enclosed_name() else { - return Err(format!( - "curated plugins zip entry `{}` escapes extraction root", - entry.name() - )); - }; - - let mut components = relative_path.components(); - let Some(std::path::Component::Normal(_)) = components.next() else { - continue; - }; - - let output_relative = components.fold(PathBuf::new(), |mut path, component| { - if let std::path::Component::Normal(segment) = component { - path.push(segment); - } - path - }); - if output_relative.as_os_str().is_empty() { - continue; - } - - let output_path = destination.join(&output_relative); - if entry.is_dir() { - std::fs::create_dir_all(&output_path).map_err(|err| { - format!( - "failed to create curated plugins directory {}: {err}", - output_path.display() - ) - })?; - continue; - } - - if let Some(parent) = output_path.parent() { - std::fs::create_dir_all(parent).map_err(|err| { - format!( - "failed to create curated plugins directory {}: {err}", - parent.display() - ) - })?; - } - let mut output = std::fs::File::create(&output_path).map_err(|err| { - format!( - "failed to create curated plugins file {}: {err}", - output_path.display() - ) - })?; - std::io::copy(&mut entry, &mut output).map_err(|err| { - format!( - "failed to write curated plugins file {}: {err}", - output_path.display() - ) - })?; - apply_zip_permissions(&entry, &output_path)?; - } - - Ok(()) -} - -#[cfg(unix)] -fn apply_zip_permissions(entry: &zip::read::ZipFile<'_>, output_path: &Path) -> Result<(), String> { - use std::os::unix::fs::PermissionsExt; - - let Some(mode) = entry.unix_mode() else { - return Ok(()); - }; - std::fs::set_permissions(output_path, std::fs::Permissions::from_mode(mode)).map_err(|err| { - format!( - "failed to set permissions on curated plugins file {}: {err}", - output_path.display() - ) - }) -} - -#[cfg(not(unix))] -fn apply_zip_permissions( - _entry: &zip::read::ZipFile<'_>, - _output_path: &Path, -) -> Result<(), String> { - Ok(()) -} - -#[cfg(test)] -#[path = "startup_sync_tests.rs"] -mod tests; diff --git a/vendor/codex/codex-rs/core/src/plugins/startup_sync_tests.rs b/vendor/codex/codex-rs/core/src/plugins/startup_sync_tests.rs deleted file mode 100644 index 74dd0d0f..00000000 --- a/vendor/codex/codex-rs/core/src/plugins/startup_sync_tests.rs +++ /dev/null @@ -1,792 +0,0 @@ -use super::*; -use crate::config::CONFIG_TOML_FILE; -use crate::plugins::test_support::TEST_CURATED_PLUGIN_SHA; -use crate::plugins::test_support::write_curated_plugin_sha; -use crate::plugins::test_support::write_file; -use crate::plugins::test_support::write_openai_curated_marketplace; -use codex_login::CodexAuth; -use pretty_assertions::assert_eq; -use std::io::Write; -use std::path::Path; -use std::path::PathBuf; -use tempfile::tempdir; -use wiremock::Mock; -use wiremock::MockServer; -use wiremock::ResponseTemplate; -use wiremock::matchers::header; -use wiremock::matchers::method; -use wiremock::matchers::path; -use zip::ZipWriter; -use zip::write::SimpleFileOptions; - -fn has_plugins_clone_dirs(codex_home: &Path) -> bool { - let Ok(entries) = std::fs::read_dir(codex_home.join(".tmp")) else { - return false; - }; - - entries.flatten().any(|entry| { - let path = entry.path(); - path.is_dir() - && path - .file_name() - .and_then(|name| name.to_str()) - .is_some_and(|name| name.starts_with("plugins-clone-")) - }) -} - -#[cfg(unix)] -fn write_executable_script(path: &Path, contents: &str) { - #[cfg(unix)] - use std::os::unix::fs::PermissionsExt; - - std::fs::write(path, contents).expect("write script"); - #[cfg(unix)] - { - let mut permissions = std::fs::metadata(path).expect("metadata").permissions(); - permissions.set_mode(0o755); - std::fs::set_permissions(path, permissions).expect("chmod"); - } -} - -async fn mount_github_repo_and_ref(server: &MockServer, sha: &str) { - Mock::given(method("GET")) - .and(path("/repos/openai/plugins")) - .respond_with(ResponseTemplate::new(200).set_body_string(r#"{"default_branch":"main"}"#)) - .mount(server) - .await; - Mock::given(method("GET")) - .and(path("/repos/openai/plugins/git/ref/heads/main")) - .respond_with( - ResponseTemplate::new(200) - .set_body_string(format!(r#"{{"object":{{"sha":"{sha}"}}}}"#)), - ) - .mount(server) - .await; -} - -async fn mount_github_zipball(server: &MockServer, sha: &str, bytes: Vec) { - Mock::given(method("GET")) - .and(path(format!("/repos/openai/plugins/zipball/{sha}"))) - .respond_with( - ResponseTemplate::new(200) - .insert_header("content-type", "application/zip") - .set_body_bytes(bytes), - ) - .mount(server) - .await; -} - -async fn mount_export_archive(server: &MockServer, bytes: Vec) -> String { - let export_api_url = format!("{}/backend-api/plugins/export/curated", server.uri()); - Mock::given(method("GET")) - .and(path("/backend-api/plugins/export/curated")) - .respond_with(ResponseTemplate::new(200).set_body_string(format!( - r#"{{"download_url":"{}/files/curated-plugins.zip"}}"#, - server.uri() - ))) - .mount(server) - .await; - Mock::given(method("GET")) - .and(path("/files/curated-plugins.zip")) - .respond_with( - ResponseTemplate::new(200) - .insert_header("content-type", "application/zip") - .set_body_bytes(bytes), - ) - .mount(server) - .await; - export_api_url -} - -async fn run_sync_with_transport_overrides( - codex_home: PathBuf, - git_binary: impl Into, - api_base_url: impl Into, - backup_archive_api_url: impl Into, -) -> Result { - let git_binary = git_binary.into(); - let api_base_url = api_base_url.into(); - let backup_archive_api_url = backup_archive_api_url.into(); - tokio::task::spawn_blocking(move || { - sync_openai_plugins_repo_with_transport_overrides( - codex_home.as_path(), - &git_binary, - &api_base_url, - &backup_archive_api_url, - ) - }) - .await - .expect("sync task should join") -} - -async fn run_http_sync( - codex_home: PathBuf, - api_base_url: impl Into, -) -> Result { - let api_base_url = api_base_url.into(); - tokio::task::spawn_blocking(move || { - sync_openai_plugins_repo_via_http(codex_home.as_path(), &api_base_url) - }) - .await - .expect("sync task should join") -} - -fn assert_curated_gmail_repo(repo_path: &Path) { - assert!(repo_path.join(".agents/plugins/marketplace.json").is_file()); - assert!( - repo_path - .join("plugins/gmail/.codex-plugin/plugin.json") - .is_file() - ); -} - -#[test] -fn curated_plugins_repo_path_uses_codex_home_tmp_dir() { - let tmp = tempdir().expect("tempdir"); - assert_eq!( - curated_plugins_repo_path(tmp.path()), - tmp.path().join(".tmp/plugins") - ); -} - -#[test] -fn read_curated_plugins_sha_reads_trimmed_sha_file() { - let tmp = tempdir().expect("tempdir"); - std::fs::create_dir_all(tmp.path().join(".tmp")).expect("create tmp"); - std::fs::write(tmp.path().join(".tmp/plugins.sha"), "abc123\n").expect("write sha"); - - assert_eq!( - read_curated_plugins_sha(tmp.path()).as_deref(), - Some("abc123") - ); -} - -#[cfg(unix)] -#[test] -fn remove_stale_curated_repo_temp_dirs_removes_only_matching_directories() { - use std::os::unix::ffi::OsStrExt; - use std::time::SystemTime; - - fn set_dir_mtime(path: &Path, age: Duration) -> Result<(), Box> { - let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?; - let modified_at = now.saturating_sub(age); - let tv_sec = i64::try_from(modified_at.as_secs())?; - let ts = libc::timespec { tv_sec, tv_nsec: 0 }; - let times = [ts, ts]; - let c_path = std::ffi::CString::new(path.as_os_str().as_bytes())?; - let result = unsafe { libc::utimensat(libc::AT_FDCWD, c_path.as_ptr(), times.as_ptr(), 0) }; - if result != 0 { - return Err(std::io::Error::last_os_error().into()); - } - Ok(()) - } - - let tmp = tempdir().expect("tempdir"); - let parent = tmp.path().join(".tmp"); - let stale_clone_dir = parent.join("plugins-clone-stale"); - let fresh_clone_dir = parent.join("plugins-clone-fresh"); - let unrelated_dir = parent.join("plugins-cache"); - - std::fs::create_dir_all(&stale_clone_dir).expect("create stale clone dir"); - std::fs::create_dir_all(&fresh_clone_dir).expect("create fresh clone dir"); - std::fs::create_dir_all(&unrelated_dir).expect("create unrelated dir"); - set_dir_mtime( - &stale_clone_dir, - CURATED_PLUGINS_STALE_TEMP_DIR_MAX_AGE + Duration::from_secs(60), - ) - .expect("age stale clone dir"); - set_dir_mtime(&fresh_clone_dir, Duration::ZERO).expect("age fresh clone dir"); - - remove_stale_curated_repo_temp_dirs(&parent, CURATED_PLUGINS_STALE_TEMP_DIR_MAX_AGE); - - assert!(!stale_clone_dir.exists()); - assert!(fresh_clone_dir.is_dir()); - assert!(unrelated_dir.is_dir()); -} - -#[cfg(unix)] -#[test] -fn sync_openai_plugins_repo_prefers_git_when_available() { - let tmp = tempdir().expect("tempdir"); - let bin_dir = tempfile::Builder::new() - .prefix("fake-git-") - .tempdir() - .expect("tempdir"); - let git_path = bin_dir.path().join("git"); - let sha = "0123456789abcdef0123456789abcdef01234567"; - - write_executable_script( - &git_path, - &format!( - r#"#!/bin/sh -if [ "$1" = "ls-remote" ]; then - printf '%s\tHEAD\n' "{sha}" - exit 0 -fi -if [ "$1" = "clone" ]; then - dest="$5" - mkdir -p "$dest/.git" "$dest/.agents/plugins" "$dest/plugins/gmail/.codex-plugin" - cat > "$dest/.agents/plugins/marketplace.json" <<'EOF' -{{"name":"openai-curated","plugins":[{{"name":"gmail","source":{{"source":"local","path":"./plugins/gmail"}}}}]}} -EOF - printf '%s\n' '{{"name":"gmail"}}' > "$dest/plugins/gmail/.codex-plugin/plugin.json" - exit 0 -fi -if [ "$1" = "-C" ] && [ "$3" = "rev-parse" ] && [ "$4" = "HEAD" ]; then - printf '%s\n' "{sha}" - exit 0 -fi -echo "unexpected git invocation: $@" >&2 -exit 1 -"# - ), - ); - - let synced_sha = sync_openai_plugins_repo_with_transport_overrides( - tmp.path(), - git_path.to_str().expect("utf8 path"), - "http://127.0.0.1:9", - "http://127.0.0.1:9/backend-api/plugins/export/curated", - ) - .expect("git sync should succeed"); - - assert_eq!(synced_sha, sha); - let repo_path = curated_plugins_repo_path(tmp.path()); - assert!(repo_path.join(".git").is_dir()); - assert_curated_gmail_repo(&repo_path); - assert_eq!(read_curated_plugins_sha(tmp.path()).as_deref(), Some(sha)); -} - -#[cfg(unix)] -#[test] -fn sync_openai_plugins_repo_via_git_succeeds_with_local_rewritten_remote() { - let tmp = tempdir().expect("tempdir"); - let repo_root = tempfile::Builder::new() - .prefix("curated-repo-success-") - .tempdir() - .expect("tempdir"); - let work_repo = repo_root.path().join("work/plugins"); - let remote_repo = repo_root.path().join("remotes/openai/plugins.git"); - std::fs::create_dir_all(work_repo.join(".agents/plugins")).expect("create marketplace dir"); - std::fs::create_dir_all(work_repo.join("plugins/gmail/.codex-plugin")) - .expect("create plugin dir"); - std::fs::write( - work_repo.join(".agents/plugins/marketplace.json"), - r#"{"name":"openai-curated","plugins":[{"name":"gmail","source":{"source":"local","path":"./plugins/gmail"}}]}"#, - ) - .expect("write marketplace"); - std::fs::write( - work_repo.join("plugins/gmail/.codex-plugin/plugin.json"), - r#"{"name":"gmail"}"#, - ) - .expect("write plugin manifest"); - - let init_status = Command::new("git") - .arg("-C") - .arg(&work_repo) - .arg("init") - .status() - .expect("run git init"); - assert!(init_status.success()); - - let add_status = Command::new("git") - .arg("-C") - .arg(&work_repo) - .arg("add") - .arg(".") - .status() - .expect("run git add"); - assert!(add_status.success()); - - let commit_status = Command::new("git") - .arg("-C") - .arg(&work_repo) - .arg("-c") - .arg("user.name=Codex Test") - .arg("-c") - .arg("user.email=codex@example.com") - .arg("commit") - .arg("-m") - .arg("init") - .status() - .expect("run git commit"); - assert!(commit_status.success()); - - std::fs::create_dir_all(remote_repo.parent().expect("remote parent")) - .expect("create remote parent"); - let clone_status = Command::new("git") - .arg("clone") - .arg("--bare") - .arg(&work_repo) - .arg(&remote_repo) - .status() - .expect("run git clone --bare"); - assert!(clone_status.success()); - - let sha_output = Command::new("git") - .arg("-C") - .arg(&work_repo) - .arg("rev-parse") - .arg("HEAD") - .output() - .expect("run git rev-parse"); - assert!(sha_output.status.success()); - let sha = String::from_utf8_lossy(&sha_output.stdout) - .trim() - .to_string(); - - let git_config_path = repo_root.path().join("git-rewrite.conf"); - std::fs::write( - &git_config_path, - format!( - "[url \"file://{}/\"]\n insteadOf = https://github.com/\n", - repo_root.path().join("remotes").display() - ), - ) - .expect("write git config"); - - let bin_dir = tempfile::Builder::new() - .prefix("git-rewrite-wrapper-") - .tempdir() - .expect("tempdir"); - let git_wrapper = bin_dir.path().join("git"); - write_executable_script( - &git_wrapper, - &format!( - "#!/bin/sh\nGIT_CONFIG_GLOBAL='{}' exec git \"$@\"\n", - git_config_path.display() - ), - ); - - let synced_sha = - sync_openai_plugins_repo_via_git(tmp.path(), git_wrapper.to_str().expect("utf8 path")) - .expect("git sync should succeed"); - - assert_eq!(synced_sha, sha); - assert_curated_gmail_repo(&curated_plugins_repo_path(tmp.path())); - assert_eq!( - read_curated_plugins_sha(tmp.path()).as_deref(), - Some(sha.as_str()) - ); - assert!(!has_plugins_clone_dirs(tmp.path())); -} - -#[tokio::test] -async fn sync_openai_plugins_repo_falls_back_to_http_when_git_is_unavailable() { - let tmp = tempdir().expect("tempdir"); - let server = MockServer::start().await; - let sha = "0123456789abcdef0123456789abcdef01234567"; - - mount_github_repo_and_ref(&server, sha).await; - mount_github_zipball(&server, sha, curated_repo_zipball_bytes(sha)).await; - - let synced_sha = run_sync_with_transport_overrides( - tmp.path().to_path_buf(), - "missing-git-for-test", - server.uri(), - "http://127.0.0.1:9/backend-api/plugins/export/curated", - ) - .await - .expect("fallback sync should succeed"); - - let repo_path = curated_plugins_repo_path(tmp.path()); - assert_eq!(synced_sha, sha); - assert_curated_gmail_repo(&repo_path); - assert_eq!(read_curated_plugins_sha(tmp.path()).as_deref(), Some(sha)); -} - -#[cfg(unix)] -#[tokio::test] -async fn sync_openai_plugins_repo_falls_back_to_http_when_git_sync_fails() { - let tmp = tempdir().expect("tempdir"); - let bin_dir = tempfile::Builder::new() - .prefix("fake-git-fail-") - .tempdir() - .expect("tempdir"); - let git_path = bin_dir.path().join("git"); - let sha = "0123456789abcdef0123456789abcdef01234567"; - - write_executable_script( - &git_path, - r#"#!/bin/sh -echo "simulated git failure" >&2 -exit 1 -"#, - ); - - let server = MockServer::start().await; - mount_github_repo_and_ref(&server, sha).await; - mount_github_zipball(&server, sha, curated_repo_zipball_bytes(sha)).await; - - let synced_sha = run_sync_with_transport_overrides( - tmp.path().to_path_buf(), - git_path.to_str().expect("utf8 path"), - server.uri(), - "http://127.0.0.1:9/backend-api/plugins/export/curated", - ) - .await - .expect("fallback sync should succeed"); - - let repo_path = curated_plugins_repo_path(tmp.path()); - assert_eq!(synced_sha, sha); - assert_curated_gmail_repo(&repo_path); - assert_eq!(read_curated_plugins_sha(tmp.path()).as_deref(), Some(sha)); -} - -#[cfg(unix)] -#[test] -fn sync_openai_plugins_repo_via_git_cleans_up_staged_dir_on_clone_failure() { - let tmp = tempdir().expect("tempdir"); - let bin_dir = tempfile::Builder::new() - .prefix("fake-git-partial-fail-") - .tempdir() - .expect("tempdir"); - let git_path = bin_dir.path().join("git"); - let sha = "0123456789abcdef0123456789abcdef01234567"; - - write_executable_script( - &git_path, - &format!( - r#"#!/bin/sh -if [ "$1" = "ls-remote" ]; then - printf '%s\tHEAD\n' "{sha}" - exit 0 -fi -if [ "$1" = "clone" ]; then - dest="$5" - mkdir -p "$dest/.git" - echo "fatal: early EOF" >&2 - exit 128 -fi -echo "unexpected git invocation: $@" >&2 -exit 1 -"# - ), - ); - - let err = sync_openai_plugins_repo_via_git(tmp.path(), git_path.to_str().expect("utf8 path")) - .expect_err("git sync should fail"); - - assert!(err.contains("fatal: early EOF")); - assert!(!has_plugins_clone_dirs(tmp.path())); -} - -#[tokio::test] -async fn sync_openai_plugins_repo_via_http_cleans_up_staged_dir_on_extract_failure() { - let tmp = tempdir().expect("tempdir"); - let server = MockServer::start().await; - let sha = "0123456789abcdef0123456789abcdef01234567"; - - mount_github_repo_and_ref(&server, sha).await; - mount_github_zipball(&server, sha, b"not a zip archive".to_vec()).await; - - let err = run_http_sync(tmp.path().to_path_buf(), server.uri()) - .await - .expect_err("http sync should fail"); - - assert!(err.contains("failed to open curated plugins zip archive")); - assert!(!has_plugins_clone_dirs(tmp.path())); -} - -#[tokio::test] -async fn sync_openai_plugins_repo_skips_archive_download_when_sha_matches() { - let tmp = tempdir().expect("tempdir"); - let repo_path = curated_plugins_repo_path(tmp.path()); - std::fs::create_dir_all(repo_path.join(".agents/plugins")).expect("create repo"); - std::fs::write( - repo_path.join(".agents/plugins/marketplace.json"), - r#"{"name":"openai-curated","plugins":[]}"#, - ) - .expect("write marketplace"); - std::fs::create_dir_all(tmp.path().join(".tmp")).expect("create tmp"); - let sha = "fedcba9876543210fedcba9876543210fedcba98"; - std::fs::write(tmp.path().join(".tmp/plugins.sha"), format!("{sha}\n")).expect("write sha"); - - let server = MockServer::start().await; - mount_github_repo_and_ref(&server, sha).await; - - run_sync_with_transport_overrides( - tmp.path().to_path_buf(), - "missing-git-for-test", - server.uri(), - "http://127.0.0.1:9/backend-api/plugins/export/curated", - ) - .await - .expect("sync should succeed"); - - assert_eq!(read_curated_plugins_sha(tmp.path()).as_deref(), Some(sha)); - assert!(repo_path.join(".agents/plugins/marketplace.json").is_file()); -} - -#[tokio::test] -async fn sync_openai_plugins_repo_falls_back_to_export_archive_when_no_snapshot_exists() { - let tmp = tempdir().expect("tempdir"); - let server = MockServer::start().await; - let export_sha = "1111111111111111111111111111111111111111"; - - Mock::given(method("GET")) - .and(path("/repos/openai/plugins")) - .respond_with(ResponseTemplate::new(500).set_body_string("github repo lookup failed")) - .mount(&server) - .await; - let export_api_url = - mount_export_archive(&server, curated_repo_backup_archive_zip_bytes(export_sha)).await; - - let synced_sha = run_sync_with_transport_overrides( - tmp.path().to_path_buf(), - "missing-git-for-test", - server.uri(), - export_api_url, - ) - .await - .expect("export fallback sync should succeed"); - - let repo_path = curated_plugins_repo_path(tmp.path()); - assert_eq!(synced_sha, export_sha); - assert_curated_gmail_repo(&repo_path); - assert_eq!( - read_curated_plugins_sha(tmp.path()).as_deref(), - Some(export_sha) - ); -} - -#[tokio::test] -async fn sync_openai_plugins_repo_skips_export_archive_when_snapshot_exists() { - let tmp = tempdir().expect("tempdir"); - let curated_root = curated_plugins_repo_path(tmp.path()); - write_openai_curated_marketplace(&curated_root, &["linear"]); - write_curated_plugin_sha(tmp.path()); - - let plugin_manifest_path = curated_root.join("plugins/linear/.codex-plugin/plugin.json"); - let original_manifest = - std::fs::read_to_string(&plugin_manifest_path).expect("read existing plugin manifest"); - - let server = MockServer::start().await; - - Mock::given(method("GET")) - .and(path("/repos/openai/plugins")) - .respond_with(ResponseTemplate::new(500).set_body_string("github repo lookup failed")) - .mount(&server) - .await; - let export_api_url = mount_export_archive( - &server, - curated_repo_backup_archive_zip_bytes("2222222222222222222222222222222222222222"), - ) - .await; - - let err = run_sync_with_transport_overrides( - tmp.path().to_path_buf(), - "missing-git-for-test", - server.uri(), - export_api_url, - ) - .await - .expect_err("existing snapshot should suppress export fallback"); - - assert!(err.contains("export archive fallback skipped")); - assert_eq!( - std::fs::read_to_string(&plugin_manifest_path).expect("read plugin manifest after sync"), - original_manifest - ); - assert_eq!( - read_curated_plugins_sha(tmp.path()).as_deref(), - Some(TEST_CURATED_PLUGIN_SHA) - ); -} - -#[test] -fn read_extracted_backup_archive_git_sha_reads_head_ref_from_extracted_repo() { - let tmp = tempdir().expect("tempdir"); - let git_dir = tmp.path().join(".git/refs/heads"); - std::fs::create_dir_all(&git_dir).expect("create git ref dir"); - std::fs::write(tmp.path().join(".git/HEAD"), "ref: refs/heads/main\n").expect("write HEAD"); - std::fs::write( - git_dir.join("main"), - "3333333333333333333333333333333333333333\n", - ) - .expect("write main ref"); - - assert_eq!( - read_extracted_backup_archive_git_sha(tmp.path()) - .expect("read extracted backup archive git sha"), - Some("3333333333333333333333333333333333333333".to_string()) - ); -} - -#[test] -fn read_extracted_backup_archive_git_sha_rejects_non_refs_head_target() { - let tmp = tempdir().expect("tempdir"); - std::fs::create_dir_all(tmp.path().join(".git")).expect("create git dir"); - std::fs::write(tmp.path().join(".git/HEAD"), "ref: HEAD\n").expect("write HEAD"); - - let err = read_extracted_backup_archive_git_sha(tmp.path()) - .expect_err("non-refs target should be rejected"); - - assert!(err.contains("must stay under refs/")); -} - -#[test] -fn read_extracted_backup_archive_git_sha_rejects_path_traversal_ref() { - let tmp = tempdir().expect("tempdir"); - std::fs::create_dir_all(tmp.path().join(".git")).expect("create git dir"); - std::fs::write(tmp.path().join(".git/HEAD"), "ref: refs/heads/../../evil\n") - .expect("write HEAD"); - - let err = read_extracted_backup_archive_git_sha(tmp.path()) - .expect_err("path traversal ref should be rejected"); - - assert!(err.contains("invalid path components")); -} - -#[tokio::test] -async fn startup_remote_plugin_sync_writes_marker_and_reconciles_state() { - let tmp = tempdir().expect("tempdir"); - let curated_root = curated_plugins_repo_path(tmp.path()); - write_openai_curated_marketplace(&curated_root, &["linear"]); - write_curated_plugin_sha(tmp.path()); - write_file( - &tmp.path().join(CONFIG_TOML_FILE), - r#"[features] -plugins = true - -[plugins."linear@openai-curated"] -enabled = false -"#, - ); - - let server = MockServer::start().await; - Mock::given(method("GET")) - .and(path("/backend-api/plugins/list")) - .and(header("authorization", "Bearer Access Token")) - .and(header("chatgpt-account-id", "account_id")) - .respond_with(ResponseTemplate::new(200).set_body_string( - r#"[ - {"id":"1","name":"linear","marketplace_name":"openai-curated","version":"1.0.0","enabled":true} -]"#, - )) - .mount(&server) - .await; - - let mut config = crate::plugins::test_support::load_plugins_config(tmp.path()).await; - config.chatgpt_base_url = format!("{}/backend-api/", server.uri()); - let manager = Arc::new(PluginsManager::new(tmp.path().to_path_buf())); - let auth_manager = - AuthManager::from_auth_for_testing(CodexAuth::create_dummy_chatgpt_auth_for_testing()); - - start_startup_remote_plugin_sync_once( - Arc::clone(&manager), - tmp.path().to_path_buf(), - config, - auth_manager, - ); - - let marker_path = tmp.path().join(STARTUP_REMOTE_PLUGIN_SYNC_MARKER_FILE); - tokio::time::timeout(Duration::from_secs(5), async { - loop { - if marker_path.is_file() { - break; - } - tokio::time::sleep(Duration::from_millis(10)).await; - } - }) - .await - .expect("marker should be written"); - - assert!( - tmp.path() - .join(format!( - "plugins/cache/openai-curated/linear/{TEST_CURATED_PLUGIN_SHA}" - )) - .is_dir() - ); - let config = - std::fs::read_to_string(tmp.path().join(CONFIG_TOML_FILE)).expect("config should exist"); - assert!(config.contains(r#"[plugins."linear@openai-curated"]"#)); - assert!(config.contains("enabled = true")); - - let marker_contents = std::fs::read_to_string(marker_path).expect("marker should be readable"); - assert_eq!(marker_contents, "ok\n"); -} - -fn curated_repo_zipball_bytes(sha: &str) -> Vec { - let cursor = std::io::Cursor::new(Vec::new()); - let mut writer = ZipWriter::new(cursor); - let options = SimpleFileOptions::default(); - let root = format!("openai-plugins-{sha}"); - writer - .start_file(format!("{root}/.agents/plugins/marketplace.json"), options) - .expect("start marketplace entry"); - writer - .write_all( - br#"{ - "name": "openai-curated", - "plugins": [ - { - "name": "gmail", - "source": { - "source": "local", - "path": "./plugins/gmail" - } - } - ] -}"#, - ) - .expect("write marketplace"); - writer - .start_file( - format!("{root}/plugins/gmail/.codex-plugin/plugin.json"), - options, - ) - .expect("start plugin manifest entry"); - writer - .write_all(br#"{"name":"gmail"}"#) - .expect("write plugin manifest"); - - writer.finish().expect("finish zip writer").into_inner() -} - -fn curated_repo_backup_archive_zip_bytes(sha: &str) -> Vec { - let cursor = std::io::Cursor::new(Vec::new()); - let mut writer = ZipWriter::new(cursor); - let options = SimpleFileOptions::default(); - - writer - .start_file("plugins/.git/HEAD", options) - .expect("start HEAD entry"); - writer - .write_all(b"ref: refs/heads/main\n") - .expect("write HEAD"); - writer - .start_file("plugins/.git/refs/heads/main", options) - .expect("start main ref entry"); - writer - .write_all(format!("{sha}\n").as_bytes()) - .expect("write main ref"); - writer - .start_file("plugins/.agents/plugins/marketplace.json", options) - .expect("start marketplace entry"); - writer - .write_all( - br#"{ - "name": "openai-curated", - "plugins": [ - { - "name": "gmail", - "source": { - "source": "local", - "path": "./plugins/gmail" - } - } - ] -}"#, - ) - .expect("write marketplace"); - writer - .start_file("plugins/plugins/gmail/.codex-plugin/plugin.json", options) - .expect("start plugin manifest entry"); - writer - .write_all(br#"{"name":"gmail"}"#) - .expect("write plugin manifest"); - - writer.finish().expect("finish zip writer").into_inner() -} diff --git a/vendor/codex/codex-rs/core/src/plugins/test_support.rs b/vendor/codex/codex-rs/core/src/plugins/test_support.rs deleted file mode 100644 index 8624d408..00000000 --- a/vendor/codex/codex-rs/core/src/plugins/test_support.rs +++ /dev/null @@ -1,109 +0,0 @@ -use crate::config::CONFIG_TOML_FILE; -use crate::config::ConfigBuilder; -use std::fs; -use std::path::Path; - -use super::OPENAI_CURATED_MARKETPLACE_NAME; - -pub(crate) const TEST_CURATED_PLUGIN_SHA: &str = "0123456789abcdef0123456789abcdef01234567"; - -pub(crate) fn write_file(path: &Path, contents: &str) { - fs::create_dir_all(path.parent().expect("file should have a parent")).unwrap(); - fs::write(path, contents).unwrap(); -} - -pub(crate) fn write_curated_plugin(root: &Path, plugin_name: &str) { - let plugin_root = root.join("plugins").join(plugin_name); - write_file( - &plugin_root.join(".codex-plugin/plugin.json"), - &format!( - r#"{{ - "name": "{plugin_name}", - "description": "Plugin that includes skills, MCP servers, and app connectors" -}}"# - ), - ); - write_file( - &plugin_root.join("skills/SKILL.md"), - "---\nname: sample\ndescription: sample\n---\n", - ); - write_file( - &plugin_root.join(".mcp.json"), - r#"{ - "mcpServers": { - "sample-docs": { - "type": "http", - "url": "https://sample.example/mcp" - } - } -}"#, - ); - write_file( - &plugin_root.join(".app.json"), - r#"{ - "apps": { - "calendar": { - "id": "connector_calendar" - } - } -}"#, - ); -} - -pub(crate) fn write_openai_curated_marketplace(root: &Path, plugin_names: &[&str]) { - let plugins = plugin_names - .iter() - .map(|plugin_name| { - format!( - r#"{{ - "name": "{plugin_name}", - "source": {{ - "source": "local", - "path": "./plugins/{plugin_name}" - }} - }}"# - ) - }) - .collect::>() - .join(",\n"); - write_file( - &root.join(".agents/plugins/marketplace.json"), - &format!( - r#"{{ - "name": "{OPENAI_CURATED_MARKETPLACE_NAME}", - "plugins": [ -{plugins} - ] -}}"# - ), - ); - for plugin_name in plugin_names { - write_curated_plugin(root, plugin_name); - } -} - -pub(crate) fn write_curated_plugin_sha(codex_home: &Path) { - write_curated_plugin_sha_with(codex_home, TEST_CURATED_PLUGIN_SHA); -} - -pub(crate) fn write_curated_plugin_sha_with(codex_home: &Path, sha: &str) { - write_file(&codex_home.join(".tmp/plugins.sha"), &format!("{sha}\n")); -} - -pub(crate) fn write_plugins_feature_config(codex_home: &Path) { - write_file( - &codex_home.join(CONFIG_TOML_FILE), - r#"[features] -plugins = true -"#, - ); -} - -pub(crate) async fn load_plugins_config(codex_home: &Path) -> crate::config::Config { - ConfigBuilder::default() - .codex_home(codex_home.to_path_buf()) - .fallback_cwd(Some(codex_home.to_path_buf())) - .build() - .await - .expect("config should load") -} diff --git a/vendor/codex/codex-rs/tui/src/app.rs b/vendor/codex/codex-rs/tui/src/app.rs index 8a909244..eb2e06b1 100644 --- a/vendor/codex/codex-rs/tui/src/app.rs +++ b/vendor/codex/codex-rs/tui/src/app.rs @@ -48,7 +48,6 @@ use crate::legacy_core::config::ConfigOverrides; use crate::legacy_core::config::edit::ConfigEdit; use crate::legacy_core::config::edit::ConfigEditsBuilder; use crate::legacy_core::lookup_message_history_entry; -use crate::legacy_core::plugins::PluginsManager; #[cfg(target_os = "windows")] use crate::legacy_core::windows_sandbox::WindowsSandboxLevelExt; use crate::model_catalog::ModelCatalog; diff --git a/vendor/codex/codex-rs/tui/src/app/app_server_adapter.rs b/vendor/codex/codex-rs/tui/src/app/app_server_adapter.rs index 7bf22a9e..fb2588d4 100644 --- a/vendor/codex/codex-rs/tui/src/app/app_server_adapter.rs +++ b/vendor/codex/codex-rs/tui/src/app/app_server_adapter.rs @@ -353,6 +353,9 @@ fn server_notification_thread_target( ServerNotification::ThreadEpiphanyStateUpdated(notification) => { Some(notification.thread_id.as_str()) } + ServerNotification::ThreadEpiphanyJobsUpdated(notification) => { + Some(notification.thread_id.as_str()) + } ServerNotification::TurnStarted(notification) => Some(notification.thread_id.as_str()), ServerNotification::HookStarted(notification) => Some(notification.thread_id.as_str()), ServerNotification::TurnCompleted(notification) => Some(notification.thread_id.as_str()), diff --git a/vendor/codex/codex-rs/tui/src/app/background_requests.rs b/vendor/codex/codex-rs/tui/src/app/background_requests.rs index 80879dbd..acf03eb8 100644 --- a/vendor/codex/codex-rs/tui/src/app/background_requests.rs +++ b/vendor/codex/codex-rs/tui/src/app/background_requests.rs @@ -199,23 +199,8 @@ impl App { } pub(super) fn refresh_plugin_mentions(&mut self) { - let config = self.config.clone(); let app_event_tx = self.app_event_tx.clone(); - if !config.features.enabled(Feature::Plugins) { - app_event_tx.send(AppEvent::PluginMentionsLoaded { plugins: None }); - return; - } - - tokio::spawn(async move { - let plugins = PluginsManager::new(config.codex_home.to_path_buf()) - .plugins_for_config(&config) - .await - .capability_summaries() - .to_vec(); - app_event_tx.send(AppEvent::PluginMentionsLoaded { - plugins: Some(plugins), - }); - }); + app_event_tx.send(AppEvent::PluginMentionsLoaded { plugins: None }); } pub(super) fn submit_feedback( diff --git a/vendor/codex/codex-rs/tui/src/chatwidget.rs b/vendor/codex/codex-rs/tui/src/chatwidget.rs index 257ea7b5..eeb7e428 100644 --- a/vendor/codex/codex-rs/tui/src/chatwidget.rs +++ b/vendor/codex/codex-rs/tui/src/chatwidget.rs @@ -6689,6 +6689,7 @@ impl ChatWidget { | ServerNotification::FuzzyFileSearchSessionCompleted(_) | ServerNotification::ThreadRealtimeTranscriptDelta(_) | ServerNotification::ThreadRealtimeTranscriptDone(_) + | ServerNotification::ThreadEpiphanyJobsUpdated(_) | ServerNotification::ThreadEpiphanyStateUpdated(_) | ServerNotification::WindowsWorldWritableWarning(_) | ServerNotification::WindowsSandboxSetupCompleted(_) diff --git a/vendor/codex/codex-rs/tui/src/chatwidget/plugins.rs b/vendor/codex/codex-rs/tui/src/chatwidget/plugins.rs index f330a80f..562671c3 100644 --- a/vendor/codex/codex-rs/tui/src/chatwidget/plugins.rs +++ b/vendor/codex/codex-rs/tui/src/chatwidget/plugins.rs @@ -12,7 +12,6 @@ use crate::bottom_pane::SelectionTab; use crate::bottom_pane::SelectionToggle; use crate::bottom_pane::SelectionViewParams; use crate::history_cell; -use crate::legacy_core::plugins::OPENAI_CURATED_MARKETPLACE_NAME; use crate::onboarding::mark_url_hyperlink; use crate::render::renderable::ColumnRenderable; use crate::render::renderable::Renderable; @@ -41,6 +40,7 @@ use unicode_width::UnicodeWidthStr; const PLUGINS_SELECTION_VIEW_ID: &str = "plugins-selection"; const ALL_PLUGINS_TAB_ID: &str = "all-plugins"; const INSTALLED_PLUGINS_TAB_ID: &str = "installed-plugins"; +const OPENAI_CURATED_MARKETPLACE_NAME: &str = "openai-curated"; const OPENAI_CURATED_TAB_ID: &str = "marketplace:openai-curated"; const PLUGIN_ROW_PREFIX_WIDTH: usize = 6; const LOADING_ANIMATION_DELAY: Duration = Duration::from_secs(1);