Delete codex core plugin product library

This commit is contained in:
Meta Vens 2026-05-13 14:07:13 +01:00
commit 49dd8dc52b
28 changed files with 45 additions and 8774 deletions

View file

@ -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

Binary file not shown.

View file

@ -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.

2
vendor/codex/codex-rs/Cargo.lock generated vendored
View file

@ -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",

View file

@ -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::*;
}

View file

@ -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<Vec<AppInfo>>
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<codex_core::plugins::AppConnectorId> {
PluginsManager::new(config.codex_home.to_path_buf())
.plugins_for_config(config)
.await
.effective_apps()
async fn plugin_apps_for_config(_config: &Config) -> Vec<String> {
Vec::new()
}
pub fn connectors_for_plugin_apps(
connectors: Vec<AppInfo>,
plugin_apps: &[AppConnectorId],
plugin_apps: &[String],
) -> Vec<AppInfo> {
let plugin_app_ids = plugin_apps
.iter()
.map(|connector_id| connector_id.0.as_str())
.map(String::as_str)
.collect::<HashSet<_>>();
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::<AppInfo>::new());
}

View file

@ -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<String>,
#[arg(
long = "sparse",
value_name = "PATH",
action = clap::ArgAction::Append
)]
sparse_paths: Vec<String>,
}
#[derive(Debug, Parser)]
struct UpgradeMarketplaceArgs {
marketplace_name: Option<String>,
}
#[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<String>,
}
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."
)
}
}

View file

@ -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 {

View file

@ -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 }

View file

@ -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;

View file

@ -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<AbsolutePathBuf> {
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::<Vec<_>>();
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<PathBuf> {
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)),
}
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -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<String>,
pub sparse_paths: Vec<String>,
}
#[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<MarketplaceAddOutcome, MarketplaceAddError> {
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<String>,
) -> Result<bool, MarketplaceAddError> {
Ok(matches!(
parse_marketplace_source(source, explicit_ref)?,
source::MarketplaceSource::Local { .. }
))
}
fn add_marketplace_sync(
codex_home: &Path,
request: MarketplaceAddRequest,
) -> Result<MarketplaceAddOutcome, MarketplaceAddError> {
add_marketplace_sync_with_cloner(codex_home, request, clone_git_source)
}
fn add_marketplace_sync_with_cloner<F>(
codex_home: &Path,
request: MarketplaceAddRequest,
clone_source: F,
) -> Result<MarketplaceAddOutcome, MarketplaceAddError>
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(())
}
}

View file

@ -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<String, MarketplaceAddError> {
let safe = marketplace_name
.chars()
.map(|ch| {
if ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | '.') {
ch
} else {
'-'
}
})
.collect::<String>();
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()
)))
}

View file

@ -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<String>,
sparse_paths: Vec<String>,
},
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: &timestamp,
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<Option<PathBuf>, 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<Option<PathBuf>, 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<String> {
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<String, MarketplaceAddError> {
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));
}
}

View file

@ -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<String>,
},
Local {
path: PathBuf,
},
}
pub(crate) fn parse_marketplace_source(
source: &str,
explicit_ref: Option<String>,
) -> Result<MarketplaceSource, MarketplaceAddError> {
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<F>(
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<String, MarketplaceAddError> {
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<String>) {
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<String> {
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<PathBuf, MarketplaceAddError> {
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()),
}
);
}
}

View file

@ -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<AbsolutePathBuf>,
}
#[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<MarketplaceRemoveOutcome, MarketplaceRemoveError> {
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<MarketplaceRemoveOutcome, MarketplaceRemoveError> {
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<Option<AbsolutePathBuf>, 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"));
}
}

View file

@ -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<McpServerConfig>;
pub type PluginLoadOutcome = codex_plugin::PluginLoadOutcome<McpServerConfig>;
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;

View file

@ -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 = "<plugins_instructions>\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</plugins_instructions>";
assert_eq!(rendered, expected);
}

File diff suppressed because it is too large Load diff

View file

@ -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<u8>) {
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<u8>) -> 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<String>,
api_base_url: impl Into<String>,
backup_archive_api_url: impl Into<String>,
) -> Result<String, String> {
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<String>,
) -> Result<String, String> {
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<dyn std::error::Error>> {
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<u8> {
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<u8> {
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()
}

View file

@ -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::<Vec<_>>()
.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")
}

View file

@ -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;

View file

@ -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()),

View file

@ -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(

View file

@ -6689,6 +6689,7 @@ impl ChatWidget {
| ServerNotification::FuzzyFileSearchSessionCompleted(_)
| ServerNotification::ThreadRealtimeTranscriptDelta(_)
| ServerNotification::ThreadRealtimeTranscriptDone(_)
| ServerNotification::ThreadEpiphanyJobsUpdated(_)
| ServerNotification::ThreadEpiphanyStateUpdated(_)
| ServerNotification::WindowsWorldWritableWarning(_)
| ServerNotification::WindowsSandboxSetupCompleted(_)

View file

@ -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);