дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-06 01:57:13 +02:00
Adds a Plugins page under Settings > Agents for the plugin bundles each agent harness installs natively (Claude Code, GitHub Copilot, Codex, Gemini CLI). - Rows are grouped by harness and scope with counts and paths. Toggles change only the harness's own enablement record, and row ids are stable and owner-qualified, so a toggle never reaches another project's row. - Enabled plugins project their skills, MCP servers and memory files into Skills, MCP Connections and Memory; a workspace override decides what a globally enabled plugin projects in that workspace. - Marketplaces can be browsed, previewed and installed from, with pinned git installs. Installs are written into each harness's native store without following symlinks, including at the store root. - Plugins that run local MCP processes or lifecycle hooks need capability consent. Previews and installed folders resolve capabilities the same way, and consent is tied to the capability hash the user was shown: an install or enable whose capabilities differ is refused. Closes #6872 Co-authored-by: dengliu <[email protected]>
5832 рядки
249 KiB
Rust
5832 рядки
249 KiB
Rust
//! Agent Plugins hub (`#6872`): native multi-harness bundle discovery, capability consent,
|
|
//! source labels for projected Skills/MCP/Memory views, marketplace browsing, and pinned
|
|
//! installation into each harness's own plugin store.
|
|
|
|
use std::collections::{BTreeMap, BTreeSet, HashSet};
|
|
use std::path::{Component, Path, PathBuf};
|
|
|
|
use ide_core::settings::{AgentMcpServer, AgentPluginEntryPolicy, AgentPluginSettings};
|
|
use ide_core::{CancellationToken, IdeError, IdeResult};
|
|
use serde::{Deserialize, Serialize};
|
|
use serde_json::{Map, Value, json};
|
|
|
|
use crate::EnvSecrets;
|
|
use crate::model::{
|
|
AgentMarketplaceBrowseResult, AgentMarketplaceCandidate, AgentMarketplaceInfo, AgentMemoryEntry, AgentMemoryKind,
|
|
AgentMemorySource, AgentPlugin, AgentPluginCapabilities, AgentPluginCatalog, AgentPluginConfigField,
|
|
AgentPluginConfigFieldKind, AgentPluginFormat, AgentPluginInstallTarget, AgentPluginOrigin, AgentPluginPreview,
|
|
AgentPluginSource, AgentPluginState, AgentSkillSource, InstallAgentPluginRequest, McpKeyValue, McpScope, McpServer,
|
|
};
|
|
use crate::skill_installer::{
|
|
FetchedSubtree, ParsedSource, RepoRef, SkillSourceFetcher, fetch_and_scan_subtree, parse_source,
|
|
scan_local_subtree, write_staged_subtree,
|
|
};
|
|
|
|
/// Maximum files allowed inside one installed agent plugin bundle.
|
|
pub const MAX_PLUGIN_FILES: usize = 512;
|
|
/// Maximum unpacked bytes allowed inside one installed agent plugin bundle (8 MiB).
|
|
pub const MAX_PLUGIN_BYTES: u64 = 8 << 20;
|
|
|
|
const SKIP_DIRS: &[&str] = &["node_modules", "target", "dist", "build", "out", "vendor", "coverage", ".git", ".idea"];
|
|
|
|
const MANIFEST_CANDIDATES: &[(&str, AgentPluginFormat)] = &[
|
|
("plugin.json", AgentPluginFormat::AgentPluginsV1),
|
|
(".openidea/plugin.json", AgentPluginFormat::OpenIdea),
|
|
(".claude-plugin/plugin.json", AgentPluginFormat::Claude),
|
|
(".plugin/plugin.json", AgentPluginFormat::Copilot),
|
|
(".github/plugin/plugin.json", AgentPluginFormat::Copilot),
|
|
(".codex-plugin/plugin.json", AgentPluginFormat::Codex),
|
|
("gemini-extension.json", AgentPluginFormat::GeminiExtension),
|
|
];
|
|
|
|
const MARKETPLACE_MANIFEST_PATHS: &[&str] = &[
|
|
"marketplace.json",
|
|
".claude-plugin/marketplace.json",
|
|
".plugin/marketplace.json",
|
|
".github/plugin/marketplace.json",
|
|
];
|
|
|
|
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct InstalledPluginProvenance {
|
|
pub source_kind: String,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pub owner: Option<String>,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pub repo: Option<String>,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pub git_ref: Option<String>,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pub tree_sha: Option<String>,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pub commit_sha: Option<String>,
|
|
#[serde(default, skip_serializing_if = "String::is_empty")]
|
|
pub subpath: String,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pub local_path: Option<String>,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pub marketplace: Option<String>,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pub marketplace_source: Option<String>,
|
|
}
|
|
|
|
/// Policy inputs resolved for a project or global Settings window.
|
|
#[derive(Clone, Debug)]
|
|
pub struct PluginsPolicy {
|
|
pub user: AgentPluginSettings,
|
|
pub workspace: AgentPluginSettings,
|
|
pub workspace_trusted: bool,
|
|
pub workspace_roots: Vec<PathBuf>,
|
|
/// Capability approvals ([`capability_approval_key`]) the user granted on this machine. Kept
|
|
/// apart from settings, which only hold plugin configuration.
|
|
pub approved_capabilities: BTreeSet<String>,
|
|
}
|
|
|
|
impl Default for PluginsPolicy {
|
|
fn default() -> Self {
|
|
Self {
|
|
user: AgentPluginSettings::default(),
|
|
workspace: AgentPluginSettings::default(),
|
|
workspace_trusted: true,
|
|
workspace_roots: Vec::new(),
|
|
approved_capabilities: BTreeSet::new(),
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Key recording that the user approved `plugin`'s current executable capabilities, or `None`
|
|
/// when the plugin has nothing to approve.
|
|
pub fn capability_approval_key(plugin: &AgentPlugin) -> Option<String> {
|
|
let hash = plugin.capabilities.capability_hash.as_deref()?;
|
|
Some(format!("{}#{hash}", plugin_policy_key(plugin)))
|
|
}
|
|
|
|
/// Skill root projected by an enabled agent plugin into `skills.rs`.
|
|
#[derive(Clone, Debug)]
|
|
pub struct ProjectedSkillRoot {
|
|
pub dir: PathBuf,
|
|
pub plugin_id: String,
|
|
pub plugin_name: String,
|
|
pub source: AgentSkillSource,
|
|
}
|
|
|
|
pub fn normalize_provider_id(provider: &str) -> &str {
|
|
let base = provider.strip_suffix("-acp").unwrap_or(provider);
|
|
match base {
|
|
"claude-code" => "claude",
|
|
"github-copilot" | "copilot-cli" => "copilot",
|
|
"gemini-cli" => "gemini",
|
|
"cursor-agent" => "cursor",
|
|
_ if base == "hermes" || base.starts_with("hermes-") => "hermes",
|
|
_ => base,
|
|
}
|
|
}
|
|
|
|
/// Discovers native harness plugin bundles across workspace and user scopes.
|
|
/// A canonical path may appear once per harness/scope so each native config owns its toggle.
|
|
pub fn discover_plugins(workspaces: &[PathBuf], home: Option<&Path>) -> Vec<AgentPlugin> {
|
|
let mut out: Vec<AgentPlugin> = Vec::new();
|
|
let mut path_index: Vec<(PathBuf, AgentPluginSource, McpScope, Option<PathBuf>)> = Vec::new();
|
|
|
|
let mut seen_ws: HashSet<PathBuf> = HashSet::new();
|
|
let mut all_ws: Vec<PathBuf> = Vec::new();
|
|
for ws in workspaces {
|
|
let canon = dunce::canonicalize(ws).unwrap_or_else(|_| ws.clone());
|
|
if seen_ws.insert(canon) {
|
|
all_ws.push(ws.clone());
|
|
}
|
|
}
|
|
let base_ws = all_ws.clone();
|
|
for ws in &base_ws {
|
|
for sub in monorepo_plugin_subdirs(ws, 2) {
|
|
let canon = dunce::canonicalize(&sub).unwrap_or_else(|_| sub.clone());
|
|
if seen_ws.insert(canon) {
|
|
all_ws.push(sub);
|
|
}
|
|
}
|
|
}
|
|
|
|
let mut push = |mut plugin: AgentPlugin| {
|
|
let canon = dunce::canonicalize(&plugin.root_path.0).unwrap_or_else(|_| plugin.root_path.0.clone());
|
|
plugin.root_path = canon.clone().into();
|
|
let owner = plugin.workspace_root.as_ref().map(|root| root.0.clone());
|
|
if path_index.iter().any(|(path, source, scope, workspace)| {
|
|
path == &canon && *source == plugin.source && *scope == plugin.scope && *workspace == owner
|
|
}) {
|
|
return;
|
|
}
|
|
plugin.id = stable_plugin_id(&plugin);
|
|
path_index.push((canon, plugin.source, plugin.scope, owner));
|
|
out.push(plugin);
|
|
};
|
|
|
|
// Every harness keeps installed files in its user store; workspace rows are the user-store
|
|
// plugins a workspace's native settings enable or disable.
|
|
if let Some(home) = home {
|
|
// GitHub Copilot (`~/.copilot/installed-plugins/*` + `config.json` / `settings.json`).
|
|
for (dir, mkt, ext_enabled) in discover_copilot_plugins(&home.join(".copilot")) {
|
|
if let Some(mut p) =
|
|
inspect_plugin_dir(&dir, AgentPluginSource::CopilotUser, McpScope::User, mkt.as_deref(), true)
|
|
{
|
|
if let Some(en) = ext_enabled {
|
|
p.default_enabled = en;
|
|
}
|
|
push(p.clone());
|
|
push_workspace_scoped_copies(&mut push, p, &all_ws, Some(home));
|
|
}
|
|
}
|
|
|
|
// Copilot plugins a repository enables from a local marketplace, loaded live.
|
|
for workspace in &all_ws {
|
|
let repo_settings = workspace.join(".github/copilot/settings.json");
|
|
for (key, enabled) in json_plugin_enabled_map(&repo_settings) {
|
|
let Some((name, marketplace)) = key.rsplit_once('@') else { continue };
|
|
let Some(dir) = copilot_live_plugin_dir_in(
|
|
&[repo_settings.clone(), home.join(".copilot/settings.json")],
|
|
name,
|
|
marketplace,
|
|
) else {
|
|
continue;
|
|
};
|
|
if let Some(mut p) = inspect_plugin_dir(
|
|
&dir,
|
|
AgentPluginSource::CopilotUser,
|
|
McpScope::Workspace,
|
|
Some(marketplace),
|
|
true,
|
|
) {
|
|
p.workspace_root = Some(workspace.clone().into());
|
|
p.default_enabled = enabled;
|
|
push(p);
|
|
}
|
|
}
|
|
}
|
|
|
|
// Claude Code (`~/.claude/plugins/installed_plugins.json` + `~/.claude/plugins/cache/*`).
|
|
for discovered in discover_claude_plugins(&home.join(".claude")) {
|
|
let ClaudeDiscoveredPlugin { dir, marketplace, enabled, scope, project_path } = discovered;
|
|
if scope == McpScope::Workspace {
|
|
for workspace in &all_ws {
|
|
if project_path.as_deref().is_some_and(|registered| {
|
|
dunce::canonicalize(registered).unwrap_or_else(|_| registered.to_path_buf())
|
|
!= dunce::canonicalize(workspace).unwrap_or_else(|_| workspace.clone())
|
|
}) {
|
|
continue;
|
|
}
|
|
let Some(mut p) = inspect_plugin_dir(
|
|
&dir,
|
|
AgentPluginSource::ClaudeUser,
|
|
McpScope::Workspace,
|
|
marketplace.as_deref(),
|
|
true,
|
|
) else {
|
|
continue;
|
|
};
|
|
let enabled = native_plugin_enabled(
|
|
AgentPluginSource::ClaudeUser,
|
|
McpScope::Workspace,
|
|
Some(home),
|
|
Some(workspace),
|
|
&p.name,
|
|
p.marketplace.as_deref(),
|
|
);
|
|
// A project install recorded for this workspace without an `enabledPlugins`
|
|
// entry is shown disabled, matching Claude Code, instead of being hidden.
|
|
match (enabled, project_path.is_some()) {
|
|
(Some(enabled), _) => p.default_enabled = enabled,
|
|
(None, true) => p.default_enabled = false,
|
|
(None, false) => continue,
|
|
}
|
|
p.workspace_root = Some(workspace.clone().into());
|
|
push(p);
|
|
}
|
|
} else if let Some(mut p) =
|
|
inspect_plugin_dir(&dir, AgentPluginSource::ClaudeUser, McpScope::User, marketplace.as_deref(), true)
|
|
{
|
|
if let Some(en) = enabled.or_else(|| {
|
|
native_plugin_enabled(
|
|
AgentPluginSource::ClaudeUser,
|
|
McpScope::User,
|
|
Some(home),
|
|
None,
|
|
&p.name,
|
|
p.marketplace.as_deref(),
|
|
)
|
|
}) {
|
|
p.default_enabled = en;
|
|
}
|
|
push(p.clone());
|
|
push_workspace_scoped_copies(&mut push, p, &all_ws, Some(home));
|
|
}
|
|
}
|
|
|
|
// OpenAI Codex (`~/.codex/plugins/cache/<marketplace>/<plugin>/<version>`).
|
|
let codex_states = read_codex_plugin_states(&home.join(".codex/config.toml"));
|
|
for (dir, mkt) in scan_versioned_plugin_container(&home.join(".codex/plugins/cache"), true) {
|
|
if let Some(mut p) =
|
|
inspect_plugin_dir(&dir, AgentPluginSource::CodexUser, McpScope::User, mkt.as_deref(), true)
|
|
{
|
|
if let Some(&en) = lookup_plugin_bool(&codex_states, &p.name, p.marketplace.as_deref()) {
|
|
p.default_enabled = en;
|
|
}
|
|
push(p.clone());
|
|
push_workspace_scoped_copies(&mut push, p, &all_ws, Some(home));
|
|
}
|
|
}
|
|
|
|
// Gemini CLI (`~/.gemini/extensions/*`).
|
|
for dir in sorted_dirs(&home.join(".gemini/extensions")) {
|
|
if let Some(mut p) = inspect_plugin_dir(&dir, AgentPluginSource::GeminiUser, McpScope::User, None, false) {
|
|
p.default_enabled =
|
|
native_plugin_enabled(p.source, p.scope, Some(home), None, &p.name, p.marketplace.as_deref())
|
|
.unwrap_or(true);
|
|
push(p.clone());
|
|
push_workspace_scoped_copies(&mut push, p, &all_ws, Some(home));
|
|
}
|
|
}
|
|
}
|
|
|
|
out
|
|
}
|
|
|
|
fn push_workspace_scoped_copies(
|
|
push: &mut impl FnMut(AgentPlugin),
|
|
plugin: AgentPlugin,
|
|
workspaces: &[PathBuf],
|
|
home: Option<&Path>,
|
|
) {
|
|
for workspace in workspaces {
|
|
let Some(enabled) = native_plugin_enabled(
|
|
plugin.source,
|
|
McpScope::Workspace,
|
|
home,
|
|
Some(workspace),
|
|
&plugin.name,
|
|
plugin.marketplace.as_deref(),
|
|
) else {
|
|
continue;
|
|
};
|
|
let mut scoped = plugin.clone();
|
|
scoped.scope = McpScope::Workspace;
|
|
scoped.workspace_root = Some(workspace.clone().into());
|
|
scoped.default_enabled = enabled;
|
|
push(scoped);
|
|
}
|
|
}
|
|
|
|
fn source_slug(src: AgentPluginSource) -> &'static str {
|
|
match src {
|
|
AgentPluginSource::CopilotUser => "copilot",
|
|
AgentPluginSource::ClaudeUser => "claude",
|
|
AgentPluginSource::CodexUser => "codex",
|
|
AgentPluginSource::GeminiUser => "gemini",
|
|
}
|
|
}
|
|
|
|
fn source_for_harness(harness: &str) -> IdeResult<AgentPluginSource> {
|
|
match normalize_provider_id(harness) {
|
|
"claude" => Ok(AgentPluginSource::ClaudeUser),
|
|
"copilot" => Ok(AgentPluginSource::CopilotUser),
|
|
"codex" => Ok(AgentPluginSource::CodexUser),
|
|
"gemini" => Ok(AgentPluginSource::GeminiUser),
|
|
other => Err(IdeError::invalid(format!("Unsupported agent plugin harness `{other}`"))),
|
|
}
|
|
}
|
|
|
|
fn supports_harness(formats: &[AgentPluginFormat], harness: &str) -> bool {
|
|
match normalize_provider_id(harness) {
|
|
"claude" => formats.contains(&AgentPluginFormat::Claude),
|
|
"copilot" => {
|
|
formats.contains(&AgentPluginFormat::Copilot)
|
|
|| formats.contains(&AgentPluginFormat::Claude)
|
|
|| formats.contains(&AgentPluginFormat::AgentPluginsV1)
|
|
}
|
|
"codex" => {
|
|
formats.contains(&AgentPluginFormat::Codex)
|
|
|| formats.contains(&AgentPluginFormat::Claude)
|
|
|| formats.contains(&AgentPluginFormat::AgentPluginsV1)
|
|
}
|
|
"gemini" => formats.contains(&AgentPluginFormat::GeminiExtension),
|
|
_ => false,
|
|
}
|
|
}
|
|
|
|
/// The harness's plugin store; installs never write outside it.
|
|
fn native_store_root(source: AgentPluginSource, user_home: Option<&Path>) -> IdeResult<PathBuf> {
|
|
let home = user_home.ok_or_else(|| IdeError::unavailable("Cannot locate user home directory"))?;
|
|
Ok(home.join(match source {
|
|
AgentPluginSource::ClaudeUser => ".claude/plugins/cache",
|
|
AgentPluginSource::CopilotUser => ".copilot/installed-plugins",
|
|
AgentPluginSource::CodexUser => ".codex/plugins/cache",
|
|
AgentPluginSource::GeminiUser => ".gemini/extensions",
|
|
}))
|
|
}
|
|
|
|
/// A marketplace or plugin name used verbatim as one folder name, as the harness CLIs do.
|
|
fn store_segment(raw: &str, what: &str) -> IdeResult<String> {
|
|
let name = raw.trim();
|
|
let safe = !name.is_empty()
|
|
&& !matches!(name, "." | "..")
|
|
&& !name.starts_with('.')
|
|
&& !name.chars().any(|c| matches!(c, '/' | '\\' | ':') || c.is_control());
|
|
if safe { Ok(name.to_owned()) } else { Err(IdeError::invalid(format!("Invalid {what} name `{name}`"))) }
|
|
}
|
|
|
|
fn native_plugin_dir(
|
|
source: AgentPluginSource,
|
|
user_home: Option<&Path>,
|
|
marketplace: Option<&str>,
|
|
) -> IdeResult<PathBuf> {
|
|
let store = native_store_root(source, user_home)?;
|
|
let marketplace = marketplace.map(str::trim).filter(|m| !m.is_empty());
|
|
Ok(match source {
|
|
AgentPluginSource::ClaudeUser => store.join(store_segment(
|
|
marketplace.ok_or_else(|| IdeError::invalid("Claude Code plugins require a named marketplace"))?,
|
|
"marketplace",
|
|
)?),
|
|
AgentPluginSource::CopilotUser | AgentPluginSource::CodexUser => match marketplace {
|
|
Some(m) => store.join(store_segment(m, "marketplace")?),
|
|
None => store.join("_direct"),
|
|
},
|
|
AgentPluginSource::GeminiUser => store,
|
|
})
|
|
}
|
|
|
|
fn plugin_native_key(plugin: &AgentPlugin) -> String {
|
|
plugin
|
|
.marketplace
|
|
.as_deref()
|
|
.filter(|m| !m.is_empty() && *m != "_direct")
|
|
.map(|m| format!("{}@{m}", plugin.name))
|
|
.unwrap_or_else(|| plugin.name.clone())
|
|
}
|
|
|
|
fn native_settings_path(
|
|
source: AgentPluginSource,
|
|
scope: McpScope,
|
|
home: Option<&Path>,
|
|
workspace_root: Option<&Path>,
|
|
) -> IdeResult<PathBuf> {
|
|
let root = match scope {
|
|
McpScope::User => home.ok_or_else(|| IdeError::unavailable("Cannot locate user home directory"))?,
|
|
McpScope::Workspace => {
|
|
workspace_root.ok_or_else(|| IdeError::invalid("Open a project to configure workspace agent plugins"))?
|
|
}
|
|
};
|
|
Ok(match (source, scope) {
|
|
(AgentPluginSource::ClaudeUser, McpScope::User) => root.join(".claude/settings.json"),
|
|
(AgentPluginSource::ClaudeUser, McpScope::Workspace) => root.join(".claude/settings.json"),
|
|
(AgentPluginSource::CopilotUser, McpScope::User) => root.join(".copilot/settings.json"),
|
|
(AgentPluginSource::CopilotUser, McpScope::Workspace) => root.join(".github/copilot/settings.json"),
|
|
(AgentPluginSource::CodexUser, McpScope::User) => root.join(".codex/config.toml"),
|
|
(AgentPluginSource::CodexUser, McpScope::Workspace) => root.join(".codex/config.toml"),
|
|
(AgentPluginSource::GeminiUser, _) => home
|
|
.ok_or_else(|| IdeError::unavailable("Cannot locate user home directory"))?
|
|
.join(".gemini/extensions/extension-enablement.json"),
|
|
})
|
|
}
|
|
|
|
fn read_json_object(path: &Path) -> IdeResult<Map<String, Value>> {
|
|
match std::fs::read_to_string(path) {
|
|
Ok(text) => parse_jsonc(&text)
|
|
.map_err(|e| IdeError::invalid(format!("Invalid {}: {e}", path.display())))?
|
|
.as_object()
|
|
.cloned()
|
|
.ok_or_else(|| IdeError::invalid(format!("{} is not a JSON object", path.display()))),
|
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Map::new()),
|
|
Err(e) => Err(e.into()),
|
|
}
|
|
}
|
|
|
|
fn set_json_plugin_enabled(path: &Path, key: &str, enabled: bool) -> IdeResult<()> {
|
|
let mut text = match std::fs::read_to_string(path) {
|
|
Ok(text) => text,
|
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => "{}\n".to_owned(),
|
|
Err(e) => return Err(e.into()),
|
|
};
|
|
set_json_object_value_member(&mut text, "enabledPlugins", key, if enabled { "true" } else { "false" })
|
|
.map_err(|e| IdeError::invalid(format!("Invalid {}: {e}", path.display())))?;
|
|
parse_jsonc(&text).map_err(|e| IdeError::invalid(format!("Invalid {} after update: {e}", path.display())))?;
|
|
write_native_text(path, &text)
|
|
}
|
|
|
|
/// Adds `parent_key.key` only when it is missing, leaving a user's existing entry untouched.
|
|
fn set_json_object_member_if_absent(path: &Path, parent_key: &str, key: &str, value: &Value) -> IdeResult<()> {
|
|
let existing = read_json_object(path)?;
|
|
if existing.get(parent_key).and_then(Value::as_object).is_some_and(|parent| parent.contains_key(key)) {
|
|
return Ok(());
|
|
}
|
|
set_json_object_member(path, parent_key, key, value)
|
|
}
|
|
|
|
fn set_json_object_member(path: &Path, parent_key: &str, key: &str, value: &Value) -> IdeResult<()> {
|
|
let mut text = match std::fs::read_to_string(path) {
|
|
Ok(text) => text,
|
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => "{}\n".to_owned(),
|
|
Err(e) => return Err(e.into()),
|
|
};
|
|
let serialized = serde_json::to_string_pretty(value).map_err(|e| IdeError::invalid(e.to_string()))?;
|
|
set_json_object_value_member(&mut text, parent_key, key, &serialized)
|
|
.map_err(|e| IdeError::invalid(format!("Invalid {}: {e}", path.display())))?;
|
|
parse_jsonc(&text).map_err(|e| IdeError::invalid(format!("Invalid {} after update: {e}", path.display())))?;
|
|
write_native_text(path, &text)
|
|
}
|
|
|
|
fn set_codex_plugin_enabled(path: &Path, key: &str, enabled: bool) -> IdeResult<()> {
|
|
let text = match std::fs::read_to_string(path) {
|
|
Ok(text) => text,
|
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
|
|
Err(e) => return Err(e.into()),
|
|
};
|
|
let mut document = if text.trim().is_empty() {
|
|
toml_edit::DocumentMut::new()
|
|
} else {
|
|
text.parse::<toml_edit::DocumentMut>()
|
|
.map_err(|e| IdeError::invalid(format!("Invalid {}: {e}", path.display())))?
|
|
};
|
|
let leading = take_comment_only_trivia(&mut document);
|
|
if !document.contains_key("plugins") {
|
|
let mut table = toml_edit::Table::new();
|
|
table.set_implicit(true);
|
|
document["plugins"] = toml_edit::Item::Table(table);
|
|
}
|
|
let plugins = document["plugins"]
|
|
.as_table_mut()
|
|
.ok_or_else(|| IdeError::invalid(format!("{} [plugins] is not a table", path.display())))?;
|
|
if !plugins.contains_key(key) {
|
|
plugins.insert(key, toml_edit::Item::Table(toml_edit::Table::new()));
|
|
}
|
|
let plugin = plugins[key]
|
|
.as_table_mut()
|
|
.ok_or_else(|| IdeError::invalid(format!("{} [plugins.{key}] is not a table", path.display())))?;
|
|
plugin["enabled"] = toml_edit::value(enabled);
|
|
write_native_text(path, &format!("{leading}{document}"))
|
|
}
|
|
|
|
fn set_json_object_value_member(text: &mut String, parent_key: &str, key: &str, value: &str) -> Result<(), String> {
|
|
let root = json_object_info(text, 0)?;
|
|
if let Some(parent) = root.member(parent_key) {
|
|
let parent_open = skip_json_trivia(text, parent.start);
|
|
if text.as_bytes().get(parent_open) != Some(&b'{') {
|
|
return Err(format!("{parent_key} is not an object"));
|
|
}
|
|
let object = json_object_info(text, parent_open)?;
|
|
if let Some(member) = object.member(key) {
|
|
text.replace_range(member.start..member.end, value);
|
|
} else {
|
|
insert_json_object_member(text, &object, key, value);
|
|
}
|
|
return Ok(());
|
|
}
|
|
|
|
let nested = format!("{{\n {}: {}\n}}", json_string(key), indent_continuation_lines(value, " ", "\n"));
|
|
insert_json_object_member(text, &root, parent_key, &nested);
|
|
Ok(())
|
|
}
|
|
|
|
fn set_json_top_level_value(path: &Path, key: &str, value: &Value) -> IdeResult<()> {
|
|
let mut text = match std::fs::read_to_string(path) {
|
|
Ok(text) => text,
|
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => "{}\n".to_owned(),
|
|
Err(e) => return Err(e.into()),
|
|
};
|
|
let serialized = serde_json::to_string_pretty(value).map_err(|e| IdeError::invalid(e.to_string()))?;
|
|
let root = json_object_info(&text, 0).map_err(|e| IdeError::invalid(format!("Invalid {}: {e}", path.display())))?;
|
|
if let Some(member) = root.member(key) {
|
|
text.replace_range(member.start..member.end, &serialized);
|
|
} else {
|
|
insert_json_object_member(&mut text, &root, key, &serialized);
|
|
}
|
|
parse_jsonc(&text).map_err(|e| IdeError::invalid(format!("Invalid {} after update: {e}", path.display())))?;
|
|
write_native_text(path, &text)
|
|
}
|
|
|
|
#[derive(Clone, Debug)]
|
|
struct JsonMember {
|
|
name: String,
|
|
start: usize,
|
|
end: usize,
|
|
}
|
|
|
|
#[derive(Clone, Debug)]
|
|
struct JsonObject {
|
|
close: usize,
|
|
members: Vec<JsonMember>,
|
|
}
|
|
|
|
impl JsonObject {
|
|
fn member(&self, name: &str) -> Option<&JsonMember> {
|
|
self.members.iter().find(|member| member.name == name)
|
|
}
|
|
}
|
|
|
|
fn json_object_info(text: &str, from: usize) -> Result<JsonObject, String> {
|
|
let open = skip_json_trivia(text, from);
|
|
if text.as_bytes().get(open) != Some(&b'{') {
|
|
return Err("expected a JSON object".to_owned());
|
|
}
|
|
let bytes = text.as_bytes();
|
|
let mut i = skip_json_trivia(text, open + 1);
|
|
let mut members = Vec::new();
|
|
loop {
|
|
if bytes.get(i) == Some(&b'}') {
|
|
return Ok(JsonObject { close: i, members });
|
|
}
|
|
if bytes.get(i) == Some(&b',') {
|
|
i = skip_json_trivia(text, i + 1);
|
|
continue;
|
|
}
|
|
if bytes.get(i) != Some(&b'"') {
|
|
return Err(format!("expected an object member at byte {i}"));
|
|
}
|
|
let key_end = scan_json_string(text, i)?;
|
|
let name: String = serde_json::from_str(&text[i..key_end]).map_err(|e| e.to_string())?;
|
|
i = skip_json_trivia(text, key_end);
|
|
if bytes.get(i) != Some(&b':') {
|
|
return Err(format!("expected `:` after object member {name:?}"));
|
|
}
|
|
let start = skip_json_trivia(text, i + 1);
|
|
let end = scan_json_value(text, start)?;
|
|
members.push(JsonMember { name, start, end });
|
|
i = skip_json_trivia(text, end);
|
|
if bytes.get(i) == Some(&b',') {
|
|
i = skip_json_trivia(text, i + 1);
|
|
} else if bytes.get(i) != Some(&b'}') {
|
|
return Err(format!("expected `,` or `}}` after object member at byte {i}"));
|
|
}
|
|
}
|
|
}
|
|
|
|
fn insert_json_object_member(text: &mut String, object: &JsonObject, key: &str, value: &str) {
|
|
let close = object.close;
|
|
let newline = if text.contains("\r\n") { "\r\n" } else { "\n" };
|
|
let line_start = text[..close].rfind('\n').map_or(0, |index| index + 1);
|
|
let line_indent: String = text[line_start..].chars().take_while(|c| *c == ' ' || *c == '\t').collect();
|
|
let child_indent = format!("{line_indent} ");
|
|
let value = indent_continuation_lines(value, &child_indent, newline);
|
|
let insertion = if object.members.is_empty() {
|
|
// An empty object (a new file's `{}` included) opens onto its own lines.
|
|
let before_close = text[..close].trim_end_matches([' ', '\t']).len();
|
|
text.replace_range(before_close..close, "");
|
|
let close = before_close;
|
|
let insertion = format!("{newline}{child_indent}{}: {value}{newline}{line_indent}", json_string(key));
|
|
let insertion = if text[..close].ends_with(['\n', '\r']) {
|
|
format!("{child_indent}{}: {value}{newline}{line_indent}", json_string(key))
|
|
} else {
|
|
insertion
|
|
};
|
|
text.insert_str(close, &insertion);
|
|
return;
|
|
} else {
|
|
// Insert right after the last member (and its trailing comma), so the closing brace and
|
|
// any comments before it stay where they are.
|
|
let last_end = object.members.last().map_or(close, |member| member.end);
|
|
let after = skip_json_trivia(text, last_end);
|
|
let (at, comma) = if text.as_bytes().get(after) == Some(&b',') { (after + 1, "") } else { (last_end, ",") };
|
|
let multiline = text[object.members[0].start..close].contains('\n');
|
|
let insertion = if multiline {
|
|
format!("{comma}{newline}{child_indent}{}: {value}", json_string(key))
|
|
} else {
|
|
format!("{comma} {}: {value}", json_string(key))
|
|
};
|
|
(at, insertion)
|
|
};
|
|
text.insert_str(insertion.0, &insertion.1);
|
|
}
|
|
|
|
/// Leading whitespace of the line containing byte `at`.
|
|
fn line_indent_at(text: &str, at: usize) -> String {
|
|
let line_start = text[..at].rfind('\n').map_or(0, |i| i + 1);
|
|
text[line_start..].chars().take_while(|c| *c == ' ' || *c == '\t').collect()
|
|
}
|
|
|
|
/// Indents every line of a multi-line JSON value after the first by `indent`.
|
|
fn indent_continuation_lines(value: &str, indent: &str, newline: &str) -> String {
|
|
let mut lines = value.lines();
|
|
let mut out = lines.next().unwrap_or_default().to_owned();
|
|
for line in lines {
|
|
out.push_str(newline);
|
|
out.push_str(indent);
|
|
out.push_str(line);
|
|
}
|
|
out
|
|
}
|
|
|
|
fn json_string(value: &str) -> String {
|
|
serde_json::to_string(value).unwrap_or_else(|_| format!("\"{value}\""))
|
|
}
|
|
|
|
fn skip_json_trivia(text: &str, mut i: usize) -> usize {
|
|
let bytes = text.as_bytes();
|
|
if i == 0 && bytes.starts_with(&[0xef, 0xbb, 0xbf]) {
|
|
i += 3;
|
|
}
|
|
loop {
|
|
while bytes.get(i).is_some_and(u8::is_ascii_whitespace) {
|
|
i += 1;
|
|
}
|
|
if bytes.get(i) == Some(&b'/') && bytes.get(i + 1) == Some(&b'/') {
|
|
i += 2;
|
|
while bytes.get(i).is_some_and(|ch| *ch != b'\n') {
|
|
i += 1;
|
|
}
|
|
} else if bytes.get(i) == Some(&b'/') && bytes.get(i + 1) == Some(&b'*') {
|
|
i += 2;
|
|
while i < bytes.len() && !(bytes.get(i) == Some(&b'*') && bytes.get(i + 1) == Some(&b'/')) {
|
|
i += 1;
|
|
}
|
|
i = (i + 2).min(bytes.len());
|
|
} else {
|
|
return i;
|
|
}
|
|
}
|
|
}
|
|
|
|
fn scan_json_string(text: &str, start: usize) -> Result<usize, String> {
|
|
let bytes = text.as_bytes();
|
|
let mut i = start + 1;
|
|
while i < bytes.len() {
|
|
match bytes[i] {
|
|
b'\\' => i = (i + 2).min(bytes.len()),
|
|
b'"' => return Ok(i + 1),
|
|
_ => i += 1,
|
|
}
|
|
}
|
|
Err("unterminated JSON string".to_owned())
|
|
}
|
|
|
|
fn scan_json_value(text: &str, start: usize) -> Result<usize, String> {
|
|
let bytes = text.as_bytes();
|
|
match bytes.get(start) {
|
|
Some(b'"') => scan_json_string(text, start),
|
|
Some(b'{') | Some(b'[') => {
|
|
let mut stack = vec![bytes[start]];
|
|
let mut i = start + 1;
|
|
while i < bytes.len() {
|
|
match bytes[i] {
|
|
b'"' => i = scan_json_string(text, i)?,
|
|
b'/' if bytes.get(i + 1) == Some(&b'/') => {
|
|
i = skip_json_trivia(text, i);
|
|
}
|
|
b'/' if bytes.get(i + 1) == Some(&b'*') => {
|
|
i = skip_json_trivia(text, i);
|
|
}
|
|
b'{' | b'[' => {
|
|
stack.push(bytes[i]);
|
|
i += 1;
|
|
}
|
|
b'}' | b']' => {
|
|
let expected = if bytes[i] == b'}' { b'{' } else { b'[' };
|
|
if stack.pop() != Some(expected) {
|
|
return Err("mismatched JSON container".to_owned());
|
|
}
|
|
i += 1;
|
|
if stack.is_empty() {
|
|
return Ok(i);
|
|
}
|
|
}
|
|
_ => i += 1,
|
|
}
|
|
}
|
|
Err("unterminated JSON container".to_owned())
|
|
}
|
|
Some(_) => {
|
|
let mut i = start;
|
|
while bytes.get(i).is_some_and(|ch| !matches!(ch, b' ' | b'\t' | b'\r' | b'\n' | b',' | b'}' | b']' | b'/'))
|
|
{
|
|
i += 1;
|
|
}
|
|
if i == start { Err(format!("invalid JSON value at byte {start}")) } else { Ok(i) }
|
|
}
|
|
None => Err("missing JSON value".to_owned()),
|
|
}
|
|
}
|
|
|
|
fn write_native_text(path: &Path, text: &str) -> IdeResult<()> {
|
|
if let Some(parent) = path.parent() {
|
|
std::fs::create_dir_all(parent)?;
|
|
}
|
|
static NEXT_TMP: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
|
let nonce =
|
|
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or_default();
|
|
let seq = NEXT_TMP.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
|
let file_name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
|
let tmp = path.with_file_name(format!(".{file_name}.tmp-{}-{nonce}-{seq}", std::process::id()));
|
|
if let Err(error) = std::fs::write(&tmp, text) {
|
|
let _ = std::fs::remove_file(&tmp);
|
|
return Err(error.into());
|
|
}
|
|
std::fs::rename(&tmp, path).inspect_err(|_| {
|
|
let _ = std::fs::remove_file(&tmp);
|
|
})?;
|
|
Ok(())
|
|
}
|
|
|
|
fn gemini_scope_path(scope: McpScope, home: Option<&Path>, workspace_root: Option<&Path>) -> IdeResult<PathBuf> {
|
|
match scope {
|
|
McpScope::User => {
|
|
home.ok_or_else(|| IdeError::unavailable("Cannot locate user home directory")).map(Path::to_path_buf)
|
|
}
|
|
McpScope::Workspace => workspace_root
|
|
.ok_or_else(|| IdeError::invalid("Open a project to configure workspace agent plugins"))
|
|
.map(Path::to_path_buf),
|
|
}
|
|
}
|
|
|
|
fn gemini_enablement_rule(path: &Path, enabled: bool) -> String {
|
|
let mut normalized = path.to_string_lossy().replace('\\', "/");
|
|
if !normalized.starts_with('/') {
|
|
normalized.insert(0, '/');
|
|
}
|
|
normalized = format!("{}/", normalized.trim_end_matches('/'));
|
|
format!("{}{}*", if enabled { "" } else { "!" }, normalized)
|
|
}
|
|
|
|
fn gemini_rule_base(rule: &str) -> (String, bool, bool) {
|
|
let (without_bang, disabled) = match rule.strip_prefix('!') {
|
|
Some(value) => (value, true),
|
|
None => (rule, false),
|
|
};
|
|
let (base, include_subdirs) = match without_bang.strip_suffix('*') {
|
|
Some(value) => (value, true),
|
|
None => (without_bang, false),
|
|
};
|
|
(base.to_owned(), disabled, include_subdirs)
|
|
}
|
|
|
|
/// Whether `extension-enablement.json` has a rule of the workspace's own (what
|
|
/// `gemini extensions enable/disable --scope workspace` writes there), as opposed to one it
|
|
/// inherits, such as the user-scope rule for the home folder.
|
|
fn gemini_workspace_owns_rule(path: &Path, name: &str, workspace: &Path) -> bool {
|
|
let Ok(text) = std::fs::read_to_string(path) else { return false };
|
|
let Ok(root) = parse_jsonc(&text) else { return false };
|
|
let (own_base, _, _) = gemini_rule_base(&gemini_enablement_rule(workspace, true));
|
|
root.get(name)
|
|
.and_then(|e| e.get("overrides"))
|
|
.and_then(Value::as_array)
|
|
.into_iter()
|
|
.flatten()
|
|
.filter_map(Value::as_str)
|
|
.any(|rule| gemini_rule_base(rule).0 == own_base)
|
|
}
|
|
|
|
fn read_gemini_plugin_enabled(path: &Path, name: &str, scope_path: &Path) -> Option<bool> {
|
|
let text = std::fs::read_to_string(path).ok()?;
|
|
let root = parse_jsonc(&text).ok()?;
|
|
let overrides = root.get(name)?.get("overrides")?.as_array()?.iter().filter_map(Value::as_str);
|
|
let current = format!("{}/", scope_path.to_string_lossy().replace('\\', "/").trim_end_matches('/'));
|
|
let current = if current.starts_with('/') { current } else { format!("/{current}") };
|
|
let mut enabled = true;
|
|
let mut matched = false;
|
|
for rule in overrides {
|
|
let (base, disabled, include_subdirs) = gemini_rule_base(rule);
|
|
let applies = if include_subdirs { current.starts_with(&base) } else { current == base };
|
|
if applies {
|
|
enabled = !disabled;
|
|
matched = true;
|
|
}
|
|
}
|
|
matched.then_some(enabled)
|
|
}
|
|
|
|
fn set_gemini_plugin_enabled(path: &Path, name: &str, enabled: bool, scope_path: &Path) -> IdeResult<()> {
|
|
let mut root = read_json_object(path)?;
|
|
let extension = root
|
|
.entry(name.to_owned())
|
|
.or_insert_with(|| json!({ "overrides": [] }))
|
|
.as_object_mut()
|
|
.ok_or_else(|| IdeError::invalid(format!("{}.{} is not an object", path.display(), name)))?;
|
|
let overrides = extension
|
|
.entry("overrides")
|
|
.or_insert_with(|| json!([]))
|
|
.as_array_mut()
|
|
.ok_or_else(|| IdeError::invalid(format!("{}.{}.overrides is not an array", path.display(), name)))?;
|
|
let rule = gemini_enablement_rule(scope_path, enabled);
|
|
let (new_base, _, new_include_subdirs) = gemini_rule_base(&rule);
|
|
overrides.retain(|value| {
|
|
let Some(existing) = value.as_str() else { return true };
|
|
let (base, _, include_subdirs) = gemini_rule_base(existing);
|
|
if base == new_base {
|
|
return false;
|
|
}
|
|
!(new_include_subdirs && include_subdirs && base.starts_with(&new_base))
|
|
});
|
|
overrides.push(json!(rule));
|
|
let extension = root
|
|
.get(name)
|
|
.cloned()
|
|
.ok_or_else(|| IdeError::invalid(format!("Missing Gemini extension state for `{name}`")))?;
|
|
set_json_top_level_value(path, name, &extension)
|
|
}
|
|
|
|
/// Serializes read-modify-write edits of native harness configs within this process.
|
|
static NATIVE_CONFIG_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
|
|
|
fn native_config_guard() -> std::sync::MutexGuard<'static, ()> {
|
|
NATIVE_CONFIG_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
|
|
}
|
|
|
|
/// Writes an enabled/disabled value to the native configuration owned by the harness.
|
|
pub fn set_plugin_enabled(
|
|
plugin: &AgentPlugin,
|
|
enabled: bool,
|
|
user_home: Option<&Path>,
|
|
workspace_root: Option<&Path>,
|
|
) -> IdeResult<()> {
|
|
let _guard = native_config_guard();
|
|
set_plugin_enabled_locked(plugin, enabled, user_home, workspace_root)
|
|
}
|
|
|
|
fn set_plugin_enabled_locked(
|
|
plugin: &AgentPlugin,
|
|
enabled: bool,
|
|
user_home: Option<&Path>,
|
|
workspace_root: Option<&Path>,
|
|
) -> IdeResult<()> {
|
|
// A workspace row is enabled in the workspace that discovered it, not the window's primary root.
|
|
let workspace_root = plugin.workspace_root.as_ref().map(|root| root.0.as_path()).or(workspace_root);
|
|
let path = native_settings_path(plugin.source, plugin.scope, user_home, workspace_root)?;
|
|
match (plugin.source, plugin.scope) {
|
|
(AgentPluginSource::GeminiUser, _) => {
|
|
let scope_path = gemini_scope_path(plugin.scope, user_home, workspace_root)?;
|
|
set_gemini_plugin_enabled(&path, &plugin.name, enabled, &scope_path)
|
|
}
|
|
(AgentPluginSource::CodexUser, _) => set_codex_plugin_enabled(&path, &plugin_native_key(plugin), enabled),
|
|
(AgentPluginSource::ClaudeUser, _) => set_json_plugin_enabled(&path, &plugin_native_key(plugin), enabled),
|
|
(AgentPluginSource::CopilotUser, McpScope::Workspace) => {
|
|
let key = copilot_marketplace_key(plugin).ok_or_else(|| {
|
|
IdeError::invalid("Copilot repository settings can only enable plugins from a marketplace")
|
|
})?;
|
|
set_json_plugin_enabled(&path, &key, enabled)
|
|
}
|
|
(AgentPluginSource::CopilotUser, McpScope::User) => {
|
|
// Mirrors `copilot plugin enable/disable`: marketplace plugins keep `enabledPlugins` in
|
|
// settings.json and their `installedPlugins` record in sync; direct installs only have the record.
|
|
if let Some(key) = copilot_marketplace_key(plugin) {
|
|
set_json_plugin_enabled(&path, &key, enabled)?;
|
|
}
|
|
let home = user_home.ok_or_else(|| IdeError::unavailable("Cannot locate user home directory"))?;
|
|
let updated = set_copilot_installed_enabled(&home.join(".copilot/config.json"), plugin, enabled)?;
|
|
if !updated && copilot_marketplace_key(plugin).is_none() {
|
|
return Err(IdeError::not_found(format!(
|
|
"Copilot has no installed record for `{}`; reinstall it with Copilot",
|
|
plugin.name
|
|
)));
|
|
}
|
|
Ok(())
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Records a Copilot install the way `copilot plugin install` does: an `installedPlugins` entry
|
|
/// in `~/.copilot/config.json` and, for marketplace plugins, the marketplace in
|
|
/// `extraKnownMarketplaces`. A workspace install stays off globally and is enabled by the
|
|
/// repository's `.github/copilot/settings.json`.
|
|
fn register_copilot_plugin(
|
|
plugin: &AgentPlugin,
|
|
user_home: Option<&Path>,
|
|
workspace_root: Option<&Path>,
|
|
provenance: &InstalledPluginProvenance,
|
|
enabled: bool,
|
|
) -> IdeResult<()> {
|
|
let home = user_home.ok_or_else(|| IdeError::unavailable("Cannot locate user home directory"))?;
|
|
let live = copilot_installs_live(
|
|
plugin.source,
|
|
&provenance.source_kind,
|
|
provenance.marketplace.as_deref(),
|
|
provenance.marketplace_source.as_deref(),
|
|
);
|
|
if !live {
|
|
register_copilot_installed_record(home, plugin, provenance, enabled)?;
|
|
}
|
|
register_copilot_marketplace(plugin, user_home, workspace_root, provenance)
|
|
}
|
|
|
|
fn register_copilot_installed_record(
|
|
home: &Path,
|
|
plugin: &AgentPlugin,
|
|
provenance: &InstalledPluginProvenance,
|
|
enabled: bool,
|
|
) -> IdeResult<()> {
|
|
let config = home.join(".copilot/config.json");
|
|
let installed_source = match (provenance.source_kind.as_str(), &provenance.owner, &provenance.repo) {
|
|
("github", Some(owner), Some(repo)) => {
|
|
let mut source = json!({ "source": "github", "repo": format!("{owner}/{repo}") });
|
|
if !provenance.subpath.is_empty() {
|
|
source["path"] = json!(provenance.subpath);
|
|
}
|
|
source
|
|
}
|
|
_ => json!({ "source": "local", "path": provenance.local_path.clone().unwrap_or_default() }),
|
|
};
|
|
let record = json!({
|
|
"name": plugin.name,
|
|
"marketplace": plugin.marketplace.as_deref().filter(|m| *m != "_direct").unwrap_or_default(),
|
|
"version": plugin.version,
|
|
"installed_at": jiff::Timestamp::now().to_string(),
|
|
"cache_path": plugin.root_path.0,
|
|
"installed_source": installed_source,
|
|
"enabled": enabled && plugin.scope == McpScope::User,
|
|
});
|
|
let record_text = serde_json::to_string_pretty(&record).map_err(|e| IdeError::internal(e.to_string()))?;
|
|
let mut text = match std::fs::read_to_string(&config) {
|
|
Ok(text) => text,
|
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => "{}\n".to_owned(),
|
|
Err(e) => return Err(e.into()),
|
|
};
|
|
let invalid = |e: String| IdeError::invalid(format!("Invalid {}: {e}", config.display()));
|
|
let newline = if text.contains("\r\n") { "\r\n" } else { "\n" };
|
|
match installed_plugin_items(&text).map_err(invalid)? {
|
|
None => {
|
|
let root = json_object_info(&text, 0).map_err(invalid)?;
|
|
let array = format!("[\n {}\n]", indent_continuation_lines(&record_text, " ", "\n"));
|
|
insert_json_object_member(&mut text, &root, "installedPlugins", &array);
|
|
}
|
|
Some(items) => {
|
|
// Replace this plugin's record in place (dropping duplicates), or append it; every
|
|
// other record and comment in the array stays as it is.
|
|
let matching: Vec<(usize, usize)> = items
|
|
.iter()
|
|
.copied()
|
|
.filter(|(start, end)| {
|
|
parse_jsonc(&text[*start..*end]).is_ok_and(|r| copilot_record_matches(&r, plugin))
|
|
})
|
|
.collect();
|
|
if let Some(&(first_start, first_end)) = matching.first() {
|
|
// Extra matches come after the first, so each has a previous element whose end
|
|
// starts the `,` separator to remove with it.
|
|
for &(start, end) in matching.iter().skip(1).rev() {
|
|
let previous_end = items.iter().map(|(_, e)| *e).filter(|e| *e <= start).max().unwrap_or(start);
|
|
text.replace_range(previous_end..end, "");
|
|
}
|
|
let indent = line_indent_at(&text, first_start);
|
|
text.replace_range(first_start..first_end, &indent_continuation_lines(&record_text, &indent, newline));
|
|
} else if let Some(&(last_start, last_end)) = items.last() {
|
|
let indent = line_indent_at(&text, last_start);
|
|
let value = indent_continuation_lines(&record_text, &indent, newline);
|
|
text.insert_str(last_end, &format!(",{newline}{indent}{value}"));
|
|
} else {
|
|
let root = json_object_info(&text, 0).map_err(invalid)?;
|
|
let member =
|
|
root.member("installedPlugins").ok_or_else(|| invalid("missing installedPlugins".into()))?;
|
|
let (close, _) = json_array_items(&text, member.start).map_err(invalid)?;
|
|
let close_indent = line_indent_at(&text, member.start);
|
|
let indent = format!("{close_indent} ");
|
|
let value = indent_continuation_lines(&record_text, &indent, newline);
|
|
text.insert_str(close, &format!("{newline}{indent}{value}{newline}{close_indent}"));
|
|
}
|
|
}
|
|
}
|
|
parse_jsonc(&text).map_err(|e| invalid(format!("after update: {e}")))?;
|
|
write_native_text(&config, &text)
|
|
}
|
|
|
|
fn register_copilot_marketplace(
|
|
plugin: &AgentPlugin,
|
|
user_home: Option<&Path>,
|
|
workspace_root: Option<&Path>,
|
|
provenance: &InstalledPluginProvenance,
|
|
) -> IdeResult<()> {
|
|
if let Some(marketplace) = provenance.marketplace.as_deref().map(str::trim).filter(|m| !m.is_empty()) {
|
|
let source = match (provenance.source_kind.as_str(), &provenance.owner, &provenance.repo) {
|
|
("github", Some(owner), Some(repo)) => json!({ "source": "github", "repo": format!("{owner}/{repo}") }),
|
|
_ => {
|
|
let path = provenance
|
|
.marketplace_source
|
|
.as_deref()
|
|
.map(PathBuf::from)
|
|
.map(|source| marketplace_root_dir(&source))
|
|
.ok_or_else(|| {
|
|
IdeError::invalid(format!(
|
|
"Cannot register Copilot marketplace `{marketplace}` without its source"
|
|
))
|
|
})?;
|
|
json!({ "source": "directory", "path": path.to_string_lossy() })
|
|
}
|
|
};
|
|
let settings = native_settings_path(plugin.source, plugin.scope, user_home, workspace_root)?;
|
|
set_json_object_member_if_absent(
|
|
&settings,
|
|
"extraKnownMarketplaces",
|
|
marketplace,
|
|
&json!({ "source": source }),
|
|
)?;
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// The directory a marketplace manifest belongs to (`<root>/.claude-plugin/marketplace.json` → `<root>`).
|
|
fn marketplace_root_dir(source: &Path) -> PathBuf {
|
|
if !source.is_file() {
|
|
return source.to_path_buf();
|
|
}
|
|
let parent = source.parent().unwrap_or(source);
|
|
for suffix in [".agents/plugins", ".github/plugin", ".claude-plugin", ".plugin"] {
|
|
if parent.ends_with(suffix) {
|
|
let depth = Path::new(suffix).components().count();
|
|
return parent.ancestors().nth(depth).unwrap_or(parent).to_path_buf();
|
|
}
|
|
}
|
|
parent.to_path_buf()
|
|
}
|
|
|
|
/// `name@marketplace`, the key Copilot uses for marketplace plugins in `enabledPlugins`.
|
|
fn copilot_marketplace_key(plugin: &AgentPlugin) -> Option<String> {
|
|
plugin
|
|
.marketplace
|
|
.as_deref()
|
|
.map(str::trim)
|
|
.filter(|m| !m.is_empty() && *m != "_direct")
|
|
.map(|m| format!("{}@{m}", plugin.name))
|
|
}
|
|
|
|
/// Whether a Copilot `installedPlugins` record is exactly this plugin: same cache path, or the same
|
|
/// name and marketplace (`""` for direct installs).
|
|
fn copilot_record_matches(record: &Value, plugin: &AgentPlugin) -> bool {
|
|
if let Some(cache_path) = record.get("cache_path").and_then(Value::as_str) {
|
|
let canon = dunce::canonicalize(cache_path).unwrap_or_else(|_| PathBuf::from(cache_path));
|
|
if canon == plugin.root_path.0 {
|
|
return true;
|
|
}
|
|
}
|
|
let marketplace = plugin.marketplace.as_deref().filter(|m| *m != "_direct").unwrap_or_default();
|
|
record.get("name").and_then(Value::as_str) == Some(plugin.name.as_str())
|
|
&& record.get("marketplace").and_then(Value::as_str).unwrap_or_default() == marketplace
|
|
}
|
|
|
|
fn set_copilot_installed_enabled(config_path: &Path, plugin: &AgentPlugin, enabled: bool) -> IdeResult<bool> {
|
|
let Ok(mut text) = std::fs::read_to_string(config_path) else { return Ok(false) };
|
|
let invalid = |e: String| IdeError::invalid(format!("Invalid {}: {e}", config_path.display()));
|
|
let Some(items) = installed_plugin_items(&text).map_err(invalid)? else { return Ok(false) };
|
|
let mut updated = false;
|
|
// Edit each matching record's `enabled` in place, last first so earlier offsets stay valid.
|
|
for (start, end) in items.into_iter().rev() {
|
|
let Ok(record) = parse_jsonc(&text[start..end]) else { continue };
|
|
if !copilot_record_matches(&record, plugin) {
|
|
continue;
|
|
}
|
|
let object = json_object_info(&text, start).map_err(invalid)?;
|
|
let value = if enabled { "true" } else { "false" };
|
|
match object.member("enabled") {
|
|
Some(member) => text.replace_range(member.start..member.end, value),
|
|
None => insert_json_object_member(&mut text, &object, "enabled", value),
|
|
}
|
|
updated = true;
|
|
}
|
|
if updated {
|
|
parse_jsonc(&text).map_err(|e| invalid(format!("after update: {e}")))?;
|
|
write_native_text(config_path, &text)?;
|
|
}
|
|
Ok(updated)
|
|
}
|
|
|
|
/// Spans of the `installedPlugins` array's elements, or `None` when the file has no such array.
|
|
fn installed_plugin_items(text: &str) -> Result<Option<Vec<(usize, usize)>>, String> {
|
|
let root = json_object_info(text, 0)?;
|
|
let Some(member) = root.member("installedPlugins") else { return Ok(None) };
|
|
json_array_items(text, member.start).map(|(_, items)| Some(items))
|
|
}
|
|
|
|
/// The closing bracket and element spans of the JSON array starting at `from`.
|
|
fn json_array_items(text: &str, from: usize) -> Result<(usize, Vec<(usize, usize)>), String> {
|
|
let open = skip_json_trivia(text, from);
|
|
if text.as_bytes().get(open) != Some(&b'[') {
|
|
return Err("expected a JSON array".to_owned());
|
|
}
|
|
let bytes = text.as_bytes();
|
|
let mut i = skip_json_trivia(text, open + 1);
|
|
let mut items = Vec::new();
|
|
loop {
|
|
match bytes.get(i) {
|
|
Some(b']') => return Ok((i, items)),
|
|
Some(b',') => i = skip_json_trivia(text, i + 1),
|
|
Some(_) => {
|
|
let end = scan_json_value(text, i)?;
|
|
items.push((i, end));
|
|
i = skip_json_trivia(text, end);
|
|
if !matches!(bytes.get(i), Some(b',') | Some(b']')) {
|
|
return Err(format!("expected `,` or `]` after array element at byte {i}"));
|
|
}
|
|
}
|
|
None => return Err("unterminated JSON array".to_owned()),
|
|
}
|
|
}
|
|
}
|
|
|
|
fn register_native_plugin(
|
|
plugin: &AgentPlugin,
|
|
user_home: Option<&Path>,
|
|
workspace_root: Option<&Path>,
|
|
provenance: &InstalledPluginProvenance,
|
|
enabled: bool,
|
|
) -> IdeResult<()> {
|
|
let _guard = native_config_guard();
|
|
if plugin.source == AgentPluginSource::ClaudeUser {
|
|
let home = user_home.ok_or_else(|| IdeError::unavailable("Cannot locate user home directory"))?;
|
|
let path = home.join(".claude/plugins/installed_plugins.json");
|
|
let mut root = read_json_object(&path)?;
|
|
root.insert("version".to_owned(), json!(2));
|
|
let plugins = root
|
|
.entry("plugins")
|
|
.or_insert_with(|| json!({}))
|
|
.as_object_mut()
|
|
.ok_or_else(|| IdeError::invalid(format!("{}.plugins is not an object", path.display())))?;
|
|
let key = plugin_native_key(plugin);
|
|
let scope = if plugin.scope == McpScope::Workspace { "project" } else { "user" };
|
|
let installs = plugins.entry(key).or_insert_with(|| json!([]));
|
|
let installs = installs
|
|
.as_array_mut()
|
|
.ok_or_else(|| IdeError::invalid(format!("{}.plugins entry is not an array", path.display())))?;
|
|
let project_path = if plugin.scope == McpScope::Workspace {
|
|
let workspace =
|
|
workspace_root.ok_or_else(|| IdeError::invalid("Open a project to install workspace agent plugins"))?;
|
|
Some(dunce::canonicalize(workspace).unwrap_or_else(|_| workspace.to_path_buf()))
|
|
} else {
|
|
None
|
|
};
|
|
installs.retain(|entry| {
|
|
entry.get("scope").and_then(Value::as_str) != Some(scope)
|
|
|| project_path.as_ref().is_some_and(|path| {
|
|
entry.get("projectPath").and_then(Value::as_str) != Some(path.to_string_lossy().as_ref())
|
|
})
|
|
});
|
|
let timestamp = jiff::Timestamp::now().to_string();
|
|
let mut record = json!({
|
|
"installPath": plugin.root_path.0,
|
|
"version": plugin.version,
|
|
"scope": scope,
|
|
"installedAt": timestamp,
|
|
"lastUpdated": timestamp,
|
|
});
|
|
if let Some(commit_sha) = &provenance.commit_sha {
|
|
record["gitCommitSha"] = json!(commit_sha);
|
|
}
|
|
if let Some(project_path) = project_path {
|
|
record["projectPath"] = json!(project_path);
|
|
}
|
|
installs.push(record);
|
|
let plugins = root.get("plugins").cloned().unwrap_or_else(|| json!({}));
|
|
set_json_top_level_value(&path, "version", &json!(2))?;
|
|
set_json_top_level_value(&path, "plugins", &plugins)?;
|
|
if let Some(marketplace) = provenance.marketplace.as_deref() {
|
|
let marketplace_source = match (
|
|
provenance.source_kind.as_str(),
|
|
provenance.marketplace_source.as_deref(),
|
|
provenance.owner.as_deref(),
|
|
provenance.repo.as_deref(),
|
|
) {
|
|
("github", _, Some(owner), Some(repo)) => Some(json!({
|
|
"source": "github",
|
|
"repo": format!("{owner}/{repo}")
|
|
})),
|
|
("local", Some(source), _, _) => {
|
|
let source = PathBuf::from(source);
|
|
let source_kind = if source.is_file() { "file" } else { "directory" };
|
|
Some(json!({
|
|
"source": source_kind,
|
|
"path": source.to_string_lossy()
|
|
}))
|
|
}
|
|
_ => None,
|
|
};
|
|
let Some(marketplace_source) = marketplace_source else {
|
|
return Err(IdeError::invalid(format!(
|
|
"Cannot register Claude marketplace `{marketplace}` without its source"
|
|
)));
|
|
};
|
|
let settings = native_settings_path(plugin.source, plugin.scope, user_home, workspace_root)?;
|
|
set_json_object_member(
|
|
&settings,
|
|
"extraKnownMarketplaces",
|
|
marketplace,
|
|
&json!({ "source": marketplace_source }),
|
|
)?;
|
|
}
|
|
} else if plugin.source == AgentPluginSource::CopilotUser {
|
|
register_copilot_plugin(plugin, user_home, workspace_root, provenance, enabled)?;
|
|
}
|
|
set_plugin_enabled_locked(plugin, enabled, user_home, workspace_root)
|
|
}
|
|
|
|
/// Resolves discovered plugins against Workspace Trust and native enablement.
|
|
pub fn resolve_plugins(
|
|
discovered: Vec<AgentPlugin>,
|
|
policy: &PluginsPolicy,
|
|
_secrets: Option<&dyn EnvSecrets>,
|
|
) -> Vec<AgentPluginState> {
|
|
let trusted = policy.workspace_trusted;
|
|
discovered
|
|
.into_iter()
|
|
.map(|mut plugin| {
|
|
let user_pol = lookup_entry_policy(&policy.user.entries, &plugin);
|
|
let ws_pol = lookup_entry_policy(&policy.workspace.entries, &plugin);
|
|
|
|
for field in &mut plugin.config_fields {
|
|
if field.kind == AgentPluginConfigFieldKind::Secret {
|
|
field.value.clear();
|
|
field.has_secret = false;
|
|
} else {
|
|
let val = ws_pol
|
|
.filter(|_| trusted)
|
|
.and_then(|p| p.config.get(&field.key))
|
|
.or_else(|| user_pol.and_then(|p| p.config.get(&field.key)))
|
|
.or(field.default_value.as_ref())
|
|
.cloned()
|
|
.unwrap_or_default();
|
|
field.value = val;
|
|
}
|
|
}
|
|
|
|
if !trusted && plugin.scope == McpScope::Workspace {
|
|
return AgentPluginState {
|
|
plugin,
|
|
enabled: false,
|
|
origin: AgentPluginOrigin::Trust,
|
|
consent_required: false,
|
|
};
|
|
}
|
|
|
|
// A consent-requiring plugin without a computed hash can never match an approval.
|
|
let consent_required = plugin.capabilities.requires_consent
|
|
&& !capability_approval_key(&plugin).is_some_and(|key| policy.approved_capabilities.contains(&key));
|
|
let origin = if consent_required { AgentPluginOrigin::Consent } else { AgentPluginOrigin::None };
|
|
|
|
AgentPluginState { enabled: plugin.default_enabled && !consent_required, plugin, origin, consent_required }
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
/// Builds the full [`AgentPluginCatalog`] including discovered/configured marketplaces and projection counts.
|
|
pub fn resolve_catalog(
|
|
discovered: Vec<AgentPlugin>,
|
|
policy: &PluginsPolicy,
|
|
home: Option<&Path>,
|
|
_secrets: Option<&dyn EnvSecrets>,
|
|
) -> AgentPluginCatalog {
|
|
let states = resolve_plugins(discovered, policy, _secrets);
|
|
let mut projected_skills = 0u32;
|
|
let mut projected_mcp_servers = 0u32;
|
|
let mut projected_rules = 0u32;
|
|
for s in &states {
|
|
if s.enabled {
|
|
projected_skills = projected_skills.saturating_add(s.plugin.capabilities.skill_count);
|
|
projected_mcp_servers = projected_mcp_servers.saturating_add(s.plugin.capabilities.mcp_count);
|
|
projected_rules = projected_rules.saturating_add(s.plugin.capabilities.rule_count);
|
|
}
|
|
}
|
|
let marketplaces = discover_marketplaces(policy, home);
|
|
AgentPluginCatalog { plugins: states, marketplaces, projected_skills, projected_mcp_servers, projected_rules }
|
|
}
|
|
|
|
/// Discovers configured and workspace-embedded marketplaces.
|
|
pub fn discover_marketplaces(policy: &PluginsPolicy, home: Option<&Path>) -> Vec<AgentMarketplaceInfo> {
|
|
let mut out = Vec::new();
|
|
let mut seen = HashSet::new();
|
|
let mut add = |source: String, scope: McpScope, discovered: bool, name_hint: Option<String>| {
|
|
let trimmed = source.trim().to_owned();
|
|
if trimmed.is_empty() || !seen.insert(trimmed.clone()) {
|
|
return;
|
|
}
|
|
let name = name_hint.unwrap_or_else(|| marketplace_label_from_source(&trimmed));
|
|
out.push(AgentMarketplaceInfo { id: trimmed.clone(), name, source: trimmed, scope, discovered });
|
|
};
|
|
|
|
for src in &policy.user.marketplaces {
|
|
add(src.clone(), McpScope::User, false, None);
|
|
}
|
|
if policy.workspace_trusted {
|
|
for src in &policy.workspace.marketplaces {
|
|
add(src.clone(), McpScope::Workspace, false, None);
|
|
}
|
|
for ws in &policy.workspace_roots {
|
|
for rel in MARKETPLACE_MANIFEST_PATHS {
|
|
let candidate = ws.join(rel);
|
|
if candidate.is_file() {
|
|
let name = read_marketplace_name(&candidate);
|
|
add(candidate.to_string_lossy().into_owned(), McpScope::Workspace, true, name);
|
|
}
|
|
}
|
|
for src in read_extra_known_marketplaces(ws) {
|
|
add(src, McpScope::Workspace, true, None);
|
|
}
|
|
}
|
|
}
|
|
if let Some(home) = home {
|
|
// Claude's `known_marketplaces.json`
|
|
if let Ok(text) = std::fs::read_to_string(home.join(".claude/plugins/known_marketplaces.json"))
|
|
&& let Ok(Value::Object(map)) = serde_json::from_str::<Value>(&ide_core::jsonc::strip(&text))
|
|
{
|
|
for (name, val) in map {
|
|
if let Some(repo) = val.pointer("/source/repo").and_then(Value::as_str) {
|
|
add(repo.to_owned(), McpScope::User, true, Some(name));
|
|
} else if let Some(loc) = val.get("installLocation").and_then(Value::as_str) {
|
|
add(loc.to_owned(), McpScope::User, true, Some(name));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
/// Returns skill directories projected by enabled agent plugins (optionally filtered for `provider`).
|
|
/// The rows whose enablement decides what a plugin contributes: a workspace override (a row from a
|
|
/// project's native settings) replaces the user-scope row of the same installed plugin, so a
|
|
/// plugin disabled for the workspace is not projected through its globally enabled row.
|
|
fn effective_projection_states(states: &[AgentPluginState]) -> impl Iterator<Item = &AgentPluginState> {
|
|
let overridden: HashSet<(&'static str, PathBuf)> = states
|
|
.iter()
|
|
.filter(|state| state.plugin.scope == McpScope::Workspace)
|
|
.map(|state| (source_slug(state.plugin.source), state.plugin.root_path.0.clone()))
|
|
.collect();
|
|
states.iter().filter(move |state| {
|
|
state.enabled
|
|
&& !(state.plugin.scope == McpScope::User
|
|
&& overridden.contains(&(source_slug(state.plugin.source), state.plugin.root_path.0.clone())))
|
|
})
|
|
}
|
|
|
|
pub fn projected_skill_roots(states: &[AgentPluginState], provider: Option<&str>) -> Vec<ProjectedSkillRoot> {
|
|
let mut roots = Vec::new();
|
|
for state in effective_projection_states(states) {
|
|
if let Some(provider) = provider
|
|
&& !matches!(
|
|
(state.plugin.source, normalize_provider_id(provider)),
|
|
(AgentPluginSource::ClaudeUser, "claude")
|
|
| (AgentPluginSource::CopilotUser, "copilot")
|
|
| (AgentPluginSource::CodexUser, "codex")
|
|
| (AgentPluginSource::GeminiUser, "gemini")
|
|
)
|
|
{
|
|
continue;
|
|
}
|
|
let skill_source = match state.plugin.source {
|
|
AgentPluginSource::CopilotUser => AgentSkillSource::CopilotUser,
|
|
_ => AgentSkillSource::Plugin,
|
|
};
|
|
for dir in collect_plugin_skill_dirs(&state.plugin.root_path.0) {
|
|
roots.push(ProjectedSkillRoot {
|
|
dir,
|
|
plugin_id: state.plugin.id.clone(),
|
|
plugin_name: state.plugin.display_name.clone(),
|
|
source: skill_source,
|
|
});
|
|
}
|
|
}
|
|
roots
|
|
}
|
|
|
|
/// Workspace root used for `${CLAUDE_PROJECT_DIR}`/`${WORKSPACE_FOLDER}`: the workspace that owns
|
|
/// a workspace row, otherwise the primary root.
|
|
fn plugin_workspace_root<'a>(plugin: &'a AgentPlugin, roots: &'a [PathBuf]) -> Option<&'a Path> {
|
|
plugin.workspace_root.as_ref().map(|root| root.0.as_path()).or_else(|| roots.first().map(PathBuf::as_path))
|
|
}
|
|
|
|
/// Returns inspectable MCP servers projected by enabled agent plugins. Native harnesses still
|
|
/// own execution and any secret userConfig resolution.
|
|
pub fn projected_mcp_servers(
|
|
states: &[AgentPluginState],
|
|
policy: &PluginsPolicy,
|
|
home: Option<&Path>,
|
|
_secrets: Option<&dyn EnvSecrets>,
|
|
) -> Vec<McpServer> {
|
|
let mut out = Vec::new();
|
|
for state in effective_projection_states(states) {
|
|
let ws_root = plugin_workspace_root(&state.plugin, &policy.workspace_roots);
|
|
let resolved_cfg = resolved_config_map(&state.plugin, policy, _secrets);
|
|
let raw_servers = read_plugin_mcp_servers(
|
|
&state.plugin.root_path.0,
|
|
&state.plugin.id,
|
|
home,
|
|
ws_root,
|
|
&state.plugin.config_fields,
|
|
&resolved_cfg,
|
|
);
|
|
let scope = state.plugin.scope;
|
|
for (name, srv) in raw_servers {
|
|
if !srv.enabled {
|
|
continue;
|
|
}
|
|
out.push(McpServer {
|
|
id: format!("plugin:{}:{name}", state.plugin.id),
|
|
name,
|
|
scope,
|
|
transport: srv.transport,
|
|
enabled: true,
|
|
command: srv.command,
|
|
args: srv.args,
|
|
env: srv.env.into_iter().map(|(name, value)| McpKeyValue { name, value }).collect(),
|
|
url: srv.url,
|
|
headers: srv.headers.into_iter().map(|(name, value)| McpKeyValue { name, value }).collect(),
|
|
agents: srv.agents,
|
|
unapproved: false,
|
|
plugin_id: Some(state.plugin.id.clone()),
|
|
plugin_name: Some(state.plugin.display_name.clone()),
|
|
});
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
/// Projects bundled Markdown rule / context files (`rules/*.md`, `rules/*.mdc`,
|
|
/// `com.github.copilot/rules/*.md`, `GEMINI.md`) from enabled agent plugins into `memory.rs`.
|
|
pub fn projected_memory_entries(states: &[AgentPluginState]) -> Vec<AgentMemoryEntry> {
|
|
let mut out = Vec::new();
|
|
for state in effective_projection_states(states) {
|
|
let source = if state.plugin.scope == McpScope::Workspace {
|
|
AgentMemorySource::Workspace
|
|
} else {
|
|
match state.plugin.source {
|
|
AgentPluginSource::CopilotUser => AgentMemorySource::CopilotUser,
|
|
AgentPluginSource::ClaudeUser => AgentMemorySource::ClaudeUser,
|
|
AgentPluginSource::CodexUser => AgentMemorySource::CodexUser,
|
|
AgentPluginSource::GeminiUser => AgentMemorySource::GeminiUser,
|
|
}
|
|
};
|
|
for rule_path in collect_plugin_rule_files(&state.plugin.root_path.0) {
|
|
let Ok(text) = std::fs::read_to_string(&rule_path) else { continue };
|
|
let rel = rule_path
|
|
.strip_prefix(&state.plugin.root_path.0)
|
|
.ok()
|
|
.map(|p| p.to_string_lossy().replace('\\', "/"))
|
|
.unwrap_or_else(|| rule_path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default());
|
|
let id = format!("plugin::{}::{rel}", state.plugin.id);
|
|
let title = format!("{} · {rel}", state.plugin.name);
|
|
let is_gemini = rel.eq_ignore_ascii_case("GEMINI.md") || rel.ends_with("/GEMINI.md");
|
|
let kind = if is_gemini { AgentMemoryKind::Instruction } else { AgentMemoryKind::Rule };
|
|
let line_count = text.lines().count() as u32;
|
|
let byte_len = text.len() as u64;
|
|
let approx_tokens = ((text.chars().count() as u32).saturating_add(3)) / 4;
|
|
let paths = extract_frontmatter_globs(&text);
|
|
let desc =
|
|
first_body_summary(&text).unwrap_or_else(|| format!("Bundled in plugin `{}`", state.plugin.name));
|
|
out.push(AgentMemoryEntry {
|
|
id,
|
|
title,
|
|
description: desc,
|
|
kind,
|
|
source,
|
|
also_in: Vec::new(),
|
|
path: rule_path.into(),
|
|
paths,
|
|
category: None,
|
|
approx_tokens,
|
|
line_count,
|
|
byte_len,
|
|
modified_ms: None,
|
|
writable: false,
|
|
valid: true,
|
|
warnings: Vec::new(),
|
|
plugin_id: Some(state.plugin.id.clone()),
|
|
plugin_name: Some(state.plugin.display_name.clone()),
|
|
});
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
/// Browses a marketplace or plugin repository (`owner/repo[#ref]`, GitHub URL, or local directory/manifest path).
|
|
pub fn browse_marketplace(
|
|
fetcher: &dyn SkillSourceFetcher,
|
|
source: &str,
|
|
user_home: Option<&Path>,
|
|
workspace_root: Option<&Path>,
|
|
cancel: &CancellationToken,
|
|
) -> IdeResult<AgentMarketplaceBrowseResult> {
|
|
let trimmed = source.trim();
|
|
if trimmed.is_empty() {
|
|
return Err(IdeError::invalid(
|
|
"Enter a marketplace or repository such as `github/awesome-copilot`, `owner/repo`, or a local path",
|
|
));
|
|
}
|
|
|
|
// Local filesystem directory or `marketplace.json` path:
|
|
if let Some(local_candidate) = resolve_local_source(trimmed, user_home, workspace_root)
|
|
&& local_candidate.exists()
|
|
{
|
|
return browse_local_marketplace(&local_candidate, trimmed, user_home, workspace_root);
|
|
}
|
|
|
|
let parsed = parse_source(trimmed)?;
|
|
let git_ref = resolve_plugin_source_ref(fetcher, &parsed, cancel)?;
|
|
let tree = fetcher.git_tree(RepoRef { owner: &parsed.owner, repo: &parsed.repo, git_ref: &git_ref }, cancel)?;
|
|
|
|
let target = RepoRef { owner: &parsed.owner, repo: &parsed.repo, git_ref: &git_ref };
|
|
|
|
// 1. Check for a `marketplace.json` manifest in the repository (under `parsed.subpath` if given, or root).
|
|
let sub_prefix = parsed.subpath.as_deref().map(|s| format!("{s}/")).unwrap_or_default();
|
|
for mkt_rel in MARKETPLACE_MANIFEST_PATHS {
|
|
let candidate_path = format!("{sub_prefix}{mkt_rel}");
|
|
if let Some(entry) = tree.tree.iter().find(|e| e.kind == "blob" && e.path == candidate_path) {
|
|
let bytes = fetcher.read_blob(target, &entry.path, &entry.sha, 2 << 20, cancel)?;
|
|
let text = String::from_utf8(bytes).map_err(|_| IdeError::invalid("marketplace.json is not UTF-8"))?;
|
|
let (mkt_name, candidates) = parse_marketplace_json_remote(
|
|
&text,
|
|
&parsed.owner,
|
|
&parsed.repo,
|
|
&git_ref,
|
|
parsed.subpath.as_deref(),
|
|
user_home,
|
|
workspace_root,
|
|
)?;
|
|
if !candidates.is_empty() {
|
|
return Ok(AgentMarketplaceBrowseResult {
|
|
source: trimmed.to_owned(),
|
|
marketplace_name: mkt_name,
|
|
owner: Some(parsed.owner),
|
|
repo: Some(parsed.repo),
|
|
git_ref: Some(git_ref),
|
|
tree_sha: Some(tree.sha),
|
|
candidates,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
// 2. Fallback: scan the repository tree for direct plugin manifests (`plugin.json`, `.claude-plugin/plugin.json`, etc.).
|
|
let mut plugin_roots: BTreeSet<String> = BTreeSet::new();
|
|
for entry in &tree.tree {
|
|
if entry.kind != "blob" {
|
|
continue;
|
|
}
|
|
if !sub_prefix.is_empty() && !entry.path.starts_with(&sub_prefix) {
|
|
continue;
|
|
}
|
|
for (manifest_rel, _) in MANIFEST_CANDIDATES {
|
|
if entry.path == *manifest_rel {
|
|
plugin_roots.insert(String::new());
|
|
} else if let Some(dir) = entry.path.strip_suffix(&format!("/{manifest_rel}")) {
|
|
plugin_roots.insert(dir.to_owned());
|
|
}
|
|
}
|
|
}
|
|
|
|
let mut candidates = Vec::new();
|
|
for root_dir in plugin_roots {
|
|
let prefix = if root_dir.is_empty() { String::new() } else { format!("{root_dir}/") };
|
|
let mut name = root_dir
|
|
.rsplit('/')
|
|
.next()
|
|
.filter(|s| !s.is_empty())
|
|
.map(str::to_owned)
|
|
.unwrap_or_else(|| sanitize_plugin_slug(&parsed.repo));
|
|
let mut display_name = name.clone();
|
|
let mut version = None;
|
|
let mut description = String::new();
|
|
let mut author = None;
|
|
let mut keywords = Vec::new();
|
|
|
|
for (manifest_rel, _) in MANIFEST_CANDIDATES {
|
|
let p = format!("{prefix}{manifest_rel}");
|
|
if let Some(entry) = tree.tree.iter().find(|e| e.kind == "blob" && e.path == p)
|
|
&& let Ok(bytes) = fetcher.read_blob(target, &entry.path, &entry.sha, 256 * 1024, cancel)
|
|
&& let Ok(val) = parse_jsonc(&String::from_utf8_lossy(&bytes))
|
|
{
|
|
if let Some(n) = val.get("name").and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()) {
|
|
name = sanitize_plugin_slug(n);
|
|
display_name = n.to_owned();
|
|
}
|
|
if let Some(dn) = val
|
|
.get("displayName")
|
|
.or_else(|| val.pointer("/interface/displayName"))
|
|
.and_then(Value::as_str)
|
|
.map(str::trim)
|
|
.filter(|s| !s.is_empty())
|
|
{
|
|
display_name = dn.to_owned();
|
|
}
|
|
version = version.or_else(|| val.get("version").and_then(Value::as_str).map(str::to_owned));
|
|
if description.is_empty()
|
|
&& let Some(d) = val.get("description").and_then(Value::as_str)
|
|
{
|
|
description = d.trim().to_owned();
|
|
}
|
|
author = author.or_else(|| extract_author(&val));
|
|
if keywords.is_empty() {
|
|
keywords = extract_string_array(val.get("keywords"));
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
|
|
let source_spec = if root_dir.is_empty() {
|
|
format!("{}/{}#{git_ref}", parsed.owner, parsed.repo)
|
|
} else {
|
|
format!("{}/{}/{root_dir}#{git_ref}", parsed.owner, parsed.repo)
|
|
};
|
|
let (already_user, already_ws) = plugin_installed_anywhere(&name, None, user_home, workspace_root);
|
|
candidates.push(AgentMarketplaceCandidate {
|
|
name,
|
|
display_name,
|
|
version,
|
|
description,
|
|
author,
|
|
marketplace: None,
|
|
source_spec,
|
|
subpath: root_dir,
|
|
keywords,
|
|
already_installed_user: already_user,
|
|
already_installed_workspace: already_ws,
|
|
});
|
|
}
|
|
|
|
if candidates.is_empty() {
|
|
return Err(IdeError::not_found(format!(
|
|
"No marketplace.json or agent plugin manifests found in {}/{} ({git_ref})",
|
|
parsed.owner, parsed.repo
|
|
)));
|
|
}
|
|
|
|
Ok(AgentMarketplaceBrowseResult {
|
|
source: trimmed.to_owned(),
|
|
marketplace_name: format!("{}/{}", parsed.owner, parsed.repo),
|
|
owner: Some(parsed.owner),
|
|
repo: Some(parsed.repo),
|
|
git_ref: Some(git_ref),
|
|
tree_sha: Some(tree.sha),
|
|
candidates,
|
|
})
|
|
}
|
|
|
|
/// Previews an agent plugin from a GitHub `owner/repo[/subpath][#ref]` spec or a local folder path,
|
|
/// computing executable capabilities (`stdio_commands`, `hook_files`, `capability_hash`) and static scan warnings.
|
|
pub fn preview_plugin(
|
|
fetcher: &dyn SkillSourceFetcher,
|
|
source: &str,
|
|
subpath_override: Option<&str>,
|
|
marketplace: Option<&str>,
|
|
user_home: Option<&Path>,
|
|
workspace_root: Option<&Path>,
|
|
cancel: &CancellationToken,
|
|
) -> IdeResult<AgentPluginPreview> {
|
|
let trimmed = source.trim();
|
|
if trimmed.is_empty() {
|
|
return Err(IdeError::invalid("Provide a GitHub repository (`owner/repo`) or local plugin directory"));
|
|
}
|
|
|
|
if let Some(local_dir) = resolve_local_source(trimmed, user_home, workspace_root)
|
|
&& local_dir.exists()
|
|
{
|
|
let local_canon = dunce::canonicalize(&local_dir)?;
|
|
let target_dir = match subpath_override.filter(|s| !s.trim().is_empty()) {
|
|
Some(sub) => contained_join(&local_canon, sub)?,
|
|
None => local_canon.clone(),
|
|
};
|
|
let canon = dunce::canonicalize(&target_dir)?;
|
|
if !canon.starts_with(&local_canon) {
|
|
return Err(IdeError::invalid("Plugin subpath escapes its local root"));
|
|
}
|
|
let scanned = scan_local_subtree(&canon, MAX_PLUGIN_FILES, MAX_PLUGIN_BYTES, "plugin")?;
|
|
let inspected =
|
|
inspect_fetched_subtree(&scanned, canon.file_name().and_then(|s| s.to_str()).unwrap_or("plugin"))?;
|
|
let marketplace_source = marketplace
|
|
.and_then(|name| local_marketplace_source(&local_dir, name))
|
|
.map(|path| path.to_string_lossy().into_owned());
|
|
let targets = plugin_install_targets(
|
|
&inspected.name,
|
|
inspected.version.as_deref(),
|
|
None,
|
|
&inspected.formats,
|
|
marketplace,
|
|
marketplace_source.as_deref(),
|
|
user_home,
|
|
workspace_root,
|
|
);
|
|
return Ok(AgentPluginPreview {
|
|
source_kind: "local".into(),
|
|
owner: None,
|
|
repo: None,
|
|
git_ref: None,
|
|
tree_sha: Some(scanned.tree_sha.clone()),
|
|
commit_sha: None,
|
|
subpath: String::new(),
|
|
local_path: Some(canon.to_string_lossy().into_owned()),
|
|
marketplace: marketplace.map(str::to_owned),
|
|
marketplace_source,
|
|
name: inspected.name,
|
|
display_name: inspected.display_name,
|
|
version: inspected.version,
|
|
description: inspected.description,
|
|
formats: inspected.formats,
|
|
capabilities: inspected.capabilities,
|
|
files: scanned.files,
|
|
scan_warnings: scanned.scan_warnings,
|
|
targets,
|
|
});
|
|
}
|
|
|
|
let parsed = parse_source(trimmed)?;
|
|
let git_ref = resolve_plugin_source_ref(fetcher, &parsed, cancel)?;
|
|
let subpath =
|
|
subpath_override.filter(|s| !s.trim().is_empty()).map(str::to_owned).or(parsed.subpath).unwrap_or_default();
|
|
let commit_sha =
|
|
fetcher.git_commit_sha(RepoRef { owner: &parsed.owner, repo: &parsed.repo, git_ref: &git_ref }, cancel)?;
|
|
let target = RepoRef { owner: &parsed.owner, repo: &parsed.repo, git_ref: &commit_sha };
|
|
let scanned =
|
|
fetch_and_scan_subtree(fetcher, target, &subpath, None, MAX_PLUGIN_FILES, MAX_PLUGIN_BYTES, "plugin", cancel)?;
|
|
let fallback_name = subpath.rsplit('/').next().filter(|s| !s.is_empty()).unwrap_or(&parsed.repo);
|
|
let inspected = inspect_fetched_subtree(&scanned, fallback_name)?;
|
|
let targets = plugin_install_targets(
|
|
&inspected.name,
|
|
inspected.version.as_deref(),
|
|
Some(&scanned.tree_sha),
|
|
&inspected.formats,
|
|
marketplace,
|
|
marketplace.map(|_| trimmed),
|
|
user_home,
|
|
workspace_root,
|
|
);
|
|
|
|
Ok(AgentPluginPreview {
|
|
source_kind: "github".into(),
|
|
owner: Some(parsed.owner),
|
|
repo: Some(parsed.repo),
|
|
git_ref: Some(git_ref),
|
|
tree_sha: Some(scanned.tree_sha),
|
|
commit_sha: Some(commit_sha),
|
|
subpath: scanned.normalized_subpath,
|
|
local_path: None,
|
|
marketplace: marketplace.map(str::to_owned),
|
|
marketplace_source: marketplace.map(|_| trimmed.to_owned()),
|
|
name: inspected.name,
|
|
display_name: inspected.display_name,
|
|
version: inspected.version,
|
|
description: inspected.description,
|
|
formats: inspected.formats,
|
|
capabilities: inspected.capabilities,
|
|
files: scanned.files,
|
|
scan_warnings: scanned.scan_warnings,
|
|
targets,
|
|
})
|
|
}
|
|
|
|
/// Atomically installs a previewed agent plugin into the selected harness's native plugin directory,
|
|
/// enforcing static scan confirmation,
|
|
/// capability consent confirmation, and pinned `tree_sha` verification.
|
|
/// Returns `(installed_dir, capability_approval_key)`.
|
|
pub fn install_plugin(
|
|
fetcher: &dyn SkillSourceFetcher,
|
|
req: &InstallAgentPluginRequest,
|
|
user_home: Option<&Path>,
|
|
workspace_root: Option<&Path>,
|
|
cancel: &CancellationToken,
|
|
) -> IdeResult<(PathBuf, Option<String>)> {
|
|
let source = source_for_harness(&req.harness)?;
|
|
if matches!(source, AgentPluginSource::ClaudeUser | AgentPluginSource::CodexUser)
|
|
&& req.marketplace.as_deref().is_none_or(|marketplace| marketplace.trim().is_empty())
|
|
{
|
|
return Err(IdeError::invalid(format!(
|
|
"`{}` plugins must be installed from a named marketplace",
|
|
normalize_provider_id(&req.harness)
|
|
)));
|
|
}
|
|
if source == AgentPluginSource::CopilotUser
|
|
&& req.scope == McpScope::Workspace
|
|
&& req.marketplace.as_deref().is_none_or(|marketplace| marketplace.trim().is_empty())
|
|
{
|
|
return Err(IdeError::invalid("Copilot repository settings can only enable plugins from a marketplace"));
|
|
}
|
|
|
|
let (scanned, fallback_name, prov) = match req.source_kind.as_str() {
|
|
"local" => {
|
|
let raw_local = req
|
|
.local_path
|
|
.as_deref()
|
|
.filter(|s| !s.trim().is_empty())
|
|
.ok_or_else(|| IdeError::invalid("Missing local plugin folder path"))?;
|
|
let local = resolve_local_source(raw_local.trim(), user_home, workspace_root).ok_or_else(|| {
|
|
IdeError::invalid("Local plugin folders must be absolute, `~/…`, or `./…` relative to the project")
|
|
})?;
|
|
let canon = dunce::canonicalize(local)?;
|
|
let sub = scan_local_subtree(&canon, MAX_PLUGIN_FILES, MAX_PLUGIN_BYTES, "plugin")?;
|
|
let pinned = req
|
|
.tree_sha
|
|
.as_deref()
|
|
.filter(|s| !s.is_empty())
|
|
.ok_or_else(|| IdeError::invalid("Preview the plugin again before installing it"))?;
|
|
if pinned != sub.tree_sha {
|
|
return Err(IdeError::invalid(
|
|
"The local plugin folder changed after preview; preview the plugin again before installing it",
|
|
));
|
|
}
|
|
let hint = canon.file_name().and_then(|s| s.to_str()).unwrap_or("plugin").to_owned();
|
|
let prov = InstalledPluginProvenance {
|
|
source_kind: "local".into(),
|
|
owner: None,
|
|
repo: None,
|
|
git_ref: None,
|
|
tree_sha: None,
|
|
commit_sha: None,
|
|
subpath: String::new(),
|
|
local_path: Some(canon.to_string_lossy().into_owned()),
|
|
marketplace: req.marketplace.clone(),
|
|
marketplace_source: req.marketplace_source.clone(),
|
|
};
|
|
(sub, hint, prov)
|
|
}
|
|
"github" => {
|
|
let owner = req.owner.as_deref().ok_or_else(|| IdeError::invalid("Missing GitHub owner"))?;
|
|
let repo = req.repo.as_deref().ok_or_else(|| IdeError::invalid("Missing GitHub repository"))?;
|
|
let git_ref = req.git_ref.as_deref().ok_or_else(|| IdeError::invalid("Missing Git ref"))?;
|
|
let tree_sha = req
|
|
.tree_sha
|
|
.as_deref()
|
|
.filter(|s| !s.is_empty())
|
|
.ok_or_else(|| IdeError::invalid("Preview the plugin again before installing it"))?;
|
|
let commit_sha = req
|
|
.commit_sha
|
|
.as_deref()
|
|
.filter(|s| !s.is_empty())
|
|
.ok_or_else(|| IdeError::invalid("Preview the plugin again before installing it"))?;
|
|
// `git_ref` names the previewed branch/tag; content is pinned by commit and tree SHA,
|
|
// and the commit must actually record the pinned tree.
|
|
let commit_tree = fetcher.git_commit_tree_sha(owner, repo, commit_sha, cancel)?;
|
|
if !commit_tree.eq_ignore_ascii_case(tree_sha) {
|
|
return Err(IdeError::invalid(
|
|
"The previewed commit does not contain the pinned plugin tree; preview the plugin again",
|
|
));
|
|
}
|
|
let sub = fetch_and_scan_subtree(
|
|
fetcher,
|
|
RepoRef { owner, repo, git_ref: commit_sha },
|
|
&req.subpath,
|
|
Some(tree_sha),
|
|
MAX_PLUGIN_FILES,
|
|
MAX_PLUGIN_BYTES,
|
|
"plugin",
|
|
cancel,
|
|
)?;
|
|
let hint = sub.normalized_subpath.rsplit('/').next().filter(|s| !s.is_empty()).unwrap_or(repo).to_owned();
|
|
let prov = InstalledPluginProvenance {
|
|
source_kind: "github".into(),
|
|
owner: Some(owner.to_owned()),
|
|
repo: Some(repo.to_owned()),
|
|
git_ref: Some(git_ref.to_owned()),
|
|
tree_sha: Some(sub.tree_sha.clone()),
|
|
commit_sha: Some(commit_sha.to_owned()),
|
|
subpath: sub.normalized_subpath.clone(),
|
|
local_path: None,
|
|
marketplace: req.marketplace.clone(),
|
|
marketplace_source: req.marketplace_source.clone(),
|
|
};
|
|
(sub, hint, prov)
|
|
}
|
|
other => return Err(IdeError::invalid(format!("Unsupported plugin source kind {other:?}"))),
|
|
};
|
|
|
|
if !scanned.scan_warnings.is_empty() && !req.confirm_warnings {
|
|
return Err(IdeError::invalid(
|
|
"Review and confirm the static security scan warnings before installing this plugin",
|
|
));
|
|
}
|
|
|
|
let inspected = inspect_fetched_subtree(&scanned, &fallback_name)?;
|
|
if let Some(reason) = plugin_install_blocker(
|
|
source,
|
|
&inspected.formats,
|
|
req.marketplace.as_deref(),
|
|
req.marketplace_source.as_deref(),
|
|
user_home,
|
|
) {
|
|
return Err(IdeError::invalid(reason));
|
|
}
|
|
let codex_marketplace_root = match (source, req.marketplace.as_deref()) {
|
|
(AgentPluginSource::CodexUser, Some(marketplace)) => {
|
|
codex_marketplace_registration(user_home, marketplace.trim(), req.marketplace_source.as_deref())
|
|
.map_err(IdeError::invalid)?
|
|
}
|
|
_ => None,
|
|
};
|
|
if inspected.capabilities.requires_consent
|
|
&& (!req.approve_capabilities
|
|
|| req.approved_capability_hash.as_deref() != inspected.capabilities.capability_hash.as_deref())
|
|
{
|
|
return Err(IdeError::invalid(
|
|
"Approve the plugin's MCP server / lifecycle hook execution capabilities before installing",
|
|
));
|
|
}
|
|
|
|
let copilot_live =
|
|
copilot_installs_live(source, &req.source_kind, req.marketplace.as_deref(), req.marketplace_source.as_deref());
|
|
let home = user_home.ok_or_else(|| IdeError::unavailable("Cannot locate user home directory"))?;
|
|
let target_container = native_plugin_dir(source, user_home, req.marketplace.as_deref())?;
|
|
let (target_parent, folder_name) = match source {
|
|
AgentPluginSource::ClaudeUser | AgentPluginSource::CodexUser => {
|
|
let version = native_plugin_install_version(source, inspected.version.as_deref(), prov.tree_sha.as_deref());
|
|
(target_container.join(store_segment(&inspected.name, "plugin")?), version)
|
|
}
|
|
AgentPluginSource::CopilotUser | AgentPluginSource::GeminiUser => {
|
|
(target_container, store_segment(&inspected.name, "plugin")?)
|
|
}
|
|
};
|
|
let final_dir = if copilot_live {
|
|
PathBuf::from(prov.local_path.as_deref().unwrap_or_default())
|
|
} else {
|
|
// Anchored at home, so a symlinked store root (e.g. `~/.claude/plugins`) is refused too.
|
|
write_staged_subtree(
|
|
home,
|
|
&target_parent,
|
|
&folder_name,
|
|
req.overwrite,
|
|
"Plugin",
|
|
&scanned.regular_files,
|
|
&scanned.in_root_symlinks,
|
|
&[],
|
|
)?
|
|
};
|
|
|
|
// Re-inspect the installed directory on disk so `${PLUGIN_ROOT}` inside `stdio_commands`
|
|
// produces the exact on-disk `capability_hash` that `resolve_plugins` checks!
|
|
let installed =
|
|
inspect_plugin_dir(&final_dir, source_for_harness(&req.harness)?, req.scope, req.marketplace.as_deref(), true);
|
|
let Some(mut plugin) = installed else {
|
|
if !copilot_live {
|
|
let _ = std::fs::remove_dir_all(&final_dir);
|
|
}
|
|
return Err(IdeError::invalid(format!(
|
|
"`{}` does not read the installed files as a plugin; nothing was registered",
|
|
normalize_provider_id(&req.harness)
|
|
)));
|
|
};
|
|
// The installed folder must run exactly what the preview showed and the user approved.
|
|
if plugin.capabilities.capability_hash != inspected.capabilities.capability_hash {
|
|
if !copilot_live {
|
|
let _ = std::fs::remove_dir_all(&final_dir);
|
|
}
|
|
return Err(IdeError::invalid(
|
|
"The installed plugin's executable capabilities differ from the preview; nothing was registered",
|
|
));
|
|
}
|
|
let approval_key = capability_approval_key(&plugin);
|
|
if matches!(source, AgentPluginSource::ClaudeUser | AgentPluginSource::CodexUser) {
|
|
plugin.version = Some(folder_name.clone());
|
|
}
|
|
if let (Some(root), Some(home), Some(marketplace)) =
|
|
(&codex_marketplace_root, user_home, req.marketplace.as_deref())
|
|
{
|
|
register_codex_local_marketplace(home, marketplace.trim(), root)?;
|
|
}
|
|
register_native_plugin(&plugin, user_home, workspace_root, &prov, true)?;
|
|
|
|
Ok((final_dir, approval_key))
|
|
}
|
|
|
|
/// Resolves a plugin source's Git ref. Explicit refs (`#ref`, `/tree/<ref>`) must exist; only the
|
|
/// ambiguous `@suffix` form falls back to the default branch, matching the skill installer.
|
|
fn resolve_plugin_source_ref(
|
|
fetcher: &dyn SkillSourceFetcher,
|
|
parsed: &ParsedSource,
|
|
cancel: &CancellationToken,
|
|
) -> IdeResult<String> {
|
|
if let Some(explicit) = parsed.explicit_ref.as_deref() {
|
|
return Ok(explicit.to_owned());
|
|
}
|
|
if let Some(candidate) = parsed.ref_or_skill.as_deref()
|
|
&& fetcher.git_tree(RepoRef { owner: &parsed.owner, repo: &parsed.repo, git_ref: candidate }, cancel).is_ok()
|
|
{
|
|
return Ok(candidate.to_owned());
|
|
}
|
|
fetcher.default_branch(&parsed.owner, &parsed.repo, cancel)
|
|
}
|
|
|
|
fn native_plugin_install_version(source: AgentPluginSource, version: Option<&str>, tree_sha: Option<&str>) -> String {
|
|
if let Some(version) = version.map(str::trim).filter(|version| valid_plugin_version_segment(version)) {
|
|
return version.to_owned();
|
|
}
|
|
match source {
|
|
AgentPluginSource::CodexUser => "local".to_owned(),
|
|
AgentPluginSource::ClaudeUser => tree_sha
|
|
.filter(|sha| sha.len() >= 12)
|
|
.map(|sha| sha[..12].to_owned())
|
|
.unwrap_or_else(|| "unknown".to_owned()),
|
|
_ => unreachable!("only versioned plugin stores need a version"),
|
|
}
|
|
}
|
|
|
|
fn valid_plugin_version_segment(version: &str) -> bool {
|
|
!version.is_empty()
|
|
&& !matches!(version, "." | "..")
|
|
&& version.chars().all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | '.' | '+'))
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Internal inspection & helper functions
|
|
// ---------------------------------------------------------------------------
|
|
|
|
struct InspectedSubtreeMeta {
|
|
name: String,
|
|
display_name: String,
|
|
version: Option<String>,
|
|
description: String,
|
|
formats: Vec<AgentPluginFormat>,
|
|
capabilities: AgentPluginCapabilities,
|
|
}
|
|
|
|
fn inspect_fetched_subtree(scanned: &FetchedSubtree, fallback_name: &str) -> IdeResult<InspectedSubtreeMeta> {
|
|
let mut formats = Vec::new();
|
|
let mut name: Option<String> = None;
|
|
let mut display_name: Option<String> = None;
|
|
let mut version: Option<String> = None;
|
|
let mut description = String::new();
|
|
let mut native_harnesses = BTreeSet::new();
|
|
|
|
let file_map: BTreeMap<String, &[u8]> =
|
|
scanned.regular_files.iter().map(|(p, b, _)| (p.to_string_lossy().replace('\\', "/"), b.as_slice())).collect();
|
|
let executable = resolve_executable_capabilities(&ScannedPluginFiles(&file_map));
|
|
native_harnesses.extend(executable.hook_harnesses.iter().cloned());
|
|
|
|
for (rel, fmt) in MANIFEST_CANDIDATES {
|
|
let Some(bytes) = file_map.get(*rel) else { continue };
|
|
let Ok(val) = parse_jsonc(&String::from_utf8_lossy(bytes)) else { continue };
|
|
let actual_fmt = classify_manifest_format(rel, *fmt, &val);
|
|
if !formats.contains(&actual_fmt) {
|
|
formats.push(actual_fmt);
|
|
}
|
|
record_format_harness(actual_fmt, &val, &mut native_harnesses);
|
|
if name.is_none() {
|
|
name = val
|
|
.get("name")
|
|
.and_then(Value::as_str)
|
|
.map(str::trim)
|
|
.filter(|s| !s.is_empty())
|
|
.map(sanitize_plugin_slug);
|
|
}
|
|
if display_name.is_none() {
|
|
display_name = val
|
|
.get("displayName")
|
|
.or_else(|| val.pointer("/interface/displayName"))
|
|
.or_else(|| val.get("name"))
|
|
.and_then(Value::as_str)
|
|
.map(str::trim)
|
|
.filter(|s| !s.is_empty())
|
|
.map(str::to_owned);
|
|
}
|
|
if version.is_none() {
|
|
version = val.get("version").and_then(Value::as_str).map(str::to_owned);
|
|
}
|
|
if description.is_empty()
|
|
&& let Some(d) = val.get("description").and_then(Value::as_str)
|
|
{
|
|
description = d.trim().to_owned();
|
|
}
|
|
}
|
|
|
|
let mut skill_names = Vec::new();
|
|
let mut rule_count = 0u32;
|
|
let mut subagent_count = 0u32;
|
|
let mut command_count = 0u32;
|
|
let mut has_lsp = false;
|
|
let mut has_canvas_or_app = false;
|
|
|
|
for rel in file_map.keys() {
|
|
if rel == "SKILL.md" {
|
|
skill_names.push(sanitize_plugin_slug(name.as_deref().unwrap_or(fallback_name)));
|
|
} else if let Some(dir) = rel.strip_suffix("/SKILL.md")
|
|
&& let Some(folder) = dir.rsplit('/').next()
|
|
{
|
|
skill_names.push(folder.to_owned());
|
|
} else if is_rule_rel_path(rel) {
|
|
rule_count = rule_count.saturating_add(1);
|
|
} else if is_subagent_rel_path(rel) {
|
|
subagent_count = subagent_count.saturating_add(1);
|
|
native_harnesses.insert(if rel.starts_with("com.github.copilot/") { "copilot" } else { "claude" }.into());
|
|
} else if is_command_rel_path(rel) {
|
|
command_count = command_count.saturating_add(1);
|
|
} else if rel == ".lsp.json" || rel == "lsp.json" {
|
|
has_lsp = true;
|
|
native_harnesses.insert("claude".into());
|
|
} else if rel == ".app.json" || rel.starts_with("extensions/") {
|
|
has_canvas_or_app = true;
|
|
}
|
|
}
|
|
skill_names.sort();
|
|
skill_names.dedup();
|
|
let ExecutableCapabilities { mcp_names, stdio_commands, hook_files, capability_hash, .. } = executable;
|
|
|
|
if formats.is_empty()
|
|
&& skill_names.is_empty()
|
|
&& mcp_names.is_empty()
|
|
&& rule_count == 0
|
|
&& hook_files.is_empty()
|
|
&& subagent_count == 0
|
|
&& command_count == 0
|
|
{
|
|
return Err(IdeError::invalid(
|
|
"Selected directory does not contain an agent plugin manifest (`plugin.json`, `.claude-plugin/plugin.json`, etc.), skills, MCP configuration, hooks, subagents, or commands",
|
|
));
|
|
}
|
|
let requires_consent = capability_hash.is_some();
|
|
|
|
let final_name = name.unwrap_or_else(|| sanitize_plugin_slug(fallback_name));
|
|
let final_display = display_name.unwrap_or_else(|| final_name.clone());
|
|
|
|
Ok(InspectedSubtreeMeta {
|
|
name: final_name,
|
|
display_name: final_display,
|
|
version,
|
|
description,
|
|
formats,
|
|
capabilities: AgentPluginCapabilities {
|
|
skill_count: skill_names.len() as u32,
|
|
skill_names,
|
|
mcp_count: mcp_names.len() as u32,
|
|
mcp_names: mcp_names.into_iter().collect(),
|
|
rule_count,
|
|
subagent_count,
|
|
command_count,
|
|
hook_files,
|
|
stdio_commands,
|
|
has_lsp,
|
|
has_canvas_or_app,
|
|
native_harnesses: native_harnesses.into_iter().collect(),
|
|
capability_hash,
|
|
requires_consent,
|
|
},
|
|
})
|
|
}
|
|
|
|
/// A plugin's files as capability resolution reads them: the scanned preview, or the installed
|
|
/// folder. Both expose regular files only, so preview and install resolve the same capabilities.
|
|
trait PluginFiles {
|
|
fn read(&self, rel: &str) -> Option<Vec<u8>>;
|
|
/// Regular files below `dir` (plugin-relative, `/`-separated), sorted.
|
|
fn files_under(&self, dir: &str) -> Vec<String>;
|
|
}
|
|
|
|
struct ScannedPluginFiles<'a>(&'a BTreeMap<String, &'a [u8]>);
|
|
|
|
impl PluginFiles for ScannedPluginFiles<'_> {
|
|
fn read(&self, rel: &str) -> Option<Vec<u8>> {
|
|
self.0.get(rel).map(|bytes| bytes.to_vec())
|
|
}
|
|
|
|
fn files_under(&self, dir: &str) -> Vec<String> {
|
|
let prefix = format!("{dir}/");
|
|
self.0.keys().filter(|rel| rel.starts_with(&prefix)).cloned().collect()
|
|
}
|
|
}
|
|
|
|
struct DiskPluginFiles<'a>(&'a Path);
|
|
|
|
const MAX_CAPABILITY_FILE_BYTES: u64 = 1 << 20;
|
|
const MAX_CAPABILITY_WALK_FILES: usize = 2_000;
|
|
|
|
impl DiskPluginFiles<'_> {
|
|
/// `rel` as a regular file inside the plugin, reached without following any symlink.
|
|
fn regular_file(&self, rel: &str) -> Option<PathBuf> {
|
|
let rel = Path::new(rel);
|
|
if rel.as_os_str().is_empty() || !rel.components().all(|c| matches!(c, Component::Normal(_))) {
|
|
return None;
|
|
}
|
|
let mut path = self.0.to_path_buf();
|
|
let count = rel.components().count();
|
|
for (index, component) in rel.components().enumerate() {
|
|
path.push(component);
|
|
let meta = std::fs::symlink_metadata(&path).ok()?;
|
|
let last = index + 1 == count;
|
|
if meta.file_type().is_symlink() || (last && !meta.is_file()) || (!last && !meta.is_dir()) {
|
|
return None;
|
|
}
|
|
}
|
|
Some(path)
|
|
}
|
|
}
|
|
|
|
impl PluginFiles for DiskPluginFiles<'_> {
|
|
fn read(&self, rel: &str) -> Option<Vec<u8>> {
|
|
let path = self.regular_file(rel)?;
|
|
let meta = std::fs::metadata(&path).ok()?;
|
|
(meta.len() <= MAX_CAPABILITY_FILE_BYTES).then(|| std::fs::read(path).ok()).flatten()
|
|
}
|
|
|
|
fn files_under(&self, dir: &str) -> Vec<String> {
|
|
let mut out = Vec::new();
|
|
let mut stack = vec![dir.to_owned()];
|
|
while let Some(rel_dir) = stack.pop() {
|
|
let path = self.0.join(&rel_dir);
|
|
let Ok(meta) = std::fs::symlink_metadata(&path) else { continue };
|
|
if !meta.is_dir() {
|
|
continue;
|
|
}
|
|
let Ok(entries) = std::fs::read_dir(&path) else { continue };
|
|
for entry in entries.filter_map(Result::ok) {
|
|
let Some(name) = entry.file_name().to_str().map(str::to_owned) else { continue };
|
|
let Ok(file_type) = entry.file_type() else { continue };
|
|
let rel = format!("{rel_dir}/{name}");
|
|
if file_type.is_dir() {
|
|
stack.push(rel);
|
|
} else if file_type.is_file() {
|
|
out.push(rel);
|
|
}
|
|
if out.len() >= MAX_CAPABILITY_WALK_FILES {
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
out.sort();
|
|
out
|
|
}
|
|
}
|
|
|
|
/// What a plugin can execute, resolved identically for previews and installed folders.
|
|
struct ExecutableCapabilities {
|
|
mcp_names: BTreeSet<String>,
|
|
stdio_commands: Vec<String>,
|
|
hook_files: Vec<String>,
|
|
hook_harnesses: BTreeSet<String>,
|
|
capability_hash: Option<String>,
|
|
}
|
|
|
|
fn resolve_executable_capabilities(files: &dyn PluginFiles) -> ExecutableCapabilities {
|
|
let mut mcp_names = BTreeSet::new();
|
|
let mut stdio_commands = BTreeSet::new();
|
|
let mut hook_files = BTreeSet::new();
|
|
let mut hook_harnesses = BTreeSet::new();
|
|
let mut hook_contents: BTreeMap<String, Vec<u8>> = BTreeMap::new();
|
|
|
|
let mut add_hook_file = |rel: String, hook_contents: &mut BTreeMap<String, Vec<u8>>| {
|
|
if let Some(bytes) = files.read(&rel) {
|
|
classify_hook_harness(&rel, &mut hook_harnesses);
|
|
hook_files.insert(rel.clone());
|
|
hook_contents.insert(rel, bytes);
|
|
}
|
|
};
|
|
for rel in ["hooks.json", "com.github.copilot/hooks/hooks.json"] {
|
|
add_hook_file(rel.to_owned(), &mut hook_contents);
|
|
}
|
|
for rel in files.files_under("hooks").into_iter().filter(|rel| rel.ends_with(".json")) {
|
|
add_hook_file(rel, &mut hook_contents);
|
|
}
|
|
let mut inline_hooks = Vec::new();
|
|
for (rel, _) in MANIFEST_CANDIDATES {
|
|
let Some(bytes) = files.read(rel) else { continue };
|
|
let Ok(manifest) = parse_jsonc(&String::from_utf8_lossy(&bytes)) else { continue };
|
|
if let Some(mcp) = manifest.get("mcpServers") {
|
|
collect_in_memory_mcp_summary(mcp, files, &mut mcp_names, &mut stdio_commands);
|
|
}
|
|
let (paths, objects) = manifest_hook_declarations(rel, &manifest);
|
|
for path in paths {
|
|
add_hook_file(path, &mut hook_contents);
|
|
}
|
|
inline_hooks.extend(objects);
|
|
}
|
|
for rel in [".mcp.json", "mcp.json", ".github/mcp.json"] {
|
|
if let Some(bytes) = files.read(rel)
|
|
&& let Ok(value) = parse_jsonc(&String::from_utf8_lossy(&bytes))
|
|
{
|
|
collect_in_memory_mcp_summary(&value, files, &mut mcp_names, &mut stdio_commands);
|
|
}
|
|
}
|
|
for (label, bytes) in inline_hooks {
|
|
hook_files.insert(label.clone());
|
|
hook_contents.insert(label, bytes);
|
|
}
|
|
let mut referenced = BTreeSet::new();
|
|
for bytes in hook_contents.values() {
|
|
if let Ok(value) = parse_jsonc(&String::from_utf8_lossy(bytes)) {
|
|
collect_hook_reference_paths(&value, &mut referenced);
|
|
}
|
|
}
|
|
for rel in referenced {
|
|
if !hook_contents.contains_key(&rel)
|
|
&& let Some(bytes) = files.read(&rel)
|
|
{
|
|
hook_contents.insert(rel, bytes);
|
|
}
|
|
}
|
|
let stdio_commands: Vec<String> = stdio_commands.into_iter().collect();
|
|
let digests: Vec<(&str, &[u8])> =
|
|
hook_contents.iter().map(|(rel, bytes)| (rel.as_str(), bytes.as_slice())).collect();
|
|
let capability_hash = compute_capability_hash(&stdio_commands, &digests);
|
|
ExecutableCapabilities {
|
|
mcp_names,
|
|
stdio_commands,
|
|
hook_files: hook_files.into_iter().collect(),
|
|
hook_harnesses,
|
|
capability_hash,
|
|
}
|
|
}
|
|
|
|
fn collect_in_memory_mcp_summary(
|
|
val: &Value,
|
|
files: &dyn PluginFiles,
|
|
mcp_names: &mut BTreeSet<String>,
|
|
stdio_commands: &mut BTreeSet<String>,
|
|
) {
|
|
collect_in_memory_mcp_summary_inner(val, files, mcp_names, stdio_commands, &mut HashSet::new());
|
|
}
|
|
|
|
fn collect_in_memory_mcp_summary_inner(
|
|
val: &Value,
|
|
files: &dyn PluginFiles,
|
|
mcp_names: &mut BTreeSet<String>,
|
|
stdio_commands: &mut BTreeSet<String>,
|
|
visited_files: &mut HashSet<String>,
|
|
) {
|
|
match val {
|
|
Value::String(rel) => {
|
|
let clean = rel.trim().trim_start_matches("./").trim_start_matches('/');
|
|
if visited_files.insert(clean.to_owned())
|
|
&& let Some(bytes) = files.read(clean)
|
|
&& let Ok(parsed) = parse_jsonc(&String::from_utf8_lossy(&bytes))
|
|
{
|
|
collect_in_memory_mcp_summary_inner(&parsed, files, mcp_names, stdio_commands, visited_files);
|
|
}
|
|
}
|
|
Value::Array(items) => {
|
|
for item in items {
|
|
collect_in_memory_mcp_summary_inner(item, files, mcp_names, stdio_commands, visited_files);
|
|
}
|
|
}
|
|
Value::Object(obj) => {
|
|
let map = obj.get("mcpServers").or_else(|| obj.get("servers")).and_then(Value::as_object).unwrap_or(obj);
|
|
for (name, entry) in map {
|
|
let Some(srv_obj) = entry.as_object() else { continue };
|
|
if srv_obj.get("command").is_none() && srv_obj.get("url").is_none() && srv_obj.get("httpUrl").is_none()
|
|
{
|
|
continue;
|
|
}
|
|
mcp_names.insert(name.clone());
|
|
if let Some(cmd) =
|
|
srv_obj.get("command").and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty())
|
|
{
|
|
let args = extract_string_array(srv_obj.get("args"));
|
|
let env = srv_obj
|
|
.get("env")
|
|
.and_then(Value::as_object)
|
|
.into_iter()
|
|
.flatten()
|
|
.map(|(key, value)| format!("{}={}", key, scalar_capability_value(value)))
|
|
.collect::<Vec<_>>()
|
|
.join(" ");
|
|
let mut parts = vec![cmd.to_owned()];
|
|
parts.extend(args);
|
|
if !env.is_empty() {
|
|
parts.push(format!("env:{env}"));
|
|
}
|
|
let line = format!("{name}: {}", parts.join(" "));
|
|
stdio_commands.insert(line);
|
|
}
|
|
}
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
|
|
fn scalar_capability_value(value: &Value) -> String {
|
|
match value {
|
|
Value::String(value) => value.clone(),
|
|
Value::Null => "null".into(),
|
|
Value::Bool(value) => value.to_string(),
|
|
Value::Number(value) => value.to_string(),
|
|
_ => value.to_string(),
|
|
}
|
|
}
|
|
|
|
const PLUGIN_ROOT_PLACEHOLDERS: [&str; 10] = [
|
|
"${CLAUDE_PLUGIN_ROOT}",
|
|
"${PLUGIN_ROOT}",
|
|
"${COPILOT_PLUGIN_ROOT}",
|
|
"${CURSOR_PLUGIN_ROOT}",
|
|
"${extensionPath}",
|
|
"$CLAUDE_PLUGIN_ROOT",
|
|
"$PLUGIN_ROOT",
|
|
"$COPILOT_PLUGIN_ROOT",
|
|
"$CURSOR_PLUGIN_ROOT",
|
|
"%CLAUDE_PLUGIN_ROOT%",
|
|
];
|
|
|
|
/// Maps a hook command token to a plugin-relative path, expanding plugin-root placeholders.
|
|
fn hook_token_relative_path(token: &str) -> Option<String> {
|
|
let mut clean: String = token.chars().filter(|c| !matches!(c, '\'' | '"' | '`' | ';' | ',' | '(' | ')')).collect();
|
|
clean = clean.replace("${/}", "/").replace('\\', "/");
|
|
for placeholder in PLUGIN_ROOT_PLACEHOLDERS {
|
|
if let Some(rest) = clean.strip_prefix(placeholder) {
|
|
clean = rest.trim_start_matches('/').to_owned();
|
|
break;
|
|
}
|
|
}
|
|
let rel = clean.trim_start_matches("./");
|
|
(!rel.is_empty()
|
|
&& !rel.contains("://")
|
|
&& !rel.contains('$')
|
|
&& Path::new(rel).components().all(|c| matches!(c, Component::Normal(_))))
|
|
.then(|| rel.to_owned())
|
|
}
|
|
|
|
fn collect_hook_reference_paths(value: &Value, out: &mut BTreeSet<String>) {
|
|
match value {
|
|
Value::String(raw) => {
|
|
for token in raw.split(|c: char| c.is_ascii_whitespace() || c == '=') {
|
|
if let Some(rel) = hook_token_relative_path(token) {
|
|
out.insert(rel);
|
|
}
|
|
}
|
|
}
|
|
Value::Array(items) => {
|
|
for item in items {
|
|
collect_hook_reference_paths(item, out);
|
|
}
|
|
}
|
|
Value::Object(map) => {
|
|
for value in map.values() {
|
|
collect_hook_reference_paths(value, out);
|
|
}
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
|
|
/// Inspects a plugin directory on disk and builds an [`AgentPlugin`] when valid.
|
|
pub fn inspect_plugin_dir(
|
|
dir: &Path,
|
|
source: AgentPluginSource,
|
|
scope: McpScope,
|
|
marketplace_hint: Option<&str>,
|
|
allow_manifestless: bool,
|
|
) -> Option<AgentPlugin> {
|
|
if !dir.is_dir() {
|
|
return None;
|
|
}
|
|
let folder_name = dir.file_name()?.to_str()?;
|
|
if folder_name.starts_with('.') {
|
|
return None;
|
|
}
|
|
|
|
let mut formats = Vec::new();
|
|
let mut primary_manifest: Option<PathBuf> = None;
|
|
let mut name: Option<String> = None;
|
|
let mut display_name: Option<String> = None;
|
|
let mut version: Option<String> = None;
|
|
let mut description = String::new();
|
|
let mut author: Option<String> = None;
|
|
let mut homepage: Option<String> = None;
|
|
let mut repository: Option<String> = None;
|
|
let mut license: Option<String> = None;
|
|
let mut default_enabled = true;
|
|
let mut warnings = Vec::new();
|
|
let mut config_fields: Vec<AgentPluginConfigField> = Vec::new();
|
|
let mut seen_cfg_keys: HashSet<String> = HashSet::new();
|
|
let mut native_harnesses: BTreeSet<String> = BTreeSet::new();
|
|
let mut has_lsp = false;
|
|
let mut has_canvas_or_app = false;
|
|
|
|
for (rel, candidate_fmt) in MANIFEST_CANDIDATES {
|
|
let candidate_path = dir.join(rel);
|
|
if !candidate_path.is_file() {
|
|
continue;
|
|
}
|
|
let Ok(raw) = std::fs::read_to_string(&candidate_path) else {
|
|
warnings.push(format!("Could not read `{rel}`"));
|
|
continue;
|
|
};
|
|
let Ok(val) = parse_jsonc(&raw) else {
|
|
warnings.push(format!("Invalid JSON in `{rel}`"));
|
|
continue;
|
|
};
|
|
let actual_fmt = classify_manifest_format(rel, *candidate_fmt, &val);
|
|
if primary_manifest.is_none() {
|
|
primary_manifest = Some(candidate_path);
|
|
}
|
|
if !formats.contains(&actual_fmt) {
|
|
formats.push(actual_fmt);
|
|
}
|
|
record_format_harness(actual_fmt, &val, &mut native_harnesses);
|
|
|
|
if name.is_none() {
|
|
name = val.get("name").and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned);
|
|
}
|
|
if display_name.is_none() {
|
|
display_name = val
|
|
.get("displayName")
|
|
.or_else(|| val.pointer("/interface/displayName"))
|
|
.and_then(Value::as_str)
|
|
.map(str::trim)
|
|
.filter(|s| !s.is_empty())
|
|
.map(str::to_owned);
|
|
}
|
|
if version.is_none() {
|
|
version =
|
|
val.get("version").and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned);
|
|
}
|
|
if description.is_empty()
|
|
&& let Some(d) = val.get("description").and_then(Value::as_str)
|
|
{
|
|
description = d.trim().to_owned();
|
|
}
|
|
if author.is_none() {
|
|
author = extract_author(&val);
|
|
}
|
|
if homepage.is_none() {
|
|
homepage =
|
|
val.get("homepage").and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned);
|
|
}
|
|
if repository.is_none() {
|
|
repository = extract_repo_url(&val);
|
|
}
|
|
if license.is_none() {
|
|
license =
|
|
val.get("license").and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned);
|
|
}
|
|
if let Some(de) = val.get("defaultEnabled").and_then(Value::as_bool) {
|
|
default_enabled = de;
|
|
}
|
|
if val.get("lspServers").is_some() {
|
|
has_lsp = true;
|
|
native_harnesses.insert("claude".into());
|
|
}
|
|
if val.get("extensions").is_some_and(Value::is_string) || val.pointer("/extensions/com.openai/apps").is_some() {
|
|
has_canvas_or_app = true;
|
|
if val.get("extensions").is_some_and(Value::is_string) {
|
|
native_harnesses.insert("copilot".into());
|
|
}
|
|
if val.pointer("/extensions/com.openai/apps").is_some() {
|
|
native_harnesses.insert("codex".into());
|
|
}
|
|
}
|
|
extract_manifest_config_fields(&val, &mut config_fields, &mut seen_cfg_keys);
|
|
}
|
|
|
|
let marketplace = marketplace_hint.filter(|m| !m.is_empty() && *m != "_direct").map(str::to_owned);
|
|
|
|
// Discover bundled skills + approximate token budget:
|
|
let mut skill_names = Vec::new();
|
|
let mut approx_tokens = 0u32;
|
|
for skill_root in collect_plugin_skill_dirs(dir) {
|
|
if skill_root == dir && dir.join("SKILL.md").is_file() {
|
|
if let Ok(text) = std::fs::read_to_string(dir.join("SKILL.md")) {
|
|
let s_name = name.clone().unwrap_or_else(|| sanitize_plugin_slug(folder_name));
|
|
approx_tokens = approx_tokens.saturating_add(estimate_skill_header_tokens(&text));
|
|
skill_names.push(s_name);
|
|
}
|
|
} else {
|
|
for sub in sorted_dirs(&skill_root) {
|
|
let md = sub.join("SKILL.md");
|
|
if md.is_file() {
|
|
if let Some(sn) = sub.file_name().and_then(|n| n.to_str()) {
|
|
skill_names.push(sn.to_owned());
|
|
}
|
|
if let Ok(text) = std::fs::read_to_string(&md) {
|
|
approx_tokens = approx_tokens.saturating_add(estimate_skill_header_tokens(&text));
|
|
}
|
|
} else {
|
|
// Category subfolder (`<category>/<name>/SKILL.md`)
|
|
for cat_sub in sorted_dirs(&sub) {
|
|
let cat_md = cat_sub.join("SKILL.md");
|
|
if cat_md.is_file() {
|
|
if let Some(sn) = cat_sub.file_name().and_then(|n| n.to_str()) {
|
|
skill_names.push(sn.to_owned());
|
|
}
|
|
if let Ok(text) = std::fs::read_to_string(&cat_md) {
|
|
approx_tokens = approx_tokens.saturating_add(estimate_skill_header_tokens(&text));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
skill_names.sort();
|
|
skill_names.dedup();
|
|
|
|
// Discover bundled MCP servers (with default config values for token & stdio command summary):
|
|
let raw_mcp = read_plugin_mcp_servers(dir, folder_name, None, None, &config_fields, &BTreeMap::new());
|
|
let mut mcp_names = Vec::new();
|
|
for srv_name in raw_mcp.keys() {
|
|
mcp_names.push(srv_name.clone());
|
|
approx_tokens = approx_tokens.saturating_add(180);
|
|
}
|
|
// Executable capabilities come from the same resolution a preview uses, so an approval given
|
|
// at install time matches what the installed folder runs.
|
|
let executable = resolve_executable_capabilities(&DiskPluginFiles(dir));
|
|
native_harnesses.extend(executable.hook_harnesses.iter().cloned());
|
|
|
|
// Rules, subagents, commands, hooks, LSP, apps:
|
|
let rule_files = collect_plugin_rule_files(dir);
|
|
for rf in &rule_files {
|
|
if let Ok(t) = std::fs::read_to_string(rf) {
|
|
approx_tokens = approx_tokens.saturating_add(((t.chars().count() as u32).saturating_add(3)) / 4);
|
|
}
|
|
}
|
|
let claude_subagents = count_files_with_exts(&dir.join("agents"), &["md"]);
|
|
let copilot_subagents = count_files_with_exts(&dir.join("com.github.copilot/agents"), &["md"]);
|
|
let subagent_count = claude_subagents + copilot_subagents;
|
|
if claude_subagents > 0 {
|
|
native_harnesses.insert("claude".into());
|
|
}
|
|
if copilot_subagents > 0 {
|
|
native_harnesses.insert("copilot".into());
|
|
}
|
|
let command_count = count_files_with_exts(&dir.join("commands"), &["md", "toml", "txt"])
|
|
+ count_files_with_exts(&dir.join("com.github.copilot/commands"), &["md"]);
|
|
|
|
let hook_rel_names = executable.hook_files.clone();
|
|
|
|
if dir.join(".lsp.json").is_file() || dir.join("lsp.json").is_file() {
|
|
has_lsp = true;
|
|
native_harnesses.insert("claude".into());
|
|
}
|
|
if dir.join(".app.json").is_file() {
|
|
has_canvas_or_app = true;
|
|
native_harnesses.insert("codex".into());
|
|
}
|
|
if dir.join("extensions").is_dir() {
|
|
has_canvas_or_app = true;
|
|
native_harnesses.insert("copilot".into());
|
|
}
|
|
|
|
if formats.is_empty() {
|
|
if !allow_manifestless
|
|
|| (skill_names.is_empty()
|
|
&& mcp_names.is_empty()
|
|
&& rule_files.is_empty()
|
|
&& hook_rel_names.is_empty()
|
|
&& subagent_count == 0
|
|
&& command_count == 0)
|
|
{
|
|
return None;
|
|
}
|
|
formats.push(AgentPluginFormat::Copilot);
|
|
}
|
|
|
|
let capability_hash = executable.capability_hash.clone();
|
|
let requires_consent = capability_hash.is_some();
|
|
|
|
let resolved_name = name.unwrap_or_else(|| sanitize_plugin_slug(folder_name));
|
|
let resolved_display = display_name.unwrap_or_else(|| resolved_name.clone());
|
|
let readme_path: Option<ide_core::IpcPath> =
|
|
["README.md", "readme.md", "Readme.md"].into_iter().map(|f| dir.join(f)).find(|p| p.is_file()).map(Into::into);
|
|
|
|
let id = plugin_base_id(&resolved_name, marketplace.as_deref());
|
|
|
|
if description.is_empty()
|
|
&& let Some(rp) = readme_path.as_ref()
|
|
&& let Ok(rt) = std::fs::read_to_string(&rp.0)
|
|
{
|
|
description = first_body_summary(&rt).unwrap_or_default();
|
|
}
|
|
|
|
let valid = warnings.is_empty();
|
|
Some(AgentPlugin {
|
|
id,
|
|
name: resolved_name,
|
|
display_name: resolved_display,
|
|
version,
|
|
description,
|
|
author,
|
|
homepage,
|
|
repository,
|
|
license,
|
|
marketplace,
|
|
source,
|
|
scope,
|
|
workspace_root: None,
|
|
also_in: Vec::new(),
|
|
formats,
|
|
root_path: dir.to_path_buf().into(),
|
|
manifest_path: primary_manifest.map(Into::into),
|
|
readme_path,
|
|
default_enabled,
|
|
approx_tokens,
|
|
capabilities: AgentPluginCapabilities {
|
|
skill_count: skill_names.len() as u32,
|
|
skill_names,
|
|
mcp_count: mcp_names.len() as u32,
|
|
mcp_names,
|
|
rule_count: rule_files.len() as u32,
|
|
subagent_count,
|
|
command_count,
|
|
hook_files: hook_rel_names,
|
|
stdio_commands: executable.stdio_commands,
|
|
has_lsp,
|
|
has_canvas_or_app,
|
|
native_harnesses: native_harnesses.into_iter().collect(),
|
|
capability_hash,
|
|
requires_consent,
|
|
},
|
|
config_fields,
|
|
valid,
|
|
warnings,
|
|
})
|
|
}
|
|
|
|
fn compute_capability_hash(stdio_commands: &[String], hooks: &[(&str, &[u8])]) -> Option<String> {
|
|
if stdio_commands.is_empty() && hooks.is_empty() {
|
|
return None;
|
|
}
|
|
let mut hasher = blake3::Hasher::new();
|
|
hasher.update(b"openidea-agent-plugin-caps-v1\0");
|
|
let mut sorted_cmds = stdio_commands.to_vec();
|
|
sorted_cmds.sort();
|
|
for cmd in sorted_cmds {
|
|
hasher.update(b"mcp:");
|
|
hasher.update(cmd.as_bytes());
|
|
hasher.update(b"\0");
|
|
}
|
|
for (rel, bytes) in hooks {
|
|
hasher.update(b"hook:");
|
|
hasher.update(rel.as_bytes());
|
|
hasher.update(b":");
|
|
hasher.update(bytes);
|
|
hasher.update(b"\0");
|
|
}
|
|
Some(hasher.finalize().to_hex().to_string())
|
|
}
|
|
|
|
fn classify_manifest_format(rel: &str, candidate: AgentPluginFormat, val: &Value) -> AgentPluginFormat {
|
|
if rel == "plugin.json" {
|
|
let is_v1 = val
|
|
.get("$schema")
|
|
.and_then(Value::as_str)
|
|
.is_some_and(|s| s.contains("agent-plugins") || s.contains("agentplugins"));
|
|
if is_v1 { AgentPluginFormat::AgentPluginsV1 } else { AgentPluginFormat::Copilot }
|
|
} else {
|
|
candidate
|
|
}
|
|
}
|
|
|
|
fn record_format_harness(fmt: AgentPluginFormat, val: &Value, harnesses: &mut BTreeSet<String>) {
|
|
match fmt {
|
|
AgentPluginFormat::Claude => {
|
|
if val.get("hooks").is_some()
|
|
|| val.get("agents").is_some()
|
|
|| val.get("commands").is_some()
|
|
|| val.get("lspServers").is_some()
|
|
{
|
|
harnesses.insert("claude".into());
|
|
}
|
|
}
|
|
AgentPluginFormat::Copilot => {
|
|
if val.get("hooks").is_some() || val.get("extensions").is_some() || val.get("agents").is_some() {
|
|
harnesses.insert("copilot".into());
|
|
}
|
|
}
|
|
AgentPluginFormat::Codex => {
|
|
if val.get("hooks").is_some() || val.get("apps").is_some() {
|
|
harnesses.insert("codex".into());
|
|
}
|
|
}
|
|
AgentPluginFormat::GeminiExtension => {
|
|
harnesses.insert("gemini".into());
|
|
}
|
|
AgentPluginFormat::AgentPluginsV1 => {
|
|
if val.pointer("/extensions/com.openai").is_some() {
|
|
harnesses.insert("codex".into());
|
|
}
|
|
if val.pointer("/extensions/com.github.copilot").is_some() {
|
|
harnesses.insert("copilot".into());
|
|
}
|
|
}
|
|
AgentPluginFormat::OpenIdea => {}
|
|
}
|
|
}
|
|
|
|
fn classify_hook_harness(rel: &str, harnesses: &mut BTreeSet<String>) {
|
|
let lower = rel.to_ascii_lowercase();
|
|
if lower.contains("copilot") {
|
|
harnesses.insert("copilot".into());
|
|
} else if lower.contains("codex") {
|
|
harnesses.insert("codex".into());
|
|
} else {
|
|
harnesses.insert("claude".into());
|
|
}
|
|
}
|
|
|
|
fn collect_plugin_skill_dirs(root: &Path) -> Vec<PathBuf> {
|
|
let mut dirs = Vec::new();
|
|
let mut seen = HashSet::new();
|
|
let mut push = |p: PathBuf| {
|
|
if p.is_dir() {
|
|
let c = dunce::canonicalize(&p).unwrap_or_else(|_| p.clone());
|
|
if seen.insert(c) {
|
|
dirs.push(p);
|
|
}
|
|
}
|
|
};
|
|
|
|
for (rel, _) in MANIFEST_CANDIDATES {
|
|
let mp = root.join(rel);
|
|
if let Ok(raw) = std::fs::read_to_string(&mp)
|
|
&& let Ok(val) = parse_jsonc(&raw)
|
|
&& let Some(skills_val) = val.get("skills")
|
|
{
|
|
match skills_val {
|
|
Value::String(s) => {
|
|
if let Some(d) = resolve_dir_within(root, s) {
|
|
push(d);
|
|
}
|
|
}
|
|
Value::Array(arr) => {
|
|
for item in arr.iter().filter_map(Value::as_str) {
|
|
if let Some(d) = resolve_dir_within(root, item) {
|
|
push(d);
|
|
}
|
|
}
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
}
|
|
|
|
if root.join("skills").is_dir() {
|
|
push(root.join("skills"));
|
|
} else if root.join("SKILL.md").is_file() {
|
|
push(root.to_path_buf());
|
|
}
|
|
dirs
|
|
}
|
|
|
|
fn collect_plugin_rule_files(root: &Path) -> Vec<PathBuf> {
|
|
let mut out = Vec::new();
|
|
let mut seen = HashSet::new();
|
|
let mut push_file = |p: PathBuf| {
|
|
if p.is_file() {
|
|
let c = dunce::canonicalize(&p).unwrap_or_else(|_| p.clone());
|
|
if seen.insert(c) {
|
|
out.push(p);
|
|
}
|
|
}
|
|
};
|
|
|
|
for rel_dir in ["rules", "com.github.copilot/rules"] {
|
|
for f in sorted_files_with_exts(&root.join(rel_dir), &["md", "mdc", "markdown"]) {
|
|
push_file(f);
|
|
}
|
|
}
|
|
let gemini_manifest = root.join("gemini-extension.json");
|
|
if gemini_manifest.is_file() {
|
|
let ctx_name = std::fs::read_to_string(&gemini_manifest)
|
|
.ok()
|
|
.and_then(|t| parse_jsonc(&t).ok())
|
|
.and_then(|v| v.get("contextFileName").and_then(Value::as_str).map(str::to_owned))
|
|
.unwrap_or_else(|| "GEMINI.md".into());
|
|
if let Some(f) = resolve_file_within(root, &ctx_name) {
|
|
push_file(f);
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
/// Hook files and inline hook objects a plugin manifest declares (`hooks`, or Codex's
|
|
/// `extensions.com.openai.hooks`): plugin-relative paths, and `(<manifest>#<field>, JSON)` pairs
|
|
/// that stand in for inline objects in the consent list and capability hash.
|
|
fn manifest_hook_declarations(manifest_rel: &str, manifest: &Value) -> (Vec<String>, Vec<(String, Vec<u8>)>) {
|
|
let mut paths = Vec::new();
|
|
let mut inline = Vec::new();
|
|
let fields = [
|
|
("hooks", manifest.get("hooks")),
|
|
("extensions.com.openai.hooks", manifest.pointer("/extensions/com.openai/hooks")),
|
|
];
|
|
for (field, decl) in fields {
|
|
let Some(decl) = decl else { continue };
|
|
let (items, indexed): (Vec<&Value>, bool) = match decl {
|
|
Value::Array(items) => (items.iter().collect(), true),
|
|
other => (vec![other], false),
|
|
};
|
|
for (index, item) in items.into_iter().enumerate() {
|
|
match item {
|
|
Value::String(raw) => paths.extend(hook_token_relative_path(raw)),
|
|
Value::Object(_) => {
|
|
let label = if indexed {
|
|
format!("{manifest_rel}#{field}[{index}]")
|
|
} else {
|
|
format!("{manifest_rel}#{field}")
|
|
};
|
|
inline.push((label, serde_json::to_vec(item).unwrap_or_default()));
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
}
|
|
(paths, inline)
|
|
}
|
|
|
|
fn read_plugin_mcp_servers(
|
|
plugin_root: &Path,
|
|
plugin_id: &str,
|
|
home: Option<&Path>,
|
|
workspace_root: Option<&Path>,
|
|
config_fields: &[AgentPluginConfigField],
|
|
resolved_cfg: &BTreeMap<String, String>,
|
|
) -> BTreeMap<String, AgentMcpServer> {
|
|
let mut merged = BTreeMap::new();
|
|
|
|
for default_rel in [".mcp.json", "mcp.json", ".github/mcp.json"] {
|
|
if let Some(path) = resolve_file_within(plugin_root, default_rel) {
|
|
merged.extend(crate::mcp::read_external_mcp_file(&path));
|
|
}
|
|
}
|
|
|
|
for (rel, _) in MANIFEST_CANDIDATES {
|
|
let Some(manifest_path) = resolve_file_within(plugin_root, rel) else { continue };
|
|
let Ok(raw) = std::fs::read_to_string(&manifest_path) else { continue };
|
|
let Ok(val) = parse_jsonc(&raw) else { continue };
|
|
let Some(mcp_val) = val.get("mcpServers") else { continue };
|
|
extract_mcp_from_manifest_value(plugin_root, mcp_val, &mut merged);
|
|
}
|
|
|
|
let root_s = plugin_root.to_string_lossy();
|
|
let _ = (plugin_id, home);
|
|
let data_dir = plugin_root.join(".plugin-data");
|
|
let data_s = data_dir.to_string_lossy();
|
|
let ws_s = workspace_root.map(|w| w.to_string_lossy().into_owned()).unwrap_or_default();
|
|
|
|
let expand = |raw: &str| -> String {
|
|
let mut out = raw
|
|
.replace("${PLUGIN_ROOT}", &root_s)
|
|
.replace("${CLAUDE_PLUGIN_ROOT}", &root_s)
|
|
.replace("${COPILOT_PLUGIN_ROOT}", &root_s)
|
|
.replace("${CURSOR_PLUGIN_ROOT}", &root_s)
|
|
.replace("${extensionPath}", &root_s)
|
|
.replace("${PLUGIN_DATA}", &data_s)
|
|
.replace("${CLAUDE_PLUGIN_DATA}", &data_s)
|
|
.replace("${COPILOT_PLUGIN_DATA}", &data_s);
|
|
if !ws_s.is_empty() {
|
|
out = out.replace("${CLAUDE_PROJECT_DIR}", &ws_s).replace("${WORKSPACE_FOLDER}", &ws_s);
|
|
}
|
|
for (k, v) in resolved_cfg {
|
|
out = out.replace(&format!("${{user_config.{k}}}"), v);
|
|
out = out.replace(&format!("${{{k}}}"), v);
|
|
}
|
|
out
|
|
};
|
|
|
|
for srv in merged.values_mut() {
|
|
if let Some(cmd) = srv.command.as_mut() {
|
|
*cmd = expand(cmd);
|
|
}
|
|
for arg in &mut srv.args {
|
|
*arg = expand(arg);
|
|
}
|
|
if let Some(url) = srv.url.as_mut() {
|
|
*url = expand(url);
|
|
}
|
|
for val in srv.env.values_mut() {
|
|
*val = expand(val);
|
|
}
|
|
for val in srv.headers.values_mut() {
|
|
*val = expand(val);
|
|
}
|
|
// Inject Gemini `settings[].envVar` or explicit `env_var` bindings when set:
|
|
for field in config_fields {
|
|
if let Some(env_name) = field.env_var.as_deref()
|
|
&& let Some(v) = resolved_cfg.get(&field.key).filter(|s| !s.is_empty())
|
|
{
|
|
srv.env.entry(env_name.to_owned()).or_insert_with(|| v.clone());
|
|
}
|
|
}
|
|
}
|
|
|
|
merged
|
|
}
|
|
|
|
fn extract_mcp_from_manifest_value(plugin_root: &Path, mcp_val: &Value, out: &mut BTreeMap<String, AgentMcpServer>) {
|
|
match mcp_val {
|
|
Value::String(rel) => {
|
|
if let Some(p) = resolve_file_within(plugin_root, rel) {
|
|
out.extend(crate::mcp::read_external_mcp_file(&p));
|
|
}
|
|
}
|
|
Value::Array(items) => {
|
|
for item in items {
|
|
extract_mcp_from_manifest_value(plugin_root, item, out);
|
|
}
|
|
}
|
|
Value::Object(_) => {
|
|
let wrapper = json!({ "mcpServers": mcp_val });
|
|
if let Ok(parsed) = crate::mcp::parse_mcp_value(&wrapper) {
|
|
out.extend(parsed);
|
|
}
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
|
|
fn resolved_config_map(
|
|
plugin: &AgentPlugin,
|
|
policy: &PluginsPolicy,
|
|
_secrets: Option<&dyn EnvSecrets>,
|
|
) -> BTreeMap<String, String> {
|
|
let trusted = policy.workspace_trusted;
|
|
let user_pol = lookup_entry_policy(&policy.user.entries, plugin);
|
|
let ws_pol = lookup_entry_policy(&policy.workspace.entries, plugin);
|
|
let mut out = BTreeMap::new();
|
|
for field in &plugin.config_fields {
|
|
let val = if field.kind == AgentPluginConfigFieldKind::Secret {
|
|
None
|
|
} else {
|
|
ws_pol
|
|
.filter(|_| trusted)
|
|
.and_then(|p| p.config.get(&field.key))
|
|
.or_else(|| user_pol.and_then(|p| p.config.get(&field.key)))
|
|
.or(field.default_value.as_ref())
|
|
.filter(|v| !v.is_empty())
|
|
.cloned()
|
|
};
|
|
if let Some(v) = val {
|
|
out.insert(field.key.clone(), v);
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
fn extract_manifest_config_fields(val: &Value, out: &mut Vec<AgentPluginConfigField>, seen: &mut HashSet<String>) {
|
|
// 1. Claude Code `userConfig`: `{ "<key>": { "type": "string|number|boolean", "title", "description", "sensitive", "default" } }`
|
|
if let Some(obj) = val.get("userConfig").and_then(Value::as_object) {
|
|
for (key, spec) in obj {
|
|
let Some(spec_obj) = spec.as_object() else { continue };
|
|
if !seen.insert(key.clone()) {
|
|
continue;
|
|
}
|
|
let sensitive = spec_obj.get("sensitive").and_then(Value::as_bool) == Some(true);
|
|
let kind = if sensitive {
|
|
AgentPluginConfigFieldKind::Secret
|
|
} else {
|
|
match spec_obj.get("type").and_then(Value::as_str).unwrap_or("string") {
|
|
"number" | "integer" => AgentPluginConfigFieldKind::Number,
|
|
"boolean" => AgentPluginConfigFieldKind::Boolean,
|
|
_ => AgentPluginConfigFieldKind::String,
|
|
}
|
|
};
|
|
let title = spec_obj
|
|
.get("title")
|
|
.and_then(Value::as_str)
|
|
.map(str::trim)
|
|
.filter(|s| !s.is_empty())
|
|
.unwrap_or(key)
|
|
.to_owned();
|
|
let description =
|
|
spec_obj.get("description").and_then(Value::as_str).map(str::trim).unwrap_or_default().to_owned();
|
|
let default_value = scalar_to_string(spec_obj.get("default"));
|
|
out.push(AgentPluginConfigField {
|
|
key: key.clone(),
|
|
title,
|
|
description,
|
|
kind,
|
|
default_value,
|
|
required: spec_obj.get("required").and_then(Value::as_bool) == Some(true),
|
|
env_var: Some(format!("CLAUDE_PLUGIN_OPTION_{}", key.to_ascii_uppercase().replace('-', "_"))),
|
|
value: String::new(),
|
|
has_secret: false,
|
|
});
|
|
}
|
|
}
|
|
|
|
// 2. Agent Plugins `variables`: JSON-Schema subset with per-variable defaults and required keys.
|
|
if let Some(vars) = val.get("variables").and_then(Value::as_object) {
|
|
let req_set: HashSet<&str> =
|
|
vars.get("required").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).collect();
|
|
let props = vars.get("properties").and_then(Value::as_object).unwrap_or(vars);
|
|
for (key, spec) in props {
|
|
if key == "type" || key == "required" || key == "properties" {
|
|
continue;
|
|
}
|
|
let Some(spec_obj) = spec.as_object() else { continue };
|
|
if !seen.insert(key.clone()) {
|
|
continue;
|
|
}
|
|
let lower = key.to_ascii_lowercase();
|
|
let is_secret = spec_obj.get("sensitive").and_then(Value::as_bool) == Some(true)
|
|
|| lower.contains("token")
|
|
|| lower.contains("secret")
|
|
|| lower.contains("password")
|
|
|| lower.contains("api_key")
|
|
|| lower.contains("apikey");
|
|
let kind = if is_secret {
|
|
AgentPluginConfigFieldKind::Secret
|
|
} else {
|
|
match spec_obj.get("type").and_then(Value::as_str).unwrap_or("string") {
|
|
"number" | "integer" => AgentPluginConfigFieldKind::Number,
|
|
"boolean" => AgentPluginConfigFieldKind::Boolean,
|
|
_ => AgentPluginConfigFieldKind::String,
|
|
}
|
|
};
|
|
let title = spec_obj
|
|
.get("title")
|
|
.and_then(Value::as_str)
|
|
.map(str::trim)
|
|
.filter(|s| !s.is_empty())
|
|
.unwrap_or(key)
|
|
.to_owned();
|
|
let description =
|
|
spec_obj.get("description").and_then(Value::as_str).map(str::trim).unwrap_or_default().to_owned();
|
|
out.push(AgentPluginConfigField {
|
|
key: key.clone(),
|
|
title,
|
|
description,
|
|
kind,
|
|
default_value: scalar_to_string(spec_obj.get("default")),
|
|
required: req_set.contains(key.as_str()),
|
|
env_var: None,
|
|
value: String::new(),
|
|
has_secret: false,
|
|
});
|
|
}
|
|
}
|
|
|
|
// 3. Gemini `settings`: `[ { "name", "description", "envVar", "sensitive" } ]`
|
|
if let Some(arr) = val.get("settings").and_then(Value::as_array) {
|
|
for item in arr {
|
|
let Some(obj) = item.as_object() else { continue };
|
|
// Gemini requires `envVar`; the human-readable `name` is not a valid variable name.
|
|
let Some(env_var) =
|
|
obj.get("envVar").and_then(Value::as_str).map(str::trim).filter(|s| is_valid_env_var_name(s))
|
|
else {
|
|
continue;
|
|
};
|
|
if !seen.insert(env_var.to_owned()) {
|
|
continue;
|
|
}
|
|
let sensitive = obj.get("sensitive").and_then(Value::as_bool) == Some(true);
|
|
let title = obj
|
|
.get("name")
|
|
.and_then(Value::as_str)
|
|
.map(str::trim)
|
|
.filter(|s| !s.is_empty())
|
|
.unwrap_or(env_var)
|
|
.to_owned();
|
|
let description =
|
|
obj.get("description").and_then(Value::as_str).map(str::trim).unwrap_or_default().to_owned();
|
|
out.push(AgentPluginConfigField {
|
|
key: env_var.to_owned(),
|
|
title,
|
|
description,
|
|
kind: if sensitive { AgentPluginConfigFieldKind::Secret } else { AgentPluginConfigFieldKind::String },
|
|
default_value: None,
|
|
required: false,
|
|
env_var: Some(env_var.to_owned()),
|
|
value: String::new(),
|
|
has_secret: false,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
fn scalar_to_string(v: Option<&Value>) -> Option<String> {
|
|
match v? {
|
|
Value::String(s) => Some(s.clone()),
|
|
Value::Number(n) => Some(n.to_string()),
|
|
Value::Bool(b) => Some(b.to_string()),
|
|
_ => None,
|
|
}
|
|
}
|
|
|
|
fn scan_plugin_container(container: &Path, two_level: bool) -> Vec<(PathBuf, Option<String>)> {
|
|
let mut out = Vec::new();
|
|
for entry in sorted_dirs(container) {
|
|
let Some(name) = entry.file_name().and_then(|n| n.to_str()) else { continue };
|
|
if name.starts_with('.') {
|
|
continue;
|
|
}
|
|
if has_any_plugin_marker(&entry) || !two_level {
|
|
out.push((entry, None));
|
|
} else {
|
|
let mkt = (name != "_direct").then(|| name.to_owned());
|
|
for sub in sorted_dirs(&entry) {
|
|
out.push((sub, mkt.clone()));
|
|
}
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
/// Orders version-like names with numeric runs compared by value (`v10.0` after `v2.0`).
|
|
fn natural_version_cmp(left: &str, right: &str) -> std::cmp::Ordering {
|
|
fn chunks(raw: &str) -> Vec<Result<u128, &str>> {
|
|
let mut out = Vec::new();
|
|
let mut start = 0;
|
|
let bytes = raw.as_bytes();
|
|
while start < bytes.len() {
|
|
let numeric = bytes[start].is_ascii_digit();
|
|
let end = bytes[start..]
|
|
.iter()
|
|
.position(|b| b.is_ascii_digit() != numeric)
|
|
.map_or(bytes.len(), |offset| start + offset);
|
|
let part = &raw[start..end];
|
|
out.push(if numeric { part.parse::<u128>().map_err(|_| part) } else { Err(part) });
|
|
start = end;
|
|
}
|
|
out
|
|
}
|
|
let (left_chunks, right_chunks) = (chunks(left), chunks(right));
|
|
for (l, r) in left_chunks.iter().zip(&right_chunks) {
|
|
let ordering = match (l, r) {
|
|
(Ok(l), Ok(r)) => l.cmp(r),
|
|
(Ok(_), Err(_)) => std::cmp::Ordering::Greater,
|
|
(Err(_), Ok(_)) => std::cmp::Ordering::Less,
|
|
(Err(l), Err(r)) => l.cmp(r),
|
|
};
|
|
if ordering.is_ne() {
|
|
return ordering;
|
|
}
|
|
}
|
|
left_chunks.len().cmp(&right_chunks.len()).then_with(|| left.cmp(right))
|
|
}
|
|
|
|
fn scan_versioned_plugin_container(container: &Path, local_wins: bool) -> Vec<(PathBuf, Option<String>)> {
|
|
let mut out = Vec::new();
|
|
for marketplace_dir in sorted_dirs(container) {
|
|
let marketplace = marketplace_dir
|
|
.file_name()
|
|
.and_then(|name| name.to_str())
|
|
.filter(|name| *name != "_direct")
|
|
.map(str::to_owned);
|
|
for plugin_dir in sorted_dirs(&marketplace_dir) {
|
|
let mut versions = sorted_dirs(&plugin_dir);
|
|
if versions.is_empty() {
|
|
continue;
|
|
}
|
|
if local_wins
|
|
&& let Some(local) =
|
|
versions.iter().position(|path| path.file_name().and_then(|name| name.to_str()) == Some("local"))
|
|
{
|
|
out.push((versions.swap_remove(local), marketplace.clone()));
|
|
continue;
|
|
}
|
|
versions.sort_by(|left, right| {
|
|
let left = left.file_name().and_then(|name| name.to_str()).unwrap_or_default();
|
|
let right = right.file_name().and_then(|name| name.to_str()).unwrap_or_default();
|
|
let parse = |raw: &str| semver::Version::parse(raw.strip_prefix('v').unwrap_or(raw));
|
|
match (parse(left), parse(right)) {
|
|
(Ok(left), Ok(right)) => left.cmp(&right),
|
|
_ => natural_version_cmp(left, right),
|
|
}
|
|
});
|
|
out.push((versions.pop().expect("non-empty plugin versions"), marketplace.clone()));
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
fn has_any_plugin_marker(dir: &Path) -> bool {
|
|
MANIFEST_CANDIDATES.iter().any(|(rel, _)| dir.join(rel).is_file())
|
|
|| dir.join("skills").is_dir()
|
|
|| dir.join("SKILL.md").is_file()
|
|
|| dir.join(".mcp.json").is_file()
|
|
|| dir.join("mcp.json").is_file()
|
|
}
|
|
|
|
fn discover_copilot_plugins(copilot_dir: &Path) -> Vec<(PathBuf, Option<String>, Option<bool>)> {
|
|
let mut out = Vec::new();
|
|
let mut seen: HashSet<PathBuf> = HashSet::new();
|
|
|
|
let disabled_by_settings: BTreeMap<String, bool> = std::fs::read_to_string(copilot_dir.join("settings.json"))
|
|
.ok()
|
|
.and_then(|t| parse_jsonc(&t).ok())
|
|
.and_then(|v| v.get("enabledPlugins").and_then(Value::as_object).cloned())
|
|
.into_iter()
|
|
.flatten()
|
|
.filter_map(|(k, v)| Some((k, v.as_bool()?)))
|
|
.collect();
|
|
|
|
if let Ok(text) = std::fs::read_to_string(copilot_dir.join("config.json"))
|
|
&& let Ok(root) = parse_jsonc(&text)
|
|
&& let Some(installed) = root.get("installedPlugins").and_then(Value::as_array)
|
|
{
|
|
for item in installed {
|
|
let Some(obj) = item.as_object() else { continue };
|
|
let Some(raw_cache) =
|
|
obj.get("cache_path").and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty())
|
|
else {
|
|
continue;
|
|
};
|
|
let dir =
|
|
if Path::new(raw_cache).is_relative() { copilot_dir.join(raw_cache) } else { PathBuf::from(raw_cache) };
|
|
if !dir.is_dir() {
|
|
continue;
|
|
}
|
|
let canon = dunce::canonicalize(&dir).unwrap_or_else(|_| dir.clone());
|
|
if !seen.insert(canon) {
|
|
continue;
|
|
}
|
|
let mkt = obj
|
|
.get("marketplace")
|
|
.and_then(Value::as_str)
|
|
.map(str::trim)
|
|
.filter(|s| !s.is_empty() && *s != "_direct")
|
|
.map(str::to_owned);
|
|
let name = obj.get("name").and_then(Value::as_str).unwrap_or_default();
|
|
let cfg_enabled = obj.get("enabled").and_then(Value::as_bool).unwrap_or(true);
|
|
// Only marketplace plugins have an `enabledPlugins` key (`name@marketplace`).
|
|
let settings_override =
|
|
mkt.as_deref().and_then(|m| disabled_by_settings.get(&format!("{name}@{m}"))).copied();
|
|
let effective = settings_override.unwrap_or(cfg_enabled);
|
|
out.push((dir, mkt, Some(effective)));
|
|
}
|
|
}
|
|
|
|
for (dir, mkt) in scan_plugin_container(&copilot_dir.join("installed-plugins"), true) {
|
|
let canon = dunce::canonicalize(&dir).unwrap_or_else(|_| dir.clone());
|
|
if seen.insert(canon) {
|
|
let folder = dir.file_name().and_then(|s| s.to_str()).unwrap_or_default();
|
|
let settings_override =
|
|
mkt.as_deref().and_then(|m| disabled_by_settings.get(&format!("{folder}@{m}"))).copied();
|
|
out.push((dir, mkt, settings_override));
|
|
}
|
|
}
|
|
|
|
// Plugins Copilot loads live from a local directory marketplace: only `enabledPlugins` and the
|
|
// marketplace's `extraKnownMarketplaces` entry record them; nothing is copied.
|
|
for (key, enabled) in &disabled_by_settings {
|
|
let Some((name, marketplace)) = key.rsplit_once('@') else { continue };
|
|
let Some(dir) = copilot_live_plugin_dir(copilot_dir, name, marketplace) else { continue };
|
|
let canon = dunce::canonicalize(&dir).unwrap_or_else(|_| dir.clone());
|
|
if seen.insert(canon) {
|
|
out.push((dir, Some(marketplace.to_owned()), Some(*enabled)));
|
|
}
|
|
}
|
|
|
|
out
|
|
}
|
|
|
|
/// The folder of `name` in a local directory marketplace Copilot knows from `extraKnownMarketplaces`.
|
|
fn copilot_live_plugin_dir(copilot_dir: &Path, name: &str, marketplace: &str) -> Option<PathBuf> {
|
|
copilot_live_plugin_dir_in(&[copilot_dir.join("settings.json")], name, marketplace)
|
|
}
|
|
|
|
/// Like [`copilot_live_plugin_dir`], reading `extraKnownMarketplaces` from the first of `settings`
|
|
/// files that declares `marketplace` (repository settings before user settings).
|
|
fn copilot_live_plugin_dir_in(settings: &[PathBuf], name: &str, marketplace: &str) -> Option<PathBuf> {
|
|
let source = settings.iter().find_map(|path| {
|
|
read_json_object(path).ok()?.get("extraKnownMarketplaces")?.get(marketplace)?.get("source").cloned()
|
|
})?;
|
|
if source.get("source").and_then(Value::as_str) != Some("directory") {
|
|
return None;
|
|
}
|
|
let root = PathBuf::from(source.get("path").and_then(Value::as_str)?);
|
|
let manifest = MARKETPLACE_MANIFEST_PATHS.iter().map(|rel| root.join(rel)).find(|path| path.is_file())?;
|
|
let value = parse_jsonc(&std::fs::read_to_string(manifest).ok()?).ok()?;
|
|
let plugin_root =
|
|
safe_marketplace_subpath(value.pointer("/metadata/pluginRoot").and_then(Value::as_str).unwrap_or_default())?;
|
|
let entry =
|
|
value.get("plugins")?.as_array()?.iter().find(|item| item.get("name").and_then(Value::as_str) == Some(name))?;
|
|
let (dir, _) = resolve_marketplace_entry_source(entry, &root, plugin_root);
|
|
let dir = PathBuf::from(dir);
|
|
dir.is_dir().then_some(dir)
|
|
}
|
|
|
|
/// Copilot loads plugins from a local directory marketplace in place instead of copying them.
|
|
fn copilot_installs_live(
|
|
source: AgentPluginSource,
|
|
source_kind: &str,
|
|
marketplace: Option<&str>,
|
|
marketplace_source: Option<&str>,
|
|
) -> bool {
|
|
source == AgentPluginSource::CopilotUser
|
|
&& source_kind == "local"
|
|
&& marketplace.is_some_and(|m| !m.trim().is_empty())
|
|
&& marketplace_source.is_some_and(|path| Path::new(path).is_absolute())
|
|
}
|
|
|
|
struct ClaudeDiscoveredPlugin {
|
|
dir: PathBuf,
|
|
marketplace: Option<String>,
|
|
enabled: Option<bool>,
|
|
scope: McpScope,
|
|
project_path: Option<PathBuf>,
|
|
}
|
|
|
|
fn discover_claude_plugins(claude_dir: &Path) -> Vec<ClaudeDiscoveredPlugin> {
|
|
let mut out = Vec::new();
|
|
let mut seen: HashSet<(PathBuf, McpScope, Option<PathBuf>)> = HashSet::new();
|
|
let mut registered_paths = HashSet::new();
|
|
let mut registered_bases = HashSet::new();
|
|
|
|
let enabled_map: BTreeMap<String, bool> = std::fs::read_to_string(claude_dir.join("settings.json"))
|
|
.ok()
|
|
.and_then(|t| parse_jsonc(&t).ok())
|
|
.and_then(|v| v.get("enabledPlugins").and_then(Value::as_object).cloned())
|
|
.into_iter()
|
|
.flatten()
|
|
.filter_map(|(k, v)| Some((k, v.as_bool()?)))
|
|
.collect();
|
|
|
|
if let Ok(text) = std::fs::read_to_string(claude_dir.join("plugins/installed_plugins.json"))
|
|
&& let Ok(val) = parse_jsonc(&text)
|
|
{
|
|
// Supports both `{ "plugins": { "name@mkt": [ { "installPath": "..." } ] } }` and flat object/array forms.
|
|
let plugins_val = val.get("plugins").unwrap_or(&val);
|
|
if let Some(obj) = plugins_val.as_object() {
|
|
for (key, entry_val) in obj {
|
|
let (plug_name, mkt) = match key.split_once('@') {
|
|
Some((n, m)) => (n, (!m.is_empty()).then(|| m.to_owned())),
|
|
None => (key.as_str(), None),
|
|
};
|
|
let candidates: Vec<&Value> = match entry_val {
|
|
Value::Array(arr) => arr.iter().collect(),
|
|
v @ Value::Object(_) => vec![v],
|
|
_ => Vec::new(),
|
|
};
|
|
for c in candidates {
|
|
let Some(raw_path) = c
|
|
.get("installPath")
|
|
.or_else(|| c.get("path"))
|
|
.and_then(Value::as_str)
|
|
.map(str::trim)
|
|
.filter(|s| !s.is_empty())
|
|
else {
|
|
continue;
|
|
};
|
|
let dir = PathBuf::from(raw_path);
|
|
if !dir.is_dir() {
|
|
continue;
|
|
}
|
|
let scope = match c.get("scope").and_then(Value::as_str) {
|
|
Some("project") | Some("local") => McpScope::Workspace,
|
|
_ => McpScope::User,
|
|
};
|
|
let project_path = c
|
|
.get("projectPath")
|
|
.and_then(Value::as_str)
|
|
.filter(|path| !path.trim().is_empty())
|
|
.map(PathBuf::from);
|
|
let canon = dunce::canonicalize(&dir).unwrap_or_else(|_| dir.clone());
|
|
registered_paths.insert(canon.clone());
|
|
if let Some(base) = dir.parent() {
|
|
registered_bases.insert(dunce::canonicalize(base).unwrap_or_else(|_| base.to_path_buf()));
|
|
}
|
|
if seen.insert((canon, scope, project_path.clone())) {
|
|
let en = lookup_plugin_bool(&enabled_map, plug_name, mkt.as_deref()).copied();
|
|
out.push(ClaudeDiscoveredPlugin {
|
|
dir,
|
|
marketplace: mkt.clone(),
|
|
enabled: en,
|
|
scope,
|
|
project_path,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
for (dir, mkt) in scan_versioned_plugin_container(&claude_dir.join("plugins/cache"), false) {
|
|
let canon = dunce::canonicalize(&dir).unwrap_or_else(|_| dir.clone());
|
|
if registered_paths.contains(&canon) {
|
|
continue;
|
|
}
|
|
if dir
|
|
.parent()
|
|
.is_some_and(|base| registered_bases.contains(&dunce::canonicalize(base).unwrap_or_else(|_| base.into())))
|
|
{
|
|
continue;
|
|
}
|
|
if seen.insert((canon, McpScope::User, None)) {
|
|
let folder = dir.parent().and_then(Path::file_name).and_then(|s| s.to_str()).unwrap_or_default();
|
|
let en = lookup_plugin_bool(&enabled_map, folder, mkt.as_deref()).copied();
|
|
out.push(ClaudeDiscoveredPlugin {
|
|
dir,
|
|
marketplace: mkt,
|
|
enabled: en,
|
|
scope: McpScope::User,
|
|
project_path: None,
|
|
});
|
|
}
|
|
}
|
|
|
|
out
|
|
}
|
|
|
|
fn read_codex_plugin_states(config_toml: &Path) -> BTreeMap<String, bool> {
|
|
let Ok(text) = std::fs::read_to_string(config_toml) else { return BTreeMap::new() };
|
|
let Ok(val) = toml::from_str::<toml::Value>(&text) else { return BTreeMap::new() };
|
|
let Some(tbl) = val.get("plugins").and_then(toml::Value::as_table) else { return BTreeMap::new() };
|
|
let mut out = BTreeMap::new();
|
|
for (k, v) in tbl {
|
|
if let Some(en) = v.get("enabled").and_then(toml::Value::as_bool) {
|
|
out.insert(k.clone(), en);
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
fn native_plugin_enabled(
|
|
source: AgentPluginSource,
|
|
scope: McpScope,
|
|
home: Option<&Path>,
|
|
workspace_root: Option<&Path>,
|
|
name: &str,
|
|
marketplace: Option<&str>,
|
|
) -> Option<bool> {
|
|
let path = native_settings_path(source, scope, home, workspace_root).ok()?;
|
|
if source == AgentPluginSource::GeminiUser {
|
|
let scope_path = gemini_scope_path(scope, home, workspace_root).ok()?;
|
|
if scope == McpScope::Workspace && !gemini_workspace_owns_rule(&path, name, &scope_path) {
|
|
return None;
|
|
}
|
|
return read_gemini_plugin_enabled(&path, name, &scope_path);
|
|
}
|
|
if source == AgentPluginSource::CopilotUser {
|
|
// Copilot keys repository and user `enabledPlugins` by `name@marketplace` only.
|
|
let key = format!("{name}@{}", marketplace.filter(|m| !m.is_empty() && *m != "_direct")?);
|
|
return json_plugin_enabled_map(&path).get(&key).copied();
|
|
}
|
|
let map = if source == AgentPluginSource::CodexUser {
|
|
read_codex_plugin_states(&path)
|
|
} else {
|
|
std::fs::read_to_string(path)
|
|
.ok()
|
|
.and_then(|text| parse_jsonc(&text).ok())
|
|
.and_then(|value| value.get("enabledPlugins").and_then(Value::as_object).cloned())
|
|
.into_iter()
|
|
.flatten()
|
|
.filter_map(|(key, value)| value.as_bool().map(|enabled| (key, enabled)))
|
|
.collect()
|
|
};
|
|
lookup_plugin_bool(&map, name, marketplace).copied()
|
|
}
|
|
|
|
fn read_extra_known_marketplaces(ws: &Path) -> Vec<String> {
|
|
let mut out = Vec::new();
|
|
for rel in [".claude/settings.json", ".github/copilot/settings.json"] {
|
|
if let Ok(text) = std::fs::read_to_string(ws.join(rel))
|
|
&& let Ok(val) = parse_jsonc(&text)
|
|
&& let Some(obj) = val.get("extraKnownMarketplaces").and_then(Value::as_object)
|
|
{
|
|
for (_, spec) in obj {
|
|
if let Some(repo) = spec.pointer("/source/repo").and_then(Value::as_str) {
|
|
out.push(repo.to_owned());
|
|
} else if let Some(url) = spec.pointer("/source/url").and_then(Value::as_str) {
|
|
out.push(url.to_owned());
|
|
}
|
|
}
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
fn lookup_entry_policy<'a>(
|
|
map: &'a BTreeMap<String, AgentPluginEntryPolicy>,
|
|
plugin: &AgentPlugin,
|
|
) -> Option<&'a AgentPluginEntryPolicy> {
|
|
map.get(&plugin_policy_key(plugin))
|
|
}
|
|
|
|
fn lookup_plugin_bool<'a>(map: &'a BTreeMap<String, bool>, name: &str, marketplace: Option<&str>) -> Option<&'a bool> {
|
|
if let Some(m) = marketplace
|
|
&& let Some(v) = map.get(&format!("{name}@{m}")).or_else(|| map.get(&format!("{m}/{name}")))
|
|
{
|
|
return Some(v);
|
|
}
|
|
map.get(name)
|
|
}
|
|
|
|
fn browse_local_marketplace(
|
|
local_path: &Path,
|
|
raw_source: &str,
|
|
user_home: Option<&Path>,
|
|
workspace_root: Option<&Path>,
|
|
) -> IdeResult<AgentMarketplaceBrowseResult> {
|
|
let mkt_file = if local_path.is_file() {
|
|
Some(local_path.to_path_buf())
|
|
} else {
|
|
MARKETPLACE_MANIFEST_PATHS.iter().map(|rel| local_path.join(rel)).find(|p| p.is_file())
|
|
};
|
|
|
|
if let Some(mf) = mkt_file {
|
|
let text = std::fs::read_to_string(&mf)?;
|
|
let val = parse_jsonc(&text).map_err(|e| IdeError::invalid(format!("Invalid marketplace.json: {e}")))?;
|
|
let mkt_name = val.get("name").and_then(Value::as_str).unwrap_or("local-marketplace").to_owned();
|
|
let root_dir = local_path.is_dir().then_some(local_path).or_else(|| mf.parent()).unwrap_or(local_path);
|
|
let plugin_root_prefix = val
|
|
.pointer("/metadata/pluginRoot")
|
|
.and_then(Value::as_str)
|
|
.map(|s| s.trim().trim_matches('/'))
|
|
.unwrap_or_default();
|
|
let mut candidates = Vec::new();
|
|
if let Some(arr) = val.get("plugins").and_then(Value::as_array) {
|
|
for item in arr {
|
|
let Some(raw_name) = item.get("name").and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty())
|
|
else {
|
|
continue;
|
|
};
|
|
let name = sanitize_plugin_slug(raw_name);
|
|
let display_name = item
|
|
.get("displayName")
|
|
.or_else(|| item.pointer("/interface/displayName"))
|
|
.and_then(Value::as_str)
|
|
.unwrap_or(raw_name)
|
|
.to_owned();
|
|
let description = item.get("description").and_then(Value::as_str).unwrap_or_default().trim().to_owned();
|
|
let version = item.get("version").and_then(Value::as_str).map(str::to_owned);
|
|
let author = extract_author(item);
|
|
let keywords = extract_string_array(item.get("keywords"));
|
|
let (source_spec, subpath) = resolve_marketplace_entry_source(item, root_dir, plugin_root_prefix);
|
|
if source_spec.is_empty() {
|
|
continue;
|
|
}
|
|
let (already_user, already_ws) =
|
|
plugin_installed_anywhere(&name, Some(&mkt_name), user_home, workspace_root);
|
|
candidates.push(AgentMarketplaceCandidate {
|
|
name,
|
|
display_name,
|
|
version,
|
|
description,
|
|
author,
|
|
marketplace: Some(mkt_name.clone()),
|
|
source_spec,
|
|
subpath,
|
|
keywords,
|
|
already_installed_user: already_user,
|
|
already_installed_workspace: already_ws,
|
|
});
|
|
}
|
|
}
|
|
return Ok(AgentMarketplaceBrowseResult {
|
|
source: raw_source.to_owned(),
|
|
marketplace_name: mkt_name,
|
|
owner: None,
|
|
repo: None,
|
|
git_ref: None,
|
|
tree_sha: None,
|
|
candidates,
|
|
});
|
|
}
|
|
|
|
// Direct local plugin folder. The source only selects how metadata is read; the target
|
|
// harness is chosen at install time.
|
|
if let Some(plug) = inspect_plugin_dir(local_path, AgentPluginSource::CopilotUser, McpScope::User, None, true) {
|
|
let (already_user, already_ws) = plugin_installed_anywhere(&plug.name, None, user_home, workspace_root);
|
|
return Ok(AgentMarketplaceBrowseResult {
|
|
source: raw_source.to_owned(),
|
|
marketplace_name: plug.display_name.clone(),
|
|
owner: None,
|
|
repo: None,
|
|
git_ref: None,
|
|
tree_sha: None,
|
|
candidates: vec![AgentMarketplaceCandidate {
|
|
name: plug.name,
|
|
display_name: plug.display_name,
|
|
version: plug.version,
|
|
description: plug.description,
|
|
author: plug.author,
|
|
marketplace: None,
|
|
source_spec: local_path.to_string_lossy().into_owned(),
|
|
subpath: String::new(),
|
|
keywords: Vec::new(),
|
|
already_installed_user: already_user,
|
|
already_installed_workspace: already_ws,
|
|
}],
|
|
});
|
|
}
|
|
|
|
Err(IdeError::not_found(format!("No marketplace.json or agent plugin found at {}", local_path.display())))
|
|
}
|
|
|
|
fn resolve_marketplace_entry_source(item: &Value, local_root: &Path, plugin_root_prefix: &str) -> (String, String) {
|
|
if !plugin_root_prefix.is_empty()
|
|
&& !Path::new(plugin_root_prefix).components().all(|c| matches!(c, Component::Normal(_)))
|
|
{
|
|
return (String::new(), String::new());
|
|
}
|
|
let Some(src) = item.get("source") else { return (String::new(), String::new()) };
|
|
if let Some(rel) = src.as_str() {
|
|
let clean = rel.trim().trim_start_matches("./").trim_matches('/');
|
|
if clean.is_empty() || !Path::new(clean).components().all(|c| matches!(c, Component::Normal(_))) {
|
|
return (String::new(), String::new());
|
|
}
|
|
let joined = if plugin_root_prefix.is_empty() {
|
|
local_root.join(clean)
|
|
} else {
|
|
local_root.join(plugin_root_prefix).join(clean)
|
|
};
|
|
return (joined.to_string_lossy().into_owned(), String::new());
|
|
}
|
|
if let Some(obj) = src.as_object() {
|
|
let kind = obj.get("source").and_then(Value::as_str).unwrap_or_default();
|
|
match kind {
|
|
"local" => {
|
|
if let Some(p) = obj.get("path").and_then(Value::as_str) {
|
|
let clean = p.trim().trim_start_matches("./").trim_matches('/');
|
|
if clean.is_empty() || !Path::new(clean).components().all(|c| matches!(c, Component::Normal(_))) {
|
|
return (String::new(), String::new());
|
|
}
|
|
let joined = if plugin_root_prefix.is_empty() {
|
|
local_root.join(clean)
|
|
} else {
|
|
local_root.join(plugin_root_prefix).join(clean)
|
|
};
|
|
return (joined.to_string_lossy().into_owned(), String::new());
|
|
}
|
|
}
|
|
"github" => {
|
|
if let Some(repo) = obj.get("repo").and_then(Value::as_str).and_then(safe_marketplace_repo) {
|
|
let r = obj.get("ref").or_else(|| obj.get("sha")).and_then(Value::as_str);
|
|
let Ok(r) = r.map(|r| safe_marketplace_ref(r).ok_or(())).transpose() else {
|
|
return (String::new(), String::new());
|
|
};
|
|
let spec = match r {
|
|
Some(git_r) => format!("{repo}#{git_r}"),
|
|
None => repo.to_owned(),
|
|
};
|
|
return (spec, String::new());
|
|
}
|
|
}
|
|
"git-subdir" => {
|
|
if let Some(repo) =
|
|
obj.get("repo").or_else(|| obj.get("url")).and_then(Value::as_str).and_then(safe_marketplace_repo)
|
|
{
|
|
let Some(path) =
|
|
safe_marketplace_subpath(obj.get("path").and_then(Value::as_str).unwrap_or_default())
|
|
else {
|
|
return (String::new(), String::new());
|
|
};
|
|
let r = obj.get("ref").or_else(|| obj.get("sha")).and_then(Value::as_str);
|
|
let Ok(r) = r.map(|r| safe_marketplace_ref(r).ok_or(())).transpose() else {
|
|
return (String::new(), String::new());
|
|
};
|
|
let spec = match r {
|
|
Some(git_r) => format!("{repo}#{git_r}"),
|
|
None => repo,
|
|
};
|
|
return (spec, path.to_owned());
|
|
}
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
(String::new(), String::new())
|
|
}
|
|
|
|
/// A marketplace-supplied repository subpath: only normal `/`-separated components.
|
|
fn safe_marketplace_subpath(raw: &str) -> Option<&str> {
|
|
let clean = raw.trim().trim_start_matches("./").trim_matches('/');
|
|
if clean.is_empty() || clean == "." {
|
|
return Some("");
|
|
}
|
|
clean
|
|
.split('/')
|
|
.all(|part| {
|
|
!matches!(part, "" | "." | "..")
|
|
&& !part.contains(['#', '@', '\\', ':'])
|
|
&& !part.chars().any(char::is_control)
|
|
})
|
|
.then_some(clean)
|
|
}
|
|
|
|
fn is_valid_env_var_name(name: &str) -> bool {
|
|
let mut chars = name.chars();
|
|
chars.next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
|
|
&& chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
|
|
}
|
|
|
|
/// A marketplace-supplied Git ref or SHA.
|
|
fn safe_marketplace_ref(raw: &str) -> Option<&str> {
|
|
let r = raw.trim();
|
|
(!r.is_empty()
|
|
&& !r.starts_with(['-', '/'])
|
|
&& !r.contains("..")
|
|
&& r.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-' | '/')))
|
|
.then_some(r)
|
|
}
|
|
|
|
/// A marketplace-supplied GitHub repository: `owner/repo` or `https://github.com/owner/repo[.git]`.
|
|
fn safe_marketplace_repo(raw: &str) -> Option<String> {
|
|
let trimmed = raw.trim();
|
|
let bare = trimmed.strip_prefix("https://github.com/").unwrap_or(trimmed).trim_end_matches('/');
|
|
let bare = bare.strip_suffix(".git").unwrap_or(bare);
|
|
let mut parts = bare.split('/');
|
|
let (Some(owner), Some(repo), None) = (parts.next(), parts.next(), parts.next()) else { return None };
|
|
let ok = |s: &str| {
|
|
!s.is_empty()
|
|
&& !s.starts_with('.')
|
|
&& s.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
|
|
};
|
|
(ok(owner) && ok(repo)).then(|| format!("{owner}/{repo}"))
|
|
}
|
|
|
|
fn parse_marketplace_json_remote(
|
|
text: &str,
|
|
owner: &str,
|
|
repo: &str,
|
|
git_ref: &str,
|
|
base_subpath: Option<&str>,
|
|
user_home: Option<&Path>,
|
|
workspace_root: Option<&Path>,
|
|
) -> IdeResult<(String, Vec<AgentMarketplaceCandidate>)> {
|
|
let val = parse_jsonc(text).map_err(|e| IdeError::invalid(format!("Invalid marketplace.json: {e}")))?;
|
|
let mkt_name =
|
|
val.get("name").and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()).unwrap_or(repo).to_owned();
|
|
let Some(plugin_root_prefix) =
|
|
safe_marketplace_subpath(val.pointer("/metadata/pluginRoot").and_then(Value::as_str).unwrap_or_default())
|
|
else {
|
|
return Err(IdeError::invalid("Marketplace metadata.pluginRoot must stay inside the repository"));
|
|
};
|
|
let Some(arr) = val.get("plugins").and_then(Value::as_array) else {
|
|
return Ok((mkt_name, Vec::new()));
|
|
};
|
|
|
|
let mut out = Vec::new();
|
|
for item in arr {
|
|
let Some(raw_name) = item.get("name").and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()) else {
|
|
continue;
|
|
};
|
|
let name = sanitize_plugin_slug(raw_name);
|
|
let display_name = item
|
|
.get("displayName")
|
|
.or_else(|| item.pointer("/interface/displayName"))
|
|
.and_then(Value::as_str)
|
|
.unwrap_or(raw_name)
|
|
.to_owned();
|
|
let description = item.get("description").and_then(Value::as_str).unwrap_or_default().trim().to_owned();
|
|
let version = item.get("version").and_then(Value::as_str).map(str::to_owned);
|
|
let author = extract_author(item);
|
|
let keywords = extract_string_array(item.get("keywords"));
|
|
|
|
let (source_spec, subpath) = match item.get("source") {
|
|
Some(Value::String(rel)) => {
|
|
let Some(clean) = safe_marketplace_subpath(rel) else { continue };
|
|
let mut parts: Vec<&str> = Vec::new();
|
|
if let Some(b) = base_subpath.filter(|s| !s.is_empty()) {
|
|
parts.push(b);
|
|
}
|
|
if !plugin_root_prefix.is_empty() {
|
|
parts.push(plugin_root_prefix);
|
|
}
|
|
if !clean.is_empty() && clean != "." {
|
|
parts.push(clean);
|
|
}
|
|
let joined = parts.join("/");
|
|
let spec = if joined.is_empty() {
|
|
format!("{owner}/{repo}#{git_ref}")
|
|
} else {
|
|
format!("{owner}/{repo}/{joined}#{git_ref}")
|
|
};
|
|
(spec, joined)
|
|
}
|
|
Some(Value::Object(obj)) => match obj.get("source").and_then(Value::as_str).unwrap_or_default() {
|
|
"local" => {
|
|
let Some(clean) =
|
|
safe_marketplace_subpath(obj.get("path").and_then(Value::as_str).unwrap_or_default())
|
|
else {
|
|
continue;
|
|
};
|
|
let mut parts: Vec<&str> = Vec::new();
|
|
if let Some(b) = base_subpath.filter(|s| !s.is_empty()) {
|
|
parts.push(b);
|
|
}
|
|
if !plugin_root_prefix.is_empty() {
|
|
parts.push(plugin_root_prefix);
|
|
}
|
|
if !clean.is_empty() && clean != "." {
|
|
parts.push(clean);
|
|
}
|
|
let joined = parts.join("/");
|
|
let spec = if joined.is_empty() {
|
|
format!("{owner}/{repo}#{git_ref}")
|
|
} else {
|
|
format!("{owner}/{repo}/{joined}#{git_ref}")
|
|
};
|
|
(spec, joined)
|
|
}
|
|
"github" => {
|
|
let Some(ext_repo) = obj.get("repo").and_then(Value::as_str).and_then(safe_marketplace_repo) else {
|
|
continue;
|
|
};
|
|
let r = obj.get("ref").or_else(|| obj.get("sha")).and_then(Value::as_str);
|
|
let Ok(r) = r.map(|r| safe_marketplace_ref(r).ok_or(())).transpose() else { continue };
|
|
let spec = match r {
|
|
Some(gr) => format!("{ext_repo}#{gr}"),
|
|
None => ext_repo.to_owned(),
|
|
};
|
|
(spec, String::new())
|
|
}
|
|
"git-subdir" => {
|
|
let Some(ext_repo) = obj
|
|
.get("repo")
|
|
.or_else(|| obj.get("url"))
|
|
.and_then(Value::as_str)
|
|
.and_then(safe_marketplace_repo)
|
|
else {
|
|
continue;
|
|
};
|
|
let Some(sub) =
|
|
safe_marketplace_subpath(obj.get("path").and_then(Value::as_str).unwrap_or_default())
|
|
else {
|
|
continue;
|
|
};
|
|
let sub = sub.to_owned();
|
|
let r = obj.get("ref").or_else(|| obj.get("sha")).and_then(Value::as_str);
|
|
let Ok(r) = r.map(|r| safe_marketplace_ref(r).ok_or(())).transpose() else { continue };
|
|
let spec = match r {
|
|
Some(gr) => format!("{ext_repo}#{gr}"),
|
|
None => ext_repo.to_owned(),
|
|
};
|
|
(spec, sub)
|
|
}
|
|
_ => continue,
|
|
},
|
|
_ => continue,
|
|
};
|
|
|
|
let (already_user, already_ws) = plugin_installed_anywhere(&name, Some(&mkt_name), user_home, workspace_root);
|
|
out.push(AgentMarketplaceCandidate {
|
|
name,
|
|
display_name,
|
|
version,
|
|
description,
|
|
author,
|
|
marketplace: Some(mkt_name.clone()),
|
|
source_spec,
|
|
subpath,
|
|
keywords,
|
|
already_installed_user: already_user,
|
|
already_installed_workspace: already_ws,
|
|
});
|
|
}
|
|
|
|
Ok((mkt_name, out))
|
|
}
|
|
|
|
const INSTALL_SOURCES: [AgentPluginSource; 4] = [
|
|
AgentPluginSource::ClaudeUser,
|
|
AgentPluginSource::CopilotUser,
|
|
AgentPluginSource::CodexUser,
|
|
AgentPluginSource::GeminiUser,
|
|
];
|
|
|
|
/// Whether `source` records `name` (from `marketplace`) for the user and for `workspace_root`.
|
|
fn plugin_installed_in(
|
|
source: AgentPluginSource,
|
|
name: &str,
|
|
marketplace: Option<&str>,
|
|
user_home: Option<&Path>,
|
|
workspace_root: Option<&Path>,
|
|
) -> (bool, bool) {
|
|
let marketplace = marketplace.map(str::trim).filter(|m| !m.is_empty() && *m != "_direct");
|
|
let key = marketplace.map(|m| format!("{name}@{m}"));
|
|
match source {
|
|
AgentPluginSource::ClaudeUser => {
|
|
let (Some(home), Some(key)) = (user_home, key) else { return (false, false) };
|
|
let records = read_json_object(&home.join(".claude/plugins/installed_plugins.json"))
|
|
.ok()
|
|
.and_then(|root| root.get("plugins").and_then(|p| p.get(&key)).and_then(Value::as_array).cloned())
|
|
.unwrap_or_default();
|
|
let user = records.iter().any(|r| r.get("scope").and_then(Value::as_str) == Some("user"));
|
|
let workspace = workspace_root.is_some_and(|ws| {
|
|
let ws = dunce::canonicalize(ws).unwrap_or_else(|_| ws.to_path_buf());
|
|
records.iter().any(|r| {
|
|
r.get("scope").and_then(Value::as_str) == Some("project")
|
|
&& r.get("projectPath")
|
|
.and_then(Value::as_str)
|
|
.is_some_and(|p| dunce::canonicalize(p).unwrap_or_else(|_| PathBuf::from(p)) == ws)
|
|
})
|
|
});
|
|
(user, workspace)
|
|
}
|
|
AgentPluginSource::CopilotUser => {
|
|
let user = user_home.is_some_and(|home| {
|
|
let records = read_json_object(&home.join(".copilot/config.json"))
|
|
.ok()
|
|
.and_then(|root| root.get("installedPlugins").and_then(Value::as_array).cloned())
|
|
.unwrap_or_default();
|
|
records.iter().any(|r| {
|
|
r.get("name").and_then(Value::as_str) == Some(name)
|
|
&& r.get("marketplace").and_then(Value::as_str).unwrap_or_default() == marketplace.unwrap_or("")
|
|
}) || key
|
|
.as_ref()
|
|
.is_some_and(|k| json_plugin_enabled_map(&home.join(".copilot/settings.json")).contains_key(k))
|
|
});
|
|
let workspace = workspace_root.zip(key.as_ref()).is_some_and(|(ws, k)| {
|
|
json_plugin_enabled_map(&ws.join(".github/copilot/settings.json")).contains_key(k)
|
|
});
|
|
(user, workspace)
|
|
}
|
|
AgentPluginSource::CodexUser => {
|
|
let Some(key) = key else { return (false, false) };
|
|
let user =
|
|
user_home.is_some_and(|h| read_codex_plugin_states(&h.join(".codex/config.toml")).contains_key(&key));
|
|
let workspace = workspace_root
|
|
.is_some_and(|w| read_codex_plugin_states(&w.join(".codex/config.toml")).contains_key(&key));
|
|
(user, workspace)
|
|
}
|
|
AgentPluginSource::GeminiUser => {
|
|
let Some(home) = user_home else { return (false, false) };
|
|
let installed = home.join(".gemini/extensions").join(name).is_dir();
|
|
let workspace = installed
|
|
&& workspace_root.is_some_and(|ws| {
|
|
gemini_workspace_owns_rule(&home.join(".gemini/extensions/extension-enablement.json"), name, ws)
|
|
});
|
|
(installed, workspace)
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Whether any harness records `name` from `marketplace` (marketplace browse badges).
|
|
fn plugin_installed_anywhere(
|
|
name: &str,
|
|
marketplace: Option<&str>,
|
|
user_home: Option<&Path>,
|
|
workspace_root: Option<&Path>,
|
|
) -> (bool, bool) {
|
|
INSTALL_SOURCES.iter().fold((false, false), |(user, ws), source| {
|
|
let (u, w) = plugin_installed_in(*source, name, marketplace, user_home, workspace_root);
|
|
(user || u, ws || w)
|
|
})
|
|
}
|
|
|
|
fn harness_manifest_hint(source: AgentPluginSource) -> &'static str {
|
|
match source {
|
|
AgentPluginSource::ClaudeUser => "Claude Code reads `.claude-plugin/plugin.json`",
|
|
AgentPluginSource::CopilotUser => {
|
|
"Copilot reads `plugin.json`, `.plugin/plugin.json`, `.github/plugin/plugin.json`, or `.claude-plugin/plugin.json`"
|
|
}
|
|
AgentPluginSource::CodexUser => {
|
|
"Codex reads `.codex-plugin/plugin.json`, `.claude-plugin/plugin.json`, or an Agent Plugins `plugin.json`"
|
|
}
|
|
AgentPluginSource::GeminiUser => "Gemini CLI reads `gemini-extension.json`",
|
|
}
|
|
}
|
|
|
|
/// Why `source` cannot install this plugin, if it cannot.
|
|
fn plugin_install_blocker(
|
|
source: AgentPluginSource,
|
|
formats: &[AgentPluginFormat],
|
|
marketplace: Option<&str>,
|
|
marketplace_source: Option<&str>,
|
|
user_home: Option<&Path>,
|
|
) -> Option<String> {
|
|
if !supports_harness(formats, source_slug(source)) {
|
|
return Some(harness_manifest_hint(source).to_owned());
|
|
}
|
|
let marketplace = marketplace.map(str::trim).filter(|m| !m.is_empty());
|
|
match source {
|
|
AgentPluginSource::ClaudeUser if marketplace.is_none() => {
|
|
Some("Claude Code installs plugins only from a named marketplace".to_owned())
|
|
}
|
|
AgentPluginSource::CodexUser => match marketplace {
|
|
None => Some("Codex installs plugins only from a named marketplace".to_owned()),
|
|
Some(m) => codex_marketplace_registration(user_home, m, marketplace_source).err(),
|
|
},
|
|
_ => None,
|
|
}
|
|
}
|
|
|
|
/// Per-harness install eligibility and existing installs for a previewed plugin.
|
|
#[allow(clippy::too_many_arguments)]
|
|
fn plugin_install_targets(
|
|
name: &str,
|
|
version: Option<&str>,
|
|
tree_sha: Option<&str>,
|
|
formats: &[AgentPluginFormat],
|
|
marketplace: Option<&str>,
|
|
marketplace_source: Option<&str>,
|
|
user_home: Option<&Path>,
|
|
workspace_root: Option<&Path>,
|
|
) -> Vec<AgentPluginInstallTarget> {
|
|
INSTALL_SOURCES
|
|
.iter()
|
|
.map(|&source| {
|
|
let reason = plugin_install_blocker(source, formats, marketplace, marketplace_source, user_home);
|
|
let (installed_user, installed_workspace) =
|
|
plugin_installed_in(source, name, marketplace, user_home, workspace_root);
|
|
let workspace_supported =
|
|
source != AgentPluginSource::CopilotUser || marketplace.is_some_and(|m| !m.trim().is_empty());
|
|
let source_kind =
|
|
if marketplace_source.is_some_and(|path| Path::new(path).is_absolute()) { "local" } else { "github" };
|
|
let overwrite_required = !copilot_installs_live(source, source_kind, marketplace, marketplace_source)
|
|
&& native_install_dir(source, name, version, tree_sha, user_home, marketplace)
|
|
.is_some_and(|dir| std::fs::symlink_metadata(dir).is_ok());
|
|
AgentPluginInstallTarget {
|
|
harness: source_slug(source).to_owned(),
|
|
supported: reason.is_none(),
|
|
reason,
|
|
workspace_supported,
|
|
installed_user,
|
|
installed_workspace,
|
|
overwrite_required,
|
|
}
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
/// Folder an install of `name` would occupy in `source`'s user store.
|
|
fn native_install_dir(
|
|
source: AgentPluginSource,
|
|
name: &str,
|
|
version: Option<&str>,
|
|
tree_sha: Option<&str>,
|
|
user_home: Option<&Path>,
|
|
marketplace: Option<&str>,
|
|
) -> Option<PathBuf> {
|
|
let container = native_plugin_dir(source, user_home, marketplace).ok()?;
|
|
let slug = store_segment(name, "plugin").ok()?;
|
|
Some(match source {
|
|
AgentPluginSource::ClaudeUser | AgentPluginSource::CodexUser => {
|
|
container.join(&slug).join(native_plugin_install_version(source, version, tree_sha))
|
|
}
|
|
AgentPluginSource::CopilotUser | AgentPluginSource::GeminiUser => container.join(slug),
|
|
})
|
|
}
|
|
|
|
fn read_codex_marketplaces(config: &Path) -> BTreeSet<String> {
|
|
std::fs::read_to_string(config)
|
|
.ok()
|
|
.and_then(|text| text.parse::<toml_edit::DocumentMut>().ok())
|
|
.and_then(|doc| {
|
|
doc.get("marketplaces")
|
|
.and_then(|m| m.as_table_like())
|
|
.map(|t| t.iter().map(|(k, _)| k.to_owned()).collect())
|
|
})
|
|
.unwrap_or_default()
|
|
}
|
|
|
|
/// A local Codex marketplace root (`.agents/plugins/marketplace.json` or
|
|
/// `.claude-plugin/marketplace.json`, the manifests `codex plugin marketplace add` accepts) and its manifest.
|
|
fn codex_local_marketplace_root(source: &Path) -> Option<(PathBuf, PathBuf)> {
|
|
let root = if source.is_file() {
|
|
let parent = source.parent()?;
|
|
if parent.ends_with(".agents/plugins") {
|
|
parent.parent()?.parent()?.to_path_buf()
|
|
} else if parent.ends_with(".claude-plugin") {
|
|
parent.parent()?.to_path_buf()
|
|
} else {
|
|
return None;
|
|
}
|
|
} else {
|
|
source.to_path_buf()
|
|
};
|
|
[".agents/plugins/marketplace.json", ".claude-plugin/marketplace.json"]
|
|
.iter()
|
|
.map(|rel| root.join(rel))
|
|
.find(|manifest| manifest.is_file())
|
|
.map(|manifest| (root, manifest))
|
|
}
|
|
|
|
/// How Codex finds `marketplace`: already in `~/.codex/config.toml` (`Ok(None)`), or a local
|
|
/// marketplace root to register the way `codex plugin marketplace add <path>` does (`Ok(Some(root))`).
|
|
fn codex_marketplace_registration(
|
|
user_home: Option<&Path>,
|
|
marketplace: &str,
|
|
marketplace_source: Option<&str>,
|
|
) -> Result<Option<PathBuf>, String> {
|
|
let home = user_home.ok_or_else(|| "Cannot locate user home directory".to_owned())?;
|
|
if read_codex_marketplaces(&home.join(".codex/config.toml")).contains(marketplace) {
|
|
return Ok(None);
|
|
}
|
|
let local = marketplace_source
|
|
.map(PathBuf::from)
|
|
.filter(|path| path.is_absolute())
|
|
.and_then(|path| codex_local_marketplace_root(&path));
|
|
match local {
|
|
Some((root, manifest)) if read_marketplace_name(&manifest).as_deref() == Some(marketplace) => Ok(Some(root)),
|
|
_ => Err(format!(
|
|
"Codex installs only from marketplaces it knows; add `{marketplace}` with `codex plugin marketplace add` first"
|
|
)),
|
|
}
|
|
}
|
|
|
|
/// Registers a local marketplace in `~/.codex/config.toml` exactly as `codex plugin marketplace add <path>` does.
|
|
fn register_codex_local_marketplace(home: &Path, marketplace: &str, root: &Path) -> IdeResult<()> {
|
|
let path = home.join(".codex/config.toml");
|
|
let text = match std::fs::read_to_string(&path) {
|
|
Ok(text) => text,
|
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
|
|
Err(e) => return Err(e.into()),
|
|
};
|
|
let mut document = text
|
|
.parse::<toml_edit::DocumentMut>()
|
|
.map_err(|e| IdeError::invalid(format!("Invalid {}: {e}", path.display())))?;
|
|
let leading = take_comment_only_trivia(&mut document);
|
|
let marketplaces = document
|
|
.entry("marketplaces")
|
|
.or_insert_with(|| {
|
|
let mut table = toml_edit::Table::new();
|
|
table.set_implicit(true);
|
|
toml_edit::Item::Table(table)
|
|
})
|
|
.as_table_mut()
|
|
.ok_or_else(|| IdeError::invalid(format!("{} [marketplaces] is not a table", path.display())))?;
|
|
if marketplaces.contains_key(marketplace) {
|
|
return Ok(());
|
|
}
|
|
let mut entry = toml_edit::Table::new();
|
|
entry["source_type"] = toml_edit::value("local");
|
|
entry["source"] = toml_edit::value(root.to_string_lossy().as_ref());
|
|
marketplaces.insert(marketplace, toml_edit::Item::Table(entry));
|
|
write_native_text(&path, &format!("{leading}{document}"))
|
|
}
|
|
|
|
/// A TOML file holding only comments parses them as trailing trivia, which `toml_edit` would
|
|
/// print after newly added tables; take it so it can stay at the top.
|
|
fn take_comment_only_trivia(document: &mut toml_edit::DocumentMut) -> String {
|
|
if !document.as_table().is_empty() {
|
|
return String::new();
|
|
}
|
|
let trailing = document.trailing().as_str().unwrap_or_default().to_owned();
|
|
document.set_trailing("");
|
|
trailing
|
|
}
|
|
|
|
fn json_plugin_enabled_map(path: &Path) -> BTreeMap<String, bool> {
|
|
std::fs::read_to_string(path)
|
|
.ok()
|
|
.and_then(|text| parse_jsonc(&text).ok())
|
|
.and_then(|value| value.get("enabledPlugins").and_then(Value::as_object).cloned())
|
|
.into_iter()
|
|
.flatten()
|
|
.filter_map(|(key, value)| value.as_bool().map(|enabled| (key, enabled)))
|
|
.collect()
|
|
}
|
|
|
|
fn read_marketplace_name(path: &Path) -> Option<String> {
|
|
let text = std::fs::read_to_string(path).ok()?;
|
|
let val = parse_jsonc(&text).ok()?;
|
|
val.get("name").and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned)
|
|
}
|
|
|
|
fn marketplace_label_from_source(source: &str) -> String {
|
|
let clean = source.split('#').next().unwrap_or(source).trim_end_matches('/').trim_end_matches(".json");
|
|
clean.rsplit('/').next().filter(|s| !s.is_empty()).unwrap_or(source).to_owned()
|
|
}
|
|
|
|
/// Resolves a local plugin/marketplace path: absolute, `~/…`, or `./`/`../` relative to the
|
|
/// project. Bare relative text (e.g. `owner/repo`) is never treated as a local path, and nothing
|
|
/// resolves against the IDE process's working directory.
|
|
fn resolve_local_source(raw: &str, home: Option<&Path>, workspace_root: Option<&Path>) -> Option<PathBuf> {
|
|
if let Some(rest) = raw.strip_prefix("~/").or_else(|| raw.strip_prefix("~\\")) {
|
|
return home.map(|h| h.join(rest));
|
|
}
|
|
let path = Path::new(raw);
|
|
if path.is_absolute() {
|
|
return Some(path.to_path_buf());
|
|
}
|
|
let explicit_relative = ["./", "../", ".\\", "..\\"].iter().any(|prefix| raw.starts_with(prefix));
|
|
if explicit_relative { workspace_root.map(|root| root.join(raw)) } else { None }
|
|
}
|
|
|
|
fn contained_join(root: &Path, raw: &str) -> IdeResult<PathBuf> {
|
|
let rel = Path::new(raw.trim());
|
|
if rel.as_os_str().is_empty() || !rel.components().all(|c| matches!(c, Component::Normal(_))) {
|
|
return Err(IdeError::invalid("Plugin subpath must stay inside the local root"));
|
|
}
|
|
Ok(root.join(rel))
|
|
}
|
|
|
|
fn local_marketplace_source(start: &Path, marketplace: &str) -> Option<PathBuf> {
|
|
let start = dunce::canonicalize(start).ok()?;
|
|
if start.is_file() {
|
|
return read_marketplace_name(&start).filter(|name| name == marketplace).map(|_| start);
|
|
}
|
|
start.ancestors().find_map(|dir| {
|
|
MARKETPLACE_MANIFEST_PATHS
|
|
.iter()
|
|
.map(|relative| dir.join(relative))
|
|
.find(|path| path.is_file() && read_marketplace_name(path).as_deref() == Some(marketplace))
|
|
.map(|_| dir.to_path_buf())
|
|
})
|
|
}
|
|
|
|
fn plugin_base_id(name: &str, marketplace: Option<&str>) -> String {
|
|
match marketplace.map(str::trim).filter(|m| !m.is_empty()) {
|
|
Some(m) => format!("{}@{m}", sanitize_plugin_slug(name)),
|
|
None => sanitize_plugin_slug(name),
|
|
}
|
|
}
|
|
|
|
/// A row's id: harness, scope, `name@marketplace`, and a digest of the installed folder and the
|
|
/// owning workspace, so ids never depend on discovery order and a stale id cannot reach another
|
|
/// owner's row.
|
|
fn stable_plugin_id(plugin: &AgentPlugin) -> String {
|
|
let mut hasher = blake3::Hasher::new();
|
|
hasher.update(plugin.root_path.0.to_string_lossy().as_bytes());
|
|
hasher.update(b"\0");
|
|
if let Some(root) = &plugin.workspace_root {
|
|
hasher.update(root.0.to_string_lossy().as_bytes());
|
|
}
|
|
let scope = match plugin.scope {
|
|
McpScope::User => "user",
|
|
McpScope::Workspace => "workspace",
|
|
};
|
|
format!(
|
|
"{}:{scope}:{}#{}",
|
|
source_slug(plugin.source),
|
|
plugin_base_id(&plugin.name, plugin.marketplace.as_deref()),
|
|
&hasher.finalize().to_hex()[..10]
|
|
)
|
|
}
|
|
|
|
/// Stable `agents.plugins.entries` key (`<harness>:<plugin>@<marketplace>`). Unlike
|
|
/// [`AgentPlugin::id`], it does not depend on discovery order or on which other plugins exist.
|
|
pub fn plugin_policy_key(plugin: &AgentPlugin) -> String {
|
|
format!("{}:{}", source_slug(plugin.source), plugin_base_id(&plugin.name, plugin.marketplace.as_deref()))
|
|
}
|
|
|
|
pub fn sanitize_plugin_slug(raw: &str) -> String {
|
|
let mut out = String::new();
|
|
for ch in raw.chars() {
|
|
if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' || ch == '.' {
|
|
out.push(ch.to_ascii_lowercase());
|
|
} else if !out.ends_with('-') {
|
|
out.push('-');
|
|
}
|
|
if out.len() >= 64 {
|
|
break;
|
|
}
|
|
}
|
|
let trimmed = out.trim_matches(['-', '.']);
|
|
if trimmed.is_empty() { "plugin".into() } else { trimmed.to_owned() }
|
|
}
|
|
|
|
fn parse_jsonc(raw: &str) -> Result<Value, serde_json::Error> {
|
|
serde_json::from_str(&ide_core::jsonc::strip(raw))
|
|
}
|
|
|
|
fn extract_author(val: &Value) -> Option<String> {
|
|
if let Some(s) = val.get("author").and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()) {
|
|
return Some(s.to_owned());
|
|
}
|
|
val.pointer("/author/name")
|
|
.or_else(|| val.pointer("/owner/name"))
|
|
.and_then(Value::as_str)
|
|
.map(str::trim)
|
|
.filter(|s| !s.is_empty())
|
|
.map(str::to_owned)
|
|
}
|
|
|
|
fn extract_repo_url(val: &Value) -> Option<String> {
|
|
if let Some(s) = val.get("repository").and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()) {
|
|
return Some(s.to_owned());
|
|
}
|
|
val.pointer("/repository/url").and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned)
|
|
}
|
|
|
|
fn extract_string_array(v: Option<&Value>) -> Vec<String> {
|
|
v.and_then(Value::as_array)
|
|
.into_iter()
|
|
.flatten()
|
|
.filter_map(|x| x.as_str().map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned))
|
|
.collect()
|
|
}
|
|
|
|
fn resolve_file_within(base_dir: &Path, candidate: &str) -> Option<PathBuf> {
|
|
let clean = candidate.trim().trim_start_matches("./").trim_start_matches('/');
|
|
if clean.is_empty() {
|
|
return None;
|
|
}
|
|
let rel = Path::new(clean);
|
|
if !rel.components().all(|c| matches!(c, Component::Normal(_))) {
|
|
return None;
|
|
}
|
|
let joined = base_dir.join(rel);
|
|
let base_canon = dunce::canonicalize(base_dir).ok()?;
|
|
let target_canon = dunce::canonicalize(&joined).ok()?;
|
|
(target_canon.starts_with(&base_canon) && target_canon.is_file()).then_some(joined)
|
|
}
|
|
|
|
fn resolve_dir_within(base_dir: &Path, candidate: &str) -> Option<PathBuf> {
|
|
let clean = candidate.trim().trim_start_matches("./").trim_matches('/');
|
|
if clean.is_empty() || clean == "." {
|
|
return Some(base_dir.to_path_buf());
|
|
}
|
|
let rel = Path::new(clean);
|
|
if !rel.components().all(|c| matches!(c, Component::Normal(_))) {
|
|
return None;
|
|
}
|
|
let joined = base_dir.join(rel);
|
|
let base_canon = dunce::canonicalize(base_dir).ok()?;
|
|
let target_canon = dunce::canonicalize(&joined).ok()?;
|
|
(target_canon.starts_with(&base_canon) && target_canon.is_dir()).then_some(joined)
|
|
}
|
|
|
|
fn sorted_dirs(parent: &Path) -> Vec<PathBuf> {
|
|
let Ok(rd) = std::fs::read_dir(parent) else { return Vec::new() };
|
|
let mut dirs: Vec<PathBuf> = rd.filter_map(Result::ok).map(|e| e.path()).filter(|p| p.is_dir()).collect();
|
|
dirs.sort();
|
|
dirs
|
|
}
|
|
|
|
fn sorted_files_with_exts(dir: &Path, exts: &[&str]) -> Vec<PathBuf> {
|
|
let Ok(rd) = std::fs::read_dir(dir) else { return Vec::new() };
|
|
let mut files: Vec<PathBuf> = rd
|
|
.filter_map(Result::ok)
|
|
.map(|e| e.path())
|
|
.filter(|p| {
|
|
p.is_file()
|
|
&& p.extension()
|
|
.and_then(|e| e.to_str())
|
|
.is_some_and(|ext| exts.iter().any(|x| ext.eq_ignore_ascii_case(x)))
|
|
})
|
|
.collect();
|
|
files.sort();
|
|
files
|
|
}
|
|
|
|
fn count_files_with_exts(dir: &Path, exts: &[&str]) -> u32 {
|
|
sorted_files_with_exts(dir, exts).len() as u32
|
|
}
|
|
|
|
fn is_rule_rel_path(rel: &str) -> bool {
|
|
let is_rule_dir = rel.starts_with("rules/") || rel.starts_with("com.github.copilot/rules/");
|
|
let is_ext = rel.ends_with(".md") || rel.ends_with(".mdc") || rel.ends_with(".markdown");
|
|
(is_rule_dir && is_ext) || rel.eq_ignore_ascii_case("GEMINI.md")
|
|
}
|
|
|
|
fn is_subagent_rel_path(rel: &str) -> bool {
|
|
(rel.starts_with("agents/") || rel.starts_with("com.github.copilot/agents/")) && rel.ends_with(".md")
|
|
}
|
|
|
|
fn is_command_rel_path(rel: &str) -> bool {
|
|
(rel.starts_with("commands/") || rel.starts_with("com.github.copilot/commands/"))
|
|
&& (rel.ends_with(".md") || rel.ends_with(".toml") || rel.ends_with(".txt"))
|
|
}
|
|
|
|
fn estimate_skill_header_tokens(markdown: &str) -> u32 {
|
|
// Agents see a skill's frontmatter name + description in the system prompt (~60-200 tokens per skill).
|
|
let header_chars = markdown.chars().take(600).count() as u32;
|
|
(header_chars.saturating_add(3) / 4).max(32)
|
|
}
|
|
|
|
fn extract_frontmatter_globs(markdown: &str) -> Vec<String> {
|
|
let text = markdown.strip_prefix('\u{feff}').unwrap_or(markdown);
|
|
let Some(after) = text.strip_prefix("---\n").or_else(|| text.strip_prefix("---\r\n")) else {
|
|
return Vec::new();
|
|
};
|
|
let mut out = Vec::new();
|
|
let mut in_list = false;
|
|
for raw_line in after.lines() {
|
|
let line = raw_line.trim_end_matches('\r');
|
|
if matches!(line.trim(), "---" | "...") {
|
|
break;
|
|
}
|
|
if in_list {
|
|
let trimmed = line.trim();
|
|
if let Some(item) = trimmed.strip_prefix('-').map(str::trim) {
|
|
let clean = item.trim_matches(['"', '\'']).trim();
|
|
if !clean.is_empty() {
|
|
out.push(clean.to_owned());
|
|
}
|
|
continue;
|
|
} else if !trimmed.is_empty() && !line.starts_with([' ', '\t']) {
|
|
in_list = false;
|
|
}
|
|
}
|
|
if let Some((k, v)) = line.split_once(':') {
|
|
let key = k.trim().to_ascii_lowercase();
|
|
if matches!(key.as_str(), "paths" | "applyto" | "globs") {
|
|
let val = v.trim();
|
|
if val.is_empty() {
|
|
in_list = true;
|
|
} else {
|
|
let clean = val.trim_matches(['[', ']', '"', '\'']);
|
|
for part in clean.split(',') {
|
|
let p = part.trim().trim_matches(['"', '\'']).trim();
|
|
if !p.is_empty() {
|
|
out.push(p.to_owned());
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
fn first_body_summary(markdown: &str) -> Option<String> {
|
|
let text = markdown.strip_prefix('\u{feff}').unwrap_or(markdown);
|
|
let body = if let Some(after) = text.strip_prefix("---\n").or_else(|| text.strip_prefix("---\r\n")) {
|
|
after.split_once("\n---\n").or_else(|| after.split_once("\r\n---\r\n")).map(|(_, b)| b).unwrap_or(after)
|
|
} else {
|
|
text
|
|
};
|
|
for line in body.lines() {
|
|
let trimmed = line.trim().trim_start_matches('#').trim();
|
|
if !trimmed.is_empty() && !trimmed.starts_with("![") && !trimmed.starts_with("```") {
|
|
let capped: String = trimmed.chars().take(160).collect();
|
|
return Some(capped);
|
|
}
|
|
}
|
|
None
|
|
}
|
|
|
|
fn monorepo_plugin_subdirs(root: &Path, max_depth: usize) -> Vec<PathBuf> {
|
|
if max_depth == 0 {
|
|
return Vec::new();
|
|
}
|
|
let mut out = Vec::new();
|
|
for dir in sorted_dirs(root) {
|
|
let Some(name) = dir.file_name().and_then(|s| s.to_str()) else { continue };
|
|
if SKIP_DIRS.contains(&name) || name == ".openidea" {
|
|
continue;
|
|
}
|
|
if [".claude/plugins", ".github/plugins", ".codex/plugins", ".cursor/plugins", ".gemini/extensions"]
|
|
.iter()
|
|
.any(|rel| dir.join(rel).is_dir())
|
|
{
|
|
out.push(dir.clone());
|
|
}
|
|
if max_depth > 1 {
|
|
out.extend(monorepo_plugin_subdirs(&dir, max_depth - 1));
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use crate::skill_installer::{GitTree, GitTreeEntry};
|
|
use parking_lot::Mutex;
|
|
|
|
fn write(path: &Path, text: &str) {
|
|
if let Some(parent) = path.parent() {
|
|
std::fs::create_dir_all(parent).unwrap();
|
|
}
|
|
std::fs::write(path, text).unwrap();
|
|
}
|
|
|
|
#[derive(Default)]
|
|
struct MemSecrets(Mutex<BTreeMap<String, String>>);
|
|
|
|
impl EnvSecrets for MemSecrets {
|
|
fn get(&self, key: &str) -> Option<String> {
|
|
self.0.lock().get(key).cloned()
|
|
}
|
|
fn set(&self, key: &str, value: &str) -> IdeResult<()> {
|
|
self.0.lock().insert(key.to_owned(), value.to_owned());
|
|
Ok(())
|
|
}
|
|
fn delete(&self, key: &str) {
|
|
self.0.lock().remove(key);
|
|
}
|
|
fn keys(&self, prefix: &str) -> Vec<String> {
|
|
self.0.lock().keys().filter(|k| k.starts_with(prefix)).cloned().collect()
|
|
}
|
|
}
|
|
|
|
struct FakeGitHub {
|
|
branch: String,
|
|
trees: BTreeMap<String, GitTree>,
|
|
blobs: BTreeMap<String, Vec<u8>>,
|
|
commit_trees: BTreeMap<String, String>,
|
|
}
|
|
|
|
impl FakeGitHub {
|
|
fn new(files: &[(&str, &[u8], &str)], tree_sha: &str) -> Self {
|
|
let mut entries = Vec::new();
|
|
let mut blobs = BTreeMap::new();
|
|
for (path, bytes, mode) in files {
|
|
let mut h = blake3::Hasher::new();
|
|
h.update(bytes);
|
|
let sha = h.finalize().to_hex()[..40].to_string();
|
|
entries.push(GitTreeEntry {
|
|
path: (*path).to_owned(),
|
|
mode: (*mode).to_owned(),
|
|
kind: "blob".into(),
|
|
sha: sha.clone(),
|
|
size: Some(bytes.len() as u64),
|
|
});
|
|
blobs.insert(sha, bytes.to_vec());
|
|
}
|
|
let tree = GitTree { sha: tree_sha.to_owned(), truncated: false, tree: entries };
|
|
let mut trees = BTreeMap::new();
|
|
trees.insert("main".into(), tree.clone());
|
|
trees.insert(tree_sha.to_owned(), tree);
|
|
Self { branch: "main".into(), trees, blobs, commit_trees: BTreeMap::new() }
|
|
}
|
|
}
|
|
|
|
impl SkillSourceFetcher for FakeGitHub {
|
|
fn default_branch(&self, _owner: &str, _repo: &str, _cancel: &CancellationToken) -> IdeResult<String> {
|
|
Ok(self.branch.clone())
|
|
}
|
|
fn git_tree(&self, target: RepoRef<'_>, _cancel: &CancellationToken) -> IdeResult<GitTree> {
|
|
self.trees
|
|
.get(target.git_ref)
|
|
.cloned()
|
|
.ok_or_else(|| IdeError::not_found(format!("missing tree {}", target.git_ref)))
|
|
}
|
|
fn git_commit_sha(&self, target: RepoRef<'_>, _cancel: &CancellationToken) -> IdeResult<String> {
|
|
self.trees
|
|
.get(target.git_ref)
|
|
.map(|tree| tree.sha.clone())
|
|
.ok_or_else(|| IdeError::not_found(format!("missing tree {}", target.git_ref)))
|
|
}
|
|
fn git_commit_tree_sha(
|
|
&self,
|
|
_owner: &str,
|
|
_repo: &str,
|
|
commit_sha: &str,
|
|
_cancel: &CancellationToken,
|
|
) -> IdeResult<String> {
|
|
// Commits and their root trees share SHAs in this fake, unless a test rewired them.
|
|
if let Some(tree) = self.commit_trees.get(commit_sha) {
|
|
return Ok(tree.clone());
|
|
}
|
|
self.trees
|
|
.get(commit_sha)
|
|
.map(|tree| tree.sha.clone())
|
|
.ok_or_else(|| IdeError::not_found(format!("missing commit {commit_sha}")))
|
|
}
|
|
fn read_blob(
|
|
&self,
|
|
_target: RepoRef<'_>,
|
|
_repo_path: &str,
|
|
blob_sha: &str,
|
|
_max_bytes: u64,
|
|
_cancel: &CancellationToken,
|
|
) -> IdeResult<Vec<u8>> {
|
|
self.blobs.get(blob_sha).cloned().ok_or_else(|| IdeError::not_found("missing blob"))
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn discovers_native_fixtures_emitted_by_claude_copilot_codex_and_gemini_clis() {
|
|
let tmp = tempfile::tempdir().unwrap();
|
|
let home = tmp.path().join("home");
|
|
let workspace = tmp.path().join("workspace");
|
|
std::fs::create_dir_all(&workspace).unwrap();
|
|
let home_text = home.to_string_lossy().replace('\\', "/");
|
|
let workspace_text = workspace.to_string_lossy().replace('\\', "/");
|
|
let render = |fixture: &str| fixture.replace("$HOME", &home_text).replace("$WORKSPACE", &workspace_text);
|
|
// Gemini's `extensions enable/disable` stores rules with a leading slash (`/C:/...` on Windows).
|
|
let gemini_path = |text: &str| if text.starts_with('/') { text.to_owned() } else { format!("/{text}") };
|
|
let render_gemini = |fixture: &str| {
|
|
fixture.replace("$HOME", &gemini_path(&home_text)).replace("$WORKSPACE", &gemini_path(&workspace_text))
|
|
};
|
|
|
|
let claude_plugin = home.join(".claude/plugins/cache/evidence-mkt/evidence-plugin/1.2.3");
|
|
write(&claude_plugin.join(".claude-plugin/plugin.json"), r#"{"name":"evidence-plugin","version":"1.2.3"}"#);
|
|
write(&claude_plugin.join("skills/proof/SKILL.md"), "---\nname: proof\ndescription: Native evidence\n---\n");
|
|
write(
|
|
&home.join(".claude/plugins/installed_plugins.json"),
|
|
&render(include_str!("../tests/fixtures/plugins/native/claude-installed-plugins.json")),
|
|
);
|
|
write(&home.join(".claude/settings.json"), r#"{"enabledPlugins":{"evidence-plugin@evidence-mkt":true}}"#);
|
|
write(&workspace.join(".claude/settings.json"), r#"{"enabledPlugins":{"evidence-plugin@evidence-mkt":false}}"#);
|
|
|
|
let copilot_plugin = home.join(".copilot/installed-plugins/evidence-mkt/evidence-plugin");
|
|
write(&copilot_plugin.join(".plugin/plugin.json"), r#"{"name":"evidence-plugin","version":"1.2.3"}"#);
|
|
write(
|
|
&home.join(".copilot/config.json"),
|
|
&render(include_str!("../tests/fixtures/plugins/native/copilot-config.json")),
|
|
);
|
|
|
|
let codex_plugin = home.join(".codex/plugins/cache/evidence-mkt/evidence-plugin/1.2.3");
|
|
write(&codex_plugin.join(".codex-plugin/plugin.json"), r#"{"name":"evidence-plugin","version":"1.2.3"}"#);
|
|
write(
|
|
&home.join(".codex/config.toml"),
|
|
&render(include_str!("../tests/fixtures/plugins/native/codex-config.toml")),
|
|
);
|
|
|
|
let gemini_plugin = home.join(".gemini/extensions/evidence-extension");
|
|
write(&gemini_plugin.join("gemini-extension.json"), r#"{"name":"evidence-extension","version":"1.2.3"}"#);
|
|
write(
|
|
&home.join(".gemini/extensions/extension-enablement.json"),
|
|
&render_gemini(include_str!("../tests/fixtures/plugins/native/gemini-extension-enablement.json")),
|
|
);
|
|
|
|
let found = discover_plugins(std::slice::from_ref(&workspace), Some(&home));
|
|
assert!(found.iter().any(|plugin| {
|
|
plugin.source == AgentPluginSource::ClaudeUser
|
|
&& plugin.scope == McpScope::User
|
|
&& plugin.name == "evidence-plugin"
|
|
&& plugin.default_enabled
|
|
}));
|
|
assert!(found.iter().any(|plugin| {
|
|
plugin.source == AgentPluginSource::ClaudeUser
|
|
&& plugin.scope == McpScope::Workspace
|
|
&& plugin.name == "evidence-plugin"
|
|
&& !plugin.default_enabled
|
|
}));
|
|
assert!(found.iter().any(|plugin| {
|
|
plugin.source == AgentPluginSource::CopilotUser && plugin.scope == McpScope::User && plugin.default_enabled
|
|
}));
|
|
assert!(
|
|
found.iter().any(|plugin| { plugin.source == AgentPluginSource::CodexUser && !plugin.default_enabled })
|
|
);
|
|
assert!(found.iter().any(|plugin| {
|
|
plugin.source == AgentPluginSource::GeminiUser && plugin.scope == McpScope::User && plugin.default_enabled
|
|
}));
|
|
assert!(found.iter().any(|plugin| {
|
|
plugin.source == AgentPluginSource::GeminiUser
|
|
&& plugin.scope == McpScope::Workspace
|
|
&& !plugin.default_enabled
|
|
}));
|
|
}
|
|
|
|
#[test]
|
|
fn discovers_multi_manifest_bundles_across_all_harnesses_and_deduplicates_symlinks() {
|
|
let tmp = tempfile::tempdir().unwrap();
|
|
let ws = tmp.path().join("ws");
|
|
let home = tmp.path().join("home");
|
|
|
|
// 1. Multi-manifest bundle (`azure` style: `.plugin`, `.claude-plugin` in one folder)
|
|
let azure = home.join(".claude/plugins/cache/acme/azure/1.2.106");
|
|
write(
|
|
&azure.join(".plugin/plugin.json"),
|
|
r#"{"name":"azure","version":"1.2.106","description":"Azure bundle","skills":"./skills/","mcpServers":"./.mcp.json","hooks":"./hooks/copilot-hooks.json"}"#,
|
|
);
|
|
write(
|
|
&azure.join(".claude-plugin/plugin.json"),
|
|
r#"{"name":"azure","version":"1.2.106","skills":"./skills/","mcpServers":"./.mcp.json","hooks":"./hooks/claude-hooks.json","userConfig":{"subId":{"type":"string","title":"Subscription","default":"dev-sub"},"apiToken":{"type":"string","sensitive":true}}}"#,
|
|
);
|
|
write(
|
|
&azure.join("skills/azure-deploy/SKILL.md"),
|
|
"---\nname: azure-deploy\ndescription: Deploy to Azure\n---\n",
|
|
);
|
|
write(
|
|
&azure.join(".mcp.json"),
|
|
r#"{"mcpServers":{"azure-mcp":{"command":"npx","args":["-y","@azure/mcp","--root","${PLUGIN_ROOT}","--sub","${user_config.subId}"],"env":{"AZ_TOKEN":"${user_config.apiToken}"}}}}"#,
|
|
);
|
|
write(&azure.join("hooks/copilot-hooks.json"), r#"{"hooks":{}}"#);
|
|
write(&azure.join("hooks/claude-hooks.json"), r#"{"hooks":{}}"#);
|
|
|
|
// Copilot's registry and Claude's registry point to the same native bundle.
|
|
write(
|
|
&home.join(".copilot/config.json"),
|
|
&serde_json::to_string(&json!({
|
|
"installedPlugins": [{
|
|
"name": "azure",
|
|
"marketplace": "acme",
|
|
"enabled": true,
|
|
"version": "1.2.106",
|
|
"cache_path": azure.to_string_lossy()
|
|
}]
|
|
}))
|
|
.unwrap(),
|
|
);
|
|
write(
|
|
&home.join(".claude/plugins/installed_plugins.json"),
|
|
&serde_json::to_string(&json!({
|
|
"version": 2,
|
|
"plugins": {
|
|
"azure@acme": [{
|
|
"scope": "user",
|
|
"installPath": azure.to_string_lossy(),
|
|
"version": "1.2.106",
|
|
"installedAt": "2026-11-30T21:50:25.665Z",
|
|
"lastUpdated": "2026-11-30T21:50:25.665Z"
|
|
}]
|
|
}
|
|
}))
|
|
.unwrap(),
|
|
);
|
|
|
|
// 3. Workspace-scoped Claude plugin.
|
|
let perf = home.join(".claude/plugins/cache/acme/perf-kit/0.4.0");
|
|
write(
|
|
&perf.join("plugin.json"),
|
|
r#"{"$schema":"https://agent-plugins.org/schema/1.0.0/plugin.json","name":"perf-kit","version":"0.4.0","description":"Perf tools","extensions":{"com.openai":{"apps":"./.app.json"}}}"#,
|
|
);
|
|
write(&perf.join("skills/flamegraph/SKILL.md"), "---\nname: flamegraph\ndescription: Profile CPU\n---\n");
|
|
write(
|
|
&perf.join("rules/perf.mdc"),
|
|
"---\nglobs: crates/**/*.rs\n---\nAvoid unnecessary clones in hot loops.\n",
|
|
);
|
|
write(&perf.join(".app.json"), r#"{"apps":{}}"#);
|
|
write(
|
|
&home.join(".claude/plugins/installed_plugins.json"),
|
|
&serde_json::to_string(&json!({
|
|
"version": 2,
|
|
"plugins": {
|
|
"azure@acme": [{
|
|
"scope": "user",
|
|
"installPath": azure.to_string_lossy(),
|
|
"version": "1.2.106",
|
|
"installedAt": "2026-11-30T21:50:25.665Z",
|
|
"lastUpdated": "2026-11-30T21:50:25.665Z"
|
|
}],
|
|
"perf-kit@acme": [{
|
|
"installPath": perf.to_string_lossy(),
|
|
"scope": "project",
|
|
"projectPath": ws.to_string_lossy(),
|
|
"version": "0.4.0",
|
|
"installedAt": "2026-11-30T21:50:25.665Z",
|
|
"lastUpdated": "2026-11-30T21:50:25.665Z"
|
|
}]
|
|
}
|
|
}))
|
|
.unwrap(),
|
|
);
|
|
write(&ws.join(".claude/settings.json"), r#"{"enabledPlugins":{"perf-kit@acme":true}}"#);
|
|
|
|
// 4. Codex plugin disabled in `~/.codex/config.toml`
|
|
let codex_plug = home.join(".codex/plugins/cache/team-mkt/linear-sync/2.0.0");
|
|
write(&codex_plug.join(".codex-plugin/plugin.json"), r#"{"name":"linear-sync","version":"2.0.0"}"#);
|
|
write(
|
|
&codex_plug.join("skills/linear-triage/SKILL.md"),
|
|
"---\nname: linear-triage\ndescription: Triage\n---\n",
|
|
);
|
|
write(&home.join(".codex/config.toml"), "[plugins.\"linear-sync@team-mkt\"]\nenabled = false\n");
|
|
|
|
// 5. Gemini extension with `settings` and `GEMINI.md`
|
|
let gemini_ext = home.join(".gemini/extensions/gcloud-helper");
|
|
write(
|
|
&gemini_ext.join("gemini-extension.json"),
|
|
r#"{"name":"gcloud-helper","version":"1.1.0","settings":[{"name":"Project ID","envVar":"GCP_PROJECT","sensitive":false},{"name":"Default Region"}]}"#,
|
|
);
|
|
write(&gemini_ext.join("GEMINI.md"), "Always pass `--project` to gcloud commands.\n");
|
|
|
|
let found = discover_plugins(std::slice::from_ref(&ws), Some(&home));
|
|
|
|
let azure_rows: Vec<&AgentPlugin> = found.iter().filter(|p| p.name == "azure").collect();
|
|
assert_eq!(azure_rows.len(), 2, "one row per harness, even for the same canonical path");
|
|
assert!(azure_rows.iter().any(|p| p.source == AgentPluginSource::CopilotUser));
|
|
assert!(azure_rows.iter().any(|p| p.source == AgentPluginSource::ClaudeUser));
|
|
for az in azure_rows {
|
|
assert!(az.formats.contains(&AgentPluginFormat::Copilot));
|
|
assert!(az.formats.contains(&AgentPluginFormat::Claude));
|
|
assert_eq!(az.capabilities.skill_count, 1);
|
|
assert_eq!(az.capabilities.mcp_count, 1);
|
|
assert_eq!(az.capabilities.hook_files.len(), 2);
|
|
assert!(az.capabilities.requires_consent);
|
|
assert_eq!(az.config_fields.len(), 2);
|
|
}
|
|
|
|
let pk = found
|
|
.iter()
|
|
.find(|p| p.name == "perf-kit" && p.scope == McpScope::Workspace)
|
|
.expect("workspace perf-kit discovered");
|
|
assert_eq!(pk.scope, McpScope::Workspace);
|
|
assert_eq!(pk.formats, [AgentPluginFormat::AgentPluginsV1]);
|
|
assert_eq!(pk.capabilities.rule_count, 1);
|
|
assert!(pk.capabilities.has_canvas_or_app);
|
|
assert!(
|
|
!pk.capabilities.requires_consent,
|
|
"pure skills + rules + app map without stdio MCP or hooks needs no execution consent"
|
|
);
|
|
|
|
let lin = found.iter().find(|p| p.name == "linear-sync").expect("linear-sync discovered");
|
|
assert_eq!(lin.marketplace.as_deref(), Some("team-mkt"));
|
|
assert!(!lin.default_enabled, "reads disabled state from ~/.codex/config.toml");
|
|
|
|
let gem = found.iter().find(|p| p.name == "gcloud-helper").expect("gemini extension discovered");
|
|
assert_eq!(gem.formats, [AgentPluginFormat::GeminiExtension]);
|
|
assert_eq!(
|
|
gem.config_fields.iter().filter_map(|f| f.env_var.as_deref()).collect::<Vec<_>>(),
|
|
["GCP_PROJECT"],
|
|
"settings without a valid envVar are not exported"
|
|
);
|
|
assert_eq!(gem.capabilities.rule_count, 1);
|
|
}
|
|
|
|
#[test]
|
|
fn workspace_trust_and_native_plugin_projection_keep_secret_placeholders_out_of_openidea() {
|
|
let tmp = tempfile::tempdir().unwrap();
|
|
let ws = tmp.path().join("ws");
|
|
let home = tmp.path().join("home");
|
|
|
|
let ws_exec = home.join(".claude/plugins/cache/acme/db-guard/1.0.0");
|
|
write(
|
|
&ws_exec.join(".claude-plugin/plugin.json"),
|
|
r#"{"name":"db-guard","version":"1.0.0","userConfig":{"dbToken":{"type":"string","sensitive":true},"poolMax":{"type":"number","default":8}}}"#,
|
|
);
|
|
write(
|
|
&ws_exec.join(".mcp.json"),
|
|
r#"{"mcpServers":{"pg-guard":{"command":"node","args":["${CLAUDE_PLUGIN_ROOT}/srv.js","--max=${user_config.poolMax}"],"env":{"PG_TOKEN":"${user_config.dbToken}","DATA_DIR":"${PLUGIN_DATA}","WS":"${CLAUDE_PROJECT_DIR}"}}}}"#,
|
|
);
|
|
write(&ws_exec.join("hooks/hooks.json"), r#"{"hooks":{"PreToolUse":[]}}"#);
|
|
write(&ws_exec.join("skills/pg-check/SKILL.md"), "---\nname: pg-check\ndescription: Check migrations\n---\n");
|
|
write(&ws_exec.join("rules/sql.mdc"), "---\nglobs: db/**/*.sql\n---\nAlways use CONCURRENTLY on indexes.\n");
|
|
|
|
write(
|
|
&home.join(".claude/plugins/installed_plugins.json"),
|
|
&serde_json::to_string(&json!({
|
|
"version": 2,
|
|
"plugins": {
|
|
"db-guard@acme": [{
|
|
"installPath": ws_exec.to_string_lossy(),
|
|
"version": "1.0.0",
|
|
"scope": "project",
|
|
"projectPath": ws.to_string_lossy(),
|
|
"installedAt": "2026-11-30T21:50:25.665Z",
|
|
"lastUpdated": "2026-11-30T21:50:25.665Z"
|
|
}]
|
|
}
|
|
}))
|
|
.unwrap(),
|
|
);
|
|
write(&ws.join(".claude/settings.json"), r#"{"enabledPlugins":{"db-guard@acme":true,"user-lint":false}}"#);
|
|
let user_lint = home.join(".copilot/installed-plugins/_direct/user-lint");
|
|
write(&user_lint.join("plugin.json"), r#"{"name":"user-lint"}"#);
|
|
write(&user_lint.join("skills/lint-fast/SKILL.md"), "---\nname: lint-fast\ndescription: Fast lint\n---\n");
|
|
|
|
let secrets = MemSecrets::default();
|
|
|
|
let discovered = discover_plugins(std::slice::from_ref(&ws), Some(&home));
|
|
|
|
let untrusted =
|
|
PluginsPolicy { workspace_trusted: false, workspace_roots: vec![ws.clone()], ..Default::default() };
|
|
let states_untrusted = resolve_plugins(discovered.clone(), &untrusted, Some(&secrets));
|
|
let dg_untrusted = states_untrusted
|
|
.iter()
|
|
.find(|s| s.plugin.name == "db-guard" && s.plugin.scope == McpScope::Workspace)
|
|
.unwrap();
|
|
assert!(!dg_untrusted.enabled);
|
|
assert_eq!(dg_untrusted.origin, AgentPluginOrigin::Trust);
|
|
let ul_untrusted = states_untrusted.iter().find(|s| s.plugin.name == "user-lint").unwrap();
|
|
assert!(ul_untrusted.enabled, "a Claude workspace config cannot toggle a Copilot user plugin");
|
|
|
|
let trusted = PluginsPolicy { workspace_trusted: true, ..untrusted.clone() };
|
|
let states = resolve_plugins(discovered.clone(), &trusted, Some(&secrets));
|
|
let dg = states.iter().find(|s| s.plugin.name == "db-guard" && s.plugin.scope == McpScope::Workspace).unwrap();
|
|
assert!(!dg.enabled, "a consent-requiring plugin needs an approval on first discovery");
|
|
assert!(dg.consent_required);
|
|
assert_eq!(dg.origin, AgentPluginOrigin::Consent);
|
|
|
|
let secret_field = dg.plugin.config_fields.iter().find(|f| f.key == "dbToken").unwrap();
|
|
assert!(!secret_field.has_secret);
|
|
assert!(secret_field.value.is_empty());
|
|
|
|
let mut ws_settings = AgentPluginSettings::default();
|
|
ws_settings.entries.insert(
|
|
plugin_policy_key(&dg.plugin),
|
|
AgentPluginEntryPolicy { config: BTreeMap::from([("poolMax".into(), "16".into())]) },
|
|
);
|
|
let approved_policy = PluginsPolicy {
|
|
user: AgentPluginSettings::default(),
|
|
workspace: ws_settings,
|
|
workspace_trusted: true,
|
|
workspace_roots: vec![ws.clone()],
|
|
approved_capabilities: capability_approval_key(&dg.plugin).into_iter().collect(),
|
|
};
|
|
let states_approved = resolve_plugins(discovered, &approved_policy, Some(&secrets));
|
|
let dg_on = states_approved
|
|
.iter()
|
|
.find(|s| s.plugin.name == "db-guard" && s.plugin.scope == McpScope::Workspace)
|
|
.unwrap();
|
|
assert!(dg_on.enabled);
|
|
assert!(!dg_on.consent_required);
|
|
|
|
let mcp = projected_mcp_servers(&states_approved, &approved_policy, Some(&home), Some(&secrets));
|
|
assert_eq!(mcp.len(), 1);
|
|
assert_eq!(mcp[0].name, "pg-guard");
|
|
assert_eq!(mcp[0].plugin_id.as_deref(), Some(dg_on.plugin.id.as_str()));
|
|
assert!(dg_on.plugin.id.starts_with("claude:workspace:db-guard@acme#"), "{}", dg_on.plugin.id);
|
|
assert!(mcp[0].args.iter().any(|a| a == "--max=16"));
|
|
assert!(mcp[0].args[0].ends_with("srv.js") && !mcp[0].args[0].contains("${"));
|
|
assert!(mcp[0].env.iter().any(|kv| kv.name == "PG_TOKEN" && kv.value == "${user_config.dbToken}"));
|
|
assert!(mcp[0].env.iter().any(|kv| kv.name == "WS" && !kv.value.is_empty()));
|
|
|
|
// A second project in the window has its own Claude project install of the same plugin.
|
|
let ws2 = tmp.path().join("ws2");
|
|
write(&ws2.join(".claude/settings.json"), r#"{"enabledPlugins":{"db-guard@acme":false}}"#);
|
|
let mut registry: Value = serde_json::from_str(
|
|
&std::fs::read_to_string(home.join(".claude/plugins/installed_plugins.json")).unwrap(),
|
|
)
|
|
.unwrap();
|
|
let mut second = registry["plugins"]["db-guard@acme"][0].clone();
|
|
second["projectPath"] = json!(ws2.to_string_lossy());
|
|
registry["plugins"]["db-guard@acme"].as_array_mut().unwrap().push(second);
|
|
write(&home.join(".claude/plugins/installed_plugins.json"), ®istry.to_string());
|
|
let roots = [ws.clone(), ws2.clone()];
|
|
let ws2_row = discover_plugins(&roots, Some(&home))
|
|
.into_iter()
|
|
.find(|p| {
|
|
p.name == "db-guard"
|
|
&& p.scope == McpScope::Workspace
|
|
&& p.workspace_root.as_ref().is_some_and(|root| root.0 == ws2)
|
|
})
|
|
.expect("a workspace row owned by the second project");
|
|
assert!(!ws2_row.default_enabled);
|
|
let ids =
|
|
|roots: &[PathBuf]| discover_plugins(roots, Some(&home)).into_iter().map(|p| p.id).collect::<BTreeSet<_>>();
|
|
assert_eq!(ids(&[ws.clone(), ws2.clone()]), ids(&[ws2.clone(), ws.clone()]), "ids ignore discovery order");
|
|
let ws1_row = discover_plugins(&roots, Some(&home))
|
|
.into_iter()
|
|
.find(|p| p.name == "db-guard" && p.workspace_root.as_ref().is_some_and(|root| root.0 == ws))
|
|
.unwrap();
|
|
assert_ne!(ws1_row.id, ws2_row.id, "each owner's row has its own id");
|
|
assert_eq!(plugin_workspace_root(&ws2_row, &roots), Some(ws2.as_path()));
|
|
set_plugin_enabled(&ws2_row, true, Some(&home), Some(&ws)).unwrap();
|
|
assert!(json_plugin_enabled_map(&ws2.join(".claude/settings.json"))["db-guard@acme"]);
|
|
assert!(
|
|
json_plugin_enabled_map(&ws.join(".claude/settings.json"))["db-guard@acme"],
|
|
"toggling the second project's row leaves the primary project's setting alone"
|
|
);
|
|
|
|
write(
|
|
&ws.join(".agents/skills/pg-check/SKILL.md"),
|
|
"---\nname: pg-check\ndescription: Workspace override\n---\n",
|
|
);
|
|
let proj_skills = projected_skill_roots(&states_approved, Some("claude"));
|
|
let all_skills = crate::skills::discover_skills_with_agent_plugins(
|
|
std::slice::from_ref(&ws),
|
|
Some(&home),
|
|
&[],
|
|
&proj_skills,
|
|
);
|
|
let pg_skill = all_skills.iter().find(|s| s.name == "pg-check").unwrap();
|
|
assert_eq!(
|
|
pg_skill.description, "Workspace override",
|
|
"standalone workspace skill beats plugin skill on name clash"
|
|
);
|
|
assert_eq!(pg_skill.plugin_id, None);
|
|
|
|
let proj_rules = projected_memory_entries(&states_approved);
|
|
assert_eq!(proj_rules.len(), 1);
|
|
assert_eq!(proj_rules[0].plugin_id.as_deref(), Some(dg_on.plugin.id.as_str()));
|
|
assert_eq!(proj_rules[0].paths, ["db/**/*.sql"]);
|
|
}
|
|
|
|
#[test]
|
|
fn new_native_json_files_are_written_as_indented_json() {
|
|
let tmp = tempfile::tempdir().unwrap();
|
|
let path = tmp.path().join("settings.json");
|
|
set_json_object_member_if_absent(
|
|
&path,
|
|
"extraKnownMarketplaces",
|
|
"m",
|
|
&json!({ "source": { "source": "directory", "path": "/x" } }),
|
|
)
|
|
.unwrap();
|
|
set_json_plugin_enabled(&path, "p@m", true).unwrap();
|
|
assert_eq!(
|
|
std::fs::read_to_string(&path).unwrap(),
|
|
"{\n \"extraKnownMarketplaces\": {\n \"m\": {\n \"source\": {\n \"path\": \"/x\",\n \"source\": \"directory\"\n }\n }\n },\n \"enabledPlugins\": {\n \"p@m\": true\n }\n}\n"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn a_workspace_override_decides_what_a_globally_enabled_plugin_projects() {
|
|
let tmp = tempfile::tempdir().unwrap();
|
|
let home = tmp.path().join("home");
|
|
let ws = tmp.path().join("ws");
|
|
let dir = home.join(".copilot/installed-plugins/m/tool");
|
|
write(&dir.join("plugin.json"), r#"{"name":"tool"}"#);
|
|
write(&dir.join("skills/tool-skill/SKILL.md"), "---\nname: tool-skill\ndescription: x\n---\n");
|
|
write(
|
|
&home.join(".copilot/config.json"),
|
|
&json!({ "installedPlugins": [{ "name": "tool", "marketplace": "m", "enabled": true, "cache_path": dir }] })
|
|
.to_string(),
|
|
);
|
|
let policy = PluginsPolicy { workspace_roots: vec![ws.clone()], ..Default::default() };
|
|
let projected = || {
|
|
let states = resolve_plugins(discover_plugins(std::slice::from_ref(&ws), Some(&home)), &policy, None);
|
|
projected_skill_roots(&states, None).len()
|
|
};
|
|
assert_eq!(projected(), 1, "globally enabled, no workspace override");
|
|
write(&ws.join(".github/copilot/settings.json"), r#"{"enabledPlugins":{"tool@m":false}}"#);
|
|
assert_eq!(projected(), 0, "disabled for the workspace");
|
|
write(&ws.join(".github/copilot/settings.json"), r#"{"enabledPlugins":{"tool@m":true}}"#);
|
|
assert_eq!(projected(), 1, "enabled for the workspace, projected once");
|
|
}
|
|
|
|
#[test]
|
|
fn copilot_and_codex_toggles_touch_only_the_plugins_own_records() {
|
|
let tmp = tempfile::tempdir().unwrap();
|
|
let home = tmp.path().join("home");
|
|
let ws = tmp.path().join("ws");
|
|
let store = home.join(".copilot/installed-plugins");
|
|
let mut records = Vec::new();
|
|
for (marketplace, folder) in [("alpha", "alpha"), ("beta", "beta"), ("", "_direct")] {
|
|
let name = if marketplace.is_empty() { "solo" } else { "tool" };
|
|
let dir = store.join(folder).join(name);
|
|
write(&dir.join("plugin.json"), &format!(r#"{{"name":"{name}"}}"#));
|
|
records.push(json!({ "name": name, "marketplace": marketplace, "enabled": true, "cache_path": dir }));
|
|
}
|
|
let commented = records
|
|
.iter()
|
|
.map(|record| format!(" // managed by copilot\n {record}"))
|
|
.collect::<Vec<_>>()
|
|
.join(",\n");
|
|
write(
|
|
&home.join(".copilot/config.json"),
|
|
&format!(
|
|
"// User settings belong in settings.json.\n{{\n \"installedPlugins\": [\n{commented}\n ]\n}}\n"
|
|
),
|
|
);
|
|
let settings = "{\n // mine\n \"enabledPlugins\": { \"tool@alpha\": true, \"tool@beta\": true }\n}\n";
|
|
write(&home.join(".copilot/settings.json"), settings);
|
|
write(&ws.join(".github/copilot/settings.json"), r#"{"enabledPlugins":{"tool@alpha":true}}"#);
|
|
|
|
let found = discover_plugins(std::slice::from_ref(&ws), Some(&home));
|
|
let row = |name: &str, marketplace: Option<&str>, scope: McpScope| {
|
|
found
|
|
.iter()
|
|
.find(|p| p.name == name && p.marketplace.as_deref() == marketplace && p.scope == scope)
|
|
.unwrap_or_else(|| panic!("{name} {marketplace:?} {scope:?}"))
|
|
.clone()
|
|
};
|
|
set_plugin_enabled(&row("tool", Some("alpha"), McpScope::User), false, Some(&home), Some(&ws)).unwrap();
|
|
set_plugin_enabled(&row("solo", None, McpScope::User), false, Some(&home), Some(&ws)).unwrap();
|
|
set_plugin_enabled(&row("tool", Some("alpha"), McpScope::Workspace), false, Some(&home), Some(&ws)).unwrap();
|
|
|
|
let user_settings = json_plugin_enabled_map(&home.join(".copilot/settings.json"));
|
|
assert!(!user_settings["tool@alpha"]);
|
|
assert!(user_settings["tool@beta"], "a same-named plugin from another marketplace is untouched");
|
|
assert!(!user_settings.contains_key("solo"), "direct installs have no enabledPlugins key");
|
|
assert!(std::fs::read_to_string(home.join(".copilot/settings.json")).unwrap().contains("// mine"));
|
|
let config = parse_jsonc(&std::fs::read_to_string(home.join(".copilot/config.json")).unwrap()).unwrap();
|
|
let enabled = |name: &str, marketplace: &str| {
|
|
config["installedPlugins"]
|
|
.as_array()
|
|
.unwrap()
|
|
.iter()
|
|
.find(|r| r["name"] == name && r["marketplace"] == marketplace)
|
|
.unwrap()["enabled"]
|
|
.clone()
|
|
};
|
|
let config_text = std::fs::read_to_string(home.join(".copilot/config.json")).unwrap();
|
|
assert_eq!(config_text.matches("// managed by copilot").count(), 3, "{config_text}");
|
|
assert!(config_text.starts_with("// User settings belong in settings.json."));
|
|
assert_eq!(enabled("tool", "alpha"), false);
|
|
assert_eq!(enabled("tool", "beta"), true);
|
|
assert_eq!(enabled("solo", ""), false);
|
|
assert!(!json_plugin_enabled_map(&ws.join(".github/copilot/settings.json"))["tool@alpha"]);
|
|
|
|
// Re-registering a plugin replaces only its own record.
|
|
let beta = row("tool", Some("beta"), McpScope::User);
|
|
let provenance = InstalledPluginProvenance {
|
|
source_kind: "local".into(),
|
|
local_path: Some("/src/tool".into()),
|
|
..Default::default()
|
|
};
|
|
register_copilot_installed_record(&home, &beta, &provenance, true).unwrap();
|
|
let config_text = std::fs::read_to_string(home.join(".copilot/config.json")).unwrap();
|
|
assert_eq!(config_text.matches("// managed by copilot").count(), 3, "{config_text}");
|
|
let config = parse_jsonc(&config_text).unwrap();
|
|
assert_eq!(config["installedPlugins"].as_array().unwrap().len(), 3);
|
|
assert!(config_text.contains("\"installed_source\""));
|
|
|
|
let codex = home.join(".codex/plugins/cache/m/codexy/1.0.0");
|
|
write(&codex.join(".codex-plugin/plugin.json"), r#"{"name":"codexy"}"#);
|
|
write(&home.join(".codex/config.toml"), "# keep\n");
|
|
let codex_row =
|
|
inspect_plugin_dir(&codex, AgentPluginSource::CodexUser, McpScope::User, Some("m"), true).unwrap();
|
|
set_plugin_enabled(&codex_row, false, Some(&home), Some(&ws)).unwrap();
|
|
let codex_text = std::fs::read_to_string(home.join(".codex/config.toml")).unwrap();
|
|
assert!(codex_text.starts_with("# keep\n") && !codex_text.contains("[marketplaces"), "{codex_text}");
|
|
assert!(!read_codex_plugin_states(&home.join(".codex/config.toml"))["codexy@m"]);
|
|
}
|
|
|
|
#[test]
|
|
fn an_inherited_gemini_user_rule_is_not_a_workspace_install() {
|
|
let tmp = tempfile::tempdir().unwrap();
|
|
let home = tmp.path().join("home");
|
|
let ws = home.join("projects/app");
|
|
std::fs::create_dir_all(&ws).unwrap();
|
|
let ext = home.join(".gemini/extensions/notes");
|
|
write(&ext.join("gemini-extension.json"), r#"{"name":"notes","version":"1.0.0"}"#);
|
|
let enablement = home.join(".gemini/extensions/extension-enablement.json");
|
|
let user_rule = gemini_enablement_rule(&home, false);
|
|
write(&enablement, &json!({ "notes": { "overrides": [user_rule] } }).to_string());
|
|
|
|
let workspace_rows = || {
|
|
discover_plugins(std::slice::from_ref(&ws), Some(&home))
|
|
.into_iter()
|
|
.filter(|p| p.source == AgentPluginSource::GeminiUser && p.scope == McpScope::Workspace)
|
|
.count()
|
|
};
|
|
assert_eq!(workspace_rows(), 0, "the home rule applies to the project but is not the project's own");
|
|
assert!(!plugin_installed_in(AgentPluginSource::GeminiUser, "notes", None, Some(&home), Some(&ws)).1);
|
|
|
|
let ws_rule = gemini_enablement_rule(&ws, true);
|
|
write(&enablement, &json!({ "notes": { "overrides": [user_rule, ws_rule] } }).to_string());
|
|
assert_eq!(workspace_rows(), 1);
|
|
assert!(plugin_installed_in(AgentPluginSource::GeminiUser, "notes", None, Some(&home), Some(&ws)).1);
|
|
}
|
|
|
|
#[test]
|
|
fn toggles_each_native_harness_config_without_cross_harness_injection() {
|
|
let tmp = tempfile::tempdir().unwrap();
|
|
let home = tmp.path().join("home");
|
|
let ws = tmp.path().join("ws");
|
|
write(
|
|
&home.join(".claude/settings.json"),
|
|
"{\n // keep this comment\n \"permissions\": { \"allow\": [] },\n \"enabledPlugins\": { \"existing\": true }\n}\n",
|
|
);
|
|
write(
|
|
&home.join(".copilot/settings.json"),
|
|
"{\n // copilot comment\n \"editor\": { \"mode\": \"native\" }\n}\n",
|
|
);
|
|
write(
|
|
&home.join(".codex/config.toml"),
|
|
"# keep this codex comment\nmodel = \"gpt-5\"\n\n[marketplaces.acme]\nsource_type = \"git\"\nsource = \"https://github.com/acme/plugins.git\"\n\n[plugins.\"other@acme\"]\nenabled = true\n",
|
|
);
|
|
for (source, dir, name) in [
|
|
(AgentPluginSource::ClaudeUser, home.join(".claude/plugins/cache/acme/claude-only/1.0.0"), "claude-only"),
|
|
(
|
|
AgentPluginSource::CopilotUser,
|
|
home.join(".copilot/installed-plugins/_direct/copilot-only"),
|
|
"copilot-only",
|
|
),
|
|
(AgentPluginSource::CodexUser, home.join(".codex/plugins/cache/acme/codex-only/1.0.0"), "codex-only"),
|
|
(AgentPluginSource::GeminiUser, home.join(".gemini/extensions/gemini-only"), "gemini-only"),
|
|
] {
|
|
write(&dir.join("plugin.json"), &format!(r#"{{"name":"{name}"}}"#));
|
|
let plugin = inspect_plugin_dir(&dir, source, McpScope::User, Some("acme"), true).unwrap();
|
|
set_plugin_enabled(&plugin, false, Some(&home), Some(&ws)).unwrap();
|
|
}
|
|
assert_eq!(
|
|
parse_jsonc(&std::fs::read_to_string(home.join(".claude/settings.json")).unwrap()).unwrap()["enabledPlugins"]
|
|
["claude-only@acme"],
|
|
false
|
|
);
|
|
assert_eq!(
|
|
parse_jsonc(&std::fs::read_to_string(home.join(".copilot/settings.json")).unwrap()).unwrap()["enabledPlugins"]
|
|
["copilot-only@acme"],
|
|
false
|
|
);
|
|
assert!(!read_codex_plugin_states(&home.join(".codex/config.toml"))["codex-only@acme"]);
|
|
assert_eq!(
|
|
read_gemini_plugin_enabled(
|
|
&home.join(".gemini/extensions/extension-enablement.json"),
|
|
"gemini-only",
|
|
&home,
|
|
),
|
|
Some(false)
|
|
);
|
|
let gemini_dir = home.join(".gemini/extensions/gemini-only");
|
|
let mut workspace_gemini =
|
|
inspect_plugin_dir(&gemini_dir, AgentPluginSource::GeminiUser, McpScope::Workspace, None, false).unwrap();
|
|
workspace_gemini.name = "gemini-only".to_owned();
|
|
set_plugin_enabled(&workspace_gemini, true, Some(&home), Some(&ws)).unwrap();
|
|
assert_eq!(
|
|
read_gemini_plugin_enabled(&home.join(".gemini/extensions/extension-enablement.json"), "gemini-only", &ws,),
|
|
Some(true)
|
|
);
|
|
assert!(discover_plugins(std::slice::from_ref(&ws), Some(&home)).iter().any(|plugin| {
|
|
plugin.source == AgentPluginSource::GeminiUser
|
|
&& plugin.scope == McpScope::Workspace
|
|
&& plugin.name == "gemini-only"
|
|
&& plugin.default_enabled
|
|
}));
|
|
assert!(std::fs::read_to_string(home.join(".claude/settings.json")).unwrap().contains("// keep this comment"));
|
|
assert!(
|
|
parse_jsonc(&std::fs::read_to_string(home.join(".claude/settings.json")).unwrap()).unwrap()["enabledPlugins"]
|
|
["existing"]
|
|
.as_bool()
|
|
.unwrap()
|
|
);
|
|
assert!(std::fs::read_to_string(home.join(".copilot/settings.json")).unwrap().contains("// copilot comment"));
|
|
assert!(
|
|
std::fs::read_to_string(home.join(".codex/config.toml")).unwrap().contains("# keep this codex comment")
|
|
);
|
|
let codex_text = std::fs::read_to_string(home.join(".codex/config.toml")).unwrap();
|
|
assert!(codex_text.contains("source_type = \"git\""));
|
|
assert!(codex_text.contains("https://github.com/acme/plugins.git"));
|
|
}
|
|
|
|
#[test]
|
|
fn marketplace_browse_preview_and_pinned_native_install_roundtrip() {
|
|
let tmp = tempfile::tempdir().unwrap();
|
|
let ws = tmp.path().join("ws");
|
|
let home = tmp.path().join("home");
|
|
std::fs::create_dir_all(&ws).unwrap();
|
|
std::fs::create_dir_all(&home).unwrap();
|
|
|
|
let tree_v1 = "1111111111111111111111111111111111111111";
|
|
let mkt_json = br#"{"name":"acme-mkt","owner":{"name":"Acme"},"plugins":[{"name":"cloud-ops","source":"./plugins/cloud-ops","description":"Cloud toolkit","version":"1.0.0"}]}"#;
|
|
let plug_json = br#"{"name":"cloud-ops","version":"1.0.0","description":"Cloud toolkit"}"#;
|
|
let skill_md = b"---\nname: deploy-k8s\ndescription: Deploy cluster\n---\nRun kubectl.\n";
|
|
let mcp_json = br#"{"mcpServers":{"k8s":{"command":"npx","args":["-y","k8s-mcp"]}}}"#;
|
|
let helper_sh = b"#!/bin/sh\necho ok\n";
|
|
let hook_json = br#"{"hooks":{"PreToolUse":[{"matcher":"Bash","hooks":[{"command":"./scripts/helper.sh"}]}]}}"#;
|
|
|
|
let gh_v1 = FakeGitHub::new(
|
|
&[
|
|
(".claude-plugin/marketplace.json", mkt_json, "100644"),
|
|
("plugins/cloud-ops/.claude-plugin/plugin.json", plug_json, "100644"),
|
|
("plugins/cloud-ops/skills/deploy-k8s/SKILL.md", skill_md, "100644"),
|
|
("plugins/cloud-ops/.mcp.json", mcp_json, "100644"),
|
|
("plugins/cloud-ops/hooks/hooks.json", hook_json, "100644"),
|
|
("plugins/cloud-ops/scripts/helper.sh", helper_sh, "100755"),
|
|
],
|
|
tree_v1,
|
|
);
|
|
let cancel = CancellationToken::new();
|
|
|
|
// 1. Browse marketplace
|
|
let browsed = browse_marketplace(&gh_v1, "acme/plugins", Some(&home), Some(&ws), &cancel).unwrap();
|
|
assert_eq!(browsed.marketplace_name, "acme-mkt");
|
|
assert_eq!(browsed.candidates.len(), 1);
|
|
assert_eq!(browsed.candidates[0].name, "cloud-ops");
|
|
assert_eq!(browsed.candidates[0].subpath, "plugins/cloud-ops");
|
|
|
|
// 2. Preview plugin -> reports executable script warning AND stdio MCP capability consent
|
|
let preview = preview_plugin(
|
|
&gh_v1,
|
|
"acme/plugins",
|
|
Some("plugins/cloud-ops"),
|
|
Some("acme-mkt"),
|
|
Some(&home),
|
|
Some(&ws),
|
|
&cancel,
|
|
)
|
|
.unwrap();
|
|
assert_eq!(preview.tree_sha.as_deref(), Some(tree_v1));
|
|
assert_eq!(preview.commit_sha.as_deref(), Some(tree_v1));
|
|
assert!(preview.capabilities.requires_consent);
|
|
assert_eq!(preview.capabilities.skill_count, 1);
|
|
assert_eq!(preview.capabilities.mcp_count, 1);
|
|
assert!(!preview.scan_warnings.is_empty(), "flags scripts/helper.sh");
|
|
for typo in ["acme/plugins#no-such-ref", "https://github.com/acme/plugins/tree/no-such-ref"] {
|
|
assert!(browse_marketplace(&gh_v1, typo, Some(&home), Some(&ws), &cancel).is_err(), "{typo}");
|
|
assert!(
|
|
preview_plugin(&gh_v1, typo, Some("plugins/cloud-ops"), None, Some(&home), Some(&ws), &cancel).is_err(),
|
|
"{typo}"
|
|
);
|
|
}
|
|
|
|
// 3. Refuses install without `confirm_warnings` or `approve_capabilities`, or with tampered `tree_sha`
|
|
let base_req = InstallAgentPluginRequest {
|
|
source_kind: "github".into(),
|
|
owner: Some("acme".into()),
|
|
repo: Some("plugins".into()),
|
|
git_ref: preview.git_ref.clone(),
|
|
tree_sha: preview.tree_sha.clone(),
|
|
commit_sha: preview.commit_sha.clone(),
|
|
subpath: "plugins/cloud-ops".into(),
|
|
local_path: None,
|
|
marketplace: Some("acme-mkt".into()),
|
|
marketplace_source: preview.marketplace_source.clone(),
|
|
scope: McpScope::User,
|
|
harness: "claude".into(),
|
|
approve_capabilities: false,
|
|
approved_capability_hash: preview.capabilities.capability_hash.clone(),
|
|
confirm_warnings: false,
|
|
overwrite: false,
|
|
};
|
|
assert!(install_plugin(&gh_v1, &base_req, Some(&home), Some(&ws), &cancel).is_err());
|
|
assert!(
|
|
install_plugin(
|
|
&gh_v1,
|
|
&InstallAgentPluginRequest { confirm_warnings: true, ..base_req.clone() },
|
|
Some(&home),
|
|
Some(&ws),
|
|
&cancel,
|
|
)
|
|
.is_err(),
|
|
"must also approve MCP execution capabilities"
|
|
);
|
|
assert!(
|
|
install_plugin(
|
|
&gh_v1,
|
|
&InstallAgentPluginRequest {
|
|
confirm_warnings: true,
|
|
approve_capabilities: true,
|
|
tree_sha: Some("2222222222222222222222222222222222222222".into()),
|
|
..base_req.clone()
|
|
},
|
|
Some(&home),
|
|
Some(&ws),
|
|
&cancel,
|
|
)
|
|
.is_err(),
|
|
"pinned tree_sha mismatch rejected"
|
|
);
|
|
|
|
// A commit that does not record the pinned tree is refused before anything is written.
|
|
let mut rewired = FakeGitHub::new(&[], tree_v1);
|
|
rewired.trees = gh_v1.trees.clone();
|
|
rewired.blobs = gh_v1.blobs.clone();
|
|
rewired.commit_trees.insert(tree_v1.to_owned(), "2222222222222222222222222222222222222222".to_owned());
|
|
let mismatch = install_plugin(
|
|
&rewired,
|
|
&InstallAgentPluginRequest { confirm_warnings: true, approve_capabilities: true, ..base_req.clone() },
|
|
Some(&home),
|
|
Some(&ws),
|
|
&cancel,
|
|
)
|
|
.unwrap_err()
|
|
.to_string();
|
|
assert!(mismatch.contains("does not contain the pinned plugin tree"), "{mismatch}");
|
|
assert!(!home.join(".claude/plugins/cache/acme-mkt").exists());
|
|
|
|
// Approving a different capability set than the preview showed is refused.
|
|
let wrong_hash = InstallAgentPluginRequest {
|
|
confirm_warnings: true,
|
|
approve_capabilities: true,
|
|
approved_capability_hash: Some("0000".into()),
|
|
..base_req.clone()
|
|
};
|
|
assert!(install_plugin(&gh_v1, &wrong_hash, Some(&home), Some(&ws), &cancel).is_err());
|
|
|
|
// 4. Approved install succeeds and writes the native harness registration.
|
|
let (installed_dir, approval_key) = install_plugin(
|
|
&gh_v1,
|
|
&InstallAgentPluginRequest { confirm_warnings: true, approve_capabilities: true, ..base_req.clone() },
|
|
Some(&home),
|
|
Some(&ws),
|
|
&cancel,
|
|
)
|
|
.unwrap();
|
|
let rediscovered = discover_plugins(&[], Some(&home));
|
|
let approval_key = approval_key.expect("stdio MCP requires an approval");
|
|
assert!(approval_key.starts_with("claude:cloud-ops@acme-mkt#"), "{approval_key}");
|
|
assert_eq!(
|
|
rediscovered.iter().find(|p| p.name == "cloud-ops").and_then(capability_approval_key),
|
|
Some(approval_key.clone()),
|
|
"install and set_enabled must record consent under the same key"
|
|
);
|
|
let cap_hash =
|
|
rediscovered.iter().find(|p| p.name == "cloud-ops").and_then(|p| p.capabilities.capability_hash.clone());
|
|
assert!(installed_dir.ends_with(".claude/plugins/cache/acme-mkt/cloud-ops/1.0.0"));
|
|
assert_eq!(
|
|
serde_json::from_str::<Value>(&std::fs::read_to_string(home.join(".claude/settings.json")).unwrap())
|
|
.unwrap()["enabledPlugins"]["cloud-ops@acme-mkt"],
|
|
true
|
|
);
|
|
assert!(
|
|
std::fs::read_to_string(home.join(".claude/plugins/installed_plugins.json"))
|
|
.unwrap()
|
|
.contains("cloud-ops@acme-mkt")
|
|
);
|
|
assert_eq!(
|
|
parse_jsonc(&std::fs::read_to_string(home.join(".claude/settings.json")).unwrap()).unwrap()["extraKnownMarketplaces"]
|
|
["acme-mkt"]["source"]["repo"],
|
|
"acme/plugins"
|
|
);
|
|
|
|
let codex_request = InstallAgentPluginRequest {
|
|
harness: "codex".into(),
|
|
confirm_warnings: true,
|
|
approve_capabilities: true,
|
|
..base_req.clone()
|
|
};
|
|
let unknown = install_plugin(&gh_v1, &codex_request, Some(&home), Some(&ws), &cancel).unwrap_err().to_string();
|
|
assert!(unknown.contains("codex plugin marketplace add"), "{unknown}");
|
|
// What `codex plugin marketplace add acme/plugins` records (Codex keeps its own clone).
|
|
let codex_config = "# mine\n[marketplaces.acme-mkt]\nsource_type = \"git\"\nsource = \"https://github.com/acme/plugins.git\"\n";
|
|
write(&home.join(".codex/config.toml"), codex_config);
|
|
let codex_dir = install_plugin(&gh_v1, &codex_request, Some(&home), Some(&ws), &cancel).unwrap().0;
|
|
assert!(codex_dir.ends_with(".codex/plugins/cache/acme-mkt/cloud-ops/1.0.0"));
|
|
let codex_text = std::fs::read_to_string(home.join(".codex/config.toml")).unwrap();
|
|
assert!(codex_text.starts_with(codex_config), "{codex_text}");
|
|
assert!(read_codex_plugin_states(&home.join(".codex/config.toml"))["cloud-ops@acme-mkt"]);
|
|
assert!(!home.join(".codex/.tmp").exists(), "OpenIDEA never writes Codex's marketplace snapshots");
|
|
|
|
install_plugin(
|
|
&gh_v1,
|
|
&InstallAgentPluginRequest {
|
|
scope: McpScope::Workspace,
|
|
harness: "claude".into(),
|
|
confirm_warnings: true,
|
|
approve_capabilities: true,
|
|
overwrite: true,
|
|
..base_req
|
|
},
|
|
Some(&home),
|
|
Some(&ws),
|
|
&cancel,
|
|
)
|
|
.unwrap();
|
|
let claude_registry =
|
|
parse_jsonc(&std::fs::read_to_string(home.join(".claude/plugins/installed_plugins.json")).unwrap())
|
|
.unwrap();
|
|
assert_eq!(claude_registry["version"], 2);
|
|
let project_record = claude_registry["plugins"]["cloud-ops@acme-mkt"]
|
|
.as_array()
|
|
.unwrap()
|
|
.iter()
|
|
.find(|record| record["scope"] == "project")
|
|
.unwrap();
|
|
assert_eq!(project_record["projectPath"], dunce::canonicalize(&ws).unwrap().to_string_lossy().as_ref());
|
|
assert!(project_record["installedAt"].as_str().is_some());
|
|
assert!(project_record["lastUpdated"].as_str().is_some());
|
|
assert_eq!(project_record["gitCommitSha"], tree_v1);
|
|
|
|
std::fs::write(installed_dir.join("scripts/helper.sh"), "#!/bin/sh\necho changed\n").unwrap();
|
|
let changed = discover_plugins(std::slice::from_ref(&ws), Some(&home))
|
|
.into_iter()
|
|
.find(|p| p.name == "cloud-ops")
|
|
.and_then(|p| p.capabilities.capability_hash);
|
|
assert_ne!(changed, cap_hash, "hook-referenced script changes invalidate consent");
|
|
|
|
let found = discover_plugins(std::slice::from_ref(&ws), Some(&home));
|
|
assert!(found.iter().any(|p| p.name == "cloud-ops" && p.source == AgentPluginSource::ClaudeUser));
|
|
}
|
|
|
|
#[test]
|
|
fn versioned_plugin_caches_pick_the_highest_non_semver_version() {
|
|
let tmp = tempfile::tempdir().unwrap();
|
|
for version in ["v2.0", "v10.0", "v9.5"] {
|
|
std::fs::create_dir_all(tmp.path().join("mkt/tool").join(version)).unwrap();
|
|
}
|
|
let picked = scan_versioned_plugin_container(tmp.path(), false);
|
|
assert_eq!(picked.len(), 1);
|
|
assert!(picked[0].0.ends_with("v10.0"), "{:?}", picked[0].0);
|
|
}
|
|
|
|
#[test]
|
|
fn manifest_inline_and_custom_path_hooks_require_consent_with_matching_preview_and_install_hashes() {
|
|
let tmp = tempfile::tempdir().unwrap();
|
|
let dir = tmp.path().join("hooked");
|
|
write(
|
|
&dir.join(".claude-plugin/plugin.json"),
|
|
r#"{"name":"hooked","hooks":{"PreToolUse":[{"hooks":[{"type":"command","command":"${CLAUDE_PLUGIN_ROOT}/bin/guard.sh"}]}]}}"#,
|
|
);
|
|
write(&dir.join(".plugin/plugin.json"), r#"{"name":"hooked","hooks":"./config/copilot-hooks.json"}"#);
|
|
write(&dir.join("config/copilot-hooks.json"), r#"{"hooks":{"sessionStart":[{"bash":"echo hi"}]}}"#);
|
|
write(&dir.join("bin/guard.sh"), "#!/bin/sh\necho guard\n");
|
|
|
|
let on_disk = inspect_plugin_dir(&dir, AgentPluginSource::ClaudeUser, McpScope::User, Some("m"), true).unwrap();
|
|
let scanned = scan_local_subtree(&dir, MAX_PLUGIN_FILES, MAX_PLUGIN_BYTES, "plugin").unwrap();
|
|
let preview = inspect_fetched_subtree(&scanned, "hooked").unwrap();
|
|
for hooks in [&on_disk.capabilities.hook_files, &preview.capabilities.hook_files] {
|
|
assert!(hooks.contains(&".claude-plugin/plugin.json#hooks".to_owned()), "{hooks:?}");
|
|
assert!(hooks.contains(&"config/copilot-hooks.json".to_owned()), "{hooks:?}");
|
|
}
|
|
assert!(on_disk.capabilities.requires_consent);
|
|
assert_eq!(on_disk.capabilities.capability_hash, preview.capabilities.capability_hash);
|
|
|
|
write(&dir.join("bin/guard.sh"), "#!/bin/sh\necho swapped\n");
|
|
let changed = inspect_plugin_dir(&dir, AgentPluginSource::ClaudeUser, McpScope::User, Some("m"), true).unwrap();
|
|
assert_ne!(changed.capabilities.capability_hash, on_disk.capabilities.capability_hash);
|
|
}
|
|
|
|
#[test]
|
|
fn install_targets_follow_each_harness_manifest_and_codex_local_marketplace_registration() {
|
|
let tmp = tempfile::tempdir().unwrap();
|
|
let home = tmp.path().join("home");
|
|
std::fs::create_dir_all(&home).unwrap();
|
|
let market = tmp.path().join("market");
|
|
write(
|
|
&market.join(".claude-plugin/marketplace.json"),
|
|
r#"{"name":"loc","owner":{"name":"x"},"plugins":[{"name":"dual","source":"./plugins/dual"}]}"#,
|
|
);
|
|
let dual = market.join("plugins/dual");
|
|
write(&dual.join(".codex-plugin/plugin.json"), r#"{"name":"dual","version":"1.0.0"}"#);
|
|
write(&dual.join("gemini-extension.json"), r#"{"name":"dual","version":"1.0.0"}"#);
|
|
write(&dual.join("skills/s/SKILL.md"), "---\nname: s\ndescription: x\n---\n");
|
|
let gh = FakeGitHub::new(&[], "1111111111111111111111111111111111111111");
|
|
let cancel = CancellationToken::new();
|
|
|
|
let preview =
|
|
preview_plugin(&gh, dual.to_str().unwrap(), None, Some("loc"), Some(&home), None, &cancel).unwrap();
|
|
let target = |harness: &str| preview.targets.iter().find(|t| t.harness == harness).unwrap().clone();
|
|
assert!(!target("claude").supported && !target("copilot").supported, "{:?}", preview.targets);
|
|
assert!(target("codex").supported, "{:?}", target("codex"));
|
|
assert!(target("gemini").supported);
|
|
assert!(!target("codex").overwrite_required);
|
|
|
|
let request = InstallAgentPluginRequest {
|
|
source_kind: "local".into(),
|
|
owner: None,
|
|
repo: None,
|
|
git_ref: None,
|
|
tree_sha: preview.tree_sha.clone(),
|
|
commit_sha: None,
|
|
subpath: String::new(),
|
|
local_path: preview.local_path.clone(),
|
|
marketplace: Some("loc".into()),
|
|
marketplace_source: preview.marketplace_source.clone(),
|
|
scope: McpScope::User,
|
|
harness: "codex".into(),
|
|
approve_capabilities: false,
|
|
approved_capability_hash: None,
|
|
confirm_warnings: false,
|
|
overwrite: false,
|
|
};
|
|
install_plugin(&gh, &request, Some(&home), None, &cancel).unwrap();
|
|
let config = std::fs::read_to_string(home.join(".codex/config.toml")).unwrap();
|
|
let document = config.parse::<toml_edit::DocumentMut>().unwrap();
|
|
assert_eq!(document["marketplaces"]["loc"]["source_type"].as_str(), Some("local"));
|
|
assert_eq!(
|
|
document["marketplaces"]["loc"]["source"].as_str().map(PathBuf::from),
|
|
Some(dunce::canonicalize(&market).unwrap())
|
|
);
|
|
assert!(read_codex_plugin_states(&home.join(".codex/config.toml"))["dual@loc"]);
|
|
assert!(!home.join(".codex/.tmp").exists());
|
|
|
|
let again = preview_plugin(&gh, dual.to_str().unwrap(), None, Some("loc"), Some(&home), None, &cancel).unwrap();
|
|
let codex = again.targets.iter().find(|t| t.harness == "codex").unwrap();
|
|
assert!(codex.installed_user && codex.overwrite_required);
|
|
let gemini = again.targets.iter().find(|t| t.harness == "gemini").unwrap();
|
|
assert!(!gemini.installed_user && !gemini.overwrite_required, "a Codex install is not a Gemini install");
|
|
|
|
// Copilot loads plugins from a local directory marketplace in place, as `copilot plugin install` does.
|
|
write(&dual.join(".claude-plugin/plugin.json"), r#"{"name":"dual","version":"1.0.0"}"#);
|
|
let preview =
|
|
preview_plugin(&gh, dual.to_str().unwrap(), None, Some("loc"), Some(&home), None, &cancel).unwrap();
|
|
let copilot = InstallAgentPluginRequest {
|
|
harness: "copilot".into(),
|
|
tree_sha: preview.tree_sha.clone(),
|
|
..request.clone()
|
|
};
|
|
let live = install_plugin(&gh, &copilot, Some(&home), None, &cancel).unwrap().0;
|
|
assert_eq!(live, dunce::canonicalize(&dual).unwrap());
|
|
assert!(!home.join(".copilot/installed-plugins").exists() && !home.join(".copilot/config.json").exists());
|
|
assert!(json_plugin_enabled_map(&home.join(".copilot/settings.json"))["dual@loc"]);
|
|
assert!(
|
|
discover_plugins(&[], Some(&home))
|
|
.iter()
|
|
.any(|p| { p.source == AgentPluginSource::CopilotUser && p.root_path.0 == live && p.default_enabled })
|
|
);
|
|
|
|
let plain = tmp.path().join("plain");
|
|
write(&plain.join("skills/s/SKILL.md"), "---\nname: s\ndescription: x\n---\n");
|
|
let plain_preview =
|
|
preview_plugin(&gh, plain.to_str().unwrap(), None, None, Some(&home), None, &cancel).unwrap();
|
|
assert!(plain_preview.targets.iter().all(|t| !t.supported), "manifest-less bundles fit no harness");
|
|
let agent_plugins = tmp.path().join("ap1");
|
|
write(
|
|
&agent_plugins.join("plugin.json"),
|
|
r#"{"$schema":"https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","name":"ap1"}"#,
|
|
);
|
|
write(&agent_plugins.join("skills/s/SKILL.md"), "---\nname: s\ndescription: x\n---\n");
|
|
let ap1 = preview_plugin(&gh, agent_plugins.to_str().unwrap(), None, None, Some(&home), None, &cancel).unwrap();
|
|
assert!(ap1.targets.iter().find(|t| t.harness == "copilot").unwrap().supported);
|
|
}
|
|
|
|
#[test]
|
|
fn hook_scripts_behind_plugin_root_placeholders_are_covered_by_consent_hash() {
|
|
let tmp = tempfile::tempdir().unwrap();
|
|
let dir = tmp.path().join("hooked");
|
|
write(&dir.join(".claude-plugin/plugin.json"), r#"{"name":"hooked"}"#);
|
|
write(
|
|
&dir.join("hooks/hooks.json"),
|
|
r#"{"hooks":{"PreToolUse":[{"hooks":[{"type":"command","command":"\"${CLAUDE_PLUGIN_ROOT}\"/scripts/guard.sh"},{"type":"command","command":"bash root.sh --x"}]}]}}"#,
|
|
);
|
|
write(&dir.join("scripts/guard.sh"), "#!/bin/sh\necho guard\n");
|
|
write(&dir.join("root.sh"), "#!/bin/sh\necho root\n");
|
|
let hash = || {
|
|
inspect_plugin_dir(&dir, AgentPluginSource::ClaudeUser, McpScope::User, Some("mkt"), true)
|
|
.unwrap()
|
|
.capabilities
|
|
.capability_hash
|
|
.unwrap()
|
|
};
|
|
let original = hash();
|
|
write(&dir.join("scripts/guard.sh"), "#!/bin/sh\necho swapped\n");
|
|
let after_placeholder_script = hash();
|
|
assert_ne!(after_placeholder_script, original, "${{CLAUDE_PLUGIN_ROOT}} script is hashed");
|
|
write(&dir.join("root.sh"), "#!/bin/sh\necho swapped\n");
|
|
assert_ne!(hash(), after_placeholder_script, "root-level script without a slash is hashed");
|
|
}
|
|
|
|
#[test]
|
|
fn remote_marketplace_entries_reject_unsafe_paths_refs_and_repos() {
|
|
let manifest = r##"{"name":"mkt","plugins":[
|
|
{"name":"ok","source":"./plugins/ok"},
|
|
{"name":"up","source":"../escape"},
|
|
{"name":"hash","source":"plugins/x#evil"},
|
|
{"name":"local-up","source":{"source":"local","path":"a/../../b"}},
|
|
{"name":"gh-ok","source":{"source":"github","repo":"acme/tools","ref":"v1.2"}},
|
|
{"name":"gh-bad-repo","source":{"source":"github","repo":"acme/tools/../../x"}},
|
|
{"name":"gh-bad-ref","source":{"source":"github","repo":"acme/tools","ref":"main#x"}},
|
|
{"name":"sub-bad","source":{"source":"git-subdir","url":"https://github.com/acme/tools.git","path":"../x"}}
|
|
]}"##;
|
|
let (_, candidates) =
|
|
parse_marketplace_json_remote(manifest, "acme", "repo", "main", None, None, None).unwrap();
|
|
let specs: Vec<_> = candidates.iter().map(|c| (c.name.as_str(), c.source_spec.as_str())).collect();
|
|
assert_eq!(specs, [("ok", "acme/repo/plugins/ok#main"), ("gh-ok", "acme/tools#v1.2")]);
|
|
assert!(
|
|
parse_marketplace_json_remote(
|
|
r#"{"metadata":{"pluginRoot":"../up"},"plugins":[]}"#,
|
|
"acme",
|
|
"repo",
|
|
"main",
|
|
None,
|
|
None,
|
|
None
|
|
)
|
|
.is_err()
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn local_preview_and_marketplace_sources_cannot_escape_the_root() {
|
|
let tmp = tempfile::tempdir().unwrap();
|
|
let root = tmp.path().join("marketplace");
|
|
let outside = tmp.path().join("outside");
|
|
write(&outside.join(".claude-plugin/plugin.json"), r#"{"name":"outside"}"#);
|
|
write(
|
|
&root.join(".claude-plugin/marketplace.json"),
|
|
r#"{"name":"escape","plugins":[
|
|
{"name":"outside","source":"../outside"},
|
|
{"name":"bad-ref","source":{"source":"github","repo":"acme/tools","ref":"main#evil"}},
|
|
{"name":"bad-repo","source":{"source":"github","repo":"acme/../tools"}},
|
|
{"name":"bad-sub","source":{"source":"git-subdir","url":"https://github.com/acme/tools.git","path":"../x"}},
|
|
{"name":"good","source":{"source":"git-subdir","url":"https://github.com/acme/tools.git","path":"plugins/good","ref":"v1"}}
|
|
]}"#,
|
|
);
|
|
let gh = FakeGitHub::new(&[], "1111111111111111111111111111111111111111");
|
|
let cancel = CancellationToken::new();
|
|
|
|
let browse = browse_marketplace(&gh, root.to_str().unwrap(), None, None, &cancel).unwrap();
|
|
assert_eq!(
|
|
browse.candidates.iter().map(|c| (c.name.as_str(), c.source_spec.as_str())).collect::<Vec<_>>(),
|
|
[("good", "acme/tools#v1")],
|
|
"local marketplaces apply the same repo/ref/path validation as remote ones"
|
|
);
|
|
assert!(preview_plugin(&gh, root.to_str().unwrap(), Some("../outside"), None, None, None, &cancel,).is_err());
|
|
|
|
let relative = browse_marketplace(&gh, "./marketplace", None, Some(tmp.path()), &cancel).unwrap();
|
|
assert_eq!(relative.marketplace_name, "escape", "./ paths resolve against the project root");
|
|
assert_eq!(resolve_local_source("marketplace", None, Some(tmp.path())), None, "bare text is never local");
|
|
}
|
|
|
|
#[test]
|
|
fn installs_gemini_extension_globally_with_workspace_enablement_rule() {
|
|
let tmp = tempfile::tempdir().unwrap();
|
|
let source = tmp.path().join("gemini-source");
|
|
let home = tmp.path().join("home");
|
|
let workspace = tmp.path().join("workspace");
|
|
write(&source.join("gemini-extension.json"), r#"{"name":"workspace-notes","version":"1.0.0"}"#);
|
|
write(&source.join("GEMINI.md"), "Use project terminology.\n");
|
|
std::fs::create_dir_all(&home).unwrap();
|
|
std::fs::create_dir_all(&workspace).unwrap();
|
|
let github = FakeGitHub::new(&[], "1111111111111111111111111111111111111111");
|
|
let cancel = CancellationToken::new();
|
|
|
|
let claude_without_marketplace = InstallAgentPluginRequest {
|
|
source_kind: "local".into(),
|
|
owner: None,
|
|
repo: None,
|
|
git_ref: None,
|
|
tree_sha: None,
|
|
commit_sha: None,
|
|
subpath: String::new(),
|
|
local_path: Some(source.to_string_lossy().into_owned()),
|
|
marketplace: None,
|
|
marketplace_source: None,
|
|
scope: McpScope::User,
|
|
harness: "claude".into(),
|
|
approve_capabilities: false,
|
|
approved_capability_hash: None,
|
|
confirm_warnings: false,
|
|
overwrite: false,
|
|
};
|
|
let error = install_plugin(&github, &claude_without_marketplace, Some(&home), Some(&workspace), &cancel)
|
|
.unwrap_err()
|
|
.to_string();
|
|
assert!(error.contains("named marketplace"));
|
|
|
|
let preview =
|
|
preview_plugin(&github, source.to_str().unwrap(), None, None, Some(&home), Some(&workspace), &cancel)
|
|
.unwrap();
|
|
let local_request = InstallAgentPluginRequest {
|
|
source_kind: "local".into(),
|
|
owner: None,
|
|
repo: None,
|
|
git_ref: None,
|
|
tree_sha: preview.tree_sha.clone(),
|
|
commit_sha: None,
|
|
subpath: String::new(),
|
|
local_path: preview.local_path.clone(),
|
|
marketplace: None,
|
|
marketplace_source: None,
|
|
scope: McpScope::Workspace,
|
|
harness: "gemini".into(),
|
|
approve_capabilities: false,
|
|
approved_capability_hash: None,
|
|
confirm_warnings: false,
|
|
overwrite: false,
|
|
};
|
|
write(&source.join("GEMINI.md"), "Changed after preview.\n");
|
|
let changed =
|
|
install_plugin(&github, &local_request, Some(&home), Some(&workspace), &cancel).unwrap_err().to_string();
|
|
assert!(changed.contains("changed after preview"), "{changed}");
|
|
write(&source.join("GEMINI.md"), "Use project terminology.\n");
|
|
|
|
let installed = install_plugin(&github, &local_request, Some(&home), Some(&workspace), &cancel).unwrap().0;
|
|
|
|
assert_eq!(installed, home.join(".gemini/extensions/workspace-notes"));
|
|
assert_eq!(
|
|
read_gemini_plugin_enabled(
|
|
&home.join(".gemini/extensions/extension-enablement.json"),
|
|
"workspace-notes",
|
|
&workspace,
|
|
),
|
|
Some(true)
|
|
);
|
|
assert!(discover_plugins(std::slice::from_ref(&workspace), Some(&home)).iter().any(|plugin| {
|
|
plugin.name == "workspace-notes"
|
|
&& plugin.source == AgentPluginSource::GeminiUser
|
|
&& plugin.scope == McpScope::Workspace
|
|
}));
|
|
}
|
|
}
|