diff --git a/codex-rs/cli/src/main.rs b/codex-rs/cli/src/main.rs index c4560c2328..d641cd5e24 100644 --- a/codex-rs/cli/src/main.rs +++ b/codex-rs/cli/src/main.rs @@ -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) => { diff --git a/codex-rs/cli/src/plugin_import_diagnostic.rs b/codex-rs/cli/src/plugin_import_diagnostic.rs new file mode 100644 index 0000000000..3b9d196cfc --- /dev/null +++ b/codex-rs/cli/src/plugin_import_diagnostic.rs @@ -0,0 +1,1237 @@ +use anyhow::Context; +use anyhow::Result; +use clap::Parser; +use codex_core_plugins::PluginInstallRequest; +use codex_core_plugins::PluginsManager; +use codex_core_plugins::loader::diagnose_plugin_apps; +use codex_core_plugins::loader::diagnose_plugin_mcp_servers; +use codex_core_plugins::loader::load_plugin_hooks; +use codex_core_plugins::loader::load_plugin_skills; +use codex_core_plugins::manifest::diagnose_plugin_manifest; +use codex_core_plugins::marketplace::MarketplacePluginAuthPolicy; +use codex_core_plugins::marketplace::MarketplacePluginInstallPolicy; +use codex_core_plugins::marketplace::MarketplacePluginSource; +use codex_core_plugins::marketplace::ResolvedMarketplacePlugin; +use codex_core_plugins::marketplace::diagnose_marketplace; +use codex_core_plugins::marketplace::find_marketplace_manifest_path; +use codex_core_plugins::marketplace::load_marketplace; +use codex_core_plugins::store::PluginStore; +use codex_protocol::protocol::Product; +use codex_utils_absolute_path::AbsolutePathBuf; +use serde_json::Value; +use serde_json::json; +use std::collections::HashMap; +use std::collections::HashSet; +use std::collections::VecDeque; +use std::fs::File; +use std::fs::OpenOptions; +use std::io::BufWriter; +use std::io::Write; +use std::path::Path; +use std::path::PathBuf; +use std::sync::OnceLock; +use std::time::SystemTime; +use std::time::UNIX_EPOCH; + +const REPORT_SCHEMA_VERSION: u32 = 1; +const MAX_DETAIL_CHARS: usize = 4_096; +const MAX_SKILL_SCAN_DEPTH: usize = 6; +const MAX_SKILL_SCAN_DIRS: usize = 2_000; +const MAX_SKILL_SCAN_ISSUES: usize = 1_000; + +#[derive(Debug, Parser)] +#[command( + bin_name = "codex debug marketplace-import-diagnostic", + about = "Generate a redacted per-plugin marketplace import diagnostic" +)] +pub(crate) struct MarketplaceImportDiagnosticCommand { + /// Marketplace repository root containing .claude-plugin/marketplace.json or + /// .agents/plugins/marketplace.json. + #[arg(value_name = "MARKETPLACE_ROOT")] + marketplace_root: PathBuf, + + /// New JSONL report path. Each record is flushed immediately so partial reports survive failures. + #[arg(long, value_name = "JSONL_PATH")] + output: PathBuf, + + /// Exercise the real plugin installer in an isolated temporary Codex home. + #[arg(long, default_value_t = false)] + attempt_install: bool, +} + +#[derive(Default)] +struct Summary { + raw_entries: usize, + detected_entries: usize, + detection_failures: usize, + eligible_entries: usize, + installed_entries: usize, + install_failures: usize, + install_skips: usize, + entries_with_capability_issues: usize, + entries_without_capabilities: usize, +} + +pub(crate) async fn run(command: MarketplaceImportDiagnosticCommand) -> Result<()> { + if let Some(parent) = command.output.parent() + && !parent.as_os_str().is_empty() + { + std::fs::create_dir_all(parent) + .with_context(|| format!("failed to create report directory {}", parent.display()))?; + } + let diagnostic_home = tempfile::Builder::new() + .prefix("codex-marketplace-import-diagnostic-") + .tempdir() + .context("failed to create isolated diagnostic CODEX_HOME")?; + let requested_root = if command.marketplace_root.is_absolute() { + command.marketplace_root.clone() + } else { + std::env::current_dir() + .context("failed to resolve current directory")? + .join(&command.marketplace_root) + }; + let file = create_report_file(&command.output)?; + let mut writer = BufWriter::new(file); + let mut redactor = Redactor::new(&requested_root, diagnostic_home.path()); + write_record( + &mut writer, + &json!({ + "schemaVersion": REPORT_SCHEMA_VERSION, + "event": "run_started", + "unixTimeSeconds": SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs(), + "codexVersion": env!("CARGO_PKG_VERSION"), + "buildCommit": option_env!("CODEX_BUILD_COMMIT") + .or(option_env!("GIT_COMMIT")) + .unwrap_or("unknown"), + "platform": { "os": std::env::consts::OS, "arch": std::env::consts::ARCH }, + "marketplaceRoot": "", + "attemptInstall": command.attempt_install, + "isolatedCodexHome": true, + "scope": "checked_out_marketplace_enumeration_installation_and_capabilities", + "notInspected": ["claude_settings_selection", "marketplace_clone_or_auth"], + "privacy": { + "pluginContentsIncluded": false, + "environmentValuesIncluded": false, + "configContentsIncluded": false, + "rawCommandArgumentsIncluded": false, + "sanitizedErrorMessagesIncluded": true, + "identifiersIncluded": [ + "marketplace", + "plugin", + "skill", + "mcp_server", + "app_connector", + "relative_capability_path" + ] + } + }), + )?; + + let marketplace_root = match std::fs::canonicalize(&command.marketplace_root) { + Ok(path) => path, + Err(err) => { + return finish_preflight_failure( + &mut writer, + &command.output, + "marketplace_root_unavailable", + &redactor.detail(&err.to_string()), + ); + } + }; + let marketplace_root = match AbsolutePathBuf::try_from(marketplace_root) { + Ok(path) => path, + Err(err) => { + return finish_preflight_failure( + &mut writer, + &command.output, + "marketplace_root_not_absolute", + &redactor.detail(&err.to_string()), + ); + } + }; + redactor.add_replacement(marketplace_root.as_path(), ""); + let Some(marketplace_path) = find_marketplace_manifest_path(marketplace_root.as_path()) else { + return finish_preflight_failure( + &mut writer, + &command.output, + "marketplace_manifest_not_found", + "marketplace root does not contain .claude-plugin/marketplace.json or .agents/plugins/marketplace.json", + ); + }; + + let production_load = match load_marketplace(&marketplace_path) { + Ok(marketplace) => json!({ + "status": "ok", + "detectedPluginCount": marketplace.plugins.len() + }), + Err(err) => json!({ + "status": "error", + "code": "production_marketplace_load_failed", + "detail": redactor.detail(&err.to_string()) + }), + }; + let diagnostics = match diagnose_marketplace(&marketplace_path) { + Ok(diagnostics) => diagnostics, + Err(err) => { + write_record( + &mut writer, + &json!({ + "schemaVersion": REPORT_SCHEMA_VERSION, + "event": "marketplace_diagnostic", + "marketplaceManifest": relative_path(&marketplace_path, &marketplace_root, &redactor), + "productionLoader": production_load, + "status": "error", + "code": "diagnostic_marketplace_parse_failed", + "detail": redactor.detail(&err.to_string()) + }), + )?; + write_record( + &mut writer, + &json!({ + "schemaVersion": REPORT_SCHEMA_VERSION, + "event": "run_completed", + "status": "report_complete_marketplace_unreadable", + "summary": summary_json(&Summary::default()) + }), + )?; + println!( + "Marketplace import diagnostic written to {}", + command.output.display() + ); + return Ok(()); + } + }; + + let duplicate_names = duplicate_name_counts(&diagnostics.plugins); + write_record( + &mut writer, + &json!({ + "schemaVersion": REPORT_SCHEMA_VERSION, + "event": "marketplace_diagnostic", + "status": "ok", + "marketplaceManifest": relative_path(&marketplace_path, &marketplace_root, &redactor), + "marketplaceName": diagnostics.name, + "rawPluginEntryCount": diagnostics.plugins.len(), + "duplicatePluginNames": duplicate_names, + "productionLoader": production_load + }), + )?; + + let manager = PluginsManager::new(diagnostic_home.path().to_path_buf()); + let store = PluginStore::new(diagnostic_home.path().to_path_buf()); + let mut summary = Summary { + raw_entries: diagnostics.plugins.len(), + ..Default::default() + }; + let mut seen_plugin_names = HashSet::new(); + + for entry in diagnostics.plugins { + let entry_index = entry.index; + let source_kind = entry.source_kind; + let entry_name = entry + .name + .clone() + .unwrap_or_else(|| format!("")); + write_record( + &mut writer, + &json!({ + "schemaVersion": REPORT_SCHEMA_VERSION, + "event": "plugin_started", + "entryIndex": entry_index, + "pluginName": entry_name, + "sourceKind": source_kind + }), + )?; + let resolved = match entry.result { + Ok(resolved) => resolved, + Err(err) => { + summary.detection_failures += 1; + write_record( + &mut writer, + &json!({ + "schemaVersion": REPORT_SCHEMA_VERSION, + "event": "plugin_diagnostic", + "entryIndex": entry_index, + "pluginName": entry_name, + "sourceKind": source_kind, + "outcome": "not_detected", + "detection": { + "status": "error", + "code": err.code, + "detail": redactor.detail(&err.message) + }, + "eligibility": null, + "install": null, + "capabilities": null + }), + )?; + continue; + } + }; + + summary.detected_entries += 1; + let is_duplicate = !seen_plugin_names.insert(resolved.plugin_id.plugin_name.clone()); + let eligible = plugin_is_eligible(&resolved); + if eligible && !is_duplicate { + summary.eligible_entries += 1; + } + + let (install, installed_root, outcome) = if is_duplicate { + summary.install_skips += 1; + ( + json!({ + "status": "skipped", + "code": "duplicate_plugin_name", + "detail": "plugin lookup resolves the first marketplace entry with this name" + }), + None, + "detected_not_selectable", + ) + } else if !eligible { + summary.install_skips += 1; + ( + json!({ + "status": "skipped", + "code": eligibility_failure_code(&resolved), + "detail": eligibility_failure_detail(&resolved) + }), + None, + "detected_not_eligible", + ) + } else if !command.attempt_install { + summary.install_skips += 1; + ( + json!({ + "status": "skipped", + "code": "install_not_requested", + "detail": "the diagnostic was run without --attempt-install" + }), + None, + "detected_only", + ) + } else { + write_plugin_stage( + &mut writer, + entry_index, + &resolved.plugin_id.plugin_name, + "install", + )?; + match manager + .install_plugin(PluginInstallRequest { + plugin_name: resolved.plugin_id.plugin_name.clone(), + marketplace_path: marketplace_path.clone(), + }) + .await + { + Ok(installed) => { + summary.installed_entries += 1; + ( + json!({ + "status": "ok", + "code": "installed", + "version": installed.plugin_version + }), + Some(installed.installed_path), + "installed", + ) + } + Err(err) => { + summary.install_failures += 1; + ( + install_failure_diagnostic(&resolved, &err.to_string(), &redactor), + None, + "install_failed", + ) + } + } + }; + + let source_root = installed_root.or_else(|| match &resolved.source { + MarketplacePluginSource::Local { path } => Some(path.clone()), + MarketplacePluginSource::Git { .. } => None, + }); + let capabilities = match source_root { + Some(root) => { + write_plugin_stage( + &mut writer, + entry_index, + &resolved.plugin_id.plugin_name, + "capabilities", + )?; + let result = diagnose_capabilities(&root, &resolved, &store, &redactor).await; + if result.issue_count > 0 { + summary.entries_with_capability_issues += 1; + } + if !result.has_capabilities { + summary.entries_without_capabilities += 1; + } + result.value + } + None => json!({ + "status": "unavailable", + "code": "source_not_materialized", + "detail": "remote plugin capabilities cannot be inspected because installation did not succeed" + }), + }; + + write_record( + &mut writer, + &json!({ + "schemaVersion": REPORT_SCHEMA_VERSION, + "event": "plugin_diagnostic", + "entryIndex": entry_index, + "pluginName": resolved.plugin_id.plugin_name, + "pluginId": resolved.plugin_id.as_key(), + "sourceKind": source_kind, + "outcome": outcome, + "detection": { + "status": "ok", + "code": if is_duplicate { "detected_duplicate_name" } else { "detected" } + }, + "eligibility": { + "status": if eligible && !is_duplicate { "ok" } else { "skipped" }, + "installationPolicy": installation_policy_name(resolved.policy.installation), + "authenticationPolicy": authentication_policy_name(resolved.policy.authentication), + "productPolicy": product_policy_names(resolved.policy.products.as_deref()), + "code": if is_duplicate { + Some("duplicate_plugin_name") + } else if eligible { + None + } else { + Some(eligibility_failure_code(&resolved)) + } + }, + "install": install, + "capabilities": capabilities + }), + )?; + } + + write_record( + &mut writer, + &json!({ + "schemaVersion": REPORT_SCHEMA_VERSION, + "event": "run_completed", + "status": "report_complete", + "summary": summary_json(&summary) + }), + )?; + println!( + "Marketplace import diagnostic written to {} ({} entries, {} installed, {} install failures)", + command.output.display(), + summary.raw_entries, + summary.installed_entries, + summary.install_failures + ); + Ok(()) +} + +struct CapabilityResult { + value: Value, + issue_count: usize, + has_capabilities: bool, +} + +async fn diagnose_capabilities( + plugin_root: &AbsolutePathBuf, + resolved: &ResolvedMarketplacePlugin, + store: &PluginStore, + redactor: &Redactor, +) -> CapabilityResult { + let manifest_diagnostic = diagnose_plugin_manifest(plugin_root.as_path()); + let manifest_path = manifest_diagnostic + .manifest_path + .as_deref() + .map(|path| relative_path_from_path(path, plugin_root, redactor)); + let manifest_issues = manifest_diagnostic + .issues + .iter() + .map(|issue| redactor.detail(issue)) + .collect::>(); + let unsupported_capability_fields = manifest_diagnostic.unsupported_capability_fields; + let unsupported_capability_issue_count = unsupported_capability_fields.len(); + let Some(manifest) = manifest_diagnostic.manifest else { + return CapabilityResult { + issue_count: manifest_issues.len().max(1), + has_capabilities: false, + value: json!({ + "status": "error", + "code": "manifest_unavailable", + "manifest": { + "path": manifest_path, + "issues": manifest_issues, + "unsupportedCapabilityFields": unsupported_capability_fields + }, + "skills": null, + "mcp": null, + "hooks": null, + "apps": null + }), + }; + }; + + let skill_config_rules = Default::default(); + let skills = load_plugin_skills( + plugin_root, + &resolved.plugin_id, + &manifest.paths, + Some(Product::Codex), + &skill_config_rules, + ) + .await; + let skill_roots = capability_skill_roots(plugin_root, &manifest.paths.skills); + let skill_root_probes = skill_roots + .iter() + .map(|path| probe_skill_root(path, plugin_root, redactor)) + .collect::>(); + let skill_root_issue_count = skill_root_probes + .iter() + .filter(|probe| probe["status"] != "ok") + .count(); + let skill_errors = skills + .errors + .iter() + .map(|error| { + json!({ + "path": relative_path(&error.path, plugin_root, redactor), + "detail": redactor.detail(&error.message) + }) + }) + .collect::>(); + let skill_names = skills + .skills + .iter() + .map(|skill| { + json!({ + "name": skill.name, + "path": relative_path(&skill.path_to_skills_md, plugin_root, redactor) + }) + }) + .collect::>(); + + let mcp = diagnose_plugin_mcp_servers(plugin_root.as_path(), &manifest.paths).await; + let mcp_issues = mcp + .issues + .iter() + .map(|issue| redactor.detail(issue)) + .collect::>(); + let app = diagnose_plugin_apps(plugin_root.as_path(), &manifest.paths).await; + let app_issues = app + .issues + .iter() + .map(|issue| redactor.detail(issue)) + .collect::>(); + let (hook_sources, hook_warnings) = load_plugin_hooks( + plugin_root, + &resolved.plugin_id, + &store.plugin_data_root(&resolved.plugin_id), + &manifest.paths, + ); + let hook_warnings = hook_warnings + .iter() + .map(|warning| redactor.detail(warning)) + .collect::>(); + + let manifest_name_matches = manifest.name == resolved.plugin_id.plugin_name; + let issue_count = manifest_issues.len() + + skill_errors.len() + + mcp_issues.len() + + app_issues.len() + + hook_warnings.len() + + skill_root_issue_count + + unsupported_capability_issue_count + + usize::from(!manifest_name_matches); + let has_capabilities = !skill_names.is_empty() + || !mcp.server_names.is_empty() + || !hook_sources.is_empty() + || !app.connector_ids.is_empty(); + let status = if issue_count > 0 { "warning" } else { "ok" }; + + CapabilityResult { + issue_count, + has_capabilities, + value: json!({ + "status": status, + "code": if has_capabilities { "capabilities_inspected" } else { "no_supported_capabilities_detected" }, + "manifest": { + "path": manifest_path, + "name": manifest.name, + "nameMatchesMarketplace": manifest_name_matches, + "versionPresent": manifest.version.is_some(), + "issues": manifest_issues, + "unsupportedCapabilityFields": unsupported_capability_fields + }, + "skills": { + "configuredRoots": skill_root_probes, + "detected": skill_names, + "errors": skill_errors, + "reasonWhenEmpty": if skills.skills.is_empty() { + Some(if skill_roots.is_empty() { + "no default skills directory or manifest skills path was configured" + } else if skills.had_errors || skill_root_issue_count > 0 { + "skill roots were configured but one or more skills failed to load or scan" + } else { + "skill roots were inspected but no Codex-compatible skills were detected" + }) + } else { + None + } + }, + "mcp": { + "configPaths": mcp.config_paths.iter() + .map(|path| relative_path(path, plugin_root, redactor)) + .collect::>(), + "serverNames": mcp.server_names, + "issues": mcp_issues, + "reasonWhenEmpty": if mcp.config_paths.is_empty() { + Some("no default .mcp.json or manifest mcpServers path was configured") + } else if mcp.server_names.is_empty() { + Some("MCP config paths were inspected but no valid servers were detected") + } else { + None + } + }, + "hooks": { + "sourcePaths": hook_sources.iter() + .map(|source| source.source_relative_path.clone()) + .collect::>(), + "sourceCount": hook_sources.len(), + "issues": hook_warnings, + "reasonWhenEmpty": if hook_sources.is_empty() { + Some("no valid manifest hooks or default hooks/hooks.json declarations were detected") + } else { + None + } + }, + "apps": { + "configPaths": app.config_paths.iter() + .map(|path| relative_path(path, plugin_root, redactor)) + .collect::>(), + "connectorIds": app.connector_ids.iter() + .map(|connector| connector.0.clone()) + .collect::>(), + "issues": app_issues, + "reasonWhenEmpty": if app.config_paths.is_empty() { + Some("no default .app.json or manifest apps path was configured") + } else if app.connector_ids.is_empty() { + Some("app config paths were inspected but no valid connector IDs were detected") + } else { + None + } + } + }), + } +} + +fn probe_skill_root( + path: &AbsolutePathBuf, + plugin_root: &AbsolutePathBuf, + redactor: &Redactor, +) -> Value { + let display_path = relative_path(path, plugin_root, redactor); + let metadata = match std::fs::metadata(path.as_path()) { + Ok(metadata) => metadata, + Err(err) => { + return json!({ + "path": display_path, + "status": "error", + "code": "metadata_failed", + "directoriesScanned": 0, + "issues": [{ + "code": "metadata_failed", + "path": display_path, + "detail": redactor.detail(&err.to_string()) + }] + }); + } + }; + if !metadata.is_dir() { + return json!({ + "path": display_path, + "status": "error", + "code": "not_a_directory", + "directoriesScanned": 0, + "issues": [{ + "code": "not_a_directory", + "path": display_path + }] + }); + } + + let root = + std::fs::canonicalize(path.as_path()).unwrap_or_else(|_| path.as_path().to_path_buf()); + let mut queue = VecDeque::from([(root.clone(), 0)]); + let mut visited = HashSet::from([root]); + let mut issues = Vec::new(); + let mut issue_count = 0; + let mut truncated_by_directory_limit = false; + + while let Some((directory, depth)) = queue.pop_front() { + let entries = match std::fs::read_dir(&directory) { + Ok(entries) => entries, + Err(err) => { + push_skill_scan_issue( + &mut issues, + &mut issue_count, + json!({ + "code": "read_directory_failed", + "path": relative_path_from_path(&directory, plugin_root, redactor), + "detail": redactor.detail(&err.to_string()) + }), + ); + continue; + } + }; + + for entry in entries { + let entry = match entry { + Ok(entry) => entry, + Err(err) => { + push_skill_scan_issue( + &mut issues, + &mut issue_count, + json!({ + "code": "read_directory_entry_failed", + "path": relative_path_from_path(&directory, plugin_root, redactor), + "detail": redactor.detail(&err.to_string()) + }), + ); + continue; + } + }; + let entry_path = entry.path(); + if entry.file_name().to_string_lossy().starts_with('.') { + continue; + } + let metadata = match std::fs::symlink_metadata(&entry_path) { + Ok(metadata) => metadata, + Err(err) => { + push_skill_scan_issue( + &mut issues, + &mut issue_count, + json!({ + "code": "entry_metadata_failed", + "path": relative_path_from_path(&entry_path, plugin_root, redactor), + "detail": redactor.detail(&err.to_string()) + }), + ); + continue; + } + }; + + if metadata.file_type().is_symlink() { + match std::fs::read_dir(&entry_path) { + Ok(_) => enqueue_skill_scan_directory( + &entry_path, + depth + 1, + &mut queue, + &mut visited, + &mut truncated_by_directory_limit, + ), + Err(err) + if matches!( + err.kind(), + std::io::ErrorKind::NotADirectory | std::io::ErrorKind::NotFound + ) => {} + Err(err) => push_skill_scan_issue( + &mut issues, + &mut issue_count, + json!({ + "code": "read_symlink_directory_failed", + "path": relative_path_from_path(&entry_path, plugin_root, redactor), + "detail": redactor.detail(&err.to_string()) + }), + ), + } + } else if metadata.is_dir() { + enqueue_skill_scan_directory( + &entry_path, + depth + 1, + &mut queue, + &mut visited, + &mut truncated_by_directory_limit, + ); + } + } + } + + if truncated_by_directory_limit { + push_skill_scan_issue( + &mut issues, + &mut issue_count, + json!({ + "code": "directory_limit_reached", + "detail": format!("skill scan stopped adding directories after {MAX_SKILL_SCAN_DIRS} unique directories") + }), + ); + } + + json!({ + "path": display_path, + "status": if issue_count == 0 { "ok" } else { "warning" }, + "code": if issue_count == 0 { "skill_tree_scanned" } else { "skill_tree_scan_issues" }, + "directoriesScanned": visited.len(), + "issues": issues, + "omittedIssueCount": issue_count.saturating_sub(MAX_SKILL_SCAN_ISSUES) + }) +} + +fn enqueue_skill_scan_directory( + path: &Path, + depth: usize, + queue: &mut VecDeque<(PathBuf, usize)>, + visited: &mut HashSet, + truncated_by_directory_limit: &mut bool, +) { + if depth > MAX_SKILL_SCAN_DEPTH { + return; + } + if visited.len() >= MAX_SKILL_SCAN_DIRS { + *truncated_by_directory_limit = true; + return; + } + let path = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()); + if visited.insert(path.clone()) { + queue.push_back((path, depth)); + } +} + +fn push_skill_scan_issue(issues: &mut Vec, issue_count: &mut usize, issue: Value) { + *issue_count += 1; + if issues.len() < MAX_SKILL_SCAN_ISSUES { + issues.push(issue); + } +} + +fn capability_skill_roots( + plugin_root: &AbsolutePathBuf, + manifest_skill_root: &Option, +) -> Vec { + let mut roots = Vec::new(); + let default_root = plugin_root.join("skills"); + if default_root.as_path().is_dir() { + roots.push(default_root); + } + if let Some(root) = manifest_skill_root { + roots.push(root.clone()); + } + roots.sort_unstable(); + roots.dedup(); + roots +} + +fn plugin_is_eligible(plugin: &ResolvedMarketplacePlugin) -> bool { + plugin.policy.installation != MarketplacePluginInstallPolicy::NotAvailable + && match plugin.policy.products.as_deref() { + None => true, + Some([]) => false, + Some(products) => products.contains(&Product::Codex), + } +} + +fn install_failure_diagnostic( + plugin: &ResolvedMarketplacePlugin, + install_error: &str, + redactor: &Redactor, +) -> Value { + if let MarketplacePluginSource::Local { path } = &plugin.source { + match std::fs::metadata(path.as_path()) { + Err(err) if err.kind() == std::io::ErrorKind::NotFound => { + return json!({ + "status": "error", + "code": "source_path_not_found", + "detail": "marketplace local source path does not exist" + }); + } + Err(err) => { + return json!({ + "status": "error", + "code": "source_path_metadata_failed", + "detail": redactor.detail(&err.to_string()) + }); + } + Ok(metadata) if !metadata.is_dir() => { + return json!({ + "status": "error", + "code": "source_path_not_directory", + "detail": "marketplace local source path is not a directory" + }); + } + Ok(_) => {} + } + } + + json!({ + "status": "error", + "code": "install_failed", + "detail": redactor.detail(install_error) + }) +} + +fn eligibility_failure_code(plugin: &ResolvedMarketplacePlugin) -> &'static str { + if plugin.policy.installation == MarketplacePluginInstallPolicy::NotAvailable { + "installation_policy_not_available" + } else { + "product_policy_excludes_codex" + } +} + +fn eligibility_failure_detail(plugin: &ResolvedMarketplacePlugin) -> &'static str { + if plugin.policy.installation == MarketplacePluginInstallPolicy::NotAvailable { + "marketplace policy marks the plugin as not available for installation" + } else { + "marketplace product policy does not include Codex" + } +} + +fn installation_policy_name(policy: MarketplacePluginInstallPolicy) -> &'static str { + match policy { + MarketplacePluginInstallPolicy::NotAvailable => "not_available", + MarketplacePluginInstallPolicy::Available => "available", + MarketplacePluginInstallPolicy::InstalledByDefault => "installed_by_default", + } +} + +fn authentication_policy_name(policy: MarketplacePluginAuthPolicy) -> &'static str { + match policy { + MarketplacePluginAuthPolicy::OnInstall => "on_install", + MarketplacePluginAuthPolicy::OnUse => "on_use", + } +} + +fn product_policy_names(products: Option<&[Product]>) -> Value { + match products { + None => Value::Null, + Some(products) => json!( + products + .iter() + .map(|product| product.to_app_platform()) + .collect::>() + ), + } +} + +fn duplicate_name_counts( + plugins: &[codex_core_plugins::marketplace::MarketplacePluginDiagnostic], +) -> HashMap { + let mut counts = HashMap::new(); + for plugin in plugins { + if let Some(name) = &plugin.name { + *counts.entry(name.clone()).or_insert(0) += 1; + } + } + counts.retain(|_, count| *count > 1); + counts +} + +fn summary_json(summary: &Summary) -> Value { + json!({ + "rawEntries": summary.raw_entries, + "detectedEntries": summary.detected_entries, + "detectionFailures": summary.detection_failures, + "eligibleEntries": summary.eligible_entries, + "installedEntries": summary.installed_entries, + "installFailures": summary.install_failures, + "installSkips": summary.install_skips, + "entriesWithCapabilityIssues": summary.entries_with_capability_issues, + "entriesWithoutCapabilities": summary.entries_without_capabilities + }) +} + +fn create_report_file(path: &Path) -> Result { + let mut options = OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + options + .open(path) + .with_context(|| format!("failed to create new report {}", path.display())) +} + +fn finish_preflight_failure( + writer: &mut BufWriter, + output: &Path, + code: &str, + detail: &str, +) -> Result<()> { + write_record( + writer, + &json!({ + "schemaVersion": REPORT_SCHEMA_VERSION, + "event": "marketplace_diagnostic", + "status": "error", + "code": code, + "detail": detail + }), + )?; + write_record( + writer, + &json!({ + "schemaVersion": REPORT_SCHEMA_VERSION, + "event": "run_completed", + "status": "report_complete_preflight_failed", + "summary": summary_json(&Summary::default()) + }), + )?; + println!( + "Marketplace import diagnostic written to {} (preflight failed: {code})", + output.display() + ); + Ok(()) +} + +fn write_plugin_stage( + writer: &mut BufWriter, + entry_index: usize, + plugin_name: &str, + stage: &str, +) -> Result<()> { + write_record( + writer, + &json!({ + "schemaVersion": REPORT_SCHEMA_VERSION, + "event": "plugin_stage_started", + "entryIndex": entry_index, + "pluginName": plugin_name, + "stage": stage + }), + ) +} + +fn write_record(writer: &mut BufWriter, value: &Value) -> Result<()> { + serde_json::to_writer(&mut *writer, value).context("failed to serialize diagnostic record")?; + writer + .write_all(b"\n") + .context("failed to write diagnostic record")?; + writer.flush().context("failed to flush diagnostic record") +} + +fn relative_path(path: &AbsolutePathBuf, root: &AbsolutePathBuf, redactor: &Redactor) -> String { + relative_path_from_path(path.as_path(), root, redactor) +} + +fn relative_path_from_path(path: &Path, root: &AbsolutePathBuf, redactor: &Redactor) -> String { + path.strip_prefix(root.as_path()) + .map(|relative| { + if relative.as_os_str().is_empty() { + ".".to_string() + } else { + format!("./{}", relative.to_string_lossy().replace('\\', "/")) + } + }) + .unwrap_or_else(|_| redactor.detail(&path.display().to_string())) +} + +struct Redactor { + replacements: Vec<(String, &'static str)>, +} + +impl Redactor { + fn new(marketplace_root: &Path, diagnostic_home: &Path) -> Self { + let mut replacements = vec![ + (marketplace_root.display().to_string(), ""), + (diagnostic_home.display().to_string(), ""), + ]; + for value in [std::env::var_os("HOME"), std::env::var_os("USERPROFILE")] + .into_iter() + .flatten() + { + let value = PathBuf::from(value); + if value.is_absolute() { + replacements.push((value.display().to_string(), "")); + } + } + if let Ok(cwd) = std::env::current_dir() { + replacements.push((cwd.display().to_string(), "")); + } + let mut redactor = Self { replacements }; + redactor.normalize_replacements(); + redactor + } + + fn add_replacement(&mut self, path: &Path, replacement: &'static str) { + let value = path.display().to_string(); + self.replacements.retain(|(existing, _)| existing != &value); + self.replacements.push((value, replacement)); + self.normalize_replacements(); + } + + fn normalize_replacements(&mut self) { + self.replacements + .sort_by_key(|entry| std::cmp::Reverse(entry.0.len())); + self.replacements.dedup_by(|left, right| left.0 == right.0); + } + + fn detail(&self, detail: &str) -> String { + let mut redacted = detail.to_string(); + for (value, replacement) in &self.replacements { + if !value.is_empty() { + redacted = redacted.replace(value, replacement); + } + } + redacted = redact_git_command_arguments(&redacted); + redacted = redact_urls(&redacted); + redacted = redact_scp_git_remotes(redacted); + redacted = redact_absolute_paths(redacted); + redacted = redact_parser_values(redacted); + redacted = redact_known_secrets(redacted); + truncate_chars(redacted, MAX_DETAIL_CHARS) + } +} + +fn redact_git_command_arguments(detail: &str) -> String { + if let Some(output_start) = detail.find("\nstdout:") { + let header = &detail[..output_start]; + if let Some(status_start) = header.rfind(" failed with status ") { + return format!( + "git {}; git output omitted; failure class: {}", + &header[status_start..], + git_failure_class(detail) + ); + } + } + if let Some(command_start) = detail.find("failed to run git ") + && let Some((_, suffix)) = detail[command_start..].rsplit_once(": ") + { + return format!("failed to run git : {suffix}"); + } + detail.to_string() +} + +fn git_failure_class(detail: &str) -> &'static str { + let detail = detail.to_ascii_lowercase(); + if detail.contains("authentication") + || detail.contains("permission denied") + || detail.contains("publickey") + { + "authentication_or_authorization" + } else if detail.contains("repository not found") || detail.contains("not found") { + "repository_not_found" + } else if detail.contains("could not resolve host") + || detail.contains("name or service not known") + { + "dns_resolution" + } else if detail.contains("timed out") || detail.contains("timeout") { + "timeout" + } else if detail.contains("connection refused") { + "connection_refused" + } else if detail.contains("host key verification failed") { + "host_key_verification" + } else { + "git_command_failed" + } +} + +fn redact_scp_git_remotes(input: String) -> String { + static SCP_REMOTE: OnceLock = OnceLock::new(); + let regex = SCP_REMOTE + .get_or_init(|| compile_redaction_regex(r"\b[A-Za-z0-9._-]+@[A-Za-z0-9.-]+:[^\s]+")); + regex + .replace_all(&input, ":") + .to_string() +} + +fn redact_absolute_paths(input: String) -> String { + static UNIX_PATH: OnceLock = OnceLock::new(); + static WINDOWS_PATH: OnceLock = OnceLock::new(); + static UNC_PATH: OnceLock = OnceLock::new(); + let unix_path = + UNIX_PATH.get_or_init(|| compile_redaction_regex(r#"(^|[\s=(\[\"'`])\/[^\s,;:)\]\"'`]+"#)); + let windows_path = WINDOWS_PATH + .get_or_init(|| compile_redaction_regex(r#"(?i)\b[A-Z]:[\\/][^\s,;:)\]\"'`]+"#)); + let unc_path = UNC_PATH.get_or_init(|| compile_redaction_regex(r#"\\\\[^\s,;:)\]\"'`]+"#)); + let redacted = unix_path.replace_all(&input, "$1"); + let redacted = windows_path + .replace_all(&redacted, "") + .to_string(); + unc_path + .replace_all(&redacted, "") + .to_string() +} + +fn redact_known_secrets(input: String) -> String { + static OPENAI_KEY: OnceLock = OnceLock::new(); + static AWS_ACCESS_KEY: OnceLock = OnceLock::new(); + static BEARER_TOKEN: OnceLock = OnceLock::new(); + static SECRET_ASSIGNMENT: OnceLock = OnceLock::new(); + + let openai_key = OPENAI_KEY.get_or_init(|| compile_redaction_regex(r"sk-[A-Za-z0-9]{20,}")); + let aws_access_key = + AWS_ACCESS_KEY.get_or_init(|| compile_redaction_regex(r"\bAKIA[0-9A-Z]{16}\b")); + let bearer_token = BEARER_TOKEN + .get_or_init(|| compile_redaction_regex(r"(?i)\bBearer\s+[A-Za-z0-9._\-]{16,}\b")); + let secret_assignment = SECRET_ASSIGNMENT.get_or_init(|| { + compile_redaction_regex( + r#"(?i)\b(api[_-]?key|access[_-]?token|client[_-]?secret|token|secret|password|credential)\b(\s*[:=]\s*)(["']?)[^\s"']{8,}"#, + ) + }); + + let redacted = openai_key.replace_all(&input, "[REDACTED_SECRET]"); + let redacted = aws_access_key.replace_all(&redacted, "[REDACTED_SECRET]"); + let redacted = bearer_token.replace_all(&redacted, "Bearer [REDACTED_SECRET]"); + secret_assignment + .replace_all(&redacted, "$1$2$3[REDACTED_SECRET]") + .to_string() +} + +fn redact_parser_values(input: String) -> String { + static PARSER_VALUE: OnceLock = OnceLock::new(); + let regex = PARSER_VALUE.get_or_init(|| { + compile_redaction_regex( + r#"(?i)\b(string|integer|float|boolean|variant|value|token)(\s+)(`[^`\r\n]*`|"[^"\r\n]*"|'[^'\r\n]*')"#, + ) + }); + regex + .replace_all(&input, "$1$2") + .to_string() +} + +fn compile_redaction_regex(pattern: &str) -> regex_lite::Regex { + match regex_lite::Regex::new(pattern) { + Ok(regex) => regex, + Err(err) => panic!("invalid built-in diagnostic redaction regex: {err}"), + } +} + +fn redact_urls(detail: &str) -> String { + detail + .split_inclusive(char::is_whitespace) + .map(redact_url_token) + .collect() +} + +fn redact_url_token(token: &str) -> String { + let Some(scheme_end) = token.find("://") else { + return token.to_string(); + }; + let mut suffix_start = token.len(); + while suffix_start > scheme_end + 3 + && matches!( + token.as_bytes()[suffix_start - 1], + b' ' | b'\t' | b'\n' | b'\r' | b'.' | b',' | b';' | b':' | b')' | b']' + ) + { + suffix_start -= 1; + } + let (_, suffix) = token.split_at(suffix_start); + format!("{suffix}") +} + +fn truncate_chars(value: String, limit: usize) -> String { + if value.chars().count() <= limit { + return value; + } + let mut truncated = value.chars().take(limit).collect::(); + truncated.push_str("...[truncated]"); + truncated +} + +#[cfg(test)] +#[path = "plugin_import_diagnostic_tests.rs"] +mod tests; diff --git a/codex-rs/cli/src/plugin_import_diagnostic_tests.rs b/codex-rs/cli/src/plugin_import_diagnostic_tests.rs new file mode 100644 index 0000000000..32a5b6e02e --- /dev/null +++ b/codex-rs/cli/src/plugin_import_diagnostic_tests.rs @@ -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("/plugins/demo")); + assert!(detail.contains("/plugins/cache")); + assert!(detail.contains("")); + assert!(detail.contains(":")); + 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 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 ")); + assert!(detail.contains("variant ")); + assert!(detail.contains("")); + assert!(!detail.contains("8675309")); + assert!(!detail.contains("private-transport")); + assert!(!detail.contains("internal.example")); +} diff --git a/codex-rs/cli/tests/plugin_import_diagnostic.rs b/codex-rs/cli/tests/plugin_import_diagnostic.rs new file mode 100644 index 0000000000..1065ddc8a0 --- /dev/null +++ b/codex-rs/cli/tests/plugin_import_diagnostic.rs @@ -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::) + .collect::, _>>()?; + assert_eq!(records.len(), 19); + assert_eq!(records[0]["attemptInstall"], true); + + let started = records + .iter() + .filter(|record| record["event"] == "plugin_started") + .collect::>(); + assert_eq!(started.len(), 5); + assert_eq!(started[0]["pluginName"], "good"); + + let stages = records + .iter() + .filter(|record| record["event"] == "plugin_stage_started") + .collect::>(); + 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::>(); + 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::) + .collect::, _>>()?; + 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(()) +} diff --git a/codex-rs/core-plugins/src/loader.rs b/codex-rs/core-plugins/src/loader.rs index 9dfa0bbc6f..9c2a3390d1 100644 --- a/codex-rs/core-plugins/src/loader.rs +++ b/codex-rs/core-plugins/src/loader.rs @@ -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, + pub errors: Vec, pub disabled_skill_paths: HashSet, pub had_errors: bool, } @@ -788,6 +790,7 @@ pub async fn load_plugin_skills( .collect::>(); 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 { pub async fn load_plugin_apps(plugin_root: &Path) -> Vec { 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, + pub connector_ids: Vec, + pub issues: Vec, +} + +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, -) -> Vec { +) -> 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::(&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, + pub server_names: Vec, + pub issues: Vec, +} + +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::(&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::(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, ) -> JsonMap { 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, + issues: Vec, } #[derive(Debug)] diff --git a/codex-rs/core-plugins/src/manifest.rs b/codex-rs/core-plugins/src/manifest.rs index 606ca81475..e9b5d793d0 100644 --- a/codex-rs/core-plugins/src/manifest.rs +++ b/codex-rs/core-plugins/src/manifest.rs @@ -52,6 +52,14 @@ pub struct PluginManifestPaths { pub hooks: Option, } +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct PluginManifestLoadDiagnostics { + pub manifest_path: Option, + pub manifest: Option, + pub issues: Vec, + pub unsupported_capability_fields: Vec, +} + #[derive(Debug, Clone, PartialEq, Eq)] pub enum PluginManifestHooks { Paths(Vec), @@ -145,141 +153,208 @@ enum RawPluginManifestHooks { } pub fn load_plugin_manifest(plugin_root: &Path) -> Option { - let manifest_path = find_plugin_manifest_path(plugin_root)?; - let contents = fs::read_to_string(&manifest_path).ok()?; - match serde_json::from_str::(&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::(&contents) + .ok() + .and_then(|value| { + value + .as_object() + .map(unsupported_manifest_capability_fields) + }) + .unwrap_or_default(); + let raw_manifest = match serde_json::from_str::(&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, +) -> Vec { + 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, +) -> 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, + issues: &mut Vec, ) -> Option { 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::>(); (!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, ) -> Option { - 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, ) -> Option> { 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 { +fn resolve_default_prompt_str( + plugin_root: &Path, + field: &str, + prompt: &str, + issues: &mut Vec, +) -> Option { let prompt = prompt.split_whitespace().collect::>().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, +) { + 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, ) -> Option { 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, ) -> Option { // `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; diff --git a/codex-rs/core-plugins/src/manifest_diagnostics_tests.rs b/codex-rs/core-plugins/src/manifest_diagnostics_tests.rs new file mode 100644 index 0000000000..a540ab8d75 --- /dev/null +++ b/codex-rs/core-plugins/src/manifest_diagnostics_tests.rs @@ -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")); +} diff --git a/codex-rs/core-plugins/src/marketplace.rs b/codex-rs/core-plugins/src/marketplace.rs index 049d882751..3c0b824592 100644 --- a/codex-rs/core-plugins/src/marketplace.rs +++ b/codex-rs/core-plugins/src/marketplace.rs @@ -66,6 +66,30 @@ pub struct MarketplacePlugin { pub keywords: Vec, } +/// 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, + pub source_kind: &'static str, + pub result: Result, +} + +#[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, +} + #[derive(Debug, Clone, PartialEq, Eq)] pub enum MarketplacePluginSource { Local { @@ -327,6 +351,197 @@ pub fn load_marketplace(path: &AbsolutePathBuf) -> Result Result { + 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::(&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::(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, 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) -> Option { - value +fn normalize_optional_git_selector( + marketplace_path: &AbsolutePathBuf, + field: &str, + value: &Option, +) -> Result, 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 { diff --git a/codex-rs/core-plugins/src/marketplace_tests.rs b/codex-rs/core-plugins/src/marketplace_tests.rs index e134157177..a0002335b9 100644 --- a/codex-rs/core-plugins/src/marketplace_tests.rs +++ b/codex-rs/core-plugins/src/marketplace_tests.rs @@ -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()); +}