WIP fase 2b-3: rimozione sottosistemi solo-ChatGPT (plugin remoti, image gen, daybreak, cyber, attestation, cloud config, app/connettori) - test in corso
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -16,15 +16,12 @@ workspace = true
|
||||
codex-utils-process = { workspace = true }
|
||||
anyhow = { workspace = true }
|
||||
chrono = { workspace = true }
|
||||
codex-api = { workspace = true }
|
||||
codex-app-server-protocol = { workspace = true }
|
||||
codex-config = { workspace = true }
|
||||
codex-connectors = { workspace = true }
|
||||
codex-core-plugin-common = { workspace = true }
|
||||
codex-exec-server = { workspace = true }
|
||||
codex-git-utils = { workspace = true }
|
||||
codex-hooks = { workspace = true }
|
||||
codex-http-client = { workspace = true }
|
||||
codex-login = { workspace = true }
|
||||
codex-mcp = { workspace = true }
|
||||
codex-model-provider = { workspace = true }
|
||||
@@ -45,7 +42,6 @@ http = { workspace = true }
|
||||
regex = { workspace = true }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
serde_json = { workspace = true }
|
||||
serde_with = { workspace = true }
|
||||
serde_yaml = { workspace = true }
|
||||
sha2 = { workspace = true }
|
||||
tar = { workspace = true }
|
||||
@@ -55,10 +51,8 @@ tokio = { workspace = true, features = ["fs", "macros", "rt", "time"] }
|
||||
toml = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
url = { workspace = true }
|
||||
uuid = { workspace = true, features = ["v4"] }
|
||||
|
||||
[dev-dependencies]
|
||||
base64 = { workspace = true }
|
||||
codex-exec-server-test-support = { workspace = true }
|
||||
codex-utils-cargo-bin = { workspace = true }
|
||||
pretty_assertions = { workspace = true }
|
||||
@@ -66,4 +60,3 @@ tempfile = { workspace = true }
|
||||
tokio = { workspace = true, features = ["test-util"] }
|
||||
tracing-subscriber = { workspace = true }
|
||||
tracing-test = { workspace = true, features = ["no-env-filter"] }
|
||||
wiremock = { workspace = true }
|
||||
|
||||
@@ -207,7 +207,6 @@ fn apply_codex_agent_plugin_extension(
|
||||
contents: &str,
|
||||
) -> Result<(), serde_json::Error> {
|
||||
let extension = parse_legacy_plugin_manifest_uri(plugin_root, source_path, contents)?;
|
||||
resolved.paths.apps = extension.paths.apps;
|
||||
resolved.paths.hooks = extension.paths.hooks;
|
||||
resolved.paths.onboarding_skill = extension.paths.onboarding_skill;
|
||||
if extension.interface.is_some() {
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
use crate::manifest::PluginManifestFormat;
|
||||
use crate::remote::REMOTE_GLOBAL_MARKETPLACE_NAME;
|
||||
use codex_plugin::AppDeclaration;
|
||||
use codex_plugin::PluginId;
|
||||
use codex_protocol::auth::AuthMode;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
|
||||
/// aKode never authenticates to ChatGPT, so account-backed services (remote plugin
|
||||
/// catalogs and app routes) are never available for any credential.
|
||||
pub fn apps_route_available(_auth_mode: Option<AuthMode>) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
pub(crate) fn plugin_supports_apps(format: PluginManifestFormat, plugin_id: &PluginId) -> bool {
|
||||
// The remote curated installer overwrites app declarations with plugin-service metadata.
|
||||
// Keep portable app declarations inactive for other Agent Plugins.
|
||||
format == PluginManifestFormat::Legacy
|
||||
|| plugin_id.marketplace_name == REMOTE_GLOBAL_MARKETPLACE_NAME
|
||||
}
|
||||
|
||||
pub(crate) fn apply_app_mcp_routing_policy<M>(
|
||||
apps: &mut Vec<AppDeclaration>,
|
||||
mcp_servers: &mut HashMap<String, M>,
|
||||
auth_mode: Option<AuthMode>,
|
||||
plugin_active: bool,
|
||||
) {
|
||||
if !apps_route_available(auth_mode) {
|
||||
apps.clear();
|
||||
return;
|
||||
}
|
||||
|
||||
if plugin_active && !apps.is_empty() {
|
||||
let app_declaration_names = apps
|
||||
.iter()
|
||||
.map(|app| app.name.as_str())
|
||||
.collect::<HashSet<_>>();
|
||||
mcp_servers.retain(|name, _| !app_declaration_names.contains(name.as_str()));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "app_mcp_routing_tests.rs"]
|
||||
mod tests;
|
||||
@@ -1,72 +0,0 @@
|
||||
use super::*;
|
||||
use codex_plugin::AppConnectorId;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::collections::HashMap;
|
||||
|
||||
fn app(name: &str) -> AppDeclaration {
|
||||
AppDeclaration {
|
||||
name: name.to_string(),
|
||||
connector_id: AppConnectorId(format!("connector_{name}")),
|
||||
category: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn mcp_servers(mcp_servers: impl IntoIterator<Item = (&'static str, i32)>) -> HashMap<String, i32> {
|
||||
mcp_servers
|
||||
.into_iter()
|
||||
.map(|(name, value)| (name.to_string(), value))
|
||||
.collect::<HashMap<_, _>>()
|
||||
}
|
||||
|
||||
fn sorted_mcp_server_names(mcp_servers: &HashMap<String, i32>) -> Vec<String> {
|
||||
let mut names = mcp_servers.keys().cloned().collect::<Vec<_>>();
|
||||
names.sort();
|
||||
names
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apps_route_is_never_available() {
|
||||
for auth_mode in [
|
||||
Some(AuthMode::ApiKey),
|
||||
Some(AuthMode::Headers),
|
||||
Some(AuthMode::BedrockApiKey),
|
||||
Some(AuthMode::BedrockAccessKeys),
|
||||
None,
|
||||
] {
|
||||
assert!(!apps_route_available(auth_mode));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn app_mcp_routing_clears_apps_when_apps_route_is_unavailable() {
|
||||
let mut apps = vec![app("linear")];
|
||||
let mut mcp_servers = mcp_servers([("linear", 1), ("docs", 2)]);
|
||||
|
||||
for (auth_mode, plugin_active) in [
|
||||
(Some(AuthMode::ApiKey), true),
|
||||
(Some(AuthMode::Headers), true),
|
||||
(Some(AuthMode::Headers), false),
|
||||
(None, true),
|
||||
] {
|
||||
let mut apps = apps.clone();
|
||||
let mut mcp_servers = mcp_servers.clone();
|
||||
apply_app_mcp_routing_policy(&mut apps, &mut mcp_servers, auth_mode, plugin_active);
|
||||
assert!(apps.is_empty());
|
||||
assert_eq!(
|
||||
sorted_mcp_server_names(&mcp_servers),
|
||||
vec!["docs".to_string(), "linear".to_string()]
|
||||
);
|
||||
}
|
||||
apply_app_mcp_routing_policy(
|
||||
&mut apps,
|
||||
&mut mcp_servers,
|
||||
Some(AuthMode::ApiKey),
|
||||
/*plugin_active*/ true,
|
||||
);
|
||||
|
||||
assert!(apps.is_empty());
|
||||
assert_eq!(
|
||||
sorted_mcp_server_names(&mcp_servers),
|
||||
vec!["docs".to_string(), "linear".to_string()]
|
||||
);
|
||||
}
|
||||
@@ -25,7 +25,6 @@ pub struct PluginCatalogEntry {
|
||||
pub version: String,
|
||||
/// Raw MCP server declarations keyed by their authored names.
|
||||
pub mcp_servers: BTreeMap<String, Value>,
|
||||
pub connector_ids: Vec<String>,
|
||||
pub locations: Vec<PluginSourceLocation>,
|
||||
}
|
||||
|
||||
@@ -65,7 +64,6 @@ impl std::fmt::Debug for PluginCatalogEntry {
|
||||
"mcp_server_names",
|
||||
&self.mcp_servers.keys().collect::<Vec<_>>(),
|
||||
)
|
||||
.field("connector_ids", &self.connector_ids)
|
||||
.field("locations", &self.locations)
|
||||
.finish()
|
||||
}
|
||||
|
||||
@@ -21,7 +21,6 @@ fn cloud_plugin(remote_id: &str) -> PluginCatalogEntry {
|
||||
"example".to_string(),
|
||||
serde_json::json!({"command":"node","args":["server.js"]}),
|
||||
)]),
|
||||
connector_ids: vec!["connector_example".to_string()],
|
||||
locations: vec![PluginSourceLocation::Cloud {
|
||||
resource_uri: format!("plugin://{remote_id}"),
|
||||
bundle_uri: None,
|
||||
@@ -45,7 +44,6 @@ fn merged_catalog_prefers_cloud_and_matches_executor_versions() -> anyhow::Resul
|
||||
let mut first = executor_plugin("plugin_a", "executor-a")?;
|
||||
first.display_name = "Installed display name".to_string();
|
||||
first.mcp_servers.clear();
|
||||
first.connector_ids.clear();
|
||||
let second = executor_plugin("plugin_a", "executor-b")?;
|
||||
let mut incompatible = executor_plugin("plugin_a", "executor-c")?;
|
||||
incompatible.version = "2.0.0".to_string();
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
use anyhow::Context;
|
||||
use codex_app_server_protocol::PluginAvailability;
|
||||
use codex_app_server_protocol::PluginInstallPolicy;
|
||||
use codex_config::skill_config_rules_from_stack;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_plugin::PluginId;
|
||||
use std::collections::HashSet;
|
||||
use tracing::warn;
|
||||
@@ -12,8 +9,6 @@ use crate::OPENAI_CURATED_MARKETPLACE_NAME;
|
||||
use crate::PluginsConfigInput;
|
||||
use crate::PluginsManager;
|
||||
use crate::marketplace::MarketplacePluginInstallPolicy;
|
||||
use crate::remote::InstalledPluginDisplayAssets;
|
||||
use crate::remote::REMOTE_GLOBAL_MARKETPLACE_NAME;
|
||||
|
||||
const TOOL_SUGGEST_DISCOVERABLE_PLUGIN_ALLOWLIST: &[&str] = &[
|
||||
"github@openai-curated",
|
||||
@@ -30,20 +25,6 @@ const TOOL_SUGGEST_DISCOVERABLE_PLUGIN_ALLOWLIST: &[&str] = &[
|
||||
"outlook-calendar@openai-curated",
|
||||
"linear@openai-curated",
|
||||
"figma@openai-curated",
|
||||
"github@openai-curated-remote",
|
||||
"notion@openai-curated-remote",
|
||||
"slack@openai-curated-remote",
|
||||
"gmail@openai-curated-remote",
|
||||
"google-calendar@openai-curated-remote",
|
||||
"google-drive@openai-curated-remote",
|
||||
"openai-developers@openai-curated-remote",
|
||||
"canva@openai-curated-remote",
|
||||
"teams@openai-curated-remote",
|
||||
"sharepoint@openai-curated-remote",
|
||||
"outlook-email@openai-curated-remote",
|
||||
"outlook-calendar@openai-curated-remote",
|
||||
"linear@openai-curated-remote",
|
||||
"figma@openai-curated-remote",
|
||||
"chrome@openai-bundled",
|
||||
"computer-use@openai-bundled",
|
||||
];
|
||||
@@ -53,51 +34,30 @@ pub struct ToolSuggestPluginDiscoveryInput {
|
||||
pub plugins: PluginsConfigInput,
|
||||
pub configured_plugin_ids: HashSet<String>,
|
||||
pub disabled_plugin_ids: HashSet<String>,
|
||||
pub loaded_plugin_app_connector_ids: HashSet<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ToolSuggestDiscoverablePlugin {
|
||||
pub id: String,
|
||||
pub remote_plugin_id: Option<String>,
|
||||
pub name: String,
|
||||
pub description: Option<String>,
|
||||
pub has_skills: bool,
|
||||
pub mcp_server_names: Vec<String>,
|
||||
pub app_connector_ids: Vec<String>,
|
||||
}
|
||||
|
||||
impl PluginsManager {
|
||||
pub async fn list_tool_suggest_discoverable_plugins(
|
||||
&self,
|
||||
input: &ToolSuggestPluginDiscoveryInput,
|
||||
auth: Option<&CodexAuth>,
|
||||
) -> anyhow::Result<Vec<ToolSuggestDiscoverablePlugin>> {
|
||||
if !input.plugins.plugins_enabled {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
let use_remote_global_catalog =
|
||||
input.plugins.remote_plugin_enabled
|
||||
&& auth.is_some_and(|auth| {
|
||||
crate::app_mcp_routing::apps_route_available(Some(auth.auth_mode()))
|
||||
});
|
||||
let marketplaces = self
|
||||
.list_marketplaces_for_config(
|
||||
&input.plugins,
|
||||
&[],
|
||||
/*include_openai_curated*/ !use_remote_global_catalog,
|
||||
)
|
||||
.list_marketplaces_for_config(&input.plugins, &[], /*include_openai_curated*/ true)
|
||||
.context("failed to list plugin marketplaces for tool suggestions")?
|
||||
.marketplaces;
|
||||
let remote_installed_marketplaces = if use_remote_global_catalog {
|
||||
self.build_remote_installed_plugin_marketplaces_from_cache_with_display_assets(
|
||||
&[REMOTE_GLOBAL_MARKETPLACE_NAME],
|
||||
InstalledPluginDisplayAssets::Skip,
|
||||
)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let skill_config_rules = skill_config_rules_from_stack(&input.plugins.config_layer_stack);
|
||||
|
||||
let mut discoverable_plugins = Vec::<ToolSuggestDiscoverablePlugin>::new();
|
||||
@@ -127,16 +87,10 @@ impl PluginsManager {
|
||||
Ok(plugin) => {
|
||||
discoverable_plugins.push(ToolSuggestDiscoverablePlugin {
|
||||
id: plugin.config_name,
|
||||
remote_plugin_id: None,
|
||||
name: plugin.display_name,
|
||||
description: plugin.description,
|
||||
has_skills: plugin.has_skills,
|
||||
mcp_server_names: plugin.mcp_server_names,
|
||||
app_connector_ids: plugin
|
||||
.app_connector_ids
|
||||
.into_iter()
|
||||
.map(|connector_id| connector_id.0)
|
||||
.collect(),
|
||||
});
|
||||
}
|
||||
Err(err) => {
|
||||
@@ -145,62 +99,6 @@ impl PluginsManager {
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(remote_installed_marketplaces) = remote_installed_marketplaces.as_ref() {
|
||||
let mut installed_app_connector_ids = self
|
||||
.plugins_for_config(&input.plugins)
|
||||
.await
|
||||
.capability_summaries()
|
||||
.iter()
|
||||
.flat_map(|plugin| plugin.app_connector_ids.iter())
|
||||
.map(|connector_id| connector_id.0.clone())
|
||||
.collect::<HashSet<_>>();
|
||||
installed_app_connector_ids
|
||||
.extend(input.loaded_plugin_app_connector_ids.iter().cloned());
|
||||
let installed_remote_plugin_ids = remote_installed_marketplaces
|
||||
.iter()
|
||||
.flat_map(|marketplace| marketplace.plugins.iter())
|
||||
.map(|plugin| plugin.remote_plugin_id.clone())
|
||||
.collect::<HashSet<_>>();
|
||||
for plugin in
|
||||
self.cached_global_remote_discoverable_plugins_for_config(&input.plugins, auth)
|
||||
{
|
||||
let is_configured_plugin = input
|
||||
.configured_plugin_ids
|
||||
.contains(plugin.config_id.as_str())
|
||||
|| input
|
||||
.configured_plugin_ids
|
||||
.contains(plugin.remote_plugin_id.as_str());
|
||||
let is_fallback_plugin = is_tool_suggest_fallback_plugin(&plugin.config_id);
|
||||
let matches_installed_app = plugin
|
||||
.app_ids
|
||||
.iter()
|
||||
.any(|app_id| installed_app_connector_ids.contains(app_id.as_str()));
|
||||
let is_disabled = input
|
||||
.disabled_plugin_ids
|
||||
.contains(plugin.config_id.as_str())
|
||||
|| input
|
||||
.disabled_plugin_ids
|
||||
.contains(plugin.remote_plugin_id.as_str());
|
||||
if installed_remote_plugin_ids.contains(&plugin.remote_plugin_id)
|
||||
|| plugin.install_policy == PluginInstallPolicy::NotAvailable
|
||||
|| plugin.availability == PluginAvailability::DisabledByAdmin
|
||||
|| is_disabled
|
||||
|| (!is_configured_plugin && !is_fallback_plugin && !matches_installed_app)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
discoverable_plugins.push(ToolSuggestDiscoverablePlugin {
|
||||
id: plugin.config_id,
|
||||
remote_plugin_id: Some(plugin.remote_plugin_id),
|
||||
name: plugin.name,
|
||||
description: plugin.description,
|
||||
has_skills: plugin.has_skills,
|
||||
mcp_server_names: Vec::new(),
|
||||
app_connector_ids: plugin.app_ids,
|
||||
});
|
||||
}
|
||||
}
|
||||
discoverable_plugins.sort_by(|left, right| {
|
||||
left.name
|
||||
.cmp(&right.name)
|
||||
|
||||
@@ -18,7 +18,6 @@ use crate::test_support::write_file;
|
||||
use crate::test_support::write_openai_api_curated_marketplace;
|
||||
use crate::test_support::write_openai_curated_marketplace;
|
||||
use codex_config::CONFIG_TOML_FILE;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_protocol::auth::AuthMode;
|
||||
use codex_protocol::protocol::Product;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
@@ -43,13 +42,8 @@ async fn returns_api_curated_fallback_plugins_for_direct_provider_auth() {
|
||||
Some(Product::Codex),
|
||||
Some(AuthMode::ApiKey),
|
||||
);
|
||||
let auth = CodexAuth::from_api_key("test-api-key");
|
||||
let discoverable_plugins = list_discoverable_plugins(
|
||||
&plugins_manager,
|
||||
discovery_input(plugins, &[], &[], &[]),
|
||||
Some(&auth),
|
||||
)
|
||||
.await;
|
||||
let discoverable_plugins =
|
||||
list_discoverable_plugins(&plugins_manager, discovery_input(plugins, &[], &[])).await;
|
||||
|
||||
assert_eq!(
|
||||
discoverable_plugins
|
||||
@@ -79,12 +73,8 @@ async fn returns_microsoft_fallback_plugins() {
|
||||
Some(Product::Codex),
|
||||
Some(AuthMode::ApiKey),
|
||||
);
|
||||
let discoverable_plugins = list_discoverable_plugins(
|
||||
&plugins_manager,
|
||||
discovery_input(plugins, &[], &[], &[]),
|
||||
/*auth*/ None,
|
||||
)
|
||||
.await;
|
||||
let discoverable_plugins =
|
||||
list_discoverable_plugins(&plugins_manager, discovery_input(plugins, &[], &[])).await;
|
||||
|
||||
assert_eq!(
|
||||
discoverable_plugins
|
||||
@@ -100,7 +90,7 @@ async fn returns_microsoft_fallback_plugins() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn omits_openai_curated_but_keeps_configured_marketplaces_for_remote_codex_auth() {
|
||||
async fn omits_openai_curated_but_keeps_configured_marketplaces_for_headers_auth() {
|
||||
let codex_home = tempdir().expect("tempdir should succeed");
|
||||
let curated_root = curated_plugins_repo_path(codex_home.path());
|
||||
write_openai_curated_marketplace(&curated_root, &["slack"]);
|
||||
@@ -141,13 +131,8 @@ source = {bundled_marketplace_root:?}
|
||||
Some(Product::Codex),
|
||||
Some(AuthMode::Headers),
|
||||
);
|
||||
let auth = CodexAuth::Headers(codex_login::AuthHeaders::new(http::HeaderMap::new()));
|
||||
let discoverable_plugins = list_discoverable_plugins(
|
||||
&plugins_manager,
|
||||
discovery_input(plugins, &[], &[], &[]),
|
||||
Some(&auth),
|
||||
)
|
||||
.await;
|
||||
let discoverable_plugins =
|
||||
list_discoverable_plugins(&plugins_manager, discovery_input(plugins, &[], &[])).await;
|
||||
|
||||
assert_eq!(
|
||||
discoverable_plugins
|
||||
@@ -159,19 +144,15 @@ source = {bundled_marketplace_root:?}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn includes_openai_api_curated_when_remote_enabled_without_auth() {
|
||||
async fn includes_openai_api_curated_without_auth() {
|
||||
let codex_home = tempdir().expect("tempdir should succeed");
|
||||
let curated_root = curated_plugins_repo_path(codex_home.path());
|
||||
write_openai_api_curated_marketplace(&curated_root, &["slack"]);
|
||||
|
||||
let plugins = load_plugins_config(codex_home.path(), codex_home.path()).await;
|
||||
let plugins_manager = test_plugins_manager(codex_home.path().to_path_buf());
|
||||
let discoverable_plugins = list_discoverable_plugins(
|
||||
&plugins_manager,
|
||||
discovery_input(plugins, &[], &[], &[]),
|
||||
/*auth*/ None,
|
||||
)
|
||||
.await;
|
||||
let discoverable_plugins =
|
||||
list_discoverable_plugins(&plugins_manager, discovery_input(plugins, &[], &[])).await;
|
||||
|
||||
assert_eq!(
|
||||
discoverable_plugins
|
||||
@@ -231,13 +212,11 @@ source = {marketplace_root:?}
|
||||
);
|
||||
let header_projection = list_discoverable_plugins(
|
||||
&plugins_manager,
|
||||
discovery_input(plugins.clone(), &[plugin_id.as_str()], &[], &[]),
|
||||
/*auth*/ None,
|
||||
discovery_input(plugins.clone(), &[plugin_id.as_str()], &[]),
|
||||
)
|
||||
.await;
|
||||
let expected = ToolSuggestDiscoverablePlugin {
|
||||
id: plugin_id.clone(),
|
||||
remote_plugin_id: None,
|
||||
name: "sample".to_string(),
|
||||
description: Some(
|
||||
"Plugin that includes skills, MCP servers, and app connectors".to_string(),
|
||||
@@ -245,15 +224,13 @@ source = {marketplace_root:?}
|
||||
has_skills: true,
|
||||
// App routes required ChatGPT auth, so direct MCP servers are always advertised.
|
||||
mcp_server_names: vec!["sample-docs".to_string()],
|
||||
app_connector_ids: Vec::new(),
|
||||
};
|
||||
assert_eq!(header_projection, vec![expected.clone()]);
|
||||
|
||||
set_test_auth_mode(&auth_manager, Some(AuthMode::ApiKey)).await;
|
||||
let api_key_projection = list_discoverable_plugins(
|
||||
&plugins_manager,
|
||||
discovery_input(plugins, &[plugin_id.as_str()], &[], &[]),
|
||||
/*auth*/ None,
|
||||
discovery_input(plugins, &[plugin_id.as_str()], &[]),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(api_key_projection, vec![expected]);
|
||||
@@ -273,21 +250,15 @@ async fn reprojects_cached_skill_availability_for_current_config() {
|
||||
);
|
||||
let expected = ToolSuggestDiscoverablePlugin {
|
||||
id: "slack@openai-api-curated".to_string(),
|
||||
remote_plugin_id: None,
|
||||
name: "slack".to_string(),
|
||||
description: Some(
|
||||
"Plugin that includes skills, MCP servers, and app connectors".to_string(),
|
||||
),
|
||||
has_skills: true,
|
||||
mcp_server_names: vec!["sample-docs".to_string()],
|
||||
app_connector_ids: Vec::new(),
|
||||
};
|
||||
let initial = list_discoverable_plugins(
|
||||
&plugins_manager,
|
||||
discovery_input(plugins, &[], &[], &[]),
|
||||
/*auth*/ None,
|
||||
)
|
||||
.await;
|
||||
let initial =
|
||||
list_discoverable_plugins(&plugins_manager, discovery_input(plugins, &[], &[])).await;
|
||||
assert_eq!(initial, vec![expected.clone()]);
|
||||
|
||||
write_file(
|
||||
@@ -298,12 +269,8 @@ enabled = false
|
||||
"#,
|
||||
);
|
||||
let plugins = load_plugins_config(codex_home.path(), codex_home.path()).await;
|
||||
let after_skill_disabled = list_discoverable_plugins(
|
||||
&plugins_manager,
|
||||
discovery_input(plugins, &[], &[], &[]),
|
||||
/*auth*/ None,
|
||||
)
|
||||
.await;
|
||||
let after_skill_disabled =
|
||||
list_discoverable_plugins(&plugins_manager, discovery_input(plugins, &[], &[])).await;
|
||||
assert_eq!(
|
||||
after_skill_disabled,
|
||||
vec![ToolSuggestDiscoverablePlugin {
|
||||
@@ -329,25 +296,19 @@ async fn does_not_advertise_skills_when_skill_loading_fails() {
|
||||
Some(Product::Codex),
|
||||
Some(AuthMode::ApiKey),
|
||||
);
|
||||
let discoverable_plugins = list_discoverable_plugins(
|
||||
&plugins_manager,
|
||||
discovery_input(plugins, &[], &[], &[]),
|
||||
/*auth*/ None,
|
||||
)
|
||||
.await;
|
||||
let discoverable_plugins =
|
||||
list_discoverable_plugins(&plugins_manager, discovery_input(plugins, &[], &[])).await;
|
||||
|
||||
assert_eq!(
|
||||
discoverable_plugins,
|
||||
vec![ToolSuggestDiscoverablePlugin {
|
||||
id: "slack@openai-api-curated".to_string(),
|
||||
remote_plugin_id: None,
|
||||
name: "slack".to_string(),
|
||||
description: Some(
|
||||
"Plugin that includes skills, MCP servers, and app connectors".to_string(),
|
||||
),
|
||||
has_skills: false,
|
||||
mcp_server_names: vec!["sample-docs".to_string()],
|
||||
app_connector_ids: Vec::new(),
|
||||
}]
|
||||
);
|
||||
}
|
||||
@@ -372,17 +333,15 @@ async fn clear_cache_invalidates_cached_tool_suggest_metadata() {
|
||||
Some(Product::Codex),
|
||||
Some(AuthMode::ApiKey),
|
||||
);
|
||||
let input = discovery_input(plugins, &[], &[], &[]);
|
||||
let input = discovery_input(plugins, &[], &[]);
|
||||
let expected_cached = vec![ToolSuggestDiscoverablePlugin {
|
||||
id: "slack@openai-api-curated".to_string(),
|
||||
remote_plugin_id: None,
|
||||
name: "slack".to_string(),
|
||||
description: Some("Before reload".to_string()),
|
||||
has_skills: true,
|
||||
mcp_server_names: vec!["sample-docs".to_string()],
|
||||
app_connector_ids: Vec::new(),
|
||||
}];
|
||||
let initial = list_discoverable_plugins(&plugins_manager, input.clone(), /*auth*/ None).await;
|
||||
let initial = list_discoverable_plugins(&plugins_manager, input.clone()).await;
|
||||
assert_eq!(initial, expected_cached);
|
||||
|
||||
write_file(
|
||||
@@ -392,12 +351,11 @@ async fn clear_cache_invalidates_cached_tool_suggest_metadata() {
|
||||
"description": "After reload"
|
||||
}"#,
|
||||
);
|
||||
let before_reload =
|
||||
list_discoverable_plugins(&plugins_manager, input.clone(), /*auth*/ None).await;
|
||||
let before_reload = list_discoverable_plugins(&plugins_manager, input.clone()).await;
|
||||
assert_eq!(before_reload, expected_cached);
|
||||
|
||||
plugins_manager.clear_cache();
|
||||
let after_reload = list_discoverable_plugins(&plugins_manager, input, /*auth*/ None).await;
|
||||
let after_reload = list_discoverable_plugins(&plugins_manager, input).await;
|
||||
assert_eq!(
|
||||
after_reload,
|
||||
vec![ToolSuggestDiscoverablePlugin {
|
||||
@@ -448,12 +406,8 @@ source = "/tmp/{marketplace_name}"
|
||||
Some(Product::Codex),
|
||||
Some(AuthMode::ApiKey),
|
||||
);
|
||||
let discoverable_plugins = list_discoverable_plugins(
|
||||
&plugins_manager,
|
||||
discovery_input(plugins, &[], &[], &[]),
|
||||
/*auth*/ None,
|
||||
)
|
||||
.await;
|
||||
let discoverable_plugins =
|
||||
list_discoverable_plugins(&plugins_manager, discovery_input(plugins, &[], &[])).await;
|
||||
|
||||
assert_eq!(discoverable_plugins.len(), 1);
|
||||
assert_eq!(discoverable_plugins[0].id, "slack@openai-api-curated");
|
||||
@@ -479,23 +433,17 @@ async fn normalizes_description() {
|
||||
Some(Product::Codex),
|
||||
Some(AuthMode::ApiKey),
|
||||
);
|
||||
let discoverable_plugins = list_discoverable_plugins(
|
||||
&plugins_manager,
|
||||
discovery_input(plugins, &[], &[], &[]),
|
||||
/*auth*/ None,
|
||||
)
|
||||
.await;
|
||||
let discoverable_plugins =
|
||||
list_discoverable_plugins(&plugins_manager, discovery_input(plugins, &[], &[])).await;
|
||||
|
||||
assert_eq!(
|
||||
discoverable_plugins,
|
||||
vec![ToolSuggestDiscoverablePlugin {
|
||||
id: "slack@openai-api-curated".to_string(),
|
||||
remote_plugin_id: None,
|
||||
name: "slack".to_string(),
|
||||
description: Some("Plugin with extra spacing".to_string()),
|
||||
has_skills: true,
|
||||
mcp_server_names: vec!["sample-docs".to_string()],
|
||||
app_connector_ids: Vec::new(),
|
||||
}]
|
||||
);
|
||||
}
|
||||
@@ -509,12 +457,8 @@ async fn omits_installed_curated_plugins() {
|
||||
|
||||
let plugins = load_plugins_config(codex_home.path(), codex_home.path()).await;
|
||||
let plugins_manager = test_plugins_manager(codex_home.path().to_path_buf());
|
||||
let discoverable_plugins = list_discoverable_plugins(
|
||||
&plugins_manager,
|
||||
discovery_input(plugins, &[], &[], &[]),
|
||||
/*auth*/ None,
|
||||
)
|
||||
.await;
|
||||
let discoverable_plugins =
|
||||
list_discoverable_plugins(&plugins_manager, discovery_input(plugins, &[], &[])).await;
|
||||
|
||||
assert_eq!(discoverable_plugins, Vec::new());
|
||||
}
|
||||
@@ -567,12 +511,8 @@ async fn omits_not_available_curated_plugins() {
|
||||
Some(Product::Codex),
|
||||
Some(AuthMode::ApiKey),
|
||||
);
|
||||
let discoverable_plugins = list_discoverable_plugins(
|
||||
&plugins_manager,
|
||||
discovery_input(plugins, &[], &[], &[]),
|
||||
/*auth*/ None,
|
||||
)
|
||||
.await;
|
||||
let discoverable_plugins =
|
||||
list_discoverable_plugins(&plugins_manager, discovery_input(plugins, &[], &[])).await;
|
||||
|
||||
assert_eq!(
|
||||
discoverable_plugins
|
||||
@@ -623,19 +563,18 @@ async fn discovery_warns_once_per_invalid_manifest() {
|
||||
.finish();
|
||||
let _guard = tracing::subscriber::set_default(subscriber);
|
||||
|
||||
let discoverable_plugins = list_discoverable_plugins(
|
||||
&plugins_manager,
|
||||
discovery_input(plugins, &[], &[], &[]),
|
||||
/*auth*/ None,
|
||||
)
|
||||
.await;
|
||||
let discoverable_plugins =
|
||||
list_discoverable_plugins(&plugins_manager, discovery_input(plugins, &[], &[])).await;
|
||||
|
||||
assert_eq!(
|
||||
discoverable_plugins
|
||||
.iter()
|
||||
.map(|plugin| plugin.id.as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
vec!["gmail@openai-api-curated", "openai-developers@openai-api-curated"]
|
||||
vec![
|
||||
"gmail@openai-api-curated",
|
||||
"openai-developers@openai-api-curated"
|
||||
]
|
||||
);
|
||||
|
||||
let logs = String::from_utf8(buffer.lock().expect("buffer lock").clone())
|
||||
@@ -660,12 +599,8 @@ async fn does_not_expand_local_plugins_by_installed_apps() {
|
||||
|
||||
let plugins = load_plugins_config(codex_home.path(), codex_home.path()).await;
|
||||
let plugins_manager = test_plugins_manager(codex_home.path().to_path_buf());
|
||||
let discoverable_plugins = list_discoverable_plugins(
|
||||
&plugins_manager,
|
||||
discovery_input(plugins, &[], &[], &[]),
|
||||
/*auth*/ None,
|
||||
)
|
||||
.await;
|
||||
let discoverable_plugins =
|
||||
list_discoverable_plugins(&plugins_manager, discovery_input(plugins, &[], &[])).await;
|
||||
|
||||
assert_eq!(discoverable_plugins, Vec::new());
|
||||
}
|
||||
@@ -697,12 +632,8 @@ async fn does_not_read_local_plugins_for_loaded_apps() {
|
||||
.finish();
|
||||
let _guard = tracing::subscriber::set_default(subscriber);
|
||||
|
||||
let discoverable_plugins = list_discoverable_plugins(
|
||||
&plugins_manager,
|
||||
discovery_input(plugins, &[], &[], &[hubspot_app_id]),
|
||||
/*auth*/ None,
|
||||
)
|
||||
.await;
|
||||
let discoverable_plugins =
|
||||
list_discoverable_plugins(&plugins_manager, discovery_input(plugins, &[], &[])).await;
|
||||
|
||||
assert_eq!(discoverable_plugins, Vec::new());
|
||||
let logs = String::from_utf8(buffer.lock().expect("buffer lock").clone())
|
||||
@@ -772,12 +703,8 @@ source = "/tmp/{sales_marketplace_name}"
|
||||
|
||||
let plugins = load_plugins_config(codex_home.path(), codex_home.path()).await;
|
||||
let plugins_manager = test_plugins_manager(codex_home.path().to_path_buf());
|
||||
let discoverable_plugins = list_discoverable_plugins(
|
||||
&plugins_manager,
|
||||
discovery_input(plugins, &[], &[], &[]),
|
||||
/*auth*/ None,
|
||||
)
|
||||
.await;
|
||||
let discoverable_plugins =
|
||||
list_discoverable_plugins(&plugins_manager, discovery_input(plugins, &[], &[])).await;
|
||||
|
||||
assert_eq!(discoverable_plugins, Vec::new());
|
||||
}
|
||||
@@ -786,23 +713,20 @@ fn discovery_input(
|
||||
plugins: PluginsConfigInput,
|
||||
configured_plugin_ids: &[&str],
|
||||
disabled_plugin_ids: &[&str],
|
||||
loaded_plugin_app_connector_ids: &[&str],
|
||||
) -> ToolSuggestPluginDiscoveryInput {
|
||||
ToolSuggestPluginDiscoveryInput {
|
||||
plugins,
|
||||
configured_plugin_ids: string_set(configured_plugin_ids),
|
||||
disabled_plugin_ids: string_set(disabled_plugin_ids),
|
||||
loaded_plugin_app_connector_ids: string_set(loaded_plugin_app_connector_ids),
|
||||
}
|
||||
}
|
||||
|
||||
async fn list_discoverable_plugins(
|
||||
plugins_manager: &PluginsManager,
|
||||
input: ToolSuggestPluginDiscoveryInput,
|
||||
auth: Option<&CodexAuth>,
|
||||
) -> Vec<ToolSuggestDiscoverablePlugin> {
|
||||
plugins_manager
|
||||
.list_tool_suggest_discoverable_plugins(&input, auth)
|
||||
.list_tool_suggest_discoverable_plugins(&input)
|
||||
.await
|
||||
.expect("discoverable plugins should load")
|
||||
}
|
||||
@@ -820,7 +744,8 @@ async fn install_marketplace_plugin(codex_home: &Path, marketplace_root: &Path,
|
||||
PluginInstallRequest {
|
||||
plugin_name: plugin_name.to_string(),
|
||||
marketplace_path: AbsolutePathBuf::try_from({
|
||||
let api_manifest = marketplace_root.join(".agents/plugins/api_marketplace.json");
|
||||
let api_manifest =
|
||||
marketplace_root.join(".agents/plugins/api_marketplace.json");
|
||||
if api_manifest.is_file() {
|
||||
api_manifest
|
||||
} else {
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
use http::StatusCode;
|
||||
|
||||
pub(crate) fn http_status_sub_error_type(status: StatusCode) -> &'static str {
|
||||
match status.as_u16() {
|
||||
401 => "http_401",
|
||||
403 => "http_403",
|
||||
404 => "http_404",
|
||||
409 => "http_409",
|
||||
429 => "http_429",
|
||||
_ if status.is_server_error() => "http_5xx",
|
||||
_ => "http_other",
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,6 @@ use crate::PluginCatalog;
|
||||
use crate::PluginCatalogEntry;
|
||||
use crate::PluginIdentity;
|
||||
use crate::PluginSourceLocation;
|
||||
use codex_connectors::parse_plugin_app_config;
|
||||
use codex_exec_server::ExecutorCapabilityDiscoveryV2Snapshot;
|
||||
use codex_exec_server::ExecutorPlugin;
|
||||
use codex_mcp::parse_plugin_mcp_declarations;
|
||||
@@ -55,34 +54,15 @@ fn from_discovered_plugin(
|
||||
}
|
||||
None => Default::default(),
|
||||
};
|
||||
let connector_ids = match plugin
|
||||
.files
|
||||
.apps_config
|
||||
.as_ref()
|
||||
.map(|file| parse_plugin_app_config(&file.contents))
|
||||
{
|
||||
Some(Ok(apps)) => apps.into_iter().map(|app| app.connector_id.0).collect(),
|
||||
Some(Err(error)) => {
|
||||
warnings.push(format!("plugin `{plugin_id}` app configuration: {error}"));
|
||||
Vec::new()
|
||||
}
|
||||
None => Vec::new(),
|
||||
};
|
||||
(
|
||||
PluginCatalogEntry {
|
||||
enabled: true,
|
||||
id: match &plugin.remote_plugin_id {
|
||||
Some(remote_plugin_id) => PluginIdentity::Remote {
|
||||
remote_plugin_id: remote_plugin_id.clone(),
|
||||
},
|
||||
None => PluginIdentity::Local {
|
||||
plugin_id: plugin.id.clone(),
|
||||
},
|
||||
id: PluginIdentity::Local {
|
||||
plugin_id: plugin.id.clone(),
|
||||
},
|
||||
display_name: plugin.display_name.clone(),
|
||||
version: plugin.version.clone(),
|
||||
mcp_servers,
|
||||
connector_ids,
|
||||
locations: vec![PluginSourceLocation::Executor {
|
||||
environment_id: environment_id.to_string(),
|
||||
plugin_id: plugin_id.to_string(),
|
||||
|
||||
@@ -26,7 +26,6 @@ fn discovered_mcp_contents_populate_catalog() -> anyhow::Result<()> {
|
||||
plugins: vec![ExecutorPlugin {
|
||||
id: "example@marketplace".to_string(),
|
||||
display_name: "Example".to_string(),
|
||||
remote_plugin_id: Some("plugin_a".to_string()),
|
||||
version: "1.0.0".to_string(),
|
||||
files: DiscoveredPluginFiles {
|
||||
manifest: CapabilityTextFile {
|
||||
@@ -50,8 +49,8 @@ fn discovered_mcp_contents_populate_catalog() -> anyhow::Result<()> {
|
||||
PluginCatalog {
|
||||
entries: vec![PluginCatalogEntry {
|
||||
enabled: true,
|
||||
id: PluginIdentity::Remote {
|
||||
remote_plugin_id: "plugin_a".to_string(),
|
||||
id: PluginIdentity::Local {
|
||||
plugin_id: "example@marketplace".to_string(),
|
||||
},
|
||||
display_name: "Example".to_string(),
|
||||
version: "1.0.0".to_string(),
|
||||
@@ -59,7 +58,6 @@ fn discovered_mcp_contents_populate_catalog() -> anyhow::Result<()> {
|
||||
"example".to_string(),
|
||||
serde_json::json!({"command": "node"}),
|
||||
)]),
|
||||
connector_ids: Vec::new(),
|
||||
locations: vec![PluginSourceLocation::Executor {
|
||||
environment_id: "executor-a".to_string(),
|
||||
plugin_id: "example@marketplace".to_string(),
|
||||
|
||||
@@ -1,39 +1,28 @@
|
||||
//! Executor-discovered plugin hook admission and trusted MCP routing.
|
||||
//! Executor-discovered plugin hook admission.
|
||||
|
||||
use codex_config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID;
|
||||
use codex_config::HookHandlerConfig;
|
||||
use codex_config::types::PluginsConfigToml;
|
||||
use codex_exec_server::DiscoveredPluginFiles;
|
||||
use codex_exec_server::ExecutorCapabilityDiscoverySnapshot;
|
||||
use codex_exec_server::ExecutorCapabilityDiscoveryV2Snapshot;
|
||||
use codex_mcp::CODEX_APPS_MCP_SERVER_NAME;
|
||||
use codex_mcp::MCP_TOOL_CODEX_APPS_META_KEY;
|
||||
use codex_mcp::ToolInfo;
|
||||
use codex_plugin::ExecutorPluginHookSource;
|
||||
use codex_plugin::PluginId;
|
||||
use codex_plugin::is_allowlisted_bundled_cleanup_hook;
|
||||
use codex_plugin::manifest::PluginManifestHooks;
|
||||
use codex_protocol::capabilities::CapabilityRootLocation;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use serde_json::Map;
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::manifest::parse_plugin_manifest_uri;
|
||||
|
||||
/// Returns accepted inline hook sources from executor-discovered plugin manifests.
|
||||
/// Each source carries its trusted MCP routing metadata. `lookup_enabled_tool` must use a
|
||||
/// consistent catalog/config snapshot, include app-only tools, and exclude tools disabled by
|
||||
/// app policy.
|
||||
///
|
||||
/// Executor scoped hooks are best-effort because executor capabilities can become available
|
||||
/// after earlier lifecycle events have passed.
|
||||
///
|
||||
/// Note: Executor manifests are not signed yet, so temporarily we only admit the known cleanup
|
||||
/// hooks from the bundled cleanup allowlist and the remote Browser plugin.
|
||||
pub fn executor_plugin_hook_sources<'a>(
|
||||
/// hooks from the bundled cleanup allowlist.
|
||||
pub fn executor_plugin_hook_sources(
|
||||
snapshot: &ExecutorCapabilityDiscoverySnapshot,
|
||||
plugins_config: &PluginsConfigToml,
|
||||
lookup_enabled_tool: impl Fn(&str, &str) -> Option<&'a ToolInfo>,
|
||||
) -> Vec<ExecutorPluginHookSource> {
|
||||
let plugins = snapshot.roots().iter().filter_map(|entry| {
|
||||
let CapabilityRootLocation::Environment {
|
||||
@@ -48,15 +37,14 @@ pub fn executor_plugin_hook_sources<'a>(
|
||||
plugin,
|
||||
))
|
||||
});
|
||||
admitted_hook_sources(plugins, plugins_config, lookup_enabled_tool)
|
||||
admitted_hook_sources(plugins, plugins_config)
|
||||
}
|
||||
|
||||
/// Applies the same inline-hook admission and MCP routing policy to V2 inventories.
|
||||
/// Applies the same inline-hook admission policy to V2 inventories.
|
||||
/// Callers must additionally restrict sources to their accepted plugin installations.
|
||||
pub fn executor_plugin_hook_sources_v2<'a>(
|
||||
pub fn executor_plugin_hook_sources_v2(
|
||||
snapshots: &[ExecutorCapabilityDiscoveryV2Snapshot],
|
||||
plugins_config: &PluginsConfigToml,
|
||||
lookup_enabled_tool: impl Fn(&str, &str) -> Option<&'a ToolInfo>,
|
||||
) -> Vec<ExecutorPluginHookSource> {
|
||||
let plugins = snapshots.iter().flat_map(|snapshot| {
|
||||
snapshot.result.iter().flat_map(move |inventory| {
|
||||
@@ -70,13 +58,12 @@ pub fn executor_plugin_hook_sources_v2<'a>(
|
||||
})
|
||||
})
|
||||
});
|
||||
admitted_hook_sources(plugins, plugins_config, lookup_enabled_tool)
|
||||
admitted_hook_sources(plugins, plugins_config)
|
||||
}
|
||||
|
||||
fn admitted_hook_sources<'a, 'b>(
|
||||
fn admitted_hook_sources<'b>(
|
||||
plugins: impl Iterator<Item = (&'b str, &'b str, &'b PathUri, &'b DiscoveredPluginFiles)>,
|
||||
plugins_config: &PluginsConfigToml,
|
||||
lookup_enabled_tool: impl Fn(&str, &str) -> Option<&'a ToolInfo>,
|
||||
) -> Vec<ExecutorPluginHookSource> {
|
||||
let mut sources = Vec::new();
|
||||
for (plugin_id, environment_id, plugin_root, plugin) in plugins {
|
||||
@@ -126,21 +113,11 @@ fn admitted_hook_sources<'a, 'b>(
|
||||
for (event, groups) in source.hooks.matcher_groups_mut() {
|
||||
groups.retain_mut(|group| {
|
||||
group.hooks.retain(|handler| {
|
||||
let app_connector_id = match handler {
|
||||
HookHandlerConfig::McpTool { server, tool, .. }
|
||||
if server == CODEX_APPS_MCP_SERVER_NAME =>
|
||||
{
|
||||
lookup_enabled_tool(server, tool)
|
||||
.and_then(|info| info.connector_id.as_deref())
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
is_allowlisted_bundled_cleanup_hook(
|
||||
&plugin_id,
|
||||
event,
|
||||
group.matcher.as_deref(),
|
||||
handler,
|
||||
app_connector_id,
|
||||
)
|
||||
});
|
||||
!group.hooks.is_empty()
|
||||
@@ -148,45 +125,9 @@ fn admitted_hook_sources<'a, 'b>(
|
||||
}
|
||||
(!source.hooks.is_empty()).then_some(source)
|
||||
})
|
||||
.filter_map(|source| resolve_mcp_routing(source, &lookup_enabled_tool))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Resolves routing for an admitted MCP hook source.
|
||||
fn resolve_mcp_routing<'a>(
|
||||
mut source: ExecutorPluginHookSource,
|
||||
lookup_enabled_tool: &impl Fn(&str, &str) -> Option<&'a ToolInfo>,
|
||||
) -> Option<ExecutorPluginHookSource> {
|
||||
let HookHandlerConfig::McpTool { server, tool, .. } = source
|
||||
.hooks
|
||||
.matcher_groups_mut()
|
||||
.into_iter()
|
||||
.find_map(|(_, groups)| groups.first())?
|
||||
.hooks
|
||||
.first()?
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
if server != CODEX_APPS_MCP_SERVER_NAME {
|
||||
return Some(source);
|
||||
}
|
||||
|
||||
let tool_info = lookup_enabled_tool(server, tool)?;
|
||||
let routing_metadata = tool_info
|
||||
.tool
|
||||
.meta
|
||||
.as_ref()?
|
||||
.get(MCP_TOOL_CODEX_APPS_META_KEY)?
|
||||
.as_object()?;
|
||||
routing_metadata.get("resource_uri")?.as_str()?;
|
||||
source.mcp_environment_id = Some(DEFAULT_MCP_SERVER_ENVIRONMENT_ID.to_string());
|
||||
source.mcp_metadata = Some(Map::from_iter([(
|
||||
MCP_TOOL_CODEX_APPS_META_KEY.to_string(),
|
||||
Value::Object(routing_metadata.clone()),
|
||||
)]));
|
||||
Some(source)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "executor_hooks_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
@@ -2,6 +2,7 @@ use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use codex_config::HookEventsToml;
|
||||
use codex_config::HookHandlerConfig;
|
||||
use codex_config::MatcherGroup;
|
||||
use codex_exec_server::CapabilityRootDiscovery;
|
||||
use codex_exec_server::CapabilityTextFile;
|
||||
@@ -131,7 +132,7 @@ fn discovers_allowlisted_executor_plugin_hook_sources() {
|
||||
);
|
||||
|
||||
let sources =
|
||||
executor_plugin_hook_sources(&snapshot, &PluginsConfigToml::default(), |_, _| None);
|
||||
executor_plugin_hook_sources(&snapshot, &PluginsConfigToml::default());
|
||||
let mut interrupt_source = expected_source(/*index*/ 1);
|
||||
interrupt_source.hooks.interrupt = std::mem::take(&mut interrupt_source.hooks.stop);
|
||||
let mut stop_and_interrupt_source = expected_source(/*index*/ 2);
|
||||
@@ -157,7 +158,7 @@ fn discovers_allowlisted_executor_plugin_hook_sources() {
|
||||
] {
|
||||
let config = toml::from_str(config).expect("plugin policy");
|
||||
assert_eq!(
|
||||
executor_plugin_hook_sources(&snapshot, &config, |_, _| None),
|
||||
executor_plugin_hook_sources(&snapshot, &config),
|
||||
expected
|
||||
);
|
||||
}
|
||||
@@ -182,7 +183,7 @@ fn discovers_unified_computer_use_cleanup_hooks() {
|
||||
*server = "cua_repl".to_string();
|
||||
|
||||
assert_eq!(
|
||||
executor_plugin_hook_sources(&snapshot, &PluginsConfigToml::default(), |_, _| None),
|
||||
executor_plugin_hook_sources(&snapshot, &PluginsConfigToml::default()),
|
||||
vec![expected]
|
||||
);
|
||||
}
|
||||
@@ -219,7 +220,7 @@ fn filters_mixed_handlers_without_rewriting_allowed_groups() {
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
executor_plugin_hook_sources(&snapshot, &PluginsConfigToml::default(), |_, _| None),
|
||||
executor_plugin_hook_sources(&snapshot, &PluginsConfigToml::default()),
|
||||
vec![expected]
|
||||
);
|
||||
}
|
||||
@@ -251,168 +252,11 @@ fn preserves_allowlisted_executor_plugin_hook_options() {
|
||||
expected.hooks.interrupt = expected.hooks.stop.clone();
|
||||
|
||||
assert_eq!(
|
||||
executor_plugin_hook_sources(&snapshot, &PluginsConfigToml::default(), |_, _| None),
|
||||
executor_plugin_hook_sources(&snapshot, &PluginsConfigToml::default()),
|
||||
vec![expected]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolves_apps_hook_metadata_from_the_registered_connector() {
|
||||
let mut manifest = cleanup_hook_manifest();
|
||||
manifest["name"] = json!("browser");
|
||||
let handler = &mut manifest["hooks"]["hooks"]["Stop"][0]["hooks"][0];
|
||||
handler["server"] = json!("codex_apps");
|
||||
handler["tool"] = json!("browser.turn_ended");
|
||||
handler["input"] = json!({});
|
||||
let mut expected = expected_source(/*index*/ 0);
|
||||
expected.plugin_id = PluginId::parse("browser@openai-curated-remote").expect("plugin id");
|
||||
expected.mcp_environment_id = Some(DEFAULT_MCP_SERVER_ENVIRONMENT_ID.to_string());
|
||||
let routing = json!({
|
||||
"resource_uri": "/connector_openai_browser/browser-link/turn_ended",
|
||||
"contains_mcp_source": true,
|
||||
});
|
||||
expected.mcp_metadata = Some(Map::from_iter([(
|
||||
MCP_TOOL_CODEX_APPS_META_KEY.to_string(),
|
||||
routing.clone(),
|
||||
)]));
|
||||
|
||||
for (name, event, connector_id, input, routing_metadata, admitted) in [
|
||||
(
|
||||
"registered app",
|
||||
"Stop",
|
||||
Some("connector_openai_browser"),
|
||||
json!({}),
|
||||
routing.clone(),
|
||||
true,
|
||||
),
|
||||
(
|
||||
"colliding tool name",
|
||||
"Stop",
|
||||
Some("connector_other_browser"),
|
||||
json!({}),
|
||||
routing.clone(),
|
||||
false,
|
||||
),
|
||||
(
|
||||
"unavailable tool",
|
||||
"Stop",
|
||||
None,
|
||||
json!({}),
|
||||
routing.clone(),
|
||||
false,
|
||||
),
|
||||
(
|
||||
"registered subagent app",
|
||||
"SubagentStop",
|
||||
Some("connector_openai_browser"),
|
||||
json!({}),
|
||||
routing.clone(),
|
||||
true,
|
||||
),
|
||||
(
|
||||
"registered interrupted app",
|
||||
"Interrupt",
|
||||
Some("connector_openai_browser"),
|
||||
json!({}),
|
||||
routing.clone(),
|
||||
true,
|
||||
),
|
||||
(
|
||||
"colliding interrupt tool name",
|
||||
"Interrupt",
|
||||
Some("connector_other_browser"),
|
||||
json!({}),
|
||||
routing.clone(),
|
||||
false,
|
||||
),
|
||||
(
|
||||
"interrupt manifest arguments",
|
||||
"Interrupt",
|
||||
Some("connector_openai_browser"),
|
||||
json!({ "untrusted": "manifest-provided input" }),
|
||||
routing.clone(),
|
||||
false,
|
||||
),
|
||||
(
|
||||
"colliding subagent tool name",
|
||||
"SubagentStop",
|
||||
Some("connector_other_browser"),
|
||||
json!({}),
|
||||
routing.clone(),
|
||||
false,
|
||||
),
|
||||
(
|
||||
"manifest arguments",
|
||||
"Stop",
|
||||
Some("connector_openai_browser"),
|
||||
json!({ "untrusted": "manifest-provided input" }),
|
||||
routing,
|
||||
false,
|
||||
),
|
||||
(
|
||||
"missing routing metadata",
|
||||
"Stop",
|
||||
Some("connector_openai_browser"),
|
||||
json!({}),
|
||||
json!(null),
|
||||
false,
|
||||
),
|
||||
(
|
||||
"invalid resource URI",
|
||||
"Stop",
|
||||
Some("connector_openai_browser"),
|
||||
json!({}),
|
||||
json!({ "resource_uri": 42 }),
|
||||
false,
|
||||
),
|
||||
] {
|
||||
let mut manifest = manifest.clone();
|
||||
manifest["hooks"]["hooks"]["Stop"][0]["hooks"][0]["input"] = input;
|
||||
let events = manifest["hooks"]["hooks"]
|
||||
.as_object_mut()
|
||||
.expect("hook events");
|
||||
let groups = events.remove("Stop").expect("stop groups");
|
||||
events.insert(event.to_string(), groups);
|
||||
let mut expected = expected.clone();
|
||||
expected.hooks = serde_json::from_value(manifest["hooks"]["hooks"].clone()).expect("hooks");
|
||||
let snapshot = snapshot_for_manifest(
|
||||
"browser@openai-curated-remote",
|
||||
"executor-a",
|
||||
"file:///plugins/computer-use/.codex-plugin/plugin.json",
|
||||
manifest,
|
||||
);
|
||||
let tool_info = connector_id.map(|connector_id| {
|
||||
serde_json::from_value::<ToolInfo>(json!({
|
||||
"server_name": "codex_apps",
|
||||
"tool_name": "turn_ended",
|
||||
"tool_namespace": "browser",
|
||||
"connector_id": connector_id,
|
||||
"tool": {
|
||||
"name": "browser.turn_ended",
|
||||
"inputSchema": { "type": "object" },
|
||||
"_meta": { "_codex_apps": routing_metadata },
|
||||
},
|
||||
}))
|
||||
.expect("listed tool")
|
||||
});
|
||||
let actual = executor_plugin_hook_sources(
|
||||
&snapshot,
|
||||
&PluginsConfigToml::default(),
|
||||
|server, tool| {
|
||||
tool_info
|
||||
.as_ref()
|
||||
.filter(|info| info.server_name == server && info.tool.name == tool)
|
||||
},
|
||||
);
|
||||
let expected = if admitted {
|
||||
vec![expected.clone()]
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
assert_eq!(actual, expected, "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_unallowlisted_executor_plugin_hooks() {
|
||||
let mut wrong_event = cleanup_hook_manifest();
|
||||
@@ -475,7 +319,7 @@ fn ignores_unallowlisted_executor_plugin_hooks() {
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
executor_plugin_hook_sources(&snapshot, &PluginsConfigToml::default(), |_, _| None),
|
||||
executor_plugin_hook_sources(&snapshot, &PluginsConfigToml::default()),
|
||||
Vec::<ExecutorPluginHookSource>::new(),
|
||||
"{name}"
|
||||
);
|
||||
@@ -495,7 +339,7 @@ fn ignores_file_backed_executor_plugin_hooks() {
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
executor_plugin_hook_sources(&file_backed, &PluginsConfigToml::default(), |_, _| None),
|
||||
executor_plugin_hook_sources(&file_backed, &PluginsConfigToml::default()),
|
||||
Vec::<ExecutorPluginHookSource>::new()
|
||||
);
|
||||
}
|
||||
@@ -514,7 +358,6 @@ fn v2_hooks_preserve_admission_policy_and_environment_routing() {
|
||||
let plugin = codex_exec_server::ExecutorPlugin {
|
||||
id: "computer-use@openai-bundled".to_string(),
|
||||
display_name: "Computer use".to_string(),
|
||||
remote_plugin_id: None,
|
||||
version: "local".to_string(),
|
||||
root: PathUri::parse("file:///plugins/computer-use").unwrap(),
|
||||
files,
|
||||
@@ -543,7 +386,7 @@ fn v2_hooks_preserve_admission_policy_and_environment_routing() {
|
||||
let mut second = expected_source(/*index*/ 0);
|
||||
second.environment_id = "executor-b".to_string();
|
||||
assert_eq!(
|
||||
executor_plugin_hook_sources_v2(&snapshots, &PluginsConfigToml::default(), |_, _| None),
|
||||
executor_plugin_hook_sources_v2(&snapshots, &PluginsConfigToml::default()),
|
||||
vec![expected_source(/*index*/ 0), second]
|
||||
);
|
||||
let disabled = toml::from_str(
|
||||
@@ -551,7 +394,7 @@ fn v2_hooks_preserve_admission_policy_and_environment_routing() {
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
executor_plugin_hook_sources_v2(&snapshots, &disabled, |_, _| None),
|
||||
executor_plugin_hook_sources_v2(&snapshots, &disabled),
|
||||
Vec::new()
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
use codex_http_client::OutboundProxyPolicy;
|
||||
use codex_http_client::RouteAwareClientPool;
|
||||
use std::fmt::Debug;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Builds requests whose URL is also used to resolve their outbound route.
|
||||
///
|
||||
/// Implementations must keep route selection coupled to the request URL. Returning a transport
|
||||
/// client would let callers send a different URL than the one used for route selection.
|
||||
pub(crate) trait HttpClientSelector: Debug + Send + Sync {
|
||||
fn for_current_account(&self) -> Arc<dyn HttpClientSelector>;
|
||||
fn outbound_proxy_policy(&self) -> OutboundProxyPolicy;
|
||||
}
|
||||
|
||||
impl HttpClientSelector for RouteAwareClientPool {
|
||||
fn for_current_account(&self) -> Arc<dyn HttpClientSelector> {
|
||||
Arc::new(RouteAwareClientPool::for_current_account(self))
|
||||
}
|
||||
|
||||
fn outbound_proxy_policy(&self) -> OutboundProxyPolicy {
|
||||
RouteAwareClientPool::outbound_proxy_policy(self)
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,11 @@
|
||||
mod app_mcp_routing;
|
||||
mod artifact_operation;
|
||||
mod catalog;
|
||||
mod command_migration;
|
||||
mod discoverable;
|
||||
mod error_subtype;
|
||||
mod executor_catalog;
|
||||
mod executor_hooks;
|
||||
mod executor_provider;
|
||||
mod git_policy;
|
||||
mod http_client_selector;
|
||||
pub mod installed_marketplaces;
|
||||
mod loaded_cache_metrics;
|
||||
pub mod loader;
|
||||
@@ -23,11 +20,6 @@ pub mod marketplace_upgrade;
|
||||
mod npm_source;
|
||||
mod plugin_bundle_archive;
|
||||
mod provider;
|
||||
mod recommended_plugin_install;
|
||||
pub mod remote;
|
||||
pub mod remote_legacy;
|
||||
mod remote_metadata;
|
||||
mod remote_plugin_id_resolver;
|
||||
mod script_attribution;
|
||||
mod skill_snapshots;
|
||||
pub mod startup_sync;
|
||||
@@ -54,7 +46,6 @@ pub fn is_openai_curated_marketplace_name(marketplace_name: &str) -> bool {
|
||||
pub type LoadedPlugin = codex_plugin::LoadedPlugin<codex_config::McpServerConfig>;
|
||||
pub type PluginLoadOutcome = codex_plugin::PluginLoadOutcome<codex_config::McpServerConfig>;
|
||||
|
||||
pub use app_mcp_routing::apps_route_available;
|
||||
pub use artifact_operation::ArtifactOperation;
|
||||
pub use artifact_operation::recognize_artifact_operation;
|
||||
pub use catalog::PluginCatalog;
|
||||
@@ -95,12 +86,6 @@ pub use manager::PluginReadRequest;
|
||||
pub use manager::PluginUninstallError;
|
||||
pub use manager::PluginsConfigInput;
|
||||
pub use manager::PluginsManager;
|
||||
pub use manager::RecommendedPluginCandidatesInput;
|
||||
pub use manager::RemotePluginInstallOutcome;
|
||||
pub use manager::RemotePluginInstallRequest;
|
||||
pub use manager::RemotePluginOperationError;
|
||||
pub use manager::RemotePluginOperationErrorKind;
|
||||
pub use manager::RemotePluginUninstallOutcome;
|
||||
pub use marketplace_policy::allowed_configured_marketplace_names;
|
||||
pub use marketplace_upgrade::ConfigLayerReload;
|
||||
pub use marketplace_upgrade::ConfiguredMarketplaceUpgradeError as PluginMarketplaceUpgradeError;
|
||||
@@ -110,10 +95,6 @@ pub use provider::PluginProvider;
|
||||
pub use provider::PluginProviderError;
|
||||
pub use provider::PluginProviderFuture;
|
||||
pub use provider::PluginProviderResult;
|
||||
pub use recommended_plugin_install::hydrate_selected_recommended_plugin_install_metadata;
|
||||
pub use remote::RecommendedPlugin;
|
||||
pub use remote::RecommendedPluginsMode;
|
||||
pub use remote_metadata::remote_catalog_metadata_eq;
|
||||
pub use script_attribution::PluginCommandAttribution;
|
||||
pub use script_attribution::TrustedPluginRoots;
|
||||
pub use script_attribution::command_script_arguments;
|
||||
|
||||
@@ -1,7 +1,4 @@
|
||||
use crate::PluginGitMode;
|
||||
use crate::app_mcp_routing::apply_app_mcp_routing_policy;
|
||||
use crate::app_mcp_routing::apps_route_available;
|
||||
use crate::app_mcp_routing::plugin_supports_apps;
|
||||
use crate::is_openai_curated_marketplace_name;
|
||||
use crate::manifest::ManifestCache;
|
||||
use crate::manifest::PluginManifest;
|
||||
@@ -16,10 +13,6 @@ use crate::marketplace::list_marketplaces_with_home;
|
||||
use crate::marketplace::load_marketplace;
|
||||
use crate::marketplace_policy::configured_plugins_from_stack;
|
||||
use crate::npm_source::materialize_npm_plugin_source;
|
||||
use crate::remote::REMOTE_GLOBAL_MARKETPLACE_NAME;
|
||||
use crate::remote::RemoteInstalledPlugin;
|
||||
use crate::remote_plugin_id_resolver::RemoteInstalledPluginsSnapshot;
|
||||
use crate::remote_plugin_id_resolver::RemotePluginIdResolver;
|
||||
use crate::store::PluginStore;
|
||||
use crate::store::plugin_version_for_source;
|
||||
use crate::store::plugin_version_for_source_with_fallback_manifest;
|
||||
@@ -32,18 +25,13 @@ use codex_config::types::McpServerTransportConfig;
|
||||
use codex_config::types::PluginConfig;
|
||||
use codex_config::types::PluginMcpServerConfig;
|
||||
use codex_config::types::PluginsConfigToml;
|
||||
use codex_connectors::parse_plugin_app_config;
|
||||
use codex_connectors::parse_plugin_app_config_value;
|
||||
use codex_mcp::parse_agent_plugin_mcp_config;
|
||||
use codex_mcp::parse_plugin_mcp_config;
|
||||
use codex_plugin::AppDeclaration;
|
||||
use codex_plugin::LoadedPlugin;
|
||||
use codex_plugin::PluginCapabilitySummary;
|
||||
use codex_plugin::PluginHookSource;
|
||||
use codex_plugin::PluginId;
|
||||
use codex_plugin::PluginIdError;
|
||||
use codex_plugin::app_connector_ids_from_declarations;
|
||||
use codex_protocol::auth::AuthMode;
|
||||
use codex_protocol::protocol::Product;
|
||||
use codex_skills::SkillMetadata;
|
||||
use codex_skills::SkillRootLoadRequest;
|
||||
@@ -59,7 +47,6 @@ use codex_utils_plugins::migrated_command_skills_root;
|
||||
use futures::StreamExt;
|
||||
use futures::stream;
|
||||
use serde::Deserialize;
|
||||
use serde_json::Value as JsonValue;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
use std::fs;
|
||||
@@ -74,7 +61,6 @@ mod agent_plugin_mcp_overlay;
|
||||
const DEFAULT_SKILLS_DIR_NAME: &str = "skills";
|
||||
const DEFAULT_HOOKS_CONFIG_FILE: &str = "hooks/hooks.json";
|
||||
const DEFAULT_MCP_CONFIG_FILE: &str = ".mcp.json";
|
||||
const DEFAULT_APP_CONFIG_FILE: &str = ".app.json";
|
||||
const CONFIG_TOML_FILE: &str = "config.toml";
|
||||
const CURATED_PLUGIN_CACHE_VERSION_SHA_PREFIX_LEN: usize = 8;
|
||||
const MAX_CONCURRENT_PLUGIN_LOADS: usize = 8;
|
||||
@@ -86,20 +72,11 @@ pub struct PluginHookLoadOutcome {
|
||||
pub hook_load_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// The built-in curated marketplace selection for the current runtime.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum TargetCuratedMarketplace {
|
||||
OpenAi,
|
||||
OpenAiWithRemote,
|
||||
OpenAiApi,
|
||||
}
|
||||
|
||||
enum PluginLoadScope<'a> {
|
||||
AllCapabilities {
|
||||
restriction_product: Option<Product>,
|
||||
skill_config_rules: &'a SkillConfigRules,
|
||||
plugin_skill_snapshots: Option<&'a SkillRootSnapshots<PluginSkillRoot>>,
|
||||
remote_plugin_id_resolver: &'a RemotePluginIdResolver,
|
||||
skill_root_loader: &'a dyn SkillRootLoader<PluginSkillRoot>,
|
||||
},
|
||||
HooksOnly,
|
||||
@@ -142,29 +119,20 @@ pub(crate) fn log_plugin_load_errors(plugins: &[LoadedPlugin<McpServerConfig>])
|
||||
pub(crate) async fn load_plugins_from_layer_stack(
|
||||
config_layer_stack: &ConfigLayerStack,
|
||||
plugin_policy: &codex_config::types::PluginsConfigToml,
|
||||
remote_installed_plugins_snapshot: RemoteInstalledPluginsSnapshot,
|
||||
store: &PluginStore,
|
||||
plugin_skill_snapshots: Option<&SkillRootSnapshots<PluginSkillRoot>>,
|
||||
restriction_product: Option<Product>,
|
||||
remote_global_catalog_active: bool,
|
||||
skill_root_loader: &dyn SkillRootLoader<PluginSkillRoot>,
|
||||
) -> Vec<LoadedPlugin<McpServerConfig>> {
|
||||
let skill_config_rules = skill_config_rules_from_stack(config_layer_stack);
|
||||
let RemoteInstalledPluginsSnapshot {
|
||||
configs: extra_plugins,
|
||||
remote_plugin_id_resolver,
|
||||
} = remote_installed_plugins_snapshot;
|
||||
load_plugins_from_layer_stack_with_scope(
|
||||
config_layer_stack,
|
||||
plugin_policy,
|
||||
extra_plugins,
|
||||
store,
|
||||
remote_global_catalog_active,
|
||||
PluginLoadScope::AllCapabilities {
|
||||
restriction_product,
|
||||
skill_config_rules: &skill_config_rules,
|
||||
plugin_skill_snapshots,
|
||||
remote_plugin_id_resolver: &remote_plugin_id_resolver,
|
||||
skill_root_loader,
|
||||
},
|
||||
)
|
||||
@@ -174,17 +142,11 @@ pub(crate) async fn load_plugins_from_layer_stack(
|
||||
async fn load_plugins_from_layer_stack_with_scope(
|
||||
config_layer_stack: &ConfigLayerStack,
|
||||
plugin_policy: &codex_config::types::PluginsConfigToml,
|
||||
extra_plugins: HashMap<String, PluginConfig>,
|
||||
store: &PluginStore,
|
||||
remote_global_catalog_active: bool,
|
||||
scope: PluginLoadScope<'_>,
|
||||
) -> Vec<LoadedPlugin<McpServerConfig>> {
|
||||
let mut configured_plugins = merge_configured_plugins_with_remote_installed(
|
||||
configured_plugins_from_stack(config_layer_stack, store.codex_home().as_path()),
|
||||
extra_plugins,
|
||||
store,
|
||||
remote_global_catalog_active,
|
||||
);
|
||||
let mut configured_plugins =
|
||||
configured_plugins_from_stack(config_layer_stack, store.codex_home().as_path());
|
||||
for (plugin_id, plugin) in &mut configured_plugins {
|
||||
plugin.enabled =
|
||||
Some(plugin.enabled.unwrap_or(true) && plugin_policy.allows_plugin(plugin_id));
|
||||
@@ -222,27 +184,20 @@ async fn load_plugins_from_layer_stack_with_scope(
|
||||
plugins
|
||||
}
|
||||
|
||||
/// Load hooks from enabled plugins without loading their skills, MCP servers, or apps.
|
||||
/// Load hooks from enabled plugins without loading their skills or MCP servers.
|
||||
pub async fn load_plugin_hooks_from_layer_stack(
|
||||
config_layer_stack: &ConfigLayerStack,
|
||||
plugin_policy: &codex_config::types::PluginsConfigToml,
|
||||
extra_plugins: HashMap<String, PluginConfig>,
|
||||
store: &PluginStore,
|
||||
target_curated_marketplace: TargetCuratedMarketplace,
|
||||
remote_global_catalog_active: bool,
|
||||
) -> PluginHookLoadOutcome {
|
||||
let mut plugins = load_plugins_from_layer_stack_with_scope(
|
||||
config_layer_stack,
|
||||
plugin_policy,
|
||||
extra_plugins,
|
||||
store,
|
||||
remote_global_catalog_active,
|
||||
PluginLoadScope::HooksOnly,
|
||||
)
|
||||
.await;
|
||||
plugins.retain(|plugin| {
|
||||
plugin_is_eligible_for_target_marketplace(&plugin.config_name, target_curated_marketplace)
|
||||
});
|
||||
plugins.retain(|plugin| plugin_is_eligible_for_target_marketplace(&plugin.config_name));
|
||||
PluginHookLoadOutcome {
|
||||
hook_sources: plugins
|
||||
.iter()
|
||||
@@ -257,152 +212,13 @@ pub async fn load_plugin_hooks_from_layer_stack(
|
||||
}
|
||||
}
|
||||
|
||||
fn merge_configured_plugins_with_remote_installed(
|
||||
mut configured_plugins: HashMap<String, PluginConfig>,
|
||||
extra_plugins: HashMap<String, PluginConfig>,
|
||||
store: &PluginStore,
|
||||
remote_global_catalog_active: bool,
|
||||
) -> HashMap<String, PluginConfig> {
|
||||
if remote_global_catalog_active {
|
||||
// Older Desktop clients can still sync bundled Sites to an independently updated
|
||||
// SSH app-server. A cached remote install takes precedence, even when disabled.
|
||||
if extra_plugins.contains_key("sites@openai-curated-remote") {
|
||||
configured_plugins.remove("sites@openai-bundled");
|
||||
}
|
||||
if extra_plugins.contains_key("visualize@openai-curated-remote") {
|
||||
configured_plugins.remove("visualize@openai-bundled");
|
||||
}
|
||||
configured_plugins.retain(|plugin_key, _| match PluginId::parse(plugin_key) {
|
||||
Ok(plugin_id) => plugin_id.marketplace_name != crate::OPENAI_CURATED_MARKETPLACE_NAME,
|
||||
Err(_) => true,
|
||||
});
|
||||
for (plugin_key, plugin_config) in extra_plugins {
|
||||
merge_remote_plugin_config(&mut configured_plugins, plugin_key, plugin_config);
|
||||
}
|
||||
return configured_plugins;
|
||||
}
|
||||
|
||||
let mut local_curated_installed_plugin_keys = HashMap::<String, Vec<String>>::new();
|
||||
for plugin_key in configured_plugins.keys() {
|
||||
let Ok(plugin_id) = PluginId::parse(plugin_key) else {
|
||||
continue;
|
||||
};
|
||||
if plugin_id.marketplace_name != crate::OPENAI_CURATED_MARKETPLACE_NAME
|
||||
|| store.active_plugin_version(&plugin_id).is_none()
|
||||
{
|
||||
continue;
|
||||
}
|
||||
local_curated_installed_plugin_keys
|
||||
.entry(plugin_id.plugin_name)
|
||||
.or_default()
|
||||
.push(plugin_key.clone());
|
||||
}
|
||||
|
||||
for (plugin_key, plugin_config) in extra_plugins {
|
||||
let remote_curated_plugin_name = installed_plugin_name_for_marketplace(
|
||||
&plugin_key,
|
||||
REMOTE_GLOBAL_MARKETPLACE_NAME,
|
||||
store,
|
||||
);
|
||||
let local_curated_plugin_keys = remote_curated_plugin_name
|
||||
.as_ref()
|
||||
.and_then(|plugin_name| local_curated_installed_plugin_keys.get(plugin_name));
|
||||
|
||||
if local_curated_plugin_keys.is_some() {
|
||||
continue;
|
||||
}
|
||||
|
||||
merge_remote_plugin_config(&mut configured_plugins, plugin_key, plugin_config);
|
||||
}
|
||||
|
||||
configured_plugins
|
||||
}
|
||||
|
||||
pub(crate) fn plugin_is_eligible_for_target_marketplace(
|
||||
plugin_key: &str,
|
||||
target_curated_marketplace: TargetCuratedMarketplace,
|
||||
) -> bool {
|
||||
/// The ChatGPT-only `openai-curated` marketplace is never eligible; API-key accounts use the
|
||||
/// `openai-api-curated` catalog.
|
||||
pub(crate) fn plugin_is_eligible_for_target_marketplace(plugin_key: &str) -> bool {
|
||||
let Ok(plugin_id) = PluginId::parse(plugin_key) else {
|
||||
return true;
|
||||
};
|
||||
match target_curated_marketplace {
|
||||
TargetCuratedMarketplace::OpenAi => {
|
||||
plugin_id.marketplace_name != crate::OPENAI_API_CURATED_MARKETPLACE_NAME
|
||||
&& plugin_id.marketplace_name != REMOTE_GLOBAL_MARKETPLACE_NAME
|
||||
}
|
||||
TargetCuratedMarketplace::OpenAiWithRemote => {
|
||||
plugin_id.marketplace_name != crate::OPENAI_API_CURATED_MARKETPLACE_NAME
|
||||
}
|
||||
TargetCuratedMarketplace::OpenAiApi => {
|
||||
plugin_id.marketplace_name != crate::OPENAI_CURATED_MARKETPLACE_NAME
|
||||
&& plugin_id.marketplace_name != REMOTE_GLOBAL_MARKETPLACE_NAME
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn merge_remote_plugin_config(
|
||||
configured_plugins: &mut HashMap<String, PluginConfig>,
|
||||
plugin_key: String,
|
||||
mut remote_plugin_config: PluginConfig,
|
||||
) {
|
||||
if let Some(configured_plugin) = configured_plugins.get(&plugin_key) {
|
||||
remote_plugin_config
|
||||
.mcp_servers
|
||||
.clone_from(&configured_plugin.mcp_servers);
|
||||
}
|
||||
configured_plugins.insert(plugin_key, remote_plugin_config);
|
||||
}
|
||||
|
||||
fn installed_plugin_name_for_marketplace(
|
||||
plugin_key: &str,
|
||||
marketplace_name: &str,
|
||||
store: &PluginStore,
|
||||
) -> Option<String> {
|
||||
let plugin_id = PluginId::parse(plugin_key).ok()?;
|
||||
if plugin_id.marketplace_name != marketplace_name {
|
||||
return None;
|
||||
}
|
||||
store.active_plugin_root(&plugin_id)?;
|
||||
Some(plugin_id.plugin_name)
|
||||
}
|
||||
|
||||
pub fn remote_installed_plugins_to_config(
|
||||
plugins: &[RemoteInstalledPlugin],
|
||||
store: &PluginStore,
|
||||
) -> HashMap<String, PluginConfig> {
|
||||
plugins
|
||||
.iter()
|
||||
.filter_map(|plugin| {
|
||||
let plugin_id =
|
||||
match PluginId::new(plugin.name.clone(), plugin.marketplace_name.clone()) {
|
||||
Ok(plugin_id) => plugin_id,
|
||||
Err(err) => {
|
||||
warn!(
|
||||
plugin = %plugin.name,
|
||||
remote_id = %plugin.id,
|
||||
error = %err,
|
||||
"ignoring invalid remote installed plugin name"
|
||||
);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
// TODO(remote plugins): download or update missing local bundles during remote
|
||||
// installed reconciliation. Until then, only publish remote installed state for
|
||||
// bundles already present in the local plugin cache.
|
||||
store.active_plugin_root(&plugin_id)?;
|
||||
Some((
|
||||
plugin_id.as_key(),
|
||||
PluginConfig {
|
||||
enabled: Some(plugin.enabled),
|
||||
remote_plugin_id: None,
|
||||
release_id: None,
|
||||
auto_provision: None,
|
||||
mcp_servers: HashMap::new(),
|
||||
apps: HashMap::new(),
|
||||
},
|
||||
))
|
||||
})
|
||||
.collect()
|
||||
plugin_id.marketplace_name != crate::OPENAI_CURATED_MARKETPLACE_NAME
|
||||
}
|
||||
|
||||
pub fn refresh_curated_plugin_cache(
|
||||
@@ -860,20 +676,18 @@ async fn load_plugin(
|
||||
scope: &PluginLoadScope<'_>,
|
||||
) -> LoadedPlugin<McpServerConfig> {
|
||||
let plugin_id = PluginId::parse(&config_name);
|
||||
let active_plugin_installation = plugin_id
|
||||
let active_plugin_root = plugin_id
|
||||
.as_ref()
|
||||
.ok()
|
||||
.and_then(|plugin_id| store.active_plugin_installation(plugin_id));
|
||||
let root = active_plugin_installation
|
||||
.as_ref()
|
||||
.map(|installation| installation.root.clone())
|
||||
.and_then(|plugin_id| store.active_plugin_root(plugin_id));
|
||||
let root = active_plugin_root
|
||||
.clone()
|
||||
.unwrap_or_else(|| match &plugin_id {
|
||||
Ok(plugin_id) => store.plugin_base_root(plugin_id),
|
||||
Err(_) => store.root().clone(),
|
||||
});
|
||||
let mut loaded_plugin = LoadedPlugin {
|
||||
config_name,
|
||||
remote_plugin_id: None,
|
||||
manifest_name: None,
|
||||
plugin_namespace: None,
|
||||
manifest_description: None,
|
||||
@@ -884,7 +698,6 @@ async fn load_plugin(
|
||||
disabled_skill_paths: HashSet::new(),
|
||||
has_enabled_skills: false,
|
||||
mcp_servers: HashMap::new(),
|
||||
apps: Vec::new(),
|
||||
hook_sources: Vec::new(),
|
||||
hook_load_warnings: Vec::new(),
|
||||
error: None,
|
||||
@@ -894,13 +707,13 @@ async fn load_plugin(
|
||||
return loaded_plugin;
|
||||
}
|
||||
|
||||
let (loaded_plugin_id, installation) = match plugin_id {
|
||||
let (loaded_plugin_id, plugin_root) = match plugin_id {
|
||||
Ok(plugin_id) => {
|
||||
let Some(installation) = active_plugin_installation else {
|
||||
let Some(plugin_root) = active_plugin_root else {
|
||||
loaded_plugin.error = Some("plugin is not installed".to_string());
|
||||
return loaded_plugin;
|
||||
};
|
||||
(plugin_id, installation)
|
||||
(plugin_id, plugin_root)
|
||||
}
|
||||
Err(err) => {
|
||||
loaded_plugin.error = Some(err.to_string());
|
||||
@@ -908,16 +721,6 @@ async fn load_plugin(
|
||||
}
|
||||
};
|
||||
|
||||
loaded_plugin.remote_plugin_id = match scope {
|
||||
PluginLoadScope::AllCapabilities {
|
||||
remote_plugin_id_resolver,
|
||||
..
|
||||
} => remote_plugin_id_resolver.remote_plugin_id_for_installation(&installation),
|
||||
PluginLoadScope::HooksOnly => None,
|
||||
};
|
||||
|
||||
let plugin_root = installation.root;
|
||||
|
||||
if !plugin_root.as_path().is_dir() {
|
||||
loaded_plugin.error = Some("path does not exist or is not a directory".to_string());
|
||||
return loaded_plugin;
|
||||
@@ -942,7 +745,6 @@ async fn load_plugin(
|
||||
restriction_product,
|
||||
skill_config_rules,
|
||||
plugin_skill_snapshots,
|
||||
remote_plugin_id_resolver: _,
|
||||
skill_root_loader,
|
||||
} => {
|
||||
loaded_plugin.manifest_name = Some(manifest.display_name().to_string());
|
||||
@@ -951,7 +753,6 @@ async fn load_plugin(
|
||||
plugin_skill_roots(&plugin_root, manifest_paths, loaded_manifest.format);
|
||||
let plugin_identity = PluginIdentity {
|
||||
plugin_id: loaded_plugin_id.as_key(),
|
||||
remote_plugin_id: loaded_plugin.remote_plugin_id.clone(),
|
||||
};
|
||||
let resolved_skills = load_plugin_skill_inventory(
|
||||
&plugin_root,
|
||||
@@ -975,10 +776,6 @@ async fn load_plugin(
|
||||
loaded_manifest.format,
|
||||
)
|
||||
.await;
|
||||
if plugin_supports_apps(loaded_manifest.format, &loaded_plugin_id) {
|
||||
loaded_plugin.apps =
|
||||
load_plugin_apps_from_manifest(plugin_root.as_path(), manifest_paths).await;
|
||||
}
|
||||
}
|
||||
PluginLoadScope::HooksOnly => {}
|
||||
}
|
||||
@@ -1164,60 +961,6 @@ fn default_mcp_config_paths(plugin_root: &Path) -> Vec<AbsolutePathBuf> {
|
||||
paths
|
||||
}
|
||||
|
||||
pub async fn load_plugin_apps(plugin_root: &Path, plugin_id: &PluginId) -> Vec<AppDeclaration> {
|
||||
if let Some(loaded_manifest) = load_plugin_manifest_with_format(plugin_root) {
|
||||
if !plugin_supports_apps(loaded_manifest.format, plugin_id) {
|
||||
return Vec::new();
|
||||
}
|
||||
return load_plugin_apps_from_manifest(plugin_root, &loaded_manifest.manifest.paths).await;
|
||||
}
|
||||
load_apps_from_paths(plugin_root, default_app_config_paths(plugin_root)).await
|
||||
}
|
||||
|
||||
pub(crate) async fn load_plugin_apps_from_manifest(
|
||||
plugin_root: &Path,
|
||||
manifest_paths: &PluginManifestPaths,
|
||||
) -> Vec<AppDeclaration> {
|
||||
load_apps_from_paths(
|
||||
plugin_root,
|
||||
plugin_app_config_paths(plugin_root, manifest_paths),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub fn plugin_app_declarations_from_value(value: &JsonValue) -> Vec<AppDeclaration> {
|
||||
let Ok(mut apps) = parse_plugin_app_config_value(value.clone()) else {
|
||||
return Vec::new();
|
||||
};
|
||||
apps.retain(|app| !app.connector_id.0.trim().is_empty());
|
||||
let mut seen_connector_ids = HashSet::new();
|
||||
apps.retain(|app| seen_connector_ids.insert(app.connector_id.0.clone()));
|
||||
apps
|
||||
}
|
||||
|
||||
fn plugin_app_config_paths(
|
||||
plugin_root: &Path,
|
||||
manifest_paths: &PluginManifestPaths,
|
||||
) -> Vec<AbsolutePathBuf> {
|
||||
if let Some(path) = &manifest_paths.apps {
|
||||
return vec![path.clone()];
|
||||
}
|
||||
default_app_config_paths(plugin_root)
|
||||
}
|
||||
|
||||
fn default_app_config_paths(plugin_root: &Path) -> Vec<AbsolutePathBuf> {
|
||||
let mut paths = Vec::new();
|
||||
let default_path = plugin_root.join(DEFAULT_APP_CONFIG_FILE);
|
||||
if default_path.is_file()
|
||||
&& let Ok(default_path) = AbsolutePathBuf::try_from(default_path)
|
||||
{
|
||||
paths.push(default_path);
|
||||
}
|
||||
paths.sort_unstable_by(|left, right| left.as_path().cmp(right.as_path()));
|
||||
paths.dedup_by(|left, right| left.as_path() == right.as_path());
|
||||
paths
|
||||
}
|
||||
|
||||
// Discover plugin-bundled hooks from manifest `hooks` entries when present
|
||||
// (path, paths, inline object, or inline objects), otherwise from the default
|
||||
// `hooks/hooks.json` file.
|
||||
@@ -1328,41 +1071,6 @@ fn append_plugin_hook_file(
|
||||
});
|
||||
}
|
||||
|
||||
async fn load_apps_from_paths(
|
||||
plugin_root: &Path,
|
||||
app_config_paths: Vec<AbsolutePathBuf>,
|
||||
) -> Vec<AppDeclaration> {
|
||||
let mut app_declarations = Vec::new();
|
||||
for app_config_path in app_config_paths {
|
||||
let Ok(contents) = tokio::fs::read_to_string(app_config_path.as_path()).await else {
|
||||
continue;
|
||||
};
|
||||
let declarations = match parse_plugin_app_config(&contents) {
|
||||
Ok(declarations) => declarations,
|
||||
Err(err) => {
|
||||
warn!(
|
||||
path = %app_config_path.display(),
|
||||
"failed to parse plugin app config: {err}"
|
||||
);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
app_declarations.extend(declarations.into_iter().filter(|app| {
|
||||
if app.connector_id.0.trim().is_empty() {
|
||||
warn!(
|
||||
plugin = %plugin_root.display(),
|
||||
"plugin app config is missing an app id"
|
||||
);
|
||||
false
|
||||
} else {
|
||||
true
|
||||
}
|
||||
}));
|
||||
}
|
||||
app_declarations
|
||||
}
|
||||
|
||||
pub(crate) async fn plugin_capability_summary_from_root(
|
||||
plugin_id: &PluginId,
|
||||
plugin_root: &AbsolutePathBuf,
|
||||
@@ -1374,7 +1082,6 @@ pub(crate) async fn plugin_capability_summary_from_root(
|
||||
let manifest = loaded_manifest.manifest;
|
||||
let plugin_identity = PluginIdentity {
|
||||
plugin_id: plugin_id.as_key(),
|
||||
remote_plugin_id: None,
|
||||
};
|
||||
|
||||
let manifest_paths = &manifest.paths;
|
||||
@@ -1410,12 +1117,6 @@ pub(crate) async fn plugin_capability_summary_from_root(
|
||||
mcp_server_names.sort_unstable();
|
||||
mcp_server_names.dedup();
|
||||
|
||||
let app_declarations = if plugin_supports_apps(manifest_format, plugin_id) {
|
||||
load_plugin_apps_from_manifest(plugin_root.as_path(), manifest_paths).await
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
let app_connector_ids = app_connector_ids_from_declarations(&app_declarations);
|
||||
|
||||
Some(PluginCapabilitySummary {
|
||||
config_name: plugin_id.as_key(),
|
||||
@@ -1424,29 +1125,17 @@ pub(crate) async fn plugin_capability_summary_from_root(
|
||||
description: None,
|
||||
has_skills,
|
||||
mcp_server_names,
|
||||
app_connector_ids,
|
||||
})
|
||||
}
|
||||
|
||||
/// Loads plugin MCP servers without applying user-specific policy overrides.
|
||||
pub async fn load_plugin_mcp_servers(
|
||||
plugin_root: &Path,
|
||||
plugin_id: &PluginId,
|
||||
auth_mode: Option<AuthMode>,
|
||||
) -> HashMap<String, McpServerConfig> {
|
||||
load_plugin_mcp_servers_with_policy(
|
||||
plugin_root,
|
||||
plugin_id,
|
||||
auth_mode,
|
||||
/*plugin_policy*/ None,
|
||||
)
|
||||
.await
|
||||
pub async fn load_plugin_mcp_servers(plugin_root: &Path) -> HashMap<String, McpServerConfig> {
|
||||
load_plugin_mcp_servers_with_policy(plugin_root, /*plugin_policy*/ None).await
|
||||
}
|
||||
|
||||
/// Loads plugin MCP servers with the effective configuration policy for an installed plugin.
|
||||
pub async fn load_configured_plugin_mcp_servers(
|
||||
plugin_root: &Path,
|
||||
auth_mode: Option<AuthMode>,
|
||||
plugin_id: &PluginId,
|
||||
config_layer_stack: &ConfigLayerStack,
|
||||
codex_home: &Path,
|
||||
@@ -1456,7 +1145,7 @@ pub async fn load_configured_plugin_mcp_servers(
|
||||
.get(&plugin_id.as_key())
|
||||
.map(|plugin| &plugin.mcp_servers);
|
||||
|
||||
load_plugin_mcp_servers_with_policy(plugin_root, plugin_id, auth_mode, plugin_policy).await
|
||||
load_plugin_mcp_servers_with_policy(plugin_root, plugin_policy).await
|
||||
}
|
||||
|
||||
/// Applies user policy without widening the selected plugin's declared restrictions.
|
||||
@@ -1524,23 +1213,9 @@ pub fn apply_configured_plugin_mcp_server_policies(
|
||||
|
||||
async fn load_plugin_mcp_servers_with_policy(
|
||||
plugin_root: &Path,
|
||||
plugin_id: &PluginId,
|
||||
auth_mode: Option<AuthMode>,
|
||||
plugin_policy: Option<&HashMap<String, PluginMcpServerConfig>>,
|
||||
) -> HashMap<String, McpServerConfig> {
|
||||
let mut mcp_servers = load_declared_plugin_mcp_servers(plugin_root, plugin_policy).await;
|
||||
if !apps_route_available(auth_mode) || mcp_servers.is_empty() {
|
||||
return mcp_servers;
|
||||
}
|
||||
|
||||
let mut app_declarations = load_plugin_apps(plugin_root, plugin_id).await;
|
||||
apply_app_mcp_routing_policy(
|
||||
&mut app_declarations,
|
||||
&mut mcp_servers,
|
||||
auth_mode,
|
||||
/*plugin_active*/ true,
|
||||
);
|
||||
mcp_servers
|
||||
load_declared_plugin_mcp_servers(plugin_root, plugin_policy).await
|
||||
}
|
||||
|
||||
async fn load_declared_plugin_mcp_servers(
|
||||
|
||||
@@ -96,13 +96,11 @@ async fn concurrent_plugin_loads_preserve_mcp_precedence_and_hook_warnings() {
|
||||
let store = PluginStore::new(temp_dir.path().to_path_buf());
|
||||
let config: ConfigToml = stack.effective_config().try_into().expect("plugin config");
|
||||
let skill_config_rules = skill_config_rules_from_stack(&stack);
|
||||
let remote_plugin_id_resolver = RemotePluginIdResolver::default();
|
||||
let skill_root_loader = test_skill_root_loader();
|
||||
let scope = PluginLoadScope::AllCapabilities {
|
||||
restriction_product: Some(Product::Codex),
|
||||
skill_config_rules: &skill_config_rules,
|
||||
plugin_skill_snapshots: None,
|
||||
remote_plugin_id_resolver: &remote_plugin_id_resolver,
|
||||
skill_root_loader: skill_root_loader.as_ref(),
|
||||
};
|
||||
let mut expected = Vec::new();
|
||||
@@ -126,11 +124,9 @@ async fn concurrent_plugin_loads_preserve_mcp_precedence_and_hook_warnings() {
|
||||
let loaded = load_plugins_from_layer_stack(
|
||||
&stack,
|
||||
&config.plugins,
|
||||
RemoteInstalledPluginsSnapshot::default(),
|
||||
&store,
|
||||
/*plugin_skill_snapshots*/ None,
|
||||
Some(Product::Codex),
|
||||
/*remote_global_catalog_active*/ false,
|
||||
&overlap_loader,
|
||||
)
|
||||
.await;
|
||||
@@ -153,30 +149,6 @@ async fn concurrent_plugin_loads_preserve_mcp_precedence_and_hook_warnings() {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn agent_plugin_overlay_apps_are_not_runtime_active() {
|
||||
let temp_dir = TempDir::new().expect("tempdir");
|
||||
let plugin_root = temp_dir.path().join("plugin");
|
||||
write_file(
|
||||
&plugin_root.join("plugin.json"),
|
||||
&format!(r#"{{"$schema":"{AGENT_PLUGIN_SCHEMA_URI}","name":"plugin"}}"#),
|
||||
);
|
||||
write_file(
|
||||
&plugin_root.join(".codex-plugin/plugin.json"),
|
||||
r#"{"name":"plugin","apps":"./.app.json"}"#,
|
||||
);
|
||||
write_file(
|
||||
&plugin_root.join(".app.json"),
|
||||
r#"{"apps":{"example":{"id":"connector_example"}}}"#,
|
||||
);
|
||||
|
||||
assert!(
|
||||
load_plugin_apps(&plugin_root, &PluginId::parse("plugin@test").unwrap())
|
||||
.await
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn agent_plugin_codex_mcp_overlay_only_forwards_matching_stdio_server_env_vars() {
|
||||
let temp_dir = TempDir::new().expect("tempdir");
|
||||
@@ -208,12 +180,7 @@ async fn agent_plugin_codex_mcp_overlay_only_forwards_matching_stdio_server_env_
|
||||
}"#,
|
||||
);
|
||||
|
||||
let mut expected = load_plugin_mcp_servers(
|
||||
&plugin_root,
|
||||
&PluginId::parse("plugin@test").unwrap(),
|
||||
/*auth_mode*/ None,
|
||||
)
|
||||
.await;
|
||||
let mut expected = load_plugin_mcp_servers(&plugin_root).await;
|
||||
let Some(McpServerConfig {
|
||||
transport: McpServerTransportConfig::Stdio { env, env_vars, .. },
|
||||
..
|
||||
@@ -245,12 +212,7 @@ async fn agent_plugin_codex_mcp_overlay_only_forwards_matching_stdio_server_env_
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
load_plugin_mcp_servers(
|
||||
&plugin_root,
|
||||
&PluginId::parse("plugin@test").unwrap(),
|
||||
/*auth_mode*/ None
|
||||
)
|
||||
.await,
|
||||
load_plugin_mcp_servers(&plugin_root).await,
|
||||
expected
|
||||
);
|
||||
}
|
||||
@@ -276,12 +238,7 @@ async fn agent_plugin_codex_mcp_overlay_supports_inline_legacy_servers_without_p
|
||||
}"#,
|
||||
);
|
||||
|
||||
let mut expected = load_plugin_mcp_servers(
|
||||
&plugin_root,
|
||||
&PluginId::parse("plugin@test").unwrap(),
|
||||
/*auth_mode*/ None,
|
||||
)
|
||||
.await;
|
||||
let mut expected = load_plugin_mcp_servers(&plugin_root).await;
|
||||
let Some(McpServerConfig {
|
||||
transport: McpServerTransportConfig::Stdio { env_vars, .. },
|
||||
..
|
||||
@@ -302,12 +259,7 @@ async fn agent_plugin_codex_mcp_overlay_supports_inline_legacy_servers_without_p
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
load_plugin_mcp_servers(
|
||||
&plugin_root,
|
||||
&PluginId::parse("plugin@test").unwrap(),
|
||||
/*auth_mode*/ None
|
||||
)
|
||||
.await,
|
||||
load_plugin_mcp_servers(&plugin_root).await,
|
||||
expected
|
||||
);
|
||||
}
|
||||
@@ -433,11 +385,9 @@ async fn installed_agent_plugin_uses_isolated_data_root_for_stdio_mcp() {
|
||||
.try_into::<codex_config::config_toml::ConfigToml>()
|
||||
.unwrap()
|
||||
.plugins,
|
||||
RemoteInstalledPluginsSnapshot::default(),
|
||||
&store,
|
||||
/*plugin_skill_snapshots*/ None,
|
||||
Some(Product::Codex),
|
||||
/*remote_global_catalog_active*/ false,
|
||||
test_skill_root_loader().as_ref(),
|
||||
)
|
||||
.await;
|
||||
@@ -590,19 +540,8 @@ async fn legacy_ema_policy_disables_installed_and_selected_plugin_servers() {
|
||||
.expect("legacy policy stack");
|
||||
let config: ConfigToml = stack.effective_config().try_into().expect("plugin config");
|
||||
let policy = &config.plugins.plugins["plugin@market"].mcp_servers;
|
||||
let installed = load_plugin_mcp_servers_with_policy(
|
||||
&plugin_root,
|
||||
&PluginId::parse("plugin@test").unwrap(),
|
||||
/*auth_mode*/ None,
|
||||
Some(policy),
|
||||
)
|
||||
.await;
|
||||
let mut selected = load_plugin_mcp_servers(
|
||||
&plugin_root,
|
||||
&PluginId::parse("plugin@test").unwrap(),
|
||||
/*auth_mode*/ None,
|
||||
)
|
||||
.await;
|
||||
let installed = load_plugin_mcp_servers_with_policy(&plugin_root, Some(policy)).await;
|
||||
let mut selected = load_plugin_mcp_servers(&plugin_root).await;
|
||||
assert!(selected["example"].enabled);
|
||||
apply_configured_plugin_mcp_server_policies(policy, &mut selected);
|
||||
assert!(!installed["example"].enabled);
|
||||
@@ -715,11 +654,9 @@ enabled = true
|
||||
.try_into::<codex_config::config_toml::ConfigToml>()
|
||||
.unwrap()
|
||||
.plugins,
|
||||
RemoteInstalledPluginsSnapshot::default(),
|
||||
&store,
|
||||
/*plugin_skill_snapshots*/ None,
|
||||
Some(Product::Codex),
|
||||
/*remote_global_catalog_active*/ false,
|
||||
test_skill_root_loader().as_ref(),
|
||||
)
|
||||
.await;
|
||||
@@ -730,9 +667,7 @@ enabled = true
|
||||
.try_into::<codex_config::config_toml::ConfigToml>()
|
||||
.unwrap()
|
||||
.plugins,
|
||||
HashMap::new(),
|
||||
&store,
|
||||
/*remote_global_catalog_active*/ false,
|
||||
PluginLoadScope::HooksOnly,
|
||||
)
|
||||
.await;
|
||||
@@ -761,7 +696,6 @@ enabled = true
|
||||
assert!(full_valid.manifest_name.is_some());
|
||||
assert!(!full_valid.skill_roots.is_empty());
|
||||
assert!(!full_valid.mcp_servers.is_empty());
|
||||
assert!(!full_valid.apps.is_empty());
|
||||
|
||||
let hooks_only_valid = hooks_only
|
||||
.iter()
|
||||
@@ -770,34 +704,27 @@ enabled = true
|
||||
assert_eq!(hooks_only_valid.manifest_name, None);
|
||||
assert!(hooks_only_valid.skill_roots.is_empty());
|
||||
assert!(hooks_only_valid.mcp_servers.is_empty());
|
||||
assert!(hooks_only_valid.apps.is_empty());
|
||||
|
||||
for (policy, active, extra_plugins) in [
|
||||
for (policy, active) in [
|
||||
(
|
||||
"[plugins._default]\nenabled = false\n[plugins.\"valid@test\"]\nenabled = true",
|
||||
true,
|
||||
// Typed policy must also veto enabled entries from the original source map.
|
||||
configured_plugins_from_stack(&stack, temp_dir.path()),
|
||||
),
|
||||
(
|
||||
"[plugins.\"valid@test\".mcp_servers.example]\nenabled = true",
|
||||
true,
|
||||
HashMap::new(),
|
||||
),
|
||||
(
|
||||
"[plugins._default]\nenabled = false\n[plugins.\"valid@test\".mcp_servers.example]\ndefault_tools_approval_mode = 'approve'",
|
||||
false,
|
||||
HashMap::new(),
|
||||
),
|
||||
(
|
||||
"[plugins.\"valid@test\"]\nremote_plugin_id = 'remote-plugin-123'\nrelease_id = 'plugin-release-123'\nauto_provision = true",
|
||||
true,
|
||||
HashMap::new(),
|
||||
),
|
||||
(
|
||||
"[plugins._default]\nenabled = false\n[plugins.\"valid@test\"]\nremote_plugin_id = 'remote-plugin-123'\nrelease_id = 'plugin-release-123'\nauto_provision = true",
|
||||
false,
|
||||
HashMap::new(),
|
||||
),
|
||||
] {
|
||||
let stack = ConfigLayerStack::default()
|
||||
@@ -814,11 +741,9 @@ enabled = true
|
||||
let plugins = load_plugins_from_layer_stack(
|
||||
&stack,
|
||||
&policy,
|
||||
RemoteInstalledPluginsSnapshot::default(),
|
||||
&store,
|
||||
/*plugin_skill_snapshots*/ None,
|
||||
Some(Product::Codex),
|
||||
/*remote_global_catalog_active*/ false,
|
||||
test_skill_root_loader().as_ref(),
|
||||
)
|
||||
.await;
|
||||
@@ -828,19 +753,10 @@ enabled = true
|
||||
plugin.is_active(),
|
||||
!plugin.skill_roots.is_empty(),
|
||||
!plugin.mcp_servers.is_empty(),
|
||||
!plugin.apps.is_empty()
|
||||
),
|
||||
(active, active, active, active),
|
||||
(active, active, active),
|
||||
);
|
||||
let hooks = load_plugin_hooks_from_layer_stack(
|
||||
&stack,
|
||||
&policy,
|
||||
extra_plugins,
|
||||
&store,
|
||||
TargetCuratedMarketplace::OpenAi,
|
||||
/*remote_global_catalog_active*/ false,
|
||||
)
|
||||
.await;
|
||||
let hooks = load_plugin_hooks_from_layer_stack(&stack, &policy, &store).await;
|
||||
assert_eq!(
|
||||
hooks,
|
||||
PluginHookLoadOutcome {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,6 @@
|
||||
//! Plugin mutation errors and their stable telemetry classifications.
|
||||
|
||||
use crate::marketplace::MarketplaceError;
|
||||
use crate::remote_legacy::RemotePluginMutationError;
|
||||
use crate::store::PluginStoreError;
|
||||
use crate::store::error_context_sub_error_type;
|
||||
use codex_plugin::PluginIdError;
|
||||
@@ -11,9 +10,6 @@ pub enum PluginInstallError {
|
||||
#[error("{0}")]
|
||||
Marketplace(#[from] MarketplaceError),
|
||||
|
||||
#[error("{0}")]
|
||||
Remote(#[from] RemotePluginMutationError),
|
||||
|
||||
#[error("{0}")]
|
||||
Store(#[from] PluginStoreError),
|
||||
|
||||
@@ -45,7 +41,6 @@ impl PluginInstallError {
|
||||
pub fn sub_error_type(&self) -> Option<String> {
|
||||
match self {
|
||||
Self::Marketplace(err) => marketplace_error_sub_error_type(err),
|
||||
Self::Remote(err) => err.sub_error_type(),
|
||||
Self::Store(err) => err.sub_error_type(),
|
||||
Self::Config(_) => Some("failed_to_enable_plugin".to_string()),
|
||||
Self::Join(_) => Some("plugin_install_task_failed".to_string()),
|
||||
@@ -56,7 +51,6 @@ impl PluginInstallError {
|
||||
pub(super) fn plugin_install_error_type(err: &PluginInstallError) -> &'static str {
|
||||
match err {
|
||||
PluginInstallError::Marketplace(err) => marketplace_error_type(err),
|
||||
PluginInstallError::Remote(err) => remote_plugin_mutation_error_type(err),
|
||||
PluginInstallError::Store(err) => plugin_store_error_type(err),
|
||||
PluginInstallError::Config(_) => "config",
|
||||
PluginInstallError::Join(_) => "join",
|
||||
@@ -87,26 +81,6 @@ pub(super) fn marketplace_error_sub_error_type(err: &MarketplaceError) -> Option
|
||||
}
|
||||
}
|
||||
|
||||
fn remote_plugin_mutation_error_type(err: &RemotePluginMutationError) -> &'static str {
|
||||
match err {
|
||||
RemotePluginMutationError::Unavailable => "remote_mutation_unavailable",
|
||||
RemotePluginMutationError::AuthRequired => "remote_mutation_auth_required",
|
||||
RemotePluginMutationError::UnsupportedAuthMode => "remote_mutation_unsupported_auth_mode",
|
||||
RemotePluginMutationError::AuthToken(_) => "remote_mutation_auth_token",
|
||||
RemotePluginMutationError::InvalidBaseUrl(_) => "remote_mutation_invalid_base_url",
|
||||
RemotePluginMutationError::InvalidBaseUrlPath => "remote_mutation_invalid_base_url_path",
|
||||
RemotePluginMutationError::Request { .. } => "remote_mutation_request",
|
||||
RemotePluginMutationError::UnexpectedStatus { .. } => "remote_mutation_unexpected_status",
|
||||
RemotePluginMutationError::Decode { .. } => "remote_mutation_decode",
|
||||
RemotePluginMutationError::UnexpectedPluginId { .. } => {
|
||||
"remote_mutation_unexpected_plugin_id"
|
||||
}
|
||||
RemotePluginMutationError::UnexpectedEnabledState { .. } => {
|
||||
"remote_mutation_unexpected_enabled_state"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn plugin_store_error_type(err: &PluginStoreError) -> &'static str {
|
||||
match err {
|
||||
PluginStoreError::Io { .. } => "store_io",
|
||||
@@ -119,9 +93,6 @@ pub enum PluginUninstallError {
|
||||
#[error("{0}")]
|
||||
InvalidPluginId(#[from] PluginIdError),
|
||||
|
||||
#[error("{0}")]
|
||||
Remote(#[from] RemotePluginMutationError),
|
||||
|
||||
#[error("{0}")]
|
||||
Store(#[from] PluginStoreError),
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -63,8 +63,6 @@ struct RawPluginManifest {
|
||||
#[serde(default)]
|
||||
mcp_servers: Option<RawPluginManifestMcpServers>,
|
||||
#[serde(default)]
|
||||
apps: Option<String>,
|
||||
#[serde(default)]
|
||||
hooks: Option<RawPluginManifestHooks>,
|
||||
#[serde(default)]
|
||||
interface: Option<RawPluginManifestInterface>,
|
||||
@@ -288,7 +286,6 @@ fn resolve_raw_plugin_manifest(
|
||||
keywords,
|
||||
skills,
|
||||
mcp_servers,
|
||||
apps,
|
||||
hooks,
|
||||
interface,
|
||||
extensions,
|
||||
@@ -389,7 +386,6 @@ fn resolve_raw_plugin_manifest(
|
||||
extensions.get("com.openai"),
|
||||
),
|
||||
mcp_servers: resolve_manifest_mcp_servers(plugin_root, mcp_servers),
|
||||
apps: resolve_manifest_path(plugin_root, "apps", apps.as_deref()),
|
||||
hooks: resolve_manifest_hooks(plugin_root, hooks),
|
||||
},
|
||||
interface,
|
||||
@@ -1011,7 +1007,6 @@ mod tests {
|
||||
mcp_servers: Some(PluginManifestMcpServers::Path(
|
||||
plugin_root.join(".mcp.json").expect("MCP URI"),
|
||||
)),
|
||||
apps: Some(plugin_root.join("apps").expect("apps URI")),
|
||||
hooks: Some(PluginManifestHooks::Paths(vec![
|
||||
plugin_root.join("hooks.json").expect("hooks URI"),
|
||||
])),
|
||||
|
||||
@@ -100,7 +100,6 @@ impl MarketplacePluginManifestFallback {
|
||||
onboarding_skill: None,
|
||||
skills: Vec::new(),
|
||||
mcp_servers: None,
|
||||
apps: None,
|
||||
hooks: None,
|
||||
};
|
||||
if let Some(interface) = manifest.interface.as_mut() {
|
||||
@@ -648,7 +647,7 @@ fn resolve_plugin_source(
|
||||
url: normalize_git_plugin_source_url(marketplace_path, &url)?,
|
||||
path: path
|
||||
.as_deref()
|
||||
.map(|path| normalize_remote_plugin_subdir(marketplace_path, path))
|
||||
.map(|path| normalize_git_plugin_subdir(marketplace_path, path))
|
||||
.transpose()?,
|
||||
ref_name: normalize_optional_git_selector(&ref_name),
|
||||
sha: normalize_optional_git_selector(&sha),
|
||||
@@ -662,7 +661,7 @@ fn resolve_plugin_source(
|
||||
},
|
||||
) => Ok(MarketplacePluginSource::Git {
|
||||
url: normalize_git_plugin_source_url(marketplace_path, &url)?,
|
||||
path: Some(normalize_remote_plugin_subdir(marketplace_path, &path)?),
|
||||
path: Some(normalize_git_plugin_subdir(marketplace_path, &path)?),
|
||||
ref_name: normalize_optional_git_selector(&ref_name),
|
||||
sha: normalize_optional_git_selector(&sha),
|
||||
}),
|
||||
@@ -728,7 +727,7 @@ fn resolve_local_plugin_source_path(
|
||||
Ok(marketplace_root_dir(marketplace_path)?.join(relative_source_path))
|
||||
}
|
||||
|
||||
fn normalize_remote_plugin_subdir(
|
||||
fn normalize_git_plugin_subdir(
|
||||
marketplace_path: &AbsolutePathBuf,
|
||||
path: &str,
|
||||
) -> Result<String, MarketplaceError> {
|
||||
|
||||
@@ -26,10 +26,6 @@ impl PluginMarketplaceContext {
|
||||
|| self.scopes.iter().any(|scope| scope.config.plugins_enabled)
|
||||
}
|
||||
|
||||
pub fn remote_plugins_enabled(&self) -> bool {
|
||||
self.global_config.plugins_enabled && self.global_config.remote_plugin_enabled
|
||||
}
|
||||
|
||||
pub(super) fn list_marketplaces(
|
||||
&self,
|
||||
manager: &PluginsManager,
|
||||
|
||||
@@ -9,7 +9,6 @@ use crate::is_openai_curated_marketplace_name;
|
||||
use crate::marketplace::marketplace_root_dir;
|
||||
use crate::marketplace_add::MarketplaceSource;
|
||||
use crate::marketplace_add::parse_marketplace_source;
|
||||
use crate::remote::RemotePluginScope;
|
||||
use crate::startup_sync::OPENAI_PLUGINS_GIT_URL;
|
||||
use crate::startup_sync::curated_plugins_api_marketplace_path;
|
||||
use crate::startup_sync::curated_plugins_repo_path;
|
||||
@@ -458,6 +457,17 @@ fn validate_expected_marketplace_name(
|
||||
})
|
||||
}
|
||||
|
||||
/// Marketplace names of the removed remote plugin catalog. They stay reserved so a repository
|
||||
/// marketplace cannot impersonate a name that older clients treated as server-managed.
|
||||
pub(crate) const LEGACY_REMOTE_MARKETPLACE_NAMES: [&str; 6] = [
|
||||
"openai-curated-remote",
|
||||
"created-by-me-remote",
|
||||
"workspace-directory",
|
||||
"workspace-shared-with-me",
|
||||
"workspace-shared-with-me-private",
|
||||
"workspace-shared-with-me-unlisted",
|
||||
];
|
||||
|
||||
fn is_reserved_marketplace_name(marketplace_name: &str) -> bool {
|
||||
matches!(
|
||||
marketplace_name,
|
||||
@@ -466,7 +476,7 @@ fn is_reserved_marketplace_name(marketplace_name: &str) -> bool {
|
||||
| OPENAI_BUNDLED_MARKETPLACE_NAME
|
||||
| OPENAI_BUNDLED_ALPHA_MARKETPLACE_NAME
|
||||
| OPENAI_PRIMARY_RUNTIME_MARKETPLACE_NAME
|
||||
) || RemotePluginScope::from_marketplace_name(marketplace_name).is_some()
|
||||
) || LEGACY_REMOTE_MARKETPLACE_NAMES.contains(&marketplace_name)
|
||||
}
|
||||
|
||||
fn managed_marketplace_name(
|
||||
|
||||
@@ -88,4 +88,3 @@ host_pattern = '^github[.]com$'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -10,8 +10,6 @@ use codex_config::LoaderOverrides;
|
||||
use codex_config::NoopThreadConfigLoader;
|
||||
use codex_config::loader::load_config_layers_state;
|
||||
use codex_exec_server::LOCAL_FS;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_http_client::OutboundProxyPolicy;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_login::test_support::auth_manager_from_optional_auth;
|
||||
use codex_protocol::protocol::Product;
|
||||
@@ -89,10 +87,6 @@ async fn curated_git_requirements_control_plugin_skills() -> Result<()> {
|
||||
.plugins,
|
||||
"openai".to_string(),
|
||||
/*plugins_enabled*/ true,
|
||||
/*remote_plugin_enabled*/ false,
|
||||
"https://chatgpt.com/backend-api/".to_string(),
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
/*product_sku*/ None,
|
||||
);
|
||||
let auth = CodexAuth::from_api_key("test-api-key");
|
||||
let skills = test_skill_root_loader();
|
||||
@@ -123,7 +117,6 @@ async fn curated_git_requirements_control_plugin_skills() -> Result<()> {
|
||||
)?),
|
||||
scope: SkillScope::User,
|
||||
plugin_id: Some(plugin_id),
|
||||
remote_plugin_id: None,
|
||||
}],
|
||||
errors: Vec::new(),
|
||||
}
|
||||
|
||||
@@ -434,13 +434,10 @@ url = "https://github.com/openai/plugins.git"
|
||||
OPENAI_BUNDLED_MARKETPLACE_NAME,
|
||||
OPENAI_BUNDLED_ALPHA_MARKETPLACE_NAME,
|
||||
OPENAI_PRIMARY_RUNTIME_MARKETPLACE_NAME,
|
||||
crate::remote::REMOTE_GLOBAL_MARKETPLACE_NAME,
|
||||
crate::remote::REMOTE_CREATED_BY_ME_MARKETPLACE_NAME,
|
||||
crate::remote::REMOTE_WORKSPACE_MARKETPLACE_NAME,
|
||||
crate::remote::REMOTE_WORKSPACE_SHARED_WITH_ME_MARKETPLACE_NAME,
|
||||
crate::remote::REMOTE_WORKSPACE_SHARED_WITH_ME_PRIVATE_MARKETPLACE_NAME,
|
||||
crate::remote::REMOTE_WORKSPACE_SHARED_WITH_ME_UNLISTED_MARKETPLACE_NAME,
|
||||
] {
|
||||
]
|
||||
.into_iter()
|
||||
.chain(super::LEGACY_REMOTE_MARKETPLACE_NAMES)
|
||||
{
|
||||
assert!(
|
||||
MarketplacePolicy::from_requirements(config.requirements())
|
||||
.validate_install(config, codex_home.path(), &repository_manifest, marketplace)
|
||||
|
||||
@@ -616,10 +616,6 @@ fn find_marketplace_plugin_builds_manifest_fallback_from_entry() {
|
||||
}
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
manifest.paths.apps.as_ref(),
|
||||
Some(&AbsolutePathBuf::try_from(plugin_root.join("apps/app.json")).unwrap())
|
||||
);
|
||||
assert_eq!(
|
||||
manifest.paths.hooks.as_ref(),
|
||||
Some(&crate::manifest::PluginManifestHooks::Paths(vec![
|
||||
|
||||
@@ -1,52 +0,0 @@
|
||||
//! Verify connection reuse without retaining request metadata or crossing config lifetimes.
|
||||
|
||||
use super::PluginsConfigInput;
|
||||
use crate::test_support::test_http_client_factory;
|
||||
use codex_config::ConfigLayerStack;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[test]
|
||||
fn repeated_service_configs_and_early_clones_share_one_lazy_pool() {
|
||||
let input = PluginsConfigInput::new(
|
||||
ConfigLayerStack::default(),
|
||||
Default::default(),
|
||||
"openai".to_string(),
|
||||
/*plugins_enabled*/ true,
|
||||
/*remote_plugin_enabled*/ true,
|
||||
"https://chatgpt.com/backend-api".to_string(),
|
||||
test_http_client_factory(),
|
||||
/*product_sku*/ None,
|
||||
);
|
||||
let clone = input.clone();
|
||||
assert!(input.remote_http_clients.get().is_none());
|
||||
let first = input.remote_plugin_service_config();
|
||||
let reuse: Vec<_> = (0..220)
|
||||
.map(|_| {
|
||||
Arc::ptr_eq(
|
||||
&first.http_clients,
|
||||
&clone.remote_plugin_service_config().http_clients,
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let new_input = PluginsConfigInput::new(
|
||||
input.config_layer_stack.clone(),
|
||||
input.plugins.clone(),
|
||||
input.model_provider_id.clone(),
|
||||
input.plugins_enabled,
|
||||
input.remote_plugin_enabled,
|
||||
input.chatgpt_base_url.clone(),
|
||||
input.http_client_factory.clone(),
|
||||
input.product_sku,
|
||||
);
|
||||
assert_eq!(
|
||||
(
|
||||
reuse,
|
||||
Arc::ptr_eq(
|
||||
&first.http_clients,
|
||||
&new_input.remote_plugin_service_config().http_clients,
|
||||
),
|
||||
),
|
||||
(vec![true; 220], false)
|
||||
);
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
use crate::remote::RemotePluginCatalogError;
|
||||
use crate::remote::RemotePluginServiceConfig;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_tools::DiscoverableTool;
|
||||
|
||||
pub async fn hydrate_selected_recommended_plugin_install_metadata(
|
||||
config: &RemotePluginServiceConfig,
|
||||
auth: Option<&CodexAuth>,
|
||||
mut tool: DiscoverableTool,
|
||||
) -> Result<Option<DiscoverableTool>, RemotePluginCatalogError> {
|
||||
let DiscoverableTool::Plugin(plugin) = &mut tool else {
|
||||
return Ok(Some(tool));
|
||||
};
|
||||
let remote_plugin_id = plugin.remote_plugin_id.clone().ok_or_else(|| {
|
||||
RemotePluginCatalogError::UnexpectedResponse(format!(
|
||||
"recommended plugin `{}` is missing remote plugin identity",
|
||||
plugin.id
|
||||
))
|
||||
})?;
|
||||
let Some(app_connector_ids) =
|
||||
crate::remote::fetch_recommended_plugin_install_metadata(config, auth, &remote_plugin_id)
|
||||
.await?
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
plugin.app_connector_ids = app_connector_ids;
|
||||
Ok(Some(tool))
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,327 +0,0 @@
|
||||
use super::RemotePluginCatalogCacheMode;
|
||||
use super::RemotePluginDirectoryItem;
|
||||
use super::RemotePluginScope;
|
||||
use super::RemotePluginServiceConfig;
|
||||
use chrono::DateTime;
|
||||
use chrono::Utc;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_protocol::auth::AuthMode;
|
||||
use serde::Deserialize;
|
||||
use serde::Deserializer;
|
||||
use serde::Serialize;
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde::de::DeserializeSeed;
|
||||
use serde::de::IgnoredAny;
|
||||
use serde::de::MapAccess;
|
||||
use serde::de::SeqAccess;
|
||||
use serde::de::Visitor;
|
||||
use std::fmt;
|
||||
use std::fs::File;
|
||||
use std::io;
|
||||
use std::io::Read;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
use tracing::warn;
|
||||
|
||||
// `plugin/list` and other callers that assume all plugins are available locally will be
|
||||
// deprecated soon. Remove this catalog cache when those callers migrate to on-demand fetching.
|
||||
const REMOTE_PLUGIN_CATALOG_DISK_CACHE_SCHEMA_VERSION: u8 = 1;
|
||||
const REMOTE_PLUGIN_CATALOG_DISK_CACHE_DIR: &str = "cache/remote_plugin_catalog";
|
||||
const REMOTE_PLUGIN_CATALOG_DISK_CACHE_TTL: Duration = Duration::from_secs(60 * 60 * 3);
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
struct RemotePluginCatalogCacheKey {
|
||||
chatgpt_base_url: String,
|
||||
auth_mode: AuthMode,
|
||||
// Global catalogs predate scoped cache keys and must keep their existing filenames.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
scope: Option<RemotePluginScope>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
collection: Option<String>,
|
||||
}
|
||||
|
||||
impl RemotePluginCatalogCacheKey {
|
||||
fn new(
|
||||
config: &RemotePluginServiceConfig,
|
||||
auth: &CodexAuth,
|
||||
scope: RemotePluginScope,
|
||||
collection: Option<&str>,
|
||||
) -> Option<Self> {
|
||||
// Credentials never identify an account owner, so only the global catalog may be
|
||||
// cached; user and workspace catalogs are never shared.
|
||||
if !matches!(scope, RemotePluginScope::Global) {
|
||||
return None;
|
||||
}
|
||||
Some(Self {
|
||||
chatgpt_base_url: config.chatgpt_base_url.clone(),
|
||||
auth_mode: auth.auth_mode(),
|
||||
scope: None,
|
||||
collection: collection.map(str::to_owned),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct RemotePluginCatalogDiskCache<Plugins> {
|
||||
schema_version: u8,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
fetched_at: Option<DateTime<Utc>>,
|
||||
plugins: Plugins,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(super) enum RemotePluginCatalogCacheFreshness {
|
||||
Fresh,
|
||||
Stale,
|
||||
}
|
||||
|
||||
pub(super) struct CachedDirectoryPlugins<T> {
|
||||
pub plugins: Vec<T>,
|
||||
pub freshness: RemotePluginCatalogCacheFreshness,
|
||||
}
|
||||
|
||||
pub(super) fn has_cached_directory_plugins(
|
||||
codex_home: &Path,
|
||||
config: &RemotePluginServiceConfig,
|
||||
auth: &CodexAuth,
|
||||
scope: RemotePluginScope,
|
||||
cache_mode: RemotePluginCatalogCacheMode,
|
||||
) -> bool {
|
||||
// Ignore each entry so Serde still requires `plugins` to be an array.
|
||||
load_cached_directory_plugins::<IgnoredAny>(
|
||||
codex_home, config, auth, scope, /*collection*/ None, cache_mode,
|
||||
)
|
||||
.is_some()
|
||||
}
|
||||
|
||||
pub(super) fn load_cached_directory_plugins<T: DeserializeOwned>(
|
||||
codex_home: &Path,
|
||||
config: &RemotePluginServiceConfig,
|
||||
auth: &CodexAuth,
|
||||
scope: RemotePluginScope,
|
||||
collection: Option<&str>,
|
||||
cache_mode: RemotePluginCatalogCacheMode,
|
||||
) -> Option<CachedDirectoryPlugins<T>> {
|
||||
if cache_mode == RemotePluginCatalogCacheMode::ForceRefetch {
|
||||
return None;
|
||||
}
|
||||
let cache_key = RemotePluginCatalogCacheKey::new(config, auth, scope, collection)?;
|
||||
let cache_path = cache_path(codex_home, &cache_key);
|
||||
let bytes = match read_catalog_bytes(&cache_path, cache_mode) {
|
||||
Ok(bytes) => bytes?,
|
||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return None,
|
||||
Err(err) => {
|
||||
warn!(
|
||||
cache_path = %cache_path.display(),
|
||||
"failed to read remote plugin catalog disk cache: {err}"
|
||||
);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let cache: RemotePluginCatalogDiskCache<Vec<T>> = match serde_json::from_slice(&bytes) {
|
||||
Ok(cache) => cache,
|
||||
Err(err) => {
|
||||
warn!(
|
||||
cache_path = %cache_path.display(),
|
||||
"failed to parse remote plugin catalog disk cache: {err}"
|
||||
);
|
||||
let _ = std::fs::remove_file(cache_path);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
if cache.schema_version != REMOTE_PLUGIN_CATALOG_DISK_CACHE_SCHEMA_VERSION {
|
||||
let _ = std::fs::remove_file(cache_path);
|
||||
return None;
|
||||
}
|
||||
|
||||
let freshness = if is_fresh(cache.fetched_at, Utc::now()) {
|
||||
RemotePluginCatalogCacheFreshness::Fresh
|
||||
} else if cache_mode == RemotePluginCatalogCacheMode::PreferFreshCache {
|
||||
return None;
|
||||
} else {
|
||||
RemotePluginCatalogCacheFreshness::Stale
|
||||
};
|
||||
Some(CachedDirectoryPlugins {
|
||||
plugins: cache.plugins,
|
||||
freshness,
|
||||
})
|
||||
}
|
||||
|
||||
fn read_catalog_bytes(
|
||||
path: &Path,
|
||||
cache_mode: RemotePluginCatalogCacheMode,
|
||||
) -> io::Result<Option<Vec<u8>>> {
|
||||
let mut file = File::open(path)?;
|
||||
let mut bytes = Vec::new();
|
||||
if cache_mode == RemotePluginCatalogCacheMode::PreferFreshCache {
|
||||
const PREFIX_LEN: usize = 256;
|
||||
bytes.reserve_exact(PREFIX_LEN);
|
||||
file.by_ref()
|
||||
.take(PREFIX_LEN as u64)
|
||||
.read_to_end(&mut bytes)?;
|
||||
if bytes.len() < PREFIX_LEN {
|
||||
return Ok(Some(bytes));
|
||||
}
|
||||
if CatalogHeader::is_stale_prefix(&bytes, Utc::now()) {
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
file.read_to_end(&mut bytes)?;
|
||||
Ok(Some(bytes))
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct CatalogHeader {
|
||||
schema_version: Option<u8>,
|
||||
fetched_at: Option<DateTime<Utc>>,
|
||||
metadata_before_plugins: bool,
|
||||
}
|
||||
|
||||
impl CatalogHeader {
|
||||
fn is_stale_prefix(bytes: &[u8], now: DateTime<Utc>) -> bool {
|
||||
let mut header = Self::default();
|
||||
let mut json = serde_json::Deserializer::from_slice(bytes);
|
||||
// A bounded read can end inside the payload. Only fully decoded fields count.
|
||||
let parsed = json.deserialize_map(&mut header).and_then(|()| json.end());
|
||||
if parsed.is_err_and(|err| !err.is_eof()) {
|
||||
return false;
|
||||
}
|
||||
header.metadata_before_plugins && !is_fresh(header.fetched_at, now)
|
||||
}
|
||||
}
|
||||
|
||||
// Only the `plugins` field uses the seed. Serde calls `visit_seq` when it enters
|
||||
// that array, so a missing or wrongly typed payload still goes through the full reader.
|
||||
impl<'de> DeserializeSeed<'de> for &mut CatalogHeader {
|
||||
type Value = ();
|
||||
|
||||
fn deserialize<D: Deserializer<'de>>(self, deserializer: D) -> Result<(), D::Error> {
|
||||
deserializer.deserialize_seq(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Visitor<'de> for &mut CatalogHeader {
|
||||
type Value = ();
|
||||
|
||||
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
formatter.write_str("a plugin catalog object or its plugins array")
|
||||
}
|
||||
|
||||
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<(), A::Error> {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(field_identifier, rename_all = "snake_case")]
|
||||
enum Field {
|
||||
SchemaVersion,
|
||||
FetchedAt,
|
||||
Plugins,
|
||||
#[serde(other)]
|
||||
Other,
|
||||
}
|
||||
|
||||
let mut saw_plugins = false;
|
||||
while let Some(field) = map.next_key()? {
|
||||
match field {
|
||||
Field::SchemaVersion if self.schema_version.is_none() => {
|
||||
self.schema_version = Some(map.next_value()?);
|
||||
}
|
||||
Field::FetchedAt if self.fetched_at.is_none() => {
|
||||
self.fetched_at = Some(map.next_value()?);
|
||||
}
|
||||
Field::Plugins if !saw_plugins => {
|
||||
saw_plugins = true;
|
||||
map.next_value_seed(&mut *self)?;
|
||||
}
|
||||
Field::SchemaVersion => {
|
||||
return Err(serde::de::Error::duplicate_field("schema_version"));
|
||||
}
|
||||
Field::FetchedAt => return Err(serde::de::Error::duplicate_field("fetched_at")),
|
||||
Field::Plugins => return Err(serde::de::Error::duplicate_field("plugins")),
|
||||
Field::Other => {
|
||||
map.next_value::<IgnoredAny>()?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn visit_seq<A: SeqAccess<'de>>(self, mut plugins: A) -> Result<(), A::Error> {
|
||||
self.metadata_before_plugins = self.schema_version
|
||||
== Some(REMOTE_PLUGIN_CATALOG_DISK_CACHE_SCHEMA_VERSION)
|
||||
&& self.fetched_at.is_some();
|
||||
while plugins.next_element::<IgnoredAny>()?.is_some() {}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn write_cached_directory_plugins(
|
||||
codex_home: &Path,
|
||||
config: &RemotePluginServiceConfig,
|
||||
auth: &CodexAuth,
|
||||
scope: RemotePluginScope,
|
||||
collection: Option<&str>,
|
||||
plugins: &[RemotePluginDirectoryItem],
|
||||
) {
|
||||
let Some(cache_key) = RemotePluginCatalogCacheKey::new(config, auth, scope, collection) else {
|
||||
return;
|
||||
};
|
||||
let cache_path = cache_path(codex_home, &cache_key);
|
||||
let Ok(contents) = serde_json::to_string_pretty(&RemotePluginCatalogDiskCache {
|
||||
schema_version: REMOTE_PLUGIN_CATALOG_DISK_CACHE_SCHEMA_VERSION,
|
||||
fetched_at: Some(Utc::now()),
|
||||
plugins,
|
||||
}) else {
|
||||
return;
|
||||
};
|
||||
let _ = codex_utils_path::write_atomically(&cache_path, &contents);
|
||||
}
|
||||
|
||||
pub(crate) fn remove_cached_directory_plugins(
|
||||
codex_home: &Path,
|
||||
config: &RemotePluginServiceConfig,
|
||||
auth: &CodexAuth,
|
||||
scope: RemotePluginScope,
|
||||
collection: Option<&str>,
|
||||
) {
|
||||
let Some(cache_key) = RemotePluginCatalogCacheKey::new(config, auth, scope, collection) else {
|
||||
return;
|
||||
};
|
||||
let cache_path = cache_path(codex_home, &cache_key);
|
||||
match std::fs::remove_file(&cache_path) {
|
||||
Ok(()) => {}
|
||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(err) => {
|
||||
warn!(
|
||||
cache_path = %cache_path.display(),
|
||||
"failed to remove remote plugin catalog disk cache: {err}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn cache_path(codex_home: &Path, cache_key: &RemotePluginCatalogCacheKey) -> PathBuf {
|
||||
let cache_key_json = serde_json::to_vec(cache_key).unwrap_or_default();
|
||||
let mut cache_key_hash = 0xcbf29ce484222325_u64;
|
||||
for byte in cache_key_json {
|
||||
cache_key_hash ^= u64::from(byte);
|
||||
cache_key_hash = cache_key_hash.wrapping_mul(0x100000001b3);
|
||||
}
|
||||
codex_home
|
||||
.join(REMOTE_PLUGIN_CATALOG_DISK_CACHE_DIR)
|
||||
.join(format!("{cache_key_hash:016x}.json"))
|
||||
}
|
||||
|
||||
fn is_fresh(fetched_at: Option<DateTime<Utc>>, now: DateTime<Utc>) -> bool {
|
||||
let Some(fetched_at) = fetched_at else {
|
||||
return false;
|
||||
};
|
||||
let Ok(ttl) = chrono::Duration::from_std(REMOTE_PLUGIN_CATALOG_DISK_CACHE_TTL) else {
|
||||
return false;
|
||||
};
|
||||
let age = now.signed_duration_since(fetched_at);
|
||||
age >= chrono::Duration::zero() && age <= ttl
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "catalog_cache_tests.rs"]
|
||||
mod tests;
|
||||
@@ -1,192 +0,0 @@
|
||||
use super::*;
|
||||
use chrono::TimeDelta;
|
||||
use codex_login::AuthHeaders;
|
||||
|
||||
#[test]
|
||||
fn catalog_cache_freshness_honors_ttl() {
|
||||
let now = Utc::now();
|
||||
|
||||
assert!(!is_fresh(/*fetched_at*/ None, now));
|
||||
assert!(is_fresh(Some(now), now));
|
||||
assert!(is_fresh(Some(now - TimeDelta::hours(3)), now,));
|
||||
assert!(!is_fresh(
|
||||
Some(now - TimeDelta::hours(3) - TimeDelta::milliseconds(1)),
|
||||
now,
|
||||
));
|
||||
assert!(!is_fresh(Some(now + TimeDelta::milliseconds(1)), now));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catalog_cache_paths_are_isolated_by_scope_and_collection() {
|
||||
let codex_home = Path::new("/tmp/codex-home");
|
||||
let cache_key_for_scope = |scope| RemotePluginCatalogCacheKey {
|
||||
chatgpt_base_url: "https://chatgpt.com/backend-api".to_string(),
|
||||
auth_mode: codex_protocol::auth::AuthMode::Headers,
|
||||
scope: (scope != RemotePluginScope::Global).then_some(scope),
|
||||
collection: None,
|
||||
};
|
||||
|
||||
let paths = [
|
||||
RemotePluginScope::Global,
|
||||
RemotePluginScope::User,
|
||||
RemotePluginScope::Workspace,
|
||||
]
|
||||
.map(|scope| cache_path(codex_home, &cache_key_for_scope(scope)));
|
||||
|
||||
assert_ne!(paths[0], paths[1]);
|
||||
assert_ne!(paths[0], paths[2]);
|
||||
assert_ne!(paths[1], paths[2]);
|
||||
|
||||
let mut collection_key = cache_key_for_scope(RemotePluginScope::Global);
|
||||
collection_key.collection = Some("vertical".to_string());
|
||||
assert!(!paths.contains(&cache_path(codex_home, &collection_key)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn freshness_probe_defers_plugin_validation_until_full_read() {
|
||||
let codex_home = tempfile::tempdir().expect("create codex home");
|
||||
let config = RemotePluginServiceConfig::new(
|
||||
"https://chatgpt.com/backend-api".to_string(),
|
||||
crate::test_support::test_http_client_factory(),
|
||||
/*product_sku*/ None,
|
||||
);
|
||||
let auth = CodexAuth::Headers(AuthHeaders::new(http::HeaderMap::new()));
|
||||
let scope = RemotePluginScope::Global;
|
||||
let key = RemotePluginCatalogCacheKey::new(&config, &auth, scope, /*collection*/ None)
|
||||
.expect("global cache key");
|
||||
let path = cache_path(codex_home.path(), &key);
|
||||
let probe = |mode| has_cached_directory_plugins(codex_home.path(), &config, &auth, scope, mode);
|
||||
let version = REMOTE_PLUGIN_CATALOG_DISK_CACHE_SCHEMA_VERSION;
|
||||
let now = serde_json::to_string(&Utc::now()).expect("serialize timestamp");
|
||||
let expired_at = "2000-01-01T00:00:00Z";
|
||||
let padding = " ".repeat(512);
|
||||
for contents in [
|
||||
serde_json::json!({"schema_version": version + 1, "plugins": []}).to_string(),
|
||||
serde_json::json!({"schema_version": version}).to_string(),
|
||||
serde_json::json!({"schema_version": version, "plugins": {}}).to_string(),
|
||||
format!(r#"{{"schema_version":{version},"plugins":[{{"#),
|
||||
format!(r#"{{"schema_version":{version},"fetched_at":{now},"plugins":[{padding}"#),
|
||||
format!(
|
||||
r#"{{"details":{{"fetched_at":"{expired_at}"}},"schema_version":{version},"plugins":[{padding}"#
|
||||
),
|
||||
format!(
|
||||
r#"{{"schema_version":{version},"fetched_at":"{expired_at}","fetched_at":{now},"plugins":[{padding}"#
|
||||
),
|
||||
format!(
|
||||
r#"{{"schema_version":{version},"fetched_at":"{expired_at}","plugins":{{}}}}{padding}"#
|
||||
),
|
||||
] {
|
||||
codex_utils_path::write_atomically(&path, &contents).expect("write invalid cache");
|
||||
assert!(
|
||||
!probe(RemotePluginCatalogCacheMode::PreferFreshCache),
|
||||
"{contents}"
|
||||
);
|
||||
assert!(!path.exists());
|
||||
}
|
||||
|
||||
let expired = format!(
|
||||
r#"{{"note":"[","fetched\u005fat":"{expired_at}","schema_version":{version},"plugins":[{padding}"#
|
||||
);
|
||||
codex_utils_path::write_atomically(&path, &expired).expect("write expired cache");
|
||||
assert!(!probe(RemotePluginCatalogCacheMode::PreferFreshCache));
|
||||
assert!(path.exists());
|
||||
assert!(!probe(RemotePluginCatalogCacheMode::PreferCache));
|
||||
assert!(!path.exists());
|
||||
|
||||
let reordered =
|
||||
format!(r#"{{"plugins":[{padding}],"schema_version":{version},"fetched_at":{now}}}"#);
|
||||
codex_utils_path::write_atomically(&path, &reordered).expect("write reordered cache");
|
||||
assert!(probe(RemotePluginCatalogCacheMode::PreferFreshCache));
|
||||
|
||||
let contents = serde_json::json!({
|
||||
"schema_version": version,
|
||||
"fetched_at": Utc::now(),
|
||||
"plugins": [{}],
|
||||
});
|
||||
codex_utils_path::write_atomically(&path, &contents.to_string()).expect("write invalid plugin");
|
||||
assert!(probe(RemotePluginCatalogCacheMode::PreferFreshCache));
|
||||
assert!(
|
||||
load_cached_directory_plugins::<RemotePluginDirectoryItem>(
|
||||
codex_home.path(),
|
||||
&config,
|
||||
&auth,
|
||||
scope,
|
||||
/*collection*/ None,
|
||||
RemotePluginCatalogCacheMode::PreferCache,
|
||||
)
|
||||
.is_none()
|
||||
);
|
||||
assert!(!path.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn header_auth_does_not_cache_private_catalogs_without_a_stable_identity() {
|
||||
let codex_home = tempfile::tempdir().expect("create codex home");
|
||||
let config = RemotePluginServiceConfig::new(
|
||||
"https://chatgpt.com/backend-api".to_string(),
|
||||
crate::test_support::test_http_client_factory(),
|
||||
/*product_sku*/ None,
|
||||
);
|
||||
let auth = CodexAuth::Headers(AuthHeaders::new(http::HeaderMap::new()));
|
||||
|
||||
write_cached_directory_plugins(
|
||||
codex_home.path(),
|
||||
&config,
|
||||
&auth,
|
||||
RemotePluginScope::Global,
|
||||
/*collection*/ None,
|
||||
&[],
|
||||
);
|
||||
assert!(
|
||||
load_cached_directory_plugins::<RemotePluginDirectoryItem>(
|
||||
codex_home.path(),
|
||||
&config,
|
||||
&auth,
|
||||
RemotePluginScope::Global,
|
||||
/*collection*/ None,
|
||||
RemotePluginCatalogCacheMode::PreferCache,
|
||||
)
|
||||
.is_some()
|
||||
);
|
||||
|
||||
for scope in [RemotePluginScope::User, RemotePluginScope::Workspace] {
|
||||
let insecure_cache_key = RemotePluginCatalogCacheKey {
|
||||
chatgpt_base_url: config.chatgpt_base_url.clone(),
|
||||
auth_mode: codex_protocol::auth::AuthMode::Headers,
|
||||
scope: Some(scope),
|
||||
collection: None,
|
||||
};
|
||||
let insecure_cache_path = cache_path(codex_home.path(), &insecure_cache_key);
|
||||
|
||||
write_cached_directory_plugins(
|
||||
codex_home.path(),
|
||||
&config,
|
||||
&auth,
|
||||
scope,
|
||||
/*collection*/ None,
|
||||
&[],
|
||||
);
|
||||
assert!(!insecure_cache_path.exists());
|
||||
|
||||
let insecure_cache = RemotePluginCatalogDiskCache {
|
||||
schema_version: REMOTE_PLUGIN_CATALOG_DISK_CACHE_SCHEMA_VERSION,
|
||||
fetched_at: Some(Utc::now()),
|
||||
plugins: Vec::<RemotePluginDirectoryItem>::new(),
|
||||
};
|
||||
let contents = serde_json::to_string_pretty(&insecure_cache).expect("serialize cache");
|
||||
codex_utils_path::write_atomically(&insecure_cache_path, &contents)
|
||||
.expect("write insecure cache");
|
||||
|
||||
assert!(
|
||||
load_cached_directory_plugins::<RemotePluginDirectoryItem>(
|
||||
codex_home.path(),
|
||||
&config,
|
||||
&auth,
|
||||
scope,
|
||||
/*collection*/ None,
|
||||
RemotePluginCatalogCacheMode::PreferCache,
|
||||
)
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
//! Discovers best-effort runtime invalidation hints from locally cached plugin bundles.
|
||||
//!
|
||||
//! Discovery ignores runtime policy and does not prepare runtime directories. Repeated inclusion
|
||||
//! unions old and new declarations for updates; removals capture declarations before deletion.
|
||||
|
||||
use crate::loader::load_plugin_apps_from_manifest;
|
||||
use crate::loader::load_plugin_hooks;
|
||||
use crate::loader::load_plugin_mcp_servers_from_manifest_with_format;
|
||||
use crate::loader::plugin_skill_roots;
|
||||
use crate::manifest::PluginManifestFormat;
|
||||
use crate::store::PluginStore;
|
||||
use codex_hooks::plugin_hook_declarations;
|
||||
use codex_plugin::PluginId;
|
||||
|
||||
/// Runtime categories affected by a plugin change, before runtime policy filtering.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct RemotePluginCapabilities {
|
||||
pub has_mcps: bool,
|
||||
pub has_apps: bool,
|
||||
pub has_hooks: bool,
|
||||
pub has_skills: bool,
|
||||
}
|
||||
|
||||
impl RemotePluginCapabilities {
|
||||
pub(crate) async fn include_active_bundle(
|
||||
&mut self,
|
||||
store: &PluginStore,
|
||||
plugin_id: &PluginId,
|
||||
) {
|
||||
let Some(root) = store.active_plugin_root(plugin_id) else {
|
||||
return;
|
||||
};
|
||||
let Some(loaded) = store.manifest_cache.load(root.as_path()) else {
|
||||
return;
|
||||
};
|
||||
let paths = &loaded.manifest.paths;
|
||||
self.has_skills |= !plugin_skill_roots(&root, paths, loaded.format).is_empty();
|
||||
self.has_mcps |= !load_plugin_mcp_servers_from_manifest_with_format(
|
||||
root.as_path(),
|
||||
paths,
|
||||
/*plugin_policy*/ None,
|
||||
// Declaration discovery must not create runtime directories or depend on their readiness.
|
||||
/*plugin_data_root*/
|
||||
None,
|
||||
loaded.format,
|
||||
)
|
||||
.await
|
||||
.is_empty();
|
||||
// Agent Plugins can declare Apps through an OpenAI extension even when the local
|
||||
// runtime does not activate them. Refresh hints describe declarations, not activation.
|
||||
self.has_apps |= !load_plugin_apps_from_manifest(root.as_path(), paths)
|
||||
.await
|
||||
.is_empty();
|
||||
if loaded.format == PluginManifestFormat::Legacy {
|
||||
let (sources, _) =
|
||||
load_plugin_hooks(&root, plugin_id, &store.plugin_data_root(plugin_id), paths);
|
||||
self.has_hooks |= !plugin_hook_declarations(&sources).is_empty();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "plugin_capabilities_tests.rs"]
|
||||
mod tests;
|
||||
@@ -1,58 +0,0 @@
|
||||
//! Covers local capability accumulation and removal hints from the shared bundle sync.
|
||||
|
||||
use super::*;
|
||||
use crate::test_support::write_file;
|
||||
use codex_utils_plugins::AGENT_PLUGIN_SCHEMA_URI;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use tempfile::TempDir;
|
||||
|
||||
#[tokio::test]
|
||||
async fn agent_plugin_capabilities_do_not_require_runtime_data_directory() {
|
||||
let codex_home = TempDir::new().expect("Codex home");
|
||||
let store = PluginStore::new(codex_home.path().to_path_buf());
|
||||
let plugin_id = PluginId::parse("example@test").expect("plugin id");
|
||||
let root = store.plugin_root(&plugin_id, "1.0.0");
|
||||
write_file(
|
||||
root.join("plugin.json").as_path(),
|
||||
&json!({
|
||||
"$schema": AGENT_PLUGIN_SCHEMA_URI,
|
||||
"name": "example",
|
||||
"extensions": {"com.openai": {"apps": "./connectors.json"}},
|
||||
})
|
||||
.to_string(),
|
||||
);
|
||||
write_file(
|
||||
root.join("mcp.json").as_path(),
|
||||
&json!({
|
||||
"$schema": "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",
|
||||
"mcpServers": {"example": {"type": "stdio", "command": "echo"}},
|
||||
})
|
||||
.to_string(),
|
||||
);
|
||||
write_file(
|
||||
root.join("connectors.json").as_path(),
|
||||
&json!({"apps": {"example": {"id": "connector_example"}}}).to_string(),
|
||||
);
|
||||
let data_root = store.mcp_data_root(&plugin_id, PluginManifestFormat::AgentPlugin);
|
||||
|
||||
for block_data_root in [false, true] {
|
||||
if block_data_root {
|
||||
write_file(data_root.as_path(), "not a directory");
|
||||
}
|
||||
let mut capabilities = RemotePluginCapabilities::default();
|
||||
capabilities.include_active_bundle(&store, &plugin_id).await;
|
||||
assert_eq!(
|
||||
capabilities,
|
||||
RemotePluginCapabilities {
|
||||
has_mcps: true,
|
||||
has_apps: true,
|
||||
// Agent Plugins declare a conventional skills root even if it is absent.
|
||||
has_skills: true,
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
assert_eq!(data_root.as_path().exists(), block_data_root);
|
||||
assert!(!data_root.as_path().is_dir());
|
||||
}
|
||||
}
|
||||
@@ -1,624 +0,0 @@
|
||||
use super::REMOTE_CREATED_BY_ME_MARKETPLACE_NAME;
|
||||
use super::REMOTE_GLOBAL_MARKETPLACE_NAME;
|
||||
use super::REMOTE_WORKSPACE_MARKETPLACE_NAME;
|
||||
use super::REMOTE_WORKSPACE_SHARED_WITH_ME_MARKETPLACE_NAME;
|
||||
use super::REMOTE_WORKSPACE_SHARED_WITH_ME_PRIVATE_MARKETPLACE_NAME;
|
||||
use super::REMOTE_WORKSPACE_SHARED_WITH_ME_UNLISTED_MARKETPLACE_NAME;
|
||||
use super::RemoteInstalledPlugin;
|
||||
use super::RemoteInstalledPluginScope;
|
||||
use super::RemotePluginCapabilities;
|
||||
use super::RemotePluginCatalogError;
|
||||
use super::RemotePluginScope;
|
||||
use super::RemotePluginServiceConfig;
|
||||
use super::RemotePluginShareDiscoverability;
|
||||
use super::ensure_chatgpt_auth;
|
||||
use super::fetch_installed_plugins;
|
||||
use crate::remote::InstalledPluginDisplayAssets;
|
||||
use crate::store::PLUGINS_CACHE_DIR;
|
||||
use crate::store::PluginStore;
|
||||
use crate::store::PluginStoreError;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_plugin::PluginId;
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::BTreeSet;
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::OnceLock;
|
||||
use std::sync::Weak;
|
||||
use tokio::fs;
|
||||
use tokio::sync::Semaphore;
|
||||
use tracing::warn;
|
||||
|
||||
static REMOTE_INSTALLED_PLUGIN_BUNDLE_SYNC_GATES: OnceLock<
|
||||
Mutex<HashMap<PathBuf, Weak<Semaphore>>>,
|
||||
> = OnceLock::new();
|
||||
static REMOTE_PLUGIN_CACHE_MUTATIONS_IN_FLIGHT: OnceLock<
|
||||
Mutex<HashMap<RemotePluginCacheMutationKey, usize>>,
|
||||
> = OnceLock::new();
|
||||
|
||||
/// A remote plugin bundle newly installed or updated from an authenticated snapshot.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct RemotePluginMaterialization {
|
||||
pub plugin_id: PluginId,
|
||||
pub scope: RemotePluginScope,
|
||||
pub discoverability: Option<RemotePluginShareDiscoverability>,
|
||||
pub authenticated_account_id: Option<String>,
|
||||
}
|
||||
|
||||
/// A local plugin and the runtime categories affected by its bundle or installed-state change.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct RemotePluginChange {
|
||||
pub plugin_id: String,
|
||||
pub capabilities: RemotePluginCapabilities,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
||||
pub struct RemoteInstalledPluginBundleSyncOutcome {
|
||||
/// Internal provenance for materialization-owned hook trust, not runtime change reporting.
|
||||
pub materialized_remote_plugins: Vec<RemotePluginMaterialization>,
|
||||
/// Affected plugins with capabilities from either side of the change, including removals.
|
||||
/// Installed-state removals do not depend on cache cleanup succeeding.
|
||||
pub changed_plugins: Vec<RemotePluginChange>,
|
||||
pub failed_remote_plugin_ids: Vec<String>,
|
||||
/// Failures that leave an otherwise valid installed plugin unavailable locally.
|
||||
pub failed_materialization_remote_plugin_ids: Vec<String>,
|
||||
}
|
||||
|
||||
pub(crate) struct RemoteInstalledPluginBundleSyncResult {
|
||||
pub(crate) outcome: RemoteInstalledPluginBundleSyncOutcome,
|
||||
pub(crate) installed_plugins: Vec<RemoteInstalledPlugin>,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum RemoteInstalledPluginBundleSyncError {
|
||||
#[error("{0}")]
|
||||
Catalog(#[from] RemotePluginCatalogError),
|
||||
|
||||
#[error("{0}")]
|
||||
Store(#[from] PluginStoreError),
|
||||
|
||||
#[error("timed out waiting for another remote plugin cache mutation; retry")]
|
||||
LockTimeout,
|
||||
|
||||
#[error("remote plugin state changed during reconciliation; retry reconciliation")]
|
||||
Superseded,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
struct RemotePluginCacheMutationKey {
|
||||
plugin_cache_root: PathBuf,
|
||||
marketplace_name: String,
|
||||
plugin_name: String,
|
||||
}
|
||||
|
||||
pub struct RemotePluginCacheMutationGuard {
|
||||
key: RemotePluginCacheMutationKey,
|
||||
}
|
||||
|
||||
pub(crate) fn remote_installed_plugin_bundle_sync_gate(codex_home: &Path) -> Arc<Semaphore> {
|
||||
let plugin_cache_root = remote_plugin_cache_root(codex_home);
|
||||
let gates =
|
||||
REMOTE_INSTALLED_PLUGIN_BUNDLE_SYNC_GATES.get_or_init(|| Mutex::new(HashMap::new()));
|
||||
let mut gates = match gates.lock() {
|
||||
Ok(gates) => gates,
|
||||
Err(err) => err.into_inner(),
|
||||
};
|
||||
if let Some(gate) = gates.get(&plugin_cache_root).and_then(Weak::upgrade) {
|
||||
return gate;
|
||||
}
|
||||
let gate = Arc::new(Semaphore::new(/*permits*/ 1));
|
||||
gates.insert(plugin_cache_root, Arc::downgrade(&gate));
|
||||
gate
|
||||
}
|
||||
|
||||
pub async fn sync_remote_installed_plugin_bundles_once(
|
||||
codex_home: PathBuf,
|
||||
config: &RemotePluginServiceConfig,
|
||||
auth: Option<&CodexAuth>,
|
||||
) -> Result<RemoteInstalledPluginBundleSyncOutcome, RemoteInstalledPluginBundleSyncError> {
|
||||
let result = sync_remote_installed_plugin_bundles_once_with_snapshot(
|
||||
codex_home,
|
||||
config,
|
||||
auth,
|
||||
/*previous_plugin_ids*/ &[],
|
||||
)
|
||||
.await?;
|
||||
Ok(result.outcome)
|
||||
}
|
||||
|
||||
pub(crate) async fn sync_remote_installed_plugin_bundles_once_with_snapshot(
|
||||
codex_home: PathBuf,
|
||||
config: &RemotePluginServiceConfig,
|
||||
auth: Option<&CodexAuth>,
|
||||
previous_plugin_ids: &[PluginId],
|
||||
) -> Result<RemoteInstalledPluginBundleSyncResult, RemoteInstalledPluginBundleSyncError> {
|
||||
let auth = ensure_chatgpt_auth(auth)?;
|
||||
let config = &config.for_current_account();
|
||||
let fetched_installed_plugins = fetch_installed_plugins(
|
||||
config,
|
||||
auth,
|
||||
RemoteInstalledPluginScope::All,
|
||||
InstalledPluginDisplayAssets::Include,
|
||||
)
|
||||
.await?;
|
||||
// `/installed` is an authoritative full snapshot. If any row cannot be
|
||||
// canonicalized to a local cache key, omitting it makes an installed plugin
|
||||
// indistinguishable from an uninstall, so reject the pass before downloads,
|
||||
// publication, or stale cleanup.
|
||||
let mut validated_installed_plugins = Vec::with_capacity(fetched_installed_plugins.len());
|
||||
for installed_plugin in fetched_installed_plugins {
|
||||
let cached_plugin = super::remote_installed_plugin_to_cache_entry(&installed_plugin)?;
|
||||
let plugin_id = PluginId::new(
|
||||
installed_plugin.plugin.name.clone(),
|
||||
cached_plugin.marketplace_name.clone(),
|
||||
)
|
||||
.map_err(|err| {
|
||||
RemotePluginCatalogError::UnexpectedResponse(format!(
|
||||
"remote installed plugin `{}` has an invalid local cache id: {err}",
|
||||
installed_plugin.plugin.id
|
||||
))
|
||||
})?;
|
||||
validated_installed_plugins.push((installed_plugin, cached_plugin, plugin_id));
|
||||
}
|
||||
let store = PluginStore::try_new(codex_home.clone())?;
|
||||
let installed_plugin_ids = validated_installed_plugins
|
||||
.iter()
|
||||
.map(|(_, _, plugin_id)| plugin_id.as_key())
|
||||
.collect::<BTreeSet<_>>();
|
||||
let mut changed_plugins = BTreeMap::new();
|
||||
// Metadata publication removes these plugins even when cleanup fails or partially deletes
|
||||
// a bundle. Capture cached capabilities first so consumers can still invalidate runtimes;
|
||||
// plugins that were never available locally have no previous bundle to invalidate.
|
||||
for plugin_id in previous_plugin_ids {
|
||||
let key = plugin_id.as_key();
|
||||
if installed_plugin_ids.contains(&key) || store.active_plugin_root(plugin_id).is_none() {
|
||||
continue;
|
||||
}
|
||||
let mut capabilities = RemotePluginCapabilities::default();
|
||||
capabilities.include_active_bundle(&store, plugin_id).await;
|
||||
changed_plugins.insert(
|
||||
key.clone(),
|
||||
RemotePluginChange {
|
||||
plugin_id: key,
|
||||
capabilities,
|
||||
},
|
||||
);
|
||||
}
|
||||
let mut installed_plugin_names_by_marketplace =
|
||||
BTreeMap::<String, BTreeSet<String>>::from_iter([
|
||||
(REMOTE_GLOBAL_MARKETPLACE_NAME.to_string(), BTreeSet::new()),
|
||||
(
|
||||
REMOTE_CREATED_BY_ME_MARKETPLACE_NAME.to_string(),
|
||||
BTreeSet::new(),
|
||||
),
|
||||
(
|
||||
REMOTE_WORKSPACE_MARKETPLACE_NAME.to_string(),
|
||||
BTreeSet::new(),
|
||||
),
|
||||
(
|
||||
REMOTE_WORKSPACE_SHARED_WITH_ME_MARKETPLACE_NAME.to_string(),
|
||||
BTreeSet::new(),
|
||||
),
|
||||
(
|
||||
REMOTE_WORKSPACE_SHARED_WITH_ME_PRIVATE_MARKETPLACE_NAME.to_string(),
|
||||
BTreeSet::new(),
|
||||
),
|
||||
(
|
||||
REMOTE_WORKSPACE_SHARED_WITH_ME_UNLISTED_MARKETPLACE_NAME.to_string(),
|
||||
BTreeSet::new(),
|
||||
),
|
||||
]);
|
||||
let mut failed_remote_plugin_ids = BTreeSet::new();
|
||||
let mut failed_materialization_remote_plugin_ids = BTreeSet::new();
|
||||
let mut installed_plugins = Vec::new();
|
||||
|
||||
for (installed_plugin, cached_plugin, plugin_id) in validated_installed_plugins {
|
||||
let marketplace_name = cached_plugin.marketplace_name.clone();
|
||||
let plugin = installed_plugin.plugin;
|
||||
installed_plugin_names_by_marketplace
|
||||
.entry(marketplace_name.clone())
|
||||
.or_default()
|
||||
.insert(plugin.name.clone());
|
||||
let release_version = plugin
|
||||
.release
|
||||
.version
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|version| !version.is_empty());
|
||||
if let Some(release_version) = release_version
|
||||
&& store.active_plugin_version(&plugin_id).as_deref() == Some(release_version)
|
||||
{
|
||||
if let Err(err) = store.write_remote_plugin_id(&plugin_id, &plugin.id) {
|
||||
warn!(
|
||||
remote_plugin_id = %plugin.id,
|
||||
plugin = %plugin.name,
|
||||
marketplace = %marketplace_name,
|
||||
error = %err,
|
||||
"failed to persist identity for cached remote installed plugin"
|
||||
);
|
||||
failed_remote_plugin_ids.insert(plugin.id);
|
||||
}
|
||||
installed_plugins.push(cached_plugin);
|
||||
continue;
|
||||
}
|
||||
|
||||
// aKode never downloads plugin bundles from backend-provided URLs.
|
||||
warn!(
|
||||
remote_plugin_id = %plugin.id,
|
||||
plugin = %plugin.name,
|
||||
marketplace = %marketplace_name,
|
||||
"remote plugin bundle downloads are not supported"
|
||||
);
|
||||
failed_remote_plugin_ids.insert(plugin.id.clone());
|
||||
failed_materialization_remote_plugin_ids.insert(plugin.id);
|
||||
installed_plugins.push(cached_plugin);
|
||||
}
|
||||
|
||||
installed_plugins.sort_by(|left, right| {
|
||||
left.marketplace_name
|
||||
.cmp(&right.marketplace_name)
|
||||
.then_with(|| left.id.cmp(&right.id))
|
||||
});
|
||||
let mut removed_cache_plugins = Vec::new();
|
||||
if let Err(err) = remove_stale_remote_plugin_caches(
|
||||
&store,
|
||||
&installed_plugin_names_by_marketplace,
|
||||
&mut removed_cache_plugins,
|
||||
)
|
||||
.await
|
||||
{
|
||||
warn!(error = %err, "failed to remove stale remote plugin cache entries");
|
||||
}
|
||||
for plugin in removed_cache_plugins {
|
||||
changed_plugins
|
||||
.entry(plugin.plugin_id.clone())
|
||||
.or_insert(plugin);
|
||||
}
|
||||
|
||||
Ok(RemoteInstalledPluginBundleSyncResult {
|
||||
outcome: RemoteInstalledPluginBundleSyncOutcome {
|
||||
materialized_remote_plugins: Vec::new(),
|
||||
changed_plugins: changed_plugins.into_values().collect(),
|
||||
failed_remote_plugin_ids: failed_remote_plugin_ids.into_iter().collect(),
|
||||
failed_materialization_remote_plugin_ids: failed_materialization_remote_plugin_ids
|
||||
.into_iter()
|
||||
.collect(),
|
||||
},
|
||||
installed_plugins,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn mark_remote_plugin_cache_mutation_in_flight(
|
||||
codex_home: &Path,
|
||||
marketplace_name: &str,
|
||||
plugin_name: &str,
|
||||
) -> RemotePluginCacheMutationGuard {
|
||||
let key = RemotePluginCacheMutationKey {
|
||||
plugin_cache_root: remote_plugin_cache_root(codex_home),
|
||||
marketplace_name: marketplace_name.to_string(),
|
||||
plugin_name: plugin_name.to_string(),
|
||||
};
|
||||
let mutations =
|
||||
REMOTE_PLUGIN_CACHE_MUTATIONS_IN_FLIGHT.get_or_init(|| Mutex::new(HashMap::new()));
|
||||
let mut mutations = match mutations.lock() {
|
||||
Ok(mutations) => mutations,
|
||||
Err(err) => err.into_inner(),
|
||||
};
|
||||
*mutations.entry(key.clone()).or_default() += 1;
|
||||
RemotePluginCacheMutationGuard { key }
|
||||
}
|
||||
|
||||
impl Drop for RemotePluginCacheMutationGuard {
|
||||
fn drop(&mut self) {
|
||||
let Some(mutations) = REMOTE_PLUGIN_CACHE_MUTATIONS_IN_FLIGHT.get() else {
|
||||
return;
|
||||
};
|
||||
let mut mutations = match mutations.lock() {
|
||||
Ok(mutations) => mutations,
|
||||
Err(err) => err.into_inner(),
|
||||
};
|
||||
if let Some(count) = mutations.get_mut(&self.key) {
|
||||
*count -= 1;
|
||||
if *count == 0 {
|
||||
mutations.remove(&self.key);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn remove_stale_remote_plugin_caches(
|
||||
store: &PluginStore,
|
||||
installed_plugin_names_by_marketplace: &BTreeMap<String, BTreeSet<String>>,
|
||||
removed_plugins: &mut Vec<RemotePluginChange>,
|
||||
) -> Result<(), String> {
|
||||
let codex_home = store.codex_home().as_path();
|
||||
for marketplace_name in [
|
||||
REMOTE_GLOBAL_MARKETPLACE_NAME,
|
||||
REMOTE_CREATED_BY_ME_MARKETPLACE_NAME,
|
||||
REMOTE_WORKSPACE_MARKETPLACE_NAME,
|
||||
REMOTE_WORKSPACE_SHARED_WITH_ME_MARKETPLACE_NAME,
|
||||
REMOTE_WORKSPACE_SHARED_WITH_ME_PRIVATE_MARKETPLACE_NAME,
|
||||
REMOTE_WORKSPACE_SHARED_WITH_ME_UNLISTED_MARKETPLACE_NAME,
|
||||
] {
|
||||
let marketplace_root = codex_home.join(PLUGINS_CACHE_DIR).join(marketplace_name);
|
||||
if !marketplace_root.exists() {
|
||||
continue;
|
||||
}
|
||||
let installed_plugin_names = installed_plugin_names_by_marketplace
|
||||
.get(marketplace_name)
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let mut entries = fs::read_dir(&marketplace_root).await.map_err(|err| {
|
||||
format!(
|
||||
"failed to read remote plugin cache directory {}: {err}",
|
||||
marketplace_root.display()
|
||||
)
|
||||
})?;
|
||||
while let Some(entry) = entries.next_entry().await.map_err(|err| {
|
||||
format!(
|
||||
"failed to enumerate remote plugin cache directory {}: {err}",
|
||||
marketplace_root.display()
|
||||
)
|
||||
})? {
|
||||
let plugin_name = entry.file_name().into_string().map_err(|file_name| {
|
||||
format!(
|
||||
"remote plugin cache entry under {} is not valid UTF-8: {:?}",
|
||||
marketplace_root.display(),
|
||||
file_name
|
||||
)
|
||||
})?;
|
||||
if installed_plugin_names.contains(&plugin_name) {
|
||||
continue;
|
||||
}
|
||||
if is_remote_plugin_cache_mutation_in_flight(codex_home, marketplace_name, &plugin_name)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
let cache_path = entry.path();
|
||||
let plugin_id = PluginId::new(plugin_name.clone(), marketplace_name.to_string());
|
||||
let mut capabilities = RemotePluginCapabilities::default();
|
||||
if let Ok(plugin_id) = &plugin_id {
|
||||
capabilities.include_active_bundle(store, plugin_id).await;
|
||||
}
|
||||
if cache_path.is_dir() {
|
||||
fs::remove_dir_all(&cache_path).await.map_err(|err| {
|
||||
format!(
|
||||
"failed to remove stale remote plugin cache entry {}: {err}",
|
||||
cache_path.display()
|
||||
)
|
||||
})?;
|
||||
} else {
|
||||
fs::remove_file(&cache_path).await.map_err(|err| {
|
||||
format!(
|
||||
"failed to remove stale remote plugin cache entry {}: {err}",
|
||||
cache_path.display()
|
||||
)
|
||||
})?;
|
||||
}
|
||||
let plugin_key = plugin_id
|
||||
.map(|plugin_id| plugin_id.as_key())
|
||||
.unwrap_or_else(|_| format!("{plugin_name}@{marketplace_name}"));
|
||||
removed_plugins.push(RemotePluginChange {
|
||||
plugin_id: plugin_key,
|
||||
capabilities,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn remote_plugin_cache_root(codex_home: &Path) -> PathBuf {
|
||||
codex_home.join(PLUGINS_CACHE_DIR)
|
||||
}
|
||||
|
||||
fn is_remote_plugin_cache_mutation_in_flight(
|
||||
codex_home: &Path,
|
||||
marketplace_name: &str,
|
||||
plugin_name: &str,
|
||||
) -> bool {
|
||||
let Some(mutations) = REMOTE_PLUGIN_CACHE_MUTATIONS_IN_FLIGHT.get() else {
|
||||
return false;
|
||||
};
|
||||
let mutations = match mutations.lock() {
|
||||
Ok(mutations) => mutations,
|
||||
Err(err) => err.into_inner(),
|
||||
};
|
||||
mutations.contains_key(&RemotePluginCacheMutationKey {
|
||||
plugin_cache_root: remote_plugin_cache_root(codex_home),
|
||||
marketplace_name: marketplace_name.to_string(),
|
||||
plugin_name: plugin_name.to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[tokio::test]
|
||||
async fn stale_remote_plugin_cleanup_skips_cache_mutations_in_progress() {
|
||||
let codex_home = tempfile::tempdir().expect("create codex home");
|
||||
let cached_manifest = codex_home
|
||||
.path()
|
||||
.join(PLUGINS_CACHE_DIR)
|
||||
.join(REMOTE_GLOBAL_MARKETPLACE_NAME)
|
||||
.join("linear")
|
||||
.join("1.2.3")
|
||||
.join(".codex-plugin")
|
||||
.join("plugin.json");
|
||||
std::fs::create_dir_all(cached_manifest.parent().expect("manifest parent"))
|
||||
.expect("create cached plugin manifest parent");
|
||||
std::fs::write(&cached_manifest, r#"{"name":"linear"}"#)
|
||||
.expect("write cached plugin manifest");
|
||||
let installed_plugin_names_by_marketplace =
|
||||
BTreeMap::<String, BTreeSet<String>>::from_iter([
|
||||
(REMOTE_GLOBAL_MARKETPLACE_NAME.to_string(), BTreeSet::new()),
|
||||
(
|
||||
REMOTE_WORKSPACE_MARKETPLACE_NAME.to_string(),
|
||||
BTreeSet::new(),
|
||||
),
|
||||
(
|
||||
REMOTE_WORKSPACE_SHARED_WITH_ME_PRIVATE_MARKETPLACE_NAME.to_string(),
|
||||
BTreeSet::new(),
|
||||
),
|
||||
(
|
||||
REMOTE_WORKSPACE_SHARED_WITH_ME_UNLISTED_MARKETPLACE_NAME.to_string(),
|
||||
BTreeSet::new(),
|
||||
),
|
||||
]);
|
||||
|
||||
let guard = mark_remote_plugin_cache_mutation_in_flight(
|
||||
codex_home.path(),
|
||||
REMOTE_GLOBAL_MARKETPLACE_NAME,
|
||||
"linear",
|
||||
);
|
||||
let second_guard = mark_remote_plugin_cache_mutation_in_flight(
|
||||
codex_home.path(),
|
||||
REMOTE_GLOBAL_MARKETPLACE_NAME,
|
||||
"linear",
|
||||
);
|
||||
let mut removed = Vec::new();
|
||||
remove_stale_remote_plugin_caches(
|
||||
&PluginStore::new(codex_home.path().to_path_buf()),
|
||||
&installed_plugin_names_by_marketplace,
|
||||
&mut removed,
|
||||
)
|
||||
.await
|
||||
.expect("cleanup while install is guarded");
|
||||
assert_eq!(removed, Vec::<RemotePluginChange>::new());
|
||||
assert!(cached_manifest.is_file());
|
||||
|
||||
drop(guard);
|
||||
let mut removed = Vec::new();
|
||||
remove_stale_remote_plugin_caches(
|
||||
&PluginStore::new(codex_home.path().to_path_buf()),
|
||||
&installed_plugin_names_by_marketplace,
|
||||
&mut removed,
|
||||
)
|
||||
.await
|
||||
.expect("cleanup while second install guard is still active");
|
||||
assert_eq!(removed, Vec::<RemotePluginChange>::new());
|
||||
assert!(cached_manifest.is_file());
|
||||
|
||||
drop(second_guard);
|
||||
let mut removed = Vec::new();
|
||||
remove_stale_remote_plugin_caches(
|
||||
&PluginStore::new(codex_home.path().to_path_buf()),
|
||||
&installed_plugin_names_by_marketplace,
|
||||
&mut removed,
|
||||
)
|
||||
.await
|
||||
.expect("cleanup after install guard is dropped");
|
||||
assert_eq!(
|
||||
removed,
|
||||
vec![RemotePluginChange {
|
||||
plugin_id: "linear@openai-curated-remote".to_string(),
|
||||
capabilities: RemotePluginCapabilities::default(),
|
||||
}]
|
||||
);
|
||||
assert!(!cached_manifest.exists());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stale_remote_plugin_cleanup_removes_stale_marketplace_caches_and_keeps_canonical_cache()
|
||||
{
|
||||
let codex_home = tempfile::tempdir().expect("create codex home");
|
||||
let created_by_me_cached_manifest = codex_home
|
||||
.path()
|
||||
.join(PLUGINS_CACHE_DIR)
|
||||
.join(REMOTE_CREATED_BY_ME_MARKETPLACE_NAME)
|
||||
.join("created-by-me-plugin")
|
||||
.join("1.2.3")
|
||||
.join(".codex-plugin")
|
||||
.join("plugin.json");
|
||||
std::fs::create_dir_all(
|
||||
created_by_me_cached_manifest
|
||||
.parent()
|
||||
.expect("manifest parent"),
|
||||
)
|
||||
.expect("create cached plugin manifest parent");
|
||||
std::fs::write(
|
||||
&created_by_me_cached_manifest,
|
||||
r#"{"name":"created-by-me-plugin"}"#,
|
||||
)
|
||||
.expect("write cached plugin manifest");
|
||||
let cached_manifest = codex_home
|
||||
.path()
|
||||
.join(PLUGINS_CACHE_DIR)
|
||||
.join(REMOTE_WORKSPACE_SHARED_WITH_ME_PRIVATE_MARKETPLACE_NAME)
|
||||
.join("private-plugin")
|
||||
.join("1.2.3")
|
||||
.join(".codex-plugin")
|
||||
.join("plugin.json");
|
||||
std::fs::create_dir_all(cached_manifest.parent().expect("manifest parent"))
|
||||
.expect("create cached plugin manifest parent");
|
||||
std::fs::write(&cached_manifest, r#"{"name":"private-plugin"}"#)
|
||||
.expect("write cached plugin manifest");
|
||||
let canonical_cached_manifest = codex_home
|
||||
.path()
|
||||
.join(PLUGINS_CACHE_DIR)
|
||||
.join(REMOTE_WORKSPACE_SHARED_WITH_ME_MARKETPLACE_NAME)
|
||||
.join("shared-plugin")
|
||||
.join("1.2.3")
|
||||
.join(".codex-plugin")
|
||||
.join("plugin.json");
|
||||
std::fs::create_dir_all(canonical_cached_manifest.parent().expect("manifest parent"))
|
||||
.expect("create canonical cached plugin manifest parent");
|
||||
std::fs::write(&canonical_cached_manifest, r#"{"name":"shared-plugin"}"#)
|
||||
.expect("write canonical cached plugin manifest");
|
||||
let installed_plugin_names_by_marketplace =
|
||||
BTreeMap::<String, BTreeSet<String>>::from_iter([
|
||||
(REMOTE_GLOBAL_MARKETPLACE_NAME.to_string(), BTreeSet::new()),
|
||||
(
|
||||
REMOTE_CREATED_BY_ME_MARKETPLACE_NAME.to_string(),
|
||||
BTreeSet::new(),
|
||||
),
|
||||
(
|
||||
REMOTE_WORKSPACE_MARKETPLACE_NAME.to_string(),
|
||||
BTreeSet::new(),
|
||||
),
|
||||
(
|
||||
REMOTE_WORKSPACE_SHARED_WITH_ME_MARKETPLACE_NAME.to_string(),
|
||||
BTreeSet::from(["shared-plugin".to_string()]),
|
||||
),
|
||||
(
|
||||
REMOTE_WORKSPACE_SHARED_WITH_ME_PRIVATE_MARKETPLACE_NAME.to_string(),
|
||||
BTreeSet::new(),
|
||||
),
|
||||
(
|
||||
REMOTE_WORKSPACE_SHARED_WITH_ME_UNLISTED_MARKETPLACE_NAME.to_string(),
|
||||
BTreeSet::new(),
|
||||
),
|
||||
]);
|
||||
|
||||
let mut removed = Vec::new();
|
||||
remove_stale_remote_plugin_caches(
|
||||
&PluginStore::new(codex_home.path().to_path_buf()),
|
||||
&installed_plugin_names_by_marketplace,
|
||||
&mut removed,
|
||||
)
|
||||
.await
|
||||
.expect("cleanup private shared-with-me cache");
|
||||
|
||||
assert_eq!(
|
||||
removed,
|
||||
[
|
||||
"created-by-me-plugin@created-by-me-remote",
|
||||
"private-plugin@workspace-shared-with-me-private",
|
||||
]
|
||||
.map(|plugin_id| RemotePluginChange {
|
||||
plugin_id: plugin_id.to_string(),
|
||||
capabilities: RemotePluginCapabilities::default(),
|
||||
})
|
||||
.to_vec()
|
||||
);
|
||||
assert!(!created_by_me_cached_manifest.exists());
|
||||
assert!(!cached_manifest.exists());
|
||||
assert!(canonical_cached_manifest.is_file());
|
||||
}
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
use super::RemotePluginCatalogError;
|
||||
use super::RemotePluginScope;
|
||||
use super::RemotePluginServiceConfig;
|
||||
use super::RemotePluginSummary;
|
||||
use codex_login::CodexAuth;
|
||||
use tracing::instrument;
|
||||
|
||||
/// Search parameters forwarded directly to plugin-service.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct RemotePluginSearchRequest<'a> {
|
||||
pub query: &'a str,
|
||||
pub scope: Option<RemotePluginScope>,
|
||||
pub limit: u32,
|
||||
pub page_token: Option<&'a str>,
|
||||
}
|
||||
|
||||
/// One uncached page of remote plugin search results.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct RemotePluginSearchPage {
|
||||
pub plugins: Vec<RemotePluginSummary>,
|
||||
pub next_page_token: Option<String>,
|
||||
}
|
||||
|
||||
/// Searches plugin-service without reading or populating the remote catalog cache.
|
||||
#[instrument(
|
||||
level = "debug",
|
||||
skip_all,
|
||||
fields(plugin.scope = ?search.scope, plugin.limit = search.limit)
|
||||
)]
|
||||
pub async fn search_remote_plugins(
|
||||
config: &RemotePluginServiceConfig,
|
||||
auth: Option<&CodexAuth>,
|
||||
search: RemotePluginSearchRequest<'_>,
|
||||
) -> Result<RemotePluginSearchPage, RemotePluginCatalogError> {
|
||||
let _ = (config, auth, search);
|
||||
Err(RemotePluginCatalogError::Unavailable)
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
use super::*;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use std::collections::BTreeMap;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
|
||||
mod local_paths;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
|
||||
pub enum RemotePluginShareDiscoverability {
|
||||
Listed,
|
||||
Unlisted,
|
||||
Private,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum RemotePluginSharePrincipalType {
|
||||
User,
|
||||
Group,
|
||||
Workspace,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
||||
pub struct RemotePluginSharePrincipal {
|
||||
pub principal_type: RemotePluginSharePrincipalType,
|
||||
pub principal_id: String,
|
||||
pub role: RemotePluginSharePrincipalRole,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum RemotePluginSharePrincipalRole {
|
||||
Reader,
|
||||
Editor,
|
||||
Owner,
|
||||
}
|
||||
|
||||
pub fn load_plugin_share_remote_ids_by_local_path(
|
||||
codex_home: &Path,
|
||||
) -> io::Result<BTreeMap<AbsolutePathBuf, String>> {
|
||||
let local_paths = local_paths::load_plugin_share_local_paths(codex_home)?;
|
||||
local_paths
|
||||
.into_iter()
|
||||
.map(|(remote_plugin_id, local_plugin_path)| {
|
||||
if !is_valid_remote_plugin_id(&remote_plugin_id) {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
format!(
|
||||
"invalid remote plugin id in share local path mapping: {remote_plugin_id}"
|
||||
),
|
||||
));
|
||||
}
|
||||
Ok((local_plugin_path, remote_plugin_id))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use serde::Deserialize;
|
||||
use std::collections::BTreeMap;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
use std::sync::Mutex;
|
||||
|
||||
const PLUGIN_SHARE_LOCAL_PATHS_FILE: &str = ".tmp/plugin-share-local-paths-v1.json";
|
||||
static PLUGIN_SHARE_LOCAL_PATHS_LOCK: Mutex<()> = Mutex::new(());
|
||||
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct PluginShareLocalPaths {
|
||||
#[serde(default)]
|
||||
local_plugin_paths_by_remote_plugin_id: BTreeMap<String, AbsolutePathBuf>,
|
||||
}
|
||||
|
||||
pub(crate) fn load_plugin_share_local_paths(
|
||||
codex_home: &Path,
|
||||
) -> io::Result<BTreeMap<String, AbsolutePathBuf>> {
|
||||
let _guard = lock_plugin_share_local_paths()?;
|
||||
read_plugin_share_local_paths(codex_home)
|
||||
}
|
||||
|
||||
fn lock_plugin_share_local_paths() -> io::Result<std::sync::MutexGuard<'static, ()>> {
|
||||
PLUGIN_SHARE_LOCAL_PATHS_LOCK
|
||||
.lock()
|
||||
.map_err(|err| io::Error::other(format!("plugin share local path lock poisoned: {err}")))
|
||||
}
|
||||
|
||||
fn read_plugin_share_local_paths(
|
||||
codex_home: &Path,
|
||||
) -> io::Result<BTreeMap<String, AbsolutePathBuf>> {
|
||||
let path = plugin_share_local_paths_path(codex_home);
|
||||
let contents = match std::fs::read_to_string(&path) {
|
||||
Ok(contents) => contents,
|
||||
Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(BTreeMap::new()),
|
||||
Err(err) => return Err(err),
|
||||
};
|
||||
|
||||
let mapping = serde_json::from_str::<PluginShareLocalPaths>(&contents).map_err(|err| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
format!(
|
||||
"failed to parse plugin share local path mapping {}: {err}",
|
||||
path.display()
|
||||
),
|
||||
)
|
||||
})?;
|
||||
Ok(mapping.local_plugin_paths_by_remote_plugin_id)
|
||||
}
|
||||
|
||||
fn plugin_share_local_paths_path(codex_home: &Path) -> std::path::PathBuf {
|
||||
codex_home.join(PLUGIN_SHARE_LOCAL_PATHS_FILE)
|
||||
}
|
||||
@@ -1,158 +0,0 @@
|
||||
use crate::error_subtype::http_status_sub_error_type;
|
||||
use crate::remote::RemotePluginServiceConfig;
|
||||
use codex_http_client::RouteAwareRequestError;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_protocol::protocol::Product;
|
||||
use http::StatusCode;
|
||||
use serde::Deserialize;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct RemotePluginMutationResponse {
|
||||
pub id: String,
|
||||
pub enabled: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum RemotePluginMutationError {
|
||||
#[error("remote plugins are not available in aKode")]
|
||||
Unavailable,
|
||||
|
||||
#[error("chatgpt authentication required for remote plugin mutation")]
|
||||
AuthRequired,
|
||||
|
||||
#[error(
|
||||
"chatgpt authentication required for remote plugin mutation; api key auth is not supported"
|
||||
)]
|
||||
UnsupportedAuthMode,
|
||||
|
||||
#[error("failed to read auth token for remote plugin mutation: {0}")]
|
||||
AuthToken(#[source] std::io::Error),
|
||||
|
||||
#[error("invalid chatgpt base url for remote plugin mutation: {0}")]
|
||||
InvalidBaseUrl(#[source] url::ParseError),
|
||||
|
||||
#[error("chatgpt base url cannot be used for plugin mutation")]
|
||||
InvalidBaseUrlPath,
|
||||
|
||||
#[error("failed to send remote plugin mutation request to {url}: {source}")]
|
||||
Request {
|
||||
url: String,
|
||||
#[source]
|
||||
source: RouteAwareRequestError,
|
||||
},
|
||||
|
||||
#[error("remote plugin mutation failed with status {status} from {url}: {body}")]
|
||||
UnexpectedStatus {
|
||||
url: String,
|
||||
status: StatusCode,
|
||||
body: String,
|
||||
},
|
||||
|
||||
#[error("failed to parse remote plugin mutation response from {url}: {source}")]
|
||||
Decode {
|
||||
url: String,
|
||||
#[source]
|
||||
source: serde_json::Error,
|
||||
},
|
||||
|
||||
#[error(
|
||||
"remote plugin mutation returned unexpected plugin id: expected `{expected}`, got `{actual}`"
|
||||
)]
|
||||
UnexpectedPluginId { expected: String, actual: String },
|
||||
|
||||
#[error(
|
||||
"remote plugin mutation returned unexpected enabled state for `{plugin_id}`: expected {expected_enabled}, got {actual_enabled}"
|
||||
)]
|
||||
UnexpectedEnabledState {
|
||||
plugin_id: String,
|
||||
expected_enabled: bool,
|
||||
actual_enabled: bool,
|
||||
},
|
||||
}
|
||||
|
||||
impl RemotePluginMutationError {
|
||||
pub(crate) fn sub_error_type(&self) -> Option<String> {
|
||||
match self {
|
||||
Self::UnexpectedStatus { status, .. } => {
|
||||
Some(http_status_sub_error_type(*status).to_string())
|
||||
}
|
||||
Self::Unavailable
|
||||
| Self::AuthRequired
|
||||
| Self::UnsupportedAuthMode
|
||||
| Self::AuthToken(_)
|
||||
| Self::InvalidBaseUrl(_)
|
||||
| Self::InvalidBaseUrlPath
|
||||
| Self::Request { .. }
|
||||
| Self::Decode { .. }
|
||||
| Self::UnexpectedPluginId { .. }
|
||||
| Self::UnexpectedEnabledState { .. } => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum RemotePluginFetchError {
|
||||
#[error("failed to authenticate remote featured plugin request: {0}")]
|
||||
AuthToken(#[source] std::io::Error),
|
||||
#[error("invalid chatgpt base url for remote featured plugin request: {0}")]
|
||||
InvalidBaseUrl(#[source] url::ParseError),
|
||||
|
||||
#[error("failed to send remote featured plugin request to {url}: {source}")]
|
||||
Request {
|
||||
url: String,
|
||||
#[source]
|
||||
source: RouteAwareRequestError,
|
||||
},
|
||||
|
||||
#[error("remote featured plugin request to {url} failed with status {status}: {body}")]
|
||||
UnexpectedStatus {
|
||||
url: String,
|
||||
status: StatusCode,
|
||||
body: String,
|
||||
},
|
||||
|
||||
#[error("failed to parse remote featured plugin response from {url}: {source}")]
|
||||
Decode {
|
||||
url: String,
|
||||
#[source]
|
||||
source: serde_json::Error,
|
||||
},
|
||||
}
|
||||
|
||||
pub async fn fetch_remote_featured_plugin_ids(
|
||||
config: &RemotePluginServiceConfig,
|
||||
auth: Option<&CodexAuth>,
|
||||
product: Option<Product>,
|
||||
) -> Result<Vec<String>, RemotePluginFetchError> {
|
||||
let _ = (config, auth, product);
|
||||
Ok(Vec::new())
|
||||
}
|
||||
|
||||
pub async fn enable_remote_plugin(
|
||||
config: &RemotePluginServiceConfig,
|
||||
auth: Option<&CodexAuth>,
|
||||
plugin_id: &str,
|
||||
) -> Result<(), RemotePluginMutationError> {
|
||||
post_remote_plugin_mutation(config, auth, plugin_id, "enable").await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn uninstall_remote_plugin(
|
||||
config: &RemotePluginServiceConfig,
|
||||
auth: Option<&CodexAuth>,
|
||||
plugin_id: &str,
|
||||
) -> Result<(), RemotePluginMutationError> {
|
||||
post_remote_plugin_mutation(config, auth, plugin_id, "uninstall").await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn post_remote_plugin_mutation(
|
||||
config: &RemotePluginServiceConfig,
|
||||
auth: Option<&CodexAuth>,
|
||||
plugin_id: &str,
|
||||
action: &str,
|
||||
) -> Result<RemotePluginMutationResponse, RemotePluginMutationError> {
|
||||
let _ = (config, auth, plugin_id, action);
|
||||
Err(RemotePluginMutationError::Unavailable)
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
//! Compares the metadata that determines installed-plugin behavior.
|
||||
//!
|
||||
//! Display metadata (including image URLs and store capability badges) is excluded. Callers must
|
||||
//! still publish the unmodified payload so display consumers receive fresh metadata.
|
||||
|
||||
use crate::remote::RemoteInstalledPlugin;
|
||||
use crate::remote::RemoteMarketplace;
|
||||
|
||||
pub(crate) fn installed_plugin_metadata_eq(
|
||||
previous: &[RemoteInstalledPlugin],
|
||||
current: &[RemoteInstalledPlugin],
|
||||
) -> bool {
|
||||
previous.len() == current.len()
|
||||
&& previous.iter().zip(current).all(|(previous, current)| {
|
||||
previous.marketplace_name == current.marketplace_name
|
||||
&& previous.id == current.id
|
||||
&& previous.name == current.name
|
||||
&& previous.canonical_app_id == current.canonical_app_id
|
||||
&& previous.version == current.version
|
||||
&& previous.installed_at == current.installed_at
|
||||
&& previous.enabled == current.enabled
|
||||
&& previous.install_policy == current.install_policy
|
||||
&& previous.install_policy_source == current.install_policy_source
|
||||
&& previous.must_show_installation_interstitial
|
||||
== current.must_show_installation_interstitial
|
||||
&& previous.auth_policy == current.auth_policy
|
||||
&& previous.availability == current.availability
|
||||
&& previous.disabled_reason == current.disabled_reason
|
||||
&& previous.eligible_plan_types == current.eligible_plan_types
|
||||
})
|
||||
}
|
||||
|
||||
/// Compare installed catalog identity, versions, enablement, policy and availability.
|
||||
///
|
||||
/// Plugin display order is ignored. Marketplace ordering remains significant.
|
||||
/// Callers must still store the unmodified current catalog for display consumers.
|
||||
pub fn remote_catalog_metadata_eq(
|
||||
previous: &[RemoteMarketplace],
|
||||
current: &[RemoteMarketplace],
|
||||
) -> bool {
|
||||
previous.len() == current.len()
|
||||
&& previous.iter().zip(current).all(|(previous, current)| {
|
||||
if previous.name != current.name || previous.plugins.len() != current.plugins.len() {
|
||||
return false;
|
||||
}
|
||||
// Core sorts this view by display name, which can change independently of behavior.
|
||||
let mut previous = previous.plugins.iter().collect::<Vec<_>>();
|
||||
let mut current = current.plugins.iter().collect::<Vec<_>>();
|
||||
previous.sort_unstable_by(|a, b| a.remote_plugin_id.cmp(&b.remote_plugin_id));
|
||||
current.sort_unstable_by(|a, b| a.remote_plugin_id.cmp(&b.remote_plugin_id));
|
||||
previous
|
||||
.into_iter()
|
||||
.zip(current)
|
||||
.all(|(previous, current)| {
|
||||
previous.id == current.id
|
||||
&& previous.remote_plugin_id == current.remote_plugin_id
|
||||
&& previous.name == current.name
|
||||
&& previous.version == current.version
|
||||
&& previous.local_version == current.local_version
|
||||
&& previous.installed == current.installed
|
||||
&& previous.installed_at == current.installed_at
|
||||
&& previous.enabled == current.enabled
|
||||
&& previous.install_policy == current.install_policy
|
||||
&& previous.install_policy_source == current.install_policy_source
|
||||
&& previous.must_show_installation_interstitial
|
||||
== current.must_show_installation_interstitial
|
||||
&& previous.auth_policy == current.auth_policy
|
||||
&& previous.availability == current.availability
|
||||
&& previous.disabled_reason == current.disabled_reason
|
||||
&& previous.eligible_plan_types == current.eligible_plan_types
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "remote_metadata_tests.rs"]
|
||||
mod tests;
|
||||
@@ -1,181 +0,0 @@
|
||||
//! Regression coverage for the fields that affect plugin behavior.
|
||||
|
||||
use super::*;
|
||||
use crate::remote::REMOTE_GLOBAL_MARKETPLACE_NAME;
|
||||
use crate::remote::group_remote_installed_plugins_by_marketplaces;
|
||||
use codex_app_server_protocol::PluginAuthPolicy;
|
||||
use codex_app_server_protocol::PluginAvailability;
|
||||
use codex_app_server_protocol::PluginInstallPolicy;
|
||||
use serde_json::json;
|
||||
|
||||
fn image_url(renewal: &str) -> String {
|
||||
format!("https://files.openai.com/plugins/icon.png?sig={renewal}")
|
||||
}
|
||||
|
||||
fn plugin(renewal: &str) -> RemoteInstalledPlugin {
|
||||
RemoteInstalledPlugin {
|
||||
marketplace_name: REMOTE_GLOBAL_MARKETPLACE_NAME.to_string(),
|
||||
id: "plugin-test".to_string(),
|
||||
version: Some("1.0.0".to_string()),
|
||||
name: "test".to_string(),
|
||||
canonical_app_id: None,
|
||||
installed_at: None,
|
||||
enabled: true,
|
||||
install_policy: PluginInstallPolicy::Available,
|
||||
install_policy_source: None,
|
||||
must_show_installation_interstitial: None,
|
||||
auth_policy: PluginAuthPolicy::OnUse,
|
||||
availability: PluginAvailability::Available,
|
||||
disabled_reason: None,
|
||||
eligible_plan_types: None,
|
||||
interface: Some(
|
||||
serde_json::from_value(json!({
|
||||
"capabilities": [], "screenshots": [],
|
||||
"logoUrl": image_url(renewal), "logoUrlDark": image_url(renewal),
|
||||
"composerIconUrl": image_url(renewal), "screenshotUrls": [image_url(renewal)]
|
||||
}))
|
||||
.unwrap(),
|
||||
),
|
||||
keywords: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
fn catalog(plugins: &[RemoteInstalledPlugin]) -> Vec<RemoteMarketplace> {
|
||||
group_remote_installed_plugins_by_marketplaces(plugins, &[REMOTE_GLOBAL_MARKETPLACE_NAME])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn behavioral_metadata_changes_still_invalidate() {
|
||||
let changes: &[fn(&mut RemoteInstalledPlugin)] = &[
|
||||
|plugin| plugin.id.push_str("-other"),
|
||||
|plugin| plugin.name.push_str("-other"),
|
||||
|plugin| plugin.version = Some("2.0.0".to_string()),
|
||||
|plugin| {
|
||||
plugin.installed_at =
|
||||
chrono::DateTime::from_timestamp(/*secs*/ 1, /*nsecs*/ 0)
|
||||
},
|
||||
|plugin| plugin.enabled = false,
|
||||
|plugin| plugin.install_policy = PluginInstallPolicy::NotAvailable,
|
||||
|plugin| {
|
||||
plugin.install_policy_source =
|
||||
Some(codex_app_server_protocol::PluginInstallPolicySource::WorkspaceSetting)
|
||||
},
|
||||
|plugin| plugin.must_show_installation_interstitial = Some(true),
|
||||
|plugin| plugin.auth_policy = PluginAuthPolicy::OnInstall,
|
||||
|plugin| plugin.availability = PluginAvailability::DisabledByAdmin,
|
||||
|plugin| plugin.eligible_plan_types = Some(vec!["enterprise".to_string()]),
|
||||
];
|
||||
for change in changes {
|
||||
let previous = [plugin("old")];
|
||||
let mut current = [plugin("new")];
|
||||
change(&mut current[0]);
|
||||
assert!(!installed_plugin_metadata_eq(&previous, ¤t));
|
||||
assert!(!remote_catalog_metadata_eq(
|
||||
&catalog(&previous),
|
||||
&catalog(¤t)
|
||||
));
|
||||
}
|
||||
let previous = [plugin("old")];
|
||||
let mut current = [plugin("new")];
|
||||
current[0].canonical_app_id = Some("new-app".to_string());
|
||||
assert!(!installed_plugin_metadata_eq(&previous, ¤t));
|
||||
assert!(!installed_plugin_metadata_eq(&previous, &[]));
|
||||
assert!(!remote_catalog_metadata_eq(&catalog(&previous), &[]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn display_metadata_does_not_invalidate() {
|
||||
let previous = [plugin("old")];
|
||||
let mut current = [plugin("new")];
|
||||
current[0].keywords.push("new keyword".to_string());
|
||||
let interface = current[0].interface.as_mut().unwrap();
|
||||
interface.logo_url = Some("https://another-host.test/different-image.svg".to_string());
|
||||
interface.display_name = Some("New display name".to_string());
|
||||
interface.short_description = Some("New description".to_string());
|
||||
interface.brand_color = Some("#123456".to_string());
|
||||
interface.default_prompt = Some(vec!["New starter prompt".to_string()]);
|
||||
interface.website_url = Some("https://another-host.test".to_string());
|
||||
assert_ne!(previous, current);
|
||||
assert!(installed_plugin_metadata_eq(&previous, ¤t));
|
||||
let mut current_catalog = catalog(¤t);
|
||||
current_catalog[0].display_name = "New marketplace title".to_string();
|
||||
assert!(remote_catalog_metadata_eq(
|
||||
&catalog(&previous),
|
||||
¤t_catalog
|
||||
));
|
||||
|
||||
current[0].interface = None;
|
||||
assert!(installed_plugin_metadata_eq(&previous, ¤t));
|
||||
assert!(remote_catalog_metadata_eq(
|
||||
&catalog(&previous),
|
||||
&catalog(¤t)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installed_ordering_remains_significant() {
|
||||
let mut other = plugin("old");
|
||||
other.id.push_str("-other");
|
||||
other.name.push_str("-other");
|
||||
let previous = [plugin("old"), other];
|
||||
let mut current = previous.clone();
|
||||
current.reverse();
|
||||
assert!(!installed_plugin_metadata_eq(&previous, ¤t));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn store_badge_changes_do_not_invalidate() {
|
||||
let mut previous = [plugin("old")];
|
||||
previous[0].interface.as_mut().unwrap().capabilities =
|
||||
vec!["tools".to_string(), "skills".to_string()];
|
||||
for badges in [vec!["skills", "tools"], vec!["updated badge"], vec![]] {
|
||||
let mut current = previous.clone();
|
||||
current[0].interface.as_mut().unwrap().capabilities =
|
||||
badges.into_iter().map(str::to_string).collect();
|
||||
assert_ne!(previous, current);
|
||||
assert!(installed_plugin_metadata_eq(&previous, ¤t));
|
||||
assert!(remote_catalog_metadata_eq(
|
||||
&catalog(&previous),
|
||||
&catalog(¤t)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catalog_display_reordering_does_not_invalidate() {
|
||||
let mut first = plugin("old");
|
||||
first.interface.as_mut().unwrap().display_name = Some("Alpha".to_string());
|
||||
let mut second = plugin("old");
|
||||
second.id.push_str("-second");
|
||||
second.name.push_str("-second");
|
||||
second.interface.as_mut().unwrap().display_name = Some("Beta".to_string());
|
||||
let previous = [first, second];
|
||||
let mut current = previous.clone();
|
||||
current[0].interface.as_mut().unwrap().display_name = Some("Zulu".to_string());
|
||||
let previous_catalog = catalog(&previous);
|
||||
let current_catalog = catalog(¤t);
|
||||
assert_ne!(
|
||||
previous_catalog[0].plugins[0].id,
|
||||
current_catalog[0].plugins[0].id
|
||||
);
|
||||
assert!(installed_plugin_metadata_eq(&previous, ¤t));
|
||||
assert!(remote_catalog_metadata_eq(
|
||||
&previous_catalog,
|
||||
¤t_catalog
|
||||
));
|
||||
|
||||
current[0].version = Some("2.0.0".to_string());
|
||||
assert!(!remote_catalog_metadata_eq(
|
||||
&previous_catalog,
|
||||
&catalog(¤t)
|
||||
));
|
||||
assert!(!remote_catalog_metadata_eq(
|
||||
&previous_catalog,
|
||||
&catalog(¤t[1..])
|
||||
));
|
||||
current[0] = current[1].clone();
|
||||
assert!(!remote_catalog_metadata_eq(
|
||||
&previous_catalog,
|
||||
&catalog(¤t)
|
||||
));
|
||||
}
|
||||
@@ -1,188 +0,0 @@
|
||||
//! Shared remote plugin mutations for the CLI and app-server.
|
||||
//! The sync gate covers cache/backend changes and refresh scheduling. An install outcome keeps
|
||||
//! its bundle protected from pruning until the caller finishes downstream setup and drops it.
|
||||
|
||||
use super::EffectivePluginsChangedCallback;
|
||||
use super::PluginInstallOutcome;
|
||||
use super::PluginsConfigInput;
|
||||
use super::PluginsManager;
|
||||
use crate::remote;
|
||||
use crate::remote::RemoteInstalledPluginBundleSyncError;
|
||||
use crate::remote::RemotePluginCacheMutationGuard;
|
||||
use crate::remote::RemotePluginCatalogError;
|
||||
use crate::remote::RemotePluginDetail;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_plugin::PluginId;
|
||||
use codex_plugin::PluginTelemetryMetadata;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub struct RemotePluginInstallRequest {
|
||||
pub marketplace_name: String,
|
||||
pub remote_plugin_id: String,
|
||||
pub install_attempt_id: Option<String>,
|
||||
}
|
||||
|
||||
/// Keep this outcome alive throughout post-install setup to protect the installed bundle.
|
||||
#[must_use]
|
||||
pub struct RemotePluginInstallOutcome {
|
||||
pub installed: PluginInstallOutcome,
|
||||
pub detail: RemotePluginDetail,
|
||||
pub app_ids_needing_auth: Option<Vec<String>>,
|
||||
_cache_mutation: RemotePluginCacheMutationGuard,
|
||||
}
|
||||
|
||||
pub struct RemotePluginUninstallOutcome {
|
||||
pub telemetry: PluginTelemetryMetadata,
|
||||
pub effective_plugins_changed: bool,
|
||||
/// The backend uninstall succeeded even when removing the local cache failed.
|
||||
pub cache_removal_error: Option<RemotePluginCatalogError>,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("{kind}")]
|
||||
pub struct RemotePluginOperationError {
|
||||
pub plugin_id: Option<PluginId>,
|
||||
#[source]
|
||||
pub kind: Box<RemotePluginOperationErrorKind>,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum RemotePluginOperationErrorKind {
|
||||
#[error("{context}: {source}")]
|
||||
Catalog {
|
||||
context: &'static str,
|
||||
source: RemotePluginCatalogError,
|
||||
},
|
||||
#[error("{context}: {source}")]
|
||||
Sync {
|
||||
context: &'static str,
|
||||
source: RemoteInstalledPluginBundleSyncError,
|
||||
},
|
||||
#[error("remote plugin {0} is disabled by admin")]
|
||||
DisabledByAdmin(String),
|
||||
#[error("remote plugin {0} is not available for install")]
|
||||
NotAvailable(String),
|
||||
#[error("{0}")]
|
||||
InvalidRequest(String),
|
||||
#[error("{0}")]
|
||||
Internal(String),
|
||||
}
|
||||
|
||||
impl PluginsManager {
|
||||
/// Resolve, validate, materialize, and install a remote plugin as one coordinated mutation.
|
||||
pub async fn install_remote_plugin(
|
||||
self: &Arc<Self>,
|
||||
config: &PluginsConfigInput,
|
||||
auth: Option<&CodexAuth>,
|
||||
request: RemotePluginInstallRequest,
|
||||
on_effective_plugins_changed: Option<EffectivePluginsChangedCallback>,
|
||||
) -> Result<RemotePluginInstallOutcome, RemotePluginOperationError> {
|
||||
use RemotePluginOperationErrorKind as Error;
|
||||
let unresolved = |kind| RemotePluginOperationError {
|
||||
plugin_id: None,
|
||||
kind: Box::new(kind),
|
||||
};
|
||||
let RemotePluginInstallRequest {
|
||||
marketplace_name,
|
||||
remote_plugin_id,
|
||||
install_attempt_id,
|
||||
} = request;
|
||||
if !config.plugins_enabled {
|
||||
return Err(unresolved(Error::InvalidRequest(format!(
|
||||
"remote plugin install is not enabled for marketplace {marketplace_name}"
|
||||
))));
|
||||
}
|
||||
remote::validate_remote_plugin_id(&remote_plugin_id)
|
||||
.map_err(|err| unresolved(Error::InvalidRequest(err.message)))?;
|
||||
// aKode never downloads plugin bundles from backend-provided URLs.
|
||||
let _ = (auth, install_attempt_id, on_effective_plugins_changed);
|
||||
Err(unresolved(Error::Catalog {
|
||||
context: "install remote plugin",
|
||||
source: RemotePluginCatalogError::Unavailable,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Remove the backend installation and local cache, then schedule an installed-state refresh.
|
||||
pub async fn uninstall_remote_plugin(
|
||||
self: &Arc<Self>,
|
||||
config: &PluginsConfigInput,
|
||||
auth: Option<&CodexAuth>,
|
||||
remote_plugin_id: &str,
|
||||
on_effective_plugins_changed: Option<EffectivePluginsChangedCallback>,
|
||||
) -> Result<RemotePluginUninstallOutcome, RemotePluginOperationError> {
|
||||
use RemotePluginOperationErrorKind as Error;
|
||||
let unresolved = |kind| RemotePluginOperationError {
|
||||
plugin_id: None,
|
||||
kind: Box::new(kind),
|
||||
};
|
||||
if !config.plugins_enabled {
|
||||
return Err(unresolved(Error::InvalidRequest(
|
||||
"remote plugin uninstall is not enabled".to_string(),
|
||||
)));
|
||||
}
|
||||
remote::validate_remote_plugin_id(remote_plugin_id)
|
||||
.map_err(|err| unresolved(Error::InvalidRequest(err.message)))?;
|
||||
let service = self.remote_plugin_service_config(config);
|
||||
let target =
|
||||
remote::resolve_remote_plugin_uninstall_target(&service, auth, remote_plugin_id)
|
||||
.await
|
||||
.map_err(|source| {
|
||||
unresolved(Error::Catalog {
|
||||
context: "resolve remote plugin before uninstall",
|
||||
source,
|
||||
})
|
||||
})?;
|
||||
let mut telemetry = self
|
||||
.telemetry_metadata_for_installed_plugin_with_remote_id(
|
||||
&target.plugin_id,
|
||||
remote_plugin_id,
|
||||
)
|
||||
.await;
|
||||
if telemetry.capability_summary.is_none() {
|
||||
telemetry.capability_summary = Some(target.fallback_capability_summary.clone());
|
||||
}
|
||||
let plugin_id = target.plugin_id.clone();
|
||||
let resolved = |kind| RemotePluginOperationError {
|
||||
plugin_id: Some(plugin_id.clone()),
|
||||
kind: Box::new(kind),
|
||||
};
|
||||
let _sync_guard = self
|
||||
.acquire_remote_installed_plugin_sync_guard()
|
||||
.await
|
||||
.map_err(|source| {
|
||||
resolved(Error::Sync {
|
||||
context: "failed to coordinate remote plugin uninstall",
|
||||
source,
|
||||
})
|
||||
})?;
|
||||
let _cache_mutation = remote::mark_remote_plugin_cache_mutation_in_flight(
|
||||
&self.codex_home,
|
||||
&plugin_id.marketplace_name,
|
||||
&plugin_id.plugin_name,
|
||||
);
|
||||
let cache_removal_error =
|
||||
match remote::uninstall_remote_plugin(&service, auth, self.codex_home.clone(), target)
|
||||
.await
|
||||
{
|
||||
Ok(()) => None,
|
||||
Err(err @ RemotePluginCatalogError::CacheRemove(_)) => Some(err),
|
||||
Err(source) => {
|
||||
return Err(resolved(Error::Catalog {
|
||||
context: "uninstall remote plugin",
|
||||
source,
|
||||
}));
|
||||
}
|
||||
};
|
||||
let effective_plugins_changed = self.clear_remote_installed_plugins_cache();
|
||||
self.maybe_start_remote_installed_plugins_cache_refresh_after_mutation(
|
||||
config,
|
||||
auth.cloned(),
|
||||
on_effective_plugins_changed,
|
||||
);
|
||||
Ok(RemotePluginUninstallOutcome {
|
||||
telemetry,
|
||||
effective_plugins_changed,
|
||||
cache_removal_error,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
use crate::remote::RemoteInstalledPlugin;
|
||||
use crate::remote::RemotePluginScope;
|
||||
use crate::store::ActivePluginInstallation;
|
||||
use codex_config::types::PluginConfig;
|
||||
use codex_plugin::PluginId;
|
||||
use std::collections::HashMap;
|
||||
use tracing::warn;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct RemoteInstalledPluginsSnapshot {
|
||||
pub(crate) configs: HashMap<String, PluginConfig>,
|
||||
pub(crate) remote_plugin_id_resolver: RemotePluginIdResolver,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct RemotePluginIdResolver {
|
||||
snapshot_ids: Option<HashMap<PluginId, String>>,
|
||||
}
|
||||
|
||||
impl RemotePluginIdResolver {
|
||||
pub(crate) fn new(plugins: &[RemoteInstalledPlugin]) -> Self {
|
||||
let mut snapshot_ids = HashMap::with_capacity(plugins.len());
|
||||
for plugin in plugins {
|
||||
let Ok(plugin_id) = PluginId::new(plugin.name.clone(), plugin.marketplace_name.clone())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
snapshot_ids
|
||||
.entry(plugin_id)
|
||||
.or_insert_with(|| plugin.id.clone());
|
||||
}
|
||||
Self {
|
||||
snapshot_ids: Some(snapshot_ids),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn remote_plugin_id_for_installation(
|
||||
&self,
|
||||
installation: &ActivePluginInstallation,
|
||||
) -> Option<String> {
|
||||
if let Some(snapshot_ids) = &self.snapshot_ids {
|
||||
return snapshot_ids.get(&installation.plugin_id).cloned();
|
||||
}
|
||||
|
||||
persisted_remote_plugin_id_for_installation(installation)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn persisted_remote_plugin_id_for_installation(
|
||||
installation: &ActivePluginInstallation,
|
||||
) -> Option<String> {
|
||||
RemotePluginScope::from_marketplace_name(&installation.plugin_id.marketplace_name)?;
|
||||
|
||||
match installation.persisted_remote_plugin_id() {
|
||||
Ok(remote_plugin_id) => remote_plugin_id,
|
||||
Err(err) => {
|
||||
warn!(
|
||||
plugin_id = %installation.plugin_id.as_key(),
|
||||
error = %err,
|
||||
"failed to read persisted remote plugin identity"
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,11 +6,9 @@ use crate::loader::curated_plugin_cache_version;
|
||||
use crate::marketplace::MarketplacePluginSource;
|
||||
use crate::marketplace::find_marketplace_plugin;
|
||||
use crate::marketplace_policy::primary_runtime_marketplace_root;
|
||||
use crate::remote::REMOTE_GLOBAL_MARKETPLACE_NAME;
|
||||
use crate::startup_sync::curated_plugins_api_marketplace_path;
|
||||
use crate::startup_sync::curated_plugins_repo_path;
|
||||
use crate::startup_sync::read_curated_plugins_sha;
|
||||
use crate::store::DEFAULT_PLUGIN_VERSION;
|
||||
use crate::store::PluginStore;
|
||||
use crate::store::plugin_version_for_source;
|
||||
use codex_exec_server::ExecutorFileSystem;
|
||||
@@ -52,8 +50,7 @@ impl PluginCommandAttribution {
|
||||
}
|
||||
|
||||
/// Active first-party roots eligible for command attribution.
|
||||
/// Trusted means OpenAI-shipped synced or bundled runtime code, or a
|
||||
/// server-installed global remote plugin cache entry, not a local override.
|
||||
/// Trusted means OpenAI-shipped synced or bundled runtime code, not a local override.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct TrustedPluginRoots {
|
||||
roots: Vec<TrustedPluginRoot>,
|
||||
@@ -118,15 +115,6 @@ impl TrustedPluginRoots {
|
||||
primary_runtime_marketplace_root: Option<&Path>,
|
||||
) -> Option<AbsolutePathBuf> {
|
||||
match plugin_id.marketplace_name.as_str() {
|
||||
REMOTE_GLOBAL_MARKETPLACE_NAME => {
|
||||
let active_version = store.active_plugin_version(plugin_id)?;
|
||||
if active_version == DEFAULT_PLUGIN_VERSION
|
||||
|| store.remote_plugin_id(plugin_id).ok().flatten().is_none()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(store.plugin_root(plugin_id, &active_version))
|
||||
}
|
||||
OPENAI_CURATED_MARKETPLACE_NAME | OPENAI_API_CURATED_MARKETPLACE_NAME => {
|
||||
let curated_sha = read_curated_plugins_sha(codex_home)?;
|
||||
let expected_root =
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
use super::*;
|
||||
use crate::LoadedPlugin;
|
||||
use crate::loader::curated_plugin_cache_version;
|
||||
use crate::remote::REMOTE_GLOBAL_MARKETPLACE_NAME;
|
||||
use crate::startup_sync::curated_plugins_repo_path;
|
||||
use crate::store::DEFAULT_PLUGIN_VERSION;
|
||||
use crate::store::PluginStore;
|
||||
@@ -28,13 +27,15 @@ use std::sync::Arc;
|
||||
use tempfile::TempDir;
|
||||
const ENABLED: bool = true;
|
||||
const DISABLED: bool = false;
|
||||
/// Marketplace name formerly used by the removed remote plugin catalog.
|
||||
const LEGACY_REMOTE_MARKETPLACE_NAME: &str = "openai-curated-remote";
|
||||
|
||||
fn path(path: &Path) -> AbsolutePathBuf {
|
||||
AbsolutePathBuf::from_absolute_path_checked(path).expect("absolute path")
|
||||
}
|
||||
fn loaded_plugin(config_name: &str, root: &Path, enabled: bool) -> LoadedPlugin {
|
||||
LoadedPlugin {
|
||||
config_name: config_name.to_string(),
|
||||
remote_plugin_id: None,
|
||||
manifest_name: None,
|
||||
plugin_namespace: None,
|
||||
manifest_description: None,
|
||||
@@ -45,7 +46,6 @@ fn loaded_plugin(config_name: &str, root: &Path, enabled: bool) -> LoadedPlugin
|
||||
disabled_skill_paths: HashSet::new(),
|
||||
has_enabled_skills: false,
|
||||
mcp_servers: HashMap::new(),
|
||||
apps: Vec::new(),
|
||||
hook_sources: Vec::new(),
|
||||
hook_load_warnings: Vec::new(),
|
||||
error: None,
|
||||
@@ -71,26 +71,15 @@ fn synced_plugin_root(codex_home: &Path, marketplace: &str, plugin_name: &str) -
|
||||
fs::create_dir_all(root.as_path()).expect("create cached plugin root");
|
||||
root
|
||||
}
|
||||
fn cached_remote_plugin_root(codex_home: &Path, plugin_name: &str) -> AbsolutePathBuf {
|
||||
/// Cache entry under the legacy remote marketplace name, which no longer carries any trust.
|
||||
fn cached_legacy_remote_plugin_root(codex_home: &Path, plugin_name: &str) -> AbsolutePathBuf {
|
||||
let plugin_id = PluginId::new(
|
||||
plugin_name.to_string(),
|
||||
REMOTE_GLOBAL_MARKETPLACE_NAME.to_string(),
|
||||
LEGACY_REMOTE_MARKETPLACE_NAME.to_string(),
|
||||
)
|
||||
.expect("plugin id");
|
||||
let root = PluginStore::new(codex_home.to_path_buf()).plugin_root(&plugin_id, "1.2.3");
|
||||
fs::create_dir_all(root.as_path()).expect("create cached remote plugin root");
|
||||
root
|
||||
}
|
||||
fn installed_remote_plugin_root(codex_home: &Path, plugin_name: &str) -> AbsolutePathBuf {
|
||||
let root = cached_remote_plugin_root(codex_home, plugin_name);
|
||||
let plugin_id = PluginId::new(
|
||||
plugin_name.to_string(),
|
||||
REMOTE_GLOBAL_MARKETPLACE_NAME.to_string(),
|
||||
)
|
||||
.expect("plugin id");
|
||||
PluginStore::new(codex_home.to_path_buf())
|
||||
.write_remote_plugin_id(&plugin_id, "plugins~Plugin_sample")
|
||||
.expect("write remote plugin id");
|
||||
fs::create_dir_all(root.as_path()).expect("create cached legacy remote plugin root");
|
||||
root
|
||||
}
|
||||
fn script_fixture() -> (TempDir, AbsolutePathBuf, AbsolutePathBuf) {
|
||||
@@ -275,7 +264,7 @@ fn command(parts: &[&str]) -> Vec<String> {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trusted_roots_require_verified_curated_or_remote_cache() {
|
||||
fn trusted_roots_require_verified_curated_cache() {
|
||||
let temp = TempDir::new().expect("temp dir");
|
||||
write_curated_plugin_sha_with(temp.path(), TEST_CURATED_PLUGIN_SHA);
|
||||
let root = synced_plugin_root(temp.path(), OPENAI_CURATED_MARKETPLACE_NAME, "sample");
|
||||
@@ -284,20 +273,22 @@ fn trusted_roots_require_verified_curated_or_remote_cache() {
|
||||
OPENAI_API_CURATED_MARKETPLACE_NAME,
|
||||
"api-sample",
|
||||
);
|
||||
let remote_root = installed_remote_plugin_root(temp.path(), "remote-sample");
|
||||
let unverified_remote_root = cached_remote_plugin_root(temp.path(), "unverified-remote");
|
||||
let _ = installed_remote_plugin_root(temp.path(), "overridden-remote");
|
||||
let overridden_remote_plugin_id =
|
||||
PluginId::parse("overridden-remote@openai-curated-remote").expect("plugin id");
|
||||
let remote_root = cached_legacy_remote_plugin_root(temp.path(), "remote-sample");
|
||||
let _ = cached_legacy_remote_plugin_root(temp.path(), "overridden-remote");
|
||||
let overridden_plugin_id = PluginId::new(
|
||||
"overridden-remote".to_string(),
|
||||
LEGACY_REMOTE_MARKETPLACE_NAME.to_string(),
|
||||
)
|
||||
.expect("plugin id");
|
||||
let remote_local_override = PluginStore::new(temp.path().to_path_buf())
|
||||
.plugin_root(&overridden_remote_plugin_id, DEFAULT_PLUGIN_VERSION);
|
||||
.plugin_root(&overridden_plugin_id, DEFAULT_PLUGIN_VERSION);
|
||||
let local_root = temp
|
||||
.path()
|
||||
.join("plugins/cache/openai-curated/sample/local");
|
||||
let spoofed_root = temp.path().join("spoofed/openai-curated/sample");
|
||||
let spoofed_remote_root = temp
|
||||
.path()
|
||||
.join("spoofed/openai-curated-remote/remote-sample");
|
||||
let spoofed_remote_root = temp.path().join(format!(
|
||||
"spoofed/{LEGACY_REMOTE_MARKETPLACE_NAME}/remote-sample"
|
||||
));
|
||||
fs::create_dir_all(&local_root).expect("create local root");
|
||||
fs::create_dir_all(&spoofed_root).expect("create spoofed root");
|
||||
fs::create_dir_all(&spoofed_remote_root).expect("create spoofed remote root");
|
||||
@@ -307,11 +298,6 @@ fn trusted_roots_require_verified_curated_or_remote_cache() {
|
||||
vec![
|
||||
loaded_plugin("sample@openai-curated", root.as_path(), ENABLED),
|
||||
loaded_plugin("api-sample@openai-api-curated", api_root.as_path(), ENABLED),
|
||||
loaded_plugin(
|
||||
"remote-sample@openai-curated-remote",
|
||||
remote_root.as_path(),
|
||||
ENABLED,
|
||||
),
|
||||
loaded_plugin("sample@openai-curated", &local_root, ENABLED),
|
||||
loaded_plugin("sample@openai-curated", &spoofed_root, ENABLED),
|
||||
loaded_plugin("disabled@openai-curated", root.as_path(), DISABLED),
|
||||
@@ -330,27 +316,15 @@ fn trusted_roots_require_verified_curated_or_remote_cache() {
|
||||
version: curated_plugin_cache_version(TEST_CURATED_PLUGIN_SHA),
|
||||
root: api_root.canonicalize().expect("canonical root"),
|
||||
},
|
||||
TrustedPluginRoot {
|
||||
plugin_id: PluginId::parse("remote-sample@openai-curated-remote")
|
||||
.expect("plugin id"),
|
||||
version: "1.2.3".to_string(),
|
||||
root: remote_root.canonicalize().expect("canonical root"),
|
||||
},
|
||||
]
|
||||
);
|
||||
// Cache entries under the legacy remote marketplace name are never trusted, wherever they live.
|
||||
let remote_sample = format!("remote-sample@{LEGACY_REMOTE_MARKETPLACE_NAME}");
|
||||
assert_untrusted(temp.path(), &remote_sample, remote_root.as_path());
|
||||
assert_untrusted(temp.path(), &remote_sample, &spoofed_remote_root);
|
||||
assert_untrusted(
|
||||
temp.path(),
|
||||
"unverified-remote@openai-curated-remote",
|
||||
unverified_remote_root.as_path(),
|
||||
);
|
||||
assert_untrusted(
|
||||
temp.path(),
|
||||
"remote-sample@openai-curated-remote",
|
||||
&spoofed_remote_root,
|
||||
);
|
||||
assert_untrusted(
|
||||
temp.path(),
|
||||
"overridden-remote@openai-curated-remote",
|
||||
&format!("overridden-remote@{LEGACY_REMOTE_MARKETPLACE_NAME}"),
|
||||
remote_local_override.as_path(),
|
||||
);
|
||||
#[cfg(unix)]
|
||||
@@ -529,8 +503,10 @@ fn reference_fixture(bundles: &[(&str, &str, &str)]) -> (TempDir, TrustedPluginR
|
||||
let root =
|
||||
reference_identity_fixture(&home.path().join(name).join(version), contents);
|
||||
TrustedPluginRoot {
|
||||
plugin_id: PluginId::parse(&format!("{name}@openai-curated-remote"))
|
||||
.expect("plugin id"),
|
||||
plugin_id: PluginId::parse(&format!(
|
||||
"{name}@{OPENAI_CURATED_MARKETPLACE_NAME}"
|
||||
))
|
||||
.expect("plugin id"),
|
||||
version: version.to_string(),
|
||||
root,
|
||||
}
|
||||
@@ -543,7 +519,7 @@ fn reference_fixture(bundles: &[(&str, &str, &str)]) -> (TempDir, TrustedPluginR
|
||||
fn executor_plugin(home: &Path, name: &str, version: &str, contents: &str) -> AbsolutePathBuf {
|
||||
reference_identity_fixture(
|
||||
&home.join(format!(
|
||||
"plugins/cache/openai-curated-remote/{name}/{version}"
|
||||
"plugins/cache/{OPENAI_CURATED_MARKETPLACE_NAME}/{name}/{version}"
|
||||
)),
|
||||
contents,
|
||||
)
|
||||
@@ -595,8 +571,8 @@ async fn same_helper_path_in_two_plugins_resolves_by_executor_identity() {
|
||||
for name in ["sites", "other"] {
|
||||
let root = executor_plugin(executor.path(), name, "2.0.0", contents);
|
||||
let cwd = PathUri::from_host_native_path(root.as_path()).expect("executor URI");
|
||||
let plugin_id =
|
||||
PluginId::parse(&format!("{name}@openai-curated-remote")).expect("plugin id");
|
||||
let plugin_id = PluginId::parse(&format!("{name}@{OPENAI_CURATED_MARKETPLACE_NAME}"))
|
||||
.expect("plugin id");
|
||||
assert_executor_resolution(
|
||||
&roots,
|
||||
&command(&["sh", REFERENCE_HELPER]),
|
||||
@@ -613,14 +589,15 @@ async fn executor_aliases_use_canonical_plugin_paths() {
|
||||
let contents = "printf shared\\n\n";
|
||||
let (_reference, roots) =
|
||||
reference_fixture(&[("sites", "1.2.3", contents), ("sites", "2.0.0", contents)]);
|
||||
let plugin_id = PluginId::parse("sites@openai-curated-remote").expect("plugin id");
|
||||
let plugin_id =
|
||||
PluginId::parse(&format!("sites@{OPENAI_CURATED_MARKETPLACE_NAME}")).expect("plugin id");
|
||||
let executor = TempDir::new().expect("executor");
|
||||
let target = executor_plugin(executor.path(), "sites", "2.0.0", contents);
|
||||
let alias = executor.path().join("plugin-link");
|
||||
std::os::unix::fs::symlink(target.as_path(), &alias).expect("directory alias");
|
||||
let version_alias = executor
|
||||
.path()
|
||||
.join("plugins/cache/openai-curated-remote/sites/1.2.3/scripts/renamed-entry.sh");
|
||||
let version_alias = executor.path().join(format!(
|
||||
"plugins/cache/{OPENAI_CURATED_MARKETPLACE_NAME}/sites/1.2.3/scripts/renamed-entry.sh"
|
||||
));
|
||||
fs::create_dir_all(version_alias.parent().expect("alias parent")).expect("V1 alias directory");
|
||||
std::os::unix::fs::symlink(target.join(REFERENCE_HELPER), &version_alias).expect("V1 alias");
|
||||
let cwd = PathUri::from_host_native_path(executor.path()).expect("executor URI");
|
||||
|
||||
@@ -17,7 +17,6 @@ use sha2::Sha256;
|
||||
use std::cmp::Ordering;
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
@@ -26,12 +25,8 @@ pub use codex_core_plugin_common::installed::DEFAULT_PLUGIN_VERSION;
|
||||
pub use codex_core_plugin_common::installed::PLUGINS_CACHE_DIR;
|
||||
pub const PLUGINS_DATA_DIR: &str = "plugins/data";
|
||||
const AGENT_PLUGINS_DATA_DIR: &str = "agent-plugins";
|
||||
use codex_core_plugin_common::installed::REMOTE_PLUGIN_INSTALL_METADATA_FILE;
|
||||
use codex_core_plugin_common::installed::REMOTE_PLUGIN_INSTALL_METADATA_SCHEMA_VERSION;
|
||||
const DEFAULT_AGENT_PLUGIN_VERSION: &str = "1.0.0";
|
||||
|
||||
use codex_core_plugin_common::installed::RemotePluginInstallMetadata;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct PluginInstallResult {
|
||||
pub plugin_id: PluginId,
|
||||
@@ -47,31 +42,6 @@ pub struct PluginStore {
|
||||
data_root: AbsolutePathBuf,
|
||||
}
|
||||
|
||||
pub(crate) struct ActivePluginInstallation {
|
||||
pub(crate) plugin_id: PluginId,
|
||||
pub(crate) root: AbsolutePathBuf,
|
||||
remote_plugin_install_metadata_path: AbsolutePathBuf,
|
||||
}
|
||||
|
||||
impl ActivePluginInstallation {
|
||||
pub(crate) fn persisted_remote_plugin_id(&self) -> Result<Option<String>, PluginStoreError> {
|
||||
let contents = match fs::read_to_string(self.remote_plugin_install_metadata_path.as_path())
|
||||
{
|
||||
Ok(contents) => contents,
|
||||
Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(None),
|
||||
Err(err) => {
|
||||
return Err(PluginStoreError::io(
|
||||
"failed to read remote plugin install metadata",
|
||||
err,
|
||||
));
|
||||
}
|
||||
};
|
||||
codex_core_plugin_common::installed::parse_remote_plugin_id(&contents)
|
||||
.map(Some)
|
||||
.map_err(PluginStoreError::Invalid)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum InstallManifest<'a> {
|
||||
OnDisk,
|
||||
@@ -158,88 +128,10 @@ impl PluginStore {
|
||||
.map(|plugin_version| self.plugin_root(plugin_id, &plugin_version))
|
||||
}
|
||||
|
||||
pub(crate) fn active_plugin_installation(
|
||||
&self,
|
||||
plugin_id: &PluginId,
|
||||
) -> Option<ActivePluginInstallation> {
|
||||
Some(ActivePluginInstallation {
|
||||
plugin_id: plugin_id.clone(),
|
||||
root: self.active_plugin_root(plugin_id)?,
|
||||
remote_plugin_install_metadata_path: self
|
||||
.remote_plugin_install_metadata_path(plugin_id),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn is_installed(&self, plugin_id: &PluginId) -> bool {
|
||||
self.active_plugin_version(plugin_id).is_some()
|
||||
}
|
||||
|
||||
pub fn remote_plugin_id(
|
||||
&self,
|
||||
plugin_id: &PluginId,
|
||||
) -> Result<Option<String>, PluginStoreError> {
|
||||
let Some(installation) = self.active_plugin_installation(plugin_id) else {
|
||||
return Ok(None);
|
||||
};
|
||||
installation.persisted_remote_plugin_id()
|
||||
}
|
||||
|
||||
pub fn write_remote_plugin_id(
|
||||
&self,
|
||||
plugin_id: &PluginId,
|
||||
remote_plugin_id: &str,
|
||||
) -> Result<(), PluginStoreError> {
|
||||
if !self.is_installed(plugin_id) {
|
||||
return Err(PluginStoreError::Invalid(format!(
|
||||
"cannot write remote identity for uninstalled plugin `{}`",
|
||||
plugin_id.as_key()
|
||||
)));
|
||||
}
|
||||
let remote_plugin_id = remote_plugin_id.trim();
|
||||
if remote_plugin_id.is_empty() {
|
||||
return Err(PluginStoreError::Invalid(
|
||||
"invalid remote plugin install metadata: remote plugin id must not be blank"
|
||||
.to_string(),
|
||||
));
|
||||
}
|
||||
let path = self.remote_plugin_install_metadata_path(plugin_id);
|
||||
let parent = path.as_path().parent().ok_or_else(|| {
|
||||
PluginStoreError::Invalid(format!(
|
||||
"remote plugin install metadata path has no parent: {}",
|
||||
path.display()
|
||||
))
|
||||
})?;
|
||||
let mut contents = serde_json::to_vec_pretty(&RemotePluginInstallMetadata {
|
||||
schema_version: REMOTE_PLUGIN_INSTALL_METADATA_SCHEMA_VERSION,
|
||||
remote_plugin_id: remote_plugin_id.to_string(),
|
||||
})
|
||||
.map_err(|err| {
|
||||
PluginStoreError::Invalid(format!(
|
||||
"failed to serialize remote plugin install metadata: {err}"
|
||||
))
|
||||
})?;
|
||||
contents.push(b'\n');
|
||||
let mut temporary = tempfile::NamedTempFile::new_in(parent).map_err(|err| {
|
||||
PluginStoreError::io(
|
||||
"failed to create temporary remote plugin install metadata",
|
||||
err,
|
||||
)
|
||||
})?;
|
||||
temporary.write_all(&contents).map_err(|err| {
|
||||
PluginStoreError::io("failed to write remote plugin install metadata", err)
|
||||
})?;
|
||||
temporary.as_file_mut().flush().map_err(|err| {
|
||||
PluginStoreError::io("failed to flush remote plugin install metadata", err)
|
||||
})?;
|
||||
temporary.persist(path.as_path()).map_err(|err| {
|
||||
PluginStoreError::io(
|
||||
"failed to persist remote plugin install metadata",
|
||||
err.error,
|
||||
)
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn install(
|
||||
&self,
|
||||
source_path: AbsolutePathBuf,
|
||||
@@ -331,7 +223,6 @@ impl PluginStore {
|
||||
&plugin_version,
|
||||
manifest,
|
||||
)?;
|
||||
self.remove_remote_plugin_install_metadata(&plugin_id)?;
|
||||
|
||||
Ok(PluginInstallResult {
|
||||
plugin_id,
|
||||
@@ -343,26 +234,6 @@ impl PluginStore {
|
||||
pub fn uninstall(&self, plugin_id: &PluginId) -> Result<(), PluginStoreError> {
|
||||
remove_existing_target(self.plugin_base_root(plugin_id).as_path())
|
||||
}
|
||||
|
||||
fn remote_plugin_install_metadata_path(&self, plugin_id: &PluginId) -> AbsolutePathBuf {
|
||||
self.plugin_base_root(plugin_id)
|
||||
.join(REMOTE_PLUGIN_INSTALL_METADATA_FILE)
|
||||
}
|
||||
|
||||
fn remove_remote_plugin_install_metadata(
|
||||
&self,
|
||||
plugin_id: &PluginId,
|
||||
) -> Result<(), PluginStoreError> {
|
||||
let path = self.remote_plugin_install_metadata_path(plugin_id);
|
||||
match fs::remove_file(path.as_path()) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(()),
|
||||
Err(err) => Err(PluginStoreError::io(
|
||||
"failed to remove remote plugin install metadata",
|
||||
err,
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
use super::*;
|
||||
use codex_plugin::PluginId;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use tempfile::tempdir;
|
||||
|
||||
fn write_plugin_with_version(
|
||||
@@ -278,111 +277,6 @@ fn install_with_version_uses_requested_cache_version() {
|
||||
assert!(installed_path.join(".codex-plugin/plugin.json").is_file());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_plugin_install_metadata_follows_installed_cache_lifecycle() {
|
||||
let tmp = tempdir().unwrap();
|
||||
write_plugin(tmp.path(), "sample-plugin", "sample-plugin");
|
||||
let plugin_id = PluginId::new(
|
||||
"sample-plugin".to_string(),
|
||||
"openai-curated-remote".to_string(),
|
||||
)
|
||||
.unwrap();
|
||||
let store = PluginStore::new(tmp.path().to_path_buf());
|
||||
let source = AbsolutePathBuf::try_from(tmp.path().join("sample-plugin")).unwrap();
|
||||
|
||||
store
|
||||
.install(source.clone(), plugin_id.clone())
|
||||
.expect("install plugin");
|
||||
assert_eq!(store.remote_plugin_id(&plugin_id).unwrap(), None);
|
||||
|
||||
store
|
||||
.write_remote_plugin_id(&plugin_id, "plugins~Plugin_sample")
|
||||
.expect("write remote identity");
|
||||
let metadata_path = store.remote_plugin_install_metadata_path(&plugin_id);
|
||||
assert_eq!(
|
||||
metadata_path.as_path().file_name(),
|
||||
Some(std::ffi::OsStr::new(".codex-remote-plugin-install.json"))
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::from_str::<serde_json::Value>(
|
||||
&fs::read_to_string(metadata_path.as_path()).expect("read install metadata")
|
||||
)
|
||||
.expect("parse install metadata"),
|
||||
json!({
|
||||
"schema_version": 1,
|
||||
"remote_plugin_id": "plugins~Plugin_sample",
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
store.remote_plugin_id(&plugin_id).unwrap(),
|
||||
Some("plugins~Plugin_sample".to_string())
|
||||
);
|
||||
store
|
||||
.write_remote_plugin_id(&plugin_id, "plugins~Plugin_updated")
|
||||
.expect("replace remote identity");
|
||||
assert_eq!(
|
||||
store.remote_plugin_id(&plugin_id).unwrap(),
|
||||
Some("plugins~Plugin_updated".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::from_str::<serde_json::Value>(
|
||||
&fs::read_to_string(metadata_path.as_path()).expect("read updated install metadata")
|
||||
)
|
||||
.expect("parse updated install metadata"),
|
||||
json!({
|
||||
"schema_version": 1,
|
||||
"remote_plugin_id": "plugins~Plugin_updated",
|
||||
})
|
||||
);
|
||||
|
||||
store
|
||||
.install(source, plugin_id.clone())
|
||||
.expect("replace with local install");
|
||||
assert_eq!(store.remote_plugin_id(&plugin_id).unwrap(), None);
|
||||
assert!(!metadata_path.as_path().exists());
|
||||
|
||||
store
|
||||
.write_remote_plugin_id(&plugin_id, "plugins~Plugin_sample")
|
||||
.expect("restore remote identity");
|
||||
store.uninstall(&plugin_id).expect("uninstall plugin");
|
||||
assert_eq!(store.remote_plugin_id(&plugin_id).unwrap(), None);
|
||||
assert!(!metadata_path.as_path().exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_plugin_install_metadata_rejects_unsupported_schema_version() {
|
||||
let tmp = tempdir().unwrap();
|
||||
write_plugin(tmp.path(), "sample-plugin", "sample-plugin");
|
||||
let plugin_id = PluginId::new(
|
||||
"sample-plugin".to_string(),
|
||||
"openai-curated-remote".to_string(),
|
||||
)
|
||||
.unwrap();
|
||||
let store = PluginStore::new(tmp.path().to_path_buf());
|
||||
store
|
||||
.install(
|
||||
AbsolutePathBuf::try_from(tmp.path().join("sample-plugin")).unwrap(),
|
||||
plugin_id.clone(),
|
||||
)
|
||||
.expect("install plugin");
|
||||
fs::write(
|
||||
store
|
||||
.remote_plugin_install_metadata_path(&plugin_id)
|
||||
.as_path(),
|
||||
r#"{"schema_version":2,"remote_plugin_id":"plugins~Plugin_sample"}"#,
|
||||
)
|
||||
.expect("write unsupported install metadata");
|
||||
|
||||
let err = store
|
||||
.remote_plugin_id(&plugin_id)
|
||||
.expect_err("unsupported schema version should fail");
|
||||
|
||||
assert_eq!(
|
||||
err.to_string(),
|
||||
"unsupported remote plugin install metadata schema version: 2"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn install_prefers_on_disk_manifest_version_over_fallback() {
|
||||
let tmp = tempdir().unwrap();
|
||||
|
||||
@@ -13,8 +13,6 @@ use codex_config::LoaderOverrides;
|
||||
use codex_config::NoopThreadConfigLoader;
|
||||
use codex_config::loader::load_config_layers_state;
|
||||
use codex_exec_server::LOCAL_FS;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_http_client::OutboundProxyPolicy;
|
||||
use codex_login::AuthHeaders;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
@@ -279,7 +277,6 @@ fn load_test_skill_root(root: &PluginSkillRoot) -> LoadedSkillRoot {
|
||||
path_to_skills_md: PathUri::from_abs_path(&canonical_path),
|
||||
scope: SkillScope::User,
|
||||
plugin_id: Some(root.plugin_identity.plugin_id.clone()),
|
||||
remote_plugin_id: root.plugin_identity.remote_plugin_id.clone(),
|
||||
});
|
||||
}
|
||||
Err(message) => errors.push(SkillError {
|
||||
@@ -299,10 +296,6 @@ fn load_test_skill_root(root: &PluginSkillRoot) -> LoadedSkillRoot {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn test_http_client_factory() -> HttpClientFactory {
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault)
|
||||
}
|
||||
|
||||
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();
|
||||
@@ -446,14 +439,6 @@ pub(crate) async fn load_plugins_config(codex_home: &Path, cwd: &Path) -> Plugin
|
||||
.plugins,
|
||||
model_provider_id,
|
||||
feature_enabled(&effective_config, "plugins", /*default_enabled*/ true),
|
||||
feature_enabled(
|
||||
&effective_config,
|
||||
"remote_plugin",
|
||||
/*default_enabled*/ true,
|
||||
),
|
||||
"https://chatgpt.com/backend-api/".to_string(),
|
||||
test_http_client_factory(),
|
||||
/*product_sku*/ None,
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -3,27 +3,21 @@ use std::sync::Arc;
|
||||
use std::sync::RwLock;
|
||||
|
||||
use codex_config::SkillConfigRules;
|
||||
use codex_plugin::AppDeclaration;
|
||||
use codex_plugin::PluginCapabilitySummary;
|
||||
use codex_plugin::PluginId;
|
||||
use codex_plugin::PluginIdError;
|
||||
use codex_plugin::app_connector_ids_from_declarations;
|
||||
use codex_plugin::prompt_safe_plugin_description;
|
||||
use codex_protocol::auth::AuthMode;
|
||||
use codex_protocol::protocol::Product;
|
||||
use codex_skills::SkillRootLoader;
|
||||
use codex_utils_plugins::PluginIdentity;
|
||||
use codex_utils_plugins::PluginSkillRoot;
|
||||
use tokio::sync::Semaphore;
|
||||
|
||||
use crate::app_mcp_routing::apply_app_mcp_routing_policy;
|
||||
use crate::app_mcp_routing::plugin_supports_apps;
|
||||
use crate::loader::PluginSkillInventory;
|
||||
use crate::loader::load_plugin_apps_from_manifest;
|
||||
use crate::loader::load_plugin_mcp_servers_from_manifest_with_format;
|
||||
use crate::loader::load_plugin_skill_inventory;
|
||||
use crate::manager::ConfiguredMarketplacePlugin;
|
||||
use crate::manager::remote_plugin_install_required_description;
|
||||
use crate::manager::source_install_required_description;
|
||||
use crate::manifest::ManifestCache;
|
||||
use crate::marketplace::MarketplaceError;
|
||||
use crate::marketplace::MarketplacePluginSource;
|
||||
@@ -60,33 +54,14 @@ pub(crate) struct ToolSuggestMetadataFragment {
|
||||
plugin_namespace: Option<String>,
|
||||
description: Option<String>,
|
||||
mcp_server_names: Vec<String>,
|
||||
app_declarations: Vec<AppDeclaration>,
|
||||
skill_inventory: Option<PluginSkillInventory>,
|
||||
}
|
||||
|
||||
impl ToolSuggestMetadataFragment {
|
||||
pub(crate) fn project(
|
||||
&self,
|
||||
skill_config_rules: &SkillConfigRules,
|
||||
auth_mode: Option<AuthMode>,
|
||||
) -> PluginCapabilitySummary {
|
||||
let mut app_declarations = self.app_declarations.clone();
|
||||
let mut mcp_servers = self
|
||||
.mcp_server_names
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(|name| (name, ()))
|
||||
.collect::<HashMap<_, _>>();
|
||||
if auth_mode.is_some() {
|
||||
apply_app_mcp_routing_policy(
|
||||
&mut app_declarations,
|
||||
&mut mcp_servers,
|
||||
auth_mode,
|
||||
/*plugin_active*/ true,
|
||||
);
|
||||
}
|
||||
let mut mcp_server_names = mcp_servers.into_keys().collect::<Vec<_>>();
|
||||
pub(crate) fn project(&self, skill_config_rules: &SkillConfigRules) -> PluginCapabilitySummary {
|
||||
let mut mcp_server_names = self.mcp_server_names.clone();
|
||||
mcp_server_names.sort_unstable();
|
||||
mcp_server_names.dedup();
|
||||
|
||||
PluginCapabilitySummary {
|
||||
config_name: self.config_name.clone(),
|
||||
@@ -98,7 +73,6 @@ impl ToolSuggestMetadataFragment {
|
||||
.as_ref()
|
||||
.is_some_and(|inventory| inventory.has_enabled_skills(skill_config_rules)),
|
||||
mcp_server_names,
|
||||
app_connector_ids: app_connector_ids_from_declarations(&app_declarations),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -217,10 +191,9 @@ async fn load_plugin_metadata(
|
||||
display_name: plugin.name.clone(),
|
||||
plugin_namespace: Some(plugin.name.clone()),
|
||||
description: prompt_safe_plugin_description(Some(
|
||||
&remote_plugin_install_required_description(&plugin.source),
|
||||
&source_install_required_description(&plugin.source),
|
||||
)),
|
||||
mcp_server_names: Vec::new(),
|
||||
app_declarations: Vec::new(),
|
||||
skill_inventory: None,
|
||||
}));
|
||||
};
|
||||
@@ -232,7 +205,6 @@ async fn load_plugin_metadata(
|
||||
.ok_or_else(|| "missing or invalid plugin.json".to_string())?;
|
||||
let plugin_identity = PluginIdentity {
|
||||
plugin_id: plugin_id.as_key(),
|
||||
remote_plugin_id: None,
|
||||
};
|
||||
let manifest = loaded_manifest.manifest;
|
||||
let skill_inventory = load_plugin_skill_inventory(
|
||||
@@ -257,11 +229,6 @@ async fn load_plugin_metadata(
|
||||
.collect::<Vec<_>>();
|
||||
mcp_server_names.sort_unstable();
|
||||
mcp_server_names.dedup();
|
||||
let app_declarations = if plugin_supports_apps(loaded_manifest.format, &plugin_id) {
|
||||
load_plugin_apps_from_manifest(plugin_root.as_path(), &manifest.paths).await
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
|
||||
Ok(Arc::new(ToolSuggestMetadataFragment {
|
||||
config_name: plugin.id.clone(),
|
||||
@@ -269,7 +236,6 @@ async fn load_plugin_metadata(
|
||||
plugin_namespace: Some(manifest.name.clone()),
|
||||
description: prompt_safe_plugin_description(manifest.description.as_deref()),
|
||||
mcp_server_names,
|
||||
app_declarations,
|
||||
skill_inventory: Some(skill_inventory),
|
||||
}))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user