mirror of
https://github.com/openai/codex.git
synced 2026-12-02 00:31:03 +00:00
add marketplace import diagnostic
This commit is contained in:
@@ -50,6 +50,7 @@ mod doctor;
|
||||
mod marketplace_cmd;
|
||||
mod mcp_cmd;
|
||||
mod plugin_cmd;
|
||||
mod plugin_import_diagnostic;
|
||||
mod remote_control_cmd;
|
||||
#[cfg(target_os = "windows")]
|
||||
mod sandbox_setup;
|
||||
@@ -235,6 +236,10 @@ enum DebugSubcommand {
|
||||
/// Internal: reset local memory state for a fresh start.
|
||||
#[clap(hide = true)]
|
||||
ClearMemories,
|
||||
|
||||
/// Internal: produce a redacted, per-plugin marketplace import report.
|
||||
#[clap(hide = true)]
|
||||
MarketplaceImportDiagnostic(plugin_import_diagnostic::MarketplaceImportDiagnosticCommand),
|
||||
}
|
||||
|
||||
#[derive(Debug, Parser)]
|
||||
@@ -1470,6 +1475,14 @@ async fn cli_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> {
|
||||
)?;
|
||||
run_debug_clear_memories_command(&root_config_overrides).await?;
|
||||
}
|
||||
DebugSubcommand::MarketplaceImportDiagnostic(cmd) => {
|
||||
reject_remote_mode_for_subcommand(
|
||||
root_remote.as_deref(),
|
||||
root_remote_auth_token_env.as_deref(),
|
||||
"debug marketplace-import-diagnostic",
|
||||
)?;
|
||||
plugin_import_diagnostic::run(cmd).await?;
|
||||
}
|
||||
},
|
||||
Some(Subcommand::Execpolicy(ExecpolicyCommand { sub })) => match sub {
|
||||
ExecpolicySubcommand::Check(cmd) => {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,77 @@
|
||||
use super::Redactor;
|
||||
use super::truncate_chars;
|
||||
use std::path::Path;
|
||||
|
||||
#[test]
|
||||
fn redactor_removes_roots_credentials_query_and_deep_url_paths() {
|
||||
let redactor = Redactor::new(
|
||||
Path::new("/private/customer/marketplace"),
|
||||
Path::new("/tmp/diagnostic-home"),
|
||||
);
|
||||
let detail = redactor.detail(
|
||||
"failed in /private/customer/marketplace/plugins/demo via \
|
||||
https://user:secret@example.com/private/repo.git?token=secret and \
|
||||
git@github.example.com:private/repo.git and \
|
||||
/outside/customer/path and \
|
||||
/tmp/diagnostic-home/plugins/cache; \
|
||||
api_key=sk-123456789012345678901234567890",
|
||||
);
|
||||
|
||||
assert!(detail.contains("<marketplace-root>/plugins/demo"));
|
||||
assert!(detail.contains("<diagnostic-home>/plugins/cache"));
|
||||
assert!(detail.contains("<redacted-url>"));
|
||||
assert!(detail.contains("<git-remote>:<redacted>"));
|
||||
assert!(!detail.contains("/outside/customer/path"));
|
||||
assert!(!detail.contains("user:secret"));
|
||||
assert!(!detail.contains("token=secret"));
|
||||
assert!(!detail.contains("sk-123456789012345678901234567890"));
|
||||
assert!(detail.contains("api_key=[REDACTED_SECRET]"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detail_truncation_is_bounded() {
|
||||
let truncated = truncate_chars("x".repeat(20), 8);
|
||||
assert_eq!(truncated, "xxxxxxxx...[truncated]");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn redactor_removes_git_command_arguments_and_remote_output() {
|
||||
let redactor = Redactor::new(
|
||||
Path::new("/private/customer/marketplace"),
|
||||
Path::new("/tmp/diagnostic-home"),
|
||||
);
|
||||
let detail = redactor.detail(
|
||||
"git checkout private-ref\nsecond-private-ref \
|
||||
/tmp/diagnostic-home/staging failed with status exit status: 128\n\
|
||||
stdout:\n\
|
||||
private account output\n\
|
||||
stderr:\n\
|
||||
authentication failed",
|
||||
);
|
||||
|
||||
assert!(detail.contains("git <redacted arguments> failed with status exit status: 128"));
|
||||
assert!(detail.contains("failure class: authentication_or_authorization"));
|
||||
assert!(detail.contains("git output omitted"));
|
||||
assert!(!detail.contains("private-ref"));
|
||||
assert!(!detail.contains("private account output"));
|
||||
assert!(!detail.contains("authentication failed"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn redactor_removes_parser_values_and_private_hosts() {
|
||||
let redactor = Redactor::new(
|
||||
Path::new("/private/customer/marketplace"),
|
||||
Path::new("/tmp/diagnostic-home"),
|
||||
);
|
||||
let detail = redactor.detail(
|
||||
"invalid type: integer `8675309`; unknown variant `private-transport`; fetch from \
|
||||
https://internal.example/private/config failed",
|
||||
);
|
||||
|
||||
assert!(detail.contains("integer <redacted-value>"));
|
||||
assert!(detail.contains("variant <redacted-value>"));
|
||||
assert!(detail.contains("<redacted-url>"));
|
||||
assert!(!detail.contains("8675309"));
|
||||
assert!(!detail.contains("private-transport"));
|
||||
assert!(!detail.contains("internal.example"));
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
use anyhow::Result;
|
||||
use serde_json::Value;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
use tempfile::TempDir;
|
||||
|
||||
fn write_file(path: &Path, contents: &str) -> Result<()> {
|
||||
let Some(parent) = path.parent() else {
|
||||
anyhow::bail!("fixture file should have a parent: {}", path.display());
|
||||
};
|
||||
fs::create_dir_all(parent)?;
|
||||
fs::write(path, contents)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diagnostic_reports_every_entry_and_continues_after_failures() -> Result<()> {
|
||||
let fixture = TempDir::new()?;
|
||||
let marketplace = fixture.path();
|
||||
write_file(
|
||||
&marketplace.join(".claude-plugin/marketplace.json"),
|
||||
r#"{
|
||||
"name": "diagnostic-fixture",
|
||||
"plugins": [
|
||||
{ "name": "good", "source": "./plugins/good" },
|
||||
{ "name": "missing-manifest", "source": "./plugins/missing-manifest" },
|
||||
{ "name": "missing-source", "source": "./plugins/missing-source" },
|
||||
{ "name": "unsupported", "source": { "source": "npm", "package": "private-package" } },
|
||||
{ "name": "bad-path", "source": "plugins/bad-path" }
|
||||
]
|
||||
}"#,
|
||||
)?;
|
||||
write_file(
|
||||
&marketplace.join("plugins/good/.claude-plugin/plugin.json"),
|
||||
r#"{
|
||||
"name": "good",
|
||||
"version": "1.0.0",
|
||||
"commands": "./commands",
|
||||
"hooks": "./hooks/missing.json"
|
||||
}"#,
|
||||
)?;
|
||||
write_file(
|
||||
&marketplace.join("plugins/good/skills/demo/SKILL.md"),
|
||||
r#"---
|
||||
name: demo
|
||||
description: Diagnostic fixture skill.
|
||||
---
|
||||
Use this skill only in the diagnostic fixture.
|
||||
"#,
|
||||
)?;
|
||||
write_file(
|
||||
&marketplace.join("plugins/good/skills/broken/SKILL.md"),
|
||||
"This skill is missing YAML frontmatter.",
|
||||
)?;
|
||||
write_file(
|
||||
&marketplace.join("plugins/good/.mcp.json"),
|
||||
r#"{ "mcpServers": { "broken": { "command": 42 } } }"#,
|
||||
)?;
|
||||
write_file(
|
||||
&marketplace.join("plugins/good/.app.json"),
|
||||
r#"{ "apps": { "broken": { "id": "" } } }"#,
|
||||
)?;
|
||||
fs::create_dir_all(marketplace.join("plugins/missing-manifest"))?;
|
||||
|
||||
let output_dir = TempDir::new()?;
|
||||
let output = output_dir.path().join("plugin-diagnostic.jsonl");
|
||||
let mut command = assert_cmd::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?);
|
||||
command
|
||||
.arg("debug")
|
||||
.arg("marketplace-import-diagnostic")
|
||||
.arg(marketplace)
|
||||
.arg("--output")
|
||||
.arg(&output)
|
||||
.arg("--attempt-install")
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let report = fs::read_to_string(&output)?;
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
assert_eq!(fs::metadata(&output)?.permissions().mode() & 0o077, 0);
|
||||
}
|
||||
assert!(!report.contains(&marketplace.display().to_string()));
|
||||
assert!(!report.contains("private-package"));
|
||||
let records = report
|
||||
.lines()
|
||||
.map(serde_json::from_str::<Value>)
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
assert_eq!(records.len(), 19);
|
||||
assert_eq!(records[0]["attemptInstall"], true);
|
||||
|
||||
let started = records
|
||||
.iter()
|
||||
.filter(|record| record["event"] == "plugin_started")
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(started.len(), 5);
|
||||
assert_eq!(started[0]["pluginName"], "good");
|
||||
|
||||
let stages = records
|
||||
.iter()
|
||||
.filter(|record| record["event"] == "plugin_stage_started")
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(stages.len(), 6);
|
||||
assert_eq!(stages[0]["stage"], "install");
|
||||
assert_eq!(stages[1]["stage"], "capabilities");
|
||||
|
||||
let plugins = records
|
||||
.iter()
|
||||
.filter(|record| record["event"] == "plugin_diagnostic")
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(plugins.len(), 5);
|
||||
assert_eq!(plugins[0]["pluginName"], "good");
|
||||
assert_eq!(plugins[0]["outcome"], "installed");
|
||||
assert_eq!(
|
||||
plugins[0]["capabilities"]["manifest"]["unsupportedCapabilityFields"],
|
||||
serde_json::json!(["commands"])
|
||||
);
|
||||
assert_eq!(
|
||||
plugins[0]["capabilities"]["skills"]["detected"][0]["name"],
|
||||
"good:demo"
|
||||
);
|
||||
assert!(
|
||||
plugins[0]["capabilities"]["skills"]["errors"]
|
||||
.as_array()
|
||||
.is_some_and(|errors| !errors.is_empty())
|
||||
);
|
||||
assert_eq!(
|
||||
plugins[0]["capabilities"]["mcp"]["serverNames"],
|
||||
serde_json::json!([])
|
||||
);
|
||||
assert!(
|
||||
plugins[0]["capabilities"]["mcp"]["issues"]
|
||||
.as_array()
|
||||
.is_some_and(|issues| !issues.is_empty())
|
||||
);
|
||||
assert!(
|
||||
plugins[0]["capabilities"]["hooks"]["issues"]
|
||||
.as_array()
|
||||
.is_some_and(|issues| !issues.is_empty())
|
||||
);
|
||||
assert!(
|
||||
plugins[0]["capabilities"]["apps"]["issues"]
|
||||
.as_array()
|
||||
.is_some_and(|issues| !issues.is_empty())
|
||||
);
|
||||
assert_eq!(plugins[1]["pluginName"], "missing-manifest");
|
||||
assert_eq!(plugins[1]["outcome"], "install_failed");
|
||||
assert_eq!(plugins[1]["install"]["code"], "install_failed");
|
||||
assert_eq!(plugins[2]["pluginName"], "missing-source");
|
||||
assert_eq!(plugins[2]["outcome"], "install_failed");
|
||||
assert_eq!(plugins[2]["install"]["code"], "source_path_not_found");
|
||||
assert_eq!(plugins[3]["detection"]["code"], "unsupported_source");
|
||||
assert_eq!(plugins[4]["detection"]["code"], "invalid_source");
|
||||
|
||||
let completed = records.last().expect("completion record");
|
||||
assert_eq!(completed["event"], "run_completed");
|
||||
assert_eq!(completed["summary"]["rawEntries"], 5);
|
||||
assert_eq!(completed["summary"]["detectedEntries"], 3);
|
||||
assert_eq!(completed["summary"]["detectionFailures"], 2);
|
||||
assert_eq!(completed["summary"]["installedEntries"], 1);
|
||||
assert_eq!(completed["summary"]["installFailures"], 2);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diagnostic_writes_preflight_failures_to_the_report() -> Result<()> {
|
||||
let fixture = TempDir::new()?;
|
||||
let missing_marketplace = fixture.path().join("missing-marketplace");
|
||||
let output = fixture.path().join("preflight-diagnostic.jsonl");
|
||||
let mut command = assert_cmd::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?);
|
||||
command
|
||||
.arg("debug")
|
||||
.arg("marketplace-import-diagnostic")
|
||||
.arg(&missing_marketplace)
|
||||
.arg("--output")
|
||||
.arg(&output)
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let records = fs::read_to_string(&output)?
|
||||
.lines()
|
||||
.map(serde_json::from_str::<Value>)
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
assert_eq!(records.len(), 3);
|
||||
assert_eq!(records[0]["event"], "run_started");
|
||||
assert_eq!(records[1]["event"], "marketplace_diagnostic");
|
||||
assert_eq!(records[1]["code"], "marketplace_root_unavailable");
|
||||
assert_eq!(records[2]["status"], "report_complete_preflight_failed");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diagnostic_does_not_overwrite_an_existing_report() -> Result<()> {
|
||||
let fixture = TempDir::new()?;
|
||||
let output = fixture.path().join("existing.jsonl");
|
||||
fs::write(&output, "keep-me")?;
|
||||
let mut command = assert_cmd::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?);
|
||||
command
|
||||
.arg("debug")
|
||||
.arg("marketplace-import-diagnostic")
|
||||
.arg(fixture.path())
|
||||
.arg("--output")
|
||||
.arg(&output)
|
||||
.assert()
|
||||
.failure();
|
||||
|
||||
assert_eq!(fs::read_to_string(output)?, "keep-me");
|
||||
Ok(())
|
||||
}
|
||||
@@ -15,6 +15,7 @@ use codex_config::HooksFile;
|
||||
use codex_config::types::McpServerConfig;
|
||||
use codex_config::types::PluginConfig;
|
||||
use codex_config::types::PluginMcpServerConfig;
|
||||
use codex_core_skills::SkillError;
|
||||
use codex_core_skills::SkillMetadata;
|
||||
use codex_core_skills::config_rules::SkillConfigRules;
|
||||
use codex_core_skills::config_rules::resolve_disabled_skill_paths;
|
||||
@@ -755,6 +756,7 @@ fn apply_plugin_mcp_server_policy(config: &mut McpServerConfig, policy: &PluginM
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ResolvedPluginSkills {
|
||||
pub skills: Vec<SkillMetadata>,
|
||||
pub errors: Vec<SkillError>,
|
||||
pub disabled_skill_paths: HashSet<AbsolutePathBuf>,
|
||||
pub had_errors: bool,
|
||||
}
|
||||
@@ -788,6 +790,7 @@ pub async fn load_plugin_skills(
|
||||
.collect::<Vec<_>>();
|
||||
let outcome = load_skills_from_roots(roots).await;
|
||||
let had_errors = !outcome.errors.is_empty();
|
||||
let errors = outcome.errors;
|
||||
let skills = outcome
|
||||
.skills
|
||||
.into_iter()
|
||||
@@ -797,6 +800,7 @@ pub async fn load_plugin_skills(
|
||||
|
||||
ResolvedPluginSkills {
|
||||
skills,
|
||||
errors,
|
||||
disabled_skill_paths,
|
||||
had_errors,
|
||||
}
|
||||
@@ -849,13 +853,31 @@ fn default_mcp_config_paths(plugin_root: &Path) -> Vec<AbsolutePathBuf> {
|
||||
|
||||
pub async fn load_plugin_apps(plugin_root: &Path) -> Vec<AppConnectorId> {
|
||||
if let Some(manifest) = load_plugin_manifest(plugin_root) {
|
||||
return load_apps_from_paths(
|
||||
plugin_root,
|
||||
plugin_app_config_paths(plugin_root, &manifest.paths),
|
||||
)
|
||||
.await;
|
||||
return diagnose_plugin_apps(plugin_root, &manifest.paths)
|
||||
.await
|
||||
.connector_ids;
|
||||
}
|
||||
load_apps_from_paths(plugin_root, default_app_config_paths(plugin_root)).await
|
||||
load_apps_from_paths(plugin_root, default_app_config_paths(plugin_root))
|
||||
.await
|
||||
.connector_ids
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct PluginAppLoadDiagnostics {
|
||||
pub config_paths: Vec<AbsolutePathBuf>,
|
||||
pub connector_ids: Vec<AppConnectorId>,
|
||||
pub issues: Vec<String>,
|
||||
}
|
||||
|
||||
pub async fn diagnose_plugin_apps(
|
||||
plugin_root: &Path,
|
||||
manifest_paths: &PluginManifestPaths,
|
||||
) -> PluginAppLoadDiagnostics {
|
||||
load_apps_from_paths(
|
||||
plugin_root,
|
||||
plugin_app_config_paths(plugin_root, manifest_paths),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
fn plugin_app_config_paths(
|
||||
@@ -994,11 +1016,19 @@ fn append_plugin_hook_file(
|
||||
async fn load_apps_from_paths(
|
||||
plugin_root: &Path,
|
||||
app_config_paths: Vec<AbsolutePathBuf>,
|
||||
) -> Vec<AppConnectorId> {
|
||||
) -> PluginAppLoadDiagnostics {
|
||||
let mut connector_ids = 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 mut issues = Vec::new();
|
||||
for app_config_path in &app_config_paths {
|
||||
let contents = match tokio::fs::read_to_string(app_config_path.as_path()).await {
|
||||
Ok(contents) => contents,
|
||||
Err(err) => {
|
||||
issues.push(format!(
|
||||
"failed to read plugin app config {}: {err}",
|
||||
app_config_path.display()
|
||||
));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let parsed = match serde_json::from_str::<PluginAppFile>(&contents) {
|
||||
Ok(parsed) => parsed,
|
||||
@@ -1007,6 +1037,10 @@ async fn load_apps_from_paths(
|
||||
path = %app_config_path.display(),
|
||||
"failed to parse plugin app config: {err}"
|
||||
);
|
||||
issues.push(format!(
|
||||
"failed to parse plugin app config {}: {err}",
|
||||
app_config_path.display()
|
||||
));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
@@ -1017,6 +1051,7 @@ async fn load_apps_from_paths(
|
||||
plugin = %plugin_root.display(),
|
||||
"plugin app config is missing an app id"
|
||||
);
|
||||
issues.push("plugin app config is missing an app id".to_string());
|
||||
None
|
||||
} else {
|
||||
Some(AppConnectorId(app.id))
|
||||
@@ -1025,7 +1060,11 @@ async fn load_apps_from_paths(
|
||||
}
|
||||
let mut seen_connector_ids = HashSet::new();
|
||||
connector_ids.retain(|connector_id| seen_connector_ids.insert(connector_id.0.clone()));
|
||||
connector_ids
|
||||
PluginAppLoadDiagnostics {
|
||||
config_paths: app_config_paths,
|
||||
connector_ids,
|
||||
issues,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn plugin_telemetry_metadata_from_root(
|
||||
@@ -1063,7 +1102,8 @@ pub async fn plugin_telemetry_metadata_from_root(
|
||||
plugin_root.as_path(),
|
||||
plugin_app_config_paths(plugin_root.as_path(), manifest_paths),
|
||||
)
|
||||
.await,
|
||||
.await
|
||||
.connector_ids,
|
||||
}),
|
||||
}
|
||||
}
|
||||
@@ -1084,6 +1124,35 @@ pub async fn load_plugin_mcp_servers(plugin_root: &Path) -> HashMap<String, McpS
|
||||
mcp_servers
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct PluginMcpLoadDiagnostics {
|
||||
pub config_paths: Vec<AbsolutePathBuf>,
|
||||
pub server_names: Vec<String>,
|
||||
pub issues: Vec<String>,
|
||||
}
|
||||
|
||||
pub async fn diagnose_plugin_mcp_servers(
|
||||
plugin_root: &Path,
|
||||
manifest_paths: &PluginManifestPaths,
|
||||
) -> PluginMcpLoadDiagnostics {
|
||||
let config_paths = plugin_mcp_config_paths(plugin_root, manifest_paths);
|
||||
let mut server_names = Vec::new();
|
||||
let mut issues = Vec::new();
|
||||
for path in &config_paths {
|
||||
let discovery = load_mcp_servers_from_file(plugin_root, path).await;
|
||||
server_names.extend(discovery.mcp_servers.into_keys());
|
||||
issues.extend(discovery.issues);
|
||||
}
|
||||
server_names.sort_unstable();
|
||||
server_names.dedup();
|
||||
|
||||
PluginMcpLoadDiagnostics {
|
||||
config_paths,
|
||||
server_names,
|
||||
issues,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn installed_plugin_telemetry_metadata(
|
||||
codex_home: &Path,
|
||||
plugin_id: &PluginId,
|
||||
@@ -1106,8 +1175,17 @@ async fn load_mcp_servers_from_file(
|
||||
plugin_root: &Path,
|
||||
mcp_config_path: &AbsolutePathBuf,
|
||||
) -> PluginMcpDiscovery {
|
||||
let Ok(contents) = tokio::fs::read_to_string(mcp_config_path.as_path()).await else {
|
||||
return PluginMcpDiscovery::default();
|
||||
let contents = match tokio::fs::read_to_string(mcp_config_path.as_path()).await {
|
||||
Ok(contents) => contents,
|
||||
Err(err) => {
|
||||
return PluginMcpDiscovery {
|
||||
issues: vec![format!(
|
||||
"failed to read plugin MCP config {}: {err}",
|
||||
mcp_config_path.display()
|
||||
)],
|
||||
..Default::default()
|
||||
};
|
||||
}
|
||||
};
|
||||
let parsed = match serde_json::from_str::<PluginMcpFile>(&contents) {
|
||||
Ok(parsed) => parsed,
|
||||
@@ -1116,7 +1194,13 @@ async fn load_mcp_servers_from_file(
|
||||
path = %mcp_config_path.display(),
|
||||
"failed to parse plugin MCP config: {err}"
|
||||
);
|
||||
return PluginMcpDiscovery::default();
|
||||
return PluginMcpDiscovery {
|
||||
issues: vec![format!(
|
||||
"failed to parse plugin MCP config {}: {err}",
|
||||
mcp_config_path.display()
|
||||
)],
|
||||
..Default::default()
|
||||
};
|
||||
}
|
||||
};
|
||||
normalize_plugin_mcp_servers(
|
||||
@@ -1132,9 +1216,11 @@ fn normalize_plugin_mcp_servers(
|
||||
source: &str,
|
||||
) -> PluginMcpDiscovery {
|
||||
let mut mcp_servers = HashMap::new();
|
||||
let mut issues = Vec::new();
|
||||
|
||||
for (name, config_value) in plugin_mcp_servers {
|
||||
let normalized = normalize_plugin_mcp_server_value(plugin_root, config_value);
|
||||
let normalized =
|
||||
normalize_plugin_mcp_server_value(plugin_root, &name, config_value, &mut issues);
|
||||
match serde_json::from_value::<McpServerConfig>(JsonValue::Object(normalized)) {
|
||||
Ok(config) => {
|
||||
mcp_servers.insert(name, config);
|
||||
@@ -1145,16 +1231,24 @@ fn normalize_plugin_mcp_servers(
|
||||
server = name,
|
||||
"failed to parse plugin MCP server from {source}: {err}"
|
||||
);
|
||||
issues.push(format!(
|
||||
"failed to parse plugin MCP server `{name}` from {source}: {err}"
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
PluginMcpDiscovery { mcp_servers }
|
||||
PluginMcpDiscovery {
|
||||
mcp_servers,
|
||||
issues,
|
||||
}
|
||||
}
|
||||
|
||||
fn normalize_plugin_mcp_server_value(
|
||||
plugin_root: &Path,
|
||||
server_name: &str,
|
||||
value: JsonValue,
|
||||
issues: &mut Vec<String>,
|
||||
) -> JsonMap<String, JsonValue> {
|
||||
let mut object = match value {
|
||||
JsonValue::Object(object) => object,
|
||||
@@ -1171,6 +1265,9 @@ fn normalize_plugin_mcp_server_value(
|
||||
transport = other,
|
||||
"plugin MCP server uses an unknown transport type"
|
||||
);
|
||||
issues.push(format!(
|
||||
"plugin MCP server `{server_name}` uses an unknown transport type"
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1181,6 +1278,9 @@ fn normalize_plugin_mcp_server_value(
|
||||
plugin = %plugin_root.display(),
|
||||
"plugin MCP server OAuth callbackPort is ignored; Codex uses global MCP OAuth callback settings"
|
||||
);
|
||||
issues.push(format!(
|
||||
"plugin MCP server `{server_name}` OAuth callbackPort is ignored"
|
||||
));
|
||||
}
|
||||
|
||||
if let Some(client_id) = oauth.remove("clientId") {
|
||||
@@ -1207,6 +1307,7 @@ fn normalize_plugin_mcp_server_value(
|
||||
#[derive(Debug, Default)]
|
||||
struct PluginMcpDiscovery {
|
||||
mcp_servers: HashMap<String, McpServerConfig>,
|
||||
issues: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
|
||||
@@ -52,6 +52,14 @@ pub struct PluginManifestPaths {
|
||||
pub hooks: Option<PluginManifestHooks>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct PluginManifestLoadDiagnostics {
|
||||
pub manifest_path: Option<std::path::PathBuf>,
|
||||
pub manifest: Option<PluginManifest>,
|
||||
pub issues: Vec<String>,
|
||||
pub unsupported_capability_fields: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum PluginManifestHooks {
|
||||
Paths(Vec<AbsolutePathBuf>),
|
||||
@@ -145,141 +153,208 @@ enum RawPluginManifestHooks {
|
||||
}
|
||||
|
||||
pub fn load_plugin_manifest(plugin_root: &Path) -> Option<PluginManifest> {
|
||||
let manifest_path = find_plugin_manifest_path(plugin_root)?;
|
||||
let contents = fs::read_to_string(&manifest_path).ok()?;
|
||||
match serde_json::from_str::<RawPluginManifest>(&contents) {
|
||||
Ok(manifest) => {
|
||||
let RawPluginManifest {
|
||||
name: raw_name,
|
||||
version,
|
||||
description,
|
||||
keywords,
|
||||
skills,
|
||||
mcp_servers,
|
||||
apps,
|
||||
hooks,
|
||||
interface,
|
||||
} = manifest;
|
||||
let name = plugin_root
|
||||
.file_name()
|
||||
.and_then(|entry| entry.to_str())
|
||||
.filter(|_| raw_name.trim().is_empty())
|
||||
.unwrap_or(&raw_name)
|
||||
.to_string();
|
||||
let version = version.and_then(|version| {
|
||||
let version = version.trim();
|
||||
(!version.is_empty()).then(|| version.to_string())
|
||||
});
|
||||
let interface = interface.and_then(|interface| {
|
||||
let RawPluginManifestInterface {
|
||||
display_name,
|
||||
short_description,
|
||||
long_description,
|
||||
developer_name,
|
||||
category,
|
||||
capabilities,
|
||||
website_url,
|
||||
privacy_policy_url,
|
||||
terms_of_service_url,
|
||||
default_prompt,
|
||||
brand_color,
|
||||
composer_icon,
|
||||
logo,
|
||||
screenshots,
|
||||
} = interface;
|
||||
diagnose_plugin_manifest(plugin_root).manifest
|
||||
}
|
||||
|
||||
let interface = PluginManifestInterface {
|
||||
display_name,
|
||||
short_description,
|
||||
long_description,
|
||||
developer_name,
|
||||
category,
|
||||
capabilities,
|
||||
website_url,
|
||||
privacy_policy_url,
|
||||
terms_of_service_url,
|
||||
default_prompt: resolve_default_prompts(plugin_root, default_prompt.as_ref()),
|
||||
brand_color,
|
||||
composer_icon: resolve_interface_asset_path(
|
||||
plugin_root,
|
||||
"interface.composerIcon",
|
||||
composer_icon.as_deref(),
|
||||
),
|
||||
logo: resolve_interface_asset_path(
|
||||
plugin_root,
|
||||
"interface.logo",
|
||||
logo.as_deref(),
|
||||
),
|
||||
screenshots: screenshots
|
||||
.iter()
|
||||
.filter_map(|screenshot| {
|
||||
resolve_interface_asset_path(
|
||||
plugin_root,
|
||||
"interface.screenshots",
|
||||
Some(screenshot),
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
};
|
||||
|
||||
let has_fields = interface.display_name.is_some()
|
||||
|| interface.short_description.is_some()
|
||||
|| interface.long_description.is_some()
|
||||
|| interface.developer_name.is_some()
|
||||
|| interface.category.is_some()
|
||||
|| !interface.capabilities.is_empty()
|
||||
|| interface.website_url.is_some()
|
||||
|| interface.privacy_policy_url.is_some()
|
||||
|| interface.terms_of_service_url.is_some()
|
||||
|| interface.default_prompt.is_some()
|
||||
|| interface.brand_color.is_some()
|
||||
|| interface.composer_icon.is_some()
|
||||
|| interface.logo.is_some()
|
||||
|| !interface.screenshots.is_empty();
|
||||
|
||||
has_fields.then_some(interface)
|
||||
});
|
||||
Some(PluginManifest {
|
||||
name,
|
||||
version,
|
||||
description,
|
||||
keywords,
|
||||
paths: PluginManifestPaths {
|
||||
skills: resolve_manifest_path_value(plugin_root, "skills", skills.as_ref()),
|
||||
mcp_servers: resolve_manifest_path(
|
||||
plugin_root,
|
||||
"mcpServers",
|
||||
mcp_servers.as_deref(),
|
||||
),
|
||||
apps: resolve_manifest_path(plugin_root, "apps", apps.as_deref()),
|
||||
hooks: resolve_manifest_hooks(plugin_root, hooks),
|
||||
},
|
||||
interface,
|
||||
})
|
||||
}
|
||||
pub fn diagnose_plugin_manifest(plugin_root: &Path) -> PluginManifestLoadDiagnostics {
|
||||
let Some(manifest_path) = find_plugin_manifest_path(plugin_root) else {
|
||||
return PluginManifestLoadDiagnostics {
|
||||
issues: vec![
|
||||
"plugin root does not contain .codex-plugin/plugin.json or .claude-plugin/plugin.json"
|
||||
.to_string(),
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
};
|
||||
let contents = match fs::read_to_string(&manifest_path) {
|
||||
Ok(contents) => contents,
|
||||
Err(err) => {
|
||||
tracing::warn!(
|
||||
path = %manifest_path.display(),
|
||||
"failed to parse plugin manifest: {err}"
|
||||
let message = format!(
|
||||
"failed to read plugin manifest {}: {err}",
|
||||
manifest_path.display()
|
||||
);
|
||||
None
|
||||
return PluginManifestLoadDiagnostics {
|
||||
manifest_path: Some(manifest_path),
|
||||
issues: vec![message],
|
||||
..Default::default()
|
||||
};
|
||||
}
|
||||
};
|
||||
let unsupported_capability_fields = serde_json::from_str::<JsonValue>(&contents)
|
||||
.ok()
|
||||
.and_then(|value| {
|
||||
value
|
||||
.as_object()
|
||||
.map(unsupported_manifest_capability_fields)
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let raw_manifest = match serde_json::from_str::<RawPluginManifest>(&contents) {
|
||||
Ok(manifest) => manifest,
|
||||
Err(err) => {
|
||||
let message = format!("failed to parse plugin manifest: {err}");
|
||||
tracing::warn!(path = %manifest_path.display(), "{message}");
|
||||
return PluginManifestLoadDiagnostics {
|
||||
manifest_path: Some(manifest_path),
|
||||
issues: vec![message],
|
||||
unsupported_capability_fields,
|
||||
..Default::default()
|
||||
};
|
||||
}
|
||||
};
|
||||
let mut issues = Vec::new();
|
||||
let manifest = resolve_plugin_manifest(plugin_root, raw_manifest, &mut issues);
|
||||
PluginManifestLoadDiagnostics {
|
||||
manifest_path: Some(manifest_path),
|
||||
manifest: Some(manifest),
|
||||
issues,
|
||||
unsupported_capability_fields,
|
||||
}
|
||||
}
|
||||
|
||||
fn unsupported_manifest_capability_fields(
|
||||
object: &serde_json::Map<String, JsonValue>,
|
||||
) -> Vec<String> {
|
||||
const UNSUPPORTED_CAPABILITY_FIELDS: &[&str] =
|
||||
&["agents", "commands", "lspServers", "outputStyles"];
|
||||
UNSUPPORTED_CAPABILITY_FIELDS
|
||||
.iter()
|
||||
.filter(|field| object.contains_key(**field))
|
||||
.map(|field| (*field).to_string())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn resolve_plugin_manifest(
|
||||
plugin_root: &Path,
|
||||
manifest: RawPluginManifest,
|
||||
issues: &mut Vec<String>,
|
||||
) -> PluginManifest {
|
||||
let RawPluginManifest {
|
||||
name: raw_name,
|
||||
version,
|
||||
description,
|
||||
keywords,
|
||||
skills,
|
||||
mcp_servers,
|
||||
apps,
|
||||
hooks,
|
||||
interface,
|
||||
} = manifest;
|
||||
let name = plugin_root
|
||||
.file_name()
|
||||
.and_then(|entry| entry.to_str())
|
||||
.filter(|_| raw_name.trim().is_empty())
|
||||
.unwrap_or(&raw_name)
|
||||
.to_string();
|
||||
let version = version.and_then(|version| {
|
||||
let version = version.trim();
|
||||
(!version.is_empty()).then(|| version.to_string())
|
||||
});
|
||||
let interface = interface.and_then(|interface| {
|
||||
let RawPluginManifestInterface {
|
||||
display_name,
|
||||
short_description,
|
||||
long_description,
|
||||
developer_name,
|
||||
category,
|
||||
capabilities,
|
||||
website_url,
|
||||
privacy_policy_url,
|
||||
terms_of_service_url,
|
||||
default_prompt,
|
||||
brand_color,
|
||||
composer_icon,
|
||||
logo,
|
||||
screenshots,
|
||||
} = interface;
|
||||
|
||||
let interface = PluginManifestInterface {
|
||||
display_name,
|
||||
short_description,
|
||||
long_description,
|
||||
developer_name,
|
||||
category,
|
||||
capabilities,
|
||||
website_url,
|
||||
privacy_policy_url,
|
||||
terms_of_service_url,
|
||||
default_prompt: resolve_default_prompts(plugin_root, default_prompt.as_ref(), issues),
|
||||
brand_color,
|
||||
composer_icon: resolve_interface_asset_path(
|
||||
plugin_root,
|
||||
"interface.composerIcon",
|
||||
composer_icon.as_deref(),
|
||||
issues,
|
||||
),
|
||||
logo: resolve_interface_asset_path(
|
||||
plugin_root,
|
||||
"interface.logo",
|
||||
logo.as_deref(),
|
||||
issues,
|
||||
),
|
||||
screenshots: screenshots
|
||||
.iter()
|
||||
.filter_map(|screenshot| {
|
||||
resolve_interface_asset_path(
|
||||
plugin_root,
|
||||
"interface.screenshots",
|
||||
Some(screenshot),
|
||||
issues,
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
};
|
||||
|
||||
let has_fields = interface.display_name.is_some()
|
||||
|| interface.short_description.is_some()
|
||||
|| interface.long_description.is_some()
|
||||
|| interface.developer_name.is_some()
|
||||
|| interface.category.is_some()
|
||||
|| !interface.capabilities.is_empty()
|
||||
|| interface.website_url.is_some()
|
||||
|| interface.privacy_policy_url.is_some()
|
||||
|| interface.terms_of_service_url.is_some()
|
||||
|| interface.default_prompt.is_some()
|
||||
|| interface.brand_color.is_some()
|
||||
|| interface.composer_icon.is_some()
|
||||
|| interface.logo.is_some()
|
||||
|| !interface.screenshots.is_empty();
|
||||
|
||||
has_fields.then_some(interface)
|
||||
});
|
||||
PluginManifest {
|
||||
name,
|
||||
version,
|
||||
description,
|
||||
keywords,
|
||||
paths: PluginManifestPaths {
|
||||
skills: resolve_manifest_path_value(plugin_root, "skills", skills.as_ref(), issues),
|
||||
mcp_servers: resolve_manifest_path(
|
||||
plugin_root,
|
||||
"mcpServers",
|
||||
mcp_servers.as_deref(),
|
||||
issues,
|
||||
),
|
||||
apps: resolve_manifest_path(plugin_root, "apps", apps.as_deref(), issues),
|
||||
hooks: resolve_manifest_hooks(plugin_root, hooks, issues),
|
||||
},
|
||||
interface,
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_manifest_hooks(
|
||||
plugin_root: &Path,
|
||||
hooks: Option<RawPluginManifestHooks>,
|
||||
issues: &mut Vec<String>,
|
||||
) -> Option<PluginManifestHooks> {
|
||||
match hooks? {
|
||||
RawPluginManifestHooks::Path(path) => {
|
||||
resolve_manifest_path(plugin_root, "hooks", Some(&path))
|
||||
resolve_manifest_path(plugin_root, "hooks", Some(&path), issues)
|
||||
.map(|path| PluginManifestHooks::Paths(vec![path]))
|
||||
}
|
||||
RawPluginManifestHooks::Paths(paths) => {
|
||||
let hooks = paths
|
||||
.iter()
|
||||
.filter_map(|path| resolve_manifest_path(plugin_root, "hooks", Some(path)))
|
||||
.filter_map(|path| resolve_manifest_path(plugin_root, "hooks", Some(path), issues))
|
||||
.collect::<Vec<_>>();
|
||||
(!hooks.is_empty()).then_some(PluginManifestHooks::Paths(hooks))
|
||||
}
|
||||
@@ -288,10 +363,12 @@ fn resolve_manifest_hooks(
|
||||
(!hooks.is_empty()).then_some(PluginManifestHooks::Inline(hooks))
|
||||
}
|
||||
RawPluginManifestHooks::Invalid(value) => {
|
||||
tracing::warn!(
|
||||
let message = format!(
|
||||
"ignoring hooks: expected a string, string array, object, or object array; found {}",
|
||||
json_value_type(&value)
|
||||
);
|
||||
tracing::warn!("{message}");
|
||||
issues.push(message);
|
||||
None
|
||||
}
|
||||
}
|
||||
@@ -301,17 +378,19 @@ fn resolve_interface_asset_path(
|
||||
plugin_root: &Path,
|
||||
field: &'static str,
|
||||
path: Option<&str>,
|
||||
issues: &mut Vec<String>,
|
||||
) -> Option<AbsolutePathBuf> {
|
||||
resolve_manifest_path(plugin_root, field, path)
|
||||
resolve_manifest_path(plugin_root, field, path, issues)
|
||||
}
|
||||
|
||||
fn resolve_default_prompts(
|
||||
plugin_root: &Path,
|
||||
value: Option<&RawPluginManifestDefaultPrompt>,
|
||||
issues: &mut Vec<String>,
|
||||
) -> Option<Vec<String>> {
|
||||
match value? {
|
||||
RawPluginManifestDefaultPrompt::String(prompt) => {
|
||||
resolve_default_prompt_str(plugin_root, "interface.defaultPrompt", prompt)
|
||||
resolve_default_prompt_str(plugin_root, "interface.defaultPrompt", prompt, issues)
|
||||
.map(|prompt| vec![prompt])
|
||||
}
|
||||
RawPluginManifestDefaultPrompt::List(values) => {
|
||||
@@ -322,6 +401,7 @@ fn resolve_default_prompts(
|
||||
plugin_root,
|
||||
"interface.defaultPrompt",
|
||||
&format!("maximum of {MAX_DEFAULT_PROMPT_COUNT} prompts is supported"),
|
||||
issues,
|
||||
);
|
||||
break;
|
||||
}
|
||||
@@ -330,7 +410,7 @@ fn resolve_default_prompts(
|
||||
RawPluginManifestDefaultPromptEntry::String(prompt) => {
|
||||
let field = format!("interface.defaultPrompt[{index}]");
|
||||
if let Some(prompt) =
|
||||
resolve_default_prompt_str(plugin_root, &field, prompt)
|
||||
resolve_default_prompt_str(plugin_root, &field, prompt, issues)
|
||||
{
|
||||
prompts.push(prompt);
|
||||
}
|
||||
@@ -341,6 +421,7 @@ fn resolve_default_prompts(
|
||||
plugin_root,
|
||||
&field,
|
||||
&format!("expected a string, found {}", json_value_type(value)),
|
||||
issues,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -356,16 +437,22 @@ fn resolve_default_prompts(
|
||||
"expected a string or array of strings, found {}",
|
||||
json_value_type(value)
|
||||
),
|
||||
issues,
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_default_prompt_str(plugin_root: &Path, field: &str, prompt: &str) -> Option<String> {
|
||||
fn resolve_default_prompt_str(
|
||||
plugin_root: &Path,
|
||||
field: &str,
|
||||
prompt: &str,
|
||||
issues: &mut Vec<String>,
|
||||
) -> Option<String> {
|
||||
let prompt = prompt.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||
if prompt.is_empty() {
|
||||
warn_invalid_default_prompt(plugin_root, field, "prompt must not be empty");
|
||||
warn_invalid_default_prompt(plugin_root, field, "prompt must not be empty", issues);
|
||||
return None;
|
||||
}
|
||||
if prompt.chars().count() > MAX_DEFAULT_PROMPT_LEN {
|
||||
@@ -373,13 +460,20 @@ fn resolve_default_prompt_str(plugin_root: &Path, field: &str, prompt: &str) ->
|
||||
plugin_root,
|
||||
field,
|
||||
&format!("prompt must be at most {MAX_DEFAULT_PROMPT_LEN} characters"),
|
||||
issues,
|
||||
);
|
||||
return None;
|
||||
}
|
||||
Some(prompt)
|
||||
}
|
||||
|
||||
fn warn_invalid_default_prompt(plugin_root: &Path, field: &str, message: &str) {
|
||||
fn warn_invalid_default_prompt(
|
||||
plugin_root: &Path,
|
||||
field: &str,
|
||||
message: &str,
|
||||
issues: &mut Vec<String>,
|
||||
) {
|
||||
issues.push(format!("ignoring {field}: {message}"));
|
||||
if let Some(manifest_path) = find_plugin_manifest_path(plugin_root) {
|
||||
tracing::warn!(
|
||||
path = %manifest_path.display(),
|
||||
@@ -405,14 +499,19 @@ fn resolve_manifest_path_value(
|
||||
plugin_root: &Path,
|
||||
field: &'static str,
|
||||
path: Option<&RawPluginManifestPath>,
|
||||
issues: &mut Vec<String>,
|
||||
) -> Option<AbsolutePathBuf> {
|
||||
match path? {
|
||||
RawPluginManifestPath::Path(path) => resolve_manifest_path(plugin_root, field, Some(path)),
|
||||
RawPluginManifestPath::Path(path) => {
|
||||
resolve_manifest_path(plugin_root, field, Some(path), issues)
|
||||
}
|
||||
RawPluginManifestPath::Invalid(value) => {
|
||||
tracing::warn!(
|
||||
let message = format!(
|
||||
"ignoring {field}: expected a string; found {}",
|
||||
json_value_type(value)
|
||||
);
|
||||
tracing::warn!("{message}");
|
||||
issues.push(message);
|
||||
None
|
||||
}
|
||||
}
|
||||
@@ -422,19 +521,25 @@ fn resolve_manifest_path(
|
||||
plugin_root: &Path,
|
||||
field: &'static str,
|
||||
path: Option<&str>,
|
||||
issues: &mut Vec<String>,
|
||||
) -> Option<AbsolutePathBuf> {
|
||||
// `plugin.json` paths are required to be relative to the plugin root and we return the
|
||||
// normalized absolute path to the rest of the system.
|
||||
let path = path?;
|
||||
if path.is_empty() {
|
||||
issues.push(format!("ignoring {field}: path must not be empty"));
|
||||
return None;
|
||||
}
|
||||
let Some(relative_path) = path.strip_prefix("./") else {
|
||||
tracing::warn!("ignoring {field}: path must start with `./` relative to plugin root");
|
||||
issues.push(format!(
|
||||
"ignoring {field}: path must start with `./` relative to plugin root"
|
||||
));
|
||||
return None;
|
||||
};
|
||||
if relative_path.is_empty() {
|
||||
tracing::warn!("ignoring {field}: path must not be `./`");
|
||||
issues.push(format!("ignoring {field}: path must not be `./`"));
|
||||
return None;
|
||||
}
|
||||
|
||||
@@ -444,21 +549,28 @@ fn resolve_manifest_path(
|
||||
Component::Normal(component) => normalized.push(component),
|
||||
Component::ParentDir => {
|
||||
tracing::warn!("ignoring {field}: path must not contain '..'");
|
||||
issues.push(format!("ignoring {field}: path must not contain '..'"));
|
||||
return None;
|
||||
}
|
||||
_ => {
|
||||
tracing::warn!("ignoring {field}: path must stay within the plugin root");
|
||||
issues.push(format!(
|
||||
"ignoring {field}: path must stay within the plugin root"
|
||||
));
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
AbsolutePathBuf::try_from(plugin_root.join(normalized))
|
||||
.map_err(|err| {
|
||||
tracing::warn!("ignoring {field}: path must resolve to an absolute path: {err}");
|
||||
err
|
||||
})
|
||||
.ok()
|
||||
match AbsolutePathBuf::try_from(plugin_root.join(normalized)) {
|
||||
Ok(path) => Some(path),
|
||||
Err(err) => {
|
||||
let message = format!("ignoring {field}: path must resolve to an absolute path: {err}");
|
||||
tracing::warn!("{message}");
|
||||
issues.push(message);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -646,3 +758,7 @@ mod tests {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "manifest_diagnostics_tests.rs"]
|
||||
mod diagnostic_tests;
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
use super::diagnose_plugin_manifest;
|
||||
use std::fs;
|
||||
use tempfile::tempdir;
|
||||
|
||||
#[test]
|
||||
fn diagnostics_explain_ignored_capability_paths() {
|
||||
let tmp = tempdir().expect("tempdir");
|
||||
let plugin_root = tmp.path().join("plugin");
|
||||
let manifest_path = plugin_root.join(".claude-plugin/plugin.json");
|
||||
fs::create_dir_all(manifest_path.parent().expect("manifest parent"))
|
||||
.expect("create manifest directory");
|
||||
fs::write(
|
||||
manifest_path,
|
||||
r#"{
|
||||
"name": "plugin",
|
||||
"skills": "../outside",
|
||||
"hooks": 7,
|
||||
"commands": "./commands"
|
||||
}"#,
|
||||
)
|
||||
.expect("write manifest");
|
||||
|
||||
let diagnostics = diagnose_plugin_manifest(&plugin_root);
|
||||
let manifest = diagnostics.manifest.expect("partially valid manifest");
|
||||
|
||||
assert!(manifest.paths.skills.is_none());
|
||||
assert!(manifest.paths.hooks.is_none());
|
||||
assert!(
|
||||
diagnostics
|
||||
.issues
|
||||
.iter()
|
||||
.any(|issue| issue.contains("skills") && issue.contains("start with `./`"))
|
||||
);
|
||||
assert_eq!(
|
||||
diagnostics.unsupported_capability_fields,
|
||||
vec!["commands".to_string()]
|
||||
);
|
||||
assert!(
|
||||
diagnostics
|
||||
.issues
|
||||
.iter()
|
||||
.any(|issue| issue.contains("hooks") && issue.contains("found number"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diagnostics_explain_missing_manifest() {
|
||||
let tmp = tempdir().expect("tempdir");
|
||||
let diagnostics = diagnose_plugin_manifest(tmp.path());
|
||||
|
||||
assert!(diagnostics.manifest.is_none());
|
||||
assert_eq!(diagnostics.issues.len(), 1);
|
||||
assert!(diagnostics.issues[0].contains("does not contain"));
|
||||
}
|
||||
@@ -66,6 +66,30 @@ pub struct MarketplacePlugin {
|
||||
pub keywords: Vec<String>,
|
||||
}
|
||||
|
||||
/// One raw marketplace entry resolved independently for support diagnostics.
|
||||
///
|
||||
/// Unlike [`load_marketplace`], this preserves a result for malformed entries instead of
|
||||
/// rejecting or silently skipping them with the rest of the marketplace.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct MarketplacePluginDiagnostic {
|
||||
pub index: usize,
|
||||
pub name: Option<String>,
|
||||
pub source_kind: &'static str,
|
||||
pub result: Result<ResolvedMarketplacePlugin, MarketplacePluginDiagnosticError>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct MarketplacePluginDiagnosticError {
|
||||
pub code: &'static str,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct MarketplaceDiagnostics {
|
||||
pub name: String,
|
||||
pub plugins: Vec<MarketplacePluginDiagnostic>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum MarketplacePluginSource {
|
||||
Local {
|
||||
@@ -327,6 +351,197 @@ pub fn load_marketplace(path: &AbsolutePathBuf) -> Result<Marketplace, Marketpla
|
||||
})
|
||||
}
|
||||
|
||||
/// Resolve every raw plugin entry without allowing one malformed entry to hide the others.
|
||||
///
|
||||
/// This is intentionally separate from the normal marketplace loader: callers can compare this
|
||||
/// output with [`load_marketplace`] to explain both whole-file failures and per-entry skips.
|
||||
#[doc(hidden)]
|
||||
pub fn diagnose_marketplace(
|
||||
path: &AbsolutePathBuf,
|
||||
) -> Result<MarketplaceDiagnostics, MarketplaceError> {
|
||||
let contents = fs::read_to_string(path.as_path()).map_err(|err| {
|
||||
if err.kind() == io::ErrorKind::NotFound {
|
||||
MarketplaceError::MarketplaceNotFound {
|
||||
path: path.to_path_buf(),
|
||||
}
|
||||
} else {
|
||||
MarketplaceError::io("failed to read marketplace file", err)
|
||||
}
|
||||
})?;
|
||||
let value = serde_json::from_str::<JsonValue>(&contents).map_err(|err| {
|
||||
MarketplaceError::InvalidMarketplaceFile {
|
||||
path: path.to_path_buf(),
|
||||
message: err.to_string(),
|
||||
}
|
||||
})?;
|
||||
let object = value
|
||||
.as_object()
|
||||
.ok_or_else(|| MarketplaceError::InvalidMarketplaceFile {
|
||||
path: path.to_path_buf(),
|
||||
message: "expected a JSON object".to_string(),
|
||||
})?;
|
||||
let name = object
|
||||
.get("name")
|
||||
.and_then(JsonValue::as_str)
|
||||
.filter(|name| !name.trim().is_empty())
|
||||
.ok_or_else(|| MarketplaceError::InvalidMarketplaceFile {
|
||||
path: path.to_path_buf(),
|
||||
message: "marketplace name must be a non-empty string".to_string(),
|
||||
})?
|
||||
.to_string();
|
||||
let raw_plugins = object
|
||||
.get("plugins")
|
||||
.and_then(JsonValue::as_array)
|
||||
.ok_or_else(|| MarketplaceError::InvalidMarketplaceFile {
|
||||
path: path.to_path_buf(),
|
||||
message: "marketplace plugins must be an array".to_string(),
|
||||
})?;
|
||||
|
||||
let plugins = raw_plugins
|
||||
.iter()
|
||||
.cloned()
|
||||
.enumerate()
|
||||
.map(|(index, value)| diagnose_marketplace_plugin_entry(path, &name, index, value))
|
||||
.collect();
|
||||
Ok(MarketplaceDiagnostics { name, plugins })
|
||||
}
|
||||
|
||||
fn diagnose_marketplace_plugin_entry(
|
||||
marketplace_path: &AbsolutePathBuf,
|
||||
marketplace_name: &str,
|
||||
index: usize,
|
||||
value: JsonValue,
|
||||
) -> MarketplacePluginDiagnostic {
|
||||
let name = value
|
||||
.as_object()
|
||||
.and_then(|object| object.get("name"))
|
||||
.and_then(JsonValue::as_str)
|
||||
.map(str::to_string);
|
||||
let source_kind = diagnostic_source_kind(&value);
|
||||
let plugin = match serde_json::from_value::<RawMarketplaceManifestPlugin>(value) {
|
||||
Ok(plugin) => plugin,
|
||||
Err(err) => {
|
||||
return MarketplacePluginDiagnostic {
|
||||
index,
|
||||
name,
|
||||
source_kind,
|
||||
result: Err(MarketplacePluginDiagnosticError {
|
||||
code: "invalid_entry",
|
||||
message: err.to_string(),
|
||||
}),
|
||||
};
|
||||
}
|
||||
};
|
||||
let RawMarketplaceManifestPlugin {
|
||||
name: plugin_name,
|
||||
source,
|
||||
policy,
|
||||
category,
|
||||
} = plugin;
|
||||
let source = match source {
|
||||
RawMarketplaceManifestPluginSource::Unsupported(value) => {
|
||||
return MarketplacePluginDiagnostic {
|
||||
index,
|
||||
name: Some(plugin_name),
|
||||
source_kind,
|
||||
result: Err(MarketplacePluginDiagnosticError {
|
||||
code: "unsupported_source",
|
||||
message: format!(
|
||||
"unsupported plugin source value type: {}",
|
||||
json_value_type(&value)
|
||||
),
|
||||
}),
|
||||
};
|
||||
}
|
||||
source => match resolve_plugin_source(marketplace_path, source) {
|
||||
Ok(source) => source,
|
||||
Err(err) => {
|
||||
return MarketplacePluginDiagnostic {
|
||||
index,
|
||||
name: Some(plugin_name),
|
||||
source_kind,
|
||||
result: Err(MarketplacePluginDiagnosticError {
|
||||
code: "invalid_source",
|
||||
message: err.to_string(),
|
||||
}),
|
||||
};
|
||||
}
|
||||
},
|
||||
};
|
||||
let plugin_id = match PluginId::new(plugin_name.clone(), marketplace_name.to_string()) {
|
||||
Ok(plugin_id) => plugin_id,
|
||||
Err(PluginIdError::Invalid(message)) => {
|
||||
return MarketplacePluginDiagnostic {
|
||||
index,
|
||||
name: Some(plugin_name),
|
||||
source_kind,
|
||||
result: Err(MarketplacePluginDiagnosticError {
|
||||
code: "invalid_plugin_id",
|
||||
message,
|
||||
}),
|
||||
};
|
||||
}
|
||||
};
|
||||
let manifest = match &source {
|
||||
MarketplacePluginSource::Local { path } => load_plugin_manifest(path.as_path()),
|
||||
MarketplacePluginSource::Git { .. } => None,
|
||||
};
|
||||
let interface = plugin_interface_with_marketplace_category(
|
||||
manifest
|
||||
.as_ref()
|
||||
.and_then(|manifest| manifest.interface.clone()),
|
||||
category,
|
||||
);
|
||||
|
||||
MarketplacePluginDiagnostic {
|
||||
index,
|
||||
name: Some(plugin_name),
|
||||
source_kind,
|
||||
result: Ok(ResolvedMarketplacePlugin {
|
||||
plugin_id,
|
||||
source,
|
||||
policy: MarketplacePluginPolicy {
|
||||
installation: policy.installation,
|
||||
authentication: policy.authentication,
|
||||
products: policy.products,
|
||||
},
|
||||
interface,
|
||||
manifest,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn diagnostic_source_kind(value: &JsonValue) -> &'static str {
|
||||
let Some(source) = value.as_object().and_then(|object| object.get("source")) else {
|
||||
return "missing";
|
||||
};
|
||||
match source {
|
||||
JsonValue::String(_) => "local_path",
|
||||
JsonValue::Object(object) => match object.get("source").and_then(JsonValue::as_str) {
|
||||
Some("local") => "local",
|
||||
Some("url") => "git_url",
|
||||
Some("git-subdir") => "git_subdir",
|
||||
Some(_) => "unsupported_object",
|
||||
None => "object_without_source_type",
|
||||
},
|
||||
JsonValue::Null => "null",
|
||||
JsonValue::Bool(_) => "boolean",
|
||||
JsonValue::Number(_) => "number",
|
||||
JsonValue::Array(_) => "array",
|
||||
}
|
||||
}
|
||||
|
||||
fn json_value_type(value: &JsonValue) -> &'static str {
|
||||
match value {
|
||||
JsonValue::Null => "null",
|
||||
JsonValue::Bool(_) => "boolean",
|
||||
JsonValue::Number(_) => "number",
|
||||
JsonValue::String(_) => "string",
|
||||
JsonValue::Array(_) => "array",
|
||||
JsonValue::Object(_) => "object",
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn load_raw_marketplace_plugin_names(
|
||||
path: &AbsolutePathBuf,
|
||||
) -> Result<HashSet<String>, MarketplaceError> {
|
||||
@@ -509,8 +724,8 @@ fn resolve_plugin_source(
|
||||
.as_deref()
|
||||
.map(|path| normalize_remote_plugin_subdir(marketplace_path, path))
|
||||
.transpose()?,
|
||||
ref_name: normalize_optional_git_selector(&ref_name),
|
||||
sha: normalize_optional_git_selector(&sha),
|
||||
ref_name: normalize_optional_git_selector(marketplace_path, "ref", &ref_name)?,
|
||||
sha: normalize_optional_git_selector(marketplace_path, "sha", &sha)?,
|
||||
}),
|
||||
RawMarketplaceManifestPluginSource::Object(
|
||||
RawMarketplaceManifestPluginSourceObject::GitSubdir {
|
||||
@@ -522,8 +737,8 @@ 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)?),
|
||||
ref_name: normalize_optional_git_selector(&ref_name),
|
||||
sha: normalize_optional_git_selector(&sha),
|
||||
ref_name: normalize_optional_git_selector(marketplace_path, "ref", &ref_name)?,
|
||||
sha: normalize_optional_git_selector(marketplace_path, "sha", &sha)?,
|
||||
}),
|
||||
RawMarketplaceManifestPluginSource::Unsupported(_) => {
|
||||
unreachable!("unsupported plugin sources should be filtered before resolution")
|
||||
@@ -576,6 +791,12 @@ fn normalize_remote_plugin_subdir(
|
||||
message: "git plugin source path must not be empty".to_string(),
|
||||
});
|
||||
}
|
||||
if path.chars().any(char::is_control) {
|
||||
return Err(MarketplaceError::InvalidMarketplaceFile {
|
||||
path: marketplace_path.to_path_buf(),
|
||||
message: "git plugin source path must not contain control characters".to_string(),
|
||||
});
|
||||
}
|
||||
let relative_path = Path::new(path);
|
||||
if relative_path
|
||||
.components()
|
||||
@@ -600,6 +821,12 @@ fn normalize_git_plugin_source_url(
|
||||
message: "git plugin source url must not be empty".to_string(),
|
||||
});
|
||||
}
|
||||
if url.chars().any(char::is_control) {
|
||||
return Err(MarketplaceError::InvalidMarketplaceFile {
|
||||
path: marketplace_path.to_path_buf(),
|
||||
message: "git plugin source url must not contain control characters".to_string(),
|
||||
});
|
||||
}
|
||||
if url.starts_with("http://") || url.starts_with("https://") {
|
||||
return Ok(normalize_github_git_url(url));
|
||||
}
|
||||
@@ -622,7 +849,7 @@ fn normalize_git_plugin_source_url(
|
||||
|
||||
Err(MarketplaceError::InvalidMarketplaceFile {
|
||||
path: marketplace_path.to_path_buf(),
|
||||
message: format!("invalid git plugin source url: {url}"),
|
||||
message: "invalid git plugin source url format".to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -649,12 +876,26 @@ fn normalize_relative_git_plugin_source_url(
|
||||
Ok(normalized.display().to_string())
|
||||
}
|
||||
|
||||
fn normalize_optional_git_selector(value: &Option<String>) -> Option<String> {
|
||||
value
|
||||
fn normalize_optional_git_selector(
|
||||
marketplace_path: &AbsolutePathBuf,
|
||||
field: &str,
|
||||
value: &Option<String>,
|
||||
) -> Result<Option<String>, MarketplaceError> {
|
||||
let value = value
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(str::to_string)
|
||||
.map(str::to_string);
|
||||
if value
|
||||
.as_deref()
|
||||
.is_some_and(|value| value.chars().any(char::is_control))
|
||||
{
|
||||
return Err(MarketplaceError::InvalidMarketplaceFile {
|
||||
path: marketplace_path.to_path_buf(),
|
||||
message: format!("git plugin source {field} must not contain control characters"),
|
||||
});
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn normalize_github_git_url(url: &str) -> String {
|
||||
|
||||
@@ -280,6 +280,36 @@ fn normalize_relative_git_plugin_source_url_rejects_parent_traversal() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn git_source_validation_does_not_echo_invalid_values() {
|
||||
let tmp = tempdir().unwrap();
|
||||
let marketplace_path =
|
||||
AbsolutePathBuf::try_from(tmp.path().join("repo/.agents/plugins/marketplace.json"))
|
||||
.unwrap();
|
||||
|
||||
let invalid_url = "rippling-private-source";
|
||||
let err = normalize_git_plugin_source_url(&marketplace_path, invalid_url).unwrap_err();
|
||||
assert_eq!(
|
||||
err.to_string(),
|
||||
format!(
|
||||
"invalid marketplace file `{}`: invalid git plugin source url format",
|
||||
marketplace_path.display()
|
||||
)
|
||||
);
|
||||
assert!(!err.to_string().contains(invalid_url));
|
||||
|
||||
let invalid_ref = Some("private-ref\nsecond-line".to_string());
|
||||
let err = normalize_optional_git_selector(&marketplace_path, "ref", &invalid_ref).unwrap_err();
|
||||
assert_eq!(
|
||||
err.to_string(),
|
||||
format!(
|
||||
"invalid marketplace file `{}`: git plugin source ref must not contain control characters",
|
||||
marketplace_path.display()
|
||||
)
|
||||
);
|
||||
assert!(!err.to_string().contains("private-ref"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_marketplace_plugin_skips_root_equivalent_git_subdir_paths() {
|
||||
for path in [".", "./", "plugins/.."] {
|
||||
@@ -1554,3 +1584,35 @@ fn find_installable_marketplace_plugin_rejects_explicit_empty_products() {
|
||||
"plugin `disabled-plugin` is not available for install in marketplace `codex-curated`"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diagnose_marketplace_preserves_results_after_malformed_entries() {
|
||||
let tmp = tempdir().unwrap();
|
||||
let repo_root = tmp.path().join("repo");
|
||||
let marketplace_path = write_alternate_marketplace(
|
||||
&repo_root,
|
||||
r#"{
|
||||
"name": "diagnostic",
|
||||
"plugins": [
|
||||
{ "name": "valid", "source": "./plugins/valid" },
|
||||
{ "name": "missing-source" },
|
||||
{ "name": "invalid-source", "source": "plugins/invalid" }
|
||||
]
|
||||
}"#,
|
||||
);
|
||||
|
||||
let diagnostics = diagnose_marketplace(&marketplace_path).unwrap();
|
||||
|
||||
assert_eq!(diagnostics.name, "diagnostic");
|
||||
assert_eq!(diagnostics.plugins.len(), 3);
|
||||
assert!(diagnostics.plugins[0].result.is_ok());
|
||||
assert_eq!(
|
||||
diagnostics.plugins[1].result.as_ref().unwrap_err().code,
|
||||
"invalid_entry"
|
||||
);
|
||||
assert_eq!(
|
||||
diagnostics.plugins[2].result.as_ref().unwrap_err().code,
|
||||
"invalid_source"
|
||||
);
|
||||
assert!(load_marketplace(&marketplace_path).is_err());
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user