aKode fase 5: rinomina interna (crate akode-*, akode-rs/, akode-cli/, binario akode, AKODE_*, ~/.akode, snapshot)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
15
akode-rs/core-plugins/BUILD.bazel
Normal file
15
akode-rs/core-plugins/BUILD.bazel
Normal file
@@ -0,0 +1,15 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "core-plugins",
|
||||
compile_data = glob(
|
||||
include = ["**"],
|
||||
allow_empty = True,
|
||||
exclude = [
|
||||
"**/* *",
|
||||
"BUILD.bazel",
|
||||
"Cargo.toml",
|
||||
],
|
||||
),
|
||||
crate_name = "akode_core_plugins",
|
||||
)
|
||||
62
akode-rs/core-plugins/Cargo.toml
Normal file
62
akode-rs/core-plugins/Cargo.toml
Normal file
@@ -0,0 +1,62 @@
|
||||
[package]
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
name = "akode-core-plugins"
|
||||
version.workspace = true
|
||||
|
||||
[lib]
|
||||
doctest = false
|
||||
name = "akode_core_plugins"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
akode-utils-process = { workspace = true }
|
||||
anyhow = { workspace = true }
|
||||
chrono = { workspace = true }
|
||||
akode-app-server-protocol = { workspace = true }
|
||||
akode-config = { workspace = true }
|
||||
akode-core-plugin-common = { workspace = true }
|
||||
akode-exec-server = { workspace = true }
|
||||
akode-git-utils = { workspace = true }
|
||||
akode-hooks = { workspace = true }
|
||||
akode-login = { workspace = true }
|
||||
akode-mcp = { workspace = true }
|
||||
akode-model-provider = { workspace = true }
|
||||
akode-otel = { workspace = true }
|
||||
akode-plugin = { workspace = true }
|
||||
akode-protocol = { workspace = true }
|
||||
akode-shell-command = { workspace = true }
|
||||
akode-skills = { workspace = true }
|
||||
akode-tools = { workspace = true }
|
||||
akode-utils-absolute-path = { workspace = true }
|
||||
akode-utils-path = { workspace = true }
|
||||
akode-utils-path-uri = { workspace = true }
|
||||
akode-utils-plugins = { workspace = true }
|
||||
dirs = { workspace = true }
|
||||
flate2 = { workspace = true }
|
||||
futures = { workspace = true }
|
||||
http = { workspace = true }
|
||||
regex = { workspace = true }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
serde_json = { workspace = true }
|
||||
serde_yaml = { workspace = true }
|
||||
sha2 = { workspace = true }
|
||||
tar = { workspace = true }
|
||||
tempfile = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
tokio = { workspace = true, features = ["fs", "macros", "rt", "time"] }
|
||||
toml = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
url = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
akode-exec-server-test-support = { workspace = true }
|
||||
akode-utils-cargo-bin = { workspace = true }
|
||||
pretty_assertions = { workspace = true }
|
||||
tempfile = { workspace = true }
|
||||
tokio = { workspace = true, features = ["test-util"] }
|
||||
tracing-subscriber = { workspace = true }
|
||||
tracing-test = { workspace = true, features = ["no-env-filter"] }
|
||||
234
akode-rs/core-plugins/src/agent_plugin_manifest.rs
Normal file
234
akode-rs/core-plugins/src/agent_plugin_manifest.rs
Normal file
@@ -0,0 +1,234 @@
|
||||
use super::RawPluginManifest;
|
||||
use super::RawPluginManifestInterface;
|
||||
use super::RawPluginManifestMcpServers;
|
||||
use super::RawPluginManifestPaths;
|
||||
use super::UriPluginManifest;
|
||||
use super::compatibility_json_error;
|
||||
use super::parse_legacy_plugin_manifest_uri;
|
||||
use super::resolve_openai_onboarding_skill;
|
||||
use super::resolve_raw_plugin_manifest;
|
||||
use akode_utils_path_uri::PathUri;
|
||||
use akode_utils_plugins::AGENT_PLUGIN_SCHEMA_PREFIX;
|
||||
use akode_utils_plugins::AGENT_PLUGIN_SCHEMA_URI;
|
||||
use akode_utils_plugins::SUPPORTED_AGENT_PLUGIN_SCHEMA_URIS;
|
||||
use serde::Deserialize;
|
||||
use serde_json::Value as JsonValue;
|
||||
|
||||
const AKODE_AGENT_PLUGIN_EXTENSION_NAMESPACE: &str = "com.openai";
|
||||
const AGENT_PLUGIN_FIELDS: &[&str] = &[
|
||||
"$schema",
|
||||
"name",
|
||||
"version",
|
||||
"description",
|
||||
"author",
|
||||
"homepage",
|
||||
"repository",
|
||||
"license",
|
||||
"keywords",
|
||||
"extensions",
|
||||
];
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct RawAgentPluginManifest {
|
||||
#[serde(rename = "$schema")]
|
||||
schema: String,
|
||||
name: String,
|
||||
#[serde(default)]
|
||||
version: Option<String>,
|
||||
#[serde(default)]
|
||||
description: Option<String>,
|
||||
#[serde(default)]
|
||||
author: Option<RawAgentPluginAuthor>,
|
||||
#[serde(default)]
|
||||
homepage: Option<String>,
|
||||
#[serde(default, rename = "repository")]
|
||||
_repository: Option<String>,
|
||||
#[serde(default, rename = "license")]
|
||||
_license: Option<String>,
|
||||
#[serde(default)]
|
||||
keywords: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct RawAgentPluginAuthor {
|
||||
#[serde(default)]
|
||||
name: Option<String>,
|
||||
#[serde(default, rename = "email")]
|
||||
_email: Option<String>,
|
||||
#[serde(default, rename = "url")]
|
||||
_url: Option<String>,
|
||||
}
|
||||
|
||||
pub(super) fn parse_agent_plugin_manifest_uri(
|
||||
plugin_root: &PathUri,
|
||||
manifest_path: &PathUri,
|
||||
contents: &str,
|
||||
overlay: Option<(&PathUri, &str)>,
|
||||
) -> Result<UriPluginManifest, serde_json::Error> {
|
||||
let value = serde_json::from_str::<JsonValue>(contents)?;
|
||||
let JsonValue::Object(mut object) = value else {
|
||||
return Err(compatibility_json_error(
|
||||
"Agent Plugins root `plugin.json` must contain a JSON object",
|
||||
));
|
||||
};
|
||||
for field in object.keys() {
|
||||
if !AGENT_PLUGIN_FIELDS.contains(&field.as_str()) {
|
||||
tracing::warn!(path = %manifest_path, field, "ignoring unknown Agent Plugins manifest field");
|
||||
}
|
||||
}
|
||||
object.retain(|field, _| AGENT_PLUGIN_FIELDS.contains(&field.as_str()));
|
||||
if object
|
||||
.get("extensions")
|
||||
.is_some_and(|extensions| !extensions.is_object())
|
||||
{
|
||||
tracing::warn!(path = %manifest_path, "ignoring non-object Agent Plugins `extensions` field");
|
||||
object.remove("extensions");
|
||||
}
|
||||
let codex_extension = object
|
||||
.get("extensions")
|
||||
.and_then(JsonValue::as_object)
|
||||
.and_then(|extensions| extensions.get(AKODE_AGENT_PLUGIN_EXTENSION_NAMESPACE))
|
||||
.and_then(|extension| {
|
||||
if extension.is_object() {
|
||||
Some(extension)
|
||||
} else {
|
||||
tracing::warn!(
|
||||
path = %manifest_path,
|
||||
namespace = AKODE_AGENT_PLUGIN_EXTENSION_NAMESPACE,
|
||||
"ignoring non-object Agent Plugins extension"
|
||||
);
|
||||
None
|
||||
}
|
||||
});
|
||||
for field in [
|
||||
"version",
|
||||
"description",
|
||||
"author",
|
||||
"homepage",
|
||||
"repository",
|
||||
"license",
|
||||
] {
|
||||
if object.get(field).is_some_and(JsonValue::is_null) {
|
||||
return Err(compatibility_json_error(format!(
|
||||
"Agent Plugins `{field}` must use its declared type when present"
|
||||
)));
|
||||
}
|
||||
}
|
||||
if let Some(author) = object.get("author").and_then(JsonValue::as_object) {
|
||||
for field in ["name", "email", "url"] {
|
||||
if author.get(field).is_some_and(JsonValue::is_null) {
|
||||
return Err(compatibility_json_error(format!(
|
||||
"Agent Plugins `author.{field}` must be a string when present"
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let onboarding_skill = resolve_openai_onboarding_skill(plugin_root, codex_extension);
|
||||
let codex_extension = codex_extension.map(serde_json::to_string).transpose()?;
|
||||
|
||||
let raw = serde_json::from_value::<RawAgentPluginManifest>(JsonValue::Object(object))?;
|
||||
if !SUPPORTED_AGENT_PLUGIN_SCHEMA_URIS.contains(&raw.schema.as_str()) {
|
||||
let message = if raw.schema.starts_with(AGENT_PLUGIN_SCHEMA_PREFIX) {
|
||||
format!(
|
||||
"unsupported Agent Plugins schema `{}`; supported schemas: `{AGENT_PLUGIN_SCHEMA_URI}`",
|
||||
raw.schema
|
||||
)
|
||||
} else {
|
||||
format!(
|
||||
"root `plugin.json` is not an Agent Plugins manifest; expected `$schema` `{AGENT_PLUGIN_SCHEMA_URI}`"
|
||||
)
|
||||
};
|
||||
return Err(compatibility_json_error(message));
|
||||
}
|
||||
if !is_valid_agent_plugin_name(&raw.name) {
|
||||
return Err(compatibility_json_error(format!(
|
||||
"invalid Agent Plugins name `{}`; use lowercase letters, numbers, dots, or hyphens",
|
||||
raw.name
|
||||
)));
|
||||
}
|
||||
|
||||
let version = raw.version.and_then(non_empty_trimmed);
|
||||
let description = raw.description.and_then(non_empty_trimmed);
|
||||
let developer_name = raw
|
||||
.author
|
||||
.and_then(|author| author.name)
|
||||
.and_then(non_empty_trimmed);
|
||||
let homepage = raw.homepage.and_then(non_empty_trimmed);
|
||||
let name = raw.name;
|
||||
let mut resolved = resolve_raw_plugin_manifest(
|
||||
plugin_root,
|
||||
manifest_path,
|
||||
RawPluginManifest {
|
||||
name: name.clone(),
|
||||
version,
|
||||
description: description.clone(),
|
||||
keywords: raw.keywords,
|
||||
skills: Some(RawPluginManifestPaths::Path("./skills".to_string())),
|
||||
mcp_servers: Some(RawPluginManifestMcpServers::Path("./mcp.json".to_string())),
|
||||
interface: Some(RawPluginManifestInterface {
|
||||
display_name: Some(name),
|
||||
short_description: description.clone(),
|
||||
long_description: description,
|
||||
developer_name,
|
||||
category: Some("Other".to_string()),
|
||||
website_url: homepage,
|
||||
..RawPluginManifestInterface::default()
|
||||
}),
|
||||
..RawPluginManifest::default()
|
||||
},
|
||||
)?;
|
||||
|
||||
if let Some(extension) = codex_extension.as_deref() {
|
||||
apply_codex_agent_plugin_extension(&mut resolved, plugin_root, manifest_path, extension)?;
|
||||
resolved.paths.onboarding_skill = onboarding_skill;
|
||||
} else if let Some((overlay_path, overlay_contents)) = overlay {
|
||||
apply_codex_agent_plugin_extension(
|
||||
&mut resolved,
|
||||
plugin_root,
|
||||
overlay_path,
|
||||
overlay_contents,
|
||||
)?;
|
||||
}
|
||||
Ok(resolved)
|
||||
}
|
||||
|
||||
fn non_empty_trimmed(value: String) -> Option<String> {
|
||||
let value = value.trim();
|
||||
(!value.is_empty()).then(|| value.to_string())
|
||||
}
|
||||
|
||||
fn apply_codex_agent_plugin_extension(
|
||||
resolved: &mut UriPluginManifest,
|
||||
plugin_root: &PathUri,
|
||||
source_path: &PathUri,
|
||||
contents: &str,
|
||||
) -> Result<(), serde_json::Error> {
|
||||
let extension = parse_legacy_plugin_manifest_uri(plugin_root, source_path, contents)?;
|
||||
resolved.paths.hooks = extension.paths.hooks;
|
||||
resolved.paths.onboarding_skill = extension.paths.onboarding_skill;
|
||||
if extension.interface.is_some() {
|
||||
resolved.interface = extension.interface;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn is_valid_agent_plugin_name(name: &str) -> bool {
|
||||
!name.is_empty()
|
||||
&& name.len() <= 64
|
||||
&& !name.contains("--")
|
||||
&& !name.contains("..")
|
||||
&& name
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || b".-".contains(&byte))
|
||||
&& name
|
||||
.as_bytes()
|
||||
.first()
|
||||
.is_some_and(u8::is_ascii_alphanumeric)
|
||||
&& name
|
||||
.as_bytes()
|
||||
.last()
|
||||
.is_some_and(u8::is_ascii_alphanumeric)
|
||||
}
|
||||
275
akode-rs/core-plugins/src/agent_plugin_manifest_tests.rs
Normal file
275
akode-rs/core-plugins/src/agent_plugin_manifest_tests.rs
Normal file
@@ -0,0 +1,275 @@
|
||||
use super::PluginManifest;
|
||||
use super::PluginManifestMcpServers;
|
||||
use super::load_plugin_manifest;
|
||||
use akode_utils_absolute_path::AbsolutePathBuf;
|
||||
use akode_utils_plugins::AGENT_PLUGIN_SCHEMA_URI;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
use tempfile::tempdir;
|
||||
|
||||
fn write_agent_plugin_manifest(plugin_root: &Path, extra_fields: &str) {
|
||||
fs::create_dir_all(plugin_root).expect("create plugin root");
|
||||
fs::write(
|
||||
plugin_root.join("plugin.json"),
|
||||
format!(
|
||||
r#"{{
|
||||
"$schema": "{AGENT_PLUGIN_SCHEMA_URI}",
|
||||
"name": "demo-plugin"{extra_fields}
|
||||
}}"#
|
||||
),
|
||||
)
|
||||
.expect("write Agent Plugins manifest");
|
||||
}
|
||||
|
||||
fn load_manifest(plugin_root: &Path) -> PluginManifest {
|
||||
load_plugin_manifest(plugin_root).expect("load plugin manifest")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uses_portable_metadata_and_fixed_components() {
|
||||
let tmp = tempdir().expect("tempdir");
|
||||
let plugin_root = tmp.path().join("demo-plugin");
|
||||
write_agent_plugin_manifest(
|
||||
&plugin_root,
|
||||
r#",
|
||||
"version": "release-2026-07",
|
||||
"description": "Portable demo",
|
||||
"author": {"name": "Portable Author"},
|
||||
"homepage": "https://example.com/plugin",
|
||||
"keywords": ["portable"]"#,
|
||||
);
|
||||
|
||||
let manifest = load_manifest(&plugin_root);
|
||||
|
||||
assert_eq!(manifest.name, "demo-plugin");
|
||||
assert_eq!(manifest.version.as_deref(), Some("release-2026-07"));
|
||||
assert_eq!(manifest.description.as_deref(), Some("Portable demo"));
|
||||
assert_eq!(manifest.keywords, vec!["portable"]);
|
||||
assert_eq!(
|
||||
manifest.paths.skills,
|
||||
vec![
|
||||
AbsolutePathBuf::from_absolute_path_checked(plugin_root.join("skills"))
|
||||
.expect("skills path")
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
manifest.paths.mcp_servers,
|
||||
Some(PluginManifestMcpServers::Path(
|
||||
AbsolutePathBuf::from_absolute_path_checked(plugin_root.join("mcp.json"))
|
||||
.expect("MCP path")
|
||||
))
|
||||
);
|
||||
let interface = manifest.interface.expect("default portable interface");
|
||||
assert_eq!(interface.display_name.as_deref(), Some("demo-plugin"));
|
||||
assert_eq!(
|
||||
interface.short_description.as_deref(),
|
||||
Some("Portable demo")
|
||||
);
|
||||
assert_eq!(interface.long_description.as_deref(), Some("Portable demo"));
|
||||
assert_eq!(interface.developer_name.as_deref(), Some("Portable Author"));
|
||||
assert_eq!(
|
||||
interface.website_url.as_deref(),
|
||||
Some("https://example.com/plugin")
|
||||
);
|
||||
assert_eq!(interface.category.as_deref(), Some("Other"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn does_not_invent_optional_metadata() {
|
||||
let tmp = tempdir().expect("tempdir");
|
||||
let plugin_root = tmp.path().join("demo-plugin");
|
||||
write_agent_plugin_manifest(&plugin_root, "");
|
||||
|
||||
let manifest = load_manifest(&plugin_root);
|
||||
|
||||
assert_eq!(manifest.version, None);
|
||||
assert_eq!(manifest.description, None);
|
||||
let interface = manifest.interface.expect("default portable interface");
|
||||
assert_eq!(interface.display_name.as_deref(), Some("demo-plugin"));
|
||||
assert_eq!(interface.short_description, None);
|
||||
assert_eq!(interface.long_description, None);
|
||||
assert_eq!(interface.developer_name, None);
|
||||
assert_eq!(interface.website_url, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalizes_empty_optional_metadata() {
|
||||
let tmp = tempdir().expect("tempdir");
|
||||
let plugin_root = tmp.path().join("demo-plugin");
|
||||
write_agent_plugin_manifest(
|
||||
&plugin_root,
|
||||
r#",
|
||||
"version": "",
|
||||
"description": " ",
|
||||
"author": {"name": " ", "email": ""},
|
||||
"homepage": "",
|
||||
"keywords": [""]"#,
|
||||
);
|
||||
|
||||
let manifest = load_manifest(&plugin_root);
|
||||
|
||||
assert_eq!(manifest.version, None);
|
||||
assert_eq!(manifest.description, None);
|
||||
assert_eq!(manifest.keywords, vec![""]);
|
||||
let interface = manifest.interface.expect("default portable interface");
|
||||
assert_eq!(interface.short_description, None);
|
||||
assert_eq!(interface.long_description, None);
|
||||
assert_eq!(interface.developer_name, None);
|
||||
assert_eq!(interface.website_url, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_dotted_names_and_ignores_extensions() {
|
||||
let tmp = tempdir().expect("tempdir");
|
||||
let plugin_root = tmp.path().join("acme-tools");
|
||||
fs::create_dir_all(&plugin_root).expect("create plugin root");
|
||||
fs::write(
|
||||
plugin_root.join("plugin.json"),
|
||||
format!(
|
||||
r#"{{
|
||||
"$schema":"{AGENT_PLUGIN_SCHEMA_URI}",
|
||||
"name":"acme.tools",
|
||||
"extensions":{{
|
||||
"com.example.client":{{"future":true}},
|
||||
"com.example.unimplemented":"ignored"
|
||||
}}
|
||||
}}"#
|
||||
),
|
||||
)
|
||||
.expect("write manifest");
|
||||
|
||||
assert_eq!(load_manifest(&plugin_root).name, "acme.tools");
|
||||
|
||||
fs::write(
|
||||
plugin_root.join("plugin.json"),
|
||||
format!(
|
||||
r#"{{"$schema":"{AGENT_PLUGIN_SCHEMA_URI}","name":"acme.tools","extensions":false}}"#
|
||||
),
|
||||
)
|
||||
.expect("write manifest with invalid extensions");
|
||||
assert_eq!(load_manifest(&plugin_root).name, "acme.tools");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_overlong_name_and_wrong_metadata_types() {
|
||||
let tmp = tempdir().expect("tempdir");
|
||||
let plugin_root = tmp.path().join("demo-plugin");
|
||||
fs::create_dir_all(&plugin_root).expect("create plugin root");
|
||||
fs::write(
|
||||
plugin_root.join("plugin.json"),
|
||||
format!(
|
||||
r#"{{"$schema":"{AGENT_PLUGIN_SCHEMA_URI}","name":"{}"}}"#,
|
||||
"a".repeat(65)
|
||||
),
|
||||
)
|
||||
.expect("write manifest");
|
||||
assert_eq!(load_plugin_manifest(&plugin_root), None);
|
||||
|
||||
fs::write(
|
||||
plugin_root.join("plugin.json"),
|
||||
format!(r#"{{"$schema":"{AGENT_PLUGIN_SCHEMA_URI}","name":"demo-plugin","homepage":42}}"#),
|
||||
)
|
||||
.expect("write manifest");
|
||||
assert_eq!(load_plugin_manifest(&plugin_root), None);
|
||||
|
||||
fs::write(
|
||||
plugin_root.join("plugin.json"),
|
||||
format!(r#"{{"$schema":"{AGENT_PLUGIN_SCHEMA_URI}","name":"demo-plugin","version":null}}"#),
|
||||
)
|
||||
.expect("write manifest");
|
||||
assert_eq!(load_plugin_manifest(&plugin_root), None);
|
||||
|
||||
fs::write(
|
||||
plugin_root.join("plugin.json"),
|
||||
format!(
|
||||
r#"{{"$schema":"{AGENT_PLUGIN_SCHEMA_URI}","name":"demo-plugin","author":{{"name":null}}}}"#
|
||||
),
|
||||
)
|
||||
.expect("write manifest");
|
||||
assert_eq!(load_plugin_manifest(&plugin_root), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_codex_overlay_keeps_portable_components_fixed() {
|
||||
let tmp = tempdir().expect("tempdir");
|
||||
let plugin_root = tmp.path().join("demo-plugin");
|
||||
write_agent_plugin_manifest(
|
||||
&plugin_root,
|
||||
r#",
|
||||
"version": "portable-version",
|
||||
"description": "Portable description""#,
|
||||
);
|
||||
fs::create_dir_all(plugin_root.join(".codex-plugin")).expect("create overlay dir");
|
||||
fs::write(
|
||||
plugin_root.join(".codex-plugin/plugin.json"),
|
||||
r#"{
|
||||
"name": "different-name",
|
||||
"version": "9.9.9",
|
||||
"description": "Codex description",
|
||||
"skills": [],
|
||||
"mcpServers": null,
|
||||
"interface": {"displayName": "Codex Demo"}
|
||||
}"#,
|
||||
)
|
||||
.expect("write overlay");
|
||||
|
||||
let manifest = load_manifest(&plugin_root);
|
||||
|
||||
assert_eq!(manifest.name, "demo-plugin");
|
||||
assert_eq!(manifest.version.as_deref(), Some("portable-version"));
|
||||
assert_eq!(
|
||||
manifest.description.as_deref(),
|
||||
Some("Portable description")
|
||||
);
|
||||
assert_eq!(
|
||||
manifest.paths.skills,
|
||||
vec![
|
||||
AbsolutePathBuf::from_absolute_path_checked(plugin_root.join("skills"))
|
||||
.expect("skills path")
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
manifest.paths.mcp_servers,
|
||||
Some(PluginManifestMcpServers::Path(
|
||||
AbsolutePathBuf::from_absolute_path_checked(plugin_root.join("mcp.json"))
|
||||
.expect("MCP path")
|
||||
))
|
||||
);
|
||||
assert_eq!(
|
||||
manifest
|
||||
.interface
|
||||
.and_then(|interface| interface.display_name),
|
||||
Some("Codex Demo".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_openai_extension_precedes_legacy_overlay() {
|
||||
let tmp = tempdir().expect("tempdir");
|
||||
let plugin_root = tmp.path().join("demo-plugin");
|
||||
write_agent_plugin_manifest(
|
||||
&plugin_root,
|
||||
r#",
|
||||
"extensions": {
|
||||
"com.openai": {
|
||||
"interface": {"displayName": "Inline Codex"}
|
||||
}
|
||||
}"#,
|
||||
);
|
||||
fs::create_dir_all(plugin_root.join(".codex-plugin")).expect("create overlay dir");
|
||||
fs::write(
|
||||
plugin_root.join(".codex-plugin/plugin.json"),
|
||||
r#"{"interface":{"displayName":"Legacy Codex"}}"#,
|
||||
)
|
||||
.expect("write overlay");
|
||||
|
||||
let manifest = load_manifest(&plugin_root);
|
||||
|
||||
assert_eq!(
|
||||
manifest
|
||||
.interface
|
||||
.and_then(|interface| interface.display_name),
|
||||
Some("Inline Codex".to_string())
|
||||
);
|
||||
}
|
||||
99
akode-rs/core-plugins/src/agent_plugin_mcp_overlay.rs
Normal file
99
akode-rs/core-plugins/src/agent_plugin_mcp_overlay.rs
Normal file
@@ -0,0 +1,99 @@
|
||||
use super::load_mcp_servers_from_file;
|
||||
use super::load_mcp_servers_from_manifest_object;
|
||||
use super::plugin_mcp_config_paths;
|
||||
use crate::manifest::PluginManifestFormat;
|
||||
use crate::manifest::PluginManifestMcpServers;
|
||||
use crate::manifest::parse_plugin_manifest;
|
||||
use akode_config::types::McpServerConfig;
|
||||
use akode_config::types::McpServerTransportConfig;
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
use tracing::warn;
|
||||
|
||||
pub(super) async fn apply_codex_env_overlay(
|
||||
plugin_root: &Path,
|
||||
agent_servers: &mut HashMap<String, McpServerConfig>,
|
||||
) {
|
||||
if agent_servers.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let overlay_path = plugin_root.join(".codex-plugin/plugin.json");
|
||||
let Ok(contents) = tokio::fs::read_to_string(&overlay_path).await else {
|
||||
return;
|
||||
};
|
||||
let overlay_manifest = match parse_plugin_manifest(plugin_root, &overlay_path, &contents) {
|
||||
Ok(manifest) => manifest,
|
||||
Err(err) => {
|
||||
warn!(
|
||||
path = %overlay_path.display(),
|
||||
"failed to parse Codex Agent Plugin MCP overlay: {err}"
|
||||
);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let overlay_servers = match &overlay_manifest.paths.mcp_servers {
|
||||
Some(PluginManifestMcpServers::Object(servers)) => {
|
||||
load_mcp_servers_from_manifest_object(plugin_root, servers).mcp_servers
|
||||
}
|
||||
Some(PluginManifestMcpServers::Path(_)) | None => {
|
||||
let mut servers = HashMap::new();
|
||||
for path in plugin_mcp_config_paths(plugin_root, &overlay_manifest.paths) {
|
||||
servers.extend(
|
||||
load_mcp_servers_from_file(
|
||||
plugin_root,
|
||||
/*plugin_data_root*/ None,
|
||||
PluginManifestFormat::Legacy,
|
||||
&path,
|
||||
)
|
||||
.await
|
||||
.mcp_servers,
|
||||
);
|
||||
}
|
||||
servers
|
||||
}
|
||||
};
|
||||
|
||||
for (name, overlay_server) in overlay_servers {
|
||||
let Some(agent_server) = agent_servers.get_mut(&name) else {
|
||||
continue;
|
||||
};
|
||||
let (
|
||||
McpServerTransportConfig::Stdio { env, env_vars, .. },
|
||||
McpServerTransportConfig::Stdio {
|
||||
env_vars: mut overlay_env_vars,
|
||||
..
|
||||
},
|
||||
) = (&mut agent_server.transport, overlay_server.transport)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
|
||||
overlay_env_vars.retain(|variable| !variable.is_remote_source());
|
||||
|
||||
if let Some(env) = env {
|
||||
env.retain(|name, value| {
|
||||
let Some(reference) = value
|
||||
.strip_prefix("${")
|
||||
.and_then(|reference| reference.strip_suffix('}'))
|
||||
else {
|
||||
return true;
|
||||
};
|
||||
!overlay_env_vars.iter().any(|variable| {
|
||||
environment_names_match(name, variable.name())
|
||||
&& environment_names_match(reference, variable.name())
|
||||
})
|
||||
});
|
||||
}
|
||||
env_vars.extend(overlay_env_vars);
|
||||
}
|
||||
}
|
||||
|
||||
fn environment_names_match(left: &str, right: &str) -> bool {
|
||||
if cfg!(windows) {
|
||||
left.eq_ignore_ascii_case(right)
|
||||
} else {
|
||||
left == right
|
||||
}
|
||||
}
|
||||
108
akode-rs/core-plugins/src/artifact_operation.rs
Normal file
108
akode-rs/core-plugins/src/artifact_operation.rs
Normal file
@@ -0,0 +1,108 @@
|
||||
use crate::PluginCommandAttribution;
|
||||
use crate::command_script_arguments;
|
||||
|
||||
const PRIMARY_RUNTIME_MARKETPLACE_NAME: &str = "openai-primary-runtime";
|
||||
const MAX_EXPECTED_OUTPUT_COUNT: u32 = 100;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct ArtifactOperation {
|
||||
pub plugin_name: &'static str,
|
||||
pub script_path: &'static str,
|
||||
pub artifact_type: &'static str,
|
||||
pub operation_kind: &'static str,
|
||||
pub expected_output_count: u32,
|
||||
pub output_format: &'static str,
|
||||
}
|
||||
|
||||
struct ArtifactSkill {
|
||||
plugin_name: &'static str,
|
||||
script_path: &'static str,
|
||||
artifact_type: &'static str,
|
||||
output_formats: &'static [&'static str],
|
||||
}
|
||||
|
||||
const ARTIFACT_SKILLS: &[ArtifactSkill] = &[
|
||||
ArtifactSkill {
|
||||
plugin_name: "presentations",
|
||||
script_path: "skills/presentations/container_tools/mark_artifact_operation_started.mjs",
|
||||
artifact_type: "presentation",
|
||||
output_formats: &["ppt", "pptx"],
|
||||
},
|
||||
ArtifactSkill {
|
||||
plugin_name: "documents",
|
||||
script_path: "skills/documents/container_tools/mark_artifact_operation_started.mjs",
|
||||
artifact_type: "document",
|
||||
output_formats: &["doc", "docx"],
|
||||
},
|
||||
ArtifactSkill {
|
||||
plugin_name: "spreadsheets",
|
||||
script_path: "skills/spreadsheets/container_tools/mark_artifact_operation_started.mjs",
|
||||
artifact_type: "spreadsheet",
|
||||
output_formats: &["csv", "tsv", "xls", "xlsm", "xlsx"],
|
||||
},
|
||||
ArtifactSkill {
|
||||
plugin_name: "pdf",
|
||||
script_path: "skills/pdf/container_tools/mark_artifact_operation_started.mjs",
|
||||
artifact_type: "pdf",
|
||||
output_formats: &["pdf"],
|
||||
},
|
||||
];
|
||||
|
||||
pub fn recognize_artifact_operation(
|
||||
attribution: Option<&PluginCommandAttribution>,
|
||||
command: &[String],
|
||||
) -> Option<ArtifactOperation> {
|
||||
let attribution = attribution?;
|
||||
if attribution.plugin_id.marketplace_name != PRIMARY_RUNTIME_MARKETPLACE_NAME {
|
||||
return None;
|
||||
}
|
||||
let skill = ARTIFACT_SKILLS.iter().find(|skill| {
|
||||
attribution.plugin_id.plugin_name == skill.plugin_name
|
||||
&& attribution.normalized_relative_path == skill.script_path
|
||||
})?;
|
||||
let script_arguments = command_script_arguments(command)?;
|
||||
let [
|
||||
operation_kind_flag,
|
||||
operation_kind,
|
||||
expected_output_count_flag,
|
||||
expected_output_count,
|
||||
output_format_flag,
|
||||
output_format,
|
||||
] = script_arguments.as_slice()
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
if operation_kind_flag != "--operation-kind"
|
||||
|| expected_output_count_flag != "--expected-output-count"
|
||||
|| output_format_flag != "--output-format"
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let operation_kind = match operation_kind.as_str() {
|
||||
"create" => "create",
|
||||
"edit" => "edit",
|
||||
_ => return None,
|
||||
};
|
||||
let expected_output_count = expected_output_count.parse::<u32>().ok()?;
|
||||
if !(1..=MAX_EXPECTED_OUTPUT_COUNT).contains(&expected_output_count) {
|
||||
return None;
|
||||
}
|
||||
let output_format = skill
|
||||
.output_formats
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|known_format| known_format.eq_ignore_ascii_case(output_format))?;
|
||||
|
||||
Some(ArtifactOperation {
|
||||
plugin_name: skill.plugin_name,
|
||||
script_path: skill.script_path,
|
||||
artifact_type: skill.artifact_type,
|
||||
operation_kind,
|
||||
expected_output_count,
|
||||
output_format,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "artifact_operation_tests.rs"]
|
||||
mod tests;
|
||||
151
akode-rs/core-plugins/src/artifact_operation_tests.rs
Normal file
151
akode-rs/core-plugins/src/artifact_operation_tests.rs
Normal file
@@ -0,0 +1,151 @@
|
||||
use super::*;
|
||||
use akode_plugin::PluginId;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn recognizes_supported_artifact_markers() {
|
||||
for skill in ARTIFACT_SKILLS {
|
||||
for operation_kind in ["create", "edit"] {
|
||||
let attribution = attribution(skill.plugin_name, skill.script_path);
|
||||
assert_eq!(
|
||||
recognize_artifact_operation(
|
||||
Some(&attribution),
|
||||
&marker_command(
|
||||
skill.script_path,
|
||||
operation_kind,
|
||||
"2",
|
||||
skill.output_formats[0],
|
||||
),
|
||||
),
|
||||
Some(ArtifactOperation {
|
||||
plugin_name: skill.plugin_name,
|
||||
script_path: skill.script_path,
|
||||
artifact_type: skill.artifact_type,
|
||||
operation_kind,
|
||||
expected_output_count: 2,
|
||||
output_format: skill.output_formats[0],
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_untrusted_mismatched_or_invalid_markers() {
|
||||
let presentation = &ARTIFACT_SKILLS[0];
|
||||
let cases = [
|
||||
(
|
||||
None,
|
||||
marker_command(presentation.script_path, "create", "1", "pptx"),
|
||||
),
|
||||
(
|
||||
Some(PluginCommandAttribution {
|
||||
plugin_id: PluginId::parse("documents@openai-primary-runtime").expect("plugin id"),
|
||||
normalized_relative_path: presentation.script_path.to_string(),
|
||||
}),
|
||||
marker_command(presentation.script_path, "create", "1", "pptx"),
|
||||
),
|
||||
(
|
||||
Some(attribution(
|
||||
"presentations",
|
||||
"skills/presentations/container_tools/render_slides.mjs",
|
||||
)),
|
||||
marker_command(presentation.script_path, "create", "1", "pptx"),
|
||||
),
|
||||
(
|
||||
Some(attribution(
|
||||
presentation.plugin_name,
|
||||
presentation.script_path,
|
||||
)),
|
||||
command_with_arguments(presentation.script_path, Vec::new()),
|
||||
),
|
||||
(
|
||||
Some(attribution(
|
||||
presentation.plugin_name,
|
||||
presentation.script_path,
|
||||
)),
|
||||
command_with_arguments(
|
||||
presentation.script_path,
|
||||
marker_arguments("read", "1", "pptx"),
|
||||
),
|
||||
),
|
||||
(
|
||||
Some(attribution(
|
||||
presentation.plugin_name,
|
||||
presentation.script_path,
|
||||
)),
|
||||
command_with_arguments(
|
||||
presentation.script_path,
|
||||
marker_arguments("create", "0", "pptx"),
|
||||
),
|
||||
),
|
||||
(
|
||||
Some(attribution(
|
||||
presentation.plugin_name,
|
||||
presentation.script_path,
|
||||
)),
|
||||
command_with_arguments(
|
||||
presentation.script_path,
|
||||
marker_arguments("create", "101", "pptx"),
|
||||
),
|
||||
),
|
||||
(
|
||||
Some(attribution(
|
||||
presentation.plugin_name,
|
||||
presentation.script_path,
|
||||
)),
|
||||
command_with_arguments(
|
||||
presentation.script_path,
|
||||
marker_arguments("create", "1", "html"),
|
||||
),
|
||||
),
|
||||
];
|
||||
|
||||
for (attribution, command) in cases {
|
||||
assert_eq!(
|
||||
recognize_artifact_operation(attribution.as_ref(), &command),
|
||||
None
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn attribution(plugin_name: &str, script_path: &str) -> PluginCommandAttribution {
|
||||
PluginCommandAttribution {
|
||||
plugin_id: PluginId::parse(&format!("{plugin_name}@openai-primary-runtime"))
|
||||
.expect("plugin id"),
|
||||
normalized_relative_path: script_path.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn marker_command(
|
||||
script_path: &str,
|
||||
operation_kind: &str,
|
||||
expected_output_count: &str,
|
||||
output_format: &str,
|
||||
) -> Vec<String> {
|
||||
command_with_arguments(
|
||||
script_path,
|
||||
marker_arguments(operation_kind, expected_output_count, output_format),
|
||||
)
|
||||
}
|
||||
|
||||
fn command_with_arguments(script_path: &str, arguments: Vec<String>) -> Vec<String> {
|
||||
[vec!["node".to_string(), script_path.to_string()], arguments].concat()
|
||||
}
|
||||
|
||||
fn marker_arguments(
|
||||
operation_kind: &str,
|
||||
expected_output_count: &str,
|
||||
output_format: &str,
|
||||
) -> Vec<String> {
|
||||
[
|
||||
"--operation-kind",
|
||||
operation_kind,
|
||||
"--expected-output-count",
|
||||
expected_output_count,
|
||||
"--output-format",
|
||||
output_format,
|
||||
]
|
||||
.map(str::to_string)
|
||||
.to_vec()
|
||||
}
|
||||
139
akode-rs/core-plugins/src/catalog.rs
Normal file
139
akode-rs/core-plugins/src/catalog.rs
Normal file
@@ -0,0 +1,139 @@
|
||||
//! Source-neutral plugin catalogs, reconciliation, and source-aware enablement policy.
|
||||
|
||||
use akode_config::types::PluginConfig;
|
||||
use akode_core_plugin_common::PluginIdentity;
|
||||
use akode_utils_path_uri::PathUri;
|
||||
use serde_json::Value;
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// One source's discovery snapshot; only a complete empty catalog establishes absence.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct PluginCatalog {
|
||||
pub entries: Vec<PluginCatalogEntry>,
|
||||
pub warnings: Vec<String>,
|
||||
/// Listing omitted entries.
|
||||
pub is_partial: bool,
|
||||
}
|
||||
|
||||
/// Manifest metadata and every location that can supply the same logical plugin.
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub struct PluginCatalogEntry {
|
||||
pub id: PluginIdentity,
|
||||
pub enabled: bool,
|
||||
pub display_name: String,
|
||||
pub version: String,
|
||||
/// Raw MCP server declarations keyed by their authored names.
|
||||
pub mcp_servers: BTreeMap<String, Value>,
|
||||
pub locations: Vec<PluginSourceLocation>,
|
||||
}
|
||||
|
||||
impl PluginCatalogEntry {
|
||||
/// Disabled entries never project. Otherwise Cloud membership supplies enablement;
|
||||
/// executor-only entries require every installation's local plugin ID in the supplied
|
||||
/// config, where omitted enablement retains the configured plugin's default.
|
||||
/// A remote identity alone does not establish Cloud membership.
|
||||
pub fn is_enabled(&self, configured_plugins: &HashMap<String, PluginConfig>) -> bool {
|
||||
if !self.enabled {
|
||||
return false;
|
||||
}
|
||||
let is_cloud_plugin = self
|
||||
.locations
|
||||
.iter()
|
||||
.any(|location| matches!(location, PluginSourceLocation::Cloud { .. }));
|
||||
is_cloud_plugin
|
||||
|| self.locations.iter().all(|location| match location {
|
||||
PluginSourceLocation::Executor { plugin_id, .. } => configured_plugins
|
||||
.get(plugin_id)
|
||||
.is_some_and(|plugin| plugin.enabled.unwrap_or(true)),
|
||||
PluginSourceLocation::Cloud { .. } => true,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for PluginCatalogEntry {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
formatter
|
||||
.debug_struct("PluginCatalogEntry")
|
||||
.field("id", &self.id)
|
||||
.field("enabled", &self.enabled)
|
||||
.field("display_name", &self.display_name)
|
||||
.field("version", &self.version)
|
||||
// Declaration values can contain secrets, so only log their keys.
|
||||
.field(
|
||||
"mcp_server_names",
|
||||
&self.mcp_servers.keys().collect::<Vec<_>>(),
|
||||
)
|
||||
.field("locations", &self.locations)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// A source that can supply a plugin; cloud URIs are opaque, not local paths.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum PluginSourceLocation {
|
||||
Cloud {
|
||||
resource_uri: String,
|
||||
bundle_uri: Option<String>,
|
||||
},
|
||||
Executor {
|
||||
/// Executor environment that owns `root`.
|
||||
environment_id: String,
|
||||
/// Local `name@marketplace` key used for this installation in configuration.
|
||||
plugin_id: String,
|
||||
root: PathUri,
|
||||
},
|
||||
}
|
||||
|
||||
/// Uses Cloud membership and metadata, retaining version-matched installations in order.
|
||||
/// Unavailable or partial Cloud data preserves unmatched executor entries. Complete Cloud
|
||||
/// catalogs disable unmatched remote entries; local entries retain their enablement.
|
||||
pub fn merge_catalogs(
|
||||
executor: Option<&PluginCatalog>,
|
||||
cloud: Option<&PluginCatalog>,
|
||||
) -> PluginCatalog {
|
||||
let Some(executor) = executor else {
|
||||
return cloud.cloned().unwrap_or_default();
|
||||
};
|
||||
let Some(cloud) = cloud else {
|
||||
return executor.clone();
|
||||
};
|
||||
let mut merged = cloud.clone();
|
||||
merged.is_partial |= executor.is_partial;
|
||||
merged.warnings.extend(executor.warnings.iter().cloned());
|
||||
for installation in &executor.entries {
|
||||
if matches!(&installation.id, PluginIdentity::Local { .. }) {
|
||||
merged.entries.push(installation.clone());
|
||||
continue;
|
||||
}
|
||||
// Appended executor entries are not Cloud definitions and cannot authorize each other.
|
||||
let Some(definition) = merged.entries[..cloud.entries.len()]
|
||||
.iter_mut()
|
||||
.find(|definition| definition.id == installation.id)
|
||||
else {
|
||||
let mut unmatched = installation.clone();
|
||||
if !cloud.is_partial {
|
||||
unmatched.enabled = false;
|
||||
}
|
||||
merged.entries.push(unmatched);
|
||||
continue;
|
||||
};
|
||||
if definition.version != installation.version {
|
||||
merged.warnings.push(format!(
|
||||
"plugin `{}` has different cloud and executor versions; retaining the cloud definition",
|
||||
definition.id.as_str(),
|
||||
));
|
||||
continue;
|
||||
}
|
||||
for location in &installation.locations {
|
||||
if !definition.locations.contains(location) {
|
||||
definition.locations.push(location.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
merged
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "catalog_tests.rs"]
|
||||
mod tests;
|
||||
195
akode-rs/core-plugins/src/catalog_tests.rs
Normal file
195
akode-rs/core-plugins/src/catalog_tests.rs
Normal file
@@ -0,0 +1,195 @@
|
||||
//! Tests Cloud catalog authority, version matching, and installation reconciliation.
|
||||
|
||||
use super::PluginCatalog;
|
||||
use super::PluginCatalogEntry;
|
||||
use super::PluginIdentity;
|
||||
use super::PluginSourceLocation;
|
||||
use super::merge_catalogs;
|
||||
use akode_utils_path_uri::PathUri;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
fn cloud_plugin(remote_id: &str) -> PluginCatalogEntry {
|
||||
PluginCatalogEntry {
|
||||
enabled: true,
|
||||
id: PluginIdentity::Remote {
|
||||
remote_plugin_id: remote_id.to_string(),
|
||||
},
|
||||
display_name: "Example".to_string(),
|
||||
version: "1.0.0".to_string(),
|
||||
mcp_servers: BTreeMap::from([(
|
||||
"example".to_string(),
|
||||
serde_json::json!({"command":"node","args":["server.js"]}),
|
||||
)]),
|
||||
locations: vec![PluginSourceLocation::Cloud {
|
||||
resource_uri: format!("plugin://{remote_id}"),
|
||||
bundle_uri: None,
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
fn executor_plugin(remote_id: &str, environment_id: &str) -> anyhow::Result<PluginCatalogEntry> {
|
||||
let mut entry = cloud_plugin(remote_id);
|
||||
entry.locations = vec![PluginSourceLocation::Executor {
|
||||
environment_id: environment_id.to_string(),
|
||||
plugin_id: "example@marketplace".to_string(),
|
||||
root: PathUri::parse("file:///plugins/example/1.0.0")?,
|
||||
}];
|
||||
Ok(entry)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merged_catalog_prefers_cloud_and_matches_executor_versions() -> anyhow::Result<()> {
|
||||
let definition = cloud_plugin("plugin_a");
|
||||
let mut first = executor_plugin("plugin_a", "executor-a")?;
|
||||
first.display_name = "Installed display name".to_string();
|
||||
first.mcp_servers.clear();
|
||||
let second = executor_plugin("plugin_a", "executor-b")?;
|
||||
let mut incompatible = executor_plugin("plugin_a", "executor-c")?;
|
||||
incompatible.version = "2.0.0".to_string();
|
||||
let mut expected = definition.clone();
|
||||
expected.locations.extend(first.locations.clone());
|
||||
expected.locations.extend(second.locations.clone());
|
||||
|
||||
let executor = PluginCatalog {
|
||||
entries: vec![first.clone(), first, second, incompatible],
|
||||
warnings: vec!["executor warning".to_string()],
|
||||
..Default::default()
|
||||
};
|
||||
let cloud = PluginCatalog {
|
||||
entries: vec![definition],
|
||||
warnings: vec!["cloud warning".to_string()],
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
merge_catalogs(Some(&executor), Some(&cloud)),
|
||||
PluginCatalog {
|
||||
entries: vec![expected],
|
||||
warnings: vec![
|
||||
"cloud warning".to_string(),
|
||||
"executor warning".to_string(),
|
||||
"plugin `plugin_a` has different cloud and executor versions; retaining the cloud definition"
|
||||
.to_string(),
|
||||
],
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cloud_catalog_controls_remote_plugins_but_preserves_local_plugins() -> anyhow::Result<()> {
|
||||
let installed = executor_plugin("plugin_a", "executor-a")?;
|
||||
let mut local = executor_plugin("plugin_a", "executor-b")?;
|
||||
local.id = PluginIdentity::Local {
|
||||
plugin_id: "example@marketplace".to_string(),
|
||||
};
|
||||
let executor = PluginCatalog {
|
||||
entries: vec![installed.clone(), local.clone()],
|
||||
..Default::default()
|
||||
};
|
||||
let local_only = PluginCatalog {
|
||||
entries: vec![local.clone()],
|
||||
..Default::default()
|
||||
};
|
||||
// An available Cloud catalog controls remote entries; local entries are unaffected.
|
||||
let mut other_installation = executor_plugin("plugin_a", "executor-c")?;
|
||||
other_installation.version = "2.0.0".to_string();
|
||||
let unmatched = PluginCatalog {
|
||||
entries: vec![installed.clone(), other_installation.clone(), local.clone()],
|
||||
..Default::default()
|
||||
};
|
||||
let mut disabled = installed.clone();
|
||||
disabled.enabled = false;
|
||||
other_installation.enabled = false;
|
||||
let disabled_entries = vec![disabled, other_installation, local.clone()];
|
||||
assert_eq!(merge_catalogs(Some(&unmatched), /*cloud*/ None), unmatched);
|
||||
let explicitly_disabled = PluginCatalog {
|
||||
entries: disabled_entries.clone(),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
merge_catalogs(Some(&explicitly_disabled), /*cloud*/ None),
|
||||
explicitly_disabled,
|
||||
);
|
||||
for cloud in [
|
||||
Some(PluginCatalog::default()),
|
||||
Some(PluginCatalog {
|
||||
is_partial: true,
|
||||
warnings: vec!["partial cloud listing".to_string()],
|
||||
..Default::default()
|
||||
}),
|
||||
] {
|
||||
assert_eq!(
|
||||
merge_catalogs(Some(&unmatched), cloud.as_ref()),
|
||||
PluginCatalog {
|
||||
entries: if cloud.as_ref().is_some_and(|catalog| catalog.is_partial) {
|
||||
unmatched.entries.clone()
|
||||
} else {
|
||||
disabled_entries.clone()
|
||||
},
|
||||
is_partial: cloud.as_ref().is_some_and(|catalog| catalog.is_partial),
|
||||
warnings: cloud.map(|catalog| catalog.warnings).unwrap_or_default(),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
let definition = cloud_plugin("plugin_a");
|
||||
let cloud = PluginCatalog {
|
||||
entries: vec![definition.clone()],
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(merge_catalogs(/*executor*/ None, Some(&cloud)), cloud);
|
||||
assert_eq!(
|
||||
merge_catalogs(/*executor*/ None, /*cloud*/ None),
|
||||
PluginCatalog::default(),
|
||||
);
|
||||
let mut authorized = definition.clone();
|
||||
authorized.locations.extend(installed.locations);
|
||||
assert_eq!(
|
||||
merge_catalogs(Some(&executor), Some(&cloud)),
|
||||
PluginCatalog {
|
||||
entries: vec![authorized, local.clone()],
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
|
||||
// Removing an installation preserves its Cloud definition without the executor route.
|
||||
assert_eq!(
|
||||
merge_catalogs(Some(&local_only), Some(&cloud)),
|
||||
PluginCatalog {
|
||||
entries: vec![definition, local],
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_cloud_merges_known_plugins_and_preserves_unmatched_enablement() -> anyhow::Result<()> {
|
||||
let definition = cloud_plugin("matched");
|
||||
let matched = executor_plugin("matched", "executor-a")?;
|
||||
let mut denied = executor_plugin("denied", "executor-a")?;
|
||||
denied.enabled = false;
|
||||
let unmatched = executor_plugin("unmatched", "executor-a")?;
|
||||
let executor = PluginCatalog {
|
||||
entries: vec![matched.clone(), denied.clone(), unmatched.clone()],
|
||||
..Default::default()
|
||||
};
|
||||
let cloud = PluginCatalog {
|
||||
entries: vec![definition.clone()],
|
||||
is_partial: true,
|
||||
..Default::default()
|
||||
};
|
||||
let mut expected = definition;
|
||||
expected.locations.extend(matched.locations);
|
||||
assert_eq!(
|
||||
merge_catalogs(Some(&executor), Some(&cloud)),
|
||||
PluginCatalog {
|
||||
entries: vec![expected, denied, unmatched],
|
||||
is_partial: true,
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
438
akode-rs/core-plugins/src/command_migration.rs
Normal file
438
akode-rs/core-plugins/src/command_migration.rs
Normal file
@@ -0,0 +1,438 @@
|
||||
mod plugin;
|
||||
mod render;
|
||||
|
||||
use render::rewrite_terms;
|
||||
use render::slugify_name;
|
||||
use render::yaml_string;
|
||||
use serde_yaml::Value as YamlValue;
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
const COMMAND_SKILL_PREFIX: &str = "source-command";
|
||||
const MAX_SKILL_NAME_LEN: usize = 64;
|
||||
|
||||
pub(crate) use plugin::migrate_plugin_commands;
|
||||
|
||||
/// Describes source-specific terms that should be rewritten in migrated command skills.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct RewriteProfile {
|
||||
doc_file_name: &'static str,
|
||||
term_variants: &'static [&'static str],
|
||||
case_sensitive_term_variants: &'static [&'static str],
|
||||
}
|
||||
|
||||
impl RewriteProfile {
|
||||
pub const fn new(doc_file_name: &'static str, term_variants: &'static [&'static str]) -> Self {
|
||||
Self {
|
||||
doc_file_name,
|
||||
term_variants,
|
||||
case_sensitive_term_variants: &[],
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn with_case_sensitive_term_variants(
|
||||
mut self,
|
||||
term_variants: &'static [&'static str],
|
||||
) -> Self {
|
||||
self.case_sensitive_term_variants = term_variants;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Controls how migrated commands obtain the description required by a Codex skill.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum CommandDescriptionMode {
|
||||
/// Skip source commands that do not declare a non-empty frontmatter description.
|
||||
RequireFrontmatter,
|
||||
/// Derive a stable description from the source command name when frontmatter is absent.
|
||||
UseSourceNameFallback,
|
||||
}
|
||||
|
||||
/// Describes source-specific command migration behavior.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct CommandMigrationProfile {
|
||||
rewrite_profile: RewriteProfile,
|
||||
description_mode: CommandDescriptionMode,
|
||||
}
|
||||
|
||||
impl CommandMigrationProfile {
|
||||
pub const fn new(
|
||||
rewrite_profile: RewriteProfile,
|
||||
description_mode: CommandDescriptionMode,
|
||||
) -> Self {
|
||||
Self {
|
||||
rewrite_profile,
|
||||
description_mode,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct ParsedCommand {
|
||||
description: Option<String>,
|
||||
body: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
struct CommandSource {
|
||||
source_file: PathBuf,
|
||||
name: String,
|
||||
source_name: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum CommandSkillSizeLimit {
|
||||
Unbounded,
|
||||
MaxBytes(usize),
|
||||
}
|
||||
|
||||
pub fn count_missing_commands_with_profile(
|
||||
source_commands: &Path,
|
||||
target_skills: &Path,
|
||||
profile: CommandMigrationProfile,
|
||||
) -> io::Result<usize> {
|
||||
Ok(missing_command_names_with_profile(source_commands, target_skills, profile)?.len())
|
||||
}
|
||||
|
||||
pub fn missing_command_names_with_profile(
|
||||
source_commands: &Path,
|
||||
target_skills: &Path,
|
||||
profile: CommandMigrationProfile,
|
||||
) -> io::Result<Vec<String>> {
|
||||
Ok(
|
||||
unique_supported_command_sources(source_commands, profile.description_mode)?
|
||||
.into_iter()
|
||||
.filter(|source| !target_skills.join(&source.name).exists())
|
||||
.map(|source| source.name)
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn import_commands_with_profile(
|
||||
source_commands: &Path,
|
||||
target_skills: &Path,
|
||||
profile: CommandMigrationProfile,
|
||||
) -> io::Result<Vec<String>> {
|
||||
if !source_commands.is_dir() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
fs::create_dir_all(target_skills)?;
|
||||
import_command_sources(
|
||||
unique_supported_command_sources(source_commands, profile.description_mode)?,
|
||||
target_skills,
|
||||
profile,
|
||||
CommandSkillSizeLimit::Unbounded,
|
||||
)
|
||||
}
|
||||
|
||||
fn import_command_sources(
|
||||
command_sources: Vec<CommandSource>,
|
||||
target_skills: &Path,
|
||||
profile: CommandMigrationProfile,
|
||||
size_limit: CommandSkillSizeLimit,
|
||||
) -> io::Result<Vec<String>> {
|
||||
if command_sources.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
let mut imported = Vec::new();
|
||||
for CommandSource {
|
||||
source_file,
|
||||
name,
|
||||
source_name,
|
||||
} in command_sources
|
||||
{
|
||||
let document = parse_command(&source_file)?;
|
||||
let target_dir = target_skills.join(&name);
|
||||
if target_dir.exists() {
|
||||
continue;
|
||||
}
|
||||
let Some(description) =
|
||||
command_skill_description(&document, &source_name, profile.description_mode)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let rendered = render_command_skill(
|
||||
&document.body,
|
||||
&name,
|
||||
&description,
|
||||
&source_name,
|
||||
profile.rewrite_profile,
|
||||
);
|
||||
if let CommandSkillSizeLimit::MaxBytes(max_bytes) = size_limit
|
||||
&& rendered.len() > max_bytes
|
||||
{
|
||||
continue;
|
||||
}
|
||||
fs::create_dir_all(&target_dir)?;
|
||||
fs::write(target_dir.join("SKILL.md"), rendered)?;
|
||||
imported.push(name);
|
||||
}
|
||||
|
||||
Ok(imported)
|
||||
}
|
||||
|
||||
fn unique_supported_command_sources(
|
||||
source_commands: &Path,
|
||||
description_mode: CommandDescriptionMode,
|
||||
) -> io::Result<Vec<CommandSource>> {
|
||||
Ok(unique_command_sources(supported_command_sources(
|
||||
source_commands,
|
||||
description_mode,
|
||||
)?))
|
||||
}
|
||||
|
||||
fn supported_command_sources(
|
||||
source_commands: &Path,
|
||||
description_mode: CommandDescriptionMode,
|
||||
) -> io::Result<Vec<CommandSource>> {
|
||||
let mut sources = Vec::new();
|
||||
for source_file in command_source_files(source_commands)? {
|
||||
let document = parse_command(&source_file)?;
|
||||
let source_name = command_source_name(source_commands, &source_file);
|
||||
let Some(name) = command_skill_name_if_supported(
|
||||
&source_name,
|
||||
&source_file,
|
||||
&document,
|
||||
description_mode,
|
||||
) else {
|
||||
continue;
|
||||
};
|
||||
sources.push(CommandSource {
|
||||
source_file,
|
||||
name,
|
||||
source_name,
|
||||
});
|
||||
}
|
||||
Ok(sources)
|
||||
}
|
||||
|
||||
fn unique_command_sources(command_sources: Vec<CommandSource>) -> Vec<CommandSource> {
|
||||
let mut by_name = BTreeMap::<String, BTreeMap<PathBuf, String>>::new();
|
||||
for source in command_sources {
|
||||
by_name
|
||||
.entry(source.name)
|
||||
.or_default()
|
||||
.insert(source.source_file, source.source_name);
|
||||
}
|
||||
|
||||
by_name
|
||||
.into_iter()
|
||||
.filter_map(|(name, source_files)| {
|
||||
let mut source_files = source_files.into_iter();
|
||||
let (source_file, source_name) = source_files.next()?;
|
||||
if source_files.next().is_some() {
|
||||
return None;
|
||||
}
|
||||
Some(CommandSource {
|
||||
source_file,
|
||||
name,
|
||||
source_name,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn command_source_files(source_commands: &Path) -> io::Result<Vec<PathBuf>> {
|
||||
if source_commands.is_file() {
|
||||
return Ok(
|
||||
if source_commands.extension().and_then(|ext| ext.to_str()) == Some("md") {
|
||||
vec![source_commands.to_path_buf()]
|
||||
} else {
|
||||
Vec::new()
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
let mut files = Vec::new();
|
||||
collect_markdown_files(source_commands, &mut files)?;
|
||||
files.sort();
|
||||
Ok(files)
|
||||
}
|
||||
|
||||
fn collect_markdown_files(dir: &Path, files: &mut Vec<PathBuf>) -> io::Result<()> {
|
||||
if !dir.is_dir() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
for entry in fs::read_dir(dir)? {
|
||||
let entry = entry?;
|
||||
let path = entry.path();
|
||||
let file_type = entry.file_type()?;
|
||||
if file_type.is_dir() {
|
||||
collect_markdown_files(&path, files)?;
|
||||
} else if file_type.is_file() && path.extension().and_then(|ext| ext.to_str()) == Some("md")
|
||||
{
|
||||
files.push(path);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn parse_command(source_file: &Path) -> io::Result<ParsedCommand> {
|
||||
Ok(parse_command_content(&fs::read_to_string(source_file)?))
|
||||
}
|
||||
|
||||
fn parse_command_content(content: &str) -> ParsedCommand {
|
||||
let Some(rest) = content
|
||||
.strip_prefix("---\n")
|
||||
.or_else(|| content.strip_prefix("---\r\n"))
|
||||
else {
|
||||
return ParsedCommand {
|
||||
description: None,
|
||||
body: content.to_string(),
|
||||
};
|
||||
};
|
||||
let Some((end, body_start)) = frontmatter_end(rest) else {
|
||||
return ParsedCommand {
|
||||
description: None,
|
||||
body: content.to_string(),
|
||||
};
|
||||
};
|
||||
|
||||
ParsedCommand {
|
||||
description: parse_command_description(&rest[..end]),
|
||||
body: rest[body_start..].to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn frontmatter_end(rest: &str) -> Option<(usize, usize)> {
|
||||
[
|
||||
"\r\n---\r\n",
|
||||
"\r\n---\n",
|
||||
"\n---\r\n",
|
||||
"\n---\n",
|
||||
"\r\n---",
|
||||
"\n---",
|
||||
]
|
||||
.into_iter()
|
||||
.filter_map(|delimiter| rest.find(delimiter).map(|end| (end, end + delimiter.len())))
|
||||
.min_by_key(|(end, _body_start)| *end)
|
||||
}
|
||||
|
||||
fn parse_command_description(raw_frontmatter: &str) -> Option<String> {
|
||||
let parsed: YamlValue = serde_yaml::from_str(raw_frontmatter).ok()?;
|
||||
let mapping = parsed.as_mapping()?;
|
||||
mapping.iter().find_map(|(key, value)| {
|
||||
if key.as_str()?.trim() == "description" {
|
||||
yaml_scalar(value)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn yaml_scalar(value: &YamlValue) -> Option<String> {
|
||||
match value {
|
||||
YamlValue::String(value) => Some(value.trim().to_string()),
|
||||
YamlValue::Bool(value) => Some(value.to_string()),
|
||||
YamlValue::Number(value) => Some(value.to_string()),
|
||||
YamlValue::Null | YamlValue::Sequence(_) | YamlValue::Mapping(_) | YamlValue::Tagged(_) => {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn command_skill_name(source_name: &str) -> String {
|
||||
slugify_name(&format!("{COMMAND_SKILL_PREFIX}-{source_name}"))
|
||||
}
|
||||
|
||||
fn command_skill_name_if_supported(
|
||||
source_name: &str,
|
||||
source_file: &Path,
|
||||
document: &ParsedCommand,
|
||||
description_mode: CommandDescriptionMode,
|
||||
) -> Option<String> {
|
||||
if source_file.file_stem().and_then(|stem| stem.to_str()) == Some("README") {
|
||||
return None;
|
||||
}
|
||||
command_skill_description(document, source_name, description_mode)?;
|
||||
let name = command_skill_name(source_name);
|
||||
if name.chars().count() > MAX_SKILL_NAME_LEN
|
||||
|| has_unsupported_command_template_features(&document.body)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(name)
|
||||
}
|
||||
|
||||
fn command_skill_description(
|
||||
document: &ParsedCommand,
|
||||
source_name: &str,
|
||||
description_mode: CommandDescriptionMode,
|
||||
) -> Option<String> {
|
||||
document
|
||||
.description
|
||||
.as_deref()
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
.map(ToOwned::to_owned)
|
||||
.or_else(|| match description_mode {
|
||||
CommandDescriptionMode::RequireFrontmatter => None,
|
||||
CommandDescriptionMode::UseSourceNameFallback => {
|
||||
Some(format!("Migrated source command `{source_name}`"))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn command_source_name(source_commands: &Path, source_file: &Path) -> String {
|
||||
if source_commands.is_file() {
|
||||
return source_file
|
||||
.file_stem()
|
||||
.and_then(|stem| stem.to_str())
|
||||
.unwrap_or_default()
|
||||
.to_string();
|
||||
}
|
||||
source_file
|
||||
.strip_prefix(source_commands)
|
||||
.unwrap_or(source_file)
|
||||
.with_extension("")
|
||||
.components()
|
||||
.filter_map(|component| component.as_os_str().to_str())
|
||||
.collect::<Vec<_>>()
|
||||
.join("-")
|
||||
}
|
||||
|
||||
fn render_command_skill(
|
||||
body: &str,
|
||||
name: &str,
|
||||
description: &str,
|
||||
source_name: &str,
|
||||
rewrite_profile: RewriteProfile,
|
||||
) -> String {
|
||||
let body = rewrite_terms(body.trim(), rewrite_profile);
|
||||
let template_body = if body.is_empty() {
|
||||
"No command template body was found.".to_string()
|
||||
} else {
|
||||
body
|
||||
};
|
||||
format!(
|
||||
"---\nname: {}\ndescription: {}\n---\n\n# {name}\n\nUse this skill when the user asks to run the migrated source command `{source_name}`.\n\n## Command Template\n\n{template_body}\n",
|
||||
yaml_string(name),
|
||||
yaml_string(&rewrite_terms(description, rewrite_profile)),
|
||||
)
|
||||
}
|
||||
|
||||
fn has_unsupported_command_template_features(template: &str) -> bool {
|
||||
template.contains("$ARGUMENTS")
|
||||
|| contains_numbered_argument_placeholder(template)
|
||||
|| (template.contains("{{") && template.contains("}}"))
|
||||
|| template.contains("!`")
|
||||
|| template.contains("! `")
|
||||
|| template
|
||||
.split_whitespace()
|
||||
.any(|token| token.strip_prefix('@').is_some_and(|rest| !rest.is_empty()))
|
||||
}
|
||||
|
||||
fn contains_numbered_argument_placeholder(template: &str) -> bool {
|
||||
let bytes = template.as_bytes();
|
||||
bytes
|
||||
.windows(2)
|
||||
.any(|window| window[0] == b'$' && window[1].is_ascii_digit())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "command_migration_tests.rs"]
|
||||
mod tests;
|
||||
53
akode-rs/core-plugins/src/command_migration/plugin.rs
Normal file
53
akode-rs/core-plugins/src/command_migration/plugin.rs
Normal file
@@ -0,0 +1,53 @@
|
||||
use super::CommandDescriptionMode;
|
||||
use super::CommandMigrationProfile;
|
||||
use super::CommandSkillSizeLimit;
|
||||
use super::CommandSource;
|
||||
use super::RewriteProfile;
|
||||
use super::import_command_sources;
|
||||
use super::supported_command_sources;
|
||||
use super::unique_command_sources;
|
||||
use crate::manifest::load_plugin_command_paths;
|
||||
use akode_utils_absolute_path::AbsolutePathBuf;
|
||||
use akode_utils_plugins::migrated_command_skills_root;
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
|
||||
const PLUGIN_COMMANDS_DIR: &str = "commands";
|
||||
const MAX_MIGRATED_COMMAND_SKILL_BYTES: usize = 4_000;
|
||||
|
||||
const PLUGIN_REWRITE_PROFILE: RewriteProfile = RewriteProfile::new("AGENTS.md", &[]);
|
||||
const PLUGIN_MIGRATION_PROFILE: CommandMigrationProfile = CommandMigrationProfile::new(
|
||||
PLUGIN_REWRITE_PROFILE,
|
||||
CommandDescriptionMode::RequireFrontmatter,
|
||||
);
|
||||
|
||||
pub(crate) fn migrate_plugin_commands(plugin_root: &Path) -> io::Result<()> {
|
||||
let absolute_plugin_root = AbsolutePathBuf::from_absolute_path(plugin_root)?;
|
||||
let target_skills = migrated_command_skills_root(&absolute_plugin_root);
|
||||
if target_skills.is_dir() {
|
||||
fs::remove_dir_all(&target_skills)?;
|
||||
} else if target_skills.exists() {
|
||||
fs::remove_file(&target_skills)?;
|
||||
}
|
||||
import_command_sources(
|
||||
plugin_command_sources(plugin_root)?,
|
||||
&target_skills,
|
||||
PLUGIN_MIGRATION_PROFILE,
|
||||
CommandSkillSizeLimit::MaxBytes(MAX_MIGRATED_COMMAND_SKILL_BYTES),
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn plugin_command_sources(plugin_root: &Path) -> io::Result<Vec<CommandSource>> {
|
||||
let command_paths = load_plugin_command_paths(plugin_root)?
|
||||
.unwrap_or_else(|| vec![plugin_root.join(PLUGIN_COMMANDS_DIR)]);
|
||||
let mut sources = Vec::new();
|
||||
for command_path in command_paths {
|
||||
sources.extend(supported_command_sources(
|
||||
&command_path,
|
||||
CommandDescriptionMode::RequireFrontmatter,
|
||||
)?);
|
||||
}
|
||||
Ok(unique_command_sources(sources))
|
||||
}
|
||||
95
akode-rs/core-plugins/src/command_migration/render.rs
Normal file
95
akode-rs/core-plugins/src/command_migration/render.rs
Normal file
@@ -0,0 +1,95 @@
|
||||
use super::RewriteProfile;
|
||||
|
||||
pub(super) fn rewrite_terms(content: &str, profile: RewriteProfile) -> String {
|
||||
let mut rewritten =
|
||||
replace_case_insensitive_with_boundaries(content, profile.doc_file_name, "AGENTS.md");
|
||||
for from in profile.term_variants {
|
||||
rewritten = replace_case_insensitive_with_boundaries(&rewritten, from, "Codex");
|
||||
}
|
||||
for from in profile.case_sensitive_term_variants {
|
||||
rewritten = replace_with_boundaries(&rewritten, from, "Codex");
|
||||
}
|
||||
rewritten
|
||||
}
|
||||
|
||||
fn replace_with_boundaries(input: &str, needle: &str, replacement: &str) -> String {
|
||||
if needle.is_empty() {
|
||||
return input.to_string();
|
||||
}
|
||||
|
||||
replace_with_boundaries_impl(input, needle, replacement, input)
|
||||
}
|
||||
|
||||
fn replace_case_insensitive_with_boundaries(
|
||||
input: &str,
|
||||
needle: &str,
|
||||
replacement: &str,
|
||||
) -> String {
|
||||
let needle_lower = needle.to_ascii_lowercase();
|
||||
if needle_lower.is_empty() {
|
||||
return input.to_string();
|
||||
}
|
||||
let haystack_lower = input.to_ascii_lowercase();
|
||||
replace_with_boundaries_impl(input, &needle_lower, replacement, &haystack_lower)
|
||||
}
|
||||
|
||||
fn replace_with_boundaries_impl(
|
||||
input: &str,
|
||||
needle: &str,
|
||||
replacement: &str,
|
||||
searchable_input: &str,
|
||||
) -> String {
|
||||
let bytes = input.as_bytes();
|
||||
let mut output = String::with_capacity(input.len());
|
||||
let mut last_emitted = 0usize;
|
||||
let mut search_start = 0usize;
|
||||
|
||||
while let Some(relative_pos) = searchable_input[search_start..].find(needle) {
|
||||
let start = search_start + relative_pos;
|
||||
let end = start + needle.len();
|
||||
let boundary_before = start == 0 || !is_word_byte(bytes[start - 1]);
|
||||
let boundary_after = end == bytes.len() || !is_word_byte(bytes[end]);
|
||||
|
||||
if boundary_before && boundary_after {
|
||||
output.push_str(&input[last_emitted..start]);
|
||||
output.push_str(replacement);
|
||||
last_emitted = end;
|
||||
}
|
||||
search_start = start + 1;
|
||||
}
|
||||
|
||||
if last_emitted == 0 {
|
||||
return input.to_string();
|
||||
}
|
||||
output.push_str(&input[last_emitted..]);
|
||||
output
|
||||
}
|
||||
|
||||
pub(super) fn yaml_string(value: &str) -> String {
|
||||
format!("\"{}\"", value.replace('\\', "\\\\").replace('"', "\\\""))
|
||||
}
|
||||
|
||||
pub(super) fn slugify_name(value: &str) -> String {
|
||||
let mut slug = String::new();
|
||||
let mut last_was_dash = false;
|
||||
for ch in value.chars() {
|
||||
if ch.is_ascii_alphanumeric() {
|
||||
slug.push(ch.to_ascii_lowercase());
|
||||
last_was_dash = false;
|
||||
} else if !last_was_dash {
|
||||
slug.push('-');
|
||||
last_was_dash = true;
|
||||
}
|
||||
}
|
||||
|
||||
let slug = slug.trim_matches('-').to_string();
|
||||
if slug.is_empty() {
|
||||
"migrated".to_string()
|
||||
} else {
|
||||
slug
|
||||
}
|
||||
}
|
||||
|
||||
fn is_word_byte(byte: u8) -> bool {
|
||||
byte.is_ascii_alphanumeric() || byte == b'_'
|
||||
}
|
||||
146
akode-rs/core-plugins/src/command_migration_tests.rs
Normal file
146
akode-rs/core-plugins/src/command_migration_tests.rs
Normal file
@@ -0,0 +1,146 @@
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
const TEST_REWRITE_PROFILE: RewriteProfile = RewriteProfile::new(
|
||||
"CLAUDE.md",
|
||||
&[
|
||||
"claude code",
|
||||
"claude-code",
|
||||
"claude_code",
|
||||
"claudecode",
|
||||
"claude",
|
||||
],
|
||||
);
|
||||
|
||||
#[test]
|
||||
fn command_skill_names_must_fit_codex_skill_loader_limit() {
|
||||
let source_name = "this-is-a-deeply-nested-command-with-a-very-long-name";
|
||||
let file = Path::new("commands/this/is/a/deeply/nested/command/with/a/very/long/name.md");
|
||||
let document = parse_command_content("---\ndescription: Review PR\n---\nReview\n");
|
||||
|
||||
assert!(
|
||||
command_skill_name_if_supported(
|
||||
source_name,
|
||||
file,
|
||||
&document,
|
||||
CommandDescriptionMode::RequireFrontmatter,
|
||||
)
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn commands_with_overlong_descriptions_are_preserved() {
|
||||
let description = "x".repeat(1025);
|
||||
let document =
|
||||
parse_command_content(&format!("---\ndescription: {description}\n---\nReview\n"));
|
||||
|
||||
assert_eq!(
|
||||
command_skill_name_if_supported(
|
||||
"review",
|
||||
Path::new("commands/review.md"),
|
||||
&document,
|
||||
CommandDescriptionMode::RequireFrontmatter,
|
||||
),
|
||||
Some("source-command-review".to_string())
|
||||
);
|
||||
|
||||
let rendered = render_command_skill(
|
||||
&document.body,
|
||||
"source-command-review",
|
||||
&description,
|
||||
"review",
|
||||
TEST_REWRITE_PROFILE,
|
||||
);
|
||||
assert_eq!(
|
||||
parse_command_content(&rendered).description.as_deref(),
|
||||
Some(description.as_str())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn commands_with_provider_runtime_expansion_are_skipped() {
|
||||
let document = parse_command_content(
|
||||
"---\ndescription: Deploy\n---\nDeploy $ARGUMENTS from @release.yaml\n",
|
||||
);
|
||||
|
||||
assert!(
|
||||
command_skill_name_if_supported(
|
||||
"deploy",
|
||||
Path::new("commands/deploy.md"),
|
||||
&document,
|
||||
CommandDescriptionMode::RequireFrontmatter,
|
||||
)
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn commands_without_description_are_skipped() {
|
||||
let document = parse_command_content("Review the current change.\n");
|
||||
|
||||
assert!(
|
||||
command_skill_name_if_supported(
|
||||
"review",
|
||||
Path::new("commands/review.md"),
|
||||
&document,
|
||||
CommandDescriptionMode::RequireFrontmatter,
|
||||
)
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn commands_can_derive_descriptions_from_source_names() {
|
||||
let root = tempfile::TempDir::new().expect("tempdir");
|
||||
let commands = root.path().join("commands");
|
||||
let target_skills = root.path().join("skills");
|
||||
fs::create_dir_all(&commands).expect("create commands");
|
||||
fs::write(
|
||||
commands.join("review-code.md"),
|
||||
"Review the current change.\n",
|
||||
)
|
||||
.expect("write command");
|
||||
let profile = CommandMigrationProfile::new(
|
||||
TEST_REWRITE_PROFILE,
|
||||
CommandDescriptionMode::UseSourceNameFallback,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
import_commands_with_profile(&commands, &target_skills, profile).unwrap(),
|
||||
vec!["source-command-review-code".to_string()]
|
||||
);
|
||||
let rendered = fs::read_to_string(
|
||||
target_skills
|
||||
.join("source-command-review-code")
|
||||
.join("SKILL.md"),
|
||||
)
|
||||
.expect("read migrated command");
|
||||
assert!(rendered.contains("description: \"Migrated source command `review-code`\""));
|
||||
assert!(rendered.contains("Review the current change."));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_slug_collisions_are_skipped() {
|
||||
let root = tempfile::TempDir::new().expect("tempdir");
|
||||
let commands = root.path().join("commands");
|
||||
fs::create_dir_all(&commands).expect("create commands");
|
||||
fs::write(
|
||||
commands.join("foo-bar.md"),
|
||||
"---\ndescription: First\n---\nRun the first command.\n",
|
||||
)
|
||||
.expect("write first command");
|
||||
fs::write(
|
||||
commands.join("foo_bar.md"),
|
||||
"---\ndescription: Second\n---\nRun the second command.\n",
|
||||
)
|
||||
.expect("write second command");
|
||||
|
||||
assert_eq!(
|
||||
unique_supported_command_sources(&commands, CommandDescriptionMode::RequireFrontmatter,)
|
||||
.unwrap(),
|
||||
Vec::<CommandSource>::new()
|
||||
);
|
||||
}
|
||||
132
akode-rs/core-plugins/src/discoverable.rs
Normal file
132
akode-rs/core-plugins/src/discoverable.rs
Normal file
@@ -0,0 +1,132 @@
|
||||
use anyhow::Context;
|
||||
use akode_config::skill_config_rules_from_stack;
|
||||
use akode_plugin::PluginId;
|
||||
use std::collections::HashSet;
|
||||
use tracing::warn;
|
||||
|
||||
use crate::OPENAI_API_CURATED_MARKETPLACE_NAME;
|
||||
use crate::OPENAI_CURATED_MARKETPLACE_NAME;
|
||||
use crate::PluginsConfigInput;
|
||||
use crate::PluginsManager;
|
||||
use crate::marketplace::MarketplacePluginInstallPolicy;
|
||||
|
||||
const TOOL_SUGGEST_DISCOVERABLE_PLUGIN_ALLOWLIST: &[&str] = &[
|
||||
"github@openai-curated",
|
||||
"notion@openai-curated",
|
||||
"slack@openai-curated",
|
||||
"gmail@openai-curated",
|
||||
"google-calendar@openai-curated",
|
||||
"google-drive@openai-curated",
|
||||
"openai-developers@openai-curated",
|
||||
"canva@openai-curated",
|
||||
"teams@openai-curated",
|
||||
"sharepoint@openai-curated",
|
||||
"outlook-email@openai-curated",
|
||||
"outlook-calendar@openai-curated",
|
||||
"linear@openai-curated",
|
||||
"figma@openai-curated",
|
||||
"chrome@openai-bundled",
|
||||
"computer-use@openai-bundled",
|
||||
];
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ToolSuggestPluginDiscoveryInput {
|
||||
pub plugins: PluginsConfigInput,
|
||||
pub configured_plugin_ids: HashSet<String>,
|
||||
pub disabled_plugin_ids: HashSet<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ToolSuggestDiscoverablePlugin {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub description: Option<String>,
|
||||
pub has_skills: bool,
|
||||
pub mcp_server_names: Vec<String>,
|
||||
}
|
||||
|
||||
impl PluginsManager {
|
||||
pub async fn list_tool_suggest_discoverable_plugins(
|
||||
&self,
|
||||
input: &ToolSuggestPluginDiscoveryInput,
|
||||
) -> anyhow::Result<Vec<ToolSuggestDiscoverablePlugin>> {
|
||||
if !input.plugins.plugins_enabled {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
let marketplaces = self
|
||||
.list_marketplaces_for_config(&input.plugins, &[], /*include_openai_curated*/ true)
|
||||
.context("failed to list plugin marketplaces for tool suggestions")?
|
||||
.marketplaces;
|
||||
let skill_config_rules = skill_config_rules_from_stack(&input.plugins.config_layer_stack);
|
||||
|
||||
let mut discoverable_plugins = Vec::<ToolSuggestDiscoverablePlugin>::new();
|
||||
for marketplace in marketplaces {
|
||||
let marketplace_name = marketplace.name;
|
||||
|
||||
for plugin in marketplace.plugins {
|
||||
let is_configured_plugin = input.configured_plugin_ids.contains(plugin.id.as_str());
|
||||
let is_fallback_plugin = is_tool_suggest_fallback_plugin(&plugin.id);
|
||||
if plugin.installed
|
||||
|| plugin.policy.installation == MarketplacePluginInstallPolicy::NotAvailable
|
||||
|| input.disabled_plugin_ids.contains(plugin.id.as_str())
|
||||
|| (!is_configured_plugin && !is_fallback_plugin)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
let plugin_id = plugin.id.clone();
|
||||
match self
|
||||
.tool_suggest_metadata_for_marketplace_plugin(
|
||||
&marketplace_name,
|
||||
&plugin,
|
||||
&skill_config_rules,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(plugin) => {
|
||||
discoverable_plugins.push(ToolSuggestDiscoverablePlugin {
|
||||
id: plugin.config_name,
|
||||
name: plugin.display_name,
|
||||
description: plugin.description,
|
||||
has_skills: plugin.has_skills,
|
||||
mcp_server_names: plugin.mcp_server_names,
|
||||
});
|
||||
}
|
||||
Err(err) => {
|
||||
warn!("failed to load discoverable plugin suggestion {plugin_id}: {err:#}")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
discoverable_plugins.sort_by(|left, right| {
|
||||
left.name
|
||||
.cmp(&right.name)
|
||||
.then_with(|| left.id.cmp(&right.id))
|
||||
});
|
||||
Ok(discoverable_plugins)
|
||||
}
|
||||
}
|
||||
|
||||
fn is_tool_suggest_fallback_plugin(plugin_id: &str) -> bool {
|
||||
if TOOL_SUGGEST_DISCOVERABLE_PLUGIN_ALLOWLIST.contains(&plugin_id) {
|
||||
return true;
|
||||
}
|
||||
|
||||
let Ok(plugin_id) = PluginId::parse(plugin_id) else {
|
||||
return false;
|
||||
};
|
||||
if plugin_id.marketplace_name != OPENAI_API_CURATED_MARKETPLACE_NAME {
|
||||
return false;
|
||||
}
|
||||
|
||||
let default_curated_plugin_id = format!(
|
||||
"{}@{}",
|
||||
plugin_id.plugin_name, OPENAI_CURATED_MARKETPLACE_NAME
|
||||
);
|
||||
TOOL_SUGGEST_DISCOVERABLE_PLUGIN_ALLOWLIST.contains(&default_curated_plugin_id.as_str())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "discoverable_tests.rs"]
|
||||
mod tests;
|
||||
776
akode-rs/core-plugins/src/discoverable_tests.rs
Normal file
776
akode-rs/core-plugins/src/discoverable_tests.rs
Normal file
@@ -0,0 +1,776 @@
|
||||
use super::ToolSuggestDiscoverablePlugin;
|
||||
use super::ToolSuggestPluginDiscoveryInput;
|
||||
use crate::OPENAI_BUNDLED_MARKETPLACE_NAME;
|
||||
use crate::PluginInstallRequest;
|
||||
use crate::PluginsConfigInput;
|
||||
use crate::PluginsManager;
|
||||
use crate::startup_sync::curated_plugins_repo_path;
|
||||
use crate::test_support::TEST_CURATED_PLUGIN_SHA;
|
||||
use crate::test_support::load_plugins_config;
|
||||
use crate::test_support::set_test_auth_mode;
|
||||
use crate::test_support::test_auth_manager;
|
||||
use crate::test_support::test_plugins_manager;
|
||||
use crate::test_support::test_plugins_manager_with_auth_manager;
|
||||
use crate::test_support::test_plugins_manager_with_options;
|
||||
use crate::test_support::write_curated_plugin;
|
||||
use crate::test_support::write_curated_plugin_sha_with;
|
||||
use crate::test_support::write_file;
|
||||
use crate::test_support::write_openai_api_curated_marketplace;
|
||||
use crate::test_support::write_openai_curated_marketplace;
|
||||
use akode_config::CONFIG_TOML_FILE;
|
||||
use akode_protocol::auth::AuthMode;
|
||||
use akode_protocol::protocol::Product;
|
||||
use akode_utils_absolute_path::AbsolutePathBuf;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::collections::HashSet;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use tempfile::tempdir;
|
||||
use tracing::Level;
|
||||
use tracing_subscriber::fmt::format::FmtSpan;
|
||||
use tracing_test::internal::MockWriter;
|
||||
|
||||
#[tokio::test]
|
||||
async fn returns_api_curated_fallback_plugins_for_direct_provider_auth() {
|
||||
let codex_home = tempdir().expect("tempdir should succeed");
|
||||
let curated_root = curated_plugins_repo_path(codex_home.path());
|
||||
write_openai_api_curated_marketplace(&curated_root, &["sample", "slack", "openai-developers"]);
|
||||
|
||||
let plugins = load_plugins_config(codex_home.path(), codex_home.path()).await;
|
||||
let plugins_manager = test_plugins_manager_with_options(
|
||||
codex_home.path().to_path_buf(),
|
||||
Some(Product::Codex),
|
||||
Some(AuthMode::ApiKey),
|
||||
);
|
||||
let discoverable_plugins =
|
||||
list_discoverable_plugins(&plugins_manager, discovery_input(plugins, &[], &[])).await;
|
||||
|
||||
assert_eq!(
|
||||
discoverable_plugins
|
||||
.into_iter()
|
||||
.map(|plugin| plugin.id)
|
||||
.collect::<Vec<_>>(),
|
||||
vec![
|
||||
"openai-developers@openai-api-curated".to_string(),
|
||||
"slack@openai-api-curated".to_string(),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn returns_microsoft_fallback_plugins() {
|
||||
let codex_home = tempdir().expect("tempdir should succeed");
|
||||
let curated_root = curated_plugins_repo_path(codex_home.path());
|
||||
write_openai_api_curated_marketplace(
|
||||
&curated_root,
|
||||
&["teams", "sharepoint", "outlook-email", "outlook-calendar"],
|
||||
);
|
||||
install_marketplace_plugin(codex_home.path(), curated_root.as_path(), "teams").await;
|
||||
|
||||
let plugins = load_plugins_config(codex_home.path(), codex_home.path()).await;
|
||||
let plugins_manager = test_plugins_manager_with_options(
|
||||
codex_home.path().to_path_buf(),
|
||||
Some(Product::Codex),
|
||||
Some(AuthMode::ApiKey),
|
||||
);
|
||||
let discoverable_plugins =
|
||||
list_discoverable_plugins(&plugins_manager, discovery_input(plugins, &[], &[])).await;
|
||||
|
||||
assert_eq!(
|
||||
discoverable_plugins
|
||||
.into_iter()
|
||||
.map(|plugin| plugin.id)
|
||||
.collect::<Vec<_>>(),
|
||||
vec![
|
||||
"outlook-calendar@openai-api-curated".to_string(),
|
||||
"outlook-email@openai-api-curated".to_string(),
|
||||
"sharepoint@openai-api-curated".to_string(),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn omits_openai_curated_but_keeps_configured_marketplaces_for_headers_auth() {
|
||||
let codex_home = tempdir().expect("tempdir should succeed");
|
||||
let curated_root = curated_plugins_repo_path(codex_home.path());
|
||||
write_openai_curated_marketplace(&curated_root, &["slack"]);
|
||||
|
||||
let bundled_marketplace_name = OPENAI_BUNDLED_MARKETPLACE_NAME;
|
||||
let bundled_marketplace_root = codex_home.path().join(format!(
|
||||
".tmp/bundled-marketplaces/{bundled_marketplace_name}"
|
||||
));
|
||||
write_file(
|
||||
&bundled_marketplace_root.join(".agents/plugins/marketplace.json"),
|
||||
&format!(
|
||||
r#"{{
|
||||
"name": "{bundled_marketplace_name}",
|
||||
"plugins": [
|
||||
{{"name": "chrome", "source": {{"source": "local", "path": "./plugins/chrome"}}}}
|
||||
]
|
||||
}}
|
||||
"#
|
||||
),
|
||||
);
|
||||
write_curated_plugin(&bundled_marketplace_root, "chrome");
|
||||
write_file(
|
||||
&codex_home.path().join(CONFIG_TOML_FILE),
|
||||
&format!(
|
||||
r#"[features]
|
||||
plugins = true
|
||||
|
||||
[marketplaces.{bundled_marketplace_name}]
|
||||
source_type = "local"
|
||||
source = {bundled_marketplace_root:?}
|
||||
"#
|
||||
),
|
||||
);
|
||||
|
||||
let plugins = load_plugins_config(codex_home.path(), codex_home.path()).await;
|
||||
let plugins_manager = test_plugins_manager_with_options(
|
||||
codex_home.path().to_path_buf(),
|
||||
Some(Product::Codex),
|
||||
Some(AuthMode::Headers),
|
||||
);
|
||||
let discoverable_plugins =
|
||||
list_discoverable_plugins(&plugins_manager, discovery_input(plugins, &[], &[])).await;
|
||||
|
||||
assert_eq!(
|
||||
discoverable_plugins
|
||||
.into_iter()
|
||||
.map(|plugin| plugin.id)
|
||||
.collect::<Vec<_>>(),
|
||||
vec!["chrome@openai-bundled".to_string()]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn includes_openai_api_curated_without_auth() {
|
||||
let codex_home = tempdir().expect("tempdir should succeed");
|
||||
let curated_root = curated_plugins_repo_path(codex_home.path());
|
||||
write_openai_api_curated_marketplace(&curated_root, &["slack"]);
|
||||
|
||||
let plugins = load_plugins_config(codex_home.path(), codex_home.path()).await;
|
||||
let plugins_manager = test_plugins_manager(codex_home.path().to_path_buf());
|
||||
let discoverable_plugins =
|
||||
list_discoverable_plugins(&plugins_manager, discovery_input(plugins, &[], &[])).await;
|
||||
|
||||
assert_eq!(
|
||||
discoverable_plugins
|
||||
.into_iter()
|
||||
.map(|plugin| plugin.id)
|
||||
.collect::<Vec<_>>(),
|
||||
vec!["slack@openai-api-curated".to_string()]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn deduplicates_and_reprojects_cached_configured_marketplace_plugin() {
|
||||
let codex_home = tempdir().expect("tempdir should succeed");
|
||||
let plugin_name = "sample";
|
||||
let marketplace_name = OPENAI_BUNDLED_MARKETPLACE_NAME;
|
||||
let plugin_id = format!("{plugin_name}@{marketplace_name}");
|
||||
let marketplace_root = codex_home
|
||||
.path()
|
||||
.join(format!(".tmp/bundled-marketplaces/{marketplace_name}"));
|
||||
write_file(
|
||||
&marketplace_root.join(".agents/plugins/marketplace.json"),
|
||||
&format!(
|
||||
r#"{{
|
||||
"name": "{marketplace_name}",
|
||||
"plugins": [
|
||||
{{"name": "{plugin_name}", "source": {{"source": "local", "path": "./plugins/{plugin_name}"}}}}
|
||||
]
|
||||
}}
|
||||
"#
|
||||
),
|
||||
);
|
||||
write_curated_plugin(&marketplace_root, plugin_name);
|
||||
write_plugin_app(
|
||||
&marketplace_root,
|
||||
plugin_name,
|
||||
"sample-docs",
|
||||
"connector_sample",
|
||||
);
|
||||
write_file(
|
||||
&codex_home.path().join(CONFIG_TOML_FILE),
|
||||
&format!(
|
||||
r#"[features]
|
||||
plugins = true
|
||||
|
||||
[marketplaces.{marketplace_name}]
|
||||
source_type = "local"
|
||||
source = {marketplace_root:?}
|
||||
"#
|
||||
),
|
||||
);
|
||||
let plugins = load_plugins_config(codex_home.path(), codex_home.path()).await;
|
||||
let auth_manager = test_auth_manager(Some(AuthMode::ApiKey));
|
||||
let plugins_manager = test_plugins_manager_with_auth_manager(
|
||||
codex_home.path().to_path_buf(),
|
||||
Some(Product::Codex),
|
||||
Arc::clone(&auth_manager),
|
||||
);
|
||||
let header_projection = list_discoverable_plugins(
|
||||
&plugins_manager,
|
||||
discovery_input(plugins.clone(), &[plugin_id.as_str()], &[]),
|
||||
)
|
||||
.await;
|
||||
let expected = ToolSuggestDiscoverablePlugin {
|
||||
id: plugin_id.clone(),
|
||||
name: "sample".to_string(),
|
||||
description: Some(
|
||||
"Plugin that includes skills, MCP servers, and app connectors".to_string(),
|
||||
),
|
||||
has_skills: true,
|
||||
// App routes required ChatGPT auth, so direct MCP servers are always advertised.
|
||||
mcp_server_names: vec!["sample-docs".to_string()],
|
||||
};
|
||||
assert_eq!(header_projection, vec![expected.clone()]);
|
||||
|
||||
set_test_auth_mode(&auth_manager, Some(AuthMode::ApiKey)).await;
|
||||
let api_key_projection = list_discoverable_plugins(
|
||||
&plugins_manager,
|
||||
discovery_input(plugins, &[plugin_id.as_str()], &[]),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(api_key_projection, vec![expected]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reprojects_cached_skill_availability_for_current_config() {
|
||||
let codex_home = tempdir().expect("tempdir should succeed");
|
||||
let curated_root = curated_plugins_repo_path(codex_home.path());
|
||||
write_openai_api_curated_marketplace(&curated_root, &["slack"]);
|
||||
|
||||
let plugins = load_plugins_config(codex_home.path(), codex_home.path()).await;
|
||||
let plugins_manager = test_plugins_manager_with_options(
|
||||
codex_home.path().to_path_buf(),
|
||||
Some(Product::Codex),
|
||||
Some(AuthMode::ApiKey),
|
||||
);
|
||||
let expected = ToolSuggestDiscoverablePlugin {
|
||||
id: "slack@openai-api-curated".to_string(),
|
||||
name: "slack".to_string(),
|
||||
description: Some(
|
||||
"Plugin that includes skills, MCP servers, and app connectors".to_string(),
|
||||
),
|
||||
has_skills: true,
|
||||
mcp_server_names: vec!["sample-docs".to_string()],
|
||||
};
|
||||
let initial =
|
||||
list_discoverable_plugins(&plugins_manager, discovery_input(plugins, &[], &[])).await;
|
||||
assert_eq!(initial, vec![expected.clone()]);
|
||||
|
||||
write_file(
|
||||
&codex_home.path().join(CONFIG_TOML_FILE),
|
||||
r#"[[skills.config]]
|
||||
name = "slack:sample"
|
||||
enabled = false
|
||||
"#,
|
||||
);
|
||||
let plugins = load_plugins_config(codex_home.path(), codex_home.path()).await;
|
||||
let after_skill_disabled =
|
||||
list_discoverable_plugins(&plugins_manager, discovery_input(plugins, &[], &[])).await;
|
||||
assert_eq!(
|
||||
after_skill_disabled,
|
||||
vec![ToolSuggestDiscoverablePlugin {
|
||||
has_skills: false,
|
||||
..expected
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn does_not_advertise_skills_when_skill_loading_fails() {
|
||||
let codex_home = tempdir().expect("tempdir should succeed");
|
||||
let curated_root = curated_plugins_repo_path(codex_home.path());
|
||||
write_openai_api_curated_marketplace(&curated_root, &["slack"]);
|
||||
write_file(
|
||||
&curated_root.join("plugins/slack/skills/SKILL.md"),
|
||||
"---\nname: bad",
|
||||
);
|
||||
|
||||
let plugins = load_plugins_config(codex_home.path(), codex_home.path()).await;
|
||||
let plugins_manager = test_plugins_manager_with_options(
|
||||
codex_home.path().to_path_buf(),
|
||||
Some(Product::Codex),
|
||||
Some(AuthMode::ApiKey),
|
||||
);
|
||||
let discoverable_plugins =
|
||||
list_discoverable_plugins(&plugins_manager, discovery_input(plugins, &[], &[])).await;
|
||||
|
||||
assert_eq!(
|
||||
discoverable_plugins,
|
||||
vec![ToolSuggestDiscoverablePlugin {
|
||||
id: "slack@openai-api-curated".to_string(),
|
||||
name: "slack".to_string(),
|
||||
description: Some(
|
||||
"Plugin that includes skills, MCP servers, and app connectors".to_string(),
|
||||
),
|
||||
has_skills: false,
|
||||
mcp_server_names: vec!["sample-docs".to_string()],
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn clear_cache_invalidates_cached_tool_suggest_metadata() {
|
||||
let codex_home = tempdir().expect("tempdir should succeed");
|
||||
let curated_root = curated_plugins_repo_path(codex_home.path());
|
||||
write_openai_api_curated_marketplace(&curated_root, &["slack"]);
|
||||
let plugin_manifest = curated_root.join("plugins/slack/.codex-plugin/plugin.json");
|
||||
write_file(
|
||||
&plugin_manifest,
|
||||
r#"{
|
||||
"name": "slack",
|
||||
"description": "Before reload"
|
||||
}"#,
|
||||
);
|
||||
|
||||
let plugins = load_plugins_config(codex_home.path(), codex_home.path()).await;
|
||||
let plugins_manager = test_plugins_manager_with_options(
|
||||
codex_home.path().to_path_buf(),
|
||||
Some(Product::Codex),
|
||||
Some(AuthMode::ApiKey),
|
||||
);
|
||||
let input = discovery_input(plugins, &[], &[]);
|
||||
let expected_cached = vec![ToolSuggestDiscoverablePlugin {
|
||||
id: "slack@openai-api-curated".to_string(),
|
||||
name: "slack".to_string(),
|
||||
description: Some("Before reload".to_string()),
|
||||
has_skills: true,
|
||||
mcp_server_names: vec!["sample-docs".to_string()],
|
||||
}];
|
||||
let initial = list_discoverable_plugins(&plugins_manager, input.clone()).await;
|
||||
assert_eq!(initial, expected_cached);
|
||||
|
||||
write_file(
|
||||
&plugin_manifest,
|
||||
r#"{
|
||||
"name": "slack",
|
||||
"description": "After reload"
|
||||
}"#,
|
||||
);
|
||||
let before_reload = list_discoverable_plugins(&plugins_manager, input.clone()).await;
|
||||
assert_eq!(before_reload, expected_cached);
|
||||
|
||||
plugins_manager.clear_cache();
|
||||
let after_reload = list_discoverable_plugins(&plugins_manager, input).await;
|
||||
assert_eq!(
|
||||
after_reload,
|
||||
vec![ToolSuggestDiscoverablePlugin {
|
||||
description: Some("After reload".to_string()),
|
||||
..expected_cached[0].clone()
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ignores_missing_marketplace_plugin() {
|
||||
let codex_home = tempdir().expect("tempdir should succeed");
|
||||
let curated_root = curated_plugins_repo_path(codex_home.path());
|
||||
write_openai_api_curated_marketplace(&curated_root, &["installed", "slack"]);
|
||||
let marketplace_name = OPENAI_BUNDLED_MARKETPLACE_NAME;
|
||||
let marketplace_root = codex_home
|
||||
.path()
|
||||
.join(format!(".tmp/marketplaces/{marketplace_name}"));
|
||||
write_file(
|
||||
&marketplace_root.join(".agents/plugins/marketplace.json"),
|
||||
&format!(
|
||||
r#"{{
|
||||
"name": "{marketplace_name}",
|
||||
"plugins": [
|
||||
{{"name": "sample", "source": {{"source": "local", "path": "./plugins/sample"}}}}
|
||||
]
|
||||
}}
|
||||
"#
|
||||
),
|
||||
);
|
||||
write_file(
|
||||
&codex_home.path().join(CONFIG_TOML_FILE),
|
||||
&format!(
|
||||
r#"[features]
|
||||
plugins = true
|
||||
|
||||
[marketplaces.{marketplace_name}]
|
||||
source_type = "git"
|
||||
source = "/tmp/{marketplace_name}"
|
||||
"#
|
||||
),
|
||||
);
|
||||
install_marketplace_plugin(codex_home.path(), curated_root.as_path(), "installed").await;
|
||||
|
||||
let plugins = load_plugins_config(codex_home.path(), codex_home.path()).await;
|
||||
let plugins_manager = test_plugins_manager_with_options(
|
||||
codex_home.path().to_path_buf(),
|
||||
Some(Product::Codex),
|
||||
Some(AuthMode::ApiKey),
|
||||
);
|
||||
let discoverable_plugins =
|
||||
list_discoverable_plugins(&plugins_manager, discovery_input(plugins, &[], &[])).await;
|
||||
|
||||
assert_eq!(discoverable_plugins.len(), 1);
|
||||
assert_eq!(discoverable_plugins[0].id, "slack@openai-api-curated");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn normalizes_description() {
|
||||
let codex_home = tempdir().expect("tempdir should succeed");
|
||||
let curated_root = curated_plugins_repo_path(codex_home.path());
|
||||
write_openai_api_curated_marketplace(&curated_root, &["installed", "slack"]);
|
||||
write_file(
|
||||
&curated_root.join("plugins/slack/.codex-plugin/plugin.json"),
|
||||
r#"{
|
||||
"name": "slack",
|
||||
"description": " Plugin\n with extra spacing "
|
||||
}"#,
|
||||
);
|
||||
install_marketplace_plugin(codex_home.path(), curated_root.as_path(), "installed").await;
|
||||
|
||||
let plugins = load_plugins_config(codex_home.path(), codex_home.path()).await;
|
||||
let plugins_manager = test_plugins_manager_with_options(
|
||||
codex_home.path().to_path_buf(),
|
||||
Some(Product::Codex),
|
||||
Some(AuthMode::ApiKey),
|
||||
);
|
||||
let discoverable_plugins =
|
||||
list_discoverable_plugins(&plugins_manager, discovery_input(plugins, &[], &[])).await;
|
||||
|
||||
assert_eq!(
|
||||
discoverable_plugins,
|
||||
vec![ToolSuggestDiscoverablePlugin {
|
||||
id: "slack@openai-api-curated".to_string(),
|
||||
name: "slack".to_string(),
|
||||
description: Some("Plugin with extra spacing".to_string()),
|
||||
has_skills: true,
|
||||
mcp_server_names: vec!["sample-docs".to_string()],
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn omits_installed_curated_plugins() {
|
||||
let codex_home = tempdir().expect("tempdir should succeed");
|
||||
let curated_root = curated_plugins_repo_path(codex_home.path());
|
||||
write_openai_curated_marketplace(&curated_root, &["slack"]);
|
||||
install_marketplace_plugin(codex_home.path(), curated_root.as_path(), "slack").await;
|
||||
|
||||
let plugins = load_plugins_config(codex_home.path(), codex_home.path()).await;
|
||||
let plugins_manager = test_plugins_manager(codex_home.path().to_path_buf());
|
||||
let discoverable_plugins =
|
||||
list_discoverable_plugins(&plugins_manager, discovery_input(plugins, &[], &[])).await;
|
||||
|
||||
assert_eq!(discoverable_plugins, Vec::new());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn omits_not_available_curated_plugins() {
|
||||
let codex_home = tempdir().expect("tempdir should succeed");
|
||||
let curated_root = curated_plugins_repo_path(codex_home.path());
|
||||
write_file(
|
||||
&curated_root.join(".agents/plugins/api_marketplace.json"),
|
||||
r#"{
|
||||
"name": "openai-api-curated",
|
||||
"plugins": [
|
||||
{
|
||||
"name": "installed",
|
||||
"source": {
|
||||
"source": "local",
|
||||
"path": "./plugins/installed"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "slack",
|
||||
"source": {
|
||||
"source": "local",
|
||||
"path": "./plugins/slack"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "gmail",
|
||||
"source": {
|
||||
"source": "local",
|
||||
"path": "./plugins/gmail"
|
||||
},
|
||||
"policy": {
|
||||
"installation": "NOT_AVAILABLE"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
"#,
|
||||
);
|
||||
write_curated_plugin(&curated_root, "installed");
|
||||
write_curated_plugin(&curated_root, "slack");
|
||||
write_curated_plugin(&curated_root, "gmail");
|
||||
install_marketplace_plugin(codex_home.path(), curated_root.as_path(), "installed").await;
|
||||
|
||||
let plugins = load_plugins_config(codex_home.path(), codex_home.path()).await;
|
||||
let plugins_manager = test_plugins_manager_with_options(
|
||||
codex_home.path().to_path_buf(),
|
||||
Some(Product::Codex),
|
||||
Some(AuthMode::ApiKey),
|
||||
);
|
||||
let discoverable_plugins =
|
||||
list_discoverable_plugins(&plugins_manager, discovery_input(plugins, &[], &[])).await;
|
||||
|
||||
assert_eq!(
|
||||
discoverable_plugins
|
||||
.into_iter()
|
||||
.map(|plugin| plugin.id)
|
||||
.collect::<Vec<_>>(),
|
||||
vec!["slack@openai-api-curated".to_string()]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn discovery_warns_once_per_invalid_manifest() {
|
||||
let codex_home = tempdir().expect("tempdir should succeed");
|
||||
let curated_root = curated_plugins_repo_path(codex_home.path());
|
||||
write_openai_api_curated_marketplace(&curated_root, &["slack", "gmail", "openai-developers"]);
|
||||
install_marketplace_plugin(codex_home.path(), curated_root.as_path(), "slack").await;
|
||||
|
||||
let too_long_prompt = "x".repeat(513);
|
||||
for plugin_name in ["gmail", "openai-developers"] {
|
||||
write_file(
|
||||
&curated_root.join(format!("plugins/{plugin_name}/.codex-plugin/plugin.json")),
|
||||
&format!(
|
||||
r#"{{
|
||||
"name": "{plugin_name}",
|
||||
"description": "Plugin that includes skills, MCP servers, and app connectors",
|
||||
"interface": {{
|
||||
"defaultPrompt": "{too_long_prompt}"
|
||||
}}
|
||||
}}"#
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
let plugins = load_plugins_config(codex_home.path(), codex_home.path()).await;
|
||||
let plugins_manager = test_plugins_manager_with_options(
|
||||
codex_home.path().to_path_buf(),
|
||||
Some(Product::Codex),
|
||||
Some(AuthMode::ApiKey),
|
||||
);
|
||||
let buffer: &'static std::sync::Mutex<Vec<u8>> =
|
||||
Box::leak(Box::new(std::sync::Mutex::new(Vec::new())));
|
||||
let subscriber = tracing_subscriber::fmt()
|
||||
.with_level(true)
|
||||
.with_ansi(false)
|
||||
.with_max_level(Level::WARN)
|
||||
.with_span_events(FmtSpan::NONE)
|
||||
.with_writer(MockWriter::new(buffer))
|
||||
.finish();
|
||||
let _guard = tracing::subscriber::set_default(subscriber);
|
||||
|
||||
let discoverable_plugins =
|
||||
list_discoverable_plugins(&plugins_manager, discovery_input(plugins, &[], &[])).await;
|
||||
|
||||
assert_eq!(
|
||||
discoverable_plugins
|
||||
.iter()
|
||||
.map(|plugin| plugin.id.as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
vec![
|
||||
"gmail@openai-api-curated",
|
||||
"openai-developers@openai-api-curated"
|
||||
]
|
||||
);
|
||||
|
||||
let logs = String::from_utf8(buffer.lock().expect("buffer lock").clone())
|
||||
.expect("utf8 logs")
|
||||
.replace('\\', "/");
|
||||
assert_eq!(logs.matches("ignoring interface.defaultPrompt").count(), 2);
|
||||
assert_eq!(logs.matches("gmail/.codex-plugin/plugin.json").count(), 1);
|
||||
assert_eq!(
|
||||
logs.matches("openai-developers/.codex-plugin/plugin.json")
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn does_not_expand_local_plugins_by_installed_apps() {
|
||||
let codex_home = tempdir().expect("tempdir should succeed");
|
||||
let curated_root = curated_plugins_repo_path(codex_home.path());
|
||||
write_openai_curated_marketplace(&curated_root, &["sample", "slack", "hubspot"]);
|
||||
write_plugin_app(&curated_root, "sample", "sample", "connector_sample");
|
||||
install_marketplace_plugin(codex_home.path(), curated_root.as_path(), "slack").await;
|
||||
|
||||
let plugins = load_plugins_config(codex_home.path(), codex_home.path()).await;
|
||||
let plugins_manager = test_plugins_manager(codex_home.path().to_path_buf());
|
||||
let discoverable_plugins =
|
||||
list_discoverable_plugins(&plugins_manager, discovery_input(plugins, &[], &[])).await;
|
||||
|
||||
assert_eq!(discoverable_plugins, Vec::new());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn does_not_read_local_plugins_for_loaded_apps() {
|
||||
let hubspot_app_id = "asdk_app_697acb8e53d88191bf7a79e62012ae14";
|
||||
let granola_app_id = "asdk_app_697761cab6f48191b5ed345919a3ce8b";
|
||||
let codex_home = tempdir().expect("tempdir should succeed");
|
||||
let curated_root = curated_plugins_repo_path(codex_home.path());
|
||||
write_openai_curated_marketplace(&curated_root, &["hubspot", "granola", "sample"]);
|
||||
write_plugin_app(&curated_root, "hubspot", "hubspot", hubspot_app_id);
|
||||
write_plugin_app(&curated_root, "granola", "granola", granola_app_id);
|
||||
write_file(
|
||||
&curated_root.join("plugins/sample/.app.json"),
|
||||
"invalid json",
|
||||
);
|
||||
|
||||
let plugins = load_plugins_config(codex_home.path(), codex_home.path()).await;
|
||||
let plugins_manager = test_plugins_manager(codex_home.path().to_path_buf());
|
||||
let buffer: &'static std::sync::Mutex<Vec<u8>> =
|
||||
Box::leak(Box::new(std::sync::Mutex::new(Vec::new())));
|
||||
let subscriber = tracing_subscriber::fmt()
|
||||
.with_level(true)
|
||||
.with_ansi(false)
|
||||
.with_max_level(Level::WARN)
|
||||
.with_span_events(FmtSpan::NONE)
|
||||
.with_writer(MockWriter::new(buffer))
|
||||
.finish();
|
||||
let _guard = tracing::subscriber::set_default(subscriber);
|
||||
|
||||
let discoverable_plugins =
|
||||
list_discoverable_plugins(&plugins_manager, discovery_input(plugins, &[], &[])).await;
|
||||
|
||||
assert_eq!(discoverable_plugins, Vec::new());
|
||||
let logs = String::from_utf8(buffer.lock().expect("buffer lock").clone())
|
||||
.expect("utf8 logs")
|
||||
.replace('\\', "/");
|
||||
assert_eq!(logs.matches("plugins/sample/.app.json").count(), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn does_not_expand_local_sales_apps() {
|
||||
let hubspot_app_id = "asdk_app_697acb8e53d88191bf7a79e62012ae14";
|
||||
let granola_app_id = "asdk_app_697761cab6f48191b5ed345919a3ce8b";
|
||||
let test_app_id = "asdk_app_test_source";
|
||||
let codex_home = tempdir().expect("tempdir should succeed");
|
||||
let curated_root = curated_plugins_repo_path(codex_home.path());
|
||||
write_openai_curated_marketplace(&curated_root, &["hubspot", "granola", "test-source"]);
|
||||
write_plugin_app(&curated_root, "hubspot", "hubspot", hubspot_app_id);
|
||||
write_plugin_app(&curated_root, "granola", "granola", granola_app_id);
|
||||
write_plugin_app(&curated_root, "test-source", "test_source", test_app_id);
|
||||
|
||||
let sales_marketplace_name = "oai-maintained-plugins";
|
||||
let sales_marketplace_root = codex_home
|
||||
.path()
|
||||
.join(format!(".tmp/marketplaces/{sales_marketplace_name}"));
|
||||
write_file(
|
||||
&sales_marketplace_root.join(".agents/plugins/marketplace.json"),
|
||||
&format!(
|
||||
r#"{{
|
||||
"name": "{sales_marketplace_name}",
|
||||
"plugins": [
|
||||
{{"name": "sales", "source": {{"source": "local", "path": "./plugins/sales"}}}}
|
||||
]
|
||||
}}
|
||||
"#
|
||||
),
|
||||
);
|
||||
write_curated_plugin(&sales_marketplace_root, "sales");
|
||||
write_file(
|
||||
&sales_marketplace_root.join("plugins/sales/.app.json"),
|
||||
&format!(
|
||||
r#"{{
|
||||
"apps": {{
|
||||
"hubspot": {{
|
||||
"id": "{hubspot_app_id}"
|
||||
}},
|
||||
"granola": {{
|
||||
"id": "{granola_app_id}"
|
||||
}}
|
||||
}}
|
||||
}}
|
||||
"#
|
||||
),
|
||||
);
|
||||
write_file(
|
||||
&codex_home.path().join(CONFIG_TOML_FILE),
|
||||
&format!(
|
||||
r#"[features]
|
||||
plugins = true
|
||||
|
||||
[marketplaces.{sales_marketplace_name}]
|
||||
source_type = "git"
|
||||
source = "/tmp/{sales_marketplace_name}"
|
||||
"#
|
||||
),
|
||||
);
|
||||
install_marketplace_plugin(codex_home.path(), sales_marketplace_root.as_path(), "sales").await;
|
||||
|
||||
let plugins = load_plugins_config(codex_home.path(), codex_home.path()).await;
|
||||
let plugins_manager = test_plugins_manager(codex_home.path().to_path_buf());
|
||||
let discoverable_plugins =
|
||||
list_discoverable_plugins(&plugins_manager, discovery_input(plugins, &[], &[])).await;
|
||||
|
||||
assert_eq!(discoverable_plugins, Vec::new());
|
||||
}
|
||||
|
||||
fn discovery_input(
|
||||
plugins: PluginsConfigInput,
|
||||
configured_plugin_ids: &[&str],
|
||||
disabled_plugin_ids: &[&str],
|
||||
) -> ToolSuggestPluginDiscoveryInput {
|
||||
ToolSuggestPluginDiscoveryInput {
|
||||
plugins,
|
||||
configured_plugin_ids: string_set(configured_plugin_ids),
|
||||
disabled_plugin_ids: string_set(disabled_plugin_ids),
|
||||
}
|
||||
}
|
||||
|
||||
async fn list_discoverable_plugins(
|
||||
plugins_manager: &PluginsManager,
|
||||
input: ToolSuggestPluginDiscoveryInput,
|
||||
) -> Vec<ToolSuggestDiscoverablePlugin> {
|
||||
plugins_manager
|
||||
.list_tool_suggest_discoverable_plugins(&input)
|
||||
.await
|
||||
.expect("discoverable plugins should load")
|
||||
}
|
||||
|
||||
fn string_set(values: &[&str]) -> HashSet<String> {
|
||||
values.iter().map(ToString::to_string).collect()
|
||||
}
|
||||
|
||||
async fn install_marketplace_plugin(codex_home: &Path, marketplace_root: &Path, plugin_name: &str) {
|
||||
write_curated_plugin_sha_with(codex_home, TEST_CURATED_PLUGIN_SHA);
|
||||
let config = load_plugins_config(codex_home, marketplace_root).await;
|
||||
test_plugins_manager(codex_home.to_path_buf())
|
||||
.install_plugin(
|
||||
&config.config_layer_stack,
|
||||
PluginInstallRequest {
|
||||
plugin_name: plugin_name.to_string(),
|
||||
marketplace_path: AbsolutePathBuf::try_from({
|
||||
let api_manifest =
|
||||
marketplace_root.join(".agents/plugins/api_marketplace.json");
|
||||
if api_manifest.is_file() {
|
||||
api_manifest
|
||||
} else {
|
||||
marketplace_root.join(".agents/plugins/marketplace.json")
|
||||
}
|
||||
})
|
||||
.expect("marketplace path"),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("plugin should install");
|
||||
}
|
||||
|
||||
fn write_plugin_app(root: &Path, plugin_name: &str, app_name: &str, app_id: &str) {
|
||||
write_file(
|
||||
&root.join(format!("plugins/{plugin_name}/.app.json")),
|
||||
&format!(
|
||||
r#"{{
|
||||
"apps": {{
|
||||
"{app_name}": {{
|
||||
"id": "{app_id}"
|
||||
}}
|
||||
}}
|
||||
}}
|
||||
"#
|
||||
),
|
||||
);
|
||||
}
|
||||
78
akode-rs/core-plugins/src/executor_catalog.rs
Normal file
78
akode-rs/core-plugins/src/executor_catalog.rs
Normal file
@@ -0,0 +1,78 @@
|
||||
//! Converts V2 discovery contents to inert plugin catalogs without additional I/O.
|
||||
|
||||
use crate::PluginCatalog;
|
||||
use crate::PluginCatalogEntry;
|
||||
use crate::PluginIdentity;
|
||||
use crate::PluginSourceLocation;
|
||||
use akode_exec_server::ExecutorCapabilityDiscoveryV2Snapshot;
|
||||
use akode_exec_server::ExecutorPlugin;
|
||||
use akode_mcp::parse_plugin_mcp_declarations;
|
||||
|
||||
/// Projects V2 inventories into a plugin catalog without additional filesystem access.
|
||||
pub fn catalog_from_snapshots(
|
||||
snapshots: &[ExecutorCapabilityDiscoveryV2Snapshot],
|
||||
) -> PluginCatalog {
|
||||
let mut catalog = PluginCatalog::default();
|
||||
for snapshot in snapshots {
|
||||
let inventory = match &snapshot.result {
|
||||
Ok(inventory) => inventory,
|
||||
Err(error) => {
|
||||
catalog.is_partial = true;
|
||||
catalog.warnings.push(format!(
|
||||
"could not discover plugins in environment `{}`; skipping its plugin inventory: {error}",
|
||||
snapshot.environment_id
|
||||
));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
catalog.warnings.extend(inventory.warnings.iter().cloned());
|
||||
for plugin in &inventory.plugins {
|
||||
let (entry, warnings) = from_discovered_plugin(&snapshot.environment_id, plugin);
|
||||
catalog.entries.push(entry);
|
||||
catalog.warnings.extend(warnings);
|
||||
}
|
||||
}
|
||||
catalog
|
||||
}
|
||||
|
||||
fn from_discovered_plugin(
|
||||
environment_id: &str,
|
||||
plugin: &ExecutorPlugin,
|
||||
) -> (PluginCatalogEntry, Vec<String>) {
|
||||
let plugin_id = &plugin.id;
|
||||
let mut warnings = Vec::new();
|
||||
let mcp_servers = match plugin
|
||||
.files
|
||||
.mcp_config
|
||||
.as_ref()
|
||||
.map(|file| parse_plugin_mcp_declarations(&file.contents))
|
||||
{
|
||||
Some(Ok(servers)) => servers,
|
||||
Some(Err(error)) => {
|
||||
warnings.push(format!("plugin `{plugin_id}` MCP configuration: {error}"));
|
||||
Default::default()
|
||||
}
|
||||
None => Default::default(),
|
||||
};
|
||||
(
|
||||
PluginCatalogEntry {
|
||||
enabled: true,
|
||||
id: PluginIdentity::Local {
|
||||
plugin_id: plugin.id.clone(),
|
||||
},
|
||||
display_name: plugin.display_name.clone(),
|
||||
version: plugin.version.clone(),
|
||||
mcp_servers,
|
||||
locations: vec![PluginSourceLocation::Executor {
|
||||
environment_id: environment_id.to_string(),
|
||||
plugin_id: plugin_id.to_string(),
|
||||
root: plugin.root.clone(),
|
||||
}],
|
||||
},
|
||||
warnings,
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "executor_catalog_tests.rs"]
|
||||
mod tests;
|
||||
71
akode-rs/core-plugins/src/executor_catalog_tests.rs
Normal file
71
akode-rs/core-plugins/src/executor_catalog_tests.rs
Normal file
@@ -0,0 +1,71 @@
|
||||
//! Tests conversion of DiscoveryV2 payloads into inert plugin catalogs.
|
||||
|
||||
use super::catalog_from_snapshots;
|
||||
use crate::PluginCatalog;
|
||||
use crate::PluginCatalogEntry;
|
||||
use crate::PluginIdentity;
|
||||
use crate::PluginSourceLocation;
|
||||
use akode_exec_server::CapabilityTextFile;
|
||||
use akode_exec_server::DiscoverV2CapabilitiesResponse;
|
||||
use akode_exec_server::DiscoveredPluginFiles;
|
||||
use akode_exec_server::ExecutorCapabilityDiscoveryV2Snapshot;
|
||||
use akode_exec_server::ExecutorPlugin;
|
||||
use akode_utils_path_uri::PathUri;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[test]
|
||||
fn discovered_mcp_contents_populate_catalog() -> anyhow::Result<()> {
|
||||
let root = PathUri::parse("file:///plugins/example/1.0.0")?;
|
||||
let manifest_path = root.join(".codex-plugin/plugin.json")?;
|
||||
let declarations = serde_json::json!({"example": {"command": "node"}});
|
||||
let snapshot = ExecutorCapabilityDiscoveryV2Snapshot {
|
||||
environment_id: "executor-a".to_string(),
|
||||
result: Ok(Arc::new(DiscoverV2CapabilitiesResponse {
|
||||
plugins: vec![ExecutorPlugin {
|
||||
id: "example@marketplace".to_string(),
|
||||
display_name: "Example".to_string(),
|
||||
version: "1.0.0".to_string(),
|
||||
files: DiscoveredPluginFiles {
|
||||
manifest: CapabilityTextFile {
|
||||
path: manifest_path.clone(),
|
||||
contents: r#"{"name":"example"}"#.to_string(),
|
||||
},
|
||||
mcp_config: Some(CapabilityTextFile {
|
||||
path: manifest_path,
|
||||
contents: declarations.to_string(),
|
||||
}),
|
||||
apps_config: None,
|
||||
},
|
||||
root: root.clone(),
|
||||
skills: Vec::new(),
|
||||
}],
|
||||
..Default::default()
|
||||
})),
|
||||
};
|
||||
assert_eq!(
|
||||
catalog_from_snapshots(&[snapshot]),
|
||||
PluginCatalog {
|
||||
entries: vec![PluginCatalogEntry {
|
||||
enabled: true,
|
||||
id: PluginIdentity::Local {
|
||||
plugin_id: "example@marketplace".to_string(),
|
||||
},
|
||||
display_name: "Example".to_string(),
|
||||
version: "1.0.0".to_string(),
|
||||
mcp_servers: BTreeMap::from([(
|
||||
"example".to_string(),
|
||||
serde_json::json!({"command": "node"}),
|
||||
)]),
|
||||
locations: vec![PluginSourceLocation::Executor {
|
||||
environment_id: "executor-a".to_string(),
|
||||
plugin_id: "example@marketplace".to_string(),
|
||||
root,
|
||||
}],
|
||||
}],
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
133
akode-rs/core-plugins/src/executor_hooks.rs
Normal file
133
akode-rs/core-plugins/src/executor_hooks.rs
Normal file
@@ -0,0 +1,133 @@
|
||||
//! Executor-discovered plugin hook admission.
|
||||
|
||||
use akode_config::types::PluginsConfigToml;
|
||||
use akode_exec_server::DiscoveredPluginFiles;
|
||||
use akode_exec_server::ExecutorCapabilityDiscoverySnapshot;
|
||||
use akode_exec_server::ExecutorCapabilityDiscoveryV2Snapshot;
|
||||
use akode_plugin::ExecutorPluginHookSource;
|
||||
use akode_plugin::PluginId;
|
||||
use akode_plugin::is_allowlisted_bundled_cleanup_hook;
|
||||
use akode_plugin::manifest::PluginManifestHooks;
|
||||
use akode_protocol::capabilities::CapabilityRootLocation;
|
||||
use akode_utils_path_uri::PathUri;
|
||||
|
||||
use crate::manifest::parse_plugin_manifest_uri;
|
||||
|
||||
/// Returns accepted inline hook sources from executor-discovered plugin manifests.
|
||||
///
|
||||
/// Executor scoped hooks are best-effort because executor capabilities can become available
|
||||
/// after earlier lifecycle events have passed.
|
||||
///
|
||||
/// Note: Executor manifests are not signed yet, so temporarily we only admit the known cleanup
|
||||
/// hooks from the bundled cleanup allowlist.
|
||||
pub fn executor_plugin_hook_sources(
|
||||
snapshot: &ExecutorCapabilityDiscoverySnapshot,
|
||||
plugins_config: &PluginsConfigToml,
|
||||
) -> Vec<ExecutorPluginHookSource> {
|
||||
let plugins = snapshot.roots().iter().filter_map(|entry| {
|
||||
let CapabilityRootLocation::Environment {
|
||||
environment_id,
|
||||
path: plugin_root,
|
||||
} = &entry.selected_root.location;
|
||||
let plugin = entry.result.as_ref().ok()?.plugin.as_ref()?;
|
||||
Some((
|
||||
entry.selected_root.id.as_str(),
|
||||
environment_id.as_str(),
|
||||
plugin_root,
|
||||
plugin,
|
||||
))
|
||||
});
|
||||
admitted_hook_sources(plugins, plugins_config)
|
||||
}
|
||||
|
||||
/// Applies the same inline-hook admission policy to V2 inventories.
|
||||
/// Callers must additionally restrict sources to their accepted plugin installations.
|
||||
pub fn executor_plugin_hook_sources_v2(
|
||||
snapshots: &[ExecutorCapabilityDiscoveryV2Snapshot],
|
||||
plugins_config: &PluginsConfigToml,
|
||||
) -> Vec<ExecutorPluginHookSource> {
|
||||
let plugins = snapshots.iter().flat_map(|snapshot| {
|
||||
snapshot.result.iter().flat_map(move |inventory| {
|
||||
inventory.plugins.iter().map(move |plugin| {
|
||||
(
|
||||
plugin.id.as_str(),
|
||||
snapshot.environment_id.as_str(),
|
||||
&plugin.root,
|
||||
&plugin.files,
|
||||
)
|
||||
})
|
||||
})
|
||||
});
|
||||
admitted_hook_sources(plugins, plugins_config)
|
||||
}
|
||||
|
||||
fn admitted_hook_sources<'b>(
|
||||
plugins: impl Iterator<Item = (&'b str, &'b str, &'b PathUri, &'b DiscoveredPluginFiles)>,
|
||||
plugins_config: &PluginsConfigToml,
|
||||
) -> Vec<ExecutorPluginHookSource> {
|
||||
let mut sources = Vec::new();
|
||||
for (plugin_id, environment_id, plugin_root, plugin) in plugins {
|
||||
if !plugins_config.allows_plugin(plugin_id) {
|
||||
continue;
|
||||
}
|
||||
let Ok(plugin_id) = PluginId::parse(plugin_id) else {
|
||||
continue;
|
||||
};
|
||||
let Ok(manifest) = parse_plugin_manifest_uri(
|
||||
plugin_root,
|
||||
&plugin.manifest.path,
|
||||
&plugin.manifest.contents,
|
||||
) else {
|
||||
continue;
|
||||
};
|
||||
// Only inline hooks are supported for now, so skip any other source types.
|
||||
let Some(PluginManifestHooks::Inline(hook_files)) = manifest.paths.hooks else {
|
||||
continue;
|
||||
};
|
||||
|
||||
for (hook_index, hook_file) in hook_files.into_iter().enumerate() {
|
||||
let manifest_relative_path = plugin
|
||||
.manifest
|
||||
.path
|
||||
.relative_path_from(plugin_root)
|
||||
.unwrap_or_else(|| plugin.manifest.path.to_string());
|
||||
|
||||
sources.push(ExecutorPluginHookSource {
|
||||
plugin_id: plugin_id.clone(),
|
||||
environment_id: environment_id.to_string(),
|
||||
mcp_environment_id: None,
|
||||
mcp_metadata: None,
|
||||
plugin_root: plugin_root.clone(),
|
||||
manifest_path: plugin.manifest.path.clone(),
|
||||
source_relative_path: format!("{manifest_relative_path}#hooks[{hook_index}]"),
|
||||
hooks: hook_file.hooks,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// FIXME: Remove this temporary filter once executor plugin hooks can be trusted.
|
||||
sources
|
||||
.into_iter()
|
||||
.filter_map(|mut source| {
|
||||
let plugin_id = source.plugin_id.as_key();
|
||||
for (event, groups) in source.hooks.matcher_groups_mut() {
|
||||
groups.retain_mut(|group| {
|
||||
group.hooks.retain(|handler| {
|
||||
is_allowlisted_bundled_cleanup_hook(
|
||||
&plugin_id,
|
||||
event,
|
||||
group.matcher.as_deref(),
|
||||
handler,
|
||||
)
|
||||
});
|
||||
!group.hooks.is_empty()
|
||||
});
|
||||
}
|
||||
(!source.hooks.is_empty()).then_some(source)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "executor_hooks_tests.rs"]
|
||||
mod tests;
|
||||
400
akode-rs/core-plugins/src/executor_hooks_tests.rs
Normal file
400
akode-rs/core-plugins/src/executor_hooks_tests.rs
Normal file
@@ -0,0 +1,400 @@
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use akode_config::HookEventsToml;
|
||||
use akode_config::HookHandlerConfig;
|
||||
use akode_config::MatcherGroup;
|
||||
use akode_exec_server::CapabilityRootDiscovery;
|
||||
use akode_exec_server::CapabilityTextFile;
|
||||
use akode_exec_server::DiscoveredPluginFiles;
|
||||
use akode_exec_server::ExecutorCapabilityDiscoverySnapshot;
|
||||
use akode_plugin::ExecutorPluginHookSource;
|
||||
use akode_protocol::capabilities::CapabilityRootLocation;
|
||||
use akode_protocol::capabilities::SelectedCapabilityRoot;
|
||||
use akode_utils_path_uri::PathUri;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn snapshot_for_manifest(
|
||||
plugin_id: &str,
|
||||
environment_id: &str,
|
||||
manifest_path: &str,
|
||||
manifest: serde_json::Value,
|
||||
) -> ExecutorCapabilityDiscoverySnapshot {
|
||||
let plugin_root = PathUri::parse("file:///plugins/computer-use").expect("plugin root");
|
||||
let manifest_path = PathUri::parse(manifest_path).expect("manifest path");
|
||||
let selected_root = SelectedCapabilityRoot {
|
||||
id: plugin_id.to_string(),
|
||||
location: CapabilityRootLocation::Environment {
|
||||
environment_id: environment_id.to_string(),
|
||||
path: plugin_root.clone(),
|
||||
},
|
||||
};
|
||||
let discovery = CapabilityRootDiscovery {
|
||||
id: plugin_id.to_string(),
|
||||
path: plugin_root,
|
||||
plugin: Some(DiscoveredPluginFiles {
|
||||
manifest: CapabilityTextFile {
|
||||
path: manifest_path,
|
||||
contents: manifest.to_string(),
|
||||
},
|
||||
mcp_config: None,
|
||||
apps_config: None,
|
||||
}),
|
||||
skills: Vec::new(),
|
||||
namespace_manifests: Vec::new(),
|
||||
warnings: Vec::new(),
|
||||
error: None,
|
||||
};
|
||||
ExecutorCapabilityDiscoverySnapshot::new(
|
||||
&[selected_root],
|
||||
vec![Ok(Arc::new(discovery))],
|
||||
HashMap::new(),
|
||||
)
|
||||
}
|
||||
|
||||
fn cleanup_hook_manifest() -> serde_json::Value {
|
||||
json!({
|
||||
"name": "computer-use",
|
||||
"hooks": {
|
||||
"hooks": {
|
||||
"Stop": [{
|
||||
"hooks": [{
|
||||
"type": "mcp_tool",
|
||||
"server": "node_repl",
|
||||
"tool": "turn_ended",
|
||||
"input": {
|
||||
"hook_event_name": "${hook_event_name}",
|
||||
"session_id": "${session_id}",
|
||||
"turn_id": "${turn_id}"
|
||||
}
|
||||
}]
|
||||
}]
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn expected_source(index: usize) -> ExecutorPluginHookSource {
|
||||
ExecutorPluginHookSource {
|
||||
plugin_id: PluginId::parse("computer-use@openai-bundled").expect("plugin id"),
|
||||
environment_id: "executor-a".to_string(),
|
||||
mcp_environment_id: None,
|
||||
mcp_metadata: None,
|
||||
plugin_root: PathUri::parse("file:///plugins/computer-use").expect("plugin root"),
|
||||
manifest_path: PathUri::parse("file:///plugins/computer-use/.codex-plugin/plugin.json")
|
||||
.expect("manifest path"),
|
||||
source_relative_path: format!(".codex-plugin/plugin.json#hooks[{index}]"),
|
||||
hooks: HookEventsToml {
|
||||
stop: vec![MatcherGroup {
|
||||
matcher: None,
|
||||
hooks: vec![HookHandlerConfig::McpTool {
|
||||
server: "node_repl".to_string(),
|
||||
tool: "turn_ended".to_string(),
|
||||
input: serde_json::from_value(json!({
|
||||
"hook_event_name": "${hook_event_name}",
|
||||
"session_id": "${session_id}",
|
||||
"turn_id": "${turn_id}",
|
||||
}))
|
||||
.expect("executor hook input"),
|
||||
timeout_sec: None,
|
||||
status_message: None,
|
||||
}],
|
||||
}],
|
||||
..Default::default()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn discovers_allowlisted_executor_plugin_hook_sources() {
|
||||
let cleanup_hooks = cleanup_hook_manifest()["hooks"]["hooks"]["Stop"].clone();
|
||||
let manifest = json!({
|
||||
"name": "computer-use",
|
||||
"hooks": [
|
||||
{ "hooks": { "Stop": cleanup_hooks } },
|
||||
{ "hooks": { "Interrupt": cleanup_hooks } },
|
||||
{ "hooks": {
|
||||
"Stop": cleanup_hooks,
|
||||
"Interrupt": cleanup_hooks,
|
||||
"UserPromptSubmit": cleanup_hooks
|
||||
} },
|
||||
{ "hooks": { "UserPromptSubmit": cleanup_hooks } }
|
||||
]
|
||||
});
|
||||
let snapshot = snapshot_for_manifest(
|
||||
"computer-use@openai-bundled",
|
||||
"executor-a",
|
||||
"file:///plugins/computer-use/.codex-plugin/plugin.json",
|
||||
manifest,
|
||||
);
|
||||
|
||||
let sources =
|
||||
executor_plugin_hook_sources(&snapshot, &PluginsConfigToml::default());
|
||||
let mut interrupt_source = expected_source(/*index*/ 1);
|
||||
interrupt_source.hooks.interrupt = std::mem::take(&mut interrupt_source.hooks.stop);
|
||||
let mut stop_and_interrupt_source = expected_source(/*index*/ 2);
|
||||
stop_and_interrupt_source.hooks.interrupt = stop_and_interrupt_source.hooks.stop.clone();
|
||||
|
||||
assert_eq!(
|
||||
sources,
|
||||
vec![
|
||||
expected_source(/*index*/ 0),
|
||||
interrupt_source,
|
||||
stop_and_interrupt_source,
|
||||
]
|
||||
);
|
||||
for (config, expected) in [
|
||||
(
|
||||
"[_default]\nenabled = false\n[\"computer-use@other-marketplace\"]\nenabled = true",
|
||||
Vec::new(),
|
||||
),
|
||||
(
|
||||
"[_default]\nenabled = false\n[\"computer-use@openai-bundled\"]\nenabled = true",
|
||||
sources,
|
||||
),
|
||||
] {
|
||||
let config = toml::from_str(config).expect("plugin policy");
|
||||
assert_eq!(
|
||||
executor_plugin_hook_sources(&snapshot, &config),
|
||||
expected
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn discovers_unified_computer_use_cleanup_hooks() {
|
||||
let mut manifest = cleanup_hook_manifest();
|
||||
manifest["name"] = json!("unified-computer-use");
|
||||
manifest["hooks"]["hooks"]["Stop"][0]["hooks"][0]["server"] = json!("cua_repl");
|
||||
let snapshot = snapshot_for_manifest(
|
||||
"unified-computer-use@openai-bundled",
|
||||
"executor-a",
|
||||
"file:///plugins/computer-use/.codex-plugin/plugin.json",
|
||||
manifest,
|
||||
);
|
||||
let mut expected = expected_source(/*index*/ 0);
|
||||
expected.plugin_id = PluginId::parse("unified-computer-use@openai-bundled").expect("plugin id");
|
||||
let HookHandlerConfig::McpTool { server, .. } = &mut expected.hooks.stop[0].hooks[0] else {
|
||||
panic!("expected an MCP tool hook");
|
||||
};
|
||||
*server = "cua_repl".to_string();
|
||||
|
||||
assert_eq!(
|
||||
executor_plugin_hook_sources(&snapshot, &PluginsConfigToml::default()),
|
||||
vec![expected]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filters_mixed_handlers_without_rewriting_allowed_groups() {
|
||||
let mut expected = expected_source(/*index*/ 0);
|
||||
let mut second_handler = expected.hooks.stop[0].hooks[0].clone();
|
||||
let HookHandlerConfig::McpTool { input, .. } = &mut second_handler else {
|
||||
panic!("expected an MCP tool hook");
|
||||
};
|
||||
input.insert("order".to_string(), json!(2));
|
||||
expected.hooks.stop[0].hooks.push(second_handler.clone());
|
||||
expected.hooks.stop.push(MatcherGroup {
|
||||
matcher: None,
|
||||
hooks: vec![second_handler],
|
||||
});
|
||||
|
||||
let mut manifest = cleanup_hook_manifest();
|
||||
manifest["hooks"]["hooks"]["Stop"] =
|
||||
serde_json::to_value(&expected.hooks.stop).expect("serialize stop hooks");
|
||||
manifest["hooks"]["hooks"]["Stop"][0]["hooks"]
|
||||
.as_array_mut()
|
||||
.expect("stop handlers")
|
||||
.insert(
|
||||
/*index*/ 0,
|
||||
json!({ "type": "mcp_tool", "server": "node_repl", "tool": "other" }),
|
||||
);
|
||||
let snapshot = snapshot_for_manifest(
|
||||
"computer-use@openai-bundled",
|
||||
"executor-a",
|
||||
"file:///plugins/computer-use/.codex-plugin/plugin.json",
|
||||
manifest,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
executor_plugin_hook_sources(&snapshot, &PluginsConfigToml::default()),
|
||||
vec![expected]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_allowlisted_executor_plugin_hook_options() {
|
||||
let mut manifest = cleanup_hook_manifest();
|
||||
let handler = &mut manifest["hooks"]["hooks"]["Stop"][0]["hooks"][0];
|
||||
handler["input"] = json!({ "untrusted": "manifest-provided input" });
|
||||
handler["timeout"] = json!(30);
|
||||
handler["statusMessage"] = json!("Cleaning up Computer Use");
|
||||
manifest["hooks"]["hooks"]["Interrupt"] = manifest["hooks"]["hooks"]["Stop"].clone();
|
||||
let snapshot = snapshot_for_manifest(
|
||||
"computer-use@openai-bundled",
|
||||
"executor-a",
|
||||
"file:///plugins/computer-use/.codex-plugin/plugin.json",
|
||||
manifest,
|
||||
);
|
||||
|
||||
let mut expected = expected_source(/*index*/ 0);
|
||||
expected.hooks.stop[0].hooks[0] = HookHandlerConfig::McpTool {
|
||||
server: "node_repl".to_string(),
|
||||
tool: "turn_ended".to_string(),
|
||||
input: serde_json::from_value(json!({ "untrusted": "manifest-provided input" }))
|
||||
.expect("manifest-provided executor hook input"),
|
||||
timeout_sec: Some(30),
|
||||
status_message: Some("Cleaning up Computer Use".to_string()),
|
||||
};
|
||||
expected.hooks.interrupt = expected.hooks.stop.clone();
|
||||
|
||||
assert_eq!(
|
||||
executor_plugin_hook_sources(&snapshot, &PluginsConfigToml::default()),
|
||||
vec![expected]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_unallowlisted_executor_plugin_hooks() {
|
||||
let mut wrong_event = cleanup_hook_manifest();
|
||||
let hook_events = wrong_event["hooks"]["hooks"]
|
||||
.as_object_mut()
|
||||
.expect("hook events");
|
||||
let stop_groups = hook_events.remove("Stop").expect("stop groups");
|
||||
hook_events.insert("SessionStart".to_string(), stop_groups);
|
||||
let mut wrong_handler = cleanup_hook_manifest();
|
||||
wrong_handler["hooks"]["hooks"]["Stop"][0]["hooks"][0] = json!({
|
||||
"type": "command",
|
||||
"command": "echo cleanup"
|
||||
});
|
||||
let mut wrong_server = cleanup_hook_manifest();
|
||||
wrong_server["hooks"]["hooks"]["Stop"][0]["hooks"][0]["server"] = json!("other");
|
||||
let mut wrong_tool = cleanup_hook_manifest();
|
||||
wrong_tool["hooks"]["hooks"]["Stop"][0]["hooks"][0]["tool"] = json!("other");
|
||||
let mut wrong_matcher = cleanup_hook_manifest();
|
||||
wrong_matcher["hooks"]["hooks"]["Stop"][0]["matcher"] = json!("unexpected");
|
||||
for (name, plugin_id, manifest) in [
|
||||
(
|
||||
"unallowlisted bundled plugin",
|
||||
"another-plugin@openai-bundled",
|
||||
cleanup_hook_manifest(),
|
||||
),
|
||||
(
|
||||
"wrong marketplace",
|
||||
"computer-use@other",
|
||||
cleanup_hook_manifest(),
|
||||
),
|
||||
(
|
||||
"bundled alpha marketplace",
|
||||
"computer-use@openai-bundled-alpha",
|
||||
cleanup_hook_manifest(),
|
||||
),
|
||||
(
|
||||
"bundled marketplace suffix",
|
||||
"computer-use@fake-openai-bundled",
|
||||
cleanup_hook_manifest(),
|
||||
),
|
||||
("wrong event", "computer-use@openai-bundled", wrong_event),
|
||||
(
|
||||
"wrong handler",
|
||||
"computer-use@openai-bundled",
|
||||
wrong_handler,
|
||||
),
|
||||
("wrong server", "computer-use@openai-bundled", wrong_server),
|
||||
("wrong tool", "computer-use@openai-bundled", wrong_tool),
|
||||
(
|
||||
"wrong matcher",
|
||||
"computer-use@openai-bundled",
|
||||
wrong_matcher,
|
||||
),
|
||||
] {
|
||||
let snapshot = snapshot_for_manifest(
|
||||
plugin_id,
|
||||
"executor-a",
|
||||
"file:///plugins/computer-use/.codex-plugin/plugin.json",
|
||||
manifest,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
executor_plugin_hook_sources(&snapshot, &PluginsConfigToml::default()),
|
||||
Vec::<ExecutorPluginHookSource>::new(),
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_file_backed_executor_plugin_hooks() {
|
||||
let file_backed = snapshot_for_manifest(
|
||||
"computer-use@openai-bundled",
|
||||
"executor-a",
|
||||
"file:///plugins/computer-use/.codex-plugin/plugin.json",
|
||||
json!({
|
||||
"name": "computer-use",
|
||||
"hooks": "./hooks/hooks.json"
|
||||
}),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
executor_plugin_hook_sources(&file_backed, &PluginsConfigToml::default()),
|
||||
Vec::<ExecutorPluginHookSource>::new()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn v2_hooks_preserve_admission_policy_and_environment_routing() {
|
||||
let manifest = cleanup_hook_manifest();
|
||||
let files = DiscoveredPluginFiles {
|
||||
manifest: CapabilityTextFile {
|
||||
path: PathUri::parse("file:///plugins/computer-use/.codex-plugin/plugin.json").unwrap(),
|
||||
contents: manifest.to_string(),
|
||||
},
|
||||
mcp_config: None,
|
||||
apps_config: None,
|
||||
};
|
||||
let plugin = akode_exec_server::ExecutorPlugin {
|
||||
id: "computer-use@openai-bundled".to_string(),
|
||||
display_name: "Computer use".to_string(),
|
||||
version: "local".to_string(),
|
||||
root: PathUri::parse("file:///plugins/computer-use").unwrap(),
|
||||
files,
|
||||
skills: Vec::new(),
|
||||
};
|
||||
let mut untrusted = plugin.clone();
|
||||
untrusted.id = "computer-use@untrusted".to_string();
|
||||
let inventory = Arc::new(akode_exec_server::DiscoverV2CapabilitiesResponse {
|
||||
plugins: vec![plugin, untrusted],
|
||||
..Default::default()
|
||||
});
|
||||
let snapshots = [
|
||||
ExecutorCapabilityDiscoveryV2Snapshot {
|
||||
environment_id: "executor-a".to_string(),
|
||||
result: Ok(Arc::clone(&inventory)),
|
||||
},
|
||||
ExecutorCapabilityDiscoveryV2Snapshot {
|
||||
environment_id: "executor-b".to_string(),
|
||||
result: Ok(inventory),
|
||||
},
|
||||
ExecutorCapabilityDiscoveryV2Snapshot {
|
||||
environment_id: "failed".to_string(),
|
||||
result: Err("discovery failed".to_string()),
|
||||
},
|
||||
];
|
||||
let mut second = expected_source(/*index*/ 0);
|
||||
second.environment_id = "executor-b".to_string();
|
||||
assert_eq!(
|
||||
executor_plugin_hook_sources_v2(&snapshots, &PluginsConfigToml::default()),
|
||||
vec![expected_source(/*index*/ 0), second]
|
||||
);
|
||||
let disabled = toml::from_str(
|
||||
"[_default]\nenabled = true\n[\"computer-use@openai-bundled\"]\nenabled = false",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
executor_plugin_hook_sources_v2(&snapshots, &disabled),
|
||||
Vec::new()
|
||||
);
|
||||
}
|
||||
342
akode-rs/core-plugins/src/executor_provider.rs
Normal file
342
akode-rs/core-plugins/src/executor_provider.rs
Normal file
@@ -0,0 +1,342 @@
|
||||
//! Resolves selected plugin roots through their owning executor's filesystem.
|
||||
//! Resource locations retain that environment's authority.
|
||||
|
||||
use crate::PluginProvider;
|
||||
use crate::manifest::parse_plugin_manifest_uri;
|
||||
use akode_exec_server::CapabilityRootDiscovery;
|
||||
use akode_exec_server::EnvironmentManager;
|
||||
use akode_exec_server::ExecutorFileSystem;
|
||||
use akode_exec_server::FileSystemSandboxContext;
|
||||
use akode_exec_server::GetMetadataOptions;
|
||||
use akode_exec_server::ReadFileOptions;
|
||||
use akode_plugin::ResolvedPlugin;
|
||||
use akode_plugin::ResolvedPluginError;
|
||||
use akode_protocol::capabilities::CapabilityRootLocation;
|
||||
use akode_protocol::capabilities::SelectedCapabilityRoot;
|
||||
use akode_utils_path_uri::PathUri;
|
||||
use akode_utils_path_uri::PathUriParseError;
|
||||
use akode_utils_plugins::DISCOVERABLE_PLUGIN_MANIFEST_PATHS;
|
||||
use futures::StreamExt;
|
||||
use std::io;
|
||||
use std::sync::Arc;
|
||||
use thiserror::Error;
|
||||
|
||||
const MAX_CONCURRENT_MANIFEST_PROBES: usize = 256;
|
||||
|
||||
/// Failure to resolve an environment-owned capability root as a plugin package.
|
||||
#[derive(Debug, Error)]
|
||||
pub enum ExecutorPluginProviderError {
|
||||
#[error("discovery failed for selected capability root `{root_id}`")]
|
||||
DiscoveryFailed { root_id: String },
|
||||
#[error(
|
||||
"selected capability root `{root_id}` references unavailable environment `{environment_id}`"
|
||||
)]
|
||||
UnavailableEnvironment {
|
||||
root_id: String,
|
||||
environment_id: String,
|
||||
},
|
||||
#[error("failed to inspect selected capability root `{root_id}` at {path}: {source}")]
|
||||
InspectRoot {
|
||||
root_id: String,
|
||||
path: PathUri,
|
||||
#[source]
|
||||
source: io::Error,
|
||||
},
|
||||
#[error("selected capability root `{root_id}` path {path} is not a directory")]
|
||||
RootNotDirectory { root_id: String, path: PathUri },
|
||||
#[error(
|
||||
"failed to resolve plugin manifest path `{relative_path}` below selected capability root `{root_id}` at {root}: {source}"
|
||||
)]
|
||||
InvalidManifestPath {
|
||||
root_id: String,
|
||||
root: PathUri,
|
||||
relative_path: &'static str,
|
||||
#[source]
|
||||
source: PathUriParseError,
|
||||
},
|
||||
#[error("failed to inspect plugin manifest for `{root_id}` at {path}: {source}")]
|
||||
InspectManifest {
|
||||
root_id: String,
|
||||
path: PathUri,
|
||||
#[source]
|
||||
source: io::Error,
|
||||
},
|
||||
#[error("failed to read plugin manifest for `{root_id}` at {path}: {source}")]
|
||||
ReadManifest {
|
||||
root_id: String,
|
||||
path: PathUri,
|
||||
#[source]
|
||||
source: io::Error,
|
||||
},
|
||||
#[error("failed to parse plugin manifest for `{root_id}` at {path}: {source}")]
|
||||
ParseManifest {
|
||||
root_id: String,
|
||||
path: PathUri,
|
||||
#[source]
|
||||
source: serde_json::Error,
|
||||
},
|
||||
#[error("failed to construct plugin descriptor for `{root_id}`: {source}")]
|
||||
ConstructDescriptor {
|
||||
root_id: String,
|
||||
#[source]
|
||||
source: ResolvedPluginError,
|
||||
},
|
||||
}
|
||||
|
||||
/// Resolves plugin packages through the filesystem owned by an execution environment.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ExecutorPluginProvider {
|
||||
environment_manager: Arc<EnvironmentManager>,
|
||||
}
|
||||
|
||||
/// Ownership of a selected root, independently of whether its manifest can be parsed.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum PluginRootOwnership {
|
||||
Plugin,
|
||||
Standalone,
|
||||
}
|
||||
|
||||
/// A resolved plugin paired with the concrete filesystem used to read it.
|
||||
#[derive(Clone)]
|
||||
pub struct ResolvedExecutorPlugin {
|
||||
plugin: ResolvedPlugin,
|
||||
file_system: Arc<dyn ExecutorFileSystem>,
|
||||
}
|
||||
|
||||
impl ResolvedExecutorPlugin {
|
||||
/// Returns the source-neutral plugin descriptor.
|
||||
pub fn plugin(&self) -> &ResolvedPlugin {
|
||||
&self.plugin
|
||||
}
|
||||
|
||||
/// Returns the concrete filesystem that resolved the descriptor.
|
||||
pub fn file_system(&self) -> &dyn ExecutorFileSystem {
|
||||
self.file_system.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
impl ExecutorPluginProvider {
|
||||
/// Creates a provider backed by the active execution environments.
|
||||
pub fn new(environment_manager: Arc<EnvironmentManager>) -> Self {
|
||||
Self {
|
||||
environment_manager,
|
||||
}
|
||||
}
|
||||
|
||||
/// Classifies ownership before capability parsing. Failed discovery or metadata
|
||||
/// access returns an error, not evidence that a root is standalone.
|
||||
pub async fn root_ownership(
|
||||
&self,
|
||||
selected_root: &SelectedCapabilityRoot,
|
||||
discovery: Option<&CapabilityRootDiscovery>,
|
||||
sandbox: Option<&FileSystemSandboxContext>,
|
||||
) -> Result<PluginRootOwnership, ExecutorPluginProviderError> {
|
||||
let CapabilityRootLocation::Environment {
|
||||
environment_id,
|
||||
path,
|
||||
} = &selected_root.location;
|
||||
if let Some(discovery) = discovery {
|
||||
if discovery.error.is_some() {
|
||||
return Err(ExecutorPluginProviderError::DiscoveryFailed {
|
||||
root_id: selected_root.id.clone(),
|
||||
});
|
||||
}
|
||||
if discovery.plugin.is_some()
|
||||
|| discovery.namespace_manifests.iter().any(|manifest| {
|
||||
manifest
|
||||
.path
|
||||
.parent()
|
||||
.and_then(|directory| directory.parent())
|
||||
.is_some_and(|plugin_root| path.starts_with(&plugin_root))
|
||||
})
|
||||
{
|
||||
return Ok(PluginRootOwnership::Plugin);
|
||||
}
|
||||
if discovery.warnings.is_empty() {
|
||||
return Ok(PluginRootOwnership::Standalone);
|
||||
}
|
||||
}
|
||||
let environment = self
|
||||
.environment_manager
|
||||
.get_environment(environment_id)
|
||||
.ok_or_else(|| ExecutorPluginProviderError::UnavailableEnvironment {
|
||||
root_id: selected_root.id.clone(),
|
||||
environment_id: environment_id.clone(),
|
||||
})?;
|
||||
let file_system = environment.get_filesystem();
|
||||
let manifest = find_manifest(
|
||||
selected_root,
|
||||
std::iter::successors(Some(path.clone()), PathUri::parent),
|
||||
file_system.as_ref(),
|
||||
sandbox,
|
||||
)
|
||||
.await?;
|
||||
Ok(if manifest.is_some() {
|
||||
PluginRootOwnership::Plugin
|
||||
} else {
|
||||
PluginRootOwnership::Standalone
|
||||
})
|
||||
}
|
||||
|
||||
/// Resolves a plugin and retains the exact filesystem used for package access.
|
||||
#[tracing::instrument(name = "plugins.executor.package.resolve", skip_all)]
|
||||
pub async fn resolve_bound(
|
||||
&self,
|
||||
selected_root: &SelectedCapabilityRoot,
|
||||
) -> Result<Option<ResolvedExecutorPlugin>, ExecutorPluginProviderError> {
|
||||
let root_id = &selected_root.id;
|
||||
let plugin_root = selected_plugin_root(selected_root);
|
||||
let CapabilityRootLocation::Environment { environment_id, .. } = &selected_root.location;
|
||||
let environment = self
|
||||
.environment_manager
|
||||
.get_environment(environment_id)
|
||||
.ok_or_else(|| ExecutorPluginProviderError::UnavailableEnvironment {
|
||||
root_id: root_id.clone(),
|
||||
environment_id: environment_id.clone(),
|
||||
})?;
|
||||
let file_system = environment.get_filesystem();
|
||||
let plugin = resolve_plugin_root(selected_root, plugin_root, file_system.as_ref()).await?;
|
||||
|
||||
Ok(plugin.map(|plugin| ResolvedExecutorPlugin {
|
||||
plugin,
|
||||
file_system,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
impl PluginProvider for ExecutorPluginProvider {}
|
||||
|
||||
fn selected_plugin_root(selected_root: &SelectedCapabilityRoot) -> PathUri {
|
||||
let CapabilityRootLocation::Environment { path, .. } = &selected_root.location;
|
||||
path.clone()
|
||||
}
|
||||
|
||||
async fn resolve_plugin_root(
|
||||
selected_root: &SelectedCapabilityRoot,
|
||||
plugin_root: PathUri,
|
||||
file_system: &dyn ExecutorFileSystem,
|
||||
) -> Result<Option<ResolvedPlugin>, ExecutorPluginProviderError> {
|
||||
let root_id = &selected_root.id;
|
||||
let CapabilityRootLocation::Environment { environment_id, .. } = &selected_root.location;
|
||||
let root_metadata = file_system
|
||||
.get_metadata(
|
||||
&plugin_root,
|
||||
GetMetadataOptions::default(),
|
||||
/*sandbox*/ None,
|
||||
)
|
||||
.await
|
||||
.map_err(|source| ExecutorPluginProviderError::InspectRoot {
|
||||
root_id: root_id.clone(),
|
||||
path: plugin_root.clone(),
|
||||
source,
|
||||
})?;
|
||||
if !root_metadata.is_directory {
|
||||
return Err(ExecutorPluginProviderError::RootNotDirectory {
|
||||
root_id: root_id.clone(),
|
||||
path: plugin_root,
|
||||
});
|
||||
}
|
||||
|
||||
let Some(manifest_uri) = find_manifest(
|
||||
selected_root,
|
||||
std::iter::once(plugin_root.clone()),
|
||||
file_system,
|
||||
/*sandbox*/ None,
|
||||
)
|
||||
.await?
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
let contents = file_system
|
||||
.read_file_text(
|
||||
&manifest_uri,
|
||||
ReadFileOptions::default(),
|
||||
/*sandbox*/ None,
|
||||
)
|
||||
.await
|
||||
.map_err(|source| ExecutorPluginProviderError::ReadManifest {
|
||||
root_id: root_id.clone(),
|
||||
path: manifest_uri.clone(),
|
||||
source,
|
||||
})?;
|
||||
let manifest =
|
||||
parse_plugin_manifest_uri(&plugin_root, &manifest_uri, &contents).map_err(|source| {
|
||||
ExecutorPluginProviderError::ParseManifest {
|
||||
root_id: root_id.clone(),
|
||||
path: manifest_uri.clone(),
|
||||
source,
|
||||
}
|
||||
})?;
|
||||
|
||||
let plugin = ResolvedPlugin::from_environment(
|
||||
root_id.clone(),
|
||||
environment_id.clone(),
|
||||
plugin_root,
|
||||
manifest_uri,
|
||||
manifest,
|
||||
)
|
||||
.map_err(|source| ExecutorPluginProviderError::ConstructDescriptor {
|
||||
root_id: root_id.clone(),
|
||||
source,
|
||||
})?;
|
||||
|
||||
Ok(Some(plugin))
|
||||
}
|
||||
|
||||
async fn find_manifest(
|
||||
selected_root: &SelectedCapabilityRoot,
|
||||
mut plugin_roots: impl Iterator<Item = PathUri> + Send,
|
||||
file_system: &dyn ExecutorFileSystem,
|
||||
sandbox: Option<&FileSystemSandboxContext>,
|
||||
) -> Result<Option<PathUri>, ExecutorPluginProviderError> {
|
||||
let root_id = &selected_root.id;
|
||||
let mut plugin_root = plugin_roots.next();
|
||||
let mut marker_index = 0;
|
||||
let probes = std::iter::from_fn(move || {
|
||||
let root = plugin_root.clone()?;
|
||||
let relative_path = *DISCOVERABLE_PLUGIN_MANIFEST_PATHS.get(marker_index)?;
|
||||
let candidate_uri = root.join(relative_path).map_err(|source| {
|
||||
ExecutorPluginProviderError::InvalidManifestPath {
|
||||
root_id: root_id.clone(),
|
||||
root,
|
||||
relative_path,
|
||||
source,
|
||||
}
|
||||
});
|
||||
marker_index += 1;
|
||||
if marker_index == DISCOVERABLE_PLUGIN_MANIFEST_PATHS.len() {
|
||||
marker_index = 0;
|
||||
plugin_root = plugin_roots.next();
|
||||
}
|
||||
Some(candidate_uri)
|
||||
});
|
||||
// Pipeline remote metadata calls while consuming results in ancestor/manifest priority order.
|
||||
let mut results = futures::stream::iter(probes)
|
||||
.map(|candidate_uri| async move {
|
||||
let candidate_uri = candidate_uri?;
|
||||
match file_system
|
||||
.get_metadata(&candidate_uri, GetMetadataOptions::default(), sandbox)
|
||||
.await
|
||||
{
|
||||
Ok(metadata) if metadata.is_file => Ok(Some(candidate_uri)),
|
||||
Ok(_) => Ok(None),
|
||||
Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(None),
|
||||
Err(source) => Err(ExecutorPluginProviderError::InspectManifest {
|
||||
root_id: root_id.clone(),
|
||||
path: candidate_uri,
|
||||
source,
|
||||
}),
|
||||
}
|
||||
})
|
||||
.buffered(MAX_CONCURRENT_MANIFEST_PROBES);
|
||||
while let Some(result) = results.next().await {
|
||||
if let Some(manifest) = result? {
|
||||
return Ok(Some(manifest));
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "executor_provider_tests.rs"]
|
||||
mod tests;
|
||||
657
akode-rs/core-plugins/src/executor_provider_tests.rs
Normal file
657
akode-rs/core-plugins/src/executor_provider_tests.rs
Normal file
@@ -0,0 +1,657 @@
|
||||
use super::ExecutorPluginProvider;
|
||||
use super::ExecutorPluginProviderError;
|
||||
use super::PluginRootOwnership;
|
||||
use super::find_manifest;
|
||||
use super::resolve_plugin_root;
|
||||
use crate::manifest::parse_plugin_manifest_uri;
|
||||
use akode_exec_server::CapabilityRootDiscovery;
|
||||
use akode_exec_server::CapabilityTextFile;
|
||||
use akode_exec_server::CopyOptions;
|
||||
use akode_exec_server::CreateDirectoryOptions;
|
||||
use akode_exec_server::EnvironmentManager;
|
||||
use akode_exec_server::ExecutorFileSystem;
|
||||
use akode_exec_server::ExecutorFileSystemFuture;
|
||||
use akode_exec_server::FileMetadata;
|
||||
use akode_exec_server::FileSystemReadStream;
|
||||
use akode_exec_server::FileSystemResult;
|
||||
use akode_exec_server::FileSystemSandboxContext;
|
||||
use akode_exec_server::GetMetadataOptions;
|
||||
use akode_exec_server::LOCAL_ENVIRONMENT_ID;
|
||||
use akode_exec_server::ReadDirectoryEntry;
|
||||
use akode_exec_server::ReadFileOptions;
|
||||
use akode_exec_server::RemoveOptions;
|
||||
use akode_exec_server::WalkOptions;
|
||||
use akode_exec_server::WalkOutcome;
|
||||
use akode_exec_server::WriteFileOptions;
|
||||
use akode_exec_server_test_support::environment_manager_without_environments;
|
||||
use akode_plugin::ResolvedPlugin;
|
||||
use akode_protocol::capabilities::CapabilityRootLocation;
|
||||
use akode_protocol::capabilities::SelectedCapabilityRoot;
|
||||
use akode_utils_path_uri::PathUri;
|
||||
use akode_utils_plugins::DISCOVERABLE_PLUGIN_MANIFEST_PATHS;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::collections::HashSet;
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use tempfile::tempdir;
|
||||
use tokio::sync::Semaphore;
|
||||
|
||||
const MANIFEST_CONTENTS: &str = r#"{
|
||||
"name": "demo-plugin",
|
||||
"version": " 1.2.3 ",
|
||||
"description": "Demo plugin",
|
||||
"skills": "./skills",
|
||||
"mcpServers": "./.mcp.json",
|
||||
"apps": "./.app.json",
|
||||
"interface": {
|
||||
"displayName": "Demo Plugin",
|
||||
"composerIcon": "./assets/icon.svg"
|
||||
}
|
||||
}"#;
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
enum FileSystemCall {
|
||||
Metadata(PathUri),
|
||||
SandboxedMetadata {
|
||||
path: PathUri,
|
||||
sandbox: Box<FileSystemSandboxContext>,
|
||||
},
|
||||
Read(PathUri),
|
||||
}
|
||||
|
||||
struct SyntheticPluginFileSystem {
|
||||
plugin_root: PathUri,
|
||||
manifest_path: PathUri,
|
||||
calls: Mutex<Vec<FileSystemCall>>,
|
||||
metadata_gate: Option<Arc<Semaphore>>,
|
||||
metadata_delay: Option<(PathUri, Arc<Semaphore>)>,
|
||||
metadata_error: Option<PathUri>,
|
||||
}
|
||||
|
||||
impl SyntheticPluginFileSystem {
|
||||
fn unsupported<T>() -> FileSystemResult<T> {
|
||||
Err(io::Error::new(
|
||||
io::ErrorKind::Unsupported,
|
||||
"operation is not used by plugin resolution",
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
impl ExecutorFileSystem for SyntheticPluginFileSystem {
|
||||
fn canonicalize<'a>(
|
||||
&'a self,
|
||||
_path: &'a PathUri,
|
||||
_sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, PathUri> {
|
||||
Box::pin(async { Self::unsupported() })
|
||||
}
|
||||
|
||||
fn read_file<'a>(
|
||||
&'a self,
|
||||
path: &'a PathUri,
|
||||
_options: ReadFileOptions,
|
||||
_sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, Vec<u8>> {
|
||||
Box::pin(async move {
|
||||
self.calls
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.push(FileSystemCall::Read(path.clone()));
|
||||
if path == &self.manifest_path {
|
||||
Ok(MANIFEST_CONTENTS.as_bytes().to_vec())
|
||||
} else {
|
||||
Err(io::Error::new(io::ErrorKind::NotFound, "not found"))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn read_file_stream<'a>(
|
||||
&'a self,
|
||||
_path: &'a PathUri,
|
||||
_sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, FileSystemReadStream> {
|
||||
Box::pin(async { Self::unsupported() })
|
||||
}
|
||||
|
||||
fn write_file<'a>(
|
||||
&'a self,
|
||||
_path: &'a PathUri,
|
||||
_contents: Vec<u8>,
|
||||
_options: WriteFileOptions,
|
||||
_sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, ()> {
|
||||
Box::pin(async { Self::unsupported() })
|
||||
}
|
||||
|
||||
fn create_directory<'a>(
|
||||
&'a self,
|
||||
_path: &'a PathUri,
|
||||
_options: CreateDirectoryOptions,
|
||||
_sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, ()> {
|
||||
Box::pin(async { Self::unsupported() })
|
||||
}
|
||||
|
||||
fn get_metadata<'a>(
|
||||
&'a self,
|
||||
path: &'a PathUri,
|
||||
_options: GetMetadataOptions,
|
||||
sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, FileMetadata> {
|
||||
Box::pin(async move {
|
||||
self.calls
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.push(match sandbox {
|
||||
Some(sandbox) => FileSystemCall::SandboxedMetadata {
|
||||
path: path.clone(),
|
||||
sandbox: Box::new(sandbox.clone()),
|
||||
},
|
||||
None => FileSystemCall::Metadata(path.clone()),
|
||||
});
|
||||
if let Some(gate) = &self.metadata_gate {
|
||||
gate.acquire().await.expect("open metadata gate").forget();
|
||||
}
|
||||
if let Some((delayed_path, gate)) = &self.metadata_delay
|
||||
&& delayed_path == path
|
||||
{
|
||||
gate.acquire().await.expect("open delayed gate").forget();
|
||||
}
|
||||
if self.metadata_error.as_ref() == Some(path) {
|
||||
return Err(io::Error::new(io::ErrorKind::PermissionDenied, "denied"));
|
||||
}
|
||||
let (is_directory, is_file) = if path == &self.plugin_root {
|
||||
(true, false)
|
||||
} else if path == &self.manifest_path {
|
||||
(false, true)
|
||||
} else {
|
||||
return Err(io::Error::new(io::ErrorKind::NotFound, "not found"));
|
||||
};
|
||||
Ok(FileMetadata {
|
||||
is_directory,
|
||||
is_file,
|
||||
is_symlink: false,
|
||||
size: 0,
|
||||
created_at_ms: 0,
|
||||
modified_at_ms: 0,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn read_directory<'a>(
|
||||
&'a self,
|
||||
_path: &'a PathUri,
|
||||
_sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, Vec<ReadDirectoryEntry>> {
|
||||
Box::pin(async { Self::unsupported() })
|
||||
}
|
||||
|
||||
fn walk<'a>(
|
||||
&'a self,
|
||||
_path: &'a PathUri,
|
||||
_options: WalkOptions,
|
||||
_sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, WalkOutcome> {
|
||||
Box::pin(async { Self::unsupported() })
|
||||
}
|
||||
|
||||
fn remove<'a>(
|
||||
&'a self,
|
||||
_path: &'a PathUri,
|
||||
_options: RemoveOptions,
|
||||
_sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, ()> {
|
||||
Box::pin(async { Self::unsupported() })
|
||||
}
|
||||
|
||||
fn copy<'a>(
|
||||
&'a self,
|
||||
_source_path: &'a PathUri,
|
||||
_destination_path: &'a PathUri,
|
||||
_options: CopyOptions,
|
||||
_sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, ()> {
|
||||
Box::pin(async { Self::unsupported() })
|
||||
}
|
||||
}
|
||||
|
||||
fn write_manifest(plugin_root: &Path, relative_path: &str, contents: &str) {
|
||||
let manifest_path = plugin_root.join(relative_path);
|
||||
fs::create_dir_all(manifest_path.parent().expect("manifest parent"))
|
||||
.expect("create manifest parent");
|
||||
fs::write(manifest_path, contents).expect("write manifest");
|
||||
}
|
||||
|
||||
fn selected_root(id: &str, environment_id: &str, path: &Path) -> SelectedCapabilityRoot {
|
||||
SelectedCapabilityRoot {
|
||||
id: id.to_string(),
|
||||
location: CapabilityRootLocation::Environment {
|
||||
environment_id: environment_id.to_string(),
|
||||
path: PathUri::from_host_native_path(path).expect("path URI"),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn selected_root_uri(id: &str, environment_id: &str, path: PathUri) -> SelectedCapabilityRoot {
|
||||
SelectedCapabilityRoot {
|
||||
id: id.to_string(),
|
||||
location: CapabilityRootLocation::Environment {
|
||||
environment_id: environment_id.to_string(),
|
||||
path,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn root_ownership_survives_malformed_ancestor_manifests() {
|
||||
let directory = tempdir().expect("tempdir");
|
||||
let root = directory.path().join("package/skills");
|
||||
fs::create_dir_all(&root).expect("create skills root");
|
||||
let provider = ExecutorPluginProvider::new(Arc::new(EnvironmentManager::default_for_tests()));
|
||||
let selected = selected_root("example@marketplace", LOCAL_ENVIRONMENT_ID, &root);
|
||||
assert_eq!(
|
||||
provider
|
||||
.root_ownership(&selected, /*discovery*/ None, /*sandbox*/ None)
|
||||
.await
|
||||
.unwrap(),
|
||||
PluginRootOwnership::Standalone
|
||||
);
|
||||
write_manifest(
|
||||
root.parent().unwrap(),
|
||||
".codex-plugin/plugin.json",
|
||||
"{broken",
|
||||
);
|
||||
assert_eq!(
|
||||
provider
|
||||
.root_ownership(&selected, /*discovery*/ None, /*sandbox*/ None)
|
||||
.await
|
||||
.unwrap(),
|
||||
PluginRootOwnership::Plugin
|
||||
);
|
||||
let mut discovery = CapabilityRootDiscovery {
|
||||
id: selected.id.clone(),
|
||||
path: PathUri::from_host_native_path(&root).unwrap(),
|
||||
plugin: None,
|
||||
skills: Vec::new(),
|
||||
namespace_manifests: Vec::new(),
|
||||
warnings: vec!["unreadable manifest".into()],
|
||||
error: None,
|
||||
};
|
||||
assert_eq!(
|
||||
provider
|
||||
.root_ownership(&selected, Some(&discovery), /*sandbox*/ None)
|
||||
.await
|
||||
.unwrap(),
|
||||
PluginRootOwnership::Plugin
|
||||
);
|
||||
discovery.error = Some("discovery failed".into());
|
||||
assert!(matches!(
|
||||
provider
|
||||
.root_ownership(&selected, Some(&discovery), /*sandbox*/ None)
|
||||
.await,
|
||||
Err(ExecutorPluginProviderError::DiscoveryFailed { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn discovery_ownership_uses_ancestors_not_nested_plugins() {
|
||||
let directory = tempdir().expect("tempdir");
|
||||
let path = PathUri::from_host_native_path(directory.path()).unwrap();
|
||||
let selected = selected_root_uri("example@marketplace", "executor", path.clone());
|
||||
let provider =
|
||||
ExecutorPluginProvider::new(Arc::new(environment_manager_without_environments()));
|
||||
let mut discovery = CapabilityRootDiscovery {
|
||||
id: selected.id.clone(),
|
||||
path: path.clone(),
|
||||
plugin: None,
|
||||
skills: Vec::new(),
|
||||
namespace_manifests: vec![CapabilityTextFile {
|
||||
path: path.join("nested/.codex-plugin/plugin.json").unwrap(),
|
||||
contents: "{broken".into(),
|
||||
}],
|
||||
warnings: Vec::new(),
|
||||
error: None,
|
||||
};
|
||||
assert_eq!(
|
||||
provider
|
||||
.root_ownership(&selected, Some(&discovery), /*sandbox*/ None)
|
||||
.await
|
||||
.unwrap(),
|
||||
PluginRootOwnership::Standalone
|
||||
);
|
||||
discovery.namespace_manifests[0].path = path.join(".codex-plugin/plugin.json").unwrap();
|
||||
assert_eq!(
|
||||
provider
|
||||
.root_ownership(&selected, Some(&discovery), /*sandbox*/ None)
|
||||
.await
|
||||
.unwrap(),
|
||||
PluginRootOwnership::Plugin
|
||||
);
|
||||
assert!(matches!(
|
||||
provider
|
||||
.root_ownership(&selected, /*discovery*/ None, /*sandbox*/ None)
|
||||
.await,
|
||||
Err(ExecutorPluginProviderError::UnavailableEnvironment { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ancestor_manifest_probes_pipeline_and_preserve_error_order() {
|
||||
let root = PathUri::parse("file:///a/b/c/d/e/f").expect("selected root URI");
|
||||
let owner = PathUri::parse("file:///a/b/c").expect("owner URI");
|
||||
let manifest = owner.join(".codex-plugin/plugin.json").unwrap();
|
||||
let earlier_error = root.join(".codex-plugin/plugin.json").unwrap();
|
||||
let later_error = owner.join(".claude-plugin/plugin.json").unwrap();
|
||||
let expected_probes = std::iter::successors(Some(root.clone()), PathUri::parent)
|
||||
.flat_map(|ancestor| {
|
||||
DISCOVERABLE_PLUGIN_MANIFEST_PATHS
|
||||
.iter()
|
||||
.map(move |marker| ancestor.join(marker).unwrap())
|
||||
})
|
||||
.collect::<HashSet<_>>();
|
||||
|
||||
for (metadata_error, expected) in [
|
||||
(None, Ok(Some(manifest.clone()))),
|
||||
(
|
||||
Some(earlier_error.clone()),
|
||||
Err((earlier_error.clone(), io::ErrorKind::PermissionDenied)),
|
||||
),
|
||||
(Some(later_error), Ok(Some(manifest.clone()))),
|
||||
] {
|
||||
let gate = Arc::new(Semaphore::new(/*permits*/ 0));
|
||||
let earliest_gate = Arc::new(Semaphore::new(/*permits*/ 0));
|
||||
let file_system = SyntheticPluginFileSystem {
|
||||
// A directory named like a manifest must not count as plugin ownership.
|
||||
plugin_root: earlier_error.clone(),
|
||||
manifest_path: manifest.clone(),
|
||||
calls: Mutex::new(Vec::new()),
|
||||
metadata_gate: Some(Arc::clone(&gate)),
|
||||
metadata_delay: Some((earlier_error.clone(), Arc::clone(&earliest_gate))),
|
||||
metadata_error,
|
||||
};
|
||||
let selected = selected_root_uri("example@marketplace", "executor", root.clone());
|
||||
let mut resolution = Box::pin(find_manifest(
|
||||
&selected,
|
||||
std::iter::successors(Some(root.clone()), PathUri::parent),
|
||||
&file_system,
|
||||
/*sandbox*/ None,
|
||||
));
|
||||
assert!(futures::poll!(resolution.as_mut()).is_pending());
|
||||
let probes = file_system
|
||||
.calls
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.iter()
|
||||
.map(|call| match call {
|
||||
FileSystemCall::Metadata(path) => path.clone(),
|
||||
call => panic!("unexpected filesystem call: {call:?}"),
|
||||
})
|
||||
.collect::<HashSet<_>>();
|
||||
assert_eq!(probes, expected_probes);
|
||||
gate.add_permits(probes.len());
|
||||
// Later successes/errors cannot outrank the earliest still-pending candidate.
|
||||
assert!(futures::poll!(resolution.as_mut()).is_pending());
|
||||
earliest_gate.add_permits(/*n*/ 1);
|
||||
let result = resolution.await.map_err(|error| {
|
||||
let ExecutorPluginProviderError::InspectManifest { path, source, .. } = error else {
|
||||
panic!("unexpected manifest resolution error: {error}");
|
||||
};
|
||||
(path, source.kind())
|
||||
});
|
||||
assert_eq!(result, expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn manifest_presence_uses_sandboxed_metadata_without_reading_contents() {
|
||||
let directory = tempdir().expect("tempdir");
|
||||
let plugin_root = PathUri::from_host_native_path(directory.path()).expect("root URI");
|
||||
let manifest_path = plugin_root
|
||||
.join(".codex-plugin/plugin.json")
|
||||
.expect("manifest URI");
|
||||
let file_system = SyntheticPluginFileSystem {
|
||||
plugin_root: plugin_root.clone(),
|
||||
manifest_path: manifest_path.clone(),
|
||||
calls: Mutex::new(Vec::new()),
|
||||
metadata_gate: None,
|
||||
metadata_delay: None,
|
||||
metadata_error: None,
|
||||
};
|
||||
let sandbox =
|
||||
FileSystemSandboxContext::from_permission_profile(Default::default(), plugin_root.clone());
|
||||
assert_eq!(
|
||||
find_manifest(
|
||||
&selected_root_uri("selected-demo", "executor-test", plugin_root.clone()),
|
||||
std::iter::once(plugin_root.clone()),
|
||||
&file_system,
|
||||
Some(&sandbox),
|
||||
)
|
||||
.await
|
||||
.expect("probe manifest"),
|
||||
Some(manifest_path.clone()),
|
||||
);
|
||||
assert_eq!(
|
||||
*file_system
|
||||
.calls
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner),
|
||||
vec![FileSystemCall::SandboxedMetadata {
|
||||
path: manifest_path,
|
||||
sandbox: Box::new(sandbox)
|
||||
}],
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn plugin_root_resolution_uses_supplied_executor_file_system() {
|
||||
let temp_dir = tempdir().expect("tempdir");
|
||||
let plugin_root = temp_dir.path().join("executor-only-plugin");
|
||||
assert!(!plugin_root.exists());
|
||||
let plugin_root = PathUri::from_host_native_path(&plugin_root).expect("plugin root URI");
|
||||
let manifest_path = plugin_root
|
||||
.join(".codex-plugin/plugin.json")
|
||||
.expect("manifest URI");
|
||||
let parsed_manifest =
|
||||
parse_plugin_manifest_uri(&plugin_root, &manifest_path, MANIFEST_CONTENTS)
|
||||
.expect("parse manifest");
|
||||
let file_system = SyntheticPluginFileSystem {
|
||||
plugin_root: plugin_root.clone(),
|
||||
manifest_path: manifest_path.clone(),
|
||||
calls: Mutex::new(Vec::new()),
|
||||
metadata_gate: None,
|
||||
metadata_delay: None,
|
||||
metadata_error: None,
|
||||
};
|
||||
let resolved = resolve_plugin_root(
|
||||
&selected_root_uri("selected-demo", "executor-test", plugin_root.clone()),
|
||||
plugin_root.clone(),
|
||||
&file_system,
|
||||
)
|
||||
.await
|
||||
.expect("resolve executor plugin");
|
||||
|
||||
assert_eq!(
|
||||
resolved,
|
||||
Some(
|
||||
ResolvedPlugin::from_environment(
|
||||
"selected-demo".to_string(),
|
||||
"executor-test".to_string(),
|
||||
plugin_root.clone(),
|
||||
manifest_path.clone(),
|
||||
parsed_manifest,
|
||||
)
|
||||
.expect("valid expected descriptor")
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
*file_system
|
||||
.calls
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner),
|
||||
vec![
|
||||
FileSystemCall::Metadata(plugin_root),
|
||||
FileSystemCall::Metadata(manifest_path.clone()),
|
||||
FileSystemCall::Read(manifest_path),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn plugin_root_resolution_accepts_foreign_executor_file_uri() {
|
||||
let plugin_root = PathUri::parse("file:///C:/plugins/foo").expect("Windows plugin root URI");
|
||||
let manifest_path = plugin_root
|
||||
.join(".codex-plugin/plugin.json")
|
||||
.expect("manifest URI");
|
||||
let parsed_manifest =
|
||||
parse_plugin_manifest_uri(&plugin_root, &manifest_path, MANIFEST_CONTENTS)
|
||||
.expect("parse manifest");
|
||||
let file_system = SyntheticPluginFileSystem {
|
||||
plugin_root: plugin_root.clone(),
|
||||
manifest_path: manifest_path.clone(),
|
||||
calls: Mutex::new(Vec::new()),
|
||||
metadata_gate: None,
|
||||
metadata_delay: None,
|
||||
metadata_error: None,
|
||||
};
|
||||
let selected_root = selected_root_uri("selected-demo", "executor-test", plugin_root.clone());
|
||||
let resolved = resolve_plugin_root(&selected_root, plugin_root.clone(), &file_system)
|
||||
.await
|
||||
.expect("resolve executor plugin");
|
||||
|
||||
assert_eq!(
|
||||
resolved,
|
||||
Some(
|
||||
ResolvedPlugin::from_environment(
|
||||
"selected-demo".to_string(),
|
||||
"executor-test".to_string(),
|
||||
plugin_root.clone(),
|
||||
manifest_path.clone(),
|
||||
parsed_manifest,
|
||||
)
|
||||
.expect("valid expected descriptor")
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
*file_system
|
||||
.calls
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner),
|
||||
vec![
|
||||
FileSystemCall::Metadata(plugin_root),
|
||||
FileSystemCall::Metadata(manifest_path.clone()),
|
||||
FileSystemCall::Read(manifest_path),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn standalone_capability_root_is_not_a_plugin() {
|
||||
let temp_dir = tempdir().expect("tempdir");
|
||||
let standalone_root = temp_dir.path().join("standalone-skill");
|
||||
fs::create_dir_all(&standalone_root).expect("create standalone root");
|
||||
let provider = ExecutorPluginProvider::new(Arc::new(EnvironmentManager::default_for_tests()));
|
||||
|
||||
let resolved = provider
|
||||
.resolve_bound(&selected_root(
|
||||
"standalone",
|
||||
LOCAL_ENVIRONMENT_ID,
|
||||
&standalone_root,
|
||||
))
|
||||
.await
|
||||
.expect("resolve standalone root");
|
||||
|
||||
assert!(resolved.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn root_agent_plugin_manifest_is_not_an_executor_plugin() {
|
||||
let temp_dir = tempdir().expect("tempdir");
|
||||
let plugin_root = temp_dir.path().join("agent-plugin");
|
||||
write_manifest(
|
||||
&plugin_root,
|
||||
"plugin.json",
|
||||
r#"{
|
||||
"$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
|
||||
"name": "agent-plugin",
|
||||
"version": "1.0.0"
|
||||
}"#,
|
||||
);
|
||||
let provider = ExecutorPluginProvider::new(Arc::new(EnvironmentManager::default_for_tests()));
|
||||
|
||||
let resolved = provider
|
||||
.resolve_bound(&selected_root(
|
||||
"agent-plugin",
|
||||
LOCAL_ENVIRONMENT_ID,
|
||||
&plugin_root,
|
||||
))
|
||||
.await
|
||||
.expect("resolve selected root");
|
||||
|
||||
assert!(resolved.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unavailable_environment_does_not_fall_back_to_host_filesystem() {
|
||||
let temp_dir = tempdir().expect("tempdir");
|
||||
let plugin_root = temp_dir.path().join("host-plugin");
|
||||
write_manifest(&plugin_root, ".codex-plugin/plugin.json", MANIFEST_CONTENTS);
|
||||
let provider =
|
||||
ExecutorPluginProvider::new(Arc::new(environment_manager_without_environments()));
|
||||
|
||||
let err = provider
|
||||
.resolve_bound(&selected_root("host-plugin", "missing", &plugin_root))
|
||||
.await
|
||||
.map(|_| ())
|
||||
.expect_err("missing environment should fail");
|
||||
|
||||
assert_eq!(
|
||||
err.to_string(),
|
||||
"selected capability root `host-plugin` references unavailable environment `missing`"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn malformed_preferred_manifest_does_not_fall_through_to_alternate() {
|
||||
let temp_dir = tempdir().expect("tempdir");
|
||||
let plugin_root = temp_dir.path().join("demo-plugin");
|
||||
write_manifest(&plugin_root, ".codex-plugin/plugin.json", "{not-json");
|
||||
write_manifest(
|
||||
&plugin_root,
|
||||
".claude-plugin/plugin.json",
|
||||
MANIFEST_CONTENTS,
|
||||
);
|
||||
let expected_path =
|
||||
PathUri::from_host_native_path(plugin_root.join(".codex-plugin/plugin.json"))
|
||||
.expect("manifest URI");
|
||||
let provider = ExecutorPluginProvider::new(Arc::new(EnvironmentManager::default_for_tests()));
|
||||
|
||||
let err = provider
|
||||
.resolve_bound(&selected_root(
|
||||
"selected-demo",
|
||||
LOCAL_ENVIRONMENT_ID,
|
||||
&plugin_root,
|
||||
))
|
||||
.await
|
||||
.map(|_| ())
|
||||
.expect_err("malformed preferred manifest should fail");
|
||||
|
||||
assert!(
|
||||
std::error::Error::source(&err)
|
||||
.is_some_and(<dyn std::error::Error>::is::<serde_json::Error>)
|
||||
);
|
||||
let ExecutorPluginProviderError::ParseManifest {
|
||||
root_id,
|
||||
path,
|
||||
source: _,
|
||||
} = err
|
||||
else {
|
||||
panic!("expected parse error");
|
||||
};
|
||||
assert_eq!(
|
||||
(root_id, path),
|
||||
("selected-demo".to_string(), expected_path)
|
||||
);
|
||||
}
|
||||
85
akode-rs/core-plugins/src/git_policy.rs
Normal file
85
akode-rs/core-plugins/src/git_policy.rs
Normal file
@@ -0,0 +1,85 @@
|
||||
use akode_utils_absolute_path::AbsolutePathBuf;
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
use tempfile::TempDir;
|
||||
|
||||
// These variables can redirect Git to an untrusted repository or inject command-scoped settings.
|
||||
pub(crate) const REPOSITORY_LOCAL_GIT_ENVIRONMENT_VARIABLES: &[&str] = &[
|
||||
"GIT_ALTERNATE_OBJECT_DIRECTORIES",
|
||||
"GIT_CEILING_DIRECTORIES",
|
||||
"GIT_COMMON_DIR",
|
||||
"GIT_CONFIG",
|
||||
"GIT_CONFIG_COUNT",
|
||||
"GIT_CONFIG_PARAMETERS",
|
||||
"GIT_DIR",
|
||||
"GIT_DISCOVERY_ACROSS_FILESYSTEM",
|
||||
"GIT_GRAFT_FILE",
|
||||
"GIT_IMPLICIT_WORK_TREE",
|
||||
"GIT_INDEX_FILE",
|
||||
"GIT_NAMESPACE",
|
||||
"GIT_OBJECT_DIRECTORY",
|
||||
"GIT_PREFIX",
|
||||
"GIT_REPLACE_REF_BASE",
|
||||
"GIT_SHALLOW_FILE",
|
||||
"GIT_WORK_TREE",
|
||||
];
|
||||
|
||||
/// Distinguishes isolated background Git operations from explicitly requested user operations.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum PluginGitMode {
|
||||
/// Ignores repository-scoped Git configuration inherited from the launch project.
|
||||
Automatic,
|
||||
/// Preserves the configuration explicitly available to user-requested Git commands.
|
||||
Manual,
|
||||
}
|
||||
|
||||
impl PluginGitMode {
|
||||
/// Creates a Git command with the repository-environment policy for this operation.
|
||||
/// Automatic remote lookups and initial clones must also select a trusted repository.
|
||||
pub(crate) fn command(self, git_binary: &Path) -> Command {
|
||||
let mut command = akode_utils_process::background_command(git_binary);
|
||||
command.args(["-c", akode_git_utils::SAFE_BARE_REPOSITORY_CONFIG]);
|
||||
if matches!(self, Self::Automatic) {
|
||||
command.env("GIT_OPTIONAL_LOCKS", "0");
|
||||
for name in REPOSITORY_LOCAL_GIT_ENVIRONMENT_VARIABLES {
|
||||
command.env_remove(name);
|
||||
}
|
||||
}
|
||||
command
|
||||
}
|
||||
}
|
||||
|
||||
/// Isolates an automatic Git command from repository discovery in the launch project.
|
||||
///
|
||||
/// The command must already have repository-scoped environment variables removed. Keep the
|
||||
/// returned guard alive until the Git process exits because it owns the selected repository.
|
||||
pub(crate) fn configure_trusted_git_repository(
|
||||
command: &mut Command,
|
||||
codex_home: &Path,
|
||||
) -> Result<TempDir, String> {
|
||||
let canonical_home = AbsolutePathBuf::from_absolute_path(codex_home)
|
||||
.and_then(|path| path.canonicalize())
|
||||
.map_err(|err| format!("failed to resolve trusted Codex home: {err}"))?;
|
||||
let staging_root = canonical_home.join(".tmp");
|
||||
std::fs::create_dir_all(staging_root.as_path())
|
||||
.map_err(|err| format!("failed to create trusted Git repository root: {err}"))?;
|
||||
let staging_root = staging_root
|
||||
.canonicalize()
|
||||
.map_err(|err| format!("failed to resolve trusted Git repository root: {err}"))?;
|
||||
if !staging_root.as_path().starts_with(canonical_home.as_path()) {
|
||||
return Err("trusted Git repository root escapes Codex home".to_string());
|
||||
}
|
||||
|
||||
let repository = tempfile::Builder::new()
|
||||
.prefix("git-")
|
||||
.tempdir_in(staging_root.as_path())
|
||||
.map_err(|err| format!("failed to create trusted Git repository: {err}"))?;
|
||||
for directory in ["objects", "refs"] {
|
||||
std::fs::create_dir(repository.path().join(directory))
|
||||
.map_err(|err| format!("failed to initialize trusted Git repository: {err}"))?;
|
||||
}
|
||||
std::fs::write(repository.path().join("HEAD"), "ref: refs/heads/main\n")
|
||||
.map_err(|err| format!("failed to initialize trusted Git repository HEAD: {err}"))?;
|
||||
command.env("GIT_DIR", repository.path());
|
||||
Ok(repository)
|
||||
}
|
||||
78
akode-rs/core-plugins/src/installed_marketplaces.rs
Normal file
78
akode-rs/core-plugins/src/installed_marketplaces.rs
Normal file
@@ -0,0 +1,78 @@
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use akode_config::ConfigLayerStack;
|
||||
use akode_plugin::validate_plugin_segment;
|
||||
use akode_utils_absolute_path::AbsolutePathBuf;
|
||||
use tracing::warn;
|
||||
|
||||
use crate::marketplace::find_marketplace_manifest_path;
|
||||
use crate::marketplace_policy::policy_filtered_plugin_config;
|
||||
|
||||
pub const INSTALLED_MARKETPLACES_DIR: &str = ".tmp/marketplaces";
|
||||
|
||||
pub fn marketplace_install_root(codex_home: &Path) -> PathBuf {
|
||||
codex_home.join(INSTALLED_MARKETPLACES_DIR)
|
||||
}
|
||||
|
||||
pub fn installed_marketplace_roots_from_layer_stack(
|
||||
config_layer_stack: &ConfigLayerStack,
|
||||
codex_home: &Path,
|
||||
) -> Vec<AbsolutePathBuf> {
|
||||
let Some(effective_config) = policy_filtered_plugin_config(config_layer_stack, codex_home)
|
||||
else {
|
||||
return Vec::new();
|
||||
};
|
||||
let Some(marketplaces_value) = effective_config.get("marketplaces") else {
|
||||
return Vec::new();
|
||||
};
|
||||
let Some(marketplaces) = marketplaces_value.as_table() else {
|
||||
warn!("invalid marketplaces config: expected table");
|
||||
return Vec::new();
|
||||
};
|
||||
let default_install_root = marketplace_install_root(codex_home);
|
||||
let mut roots = marketplaces
|
||||
.iter()
|
||||
.filter_map(|(marketplace_name, marketplace)| {
|
||||
if !marketplace.is_table() {
|
||||
warn!(
|
||||
marketplace_name,
|
||||
"ignoring invalid configured marketplace entry"
|
||||
);
|
||||
return None;
|
||||
}
|
||||
if let Err(err) = validate_plugin_segment(marketplace_name, "marketplace name") {
|
||||
warn!(
|
||||
marketplace_name,
|
||||
error = %err,
|
||||
"ignoring invalid configured marketplace name"
|
||||
);
|
||||
return None;
|
||||
}
|
||||
let path = resolve_configured_marketplace_root(
|
||||
marketplace_name,
|
||||
marketplace,
|
||||
&default_install_root,
|
||||
)?;
|
||||
find_marketplace_manifest_path(&path).map(|_| path)
|
||||
})
|
||||
.filter_map(|path| AbsolutePathBuf::try_from(path).ok())
|
||||
.collect::<Vec<_>>();
|
||||
roots.sort_unstable_by(|left, right| left.as_path().cmp(right.as_path()));
|
||||
roots
|
||||
}
|
||||
|
||||
pub fn resolve_configured_marketplace_root(
|
||||
marketplace_name: &str,
|
||||
marketplace: &toml::Value,
|
||||
default_install_root: &Path,
|
||||
) -> Option<PathBuf> {
|
||||
match marketplace.get("source_type").and_then(toml::Value::as_str) {
|
||||
Some("local") => marketplace
|
||||
.get("source")
|
||||
.and_then(toml::Value::as_str)
|
||||
.filter(|source| !source.is_empty())
|
||||
.map(PathBuf::from),
|
||||
_ => Some(default_install_root.join(marketplace_name)),
|
||||
}
|
||||
}
|
||||
102
akode-rs/core-plugins/src/lib.rs
Normal file
102
akode-rs/core-plugins/src/lib.rs
Normal file
@@ -0,0 +1,102 @@
|
||||
mod artifact_operation;
|
||||
mod catalog;
|
||||
mod command_migration;
|
||||
mod discoverable;
|
||||
mod executor_catalog;
|
||||
mod executor_hooks;
|
||||
mod executor_provider;
|
||||
mod git_policy;
|
||||
pub mod installed_marketplaces;
|
||||
mod loaded_cache_metrics;
|
||||
pub mod loader;
|
||||
mod manager;
|
||||
pub mod manifest;
|
||||
pub mod marketplace;
|
||||
pub mod marketplace_add;
|
||||
mod marketplace_policy;
|
||||
pub mod marketplace_remove;
|
||||
mod marketplace_staging;
|
||||
pub mod marketplace_upgrade;
|
||||
mod npm_source;
|
||||
mod plugin_bundle_archive;
|
||||
mod provider;
|
||||
mod script_attribution;
|
||||
mod skill_snapshots;
|
||||
pub mod startup_sync;
|
||||
pub mod store;
|
||||
#[cfg(test)]
|
||||
mod test_support;
|
||||
pub mod toggles;
|
||||
mod tool_suggest_metadata;
|
||||
|
||||
pub(crate) use git_policy::PluginGitMode;
|
||||
pub(crate) use git_policy::configure_trusted_git_repository;
|
||||
|
||||
pub const OPENAI_CURATED_MARKETPLACE_NAME: &str = "openai-curated";
|
||||
pub const OPENAI_API_CURATED_MARKETPLACE_NAME: &str = "openai-api-curated";
|
||||
pub const OPENAI_BUNDLED_MARKETPLACE_NAME: &str = "openai-bundled";
|
||||
pub(crate) const OPENAI_BUNDLED_ALPHA_MARKETPLACE_NAME: &str = "openai-bundled-alpha";
|
||||
pub(crate) const OPENAI_PRIMARY_RUNTIME_MARKETPLACE_NAME: &str = "openai-primary-runtime";
|
||||
|
||||
pub fn is_openai_curated_marketplace_name(marketplace_name: &str) -> bool {
|
||||
marketplace_name == OPENAI_CURATED_MARKETPLACE_NAME
|
||||
|| marketplace_name == OPENAI_API_CURATED_MARKETPLACE_NAME
|
||||
}
|
||||
|
||||
pub type LoadedPlugin = akode_plugin::LoadedPlugin<akode_config::McpServerConfig>;
|
||||
pub type PluginLoadOutcome = akode_plugin::PluginLoadOutcome<akode_config::McpServerConfig>;
|
||||
|
||||
pub use artifact_operation::ArtifactOperation;
|
||||
pub use artifact_operation::recognize_artifact_operation;
|
||||
pub use catalog::PluginCatalog;
|
||||
pub use catalog::PluginCatalogEntry;
|
||||
pub use catalog::PluginSourceLocation;
|
||||
pub use catalog::merge_catalogs;
|
||||
pub use akode_core_plugin_common::PluginIdentity;
|
||||
pub use command_migration::CommandDescriptionMode;
|
||||
pub use command_migration::CommandMigrationProfile;
|
||||
pub use command_migration::RewriteProfile as CommandRewriteProfile;
|
||||
pub use command_migration::count_missing_commands_with_profile;
|
||||
pub use command_migration::import_commands_with_profile;
|
||||
pub use command_migration::missing_command_names_with_profile;
|
||||
pub use discoverable::ToolSuggestDiscoverablePlugin;
|
||||
pub use discoverable::ToolSuggestPluginDiscoveryInput;
|
||||
pub use executor_catalog::catalog_from_snapshots;
|
||||
pub use executor_hooks::executor_plugin_hook_sources;
|
||||
pub use executor_hooks::executor_plugin_hook_sources_v2;
|
||||
pub use executor_provider::ExecutorPluginProvider;
|
||||
pub use executor_provider::ExecutorPluginProviderError;
|
||||
pub use executor_provider::PluginRootOwnership;
|
||||
pub use executor_provider::ResolvedExecutorPlugin;
|
||||
pub use loader::PluginHookLoadOutcome;
|
||||
pub use manager::ConfiguredMarketplace;
|
||||
pub use manager::ConfiguredMarketplaceListOutcome;
|
||||
pub use manager::ConfiguredMarketplacePlugin;
|
||||
pub use manager::EffectivePluginsChange;
|
||||
pub use manager::PluginDetail;
|
||||
pub use manager::PluginDetailsUnavailableReason;
|
||||
pub use manager::PluginInstallError;
|
||||
pub use manager::PluginInstallOutcome;
|
||||
pub use manager::PluginInstallRequest;
|
||||
pub use manager::PluginListBackgroundTaskOptions;
|
||||
pub use manager::PluginMarketplaceContext;
|
||||
pub use manager::PluginMarketplaceScope;
|
||||
pub use manager::PluginReadOutcome;
|
||||
pub use manager::PluginReadRequest;
|
||||
pub use manager::PluginUninstallError;
|
||||
pub use manager::PluginsConfigInput;
|
||||
pub use manager::PluginsManager;
|
||||
pub use marketplace_policy::allowed_configured_marketplace_names;
|
||||
pub use marketplace_upgrade::ConfigLayerReload;
|
||||
pub use marketplace_upgrade::ConfiguredMarketplaceUpgradeError as PluginMarketplaceUpgradeError;
|
||||
pub use marketplace_upgrade::ConfiguredMarketplaceUpgradeOutcome as PluginMarketplaceUpgradeOutcome;
|
||||
pub use provider::PluginListQuery;
|
||||
pub use provider::PluginProvider;
|
||||
pub use provider::PluginProviderError;
|
||||
pub use provider::PluginProviderFuture;
|
||||
pub use provider::PluginProviderResult;
|
||||
pub use script_attribution::PluginCommandAttribution;
|
||||
pub use script_attribution::TrustedPluginRoots;
|
||||
pub use script_attribution::command_script_arguments;
|
||||
|
||||
pub use marketplace_policy::configured_plugins_from_stack;
|
||||
49
akode-rs/core-plugins/src/loaded_cache_metrics.rs
Normal file
49
akode-rs/core-plugins/src/loaded_cache_metrics.rs
Normal file
@@ -0,0 +1,49 @@
|
||||
//! Request counts exclude disabled plugins, account-switch discards, and cancellations.
|
||||
//! Auth retries keep the furthest request outcome reached; each completed wait/load is timed.
|
||||
//! Skill-snapshot lookups are not requests. Clear events include already-empty caches.
|
||||
//! Tags never contain configuration data.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
pub(crate) const LOAD_DURATION: &str = "codex.plugins.loaded_cache.load.duration_ms";
|
||||
pub(crate) const WAIT_DURATION: &str = "codex.plugins.loaded_cache.wait.duration_ms";
|
||||
|
||||
pub(crate) enum RequestOutcome {
|
||||
Hit,
|
||||
HitAfterWait,
|
||||
Load,
|
||||
}
|
||||
|
||||
impl RequestOutcome {
|
||||
pub(crate) fn record(self) {
|
||||
let Some(metrics) = akode_otel::global() else {
|
||||
return;
|
||||
};
|
||||
let outcome = match self {
|
||||
Self::Hit => "hit",
|
||||
Self::HitAfterWait => "hit_after_wait",
|
||||
Self::Load => "load",
|
||||
};
|
||||
let _ = metrics.counter(
|
||||
"codex.plugins.loaded_cache.request",
|
||||
/*inc*/ 1,
|
||||
&[("outcome", outcome)],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn record_duration(name: &'static str, duration: Duration) {
|
||||
if let Some(metrics) = akode_otel::global() {
|
||||
let _ = metrics.record_duration(name, duration, &[]);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn record_event(event: &'static str) {
|
||||
if let Some(metrics) = akode_otel::global() {
|
||||
let _ = metrics.counter(
|
||||
"codex.plugins.loaded_cache.event",
|
||||
/*inc*/ 1,
|
||||
&[("event", event)],
|
||||
);
|
||||
}
|
||||
}
|
||||
1630
akode-rs/core-plugins/src/loader.rs
Normal file
1630
akode-rs/core-plugins/src/loader.rs
Normal file
File diff suppressed because it is too large
Load Diff
1112
akode-rs/core-plugins/src/loader_tests.rs
Normal file
1112
akode-rs/core-plugins/src/loader_tests.rs
Normal file
File diff suppressed because it is too large
Load Diff
1807
akode-rs/core-plugins/src/manager.rs
Normal file
1807
akode-rs/core-plugins/src/manager.rs
Normal file
File diff suppressed because it is too large
Load Diff
114
akode-rs/core-plugins/src/manager_errors.rs
Normal file
114
akode-rs/core-plugins/src/manager_errors.rs
Normal file
@@ -0,0 +1,114 @@
|
||||
//! Plugin mutation errors and their stable telemetry classifications.
|
||||
|
||||
use crate::marketplace::MarketplaceError;
|
||||
use crate::store::PluginStoreError;
|
||||
use crate::store::error_context_sub_error_type;
|
||||
use akode_plugin::PluginIdError;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum PluginInstallError {
|
||||
#[error("{0}")]
|
||||
Marketplace(#[from] MarketplaceError),
|
||||
|
||||
#[error("{0}")]
|
||||
Store(#[from] PluginStoreError),
|
||||
|
||||
#[error("{0}")]
|
||||
Config(#[from] anyhow::Error),
|
||||
|
||||
#[error("failed to join plugin install task: {0}")]
|
||||
Join(#[from] tokio::task::JoinError),
|
||||
}
|
||||
|
||||
impl PluginInstallError {
|
||||
pub(super) fn join(source: tokio::task::JoinError) -> Self {
|
||||
Self::Join(source)
|
||||
}
|
||||
|
||||
pub fn is_invalid_request(&self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Self::Marketplace(
|
||||
MarketplaceError::MarketplaceNotFound { .. }
|
||||
| MarketplaceError::InvalidMarketplaceFile { .. }
|
||||
| MarketplaceError::PluginNotFound { .. }
|
||||
| MarketplaceError::PluginNotAvailable { .. }
|
||||
| MarketplaceError::InvalidPlugin(_)
|
||||
) | Self::Store(PluginStoreError::Invalid(_))
|
||||
)
|
||||
}
|
||||
|
||||
pub fn sub_error_type(&self) -> Option<String> {
|
||||
match self {
|
||||
Self::Marketplace(err) => marketplace_error_sub_error_type(err),
|
||||
Self::Store(err) => err.sub_error_type(),
|
||||
Self::Config(_) => Some("failed_to_enable_plugin".to_string()),
|
||||
Self::Join(_) => Some("plugin_install_task_failed".to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn plugin_install_error_type(err: &PluginInstallError) -> &'static str {
|
||||
match err {
|
||||
PluginInstallError::Marketplace(err) => marketplace_error_type(err),
|
||||
PluginInstallError::Store(err) => plugin_store_error_type(err),
|
||||
PluginInstallError::Config(_) => "config",
|
||||
PluginInstallError::Join(_) => "join",
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn marketplace_error_type(err: &MarketplaceError) -> &'static str {
|
||||
match err {
|
||||
MarketplaceError::Io { .. } => "marketplace_io",
|
||||
MarketplaceError::MarketplaceNotFound { .. } => "marketplace_not_found",
|
||||
MarketplaceError::InvalidMarketplaceFile { .. } => "invalid_marketplace_file",
|
||||
MarketplaceError::PluginNotFound { .. } => "plugin_not_found",
|
||||
MarketplaceError::PluginNotAvailable { .. } => "plugin_not_available",
|
||||
MarketplaceError::PluginsDisabled => "plugins_disabled",
|
||||
MarketplaceError::InvalidPlugin(_) => "invalid_plugin",
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn marketplace_error_sub_error_type(err: &MarketplaceError) -> Option<String> {
|
||||
match err {
|
||||
MarketplaceError::Io { context, .. } => Some(error_context_sub_error_type(context)),
|
||||
MarketplaceError::MarketplaceNotFound { .. }
|
||||
| MarketplaceError::InvalidMarketplaceFile { .. }
|
||||
| MarketplaceError::PluginNotFound { .. }
|
||||
| MarketplaceError::PluginNotAvailable { .. }
|
||||
| MarketplaceError::PluginsDisabled
|
||||
| MarketplaceError::InvalidPlugin(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn plugin_store_error_type(err: &PluginStoreError) -> &'static str {
|
||||
match err {
|
||||
PluginStoreError::Io { .. } => "store_io",
|
||||
PluginStoreError::Invalid(_) => "store_invalid",
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum PluginUninstallError {
|
||||
#[error("{0}")]
|
||||
InvalidPluginId(#[from] PluginIdError),
|
||||
|
||||
#[error("{0}")]
|
||||
Store(#[from] PluginStoreError),
|
||||
|
||||
#[error("{0}")]
|
||||
Config(#[from] anyhow::Error),
|
||||
|
||||
#[error("failed to join plugin uninstall task: {0}")]
|
||||
Join(#[from] tokio::task::JoinError),
|
||||
}
|
||||
|
||||
impl PluginUninstallError {
|
||||
pub(super) fn join(source: tokio::task::JoinError) -> Self {
|
||||
Self::Join(source)
|
||||
}
|
||||
|
||||
pub fn is_invalid_request(&self) -> bool {
|
||||
matches!(self, Self::InvalidPluginId(_))
|
||||
}
|
||||
}
|
||||
5420
akode-rs/core-plugins/src/manager_tests.rs
Normal file
5420
akode-rs/core-plugins/src/manager_tests.rs
Normal file
File diff suppressed because it is too large
Load Diff
1026
akode-rs/core-plugins/src/manifest.rs
Normal file
1026
akode-rs/core-plugins/src/manifest.rs
Normal file
File diff suppressed because it is too large
Load Diff
181
akode-rs/core-plugins/src/manifest/manifest_cache.rs
Normal file
181
akode-rs/core-plugins/src/manifest/manifest_cache.rs
Normal file
@@ -0,0 +1,181 @@
|
||||
//! Reuse parsed manifest revisions within an explicitly owned plugin store.
|
||||
//! Store clones share the cache; independently created stores do not share entries or warnings.
|
||||
|
||||
use super::LoadedPluginManifest;
|
||||
use super::PluginManifestFormat;
|
||||
use super::UriPluginManifest;
|
||||
use super::parse_resolved_plugin_manifest;
|
||||
use akode_utils_path_uri::PathUri;
|
||||
use akode_utils_plugins::AGENT_PLUGIN_MANIFEST_RELATIVE_PATH;
|
||||
use akode_utils_plugins::find_plugin_manifest_path;
|
||||
use sha2::Digest;
|
||||
use sha2::Sha256;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::VecDeque;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
use std::sync::Mutex;
|
||||
|
||||
const CAPACITY: usize = 128;
|
||||
const MAX_CACHABLE_INPUT_LEN: usize = 64 * 1024;
|
||||
|
||||
pub(crate) struct ManifestCache {
|
||||
state: Option<Mutex<ManifestCacheState>>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct ManifestCacheState {
|
||||
entries: HashMap<(PathUri, PathUri), Entry>,
|
||||
recency: VecDeque<(PathUri, PathUri)>,
|
||||
}
|
||||
|
||||
struct Entry {
|
||||
contents_digest: [u8; 32],
|
||||
overlay: Option<(PathUri, [u8; 32])>,
|
||||
manifest: UriPluginManifest,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for ManifestCache {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
formatter
|
||||
.debug_struct("ManifestCache")
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for ManifestCache {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
state: Some(Mutex::default()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ManifestCache {
|
||||
pub(crate) fn disabled() -> Self {
|
||||
Self { state: None }
|
||||
}
|
||||
|
||||
pub(crate) fn load(&self, plugin_root: &Path) -> Option<LoadedPluginManifest> {
|
||||
let manifest_path = find_plugin_manifest_path(plugin_root)?;
|
||||
let contents = fs::read_to_string(&manifest_path).ok()?;
|
||||
let is_agent_plugin =
|
||||
manifest_path == plugin_root.join(AGENT_PLUGIN_MANIFEST_RELATIVE_PATH);
|
||||
let overlay = if is_agent_plugin {
|
||||
let overlay_path = plugin_root.join(".codex-plugin/plugin.json");
|
||||
fs::read_to_string(&overlay_path)
|
||||
.ok()
|
||||
.map(|contents| (overlay_path, contents))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
match parse_resolved_plugin_manifest(
|
||||
self,
|
||||
plugin_root,
|
||||
&manifest_path,
|
||||
&contents,
|
||||
overlay
|
||||
.as_ref()
|
||||
.map(|(path, contents)| (path.as_path(), contents.as_str())),
|
||||
) {
|
||||
Ok(manifest) => Some(LoadedPluginManifest {
|
||||
manifest,
|
||||
format: if is_agent_plugin {
|
||||
PluginManifestFormat::AgentPlugin
|
||||
} else {
|
||||
PluginManifestFormat::Legacy
|
||||
},
|
||||
}),
|
||||
Err(err) => {
|
||||
tracing::warn!(
|
||||
path = %manifest_path.display(),
|
||||
"failed to parse plugin manifest: {err}"
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn parse(
|
||||
&self,
|
||||
root: &PathUri,
|
||||
path: &PathUri,
|
||||
contents: &str,
|
||||
overlay: Option<(&PathUri, &str)>,
|
||||
parse: impl FnOnce() -> Result<UriPluginManifest, serde_json::Error>,
|
||||
) -> Result<UriPluginManifest, serde_json::Error> {
|
||||
let Some(state) = &self.state else {
|
||||
return parse();
|
||||
};
|
||||
if contents
|
||||
.len()
|
||||
.saturating_add(overlay.map_or(0, |(_, value)| value.len()))
|
||||
> MAX_CACHABLE_INPUT_LEN
|
||||
{
|
||||
state
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.remove(&(root.clone(), path.clone()));
|
||||
// Unbounded inputs must not serialize unrelated parses behind the cache lock.
|
||||
return parse();
|
||||
}
|
||||
// Parsing is synchronous and does no filesystem I/O. Serializing cache misses also
|
||||
// prevents concurrent capability loaders from validating the same revision twice.
|
||||
state
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.parse(root, path, contents, overlay, parse)
|
||||
}
|
||||
}
|
||||
|
||||
impl ManifestCacheState {
|
||||
fn remove(&mut self, key: &(PathUri, PathUri)) -> Option<Entry> {
|
||||
let entry = self.entries.remove(key)?;
|
||||
self.recency.retain(|existing| existing != key);
|
||||
Some(entry)
|
||||
}
|
||||
|
||||
fn parse(
|
||||
&mut self,
|
||||
root: &PathUri,
|
||||
path: &PathUri,
|
||||
contents: &str,
|
||||
overlay: Option<(&PathUri, &str)>,
|
||||
parse: impl FnOnce() -> Result<UriPluginManifest, serde_json::Error>,
|
||||
) -> Result<UriPluginManifest, serde_json::Error> {
|
||||
let key = (root.clone(), path.clone());
|
||||
let previous = self.remove(&key);
|
||||
let contents_digest = Sha256::digest(contents.as_bytes()).into();
|
||||
let overlay = overlay
|
||||
.map(|(path, contents)| (path.clone(), Sha256::digest(contents.as_bytes()).into()));
|
||||
if let Some(entry) = previous
|
||||
&& entry.contents_digest == contents_digest
|
||||
&& entry.overlay == overlay
|
||||
{
|
||||
let manifest = entry.manifest.clone();
|
||||
self.recency.push_front(key.clone());
|
||||
self.entries.insert(key, entry);
|
||||
return Ok(manifest);
|
||||
}
|
||||
let manifest = parse()?;
|
||||
if self.entries.len() == CAPACITY
|
||||
&& let Some(oldest) = self.recency.pop_back()
|
||||
{
|
||||
self.entries.remove(&oldest);
|
||||
}
|
||||
self.recency.push_front(key.clone());
|
||||
self.entries.insert(
|
||||
key,
|
||||
Entry {
|
||||
contents_digest,
|
||||
overlay,
|
||||
manifest: manifest.clone(),
|
||||
},
|
||||
);
|
||||
Ok(manifest)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "manifest_cache_tests.rs"]
|
||||
mod tests;
|
||||
303
akode-rs/core-plugins/src/manifest/manifest_cache_tests.rs
Normal file
303
akode-rs/core-plugins/src/manifest/manifest_cache_tests.rs
Normal file
@@ -0,0 +1,303 @@
|
||||
//! Verify parse reuse, revision invalidation, and diagnostic preservation.
|
||||
|
||||
use super::super::parse_legacy_plugin_manifest_uri;
|
||||
use super::super::parse_resolved_plugin_manifest;
|
||||
use super::ManifestCache;
|
||||
use akode_utils_path_uri::PathUri;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::cell::Cell;
|
||||
use std::sync::Mutex;
|
||||
use tracing_test::internal::MockWriter;
|
||||
|
||||
#[test]
|
||||
fn repeated_revision_runs_parser_once_and_changes_run_it_again() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let root = PathUri::from_host_native_path(directory.path()).unwrap();
|
||||
let path = root.join(".codex-plugin/plugin.json").unwrap();
|
||||
let first = r#"{"name":"demo","description":"first"}"#;
|
||||
let changed = r#"{"name":"demo","description":"changed"}"#;
|
||||
let parses = Cell::new(0);
|
||||
let cache = ManifestCache::default();
|
||||
let mut results = Vec::new();
|
||||
for contents in std::iter::repeat_n(first, 220).chain([changed, first]) {
|
||||
results.push(
|
||||
cache
|
||||
.parse(&root, &path, contents, /*overlay*/ None, || {
|
||||
parses.set(parses.get() + 1);
|
||||
parse_legacy_plugin_manifest_uri(&root, &path, contents)
|
||||
})
|
||||
.unwrap(),
|
||||
);
|
||||
}
|
||||
let original = results[0].clone();
|
||||
let mut revised = original.clone();
|
||||
revised.description = Some("changed".to_string());
|
||||
assert_eq!(
|
||||
results,
|
||||
std::iter::repeat_n(original.clone(), 220)
|
||||
.chain([revised, original])
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
assert_eq!(parses.get(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_fields_warn_once_until_the_manifest_changes() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let path = directory.path().join(".codex-plugin/plugin.json");
|
||||
let buffer: &'static Mutex<Vec<u8>> = Box::leak(Box::new(Mutex::new(Vec::new())));
|
||||
let subscriber = tracing_subscriber::fmt()
|
||||
.without_time()
|
||||
.with_ansi(/*ansi*/ false)
|
||||
.with_writer(MockWriter::new(buffer))
|
||||
.finish();
|
||||
let _guard = tracing::subscriber::set_default(subscriber);
|
||||
let original =
|
||||
r#"{"name":"demo","interface":{"defaultPrompt":" ","composerIcon":"../outside.svg"}}"#;
|
||||
let changed = r#"{"name":"demo","description":"changed","interface":{"defaultPrompt":" ","composerIcon":"../outside.svg"}}"#;
|
||||
let cache = ManifestCache::default();
|
||||
let parse = |contents| {
|
||||
parse_resolved_plugin_manifest(
|
||||
&cache,
|
||||
directory.path(),
|
||||
&path,
|
||||
contents,
|
||||
/*overlay*/ None,
|
||||
)
|
||||
.unwrap()
|
||||
};
|
||||
let first = parse(original);
|
||||
for _ in 0..220 {
|
||||
assert_eq!(parse(original), first);
|
||||
}
|
||||
let mut expected = first.clone();
|
||||
expected.description = Some("changed".to_string());
|
||||
assert_eq!(parse(changed), expected);
|
||||
assert_eq!(parse(original), first);
|
||||
let logs = String::from_utf8(buffer.lock().unwrap().clone()).unwrap();
|
||||
assert_eq!(logs.matches("ignoring interface.defaultPrompt").count(), 3);
|
||||
assert_eq!(logs.matches("ignoring interface.composerIcon").count(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlay_revision_and_resource_root_are_part_of_cached_parse() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let root = PathUri::from_host_native_path(directory.path()).unwrap();
|
||||
let other_root = root.join("other").unwrap();
|
||||
let path = root.join("plugin.json").unwrap();
|
||||
let overlay_path = root.join(".codex-plugin/plugin.json").unwrap();
|
||||
let contents = serde_json::json!({
|
||||
"$schema": akode_utils_plugins::AGENT_PLUGIN_SCHEMA_URI,
|
||||
"name": "demo"
|
||||
})
|
||||
.to_string();
|
||||
let first = r#"{"interface":{"defaultPrompt":"first"}}"#;
|
||||
let changed = r#"{"interface":{"defaultPrompt":"changed"}}"#;
|
||||
let parses = Cell::new(0);
|
||||
let cache = ManifestCache::default();
|
||||
for (plugin_root, overlay) in [
|
||||
(&root, Some((&overlay_path, first))),
|
||||
(&root, Some((&overlay_path, first))),
|
||||
(&root, Some((&overlay_path, changed))),
|
||||
(&root, None),
|
||||
(&other_root, None),
|
||||
] {
|
||||
let manifest = cache
|
||||
.parse(plugin_root, &path, &contents, overlay, || {
|
||||
parses.set(parses.get() + 1);
|
||||
super::super::agent_plugin_manifest::parse_agent_plugin_manifest_uri(
|
||||
plugin_root,
|
||||
&path,
|
||||
&contents,
|
||||
overlay,
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
let expected = super::super::agent_plugin_manifest::parse_agent_plugin_manifest_uri(
|
||||
plugin_root,
|
||||
&path,
|
||||
&contents,
|
||||
overlay,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(manifest, expected);
|
||||
}
|
||||
assert_eq!(parses.get(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_revision_is_retried_and_repair_is_visible() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let root = PathUri::from_host_native_path(directory.path()).unwrap();
|
||||
let path = root.join(".codex-plugin/plugin.json").unwrap();
|
||||
let cache = ManifestCache::default();
|
||||
for contents in ["{", "{"] {
|
||||
assert!(
|
||||
cache
|
||||
.parse(&root, &path, contents, /*overlay*/ None, || {
|
||||
parse_legacy_plugin_manifest_uri(&root, &path, contents)
|
||||
})
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
let repaired = r#"{"name":"repaired"}"#;
|
||||
assert_eq!(
|
||||
cache
|
||||
.parse(&root, &path, repaired, /*overlay*/ None, || {
|
||||
parse_legacy_plugin_manifest_uri(&root, &path, repaired)
|
||||
})
|
||||
.unwrap(),
|
||||
parse_legacy_plugin_manifest_uri(&root, &path, repaired).unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn equivalent_windows_paths_share_a_cached_revision() {
|
||||
let cache = ManifestCache::default();
|
||||
let parses = Cell::new(0);
|
||||
let contents = r#"{"name":"demo"}"#;
|
||||
let mut manifests = Vec::new();
|
||||
for value in ["file:///C:/plugins/Demo", "file:///C:/plugins/demo"] {
|
||||
let root = PathUri::parse(value).unwrap();
|
||||
let path = root.join(".codex-plugin/plugin.json").unwrap();
|
||||
manifests.push(
|
||||
cache
|
||||
.parse(&root, &path, contents, /*overlay*/ None, || {
|
||||
parses.set(parses.get() + 1);
|
||||
parse_legacy_plugin_manifest_uri(&root, &path, contents)
|
||||
})
|
||||
.unwrap(),
|
||||
);
|
||||
}
|
||||
assert_eq!(manifests[0], manifests[1]);
|
||||
assert_eq!(parses.get(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oversized_revision_invalidates_previous_result_without_being_cached() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let root = PathUri::from_host_native_path(directory.path()).unwrap();
|
||||
let path = root.join(".codex-plugin/plugin.json").unwrap();
|
||||
let small = r#"{"name":"demo"}"#;
|
||||
let large = format!("{}{small}", " ".repeat(super::MAX_CACHABLE_INPUT_LEN));
|
||||
let parses = Cell::new(0);
|
||||
let cache = ManifestCache::default();
|
||||
for contents in [small, small, &large, &large, small] {
|
||||
cache
|
||||
.parse(&root, &path, contents, /*overlay*/ None, || {
|
||||
parses.set(parses.get() + 1);
|
||||
parse_legacy_plugin_manifest_uri(&root, &path, contents)
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
assert_eq!(parses.get(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oversized_parse_does_not_block_unrelated_manifest() {
|
||||
use std::sync::mpsc;
|
||||
use std::time::Duration;
|
||||
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let root = PathUri::from_host_native_path(directory.path()).unwrap();
|
||||
let large_path = root.join("large.json").unwrap();
|
||||
let small_path = root.join("small.json").unwrap();
|
||||
let large = format!("{}{{}}", " ".repeat(super::MAX_CACHABLE_INPUT_LEN));
|
||||
let (started_tx, started_rx) = mpsc::channel();
|
||||
let (release_tx, release_rx) = mpsc::channel();
|
||||
let (completed_tx, completed_rx) = mpsc::channel();
|
||||
let root = &root;
|
||||
let large_path = &large_path;
|
||||
let small_path = &small_path;
|
||||
let large = &large;
|
||||
let cache = &ManifestCache::default();
|
||||
std::thread::scope(|scope| {
|
||||
scope.spawn(move || {
|
||||
cache
|
||||
.parse(root, large_path, large, /*overlay*/ None, || {
|
||||
started_tx.send(()).unwrap();
|
||||
release_rx.recv().unwrap();
|
||||
parse_legacy_plugin_manifest_uri(root, large_path, large)
|
||||
})
|
||||
.unwrap();
|
||||
});
|
||||
started_rx.recv_timeout(Duration::from_secs(10)).unwrap();
|
||||
scope.spawn(move || {
|
||||
cache
|
||||
.parse(root, small_path, "{}", /*overlay*/ None, || {
|
||||
parse_legacy_plugin_manifest_uri(root, small_path, "{}")
|
||||
})
|
||||
.unwrap();
|
||||
completed_tx.send(()).unwrap();
|
||||
});
|
||||
let completed = completed_rx.recv_timeout(Duration::from_secs(10));
|
||||
release_tx.send(()).unwrap();
|
||||
assert_eq!(completed, Ok(()));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn store_clones_reuse_validation_but_independent_stores_warn_again() {
|
||||
use crate::store::PluginStore;
|
||||
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let root = directory.path().join("plugin");
|
||||
std::fs::create_dir_all(root.join(".codex-plugin")).unwrap();
|
||||
std::fs::write(
|
||||
root.join(".codex-plugin/plugin.json"),
|
||||
r#"{"name":"demo","interface":{"defaultPrompt":" "}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let buffer: &'static Mutex<Vec<u8>> = Box::leak(Box::new(Mutex::new(Vec::new())));
|
||||
let subscriber = tracing_subscriber::fmt()
|
||||
.without_time()
|
||||
.with_ansi(/*ansi*/ false)
|
||||
.with_writer(MockWriter::new(buffer))
|
||||
.finish();
|
||||
let _guard = tracing::subscriber::set_default(subscriber);
|
||||
let store = PluginStore::new(directory.path().to_path_buf());
|
||||
let cloned_store = store.clone();
|
||||
let first = store.manifest_cache.load(&root).unwrap().manifest;
|
||||
for _ in 0..220 {
|
||||
assert_eq!(
|
||||
cloned_store.manifest_cache.load(&root).unwrap().manifest,
|
||||
first
|
||||
);
|
||||
}
|
||||
let independent_store = PluginStore::new(directory.path().to_path_buf());
|
||||
assert_eq!(
|
||||
independent_store
|
||||
.manifest_cache
|
||||
.load(&root)
|
||||
.unwrap()
|
||||
.manifest,
|
||||
first
|
||||
);
|
||||
let logs = String::from_utf8(buffer.lock().unwrap().clone()).unwrap();
|
||||
assert_eq!(
|
||||
logs.matches("ignoring interface.defaultPrompt: prompt must not be empty")
|
||||
.count(),
|
||||
2
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabled_cache_parses_each_load() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let root = PathUri::from_host_native_path(directory.path()).unwrap();
|
||||
let path = root.join(".codex-plugin/plugin.json").unwrap();
|
||||
let contents = r#"{"name":"demo"}"#;
|
||||
let expected = parse_legacy_plugin_manifest_uri(&root, &path, contents).unwrap();
|
||||
let cache = ManifestCache::disabled();
|
||||
let parses = Cell::new(0);
|
||||
for _ in 0..3 {
|
||||
let result = cache
|
||||
.parse(&root, &path, contents, /*overlay*/ None, || {
|
||||
parses.set(parses.get() + 1);
|
||||
parse_legacy_plugin_manifest_uri(&root, &path, contents)
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(result, expected);
|
||||
}
|
||||
assert_eq!(parses.get(), 3);
|
||||
}
|
||||
1174
akode-rs/core-plugins/src/marketplace.rs
Normal file
1174
akode-rs/core-plugins/src/marketplace.rs
Normal file
File diff suppressed because it is too large
Load Diff
482
akode-rs/core-plugins/src/marketplace_add.rs
Normal file
482
akode-rs/core-plugins/src/marketplace_add.rs
Normal file
@@ -0,0 +1,482 @@
|
||||
use crate::installed_marketplaces::marketplace_install_root;
|
||||
use crate::marketplace_policy::validate_marketplace_name_for_add;
|
||||
use crate::marketplace_policy::validate_marketplace_source_for_add;
|
||||
use crate::marketplace_staging::MarketplaceStagingDir;
|
||||
use crate::marketplace_staging::cleanup_marketplace_staging;
|
||||
use akode_config::ConfigRequirements;
|
||||
use akode_utils_absolute_path::AbsolutePathBuf;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
mod install;
|
||||
mod metadata;
|
||||
mod source;
|
||||
|
||||
use install::clone_git_source;
|
||||
use install::ensure_marketplace_destination_is_inside_install_root;
|
||||
use install::replace_marketplace_root;
|
||||
use install::safe_marketplace_dir_name;
|
||||
use metadata::MarketplaceInstallMetadata;
|
||||
use metadata::find_marketplace_root_by_name;
|
||||
use metadata::installed_marketplace_root_for_source;
|
||||
use metadata::record_added_marketplace_entry;
|
||||
pub(crate) use source::MarketplaceSource;
|
||||
pub(crate) use source::parse_marketplace_source;
|
||||
use source::stage_marketplace_source;
|
||||
use source::validate_marketplace_source_root;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct MarketplaceAddRequest {
|
||||
pub source: String,
|
||||
pub ref_name: Option<String>,
|
||||
pub sparse_paths: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct MarketplaceAddOutcome {
|
||||
pub marketplace_name: String,
|
||||
pub source_display: String,
|
||||
pub installed_root: AbsolutePathBuf,
|
||||
pub already_added: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum MarketplaceAddError {
|
||||
#[error("{0}")]
|
||||
InvalidRequest(String),
|
||||
#[error("{0}")]
|
||||
Internal(String),
|
||||
}
|
||||
|
||||
pub async fn add_marketplace(
|
||||
codex_home: PathBuf,
|
||||
requirements: ConfigRequirements,
|
||||
request: MarketplaceAddRequest,
|
||||
) -> Result<MarketplaceAddOutcome, MarketplaceAddError> {
|
||||
tokio::task::spawn_blocking(move || {
|
||||
add_marketplace_sync(codex_home.as_path(), &requirements, request)
|
||||
})
|
||||
.await
|
||||
.map_err(|err| MarketplaceAddError::Internal(format!("failed to add marketplace: {err}")))?
|
||||
}
|
||||
|
||||
pub fn is_local_marketplace_source(
|
||||
source: &str,
|
||||
explicit_ref: Option<String>,
|
||||
) -> Result<bool, MarketplaceAddError> {
|
||||
Ok(matches!(
|
||||
parse_marketplace_source(source, explicit_ref)?,
|
||||
source::MarketplaceSource::Local { .. }
|
||||
))
|
||||
}
|
||||
|
||||
fn add_marketplace_sync(
|
||||
codex_home: &Path,
|
||||
requirements: &ConfigRequirements,
|
||||
request: MarketplaceAddRequest,
|
||||
) -> Result<MarketplaceAddOutcome, MarketplaceAddError> {
|
||||
add_marketplace_sync_with_cloner(codex_home, requirements, request, clone_git_source)
|
||||
}
|
||||
|
||||
fn add_marketplace_sync_with_cloner<F>(
|
||||
codex_home: &Path,
|
||||
requirements: &ConfigRequirements,
|
||||
request: MarketplaceAddRequest,
|
||||
clone_source: F,
|
||||
) -> Result<MarketplaceAddOutcome, MarketplaceAddError>
|
||||
where
|
||||
F: Fn(&str, Option<&str>, &[String], &Path) -> Result<(), MarketplaceAddError>,
|
||||
{
|
||||
let MarketplaceAddRequest {
|
||||
source,
|
||||
ref_name,
|
||||
sparse_paths,
|
||||
} = request;
|
||||
let source = parse_marketplace_source(&source, ref_name)?;
|
||||
let managed_marketplace_name =
|
||||
validate_marketplace_source_for_add(codex_home, requirements, &source)
|
||||
.map_err(MarketplaceAddError::InvalidRequest)?;
|
||||
if !sparse_paths.is_empty() && !matches!(source, MarketplaceSource::Git { .. }) {
|
||||
return Err(MarketplaceAddError::InvalidRequest(
|
||||
"--sparse is only supported for git marketplace sources".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
let install_root = marketplace_install_root(codex_home);
|
||||
fs::create_dir_all(&install_root).map_err(|err| {
|
||||
MarketplaceAddError::Internal(format!(
|
||||
"failed to create marketplace install directory {}: {err}",
|
||||
install_root.display()
|
||||
))
|
||||
})?;
|
||||
|
||||
// Remove abandoned staging directories from earlier operations.
|
||||
// This is generally fast and rare operation so it doesn't deserve a separate cleanup task
|
||||
cleanup_marketplace_staging(&install_root);
|
||||
|
||||
let install_metadata = MarketplaceInstallMetadata::from_source(&source, &sparse_paths);
|
||||
if let Some(existing_root) =
|
||||
installed_marketplace_root_for_source(codex_home, &install_root, &install_metadata)?
|
||||
{
|
||||
let marketplace_name = validate_marketplace_source_root(&existing_root)?;
|
||||
validate_marketplace_name_for_add(managed_marketplace_name, &marketplace_name)
|
||||
.map_err(MarketplaceAddError::InvalidRequest)?;
|
||||
record_added_marketplace_entry(codex_home, &marketplace_name, &install_metadata)?;
|
||||
return Ok(MarketplaceAddOutcome {
|
||||
marketplace_name,
|
||||
source_display: source.display(),
|
||||
installed_root: AbsolutePathBuf::try_from(existing_root).map_err(|err| {
|
||||
MarketplaceAddError::Internal(format!(
|
||||
"failed to resolve installed marketplace root: {err}"
|
||||
))
|
||||
})?,
|
||||
already_added: true,
|
||||
});
|
||||
}
|
||||
|
||||
if let MarketplaceSource::Local { path } = &source {
|
||||
let marketplace_name = validate_marketplace_source_root(path)?;
|
||||
validate_marketplace_name_for_add(managed_marketplace_name, &marketplace_name)
|
||||
.map_err(MarketplaceAddError::InvalidRequest)?;
|
||||
if find_marketplace_root_by_name(codex_home, &install_root, &marketplace_name)?.is_some() {
|
||||
return Err(MarketplaceAddError::InvalidRequest(format!(
|
||||
"marketplace '{marketplace_name}' is already added from a different source; remove it before adding this source"
|
||||
)));
|
||||
}
|
||||
record_added_marketplace_entry(codex_home, &marketplace_name, &install_metadata)?;
|
||||
return Ok(MarketplaceAddOutcome {
|
||||
marketplace_name,
|
||||
source_display: source.display(),
|
||||
installed_root: AbsolutePathBuf::try_from(path.clone()).map_err(|err| {
|
||||
MarketplaceAddError::Internal(format!(
|
||||
"failed to resolve installed marketplace root: {err}"
|
||||
))
|
||||
})?,
|
||||
already_added: false,
|
||||
});
|
||||
}
|
||||
|
||||
let staged_dir = MarketplaceStagingDir::new(&install_root).map_err(|err| {
|
||||
MarketplaceAddError::Internal(format!(
|
||||
"failed to create temporary marketplace directory in {}: {err}",
|
||||
install_root.display()
|
||||
))
|
||||
})?;
|
||||
// Retain the cleanup guard through validation, installation, and config-write rollback.
|
||||
let staged_root = staged_dir.path();
|
||||
|
||||
stage_marketplace_source(&source, &sparse_paths, staged_root, clone_source)?;
|
||||
|
||||
let marketplace_name = validate_marketplace_source_root(staged_root)?;
|
||||
validate_marketplace_name_for_add(managed_marketplace_name, &marketplace_name)
|
||||
.map_err(MarketplaceAddError::InvalidRequest)?;
|
||||
|
||||
let destination = install_root.join(safe_marketplace_dir_name(&marketplace_name)?);
|
||||
ensure_marketplace_destination_is_inside_install_root(&install_root, &destination)?;
|
||||
if destination.exists() {
|
||||
return Err(MarketplaceAddError::InvalidRequest(format!(
|
||||
"marketplace '{marketplace_name}' is already added from a different source; remove it before adding this source"
|
||||
)));
|
||||
}
|
||||
replace_marketplace_root(staged_root, &destination).map_err(|err| {
|
||||
MarketplaceAddError::Internal(format!(
|
||||
"failed to install marketplace at {}: {err}",
|
||||
destination.display()
|
||||
))
|
||||
})?;
|
||||
if let Err(err) =
|
||||
record_added_marketplace_entry(codex_home, &marketplace_name, &install_metadata)
|
||||
{
|
||||
if let Err(rollback_err) = fs::rename(&destination, staged_root) {
|
||||
return Err(MarketplaceAddError::Internal(format!(
|
||||
"{err}; additionally failed to roll back installed marketplace at {}: {rollback_err}",
|
||||
destination.display()
|
||||
)));
|
||||
}
|
||||
return Err(err);
|
||||
}
|
||||
|
||||
Ok(MarketplaceAddOutcome {
|
||||
marketplace_name,
|
||||
source_display: source.display(),
|
||||
installed_root: AbsolutePathBuf::try_from(destination).map_err(|err| {
|
||||
MarketplaceAddError::Internal(format!(
|
||||
"failed to resolve installed marketplace root: {err}"
|
||||
))
|
||||
})?,
|
||||
already_added: false,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use anyhow::Result;
|
||||
use akode_config::RequirementSource;
|
||||
use akode_config::RequirementsLayerEntry;
|
||||
use akode_config::compose_requirements;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::cell::Cell;
|
||||
use tempfile::TempDir;
|
||||
|
||||
fn requirements(requirements_toml: &str) -> ConfigRequirements {
|
||||
let with_sources = compose_requirements([RequirementsLayerEntry::from_toml(
|
||||
RequirementSource::Unknown,
|
||||
requirements_toml,
|
||||
)])
|
||||
.expect("compose requirements")
|
||||
.expect("requirements should be present");
|
||||
ConfigRequirements::try_from(with_sources).expect("normalize requirements")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_marketplace_sync_installs_marketplace_and_updates_config() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let source_root = TempDir::new()?;
|
||||
write_marketplace_source(source_root.path(), "remote copy")?;
|
||||
|
||||
let result = add_marketplace_sync_with_cloner(
|
||||
codex_home.path(),
|
||||
&ConfigRequirements::default(),
|
||||
MarketplaceAddRequest {
|
||||
source: "https://github.com/owner/repo.git".to_string(),
|
||||
ref_name: None,
|
||||
sparse_paths: Vec::new(),
|
||||
},
|
||||
|_url, _ref_name, _sparse_paths, destination| {
|
||||
copy_dir_all(source_root.path(), destination)
|
||||
.map_err(|err| MarketplaceAddError::Internal(err.to_string()))
|
||||
},
|
||||
)?;
|
||||
|
||||
assert_eq!(result.marketplace_name, "debug");
|
||||
assert_eq!(result.source_display, "https://github.com/owner/repo.git");
|
||||
assert!(!result.already_added);
|
||||
assert!(
|
||||
result
|
||||
.installed_root
|
||||
.as_path()
|
||||
.join(".agents/plugins/marketplace.json")
|
||||
.is_file()
|
||||
);
|
||||
|
||||
let config = fs::read_to_string(codex_home.path().join(akode_config::CONFIG_TOML_FILE))?;
|
||||
assert!(config.contains("[marketplaces.debug]"));
|
||||
assert!(config.contains("source_type = \"git\""));
|
||||
assert!(config.contains("source = \"https://github.com/owner/repo.git\""));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn denied_git_marketplace_does_not_clone_or_create_install_root() {
|
||||
let requirements = requirements(
|
||||
r#"
|
||||
[marketplaces]
|
||||
restrict_to_allowed_sources = true
|
||||
|
||||
[marketplaces.allowed_sources.company]
|
||||
source = "git"
|
||||
url = "https://github.com/example/allowed.git"
|
||||
|
||||
[marketplaces.allowed_sources.internal]
|
||||
source = "host_pattern"
|
||||
host_pattern = '^allowed\.test$'
|
||||
"#,
|
||||
);
|
||||
for source in [
|
||||
"https://github.com/example/blocked.git",
|
||||
"https://127.0.0.1:18767/r.git",
|
||||
"https://allowed.test@127.0.0.1:18767/r.git",
|
||||
r"http://allowed.test\@127.0.0.1:18767/r.git",
|
||||
r"https://allowed.test\@127.0.0.1:18767/r.git",
|
||||
r"http://allowed.test\anything@127.0.0.1:18767/r.git",
|
||||
r"https://allowed.test\name:password@127.0.0.1:18767/r.git",
|
||||
r"https:///allowed.test\anything@127.0.0.1:18767/r.git",
|
||||
] {
|
||||
let codex_home = TempDir::new().expect("create Codex home");
|
||||
let cloner_called = Cell::new(false);
|
||||
|
||||
let err = add_marketplace_sync_with_cloner(
|
||||
codex_home.path(),
|
||||
&requirements,
|
||||
MarketplaceAddRequest {
|
||||
source: source.to_string(),
|
||||
ref_name: None,
|
||||
sparse_paths: Vec::new(),
|
||||
},
|
||||
|_url, _ref_name, _sparse_paths, _destination| {
|
||||
cloner_called.set(true);
|
||||
Ok(())
|
||||
},
|
||||
)
|
||||
.expect_err("blocked marketplace should fail");
|
||||
|
||||
assert!(err.to_string().contains("is not allowed by requirements"));
|
||||
assert!(!cloner_called.get(), "cloned denied source: {source}");
|
||||
assert!(!marketplace_install_root(codex_home.path()).exists());
|
||||
assert!(
|
||||
!codex_home
|
||||
.path()
|
||||
.join(akode_config::CONFIG_TOML_FILE)
|
||||
.exists()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_marketplace_sync_installs_local_directory_source_and_updates_config() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let source_root = TempDir::new()?;
|
||||
write_marketplace_source(source_root.path(), "local copy")?;
|
||||
|
||||
let result = add_marketplace_sync_with_cloner(
|
||||
codex_home.path(),
|
||||
&ConfigRequirements::default(),
|
||||
MarketplaceAddRequest {
|
||||
source: source_root.path().display().to_string(),
|
||||
ref_name: None,
|
||||
sparse_paths: Vec::new(),
|
||||
},
|
||||
|_url, _ref_name, _sparse_paths, _destination| {
|
||||
panic!("git cloner should not be called for local marketplace sources")
|
||||
},
|
||||
)?;
|
||||
|
||||
let expected_source = source_root.path().canonicalize()?.display().to_string();
|
||||
assert_eq!(result.marketplace_name, "debug");
|
||||
assert_eq!(result.source_display, expected_source);
|
||||
let expected_installed_root =
|
||||
AbsolutePathBuf::from_absolute_path(source_root.path().canonicalize()?)?;
|
||||
assert_eq!(result.installed_root, expected_installed_root);
|
||||
assert!(!result.already_added);
|
||||
assert!(
|
||||
!marketplace_install_root(codex_home.path())
|
||||
.join("debug")
|
||||
.exists()
|
||||
);
|
||||
|
||||
let config = fs::read_to_string(codex_home.path().join(akode_config::CONFIG_TOML_FILE))?;
|
||||
let config: toml::Value = toml::from_str(&config)?;
|
||||
assert_eq!(
|
||||
config["marketplaces"]["debug"]["source_type"].as_str(),
|
||||
Some("local")
|
||||
);
|
||||
assert_eq!(
|
||||
config["marketplaces"]["debug"]["source"].as_str(),
|
||||
Some(expected_source.as_str())
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_marketplace_sync_rejects_sparse_checkout_for_local_directory_source() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let source_root = TempDir::new()?;
|
||||
write_marketplace_source(source_root.path(), "local copy")?;
|
||||
|
||||
let err = add_marketplace_sync_with_cloner(
|
||||
codex_home.path(),
|
||||
&ConfigRequirements::default(),
|
||||
MarketplaceAddRequest {
|
||||
source: source_root.path().display().to_string(),
|
||||
ref_name: None,
|
||||
sparse_paths: vec![".agents".to_string()],
|
||||
},
|
||||
|_url, _ref_name, _sparse_paths, _destination| {
|
||||
panic!("git cloner should not be called for local marketplace sources")
|
||||
},
|
||||
)
|
||||
.unwrap_err();
|
||||
|
||||
assert_eq!(
|
||||
err.to_string(),
|
||||
"--sparse is only supported for git marketplace sources"
|
||||
);
|
||||
assert!(
|
||||
!codex_home
|
||||
.path()
|
||||
.join(akode_config::CONFIG_TOML_FILE)
|
||||
.exists()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_marketplace_sync_treats_existing_local_directory_source_as_already_added() -> Result<()>
|
||||
{
|
||||
let codex_home = TempDir::new()?;
|
||||
let source_root = TempDir::new()?;
|
||||
write_marketplace_source(source_root.path(), "local copy")?;
|
||||
|
||||
let request = MarketplaceAddRequest {
|
||||
source: source_root.path().display().to_string(),
|
||||
ref_name: None,
|
||||
sparse_paths: Vec::new(),
|
||||
};
|
||||
let requirements = ConfigRequirements::default();
|
||||
let first_result = add_marketplace_sync_with_cloner(
|
||||
codex_home.path(),
|
||||
&requirements,
|
||||
request.clone(),
|
||||
|_url, _ref_name, _sparse_paths, _destination| {
|
||||
panic!("git cloner should not be called for local marketplace sources")
|
||||
},
|
||||
)?;
|
||||
let second_result = add_marketplace_sync_with_cloner(
|
||||
codex_home.path(),
|
||||
&requirements,
|
||||
request,
|
||||
|_url, _ref_name, _sparse_paths, _destination| {
|
||||
panic!("git cloner should not be called for local marketplace sources")
|
||||
},
|
||||
)?;
|
||||
|
||||
assert!(!first_result.already_added);
|
||||
assert!(second_result.already_added);
|
||||
assert_eq!(second_result.installed_root, first_result.installed_root);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_marketplace_source(source: &Path, marker: &str) -> std::io::Result<()> {
|
||||
fs::create_dir_all(source.join(".agents/plugins"))?;
|
||||
fs::create_dir_all(source.join("plugins/sample/.codex-plugin"))?;
|
||||
fs::write(
|
||||
source.join(".agents/plugins/marketplace.json"),
|
||||
r#"{
|
||||
"name": "debug",
|
||||
"plugins": [
|
||||
{
|
||||
"name": "sample",
|
||||
"source": {
|
||||
"source": "local",
|
||||
"path": "./plugins/sample"
|
||||
}
|
||||
}
|
||||
]
|
||||
}"#,
|
||||
)?;
|
||||
fs::write(
|
||||
source.join("plugins/sample/.codex-plugin/plugin.json"),
|
||||
r#"{"name":"sample"}"#,
|
||||
)?;
|
||||
fs::write(source.join("plugins/sample/marker.txt"), marker)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn copy_dir_all(source: &Path, destination: &Path) -> std::io::Result<()> {
|
||||
fs::create_dir_all(destination)?;
|
||||
for entry in fs::read_dir(source)? {
|
||||
let entry = entry?;
|
||||
let source_path = entry.path();
|
||||
let destination_path = destination.join(entry.file_name());
|
||||
if source_path.is_dir() {
|
||||
copy_dir_all(&source_path, &destination_path)?;
|
||||
} else {
|
||||
fs::copy(&source_path, &destination_path)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
133
akode-rs/core-plugins/src/marketplace_add/install.rs
Normal file
133
akode-rs/core-plugins/src/marketplace_add/install.rs
Normal file
@@ -0,0 +1,133 @@
|
||||
use super::MarketplaceAddError;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
pub(super) fn clone_git_source(
|
||||
url: &str,
|
||||
ref_name: Option<&str>,
|
||||
sparse_paths: &[String],
|
||||
destination: &Path,
|
||||
) -> Result<(), MarketplaceAddError> {
|
||||
let destination_string = destination.to_string_lossy().to_string();
|
||||
if sparse_paths.is_empty() {
|
||||
run_git(
|
||||
&["clone", url, destination_string.as_str()],
|
||||
/*cwd*/ None,
|
||||
)?;
|
||||
if let Some(ref_name) = ref_name {
|
||||
run_git(
|
||||
&["checkout", ref_name],
|
||||
Some(Path::new(&destination_string)),
|
||||
)?;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
run_git(
|
||||
&[
|
||||
"clone",
|
||||
"--filter=blob:none",
|
||||
"--no-checkout",
|
||||
url,
|
||||
destination_string.as_str(),
|
||||
],
|
||||
/*cwd*/ None,
|
||||
)?;
|
||||
let mut sparse_args = vec!["sparse-checkout", "set"];
|
||||
sparse_args.extend(sparse_paths.iter().map(String::as_str));
|
||||
run_git(&sparse_args, Some(destination))?;
|
||||
run_git(&["checkout", ref_name.unwrap_or("HEAD")], Some(destination))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn safe_marketplace_dir_name(
|
||||
marketplace_name: &str,
|
||||
) -> Result<String, MarketplaceAddError> {
|
||||
let safe = marketplace_name
|
||||
.chars()
|
||||
.map(|ch| {
|
||||
if ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | '.') {
|
||||
ch
|
||||
} else {
|
||||
'-'
|
||||
}
|
||||
})
|
||||
.collect::<String>();
|
||||
let safe = safe.trim_matches('.').to_string();
|
||||
if safe.is_empty() || safe == ".." {
|
||||
return Err(MarketplaceAddError::InvalidRequest(format!(
|
||||
"marketplace name '{marketplace_name}' cannot be used as an install directory"
|
||||
)));
|
||||
}
|
||||
Ok(safe)
|
||||
}
|
||||
|
||||
pub(super) fn ensure_marketplace_destination_is_inside_install_root(
|
||||
install_root: &Path,
|
||||
destination: &Path,
|
||||
) -> Result<(), MarketplaceAddError> {
|
||||
let install_root = install_root.canonicalize().map_err(|err| {
|
||||
MarketplaceAddError::Internal(format!(
|
||||
"failed to resolve marketplace install root {}: {err}",
|
||||
install_root.display()
|
||||
))
|
||||
})?;
|
||||
let destination_parent = destination
|
||||
.parent()
|
||||
.ok_or_else(|| {
|
||||
MarketplaceAddError::Internal("marketplace destination has no parent".to_string())
|
||||
})?
|
||||
.canonicalize()
|
||||
.map_err(|err| {
|
||||
MarketplaceAddError::Internal(format!(
|
||||
"failed to resolve marketplace destination parent {}: {err}",
|
||||
destination.display()
|
||||
))
|
||||
})?;
|
||||
if !destination_parent.starts_with(&install_root) {
|
||||
return Err(MarketplaceAddError::InvalidRequest(format!(
|
||||
"marketplace destination {} is outside install root {}",
|
||||
destination.display(),
|
||||
install_root.display()
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn replace_marketplace_root(
|
||||
staged_root: &Path,
|
||||
destination: &Path,
|
||||
) -> std::io::Result<()> {
|
||||
if let Some(parent) = destination.parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
fs::rename(staged_root, destination)
|
||||
}
|
||||
|
||||
fn run_git(args: &[&str], cwd: Option<&Path>) -> Result<(), MarketplaceAddError> {
|
||||
let mut command = akode_utils_process::background_command("git");
|
||||
command
|
||||
.args(["-c", akode_git_utils::SAFE_BARE_REPOSITORY_CONFIG])
|
||||
.args(args);
|
||||
command.env("GIT_TERMINAL_PROMPT", "0");
|
||||
if let Some(cwd) = cwd {
|
||||
command.current_dir(cwd);
|
||||
}
|
||||
|
||||
let output = command.output().map_err(|err| {
|
||||
MarketplaceAddError::Internal(format!("failed to run git {}: {err}", args.join(" ")))
|
||||
})?;
|
||||
if output.status.success() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
Err(MarketplaceAddError::Internal(format!(
|
||||
"git {} failed with status {}\nstdout:\n{}\nstderr:\n{}",
|
||||
args.join(" "),
|
||||
output.status,
|
||||
stdout.trim(),
|
||||
stderr.trim()
|
||||
)))
|
||||
}
|
||||
348
akode-rs/core-plugins/src/marketplace_add/metadata.rs
Normal file
348
akode-rs/core-plugins/src/marketplace_add/metadata.rs
Normal file
@@ -0,0 +1,348 @@
|
||||
use super::MarketplaceAddError;
|
||||
use super::source::MarketplaceSource;
|
||||
use crate::installed_marketplaces::resolve_configured_marketplace_root;
|
||||
use crate::marketplace::validate_marketplace_root;
|
||||
use akode_config::CONFIG_TOML_FILE;
|
||||
use akode_config::MarketplaceConfigUpdate;
|
||||
use akode_config::record_user_marketplace;
|
||||
use akode_utils_path::paths_match_after_normalization;
|
||||
use std::fs;
|
||||
use std::io::ErrorKind;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(super) struct MarketplaceInstallMetadata {
|
||||
source: InstalledMarketplaceSource,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
enum InstalledMarketplaceSource {
|
||||
Git {
|
||||
url: String,
|
||||
ref_name: Option<String>,
|
||||
sparse_paths: Vec<String>,
|
||||
},
|
||||
Local {
|
||||
path: String,
|
||||
},
|
||||
}
|
||||
|
||||
pub(super) fn record_added_marketplace_entry(
|
||||
codex_home: &Path,
|
||||
marketplace_name: &str,
|
||||
install_metadata: &MarketplaceInstallMetadata,
|
||||
) -> Result<(), MarketplaceAddError> {
|
||||
let source = install_metadata.config_source();
|
||||
let update = MarketplaceConfigUpdate {
|
||||
source_type: install_metadata.config_source_type(),
|
||||
source: &source,
|
||||
ref_name: install_metadata.ref_name(),
|
||||
sparse_paths: install_metadata.sparse_paths(),
|
||||
};
|
||||
|
||||
record_user_marketplace(codex_home, marketplace_name, &update).map_err(|err| {
|
||||
MarketplaceAddError::Internal(format!(
|
||||
"failed to add marketplace '{marketplace_name}' to user config.toml: {err}"
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn installed_marketplace_root_for_source(
|
||||
codex_home: &Path,
|
||||
install_root: &Path,
|
||||
install_metadata: &MarketplaceInstallMetadata,
|
||||
) -> Result<Option<PathBuf>, MarketplaceAddError> {
|
||||
let config_path = codex_home.join(CONFIG_TOML_FILE);
|
||||
let config = match fs::read_to_string(&config_path) {
|
||||
Ok(config) => config,
|
||||
Err(err) if err.kind() == ErrorKind::NotFound => return Ok(None),
|
||||
Err(err) => {
|
||||
return Err(MarketplaceAddError::Internal(format!(
|
||||
"failed to read user config {}: {err}",
|
||||
config_path.display()
|
||||
)));
|
||||
}
|
||||
};
|
||||
let config: toml::Value = toml::from_str(&config).map_err(|err| {
|
||||
MarketplaceAddError::Internal(format!(
|
||||
"failed to parse user config {}: {err}",
|
||||
config_path.display()
|
||||
))
|
||||
})?;
|
||||
let Some(marketplaces) = config.get("marketplaces").and_then(toml::Value::as_table) else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
for (marketplace_name, marketplace) in marketplaces {
|
||||
if !install_metadata.matches_config(marketplace) {
|
||||
continue;
|
||||
}
|
||||
let root = match &install_metadata.source {
|
||||
// Keep using the resolved request path if the configured alias is retargeted.
|
||||
InstalledMarketplaceSource::Local { path } => PathBuf::from(path),
|
||||
InstalledMarketplaceSource::Git { .. } => install_root.join(marketplace_name),
|
||||
};
|
||||
if validate_marketplace_root(&root).is_ok() {
|
||||
return Ok(Some(root));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
pub(super) fn find_marketplace_root_by_name(
|
||||
codex_home: &Path,
|
||||
install_root: &Path,
|
||||
marketplace_name: &str,
|
||||
) -> Result<Option<PathBuf>, MarketplaceAddError> {
|
||||
let config_path = codex_home.join(CONFIG_TOML_FILE);
|
||||
let config = match fs::read_to_string(&config_path) {
|
||||
Ok(config) => config,
|
||||
Err(err) if err.kind() == ErrorKind::NotFound => return Ok(None),
|
||||
Err(err) => {
|
||||
return Err(MarketplaceAddError::Internal(format!(
|
||||
"failed to read user config {}: {err}",
|
||||
config_path.display()
|
||||
)));
|
||||
}
|
||||
};
|
||||
let config: toml::Value = toml::from_str(&config).map_err(|err| {
|
||||
MarketplaceAddError::Internal(format!(
|
||||
"failed to parse user config {}: {err}",
|
||||
config_path.display()
|
||||
))
|
||||
})?;
|
||||
let Some(marketplace) = config
|
||||
.get("marketplaces")
|
||||
.and_then(toml::Value::as_table)
|
||||
.and_then(|marketplaces| marketplaces.get(marketplace_name))
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
let Some(root) =
|
||||
resolve_configured_marketplace_root(marketplace_name, marketplace, install_root)
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
if validate_marketplace_root(&root).is_ok() {
|
||||
Ok(Some(root))
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
impl MarketplaceInstallMetadata {
|
||||
pub(super) fn from_source(source: &MarketplaceSource, sparse_paths: &[String]) -> Self {
|
||||
let source = match source {
|
||||
MarketplaceSource::Git { url, ref_name } => InstalledMarketplaceSource::Git {
|
||||
url: url.clone(),
|
||||
ref_name: ref_name.clone(),
|
||||
sparse_paths: sparse_paths.to_vec(),
|
||||
},
|
||||
MarketplaceSource::Local { path } => InstalledMarketplaceSource::Local {
|
||||
path: path.display().to_string(),
|
||||
},
|
||||
};
|
||||
Self { source }
|
||||
}
|
||||
|
||||
fn config_source_type(&self) -> &'static str {
|
||||
match &self.source {
|
||||
InstalledMarketplaceSource::Git { .. } => "git",
|
||||
InstalledMarketplaceSource::Local { .. } => "local",
|
||||
}
|
||||
}
|
||||
|
||||
fn config_source(&self) -> String {
|
||||
match &self.source {
|
||||
InstalledMarketplaceSource::Git { url, .. } => url.clone(),
|
||||
InstalledMarketplaceSource::Local { path } => path.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
fn ref_name(&self) -> Option<&str> {
|
||||
match &self.source {
|
||||
InstalledMarketplaceSource::Git { ref_name, .. } => ref_name.as_deref(),
|
||||
InstalledMarketplaceSource::Local { .. } => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn sparse_paths(&self) -> &[String] {
|
||||
match &self.source {
|
||||
InstalledMarketplaceSource::Git { sparse_paths, .. } => sparse_paths,
|
||||
InstalledMarketplaceSource::Local { .. } => &[],
|
||||
}
|
||||
}
|
||||
|
||||
fn matches_config(&self, marketplace: &toml::Value) -> bool {
|
||||
marketplace.get("source_type").and_then(toml::Value::as_str)
|
||||
== Some(self.config_source_type())
|
||||
&& marketplace
|
||||
.get("source")
|
||||
.and_then(toml::Value::as_str)
|
||||
.is_some_and(|source| match &self.source {
|
||||
InstalledMarketplaceSource::Local { path } => {
|
||||
paths_match_after_normalization(source, path)
|
||||
}
|
||||
InstalledMarketplaceSource::Git { url, .. } => source == url,
|
||||
})
|
||||
&& marketplace.get("ref").and_then(toml::Value::as_str) == self.ref_name()
|
||||
&& config_sparse_paths(marketplace) == self.sparse_paths()
|
||||
}
|
||||
}
|
||||
|
||||
fn config_sparse_paths(marketplace: &toml::Value) -> Vec<String> {
|
||||
marketplace
|
||||
.get("sparse_paths")
|
||||
.and_then(toml::Value::as_array)
|
||||
.map(|paths| {
|
||||
paths
|
||||
.iter()
|
||||
.filter_map(toml::Value::as_str)
|
||||
.map(str::to_string)
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
|
||||
#[test]
|
||||
fn installed_marketplace_root_for_source_propagates_config_read_errors() {
|
||||
let codex_home = TempDir::new().unwrap();
|
||||
let config_path = codex_home.path().join(CONFIG_TOML_FILE);
|
||||
fs::create_dir(&config_path).unwrap();
|
||||
|
||||
let install_root = codex_home.path().join("marketplaces");
|
||||
let source = MarketplaceSource::Git {
|
||||
url: "https://github.com/owner/repo.git".to_string(),
|
||||
ref_name: None,
|
||||
};
|
||||
let install_metadata = MarketplaceInstallMetadata::from_source(&source, &[]);
|
||||
|
||||
let err = installed_marketplace_root_for_source(
|
||||
codex_home.path(),
|
||||
&install_root,
|
||||
&install_metadata,
|
||||
)
|
||||
.unwrap_err();
|
||||
|
||||
assert!(
|
||||
err.to_string().contains(&format!(
|
||||
"failed to read user config {}:",
|
||||
config_path.display()
|
||||
)),
|
||||
"unexpected error: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installed_marketplace_root_for_source_uses_local_source_root() {
|
||||
let codex_home = TempDir::new().unwrap();
|
||||
let install_root = codex_home.path().join("marketplaces");
|
||||
let source_root = codex_home.path().join("source");
|
||||
fs::create_dir_all(source_root.join(".agents/plugins")).unwrap();
|
||||
fs::write(
|
||||
source_root.join(".agents/plugins/marketplace.json"),
|
||||
r#"{"name":"debug","plugins":[]}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let source = MarketplaceSource::Local {
|
||||
path: source_root.clone(),
|
||||
};
|
||||
let install_metadata = MarketplaceInstallMetadata::from_source(&source, &[]);
|
||||
record_added_marketplace_entry(codex_home.path(), "debug", &install_metadata).unwrap();
|
||||
|
||||
let root = installed_marketplace_root_for_source(
|
||||
codex_home.path(),
|
||||
&install_root,
|
||||
&install_metadata,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(root, Some(source_root));
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn local_marketplace_matches_canonical_and_legacy_windows_sources() {
|
||||
let source = TempDir::new().unwrap();
|
||||
let other = TempDir::new().unwrap();
|
||||
let metadata = MarketplaceInstallMetadata::from_source(
|
||||
&MarketplaceSource::Local {
|
||||
path: source.path().canonicalize().unwrap(),
|
||||
},
|
||||
&[],
|
||||
);
|
||||
let canonical = source.path().canonicalize().unwrap();
|
||||
let legacy =
|
||||
akode_utils_absolute_path::normalize_windows_device_path(&canonical.to_string_lossy())
|
||||
.unwrap();
|
||||
for spelling in [
|
||||
canonical.to_string_lossy().into_owned(),
|
||||
legacy.replace('\\', "/"),
|
||||
] {
|
||||
let config: toml::Value =
|
||||
toml::from_str(&format!("source_type = \"local\"\nsource = {spelling:?}\n"))
|
||||
.unwrap();
|
||||
assert!(metadata.matches_config(&config));
|
||||
}
|
||||
let different = other.path().to_string_lossy();
|
||||
let config: toml::Value = toml::from_str(&format!(
|
||||
"source_type = \"local\"\nsource = {different:?}\n"
|
||||
))
|
||||
.unwrap();
|
||||
assert!(!metadata.matches_config(&config));
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn installed_local_root_does_not_follow_retargeted_configured_junction() {
|
||||
let codex_home = TempDir::new().unwrap();
|
||||
let source_root = codex_home.path().join("source");
|
||||
let other_root = codex_home.path().join("other");
|
||||
for (root, name) in [(&source_root, "source"), (&other_root, "other")] {
|
||||
fs::create_dir_all(root.join(".agents/plugins")).unwrap();
|
||||
fs::write(
|
||||
root.join(".agents/plugins/marketplace.json"),
|
||||
format!(r#"{{"name":"{name}","plugins":[]}}"#),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
let alias = codex_home.path().join("configured-source");
|
||||
crate::test_support::create_directory_junction(&source_root, &alias);
|
||||
let configured_metadata = MarketplaceInstallMetadata::from_source(
|
||||
&MarketplaceSource::Local {
|
||||
path: alias.clone(),
|
||||
},
|
||||
&[],
|
||||
);
|
||||
record_added_marketplace_entry(codex_home.path(), "source", &configured_metadata).unwrap();
|
||||
let canonical_source = source_root.canonicalize().unwrap();
|
||||
let request_metadata = MarketplaceInstallMetadata::from_source(
|
||||
&MarketplaceSource::Local {
|
||||
path: canonical_source.clone(),
|
||||
},
|
||||
&[],
|
||||
);
|
||||
let root = installed_marketplace_root_for_source(
|
||||
codex_home.path(),
|
||||
&codex_home.path().join("marketplaces"),
|
||||
&request_metadata,
|
||||
)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
|
||||
// Model an updater switching the alias before the caller validates the returned root.
|
||||
fs::remove_dir(&alias).unwrap();
|
||||
crate::test_support::create_directory_junction(&other_root, &alias);
|
||||
assert_eq!(root, canonical_source);
|
||||
assert_eq!(validate_marketplace_root(&root).unwrap(), "source");
|
||||
}
|
||||
}
|
||||
393
akode-rs/core-plugins/src/marketplace_add/source.rs
Normal file
393
akode-rs/core-plugins/src/marketplace_add/source.rs
Normal file
@@ -0,0 +1,393 @@
|
||||
use super::MarketplaceAddError;
|
||||
use crate::marketplace::validate_marketplace_root;
|
||||
use akode_plugin::validate_plugin_segment;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) enum MarketplaceSource {
|
||||
Git {
|
||||
url: String,
|
||||
ref_name: Option<String>,
|
||||
},
|
||||
Local {
|
||||
path: PathBuf,
|
||||
},
|
||||
}
|
||||
|
||||
pub(crate) fn parse_marketplace_source(
|
||||
source: &str,
|
||||
explicit_ref: Option<String>,
|
||||
) -> Result<MarketplaceSource, MarketplaceAddError> {
|
||||
let source = source.trim();
|
||||
if source.is_empty() {
|
||||
return Err(MarketplaceAddError::InvalidRequest(
|
||||
"marketplace source must not be empty".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
let (base_source, parsed_ref) = split_source_ref(source);
|
||||
let ref_name = explicit_ref.or(parsed_ref);
|
||||
|
||||
if looks_like_local_path(&base_source) {
|
||||
if ref_name.is_some() {
|
||||
return Err(MarketplaceAddError::InvalidRequest(
|
||||
"--ref is only supported for git marketplace sources".to_string(),
|
||||
));
|
||||
}
|
||||
let path = resolve_local_source_path(&base_source)?;
|
||||
if path.is_file() {
|
||||
return Err(MarketplaceAddError::InvalidRequest(
|
||||
"local marketplace source must be a directory, not a file".to_string(),
|
||||
));
|
||||
}
|
||||
return Ok(MarketplaceSource::Local { path });
|
||||
}
|
||||
|
||||
if is_ssh_git_url(&base_source) || is_git_url(&base_source) {
|
||||
return Ok(MarketplaceSource::Git {
|
||||
url: normalize_git_url(&base_source),
|
||||
ref_name,
|
||||
});
|
||||
}
|
||||
|
||||
if looks_like_github_shorthand(&base_source) {
|
||||
return Ok(MarketplaceSource::Git {
|
||||
url: format!("https://github.com/{base_source}.git"),
|
||||
ref_name,
|
||||
});
|
||||
}
|
||||
|
||||
Err(MarketplaceAddError::InvalidRequest(
|
||||
"invalid marketplace source format; expected owner/repo, a git URL, or a local marketplace path"
|
||||
.to_string(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) fn stage_marketplace_source<F>(
|
||||
source: &MarketplaceSource,
|
||||
sparse_paths: &[String],
|
||||
staged_root: &Path,
|
||||
clone_source: F,
|
||||
) -> Result<(), MarketplaceAddError>
|
||||
where
|
||||
F: Fn(&str, Option<&str>, &[String], &Path) -> Result<(), MarketplaceAddError>,
|
||||
{
|
||||
if !sparse_paths.is_empty() && !matches!(source, MarketplaceSource::Git { .. }) {
|
||||
return Err(MarketplaceAddError::InvalidRequest(
|
||||
"--sparse is only supported for git marketplace sources".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
match source {
|
||||
MarketplaceSource::Git { url, ref_name } => {
|
||||
clone_source(url, ref_name.as_deref(), sparse_paths, staged_root)
|
||||
}
|
||||
MarketplaceSource::Local { .. } => unreachable!(
|
||||
"local marketplace sources are added without staging a copied install root"
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn validate_marketplace_source_root(root: &Path) -> Result<String, MarketplaceAddError> {
|
||||
let marketplace_name = validate_marketplace_root(root)
|
||||
.map_err(|err| MarketplaceAddError::InvalidRequest(err.to_string()))?;
|
||||
validate_plugin_segment(&marketplace_name, "marketplace name")
|
||||
.map_err(MarketplaceAddError::InvalidRequest)?;
|
||||
Ok(marketplace_name)
|
||||
}
|
||||
|
||||
fn split_source_ref(source: &str) -> (String, Option<String>) {
|
||||
if let Some((base, ref_name)) = source.rsplit_once('#') {
|
||||
return (base.to_string(), non_empty_ref(ref_name));
|
||||
}
|
||||
if !looks_like_local_path(source)
|
||||
&& !source.contains("://")
|
||||
&& !is_ssh_git_url(source)
|
||||
&& let Some((base, ref_name)) = source.rsplit_once('@')
|
||||
{
|
||||
return (base.to_string(), non_empty_ref(ref_name));
|
||||
}
|
||||
(source.to_string(), None)
|
||||
}
|
||||
|
||||
fn non_empty_ref(ref_name: &str) -> Option<String> {
|
||||
let ref_name = ref_name.trim();
|
||||
(!ref_name.is_empty()).then(|| ref_name.to_string())
|
||||
}
|
||||
|
||||
fn normalize_git_url(url: &str) -> String {
|
||||
let url = url.trim_end_matches('/');
|
||||
if url.starts_with("https://github.com/") && !url.ends_with(".git") {
|
||||
format!("{url}.git")
|
||||
} else {
|
||||
url.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
fn looks_like_local_path(source: &str) -> bool {
|
||||
Path::new(source).is_absolute()
|
||||
|| looks_like_windows_absolute_path(source)
|
||||
|| source.starts_with("./")
|
||||
|| source.starts_with(".\\")
|
||||
|| source.starts_with("../")
|
||||
|| source.starts_with("..\\")
|
||||
|| source.starts_with("~/")
|
||||
|| source == "."
|
||||
|| source == ".."
|
||||
}
|
||||
|
||||
fn looks_like_windows_absolute_path(source: &str) -> bool {
|
||||
let bytes = source.as_bytes();
|
||||
bytes.len() >= 3
|
||||
&& bytes[0].is_ascii_alphabetic()
|
||||
&& bytes[1] == b':'
|
||||
&& matches!(bytes[2], b'\\' | b'/')
|
||||
|| source.starts_with(r"\\")
|
||||
}
|
||||
|
||||
fn resolve_local_source_path(source: &str) -> Result<PathBuf, MarketplaceAddError> {
|
||||
let path = expand_tilde_path(source);
|
||||
let path = if path.is_absolute() {
|
||||
path
|
||||
} else {
|
||||
std::env::current_dir()
|
||||
.map_err(|err| {
|
||||
MarketplaceAddError::Internal(format!(
|
||||
"failed to read current working directory for local marketplace source: {err}"
|
||||
))
|
||||
})?
|
||||
.join(path)
|
||||
};
|
||||
|
||||
path.canonicalize().map_err(|err| {
|
||||
MarketplaceAddError::InvalidRequest(format!(
|
||||
"failed to resolve local marketplace source path: {err}"
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
fn expand_tilde_path(source: &str) -> PathBuf {
|
||||
let Some(rest) = source.strip_prefix("~/") else {
|
||||
return PathBuf::from(source);
|
||||
};
|
||||
let Some(home) = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")) else {
|
||||
return PathBuf::from(source);
|
||||
};
|
||||
PathBuf::from(home).join(rest)
|
||||
}
|
||||
|
||||
fn is_ssh_git_url(source: &str) -> bool {
|
||||
source.starts_with("ssh://") || source.starts_with("git@") && source.contains(':')
|
||||
}
|
||||
|
||||
fn is_git_url(source: &str) -> bool {
|
||||
source.starts_with("http://") || source.starts_with("https://")
|
||||
}
|
||||
|
||||
fn looks_like_github_shorthand(source: &str) -> bool {
|
||||
let mut segments = source.split('/');
|
||||
let owner = segments.next();
|
||||
let repo = segments.next();
|
||||
let extra = segments.next();
|
||||
owner.is_some_and(is_github_shorthand_segment)
|
||||
&& repo.is_some_and(is_github_shorthand_segment)
|
||||
&& extra.is_none()
|
||||
}
|
||||
|
||||
fn is_github_shorthand_segment(segment: &str) -> bool {
|
||||
!segment.is_empty()
|
||||
&& segment
|
||||
.chars()
|
||||
.all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | '.'))
|
||||
}
|
||||
|
||||
impl MarketplaceSource {
|
||||
pub(crate) fn display(&self) -> String {
|
||||
match self {
|
||||
Self::Git { url, ref_name } => match ref_name {
|
||||
Some(ref_name) => format!("{url}#{ref_name}"),
|
||||
None => url.clone(),
|
||||
},
|
||||
Self::Local { path } => path.display().to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
|
||||
#[test]
|
||||
fn github_shorthand_parses_ref_suffix() {
|
||||
assert_eq!(
|
||||
parse_marketplace_source("owner/repo@main", /*explicit_ref*/ None).unwrap(),
|
||||
MarketplaceSource::Git {
|
||||
url: "https://github.com/owner/repo.git".to_string(),
|
||||
ref_name: Some("main".to_string()),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn git_url_parses_fragment_ref() {
|
||||
assert_eq!(
|
||||
parse_marketplace_source(
|
||||
"https://example.com/team/repo.git#v1",
|
||||
/*explicit_ref*/ None
|
||||
)
|
||||
.unwrap(),
|
||||
MarketplaceSource::Git {
|
||||
url: "https://example.com/team/repo.git".to_string(),
|
||||
ref_name: Some("v1".to_string()),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_ref_overrides_source_ref() {
|
||||
assert_eq!(
|
||||
parse_marketplace_source("owner/repo@main", Some("release".to_string())).unwrap(),
|
||||
MarketplaceSource::Git {
|
||||
url: "https://github.com/owner/repo.git".to_string(),
|
||||
ref_name: Some("release".to_string()),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn github_shorthand_and_git_url_normalize_to_same_source() {
|
||||
let shorthand = parse_marketplace_source("owner/repo", /*explicit_ref*/ None).unwrap();
|
||||
let git_url = parse_marketplace_source(
|
||||
"https://github.com/owner/repo.git",
|
||||
/*explicit_ref*/ None,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(shorthand, git_url);
|
||||
assert_eq!(
|
||||
shorthand,
|
||||
MarketplaceSource::Git {
|
||||
url: "https://github.com/owner/repo.git".to_string(),
|
||||
ref_name: None,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn github_url_with_trailing_slash_normalizes_without_extra_path_segment() {
|
||||
assert_eq!(
|
||||
parse_marketplace_source("https://github.com/owner/repo/", /*explicit_ref*/ None)
|
||||
.unwrap(),
|
||||
MarketplaceSource::Git {
|
||||
url: "https://github.com/owner/repo.git".to_string(),
|
||||
ref_name: None,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_github_https_source_parses_as_git_url() {
|
||||
assert_eq!(
|
||||
parse_marketplace_source("https://gitlab.com/owner/repo", /*explicit_ref*/ None)
|
||||
.unwrap(),
|
||||
MarketplaceSource::Git {
|
||||
url: "https://gitlab.com/owner/repo".to_string(),
|
||||
ref_name: None,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_url_source_is_rejected() {
|
||||
let err =
|
||||
parse_marketplace_source("file:///tmp/marketplace.git", /*explicit_ref*/ None)
|
||||
.unwrap_err();
|
||||
|
||||
assert!(
|
||||
err.to_string()
|
||||
.contains("invalid marketplace source format"),
|
||||
"unexpected error: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_path_source_parses() {
|
||||
let source = parse_marketplace_source(".", /*explicit_ref*/ None).unwrap();
|
||||
|
||||
let MarketplaceSource::Local { path } = source else {
|
||||
panic!("expected local path source");
|
||||
};
|
||||
assert!(path.is_absolute());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_absolute_paths_look_like_local_paths_on_every_host() {
|
||||
assert!(looks_like_local_path(r"C:\Users\alice\marketplace"));
|
||||
assert!(looks_like_local_path("C:/Users/alice/marketplace"));
|
||||
assert!(looks_like_local_path(r"\\server\share\marketplace"));
|
||||
assert!(!looks_like_local_path(r"C:relative\path"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_file_source_is_rejected() {
|
||||
let tempdir = TempDir::new().unwrap();
|
||||
let file = tempdir.path().join("marketplace.json");
|
||||
std::fs::write(&file, "{}").unwrap();
|
||||
|
||||
let err =
|
||||
parse_marketplace_source(file.to_str().unwrap(), /*explicit_ref*/ None).unwrap_err();
|
||||
|
||||
assert!(
|
||||
err.to_string()
|
||||
.contains("local marketplace source must be a directory, not a file"),
|
||||
"unexpected error: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_git_sources_reject_ref_override() {
|
||||
let err = parse_marketplace_source("./marketplace", Some("main".to_string())).unwrap_err();
|
||||
|
||||
assert!(
|
||||
err.to_string()
|
||||
.contains("--ref is only supported for git marketplace sources"),
|
||||
"unexpected error: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_git_sources_reject_sparse_checkout() {
|
||||
let path = std::env::current_dir().unwrap();
|
||||
let err = stage_marketplace_source(
|
||||
&MarketplaceSource::Local { path },
|
||||
&["plugins/foo".to_string()],
|
||||
Path::new("/tmp"),
|
||||
|_url, _ref_name, _sparse_paths, _staged_root| Ok(()),
|
||||
)
|
||||
.unwrap_err();
|
||||
|
||||
assert!(
|
||||
err.to_string()
|
||||
.contains("--sparse is only supported for git marketplace sources"),
|
||||
"unexpected error: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ssh_url_parses_as_git_url() {
|
||||
assert_eq!(
|
||||
parse_marketplace_source(
|
||||
"ssh://git@github.com/owner/repo.git#main",
|
||||
/*explicit_ref*/ None,
|
||||
)
|
||||
.unwrap(),
|
||||
MarketplaceSource::Git {
|
||||
url: "ssh://git@github.com/owner/repo.git".to_string(),
|
||||
ref_name: Some("main".to_string()),
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
163
akode-rs/core-plugins/src/marketplace_context.rs
Normal file
163
akode-rs/core-plugins/src/marketplace_context.rs
Normal file
@@ -0,0 +1,163 @@
|
||||
//! Aggregates request-wide plugin settings and repository-scoped marketplaces.
|
||||
//!
|
||||
//! Marketplace paths and plugin sources use first-scope precedence, while plugin state is
|
||||
//! merged across scopes. Cache refresh reuses listed marketplaces and configured plugin identities.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Request-wide plugin settings and the ordered repository configurations for one marketplace request.
|
||||
#[derive(Clone)]
|
||||
pub struct PluginMarketplaceContext {
|
||||
pub global_config: PluginsConfigInput,
|
||||
pub scopes: Vec<PluginMarketplaceScope>,
|
||||
pub load_errors: Vec<MarketplaceListError>,
|
||||
}
|
||||
|
||||
/// A repository's effective configuration, or non-project configuration when no cwd was supplied.
|
||||
#[derive(Clone)]
|
||||
pub struct PluginMarketplaceScope {
|
||||
pub cwd: Option<AbsolutePathBuf>,
|
||||
pub config: PluginsConfigInput,
|
||||
}
|
||||
|
||||
impl PluginMarketplaceContext {
|
||||
pub fn plugins_enabled(&self) -> bool {
|
||||
self.global_config.plugins_enabled
|
||||
|| self.scopes.iter().any(|scope| scope.config.plugins_enabled)
|
||||
}
|
||||
|
||||
pub(super) fn list_marketplaces(
|
||||
&self,
|
||||
manager: &PluginsManager,
|
||||
include_openai_curated: bool,
|
||||
) -> Result<ConfiguredMarketplaceListOutcome, MarketplaceError> {
|
||||
let mut plugin_states = ConfiguredPluginStates::default();
|
||||
for scope in self
|
||||
.scopes
|
||||
.iter()
|
||||
.filter(|scope| scope.config.plugins_enabled)
|
||||
{
|
||||
let state = manager.configured_plugin_states(&scope.config);
|
||||
plugin_states.installed.extend(state.installed);
|
||||
plugin_states.enabled.extend(state.enabled);
|
||||
}
|
||||
|
||||
let mut combined = ConfiguredMarketplaceListOutcome {
|
||||
errors: self.load_errors.clone(),
|
||||
..Default::default()
|
||||
};
|
||||
let mut seen_marketplace_paths = HashSet::new();
|
||||
let mut seen_plugin_ids = HashSet::new();
|
||||
let mut seen_error_paths = combined
|
||||
.errors
|
||||
.iter()
|
||||
.map(|error| error.path.clone())
|
||||
.collect::<HashSet<_>>();
|
||||
|
||||
for scope in self
|
||||
.scopes
|
||||
.iter()
|
||||
.filter(|scope| scope.config.plugins_enabled)
|
||||
{
|
||||
let outcome = manager.list_marketplaces_for_config_with_states(
|
||||
&scope.config,
|
||||
scope.cwd.as_slice(),
|
||||
include_openai_curated,
|
||||
&plugin_states,
|
||||
)?;
|
||||
for mut marketplace in outcome.marketplaces {
|
||||
if !seen_marketplace_paths.insert(marketplace.path.clone()) {
|
||||
continue;
|
||||
}
|
||||
marketplace
|
||||
.plugins
|
||||
.retain(|plugin| seen_plugin_ids.insert(plugin.id.clone()));
|
||||
if !marketplace.plugins.is_empty() {
|
||||
combined.marketplaces.push(marketplace);
|
||||
}
|
||||
}
|
||||
combined.errors.extend(
|
||||
outcome
|
||||
.errors
|
||||
.into_iter()
|
||||
.filter(|error| seen_error_paths.insert(error.path.clone())),
|
||||
);
|
||||
}
|
||||
|
||||
Ok(combined)
|
||||
}
|
||||
|
||||
pub(super) fn non_curated_cache_refresh_request(
|
||||
&self,
|
||||
manager: &PluginsManager,
|
||||
marketplaces: &[ConfiguredMarketplace],
|
||||
mode: NonCuratedCacheRefreshMode,
|
||||
git_mode: PluginGitMode,
|
||||
) -> Option<NonCuratedCacheRefreshRequest> {
|
||||
let configured_plugin_key_set = self
|
||||
.scopes
|
||||
.iter()
|
||||
.filter(|scope| scope.config.plugins_enabled)
|
||||
.flat_map(|scope| {
|
||||
configured_plugins_from_stack(
|
||||
&scope.config.config_layer_stack,
|
||||
manager.codex_home.as_path(),
|
||||
)
|
||||
.into_keys()
|
||||
})
|
||||
.collect::<HashSet<_>>();
|
||||
|
||||
let mut roots = Vec::new();
|
||||
let mut configured_plugin_keys = Vec::new();
|
||||
let mut configured_plugin_sources = Vec::new();
|
||||
|
||||
for marketplace in marketplaces {
|
||||
if is_openai_curated_marketplace_name(&marketplace.name) {
|
||||
continue;
|
||||
}
|
||||
|
||||
for plugin in &marketplace.plugins {
|
||||
if !configured_plugin_key_set.contains(&plugin.id) {
|
||||
continue;
|
||||
}
|
||||
let local_version = if plugin.source.is_install_materialized() {
|
||||
plugin
|
||||
.manifest_fallback
|
||||
.as_ref()
|
||||
.and_then(MarketplacePluginManifestFallback::parse_for_listing)
|
||||
.and_then(|manifest| manifest.version)
|
||||
} else {
|
||||
plugin.local_version.clone()
|
||||
};
|
||||
configured_plugin_keys.push(plugin.id.clone());
|
||||
configured_plugin_sources.push(NonCuratedPluginSource {
|
||||
marketplace_path: marketplace.path.clone(),
|
||||
plugin_key: plugin.id.clone(),
|
||||
source: plugin.source.clone(),
|
||||
local_version,
|
||||
});
|
||||
}
|
||||
roots.push(marketplace.path.clone());
|
||||
}
|
||||
|
||||
if roots.is_empty() || configured_plugin_keys.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Refresh rediscovers sources in root order; retain listing's precedence.
|
||||
configured_plugin_keys.sort_unstable();
|
||||
configured_plugin_sources.sort_by(|left, right| {
|
||||
left.marketplace_path
|
||||
.cmp(&right.marketplace_path)
|
||||
.then_with(|| left.plugin_key.cmp(&right.plugin_key))
|
||||
});
|
||||
|
||||
Some(NonCuratedCacheRefreshRequest {
|
||||
roots,
|
||||
configured_plugin_keys,
|
||||
configured_plugin_sources,
|
||||
mode,
|
||||
git_mode,
|
||||
})
|
||||
}
|
||||
}
|
||||
622
akode-rs/core-plugins/src/marketplace_policy.rs
Normal file
622
akode-rs/core-plugins/src/marketplace_policy.rs
Normal file
@@ -0,0 +1,622 @@
|
||||
use crate::OPENAI_API_CURATED_MARKETPLACE_NAME;
|
||||
use crate::OPENAI_BUNDLED_ALPHA_MARKETPLACE_NAME;
|
||||
use crate::OPENAI_BUNDLED_MARKETPLACE_NAME;
|
||||
use crate::OPENAI_CURATED_MARKETPLACE_NAME;
|
||||
use crate::OPENAI_PRIMARY_RUNTIME_MARKETPLACE_NAME;
|
||||
use crate::installed_marketplaces::marketplace_install_root;
|
||||
use crate::installed_marketplaces::resolve_configured_marketplace_root;
|
||||
use crate::is_openai_curated_marketplace_name;
|
||||
use crate::marketplace::marketplace_root_dir;
|
||||
use crate::marketplace_add::MarketplaceSource;
|
||||
use crate::marketplace_add::parse_marketplace_source;
|
||||
use crate::startup_sync::OPENAI_PLUGINS_GIT_URL;
|
||||
use crate::startup_sync::curated_plugins_api_marketplace_path;
|
||||
use crate::startup_sync::curated_plugins_repo_path;
|
||||
use akode_config::ConfigLayerStack;
|
||||
use akode_config::ConfigRequirements;
|
||||
use akode_config::MarketplaceAllowedSourceKind;
|
||||
use akode_config::MarketplaceAllowedSourceToml;
|
||||
use akode_config::RequirementSource;
|
||||
use akode_config::types::MarketplaceConfig;
|
||||
use akode_config::types::MarketplaceSourceType;
|
||||
use akode_config::types::PluginConfig;
|
||||
use akode_config::types::PluginsConfigToml;
|
||||
use akode_plugin::PluginId;
|
||||
use akode_utils_absolute_path::AbsolutePathBuf;
|
||||
use akode_utils_path::paths_match_after_normalization;
|
||||
use regex::Regex;
|
||||
use serde::Deserialize;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use url::Url;
|
||||
|
||||
enum AllowedMarketplaceSource {
|
||||
GitUrl {
|
||||
url: String,
|
||||
ref_name: Option<String>,
|
||||
},
|
||||
GitHostPattern(Regex),
|
||||
Local(AbsolutePathBuf),
|
||||
}
|
||||
|
||||
pub(crate) struct MarketplacePolicy {
|
||||
restricted: Option<RestrictedMarketplacePolicy>,
|
||||
}
|
||||
|
||||
struct RestrictedMarketplacePolicy {
|
||||
allowed_sources: Result<Vec<AllowedMarketplaceSource>, String>,
|
||||
source: RequirementSource,
|
||||
}
|
||||
|
||||
impl MarketplacePolicy {
|
||||
pub(crate) fn from_requirements(requirements: &ConfigRequirements) -> Self {
|
||||
let Some(requirements) = requirements.marketplaces.as_ref().filter(|requirements| {
|
||||
requirements
|
||||
.value
|
||||
.restrict_to_allowed_sources
|
||||
.unwrap_or(false)
|
||||
}) else {
|
||||
return Self { restricted: None };
|
||||
};
|
||||
|
||||
let allowed_sources = requirements
|
||||
.value
|
||||
.allowed_sources
|
||||
.iter()
|
||||
.map(|(key, allowed_source)| {
|
||||
compile_allowed_source(key, allowed_source, &requirements.source)
|
||||
})
|
||||
.collect();
|
||||
Self {
|
||||
restricted: Some(RestrictedMarketplacePolicy {
|
||||
allowed_sources,
|
||||
source: requirements.source.clone(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_restricted(&self) -> bool {
|
||||
self.restricted.is_some()
|
||||
}
|
||||
|
||||
fn validate_source(&self, source: &MarketplaceSource) -> Result<(), String> {
|
||||
let Some(RestrictedMarketplacePolicy {
|
||||
allowed_sources,
|
||||
source: requirement_source,
|
||||
}) = &self.restricted
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
let allowed_sources = allowed_sources.as_ref().map_err(Clone::clone)?;
|
||||
if allowed_sources
|
||||
.iter()
|
||||
.any(|allowed_source| allowed_source.matches(source))
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
Err(format!(
|
||||
"marketplace source `{}` is not allowed by requirements from {requirement_source}",
|
||||
source.display()
|
||||
))
|
||||
}
|
||||
|
||||
pub(crate) fn validate_install(
|
||||
&self,
|
||||
config_layer_stack: &ConfigLayerStack,
|
||||
codex_home: &Path,
|
||||
marketplace_path: &AbsolutePathBuf,
|
||||
marketplace_name: &str,
|
||||
) -> Result<(), String> {
|
||||
let root = marketplace_root_dir(marketplace_path).map_err(|err| err.to_string())?;
|
||||
if let Some(expected_name) = managed_marketplace_name(codex_home, marketplace_path, &root) {
|
||||
if is_openai_curated_marketplace_name(expected_name) {
|
||||
self.validate_git_source(OPENAI_PLUGINS_GIT_URL, /*ref_name*/ None)?;
|
||||
}
|
||||
return validate_expected_marketplace_name(expected_name, marketplace_name);
|
||||
}
|
||||
if is_reserved_marketplace_name(marketplace_name) {
|
||||
return Err(format!(
|
||||
"marketplace `{marketplace_name}` is reserved and cannot be loaded from this source"
|
||||
));
|
||||
}
|
||||
if !self.is_restricted() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let effective_config = config_layer_stack.effective_config();
|
||||
let marketplace = effective_config
|
||||
.get("marketplaces")
|
||||
.and_then(toml::Value::as_table)
|
||||
.and_then(|marketplaces| marketplaces.get(marketplace_name))
|
||||
.ok_or_else(|| {
|
||||
format!(
|
||||
"marketplace `{marketplace_name}` must be added to config before plugins can be installed while marketplace source restrictions are enabled"
|
||||
)
|
||||
})?;
|
||||
self.validate_configured_marketplace(marketplace_name, marketplace)?;
|
||||
|
||||
let configured_root = resolve_configured_marketplace_root(
|
||||
marketplace_name,
|
||||
marketplace,
|
||||
&marketplace_install_root(codex_home),
|
||||
)
|
||||
.ok_or_else(|| {
|
||||
format!("configured marketplace `{marketplace_name}` does not have a usable root")
|
||||
})?;
|
||||
if !paths_match_after_normalization(&configured_root, root.as_path()) {
|
||||
return Err(format!(
|
||||
"marketplace path `{}` does not match configured marketplace `{marketplace_name}`",
|
||||
root.as_path().display()
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn validate_git_source(
|
||||
&self,
|
||||
source: &str,
|
||||
ref_name: Option<String>,
|
||||
) -> Result<Option<MarketplaceSource>, String> {
|
||||
if !self.is_restricted() {
|
||||
return Ok(None);
|
||||
}
|
||||
let source = parse_marketplace_source(source, ref_name).map_err(|err| err.to_string())?;
|
||||
if !matches!(source, MarketplaceSource::Git { .. }) {
|
||||
return Err("configured Git marketplace source is not a Git URL".to_string());
|
||||
}
|
||||
self.validate_source(&source)?;
|
||||
Ok(Some(source))
|
||||
}
|
||||
|
||||
fn validate_configured_marketplace(
|
||||
&self,
|
||||
marketplace_name: &str,
|
||||
marketplace: &toml::Value,
|
||||
) -> Result<(), String> {
|
||||
let source = configured_marketplace_source(marketplace_name, marketplace)?;
|
||||
self.validate_source(&source)
|
||||
}
|
||||
}
|
||||
|
||||
impl AllowedMarketplaceSource {
|
||||
fn matches(&self, source: &MarketplaceSource) -> bool {
|
||||
match (self, source) {
|
||||
(
|
||||
Self::GitUrl {
|
||||
url: allowed_url,
|
||||
ref_name: allowed_ref,
|
||||
},
|
||||
MarketplaceSource::Git { url, ref_name },
|
||||
) => {
|
||||
allowed_url == url
|
||||
&& allowed_ref
|
||||
.as_ref()
|
||||
.is_none_or(|allowed_ref| Some(allowed_ref) == ref_name.as_ref())
|
||||
}
|
||||
(Self::GitHostPattern(pattern), MarketplaceSource::Git { url, .. }) => {
|
||||
git_hostname(url).is_some_and(|hostname| pattern.is_match(&hostname))
|
||||
}
|
||||
(Self::Local(allowed), MarketplaceSource::Local { path }) => {
|
||||
paths_match_after_normalization(allowed.as_path(), path)
|
||||
}
|
||||
(Self::GitUrl { .. } | Self::GitHostPattern(_), MarketplaceSource::Local { .. })
|
||||
| (Self::Local(_), MarketplaceSource::Git { .. }) => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn policy_filtered_plugin_config(
|
||||
config_layer_stack: &ConfigLayerStack,
|
||||
codex_home: &Path,
|
||||
) -> Option<toml::Value> {
|
||||
let mut effective_config = config_layer_stack.effective_config();
|
||||
if effective_config.get("plugins").is_none() && effective_config.get("marketplaces").is_none() {
|
||||
return None;
|
||||
}
|
||||
let policy = MarketplacePolicy::from_requirements(config_layer_stack.requirements());
|
||||
let allowed_marketplace_names =
|
||||
allowed_configured_marketplace_names_with_policy(&effective_config, &policy, codex_home);
|
||||
let configured_marketplace_names = effective_config
|
||||
.get("marketplaces")
|
||||
.and_then(toml::Value::as_table)
|
||||
.map(|marketplaces| marketplaces.keys().cloned().collect::<HashSet<_>>())
|
||||
.unwrap_or_default();
|
||||
|
||||
if let Some(marketplaces) = effective_config
|
||||
.get_mut("marketplaces")
|
||||
.and_then(toml::Value::as_table_mut)
|
||||
{
|
||||
marketplaces
|
||||
.retain(|marketplace_name, _| allowed_marketplace_names.contains(marketplace_name));
|
||||
}
|
||||
if let Some(plugins) = effective_config
|
||||
.get_mut("plugins")
|
||||
.and_then(toml::Value::as_table_mut)
|
||||
{
|
||||
plugins.retain(|plugin_key, _| {
|
||||
if plugin_key == "_default" {
|
||||
return true;
|
||||
}
|
||||
let Ok(plugin_id) = PluginId::parse(plugin_key) else {
|
||||
return !policy.is_restricted();
|
||||
};
|
||||
let marketplace_name = &plugin_id.marketplace_name;
|
||||
if configured_marketplace_names.contains(marketplace_name) {
|
||||
return allowed_marketplace_names.contains(marketplace_name);
|
||||
}
|
||||
if is_openai_curated_marketplace_name(marketplace_name) {
|
||||
return policy
|
||||
.validate_git_source(OPENAI_PLUGINS_GIT_URL, /*ref_name*/ None)
|
||||
.is_ok();
|
||||
}
|
||||
!policy.is_restricted()
|
||||
});
|
||||
}
|
||||
Some(effective_config)
|
||||
}
|
||||
|
||||
pub fn allowed_configured_marketplace_names(
|
||||
config_layer_stack: &ConfigLayerStack,
|
||||
codex_home: &Path,
|
||||
) -> HashSet<String> {
|
||||
let effective_config = config_layer_stack.effective_config();
|
||||
let policy = MarketplacePolicy::from_requirements(config_layer_stack.requirements());
|
||||
allowed_configured_marketplace_names_with_policy(&effective_config, &policy, codex_home)
|
||||
}
|
||||
|
||||
fn allowed_configured_marketplace_names_with_policy(
|
||||
effective_config: &toml::Value,
|
||||
policy: &MarketplacePolicy,
|
||||
codex_home: &Path,
|
||||
) -> HashSet<String> {
|
||||
let Some(marketplaces) = effective_config
|
||||
.get("marketplaces")
|
||||
.and_then(toml::Value::as_table)
|
||||
else {
|
||||
return HashSet::new();
|
||||
};
|
||||
marketplaces
|
||||
.iter()
|
||||
.filter_map(|(marketplace_name, marketplace)| {
|
||||
let allowed = match managed_marketplace_config_name(codex_home, marketplace) {
|
||||
Some(expected_name) => expected_name == marketplace_name,
|
||||
None if is_reserved_marketplace_name(marketplace_name) => false,
|
||||
None if !policy.is_restricted() => true,
|
||||
None => policy
|
||||
.validate_configured_marketplace(marketplace_name, marketplace)
|
||||
.is_ok(),
|
||||
};
|
||||
allowed.then(|| marketplace_name.clone())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn configured_plugins_from_stack(
|
||||
config_layer_stack: &ConfigLayerStack,
|
||||
codex_home: &Path,
|
||||
) -> HashMap<String, PluginConfig> {
|
||||
let Some(effective_config) = policy_filtered_plugin_config(config_layer_stack, codex_home)
|
||||
else {
|
||||
return HashMap::new();
|
||||
};
|
||||
let Some(plugins_value) = effective_config.get("plugins") else {
|
||||
return HashMap::new();
|
||||
};
|
||||
match PluginsConfigToml::deserialize(plugins_value.clone()) {
|
||||
Ok(plugins) => plugins.plugins,
|
||||
Err(err) => {
|
||||
tracing::warn!("invalid plugins config: {err}");
|
||||
HashMap::new()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn validate_marketplace_source_for_add(
|
||||
codex_home: &Path,
|
||||
requirements: &ConfigRequirements,
|
||||
source: &MarketplaceSource,
|
||||
) -> Result<Option<&'static str>, String> {
|
||||
let policy = MarketplacePolicy::from_requirements(requirements);
|
||||
if let MarketplaceSource::Local { path } = source
|
||||
&& let Some(expected_name) = managed_local_marketplace_name(codex_home, path)
|
||||
{
|
||||
return Ok(Some(expected_name));
|
||||
}
|
||||
if !policy.is_restricted() {
|
||||
return Ok(None);
|
||||
}
|
||||
policy.validate_source(source)?;
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
pub(crate) fn validate_marketplace_name_for_add(
|
||||
expected_name: Option<&'static str>,
|
||||
marketplace_name: &str,
|
||||
) -> Result<(), String> {
|
||||
if let Some(expected_name) = expected_name {
|
||||
return validate_expected_marketplace_name(expected_name, marketplace_name);
|
||||
}
|
||||
if is_reserved_marketplace_name(marketplace_name) {
|
||||
return Err(format!(
|
||||
"marketplace `{marketplace_name}` is reserved and cannot be added from this source"
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn compile_allowed_source(
|
||||
key: &str,
|
||||
allowed_source: &MarketplaceAllowedSourceToml,
|
||||
requirement_source: &RequirementSource,
|
||||
) -> Result<AllowedMarketplaceSource, String> {
|
||||
let invalid = |reason: &str| {
|
||||
format!("invalid marketplace allowed source `{key}` in {requirement_source}: {reason}")
|
||||
};
|
||||
let source = allowed_source
|
||||
.source
|
||||
.ok_or_else(|| invalid("missing source"))?;
|
||||
match source {
|
||||
MarketplaceAllowedSourceKind::Git => {
|
||||
let url = allowed_source
|
||||
.url
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|url| !url.is_empty())
|
||||
.ok_or_else(|| invalid("missing url"))?;
|
||||
let ref_name = match allowed_source.ref_name.as_deref() {
|
||||
Some(ref_name) if ref_name.trim().is_empty() => {
|
||||
return Err(invalid("ref must not be empty"));
|
||||
}
|
||||
Some(ref_name) => Some(ref_name.trim().to_string()),
|
||||
None => None,
|
||||
};
|
||||
let source =
|
||||
parse_marketplace_source(url, ref_name).map_err(|err| invalid(&err.to_string()))?;
|
||||
let MarketplaceSource::Git { url, ref_name } = source else {
|
||||
return Err(invalid("expected a Git URL"));
|
||||
};
|
||||
Ok(AllowedMarketplaceSource::GitUrl { url, ref_name })
|
||||
}
|
||||
MarketplaceAllowedSourceKind::HostPattern => {
|
||||
let host_pattern = allowed_source
|
||||
.host_pattern
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|host_pattern| !host_pattern.is_empty())
|
||||
.ok_or_else(|| invalid("missing host_pattern"))?;
|
||||
Regex::new(host_pattern)
|
||||
.map(AllowedMarketplaceSource::GitHostPattern)
|
||||
.map_err(|err| invalid(&err.to_string()))
|
||||
}
|
||||
MarketplaceAllowedSourceKind::Local => {
|
||||
let path = allowed_source
|
||||
.path
|
||||
.as_ref()
|
||||
.filter(|path| !path.as_os_str().is_empty())
|
||||
.ok_or_else(|| invalid("missing path"))?;
|
||||
if !path.is_absolute() {
|
||||
return Err(invalid("local path must be absolute"));
|
||||
}
|
||||
let path = AbsolutePathBuf::from_absolute_path_checked(path)
|
||||
.map_err(|_| invalid("local path must be absolute"))?;
|
||||
Ok(AllowedMarketplaceSource::Local(path))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn configured_marketplace_source(
|
||||
marketplace_name: &str,
|
||||
marketplace: &toml::Value,
|
||||
) -> Result<MarketplaceSource, String> {
|
||||
let MarketplaceConfig {
|
||||
source_type,
|
||||
source,
|
||||
ref_name,
|
||||
..
|
||||
} = marketplace
|
||||
.clone()
|
||||
.try_into()
|
||||
.map_err(|err| format!("invalid config for marketplace `{marketplace_name}`: {err}"))?;
|
||||
let source_type = source_type.ok_or_else(|| {
|
||||
format!("configured marketplace `{marketplace_name}` is missing source_type")
|
||||
})?;
|
||||
let source = source
|
||||
.ok_or_else(|| format!("configured marketplace `{marketplace_name}` is missing source"))?;
|
||||
match source_type {
|
||||
MarketplaceSourceType::Local => Ok(MarketplaceSource::Local {
|
||||
path: PathBuf::from(source),
|
||||
}),
|
||||
MarketplaceSourceType::Git => {
|
||||
let parsed = parse_marketplace_source(&source, ref_name).map_err(|err| {
|
||||
format!("invalid source for marketplace `{marketplace_name}`: {err}")
|
||||
})?;
|
||||
if matches!(parsed, MarketplaceSource::Git { .. }) {
|
||||
Ok(parsed)
|
||||
} else {
|
||||
Err(format!(
|
||||
"configured marketplace `{marketplace_name}` source does not match source_type `git`"
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_expected_marketplace_name(
|
||||
expected_name: &str,
|
||||
marketplace_name: &str,
|
||||
) -> Result<(), String> {
|
||||
(marketplace_name == expected_name)
|
||||
.then_some(())
|
||||
.ok_or_else(|| {
|
||||
format!(
|
||||
"marketplace manifest name `{marketplace_name}` does not match managed marketplace `{expected_name}`"
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// Marketplace names of the removed remote plugin catalog. They stay reserved so a repository
|
||||
/// marketplace cannot impersonate a name that older clients treated as server-managed.
|
||||
pub(crate) const LEGACY_REMOTE_MARKETPLACE_NAMES: [&str; 6] = [
|
||||
"openai-curated-remote",
|
||||
"created-by-me-remote",
|
||||
"workspace-directory",
|
||||
"workspace-shared-with-me",
|
||||
"workspace-shared-with-me-private",
|
||||
"workspace-shared-with-me-unlisted",
|
||||
];
|
||||
|
||||
fn is_reserved_marketplace_name(marketplace_name: &str) -> bool {
|
||||
matches!(
|
||||
marketplace_name,
|
||||
OPENAI_CURATED_MARKETPLACE_NAME
|
||||
| OPENAI_API_CURATED_MARKETPLACE_NAME
|
||||
| OPENAI_BUNDLED_MARKETPLACE_NAME
|
||||
| OPENAI_BUNDLED_ALPHA_MARKETPLACE_NAME
|
||||
| OPENAI_PRIMARY_RUNTIME_MARKETPLACE_NAME
|
||||
) || LEGACY_REMOTE_MARKETPLACE_NAMES.contains(&marketplace_name)
|
||||
}
|
||||
|
||||
fn managed_marketplace_name(
|
||||
codex_home: &Path,
|
||||
marketplace_path: &AbsolutePathBuf,
|
||||
root: &AbsolutePathBuf,
|
||||
) -> Option<&'static str> {
|
||||
if is_expected_managed_path(
|
||||
marketplace_path.as_path(),
|
||||
&curated_plugins_api_marketplace_path(codex_home),
|
||||
) && is_expected_managed_path(root.as_path(), &curated_plugins_repo_path(codex_home))
|
||||
{
|
||||
return Some(OPENAI_API_CURATED_MARKETPLACE_NAME);
|
||||
}
|
||||
if is_expected_managed_path(root.as_path(), &curated_plugins_repo_path(codex_home)) {
|
||||
return Some(OPENAI_CURATED_MARKETPLACE_NAME);
|
||||
}
|
||||
managed_local_marketplace_name(codex_home, root.as_path())
|
||||
}
|
||||
|
||||
fn managed_marketplace_config_name(
|
||||
codex_home: &Path,
|
||||
marketplace: &toml::Value,
|
||||
) -> Option<&'static str> {
|
||||
if marketplace.get("source_type").and_then(toml::Value::as_str) != Some("local") {
|
||||
return None;
|
||||
}
|
||||
let path = marketplace
|
||||
.get("source")
|
||||
.and_then(toml::Value::as_str)
|
||||
.map(Path::new)
|
||||
.filter(|path| path.is_absolute())?;
|
||||
managed_local_marketplace_name(codex_home, path)
|
||||
}
|
||||
|
||||
fn managed_local_marketplace_name(codex_home: &Path, root: &Path) -> Option<&'static str> {
|
||||
for marketplace_name in [
|
||||
OPENAI_BUNDLED_MARKETPLACE_NAME,
|
||||
OPENAI_BUNDLED_ALPHA_MARKETPLACE_NAME,
|
||||
] {
|
||||
let expected_root = codex_home
|
||||
.join(".tmp/bundled-marketplaces")
|
||||
.join(marketplace_name);
|
||||
if is_expected_managed_path(root, &expected_root) {
|
||||
return Some(marketplace_name);
|
||||
}
|
||||
}
|
||||
|
||||
let runtime_root = primary_runtime_marketplace_root()?;
|
||||
is_expected_managed_path(root, &runtime_root).then_some(OPENAI_PRIMARY_RUNTIME_MARKETPLACE_NAME)
|
||||
}
|
||||
|
||||
fn is_expected_managed_path(path: &Path, expected: &Path) -> bool {
|
||||
if path == expected {
|
||||
return true;
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
path.strip_prefix("/private/var")
|
||||
.is_ok_and(|suffix| Path::new("/var").join(suffix) == expected)
|
||||
|| expected
|
||||
.strip_prefix("/private/var")
|
||||
.is_ok_and(|suffix| Path::new("/var").join(suffix) == path)
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let path = path.to_string_lossy();
|
||||
let path = akode_utils_absolute_path::normalize_windows_device_path(&path)
|
||||
.unwrap_or_else(|| path.into_owned())
|
||||
.replace('/', "\\");
|
||||
// Resolve only the owned root; arbitrary aliases must not borrow managed provenance.
|
||||
let canonical_expected = expected.canonicalize().ok();
|
||||
std::iter::once(expected)
|
||||
.chain(canonical_expected.as_deref())
|
||||
.any(|expected| {
|
||||
let expected = expected.to_string_lossy();
|
||||
let expected = akode_utils_absolute_path::normalize_windows_device_path(&expected)
|
||||
.unwrap_or_else(|| expected.into_owned());
|
||||
path.eq_ignore_ascii_case(&expected.replace('/', "\\"))
|
||||
})
|
||||
}
|
||||
#[cfg(not(any(target_os = "macos", windows)))]
|
||||
{
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn primary_runtime_marketplace_root() -> Option<PathBuf> {
|
||||
Some(
|
||||
primary_runtime_cache_dir()?
|
||||
.join("codex-runtimes/codex-primary-runtime/plugins")
|
||||
.join(OPENAI_PRIMARY_RUNTIME_MARKETPLACE_NAME),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn primary_runtime_cache_dir() -> Option<PathBuf> {
|
||||
primary_runtime_cache_dir_from_user_profile(std::env::var_os("USERPROFILE").map(PathBuf::from))
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn primary_runtime_cache_dir_from_user_profile(user_profile: Option<PathBuf>) -> Option<PathBuf> {
|
||||
user_profile.map(|profile| profile.join(".cache"))
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn primary_runtime_cache_dir() -> Option<PathBuf> {
|
||||
dirs::home_dir().map(|home| home.join(".cache"))
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
|
||||
fn primary_runtime_cache_dir() -> Option<PathBuf> {
|
||||
dirs::cache_dir()
|
||||
}
|
||||
|
||||
fn git_hostname(url: &str) -> Option<String> {
|
||||
// Url treats backslashes as HTTP(S) path separators, but Git/libcurl does not.
|
||||
// A backslash anywhere in userinfo can therefore hide the host after the final @.
|
||||
if let Some(authority_and_path) = url
|
||||
.strip_prefix("http://")
|
||||
.or_else(|| url.strip_prefix("https://"))
|
||||
{
|
||||
let authority = authority_and_path
|
||||
.trim_start_matches('/')
|
||||
.split(['/', '?', '#'])
|
||||
.next()?;
|
||||
if let Some((userinfo, _)) = authority.rsplit_once('@')
|
||||
&& userinfo.contains('\\')
|
||||
{
|
||||
return None;
|
||||
}
|
||||
}
|
||||
if let Ok(url) = Url::parse(url) {
|
||||
return url.host_str().map(str::to_ascii_lowercase);
|
||||
}
|
||||
let (_, host_and_path) = url.split_once('@')?;
|
||||
let (hostname, _) = host_and_path.split_once(':')?;
|
||||
(!hostname.is_empty()).then(|| hostname.to_ascii_lowercase())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "marketplace_policy_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,90 @@
|
||||
//! Exercises curated Git requirements across discovery, installation, cached loading, and sync.
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[path = "curated_skill_tests.rs"]
|
||||
mod skills;
|
||||
|
||||
#[tokio::test]
|
||||
async fn curated_git_policy_controls_catalog_install_and_cached_activation() {
|
||||
// The ChatGPT curated catalog required ChatGPT auth; only the API catalog remains.
|
||||
for (name, auth) in [(OPENAI_API_CURATED_MARKETPLACE_NAME, AuthMode::ApiKey)] {
|
||||
let home = TempDir::new().unwrap();
|
||||
let root = curated_plugins_repo_path(home.path());
|
||||
write_openai_curated_marketplace(&root, &["sample"]);
|
||||
write_openai_api_curated_marketplace(&root, &["sample"]);
|
||||
write_curated_plugin_sha(home.path(), TEST_CURATED_PLUGIN_SHA);
|
||||
write_cached_plugin(home.path(), name, "sample");
|
||||
let user_config = format!("[plugins.\"sample@{name}\"]\nenabled = true\n");
|
||||
let allowed = plugins_config_input_with_requirements(
|
||||
home.path(),
|
||||
&user_config,
|
||||
r#"
|
||||
[marketplaces]
|
||||
restrict_to_allowed_sources = true
|
||||
[marketplaces.allowed_sources.curated]
|
||||
source = "git"
|
||||
url = "https://github.com/openai/plugins.git"
|
||||
"#,
|
||||
);
|
||||
let blocked = plugins_config_input_with_requirements(
|
||||
home.path(),
|
||||
&user_config,
|
||||
"[marketplaces]\nrestrict_to_allowed_sources = true\n",
|
||||
);
|
||||
let host_allowed = plugins_config_input_with_requirements(
|
||||
home.path(),
|
||||
&user_config,
|
||||
r#"
|
||||
[marketplaces]
|
||||
restrict_to_allowed_sources = true
|
||||
[marketplaces.allowed_sources.github]
|
||||
source = "host_pattern"
|
||||
host_pattern = '^github[.]com$'
|
||||
"#,
|
||||
);
|
||||
let manager = Arc::new(test_plugins_manager_with_options(
|
||||
home.path().to_path_buf(),
|
||||
Some(Product::Codex),
|
||||
Some(auth),
|
||||
));
|
||||
let manifest = if name == OPENAI_CURATED_MARKETPLACE_NAME {
|
||||
root.join(".agents/plugins/marketplace.json")
|
||||
} else {
|
||||
curated_plugins_api_marketplace_path(home.path())
|
||||
};
|
||||
for (config, permitted) in [(&allowed, true), (&blocked, false), (&host_allowed, true)] {
|
||||
let expected = if permitted {
|
||||
vec![format!("sample@{name}")]
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
assert_eq!(loaded_plugin_names(&manager, config).await, expected);
|
||||
let catalogs = manager
|
||||
.list_marketplaces_for_config(config, &[], /*include_openai_curated*/ true)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
catalogs
|
||||
.marketplaces
|
||||
.iter()
|
||||
.map(|catalog| catalog.name.as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
if permitted { vec![name] } else { Vec::new() }
|
||||
);
|
||||
assert_eq!(
|
||||
manager
|
||||
.install_plugin(
|
||||
&config.config_layer_stack,
|
||||
PluginInstallRequest {
|
||||
plugin_name: "sample".to_string(),
|
||||
marketplace_path: AbsolutePathBuf::try_from(manifest.clone()).unwrap(),
|
||||
}
|
||||
)
|
||||
.await
|
||||
.is_ok(),
|
||||
permitted
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
//! Verifies managed curated Git restrictions through plugin and skill loading.
|
||||
|
||||
use std::fs;
|
||||
|
||||
use crate::PluginsConfigInput;
|
||||
use crate::PluginsManager;
|
||||
use crate::test_support::test_skill_root_loader;
|
||||
use anyhow::Result;
|
||||
use akode_config::LoaderOverrides;
|
||||
use akode_config::NoopThreadConfigLoader;
|
||||
use akode_config::loader::load_config_layers_state;
|
||||
use akode_exec_server::LOCAL_FS;
|
||||
use akode_login::CodexAuth;
|
||||
use akode_login::test_support::auth_manager_from_optional_auth;
|
||||
use akode_protocol::protocol::Product;
|
||||
use akode_protocol::protocol::SkillScope;
|
||||
use akode_skills::LoadedSkills;
|
||||
use akode_skills::SkillMetadata;
|
||||
use akode_skills::SkillRootLoadRequest;
|
||||
use akode_utils_absolute_path::AbsolutePathBuf;
|
||||
use akode_utils_path_uri::PathUri;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
|
||||
#[tokio::test]
|
||||
async fn curated_git_requirements_control_plugin_skills() -> Result<()> {
|
||||
// The ChatGPT curated catalog required ChatGPT auth; the API catalog is the only curated one.
|
||||
for (name, allow_curated) in [
|
||||
("openai-api-curated", true),
|
||||
("openai-api-curated", false),
|
||||
("openai-bundled", false),
|
||||
] {
|
||||
let home = TempDir::new()?;
|
||||
let plugin_id = format!("sample@{name}");
|
||||
let root = home
|
||||
.path()
|
||||
.join(format!("plugins/cache/{name}/sample/local"));
|
||||
fs::create_dir_all(root.join(".codex-plugin"))?;
|
||||
fs::write(
|
||||
root.join(".codex-plugin/plugin.json"),
|
||||
r#"{"name":"sample","description":"inspect sample data"}"#,
|
||||
)?;
|
||||
let skill_dir = root.join("skills/sample-search");
|
||||
fs::create_dir_all(&skill_dir)?;
|
||||
let skill_path = skill_dir.join("SKILL.md");
|
||||
fs::write(
|
||||
&skill_path,
|
||||
"---\ndescription: inspect sample data\n---\n\n# body\n",
|
||||
)?;
|
||||
let mut user_config = format!("[plugins.\"{plugin_id}\"]\nenabled = true\n");
|
||||
if name == "openai-bundled" {
|
||||
let bundled = home.path().join(".tmp/bundled-marketplaces/openai-bundled");
|
||||
user_config.push_str(&format!(
|
||||
"\n[marketplaces.openai-bundled]\nsource_type = \"local\"\nsource = {bundled:?}\n"
|
||||
));
|
||||
}
|
||||
fs::write(home.path().join("config.toml"), user_config)?;
|
||||
let requirements_path = home.path().join("requirements.toml");
|
||||
let rule = if allow_curated {
|
||||
"[marketplaces.allowed_sources.curated]\nsource = 'git'\nurl = 'https://github.com/openai/plugins.git'\n"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
fs::write(
|
||||
&requirements_path,
|
||||
format!("[marketplaces]\nrestrict_to_allowed_sources = true\n{rule}"),
|
||||
)?;
|
||||
let home_path = AbsolutePathBuf::try_from(home.path())?;
|
||||
let config_layer_stack = load_config_layers_state(
|
||||
LOCAL_FS.as_ref(),
|
||||
home.path(),
|
||||
Some(home_path),
|
||||
&[],
|
||||
LoaderOverrides {
|
||||
system_requirements_path: Some(requirements_path),
|
||||
..LoaderOverrides::without_managed_config_for_tests()
|
||||
},
|
||||
&NoopThreadConfigLoader,
|
||||
)
|
||||
.await?;
|
||||
let config = PluginsConfigInput::new(
|
||||
config_layer_stack.clone(),
|
||||
config_layer_stack
|
||||
.effective_config()
|
||||
.try_into::<akode_config::config_toml::ConfigToml>()
|
||||
.unwrap()
|
||||
.plugins,
|
||||
"openai".to_string(),
|
||||
/*plugins_enabled*/ true,
|
||||
);
|
||||
let auth = CodexAuth::from_api_key("test-api-key");
|
||||
let skills = test_skill_root_loader();
|
||||
let manager = PluginsManager::new(
|
||||
home.path().to_path_buf(),
|
||||
auth_manager_from_optional_auth(Some(auth)),
|
||||
skills.clone(),
|
||||
);
|
||||
let plugins = manager.plugins_for_config(&config).await;
|
||||
let loaded = skills
|
||||
.load_roots(SkillRootLoadRequest {
|
||||
roots: plugins.effective_plugin_skill_roots(),
|
||||
restriction_product: Some(Product::Codex),
|
||||
snapshots: manager.plugin_skill_snapshots_for_config(&config),
|
||||
})
|
||||
.await;
|
||||
let expected = if allow_curated || name == "openai-bundled" {
|
||||
LoadedSkills {
|
||||
skills: vec![SkillMetadata {
|
||||
name: "sample:sample-search".to_string(),
|
||||
description: "inspect sample data".to_string(),
|
||||
short_description: None,
|
||||
interface: None,
|
||||
dependencies: None,
|
||||
policy: None,
|
||||
path_to_skills_md: PathUri::from_abs_path(&AbsolutePathBuf::try_from(
|
||||
fs::canonicalize(skill_path)?,
|
||||
)?),
|
||||
scope: SkillScope::User,
|
||||
plugin_id: Some(plugin_id),
|
||||
}],
|
||||
errors: Vec::new(),
|
||||
}
|
||||
} else {
|
||||
LoadedSkills::default()
|
||||
};
|
||||
assert_eq!(
|
||||
loaded, expected,
|
||||
"marketplace={name}, allow_curated={allow_curated}"
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
108
akode-rs/core-plugins/src/marketplace_policy/curated_tests.rs
Normal file
108
akode-rs/core-plugins/src/marketplace_policy/curated_tests.rs
Normal file
@@ -0,0 +1,108 @@
|
||||
//! Checks the shared curated Git identity while preserving other managed marketplace exemptions.
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn curated_catalogs_apply_the_existing_git_source_policy() {
|
||||
let home = TempDir::new().unwrap();
|
||||
for (rule, allowed) in [
|
||||
("", false),
|
||||
(
|
||||
"source = 'git'\nurl = 'https://github.com/openai/plugins.git'",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"source = 'git'\nurl = 'https://github.com/openai/plugins'",
|
||||
true,
|
||||
),
|
||||
("source = 'git'\nurl = 'openai/plugins'", true),
|
||||
(
|
||||
"source = 'git'\nurl = 'https://github.com/other/plugins.git'",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"source = 'host_pattern'\nhost_pattern = '^github[.]com$'",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"source = 'host_pattern'\nhost_pattern = '^git[.]example[.]com$'",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"source = 'git'\nurl = 'https://github.com/openai/plugins.git'\nref = 'main'",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"source = 'git'\nurl = 'openai/plugins'\n[marketplaces.allowed_sources.invalid]\nsource = 'host_pattern'\nhost_pattern = '('",
|
||||
false,
|
||||
),
|
||||
] {
|
||||
let rule = if rule.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!("[marketplaces.allowed_sources.curated]\n{rule}")
|
||||
};
|
||||
let stack = config_layer_stack(&format!(
|
||||
"[marketplaces]\nrestrict_to_allowed_sources = true\n{rule}"
|
||||
));
|
||||
let policy = MarketplacePolicy::from_requirements(stack.requirements());
|
||||
for (name, manifest) in [
|
||||
(
|
||||
OPENAI_CURATED_MARKETPLACE_NAME,
|
||||
curated_plugins_repo_path(home.path()).join(".agents/plugins/marketplace.json"),
|
||||
),
|
||||
(
|
||||
OPENAI_API_CURATED_MARKETPLACE_NAME,
|
||||
curated_plugins_api_marketplace_path(home.path()),
|
||||
),
|
||||
] {
|
||||
let manifest = AbsolutePathBuf::try_from(manifest).unwrap();
|
||||
assert_eq!(
|
||||
policy
|
||||
.validate_install(&stack, home.path(), &manifest, name)
|
||||
.is_ok(),
|
||||
allowed
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_local_allowlist_cannot_authorize_curated_but_other_managed_sources_remain_allowed() {
|
||||
let home = TempDir::new().unwrap();
|
||||
let root = curated_plugins_repo_path(home.path());
|
||||
let stack = config_layer_stack(&format!(
|
||||
"[marketplaces]\nrestrict_to_allowed_sources = true\n[marketplaces.allowed_sources.local]\nsource = 'local'\npath = {root:?}"
|
||||
));
|
||||
let policy = MarketplacePolicy::from_requirements(stack.requirements());
|
||||
assert!(
|
||||
policy
|
||||
.validate_git_source(OPENAI_PLUGINS_GIT_URL, /*ref_name*/ None)
|
||||
.is_err()
|
||||
);
|
||||
// Windows test sandboxes may omit USERPROFILE, leaving no primary runtime cache root.
|
||||
let primary_runtime = primary_runtime_marketplace_root()
|
||||
.map(|root| (OPENAI_PRIMARY_RUNTIME_MARKETPLACE_NAME, root));
|
||||
for (name, root) in [
|
||||
(
|
||||
OPENAI_BUNDLED_MARKETPLACE_NAME,
|
||||
home.path().join(".tmp/bundled-marketplaces/openai-bundled"),
|
||||
),
|
||||
(
|
||||
OPENAI_BUNDLED_ALPHA_MARKETPLACE_NAME,
|
||||
home.path()
|
||||
.join(".tmp/bundled-marketplaces/openai-bundled-alpha"),
|
||||
),
|
||||
]
|
||||
.into_iter()
|
||||
.chain(primary_runtime)
|
||||
{
|
||||
let manifest =
|
||||
AbsolutePathBuf::try_from(root.join(".agents/plugins/marketplace.json")).unwrap();
|
||||
assert_eq!(
|
||||
policy.validate_install(&stack, home.path(), &manifest, name),
|
||||
Ok(())
|
||||
);
|
||||
}
|
||||
}
|
||||
850
akode-rs/core-plugins/src/marketplace_policy_tests.rs
Normal file
850
akode-rs/core-plugins/src/marketplace_policy_tests.rs
Normal file
@@ -0,0 +1,850 @@
|
||||
use super::*;
|
||||
use crate::marketplace_upgrade::upgrade_configured_git_marketplaces;
|
||||
use akode_config::ConfigLayerEntry;
|
||||
use akode_config::ConfigLayerSource;
|
||||
use akode_config::RequirementSource;
|
||||
use akode_config::RequirementsLayerEntry;
|
||||
use akode_config::compose_requirements;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::fs;
|
||||
#[cfg(target_os = "windows")]
|
||||
use std::path::PathBuf;
|
||||
use tempfile::TempDir;
|
||||
|
||||
#[path = "marketplace_policy/curated_tests.rs"]
|
||||
mod curated;
|
||||
|
||||
fn config_layer_stack(requirements_toml: &str) -> ConfigLayerStack {
|
||||
config_layer_stack_with_user_config(requirements_toml, /*user_config*/ None)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
#[test]
|
||||
fn primary_runtime_cache_uses_user_profile_on_windows() {
|
||||
assert_eq!(
|
||||
primary_runtime_cache_dir_from_user_profile(Some(PathBuf::from(r"C:\Users\user"))),
|
||||
Some(PathBuf::from(r"C:\Users\user\.cache"))
|
||||
);
|
||||
assert!(is_expected_managed_path(
|
||||
Path::new(r"\\?\c:\users\USER\.cache"),
|
||||
Path::new(r"C:\Users/user\.cache"),
|
||||
));
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn managed_windows_root_accepts_redirected_target_but_not_unowned_alias() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let target = temp.path().join("redirected-cache");
|
||||
let owned = temp.path().join(".cache");
|
||||
let alias = temp.path().join("unowned-alias");
|
||||
let other = temp.path().join("different-source");
|
||||
fs::create_dir_all(&target).unwrap();
|
||||
fs::create_dir_all(&other).unwrap();
|
||||
crate::test_support::create_directory_junction(&target, &owned);
|
||||
crate::test_support::create_directory_junction(&target, &alias);
|
||||
let canonical = owned.canonicalize().unwrap();
|
||||
assert!(is_expected_managed_path(&canonical, &owned));
|
||||
assert!(is_expected_managed_path(&owned, &owned));
|
||||
assert!(!is_expected_managed_path(&alias, &owned));
|
||||
assert!(!is_expected_managed_path(&other, &owned));
|
||||
}
|
||||
|
||||
fn config_layer_stack_with_user_config(
|
||||
requirements_toml: &str,
|
||||
user_config: Option<(&str, AbsolutePathBuf)>,
|
||||
) -> ConfigLayerStack {
|
||||
let with_sources = compose_requirements([RequirementsLayerEntry::from_toml(
|
||||
RequirementSource::Unknown,
|
||||
requirements_toml,
|
||||
)])
|
||||
.expect("compose requirements")
|
||||
.expect("requirements should be present");
|
||||
let requirements_toml = with_sources.clone().into_toml();
|
||||
let requirements =
|
||||
akode_config::ConfigRequirements::try_from(with_sources).expect("normalize requirements");
|
||||
let layers = user_config
|
||||
.map(|(contents, file)| {
|
||||
vec![ConfigLayerEntry::new(
|
||||
ConfigLayerSource::User {
|
||||
file,
|
||||
profile: None,
|
||||
},
|
||||
toml::from_str(contents).expect("parse user config"),
|
||||
)]
|
||||
})
|
||||
.unwrap_or_default();
|
||||
ConfigLayerStack::new(layers, requirements, requirements_toml)
|
||||
.expect("build config layer stack")
|
||||
}
|
||||
|
||||
fn parse_source(source: &str, ref_name: Option<&str>) -> MarketplaceSource {
|
||||
parse_marketplace_source(source, ref_name.map(str::to_string)).expect("parse source")
|
||||
}
|
||||
|
||||
fn validate_source(stack: &ConfigLayerStack, source: &MarketplaceSource) -> Result<(), String> {
|
||||
MarketplacePolicy::from_requirements(stack.requirements()).validate_source(source)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exact_git_rule_matches_url_and_ref() {
|
||||
let stack = config_layer_stack(
|
||||
r#"
|
||||
[marketplaces]
|
||||
restrict_to_allowed_sources = true
|
||||
|
||||
[marketplaces.allowed_sources.company]
|
||||
source = "git"
|
||||
url = "https://github.com/example/plugins"
|
||||
ref = "main"
|
||||
"#,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
validate_source(
|
||||
&stack,
|
||||
&parse_source("https://github.com/example/plugins.git", Some("main")),
|
||||
),
|
||||
Ok(())
|
||||
);
|
||||
for denied in [
|
||||
parse_source("https://github.com/example/plugins.git", Some("release")),
|
||||
parse_source("https://github.com/other/plugins.git", Some("main")),
|
||||
] {
|
||||
assert!(validate_source(&stack, &denied).is_err());
|
||||
}
|
||||
let normalized = MarketplacePolicy::from_requirements(stack.requirements())
|
||||
.validate_git_source("example/plugins", Some("main".to_string()))
|
||||
.expect("allowlisted shorthand should validate")
|
||||
.expect("restricted policy should normalize the source");
|
||||
assert_eq!(
|
||||
normalized,
|
||||
MarketplaceSource::Git {
|
||||
url: "https://github.com/example/plugins.git".to_string(),
|
||||
ref_name: Some("main".to_string()),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn git_rule_without_ref_allows_any_ref_for_the_same_repository() {
|
||||
let stack = config_layer_stack(
|
||||
r#"
|
||||
[marketplaces]
|
||||
restrict_to_allowed_sources = true
|
||||
|
||||
[marketplaces.allowed_sources.company]
|
||||
source = "git"
|
||||
url = "https://github.com/example/plugins"
|
||||
"#,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
validate_source(
|
||||
&stack,
|
||||
&parse_source("https://github.com/example/plugins.git", Some("release")),
|
||||
),
|
||||
Ok(())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn git_host_pattern_matches_https_and_ssh_sources() {
|
||||
let stack = config_layer_stack(
|
||||
r#"
|
||||
[marketplaces]
|
||||
restrict_to_allowed_sources = true
|
||||
|
||||
[marketplaces.allowed_sources.internal]
|
||||
source = "host_pattern"
|
||||
host_pattern = '^git\.example\.com$'
|
||||
url = "https://github.com/example/ignored.git"
|
||||
ref = "ignored"
|
||||
"#,
|
||||
);
|
||||
|
||||
for source in [
|
||||
"http://git.example.com/team/plugins.git",
|
||||
"https://git.example.com/team/plugins.git",
|
||||
"https://user@git.example.com:8443/team/plugins.git",
|
||||
"https://user%5Cname@git.example.com/team/plugins.git",
|
||||
r"http://git.example.com/team\plugins.git",
|
||||
r"https://git.example.com/team\@plugins.git",
|
||||
r"https://git.example.com?repository=team\@plugins.git",
|
||||
"ssh://git@git.example.com/team/plugins.git",
|
||||
"git@git.example.com:team/plugins.git",
|
||||
] {
|
||||
assert_eq!(
|
||||
validate_source(&stack, &parse_source(source, /*ref_name*/ None)),
|
||||
Ok(())
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
validate_source(
|
||||
&stack,
|
||||
&parse_source(
|
||||
"https://github.com/example/plugins.git",
|
||||
/*ref_name*/ None,
|
||||
),
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exact_local_rule_rejects_other_directories() {
|
||||
let allowed = TempDir::new().expect("create allowed marketplace directory");
|
||||
let denied = TempDir::new().expect("create denied marketplace directory");
|
||||
let allowed = allowed
|
||||
.path()
|
||||
.canonicalize()
|
||||
.expect("canonical allowed path");
|
||||
let denied = denied.path().canonicalize().expect("canonical denied path");
|
||||
let stack = config_layer_stack(&format!(
|
||||
r#"
|
||||
[marketplaces]
|
||||
restrict_to_allowed_sources = true
|
||||
|
||||
[marketplaces.allowed_sources.local]
|
||||
source = "local"
|
||||
path = {allowed:?}
|
||||
"#
|
||||
));
|
||||
|
||||
assert_eq!(
|
||||
validate_source(
|
||||
&stack,
|
||||
&parse_source(allowed.to_string_lossy().as_ref(), /*ref_name*/ None),
|
||||
),
|
||||
Ok(())
|
||||
);
|
||||
assert!(
|
||||
validate_source(
|
||||
&stack,
|
||||
&parse_source(denied.to_string_lossy().as_ref(), /*ref_name*/ None),
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restriction_flag_controls_empty_allowlist() {
|
||||
for (restricted, expected_allowed) in [(true, false), (false, true)] {
|
||||
let stack = config_layer_stack(&format!(
|
||||
r#"
|
||||
[marketplaces]
|
||||
restrict_to_allowed_sources = {restricted}
|
||||
"#
|
||||
));
|
||||
let result = validate_source(
|
||||
&stack,
|
||||
&parse_source(
|
||||
"https://github.com/example/plugins.git",
|
||||
/*ref_name*/ None,
|
||||
),
|
||||
);
|
||||
assert_eq!(result.is_ok(), expected_allowed);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn system_marketplace_discovery_and_install_validate_source_and_root() {
|
||||
let codex_home = TempDir::new().expect("create Codex home");
|
||||
let configured_root = TempDir::new().expect("create configured marketplace");
|
||||
let other_root = TempDir::new().expect("create other marketplace");
|
||||
let configured_root = configured_root
|
||||
.path()
|
||||
.canonicalize()
|
||||
.expect("canonical configured root");
|
||||
let other_root = other_root
|
||||
.path()
|
||||
.canonicalize()
|
||||
.expect("canonical other root");
|
||||
let config_file = AbsolutePathBuf::try_from(codex_home.path().join("config.toml"))
|
||||
.expect("absolute config path");
|
||||
let stack = config_layer_stack_with_user_config(
|
||||
&format!(
|
||||
r#"
|
||||
[marketplaces]
|
||||
restrict_to_allowed_sources = true
|
||||
|
||||
[marketplaces.allowed_sources.company]
|
||||
source = "local"
|
||||
path = {configured_root:?}
|
||||
"#
|
||||
),
|
||||
Some((
|
||||
&format!(
|
||||
r#"
|
||||
[marketplaces.company]
|
||||
source_type = "local"
|
||||
source = {configured_root:?}
|
||||
"#
|
||||
),
|
||||
config_file,
|
||||
)),
|
||||
);
|
||||
let layer = stack.layers_low_to_high().next().expect("configured layer");
|
||||
let stack = ConfigLayerStack::new(
|
||||
vec![ConfigLayerEntry::new(
|
||||
ConfigLayerSource::System {
|
||||
file: AbsolutePathBuf::try_from(codex_home.path().join("system.toml")).unwrap(),
|
||||
},
|
||||
layer.config.clone(),
|
||||
)],
|
||||
stack.requirements().clone(),
|
||||
stack.requirements_toml().clone(),
|
||||
)
|
||||
.expect("system config stack");
|
||||
let policy = MarketplacePolicy::from_requirements(stack.requirements());
|
||||
let configured_path =
|
||||
AbsolutePathBuf::try_from(configured_root.join(".agents/plugins/marketplace.json"))
|
||||
.expect("configured marketplace path");
|
||||
let other_path = AbsolutePathBuf::try_from(other_root.join(".agents/plugins/marketplace.json"))
|
||||
.expect("other marketplace path");
|
||||
|
||||
fs::create_dir_all(configured_path.as_path().parent().unwrap()).unwrap();
|
||||
fs::write(&configured_path, r#"{"name":"company","plugins":[]}"#).unwrap();
|
||||
assert_eq!(
|
||||
crate::installed_marketplaces::installed_marketplace_roots_from_layer_stack(
|
||||
&stack,
|
||||
codex_home.path()
|
||||
),
|
||||
vec![AbsolutePathBuf::try_from(configured_root).unwrap()],
|
||||
);
|
||||
assert_eq!(
|
||||
policy.validate_install(&stack, codex_home.path(), &configured_path, "company"),
|
||||
Ok(())
|
||||
);
|
||||
assert!(
|
||||
policy
|
||||
.validate_install(&stack, codex_home.path(), &configured_path, "other")
|
||||
.expect_err("unconfigured name should fail")
|
||||
.contains("must be added to config")
|
||||
);
|
||||
assert!(
|
||||
policy
|
||||
.validate_install(&stack, codex_home.path(), &other_path, "company")
|
||||
.expect_err("mismatched root should fail")
|
||||
.contains("does not match configured marketplace")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blocked_configured_source_is_not_installable() {
|
||||
let codex_home = TempDir::new().expect("create Codex home");
|
||||
let config_file = AbsolutePathBuf::try_from(codex_home.path().join("config.toml"))
|
||||
.expect("absolute config path");
|
||||
let stack = config_layer_stack_with_user_config(
|
||||
r#"
|
||||
[marketplaces]
|
||||
restrict_to_allowed_sources = true
|
||||
|
||||
[marketplaces.allowed_sources.company]
|
||||
source = "git"
|
||||
url = "https://github.com/example/allowed.git"
|
||||
"#,
|
||||
Some((
|
||||
r#"
|
||||
[marketplaces.debug]
|
||||
source_type = "git"
|
||||
source = "https://github.com/example/blocked.git"
|
||||
"#,
|
||||
config_file,
|
||||
)),
|
||||
);
|
||||
let marketplace_path = AbsolutePathBuf::try_from(
|
||||
marketplace_install_root(codex_home.path()).join("debug/.agents/plugins/marketplace.json"),
|
||||
)
|
||||
.expect("absolute marketplace path");
|
||||
|
||||
let err = MarketplacePolicy::from_requirements(stack.requirements())
|
||||
.validate_install(&stack, codex_home.path(), &marketplace_path, "debug")
|
||||
.expect_err("blocked marketplace install should fail");
|
||||
assert!(err.contains("is not allowed by requirements"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bare_relative_local_config_source_is_not_parsed_as_git_shorthand() {
|
||||
let marketplace: toml::Value = toml::from_str(
|
||||
r#"
|
||||
source_type = "local"
|
||||
source = "marketplaces/company"
|
||||
"#,
|
||||
)
|
||||
.expect("parse marketplace config");
|
||||
|
||||
assert_eq!(
|
||||
configured_marketplace_source("company", &marketplace),
|
||||
Ok(MarketplaceSource::Local {
|
||||
path: PathBuf::from("marketplaces/company"),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curated_marketplace_requires_its_expected_name() {
|
||||
let codex_home = TempDir::new().expect("create Codex home");
|
||||
let stack = config_layer_stack(
|
||||
r#"
|
||||
[marketplaces]
|
||||
restrict_to_allowed_sources = true
|
||||
[marketplaces.allowed_sources.curated]
|
||||
source = "git"
|
||||
url = "https://github.com/openai/plugins.git"
|
||||
"#,
|
||||
);
|
||||
let marketplace_path = AbsolutePathBuf::try_from(
|
||||
curated_plugins_repo_path(codex_home.path()).join(".agents/plugins/marketplace.json"),
|
||||
)
|
||||
.expect("absolute marketplace path");
|
||||
let policy = MarketplacePolicy::from_requirements(stack.requirements());
|
||||
|
||||
assert_eq!(
|
||||
policy.validate_install(
|
||||
&stack,
|
||||
codex_home.path(),
|
||||
&marketplace_path,
|
||||
crate::OPENAI_CURATED_MARKETPLACE_NAME,
|
||||
),
|
||||
Ok(())
|
||||
);
|
||||
assert!(
|
||||
policy
|
||||
.validate_install(
|
||||
&stack,
|
||||
codex_home.path(),
|
||||
&marketplace_path,
|
||||
crate::OPENAI_API_CURATED_MARKETPLACE_NAME,
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
|
||||
let repository_manifest = AbsolutePathBuf::try_from(
|
||||
codex_home
|
||||
.path()
|
||||
.join("repository/.agents/plugins/marketplace.json"),
|
||||
)
|
||||
.expect("absolute repository manifest");
|
||||
let unrestricted = ConfigLayerStack::default();
|
||||
for config in [&stack, &unrestricted] {
|
||||
for marketplace in [
|
||||
OPENAI_CURATED_MARKETPLACE_NAME,
|
||||
OPENAI_API_CURATED_MARKETPLACE_NAME,
|
||||
OPENAI_BUNDLED_MARKETPLACE_NAME,
|
||||
OPENAI_BUNDLED_ALPHA_MARKETPLACE_NAME,
|
||||
OPENAI_PRIMARY_RUNTIME_MARKETPLACE_NAME,
|
||||
]
|
||||
.into_iter()
|
||||
.chain(super::LEGACY_REMOTE_MARKETPLACE_NAMES)
|
||||
{
|
||||
assert!(
|
||||
MarketplacePolicy::from_requirements(config.requirements())
|
||||
.validate_install(config, codex_home.path(), &repository_manifest, marketplace)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn symlinked_marketplaces_cannot_borrow_managed_provenance() {
|
||||
let codex_home = TempDir::new().expect("create Codex home");
|
||||
let official_root = curated_plugins_repo_path(codex_home.path());
|
||||
let manifest = official_root.join(".agents/plugins/marketplace.json");
|
||||
fs::create_dir_all(manifest.parent().expect("manifest directory"))
|
||||
.expect("create manifest directory");
|
||||
fs::write(&manifest, "{}").expect("write official manifest");
|
||||
|
||||
let root_alias = codex_home.path().join("repository");
|
||||
std::os::unix::fs::symlink(&official_root, &root_alias).expect("symlink official root");
|
||||
let parent_alias = codex_home.path().join("parent-alias");
|
||||
std::os::unix::fs::symlink(
|
||||
official_root.parent().expect("official root parent"),
|
||||
&parent_alias,
|
||||
)
|
||||
.expect("symlink official root parent");
|
||||
let manifest_alias = codex_home
|
||||
.path()
|
||||
.join("manifest-alias/.agents/plugins/api_marketplace.json");
|
||||
fs::create_dir_all(manifest_alias.parent().expect("manifest alias parent"))
|
||||
.expect("create manifest alias directory");
|
||||
std::os::unix::fs::symlink(&manifest, &manifest_alias).expect("symlink official manifest");
|
||||
let stack = ConfigLayerStack::default();
|
||||
|
||||
for (path, marketplace) in [
|
||||
(
|
||||
root_alias.join(".agents/plugins/marketplace.json"),
|
||||
OPENAI_CURATED_MARKETPLACE_NAME,
|
||||
),
|
||||
(
|
||||
parent_alias.join("plugins/.agents/plugins/marketplace.json"),
|
||||
OPENAI_CURATED_MARKETPLACE_NAME,
|
||||
),
|
||||
(manifest_alias, OPENAI_API_CURATED_MARKETPLACE_NAME),
|
||||
] {
|
||||
let manifest = AbsolutePathBuf::try_from(path).expect("absolute repository manifest");
|
||||
assert!(
|
||||
MarketplacePolicy::from_requirements(stack.requirements())
|
||||
.validate_install(&stack, codex_home.path(), &manifest, marketplace)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn managed_bundled_source_is_bound_to_its_expected_name() {
|
||||
let codex_home = TempDir::new().expect("create Codex home");
|
||||
let bundled_root = codex_home
|
||||
.path()
|
||||
.join(".tmp/bundled-marketplaces")
|
||||
.join(crate::OPENAI_BUNDLED_MARKETPLACE_NAME);
|
||||
fs::create_dir_all(&bundled_root).expect("create bundled marketplace root");
|
||||
let stack = config_layer_stack(
|
||||
r#"
|
||||
[marketplaces]
|
||||
restrict_to_allowed_sources = true
|
||||
"#,
|
||||
);
|
||||
let source = parse_source(
|
||||
bundled_root.to_string_lossy().as_ref(),
|
||||
/*ref_name*/ None,
|
||||
);
|
||||
|
||||
let expected_name =
|
||||
validate_marketplace_source_for_add(codex_home.path(), stack.requirements(), &source)
|
||||
.expect("managed marketplace source should bypass restrictions");
|
||||
assert_eq!(
|
||||
validate_marketplace_name_for_add(expected_name, crate::OPENAI_BUNDLED_MARKETPLACE_NAME,),
|
||||
Ok(())
|
||||
);
|
||||
assert!(validate_marketplace_name_for_add(expected_name, "other").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn projected_user_config_removes_blocked_marketplaces_and_plugins() {
|
||||
let codex_home = TempDir::new().expect("create Codex home");
|
||||
let config_file = AbsolutePathBuf::try_from(codex_home.path().join("config.toml"))
|
||||
.expect("absolute config path");
|
||||
let stack = config_layer_stack_with_user_config(
|
||||
r#"
|
||||
[marketplaces]
|
||||
restrict_to_allowed_sources = true
|
||||
|
||||
[marketplaces.allowed_sources.company]
|
||||
source = "git"
|
||||
url = "https://github.com/example/allowed.git"
|
||||
"#,
|
||||
Some((
|
||||
r#"
|
||||
[marketplaces.allowed]
|
||||
source_type = "git"
|
||||
source = "https://github.com/example/allowed.git"
|
||||
|
||||
[marketplaces.blocked]
|
||||
source_type = "git"
|
||||
source = "https://github.com/example/blocked.git"
|
||||
|
||||
[plugins."sample@allowed"]
|
||||
enabled = true
|
||||
|
||||
[plugins."sample@blocked"]
|
||||
enabled = true
|
||||
"#,
|
||||
config_file,
|
||||
)),
|
||||
);
|
||||
|
||||
let projected =
|
||||
policy_filtered_plugin_config(&stack, codex_home.path()).expect("project plugin config");
|
||||
assert_eq!(
|
||||
projected["marketplaces"]
|
||||
.as_table()
|
||||
.expect("projected marketplaces")
|
||||
.keys()
|
||||
.cloned()
|
||||
.collect::<Vec<_>>(),
|
||||
vec!["allowed".to_string()]
|
||||
);
|
||||
assert_eq!(
|
||||
configured_plugins_from_stack(&stack, codex_home.path())
|
||||
.into_keys()
|
||||
.collect::<Vec<_>>(),
|
||||
vec!["sample@allowed".to_string()]
|
||||
);
|
||||
|
||||
let raw = stack.effective_user_config().expect("raw user config");
|
||||
assert!(raw["marketplaces"]["blocked"].is_table());
|
||||
assert!(raw["plugins"]["sample@blocked"].is_table());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn managed_bundled_config_is_retained_only_at_its_owned_path() {
|
||||
let codex_home = TempDir::new().expect("create Codex home");
|
||||
let bundled_root = codex_home
|
||||
.path()
|
||||
.join(".tmp/bundled-marketplaces")
|
||||
.join(crate::OPENAI_BUNDLED_MARKETPLACE_NAME);
|
||||
let config_file = AbsolutePathBuf::try_from(codex_home.path().join("config.toml"))
|
||||
.expect("absolute config path");
|
||||
let stack = config_layer_stack_with_user_config(
|
||||
r#"
|
||||
[marketplaces]
|
||||
restrict_to_allowed_sources = true
|
||||
"#,
|
||||
Some((
|
||||
&format!(
|
||||
r#"
|
||||
[marketplaces.openai-bundled]
|
||||
source_type = "local"
|
||||
source = {bundled_root:?}
|
||||
|
||||
[marketplaces.openai-bundled-alpha]
|
||||
source_type = "local"
|
||||
source = "/tmp/not-managed"
|
||||
|
||||
[marketplaces.evil]
|
||||
source_type = "local"
|
||||
source = {bundled_root:?}
|
||||
|
||||
[plugins."sample@openai-bundled"]
|
||||
enabled = true
|
||||
|
||||
[plugins."sample@openai-bundled-alpha"]
|
||||
enabled = true
|
||||
|
||||
[plugins."sample@evil"]
|
||||
enabled = true
|
||||
"#
|
||||
),
|
||||
config_file,
|
||||
)),
|
||||
);
|
||||
|
||||
let projected =
|
||||
policy_filtered_plugin_config(&stack, codex_home.path()).expect("project plugin config");
|
||||
|
||||
assert_eq!(
|
||||
projected["marketplaces"]
|
||||
.as_table()
|
||||
.expect("projected marketplaces")
|
||||
.keys()
|
||||
.cloned()
|
||||
.collect::<Vec<_>>(),
|
||||
vec![crate::OPENAI_BUNDLED_MARKETPLACE_NAME.to_string()]
|
||||
);
|
||||
assert_eq!(
|
||||
projected["plugins"]
|
||||
.as_table()
|
||||
.expect("projected plugins")
|
||||
.keys()
|
||||
.cloned()
|
||||
.collect::<Vec<_>>(),
|
||||
vec![format!("sample@{}", crate::OPENAI_BUNDLED_MARKETPLACE_NAME)]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn allowlisted_sources_cannot_claim_reserved_marketplace_names() {
|
||||
let codex_home = TempDir::new().expect("create Codex home");
|
||||
let source_root = TempDir::new().expect("create marketplace root");
|
||||
let source_root = source_root
|
||||
.path()
|
||||
.canonicalize()
|
||||
.expect("canonical marketplace root");
|
||||
let config_file = AbsolutePathBuf::try_from(codex_home.path().join("config.toml"))
|
||||
.expect("absolute config path");
|
||||
let stack = config_layer_stack_with_user_config(
|
||||
&format!(
|
||||
r#"
|
||||
[marketplaces]
|
||||
restrict_to_allowed_sources = true
|
||||
|
||||
[marketplaces.allowed_sources.local]
|
||||
source = "local"
|
||||
path = {source_root:?}
|
||||
"#
|
||||
),
|
||||
Some((
|
||||
&format!(
|
||||
r#"
|
||||
[marketplaces.openai-bundled]
|
||||
source_type = "local"
|
||||
source = {source_root:?}
|
||||
|
||||
[marketplaces.openai-curated]
|
||||
source_type = "local"
|
||||
source = {source_root:?}
|
||||
|
||||
[plugins."sample@openai-bundled"]
|
||||
enabled = true
|
||||
|
||||
[plugins."sample@openai-curated"]
|
||||
enabled = true
|
||||
"#
|
||||
),
|
||||
config_file,
|
||||
)),
|
||||
);
|
||||
|
||||
let projected =
|
||||
policy_filtered_plugin_config(&stack, codex_home.path()).expect("project plugin config");
|
||||
assert_eq!(
|
||||
projected["marketplaces"]
|
||||
.as_table()
|
||||
.expect("projected marketplaces")
|
||||
.keys()
|
||||
.cloned()
|
||||
.collect::<Vec<_>>(),
|
||||
Vec::<String>::new()
|
||||
);
|
||||
assert_eq!(
|
||||
projected["plugins"]
|
||||
.as_table()
|
||||
.expect("projected plugins")
|
||||
.keys()
|
||||
.cloned()
|
||||
.collect::<Vec<_>>(),
|
||||
Vec::<String>::new()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blocked_or_reserved_upgrade_is_rejected_before_marketplace_installation() {
|
||||
let reload_config: crate::ConfigLayerReload =
|
||||
std::sync::Arc::new(|| panic!("blocked or reserved marketplace must not reload config"));
|
||||
let codex_home = TempDir::new().expect("create Codex home");
|
||||
let config_file = AbsolutePathBuf::try_from(codex_home.path().join("config.toml"))
|
||||
.expect("absolute config path");
|
||||
let stack = config_layer_stack_with_user_config(
|
||||
r#"
|
||||
[marketplaces]
|
||||
restrict_to_allowed_sources = true
|
||||
"#,
|
||||
Some((
|
||||
r#"
|
||||
[marketplaces.debug]
|
||||
source_type = "git"
|
||||
source = "https://github.com/example/blocked.git"
|
||||
"#,
|
||||
config_file.clone(),
|
||||
)),
|
||||
);
|
||||
|
||||
let outcome = upgrade_configured_git_marketplaces(
|
||||
codex_home.path(),
|
||||
&stack,
|
||||
Some("debug"),
|
||||
&reload_config,
|
||||
);
|
||||
|
||||
assert_eq!(outcome.selected_marketplaces, vec!["debug".to_string()]);
|
||||
assert_eq!(outcome.upgraded_roots, Vec::new());
|
||||
assert_eq!(outcome.errors.len(), 1);
|
||||
assert!(
|
||||
outcome.errors[0]
|
||||
.message
|
||||
.contains("is not allowed by requirements")
|
||||
);
|
||||
assert!(!marketplace_install_root(codex_home.path()).exists());
|
||||
|
||||
let stack = config_layer_stack_with_user_config(
|
||||
"[marketplaces]\nrestrict_to_allowed_sources = false\n",
|
||||
Some((
|
||||
"[marketplaces.openai-bundled]\nsource_type = \"git\"\nsource = \"https://github.com/example/blocked.git\"\n",
|
||||
config_file,
|
||||
)),
|
||||
);
|
||||
let outcome = upgrade_configured_git_marketplaces(
|
||||
codex_home.path(),
|
||||
&stack,
|
||||
Some(crate::OPENAI_BUNDLED_MARKETPLACE_NAME),
|
||||
&reload_config,
|
||||
);
|
||||
assert!(outcome.errors[0].message.contains("is reserved"));
|
||||
assert!(!marketplace_install_root(codex_home.path()).exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_active_rule_fails_closed_even_when_another_rule_matches() {
|
||||
let stack = config_layer_stack(
|
||||
r#"
|
||||
[marketplaces]
|
||||
restrict_to_allowed_sources = true
|
||||
|
||||
[marketplaces.allowed_sources.allowed]
|
||||
source = "git"
|
||||
url = "https://github.com/example/plugins.git"
|
||||
|
||||
[marketplaces.allowed_sources.invalid]
|
||||
source = "host_pattern"
|
||||
host_pattern = "("
|
||||
"#,
|
||||
);
|
||||
|
||||
let err = validate_source(
|
||||
&stack,
|
||||
&parse_source(
|
||||
"https://github.com/example/plugins.git",
|
||||
/*ref_name*/ None,
|
||||
),
|
||||
)
|
||||
.expect_err("invalid active rule should fail closed");
|
||||
assert!(err.contains("invalid marketplace allowed source `invalid`"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_allowed_source_shapes_fail_closed() {
|
||||
for (rule, expected_error) in [
|
||||
(
|
||||
r#"
|
||||
[marketplaces.allowed_sources.invalid]
|
||||
url = "https://github.com/example/plugins.git"
|
||||
"#,
|
||||
"missing source",
|
||||
),
|
||||
(
|
||||
r#"
|
||||
[marketplaces.allowed_sources.invalid]
|
||||
source = "git"
|
||||
"#,
|
||||
"missing url",
|
||||
),
|
||||
(
|
||||
r#"
|
||||
[marketplaces.allowed_sources.invalid]
|
||||
source = "git"
|
||||
url = "https://github.com/example/plugins.git"
|
||||
ref = " "
|
||||
"#,
|
||||
"ref must not be empty",
|
||||
),
|
||||
(
|
||||
r#"
|
||||
[marketplaces.allowed_sources.invalid]
|
||||
source = "local"
|
||||
path = "../plugins"
|
||||
"#,
|
||||
"local path must be absolute",
|
||||
),
|
||||
] {
|
||||
let stack = config_layer_stack(&format!(
|
||||
r#"
|
||||
[marketplaces]
|
||||
restrict_to_allowed_sources = true
|
||||
{rule}
|
||||
"#
|
||||
));
|
||||
|
||||
let err = validate_source(
|
||||
&stack,
|
||||
&parse_source(
|
||||
"https://github.com/example/plugins.git",
|
||||
/*ref_name*/ None,
|
||||
),
|
||||
)
|
||||
.expect_err("invalid rule should fail closed");
|
||||
assert!(err.contains(expected_error), "{err}");
|
||||
}
|
||||
}
|
||||
403
akode-rs/core-plugins/src/marketplace_remove.rs
Normal file
403
akode-rs/core-plugins/src/marketplace_remove.rs
Normal file
@@ -0,0 +1,403 @@
|
||||
use crate::installed_marketplaces::marketplace_install_root;
|
||||
use akode_config::CONFIG_TOML_FILE;
|
||||
use akode_config::ConfigLayerSource;
|
||||
use akode_config::ConfigLayerStack;
|
||||
use akode_config::RemoveMarketplaceConfigOutcome;
|
||||
use akode_config::format_config_layer_source;
|
||||
use akode_config::remove_user_marketplace_config;
|
||||
use akode_plugin::validate_plugin_segment;
|
||||
use akode_utils_absolute_path::AbsolutePathBuf;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct MarketplaceRemoveRequest {
|
||||
pub marketplace_name: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct MarketplaceRemoveOutcome {
|
||||
pub marketplace_name: String,
|
||||
pub removed_installed_root: Option<AbsolutePathBuf>,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum MarketplaceRemoveError {
|
||||
#[error("{0}")]
|
||||
InvalidRequest(String),
|
||||
#[error("{0}")]
|
||||
Internal(String),
|
||||
}
|
||||
|
||||
/// Removes a marketplace's snapshot and any base-user entry only when no other
|
||||
/// enabled layer in the current operation's config stack references its name.
|
||||
pub async fn remove_marketplace(
|
||||
codex_home: PathBuf,
|
||||
config_layer_stack: ConfigLayerStack,
|
||||
request: MarketplaceRemoveRequest,
|
||||
) -> Result<MarketplaceRemoveOutcome, MarketplaceRemoveError> {
|
||||
tokio::task::spawn_blocking(move || {
|
||||
remove_marketplace_sync(codex_home.as_path(), &config_layer_stack, request)
|
||||
})
|
||||
.await
|
||||
.map_err(|err| {
|
||||
MarketplaceRemoveError::Internal(format!("failed to remove marketplace: {err}"))
|
||||
})?
|
||||
}
|
||||
|
||||
fn remove_marketplace_sync(
|
||||
codex_home: &Path,
|
||||
config_layer_stack: &ConfigLayerStack,
|
||||
request: MarketplaceRemoveRequest,
|
||||
) -> Result<MarketplaceRemoveOutcome, MarketplaceRemoveError> {
|
||||
let marketplace_name = request.marketplace_name;
|
||||
validate_plugin_segment(&marketplace_name, "marketplace name")
|
||||
.map_err(MarketplaceRemoveError::InvalidRequest)?;
|
||||
|
||||
// Removing a user override must not delete a snapshot still referenced by
|
||||
// another enabled layer, including a lower-precedence layer it shadows.
|
||||
let user_config_file = AbsolutePathBuf::resolve_path_against_base(CONFIG_TOML_FILE, codex_home);
|
||||
if let Some(layer) = config_layer_stack.layers_high_to_low().find(|layer| {
|
||||
!matches!(
|
||||
&layer.name,
|
||||
ConfigLayerSource::User { file, profile: None } if file == &user_config_file
|
||||
) && layer
|
||||
.config
|
||||
.get("marketplaces")
|
||||
.and_then(toml::Value::as_table)
|
||||
.is_some_and(|marketplaces| {
|
||||
marketplaces
|
||||
.keys()
|
||||
.any(|name| name.eq_ignore_ascii_case(&marketplace_name))
|
||||
})
|
||||
}) {
|
||||
let source = format_config_layer_source(&layer.name, CONFIG_TOML_FILE);
|
||||
return Err(MarketplaceRemoveError::InvalidRequest(format!(
|
||||
"marketplace `{marketplace_name}` is configured in {source}; remove it from that configuration source instead"
|
||||
)));
|
||||
}
|
||||
|
||||
let destination = marketplace_install_root(codex_home).join(&marketplace_name);
|
||||
let config_outcome =
|
||||
remove_user_marketplace_config(codex_home, &marketplace_name).map_err(|err| {
|
||||
MarketplaceRemoveError::Internal(format!(
|
||||
"failed to remove marketplace '{marketplace_name}' from user config.toml: {err}"
|
||||
))
|
||||
})?;
|
||||
if let RemoveMarketplaceConfigOutcome::NameCaseMismatch { configured_name } = &config_outcome {
|
||||
return Err(MarketplaceRemoveError::InvalidRequest(format!(
|
||||
"marketplace `{marketplace_name}` does not match configured marketplace `{configured_name}` exactly"
|
||||
)));
|
||||
}
|
||||
|
||||
let removed_config = config_outcome == RemoveMarketplaceConfigOutcome::Removed;
|
||||
let removed_installed_root = remove_marketplace_root(&destination)?;
|
||||
|
||||
if removed_installed_root.is_none() && !removed_config {
|
||||
return Err(MarketplaceRemoveError::InvalidRequest(format!(
|
||||
"marketplace `{marketplace_name}` is not configured or installed"
|
||||
)));
|
||||
}
|
||||
|
||||
Ok(MarketplaceRemoveOutcome {
|
||||
marketplace_name,
|
||||
removed_installed_root,
|
||||
})
|
||||
}
|
||||
|
||||
fn remove_marketplace_root(root: &Path) -> Result<Option<AbsolutePathBuf>, MarketplaceRemoveError> {
|
||||
if !root.exists() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let removed_root = AbsolutePathBuf::try_from(root.to_path_buf()).map_err(|err| {
|
||||
MarketplaceRemoveError::Internal(format!(
|
||||
"failed to resolve installed marketplace root {}: {err}",
|
||||
root.display()
|
||||
))
|
||||
})?;
|
||||
let metadata = fs::symlink_metadata(root).map_err(|err| {
|
||||
MarketplaceRemoveError::Internal(format!(
|
||||
"failed to inspect installed marketplace root {}: {err}",
|
||||
root.display()
|
||||
))
|
||||
})?;
|
||||
let remove_result = if metadata.is_dir() {
|
||||
fs::remove_dir_all(root)
|
||||
} else {
|
||||
fs::remove_file(root)
|
||||
};
|
||||
remove_result.map_err(|err| {
|
||||
MarketplaceRemoveError::Internal(format!(
|
||||
"failed to remove installed marketplace root {}: {err}",
|
||||
root.display()
|
||||
))
|
||||
})?;
|
||||
Ok(Some(removed_root))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use akode_config::ConfigLayerEntry;
|
||||
use akode_config::MarketplaceConfigUpdate;
|
||||
use akode_config::record_user_marketplace;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
|
||||
#[test]
|
||||
fn remove_marketplace_sync_removes_config_and_installed_root() {
|
||||
let codex_home = TempDir::new().unwrap();
|
||||
record_user_marketplace(
|
||||
codex_home.path(),
|
||||
"debug",
|
||||
&MarketplaceConfigUpdate {
|
||||
source_type: "git",
|
||||
source: "https://github.com/owner/repo.git",
|
||||
ref_name: Some("main"),
|
||||
sparse_paths: &[],
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let installed_root = marketplace_install_root(codex_home.path()).join("debug");
|
||||
fs::create_dir_all(installed_root.join(".agents/plugins")).unwrap();
|
||||
fs::write(
|
||||
installed_root.join(".agents/plugins/marketplace.json"),
|
||||
"{}",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let outcome = remove_marketplace_sync(
|
||||
codex_home.path(),
|
||||
&ConfigLayerStack::default(),
|
||||
MarketplaceRemoveRequest {
|
||||
marketplace_name: "debug".to_string(),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(outcome.marketplace_name, "debug");
|
||||
assert_eq!(
|
||||
outcome.removed_installed_root,
|
||||
Some(AbsolutePathBuf::try_from(installed_root.clone()).unwrap())
|
||||
);
|
||||
let config =
|
||||
fs::read_to_string(codex_home.path().join(akode_config::CONFIG_TOML_FILE)).unwrap();
|
||||
assert!(!config.contains("[marketplaces.debug]"));
|
||||
assert!(!installed_root.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_marketplace_sync_rejects_unknown_marketplace() {
|
||||
let codex_home = TempDir::new().unwrap();
|
||||
|
||||
let err = remove_marketplace_sync(
|
||||
codex_home.path(),
|
||||
&ConfigLayerStack::default(),
|
||||
MarketplaceRemoveRequest {
|
||||
marketplace_name: "debug".to_string(),
|
||||
},
|
||||
)
|
||||
.unwrap_err();
|
||||
|
||||
assert_eq!(
|
||||
err.to_string(),
|
||||
"marketplace `debug` is not configured or installed"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_marketplace_sync_preserves_shadowed_system_marketplace() {
|
||||
let codex_home = TempDir::new().unwrap();
|
||||
let config = "[marketplaces.debug]\nsource_type = \"git\"\nsource = \"https://github.com/owner/repo.git\"\n";
|
||||
let user_file =
|
||||
AbsolutePathBuf::resolve_path_against_base(CONFIG_TOML_FILE, codex_home.path());
|
||||
let system_file =
|
||||
AbsolutePathBuf::resolve_path_against_base("system.toml", codex_home.path());
|
||||
fs::write(&user_file, config).unwrap();
|
||||
fs::write(&system_file, config).unwrap();
|
||||
let installed_root = marketplace_install_root(codex_home.path()).join("debug");
|
||||
fs::create_dir_all(&installed_root).unwrap();
|
||||
let marker = installed_root.join("marker.txt");
|
||||
fs::write(&marker, "installed").unwrap();
|
||||
let stack = ConfigLayerStack::new(
|
||||
vec![
|
||||
ConfigLayerEntry::new(
|
||||
ConfigLayerSource::System {
|
||||
file: system_file.clone(),
|
||||
},
|
||||
toml::from_str(config).unwrap(),
|
||||
),
|
||||
ConfigLayerEntry::new(
|
||||
ConfigLayerSource::User {
|
||||
file: user_file.clone(),
|
||||
profile: None,
|
||||
},
|
||||
toml::from_str(config).unwrap(),
|
||||
),
|
||||
],
|
||||
Default::default(),
|
||||
Default::default(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let err = remove_marketplace_sync(
|
||||
codex_home.path(),
|
||||
&stack,
|
||||
MarketplaceRemoveRequest {
|
||||
marketplace_name: "debug".to_string(),
|
||||
},
|
||||
)
|
||||
.unwrap_err();
|
||||
|
||||
assert_eq!(
|
||||
err.to_string(),
|
||||
format!(
|
||||
"marketplace `debug` is configured in system ({}); remove it from that configuration source instead",
|
||||
system_file.display()
|
||||
),
|
||||
);
|
||||
assert_eq!(fs::read_to_string(user_file).unwrap(), config);
|
||||
assert_eq!(fs::read_to_string(system_file).unwrap(), config);
|
||||
assert_eq!(fs::read_to_string(marker).unwrap(), "installed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_marketplace_sync_rejects_case_mismatched_configured_name() {
|
||||
let codex_home = TempDir::new().unwrap();
|
||||
record_user_marketplace(
|
||||
codex_home.path(),
|
||||
"debug",
|
||||
&MarketplaceConfigUpdate {
|
||||
source_type: "git",
|
||||
source: "https://github.com/owner/repo.git",
|
||||
ref_name: Some("main"),
|
||||
sparse_paths: &[],
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let installed_root = marketplace_install_root(codex_home.path()).join("debug");
|
||||
fs::create_dir_all(&installed_root).unwrap();
|
||||
|
||||
let err = remove_marketplace_sync(
|
||||
codex_home.path(),
|
||||
&ConfigLayerStack::default(),
|
||||
MarketplaceRemoveRequest {
|
||||
marketplace_name: "Debug".to_string(),
|
||||
},
|
||||
)
|
||||
.unwrap_err();
|
||||
|
||||
assert_eq!(
|
||||
err.to_string(),
|
||||
"marketplace `Debug` does not match configured marketplace `debug` exactly"
|
||||
);
|
||||
assert!(installed_root.exists());
|
||||
let config =
|
||||
fs::read_to_string(codex_home.path().join(akode_config::CONFIG_TOML_FILE)).unwrap();
|
||||
assert!(config.contains("[marketplaces.debug]"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_marketplace_sync_keeps_installed_root_when_config_removal_fails() {
|
||||
let codex_home = TempDir::new().unwrap();
|
||||
fs::write(
|
||||
codex_home.path().join(akode_config::CONFIG_TOML_FILE),
|
||||
"[marketplaces.debug\n",
|
||||
)
|
||||
.unwrap();
|
||||
let installed_root = marketplace_install_root(codex_home.path()).join("debug");
|
||||
fs::create_dir_all(&installed_root).unwrap();
|
||||
|
||||
let err = remove_marketplace_sync(
|
||||
codex_home.path(),
|
||||
&ConfigLayerStack::default(),
|
||||
MarketplaceRemoveRequest {
|
||||
marketplace_name: "debug".to_string(),
|
||||
},
|
||||
)
|
||||
.unwrap_err();
|
||||
|
||||
assert!(
|
||||
err.to_string()
|
||||
.contains("failed to remove marketplace 'debug' from user config.toml")
|
||||
);
|
||||
assert!(installed_root.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_marketplace_sync_removes_file_installed_root() {
|
||||
let codex_home = TempDir::new().unwrap();
|
||||
record_user_marketplace(
|
||||
codex_home.path(),
|
||||
"debug",
|
||||
&MarketplaceConfigUpdate {
|
||||
source_type: "git",
|
||||
source: "https://github.com/owner/repo.git",
|
||||
ref_name: Some("main"),
|
||||
sparse_paths: &[],
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let installed_root = marketplace_install_root(codex_home.path()).join("debug");
|
||||
fs::create_dir_all(installed_root.parent().unwrap()).unwrap();
|
||||
fs::write(&installed_root, "corrupt install root").unwrap();
|
||||
|
||||
let outcome = remove_marketplace_sync(
|
||||
codex_home.path(),
|
||||
&ConfigLayerStack::default(),
|
||||
MarketplaceRemoveRequest {
|
||||
marketplace_name: "debug".to_string(),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
outcome,
|
||||
MarketplaceRemoveOutcome {
|
||||
marketplace_name: "debug".to_string(),
|
||||
removed_installed_root: Some(
|
||||
AbsolutePathBuf::try_from(installed_root.clone()).unwrap()
|
||||
),
|
||||
}
|
||||
);
|
||||
assert!(!installed_root.exists());
|
||||
let config =
|
||||
fs::read_to_string(codex_home.path().join(akode_config::CONFIG_TOML_FILE)).unwrap();
|
||||
assert!(!config.contains("[marketplaces.debug]"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_marketplace_sync_removes_inline_config_entry() {
|
||||
let codex_home = TempDir::new().unwrap();
|
||||
fs::write(
|
||||
codex_home.path().join(akode_config::CONFIG_TOML_FILE),
|
||||
r#"
|
||||
marketplaces = { debug = { source_type = "git", source = "https://github.com/owner/repo.git" } }
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
let installed_root = marketplace_install_root(codex_home.path()).join("debug");
|
||||
fs::create_dir_all(&installed_root).unwrap();
|
||||
|
||||
let outcome = remove_marketplace_sync(
|
||||
codex_home.path(),
|
||||
&ConfigLayerStack::default(),
|
||||
MarketplaceRemoveRequest {
|
||||
marketplace_name: "debug".to_string(),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(outcome.marketplace_name, "debug");
|
||||
assert_eq!(
|
||||
outcome.removed_installed_root,
|
||||
Some(AbsolutePathBuf::try_from(installed_root.clone()).unwrap())
|
||||
);
|
||||
assert!(!installed_root.exists());
|
||||
let config =
|
||||
fs::read_to_string(codex_home.path().join(akode_config::CONFIG_TOML_FILE)).unwrap();
|
||||
assert!(!config.contains("debug"));
|
||||
}
|
||||
}
|
||||
185
akode-rs/core-plugins/src/marketplace_staging.rs
Normal file
185
akode-rs/core-plugins/src/marketplace_staging.rs
Normal file
@@ -0,0 +1,185 @@
|
||||
//! Owns temporary marketplace checkouts and reclaims abandoned ones.
|
||||
//! A coordination lock protects publication of each checkout's lifetime lock. Checkouts
|
||||
//! live below their owner directory so Git and activation cannot replace the lock file.
|
||||
//! Cleanup claims a limited batch under coordination, then deletes it outside that lock.
|
||||
//! Legacy directories use age thresholds because older binaries publish no owner lock.
|
||||
|
||||
use akode_utils_path::symlink_metadata_if_exists;
|
||||
use std::fs;
|
||||
use std::fs::File;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
use std::time::SystemTime;
|
||||
use tempfile::TempDir;
|
||||
use tracing::warn;
|
||||
|
||||
const LEGACY_ADD_MAX_AGE: Duration = Duration::from_secs(24 * 60 * 60);
|
||||
// Upgrades have a 30-second timeout per Git command; leave ample room for all phases.
|
||||
const LEGACY_UPGRADE_MAX_AGE: Duration = Duration::from_secs(10 * 60);
|
||||
const LEGACY_ADD_PREFIX: &str = "marketplace-add-";
|
||||
const LEGACY_UPGRADE_PREFIX: &str = "marketplace-upgrade-";
|
||||
const MAX_CLEANUP_DIRECTORIES: usize = 4;
|
||||
const COORDINATION_LOCK: &str = ".staging.lock";
|
||||
const CLEANUP_LOCK: &str = ".staging-cleanup.lock";
|
||||
const OWNER_LOCK: &str = ".lock";
|
||||
|
||||
pub(crate) struct MarketplaceStagingDir {
|
||||
// Close the lock before TempDir removes its directory, including on Windows.
|
||||
_lock: File,
|
||||
_directory: TempDir,
|
||||
checkout: PathBuf,
|
||||
}
|
||||
|
||||
impl MarketplaceStagingDir {
|
||||
pub(crate) fn new(install_root: &Path) -> io::Result<Self> {
|
||||
let staging_root = Self::staging_root(install_root);
|
||||
fs::create_dir_all(&staging_root)?;
|
||||
let coordination = open_lock(&install_root.join(COORDINATION_LOCK))?;
|
||||
coordination.lock()?;
|
||||
let directory = tempfile::Builder::new()
|
||||
.prefix(&Self::directory_prefix())
|
||||
.tempdir_in(&staging_root)?;
|
||||
let lock = File::options()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(directory.path().join(OWNER_LOCK))?;
|
||||
lock.lock()?;
|
||||
let checkout = directory.path().join("checkout");
|
||||
Ok(Self {
|
||||
_lock: lock,
|
||||
_directory: directory,
|
||||
checkout,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn path(&self) -> &Path {
|
||||
&self.checkout
|
||||
}
|
||||
|
||||
fn staging_root(install_root: &Path) -> PathBuf {
|
||||
install_root.join(".staging")
|
||||
}
|
||||
|
||||
fn directory_prefix() -> String {
|
||||
// Windows and WSL may share a home without sharing a file-lock namespace.
|
||||
format!("marketplace-{}-", std::env::consts::OS)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn cleanup_marketplace_staging(install_root: &Path) {
|
||||
if let Err(err) = remove_stale_staging_dirs(install_root, SystemTime::now()) {
|
||||
warn!("failed to clean up marketplace staging directories: {err}");
|
||||
}
|
||||
}
|
||||
|
||||
fn open_lock(path: &Path) -> io::Result<File> {
|
||||
File::options()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.open(path)
|
||||
}
|
||||
|
||||
fn try_lock(lock: File) -> io::Result<Option<File>> {
|
||||
match lock.try_lock() {
|
||||
Ok(()) => Ok(Some(lock)),
|
||||
Err(fs::TryLockError::WouldBlock) => Ok(None),
|
||||
Err(fs::TryLockError::Error(err)) => Err(err),
|
||||
}
|
||||
}
|
||||
|
||||
fn remove_stale_staging_dirs(install_root: &Path, now: SystemTime) -> io::Result<()> {
|
||||
let staging_root = MarketplaceStagingDir::staging_root(install_root);
|
||||
let Some(metadata) = symlink_metadata_if_exists(&staging_root)? else {
|
||||
return Ok(());
|
||||
};
|
||||
if !metadata.is_dir() {
|
||||
return Ok(());
|
||||
}
|
||||
// Skip this pass if another process creates a checkout or removes a batch.
|
||||
let Some(_cleanup) = try_lock(open_lock(&install_root.join(CLEANUP_LOCK))?)? else {
|
||||
return Ok(());
|
||||
};
|
||||
let Some(coordination) = try_lock(open_lock(&install_root.join(COORDINATION_LOCK))?)? else {
|
||||
return Ok(());
|
||||
};
|
||||
let prefix = MarketplaceStagingDir::directory_prefix();
|
||||
let mut abandoned = Vec::new();
|
||||
for entry in fs::read_dir(&staging_root)? {
|
||||
let entry = entry?;
|
||||
let path = entry.path();
|
||||
// Continue past an unreadable entry so one failure cannot prevent reclamation.
|
||||
match is_abandoned_staging_dir(&entry, &prefix, now) {
|
||||
Ok(true) => abandoned.push(path),
|
||||
Ok(false) => {}
|
||||
Err(err) if err.kind() == io::ErrorKind::NotFound => {}
|
||||
Err(err) => {
|
||||
warn!(path = %path.display(), "failed to inspect marketplace staging directory: {err}");
|
||||
}
|
||||
}
|
||||
if abandoned.len() == MAX_CLEANUP_DIRECTORIES {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Unique checkout names cannot acquire a new owner after publication.
|
||||
// Keep the cleanup lock, but let new checkouts start while deletion runs.
|
||||
drop(coordination);
|
||||
for path in abandoned {
|
||||
if let Err(err) = fs::remove_dir_all(&path)
|
||||
&& err.kind() != io::ErrorKind::NotFound
|
||||
{
|
||||
warn!(path = %path.display(), "failed to remove abandoned marketplace staging directory: {err}");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn is_abandoned_staging_dir(
|
||||
entry: &fs::DirEntry,
|
||||
prefix: &str,
|
||||
now: SystemTime,
|
||||
) -> io::Result<bool> {
|
||||
if !entry.file_type()?.is_dir() {
|
||||
return Ok(false);
|
||||
}
|
||||
let name = entry.file_name();
|
||||
let Some(name) = name.to_str() else {
|
||||
return Ok(false);
|
||||
};
|
||||
if !name.starts_with(prefix) {
|
||||
// Older binaries did not publish ownership. Leave recent directories
|
||||
// alone so an upgrade can coexist with their in-flight clones.
|
||||
let max_age = if name.starts_with(LEGACY_ADD_PREFIX) {
|
||||
LEGACY_ADD_MAX_AGE
|
||||
} else if name.starts_with(LEGACY_UPGRADE_PREFIX) {
|
||||
LEGACY_UPGRADE_MAX_AGE
|
||||
} else {
|
||||
return Ok(false);
|
||||
};
|
||||
return Ok(now
|
||||
.duration_since(entry.metadata()?.modified()?)
|
||||
.unwrap_or_default()
|
||||
>= max_age);
|
||||
}
|
||||
let owner_lock = entry.path().join(OWNER_LOCK);
|
||||
let Some(metadata) = symlink_metadata_if_exists(&owner_lock)? else {
|
||||
// A crash before lock publication can leave an empty directory.
|
||||
return Ok(true);
|
||||
};
|
||||
if !metadata.is_file() {
|
||||
return Ok(false);
|
||||
}
|
||||
// An unlocked checkout has no Codex owner to activate it. A surviving Git
|
||||
// process may still write here; deletion can interrupt that abandoned clone.
|
||||
let lock = File::options().read(true).write(true).open(owner_lock)?;
|
||||
// Close the probe's lock before cleanup removes the directory on Windows.
|
||||
Ok(try_lock(lock)?.is_some())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "marketplace_staging_tests.rs"]
|
||||
mod tests;
|
||||
197
akode-rs/core-plugins/src/marketplace_staging_tests.rs
Normal file
197
akode-rs/core-plugins/src/marketplace_staging_tests.rs
Normal file
@@ -0,0 +1,197 @@
|
||||
//! Exercises staging ownership across processes and age-based recovery of legacy checkouts.
|
||||
|
||||
use super::*;
|
||||
use anyhow::Result;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::io::BufRead;
|
||||
use std::io::Read;
|
||||
use std::io::Write;
|
||||
use std::process::Stdio;
|
||||
|
||||
#[test]
|
||||
fn cleanup_preserves_live_process_and_reclaims_its_abandoned_checkout() -> Result<()> {
|
||||
const CHILD_HOME: &str = "AKODE_MARKETPLACE_STAGING_CHILD_HOME";
|
||||
if let Some(home) = std::env::var_os(CHILD_HOME) {
|
||||
let staging = MarketplaceStagingDir::new(Path::new(&home))?;
|
||||
fs::create_dir_all(staging.path())?;
|
||||
fs::write(staging.path().join("payload"), "in-flight clone")?;
|
||||
println!("staging-ready");
|
||||
std::io::stdout().flush()?;
|
||||
std::io::stdin().read_exact(&mut [0])?;
|
||||
// Model process exit while a background upgrade still owns a checkout.
|
||||
std::process::exit(0);
|
||||
}
|
||||
|
||||
let home = tempfile::tempdir()?;
|
||||
let mut child = akode_utils_process::background_command(std::env::current_exe()?)
|
||||
.args([
|
||||
"--exact",
|
||||
"marketplace_staging::tests::cleanup_preserves_live_process_and_reclaims_its_abandoned_checkout",
|
||||
"--nocapture",
|
||||
])
|
||||
.env(CHILD_HOME, home.path())
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.spawn()?;
|
||||
let stdout = std::io::BufReader::new(child.stdout.take().unwrap());
|
||||
let mut ready = false;
|
||||
for line in stdout.lines() {
|
||||
if line?.contains("staging-ready") {
|
||||
ready = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(ready, "child should publish its checkout before cleanup");
|
||||
let staging_root = home.path().join(".staging");
|
||||
let active = fs::read_dir(&staging_root)?.next().unwrap()?.path();
|
||||
let payload = active.join("checkout/payload");
|
||||
|
||||
// Age must never override the lifetime lock, even across processes.
|
||||
remove_stale_staging_dirs(home.path(), SystemTime::now() + LEGACY_ADD_MAX_AGE)?;
|
||||
assert_eq!(fs::read_to_string(&payload)?, "in-flight clone");
|
||||
let concurrent = MarketplaceStagingDir::new(home.path())?;
|
||||
fs::create_dir_all(concurrent.path())?;
|
||||
fs::write(concurrent.path().join("payload"), "second clone")?;
|
||||
|
||||
child.stdin.take().unwrap().write_all(b"x")?;
|
||||
assert!(child.wait()?.success());
|
||||
assert!(payload.exists(), "process exit must bypass TempDir cleanup");
|
||||
cleanup_marketplace_staging(home.path());
|
||||
assert!(!active.exists());
|
||||
assert_eq!(
|
||||
fs::read_to_string(concurrent.path().join("payload"))?,
|
||||
"second clone"
|
||||
);
|
||||
drop(concurrent);
|
||||
assert_eq!(fs::read_dir(staging_root)?.count(), 0);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cleanup_reclaims_unpublished_and_aged_legacy_clones() -> Result<()> {
|
||||
let home = tempfile::tempdir()?;
|
||||
let staging_root = home.path().join(".staging");
|
||||
let legacy_add = staging_root.join("marketplace-add-old");
|
||||
let legacy_upgrade = staging_root.join("marketplace-upgrade-old");
|
||||
let unrelated = staging_root.join("unrelated");
|
||||
let foreign = staging_root.join("marketplace-other-os-active");
|
||||
let unpublished = staging_root.join(format!(
|
||||
"{}unpublished",
|
||||
MarketplaceStagingDir::directory_prefix()
|
||||
));
|
||||
for path in [
|
||||
&legacy_add,
|
||||
&legacy_upgrade,
|
||||
&unrelated,
|
||||
&foreign,
|
||||
&unpublished,
|
||||
] {
|
||||
fs::create_dir_all(path)?;
|
||||
}
|
||||
fs::write(legacy_add.join("payload"), "old add")?;
|
||||
fs::write(legacy_upgrade.join("payload"), "old upgrade")?;
|
||||
let unrelated_file =
|
||||
staging_root.join(format!("{}file", MarketplaceStagingDir::directory_prefix()));
|
||||
fs::write(&unrelated_file, "keep")?;
|
||||
|
||||
// Base synthetic ages on the filesystem clock, which can differ from the wall clock.
|
||||
let now = fs::metadata(&legacy_add)?
|
||||
.modified()?
|
||||
.max(fs::metadata(&legacy_upgrade)?.modified()?);
|
||||
for (age, expected_legacy_dirs) in [
|
||||
(Duration::ZERO, [true, true]),
|
||||
(
|
||||
LEGACY_UPGRADE_MAX_AGE + Duration::from_secs(1),
|
||||
[true, false],
|
||||
),
|
||||
(LEGACY_ADD_MAX_AGE + Duration::from_secs(1), [false, false]),
|
||||
] {
|
||||
// A concurrent fork can retain the previous pass's locks until exec.
|
||||
// Wait for both locks and explicitly release them before cleanup.
|
||||
for name in [CLEANUP_LOCK, COORDINATION_LOCK] {
|
||||
let lock = open_lock(&home.path().join(name))?;
|
||||
lock.lock()?;
|
||||
lock.unlock()?;
|
||||
}
|
||||
remove_stale_staging_dirs(home.path(), now + age)?;
|
||||
assert!(!unpublished.exists());
|
||||
assert_eq!(
|
||||
[legacy_add.exists(), legacy_upgrade.exists()],
|
||||
expected_legacy_dirs,
|
||||
"legacy directories remaining after {age:?}"
|
||||
);
|
||||
}
|
||||
assert!(unrelated.exists());
|
||||
assert!(foreign.exists());
|
||||
assert_eq!(fs::read_to_string(unrelated_file)?, "keep");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn cleanup_does_not_follow_symlinks() -> Result<()> {
|
||||
let home = tempfile::tempdir()?;
|
||||
let outside = tempfile::tempdir()?;
|
||||
let staging_root = home.path().join(".staging");
|
||||
fs::create_dir_all(&staging_root)?;
|
||||
fs::write(outside.path().join("payload"), "keep")?;
|
||||
let alias = staging_root.join(format!(
|
||||
"{}directory-link",
|
||||
MarketplaceStagingDir::directory_prefix()
|
||||
));
|
||||
std::os::unix::fs::symlink(outside.path(), &alias)?;
|
||||
let legacy_alias = staging_root.join("marketplace-upgrade-link");
|
||||
std::os::unix::fs::symlink(outside.path(), &legacy_alias)?;
|
||||
let invalid_owner =
|
||||
staging_root.join(format!("{}link", MarketplaceStagingDir::directory_prefix()));
|
||||
fs::create_dir_all(&invalid_owner)?;
|
||||
std::os::unix::fs::symlink(
|
||||
outside.path().join("payload"),
|
||||
invalid_owner.join(OWNER_LOCK),
|
||||
)?;
|
||||
|
||||
remove_stale_staging_dirs(home.path(), SystemTime::now() + LEGACY_ADD_MAX_AGE)?;
|
||||
assert_eq!(fs::read_to_string(outside.path().join("payload"))?, "keep");
|
||||
assert!(alias.is_symlink());
|
||||
assert!(legacy_alias.is_symlink());
|
||||
assert!(invalid_owner.exists());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cleanup_limits_each_pass_and_skips_contended_locks() -> Result<()> {
|
||||
let home = tempfile::tempdir()?;
|
||||
let staging_root = home.path().join(".staging");
|
||||
let count = MAX_CLEANUP_DIRECTORIES + 1;
|
||||
for index in 0..count {
|
||||
fs::create_dir_all(staging_root.join(format!(
|
||||
"{}{index}",
|
||||
MarketplaceStagingDir::directory_prefix()
|
||||
)))?;
|
||||
}
|
||||
|
||||
for name in [CLEANUP_LOCK, COORDINATION_LOCK] {
|
||||
let lock = open_lock(&home.path().join(name))?;
|
||||
lock.lock()?;
|
||||
cleanup_marketplace_staging(home.path());
|
||||
assert_eq!(fs::read_dir(&staging_root)?.count(), count);
|
||||
if name == CLEANUP_LOCK {
|
||||
// A cleanup worker must not prevent another operation from creating a checkout.
|
||||
drop(MarketplaceStagingDir::new(home.path())?);
|
||||
}
|
||||
}
|
||||
|
||||
for remaining in [1, 0] {
|
||||
// Other tests can fork while cleanup holds a lock. The child retains
|
||||
// that lock until exec, even after this process closes its file.
|
||||
// Wait for both locks, then release them before testing the batch size.
|
||||
for name in [CLEANUP_LOCK, COORDINATION_LOCK] {
|
||||
let lock = open_lock(&home.path().join(name))?;
|
||||
lock.lock()?;
|
||||
lock.unlock()?;
|
||||
}
|
||||
cleanup_marketplace_staging(home.path());
|
||||
assert_eq!(fs::read_dir(&staging_root)?.count(), remaining);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
2281
akode-rs/core-plugins/src/marketplace_tests.rs
Normal file
2281
akode-rs/core-plugins/src/marketplace_tests.rs
Normal file
File diff suppressed because it is too large
Load Diff
397
akode-rs/core-plugins/src/marketplace_upgrade.rs
Normal file
397
akode-rs/core-plugins/src/marketplace_upgrade.rs
Normal file
@@ -0,0 +1,397 @@
|
||||
mod activation;
|
||||
mod git;
|
||||
|
||||
use self::activation::activate_marketplace_root;
|
||||
use self::activation::installed_marketplace_metadata_matches;
|
||||
use self::activation::read_installed_marketplace_snapshot;
|
||||
use self::activation::write_installed_marketplace_metadata;
|
||||
use self::git::clone_git_source;
|
||||
use self::git::git_remote_revision;
|
||||
use crate::PluginGitMode;
|
||||
use crate::installed_marketplaces::marketplace_install_root;
|
||||
use crate::marketplace::has_symlinked_marketplace_manifest;
|
||||
use crate::marketplace::validate_marketplace_root;
|
||||
use crate::marketplace_add::MarketplaceSource;
|
||||
use crate::marketplace_policy::MarketplacePolicy;
|
||||
use crate::marketplace_policy::validate_marketplace_name_for_add;
|
||||
use crate::marketplace_staging::MarketplaceStagingDir;
|
||||
use crate::marketplace_staging::cleanup_marketplace_staging;
|
||||
use akode_config::ConfigLayerStack;
|
||||
use akode_config::types::MarketplaceConfig;
|
||||
use akode_config::types::MarketplaceSourceType;
|
||||
use akode_plugin::validate_plugin_segment;
|
||||
use akode_utils_absolute_path::AbsolutePathBuf;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use sha2::Digest;
|
||||
use sha2::Sha256;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
/// Reloads configuration with the initiating operation's settings. Called only on a blocking worker.
|
||||
pub type ConfigLayerReload = Arc<dyn Fn() -> std::io::Result<ConfigLayerStack> + Send + Sync>;
|
||||
|
||||
const MARKETPLACE_UPGRADE_GIT_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ConfiguredMarketplaceUpgradeError {
|
||||
pub marketplace_name: String,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, PartialEq, Eq)]
|
||||
pub struct ConfiguredMarketplaceUpgradeOutcome {
|
||||
pub selected_marketplaces: Vec<String>,
|
||||
pub upgraded_roots: Vec<AbsolutePathBuf>,
|
||||
pub errors: Vec<ConfiguredMarketplaceUpgradeError>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
struct ConfiguredGitMarketplace {
|
||||
name: String,
|
||||
source: String,
|
||||
ref_name: Option<String>,
|
||||
sparse_paths: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, PartialEq, Eq)]
|
||||
struct CheckoutInputs {
|
||||
configured_name: Box<str>,
|
||||
source_sha256: Box<str>,
|
||||
ref_name: Option<Box<str>>,
|
||||
sparse_paths: Box<[Box<str>]>,
|
||||
revision: Box<str>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct MarketplaceNameMismatch {
|
||||
inputs: CheckoutInputs,
|
||||
found_name: Box<str>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct ConfiguredGitMarketplaceLoadOutcome {
|
||||
marketplaces: Vec<ConfiguredGitMarketplace>,
|
||||
errors: Vec<ConfiguredMarketplaceUpgradeError>,
|
||||
}
|
||||
|
||||
impl ConfiguredMarketplaceUpgradeOutcome {
|
||||
pub fn all_succeeded(&self) -> bool {
|
||||
self.errors.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn configured_git_marketplace_names(config_layer_stack: &ConfigLayerStack) -> Vec<String> {
|
||||
let mut names = load_configured_git_marketplaces(config_layer_stack)
|
||||
.marketplaces
|
||||
.into_iter()
|
||||
.map(|marketplace| marketplace.name)
|
||||
.collect::<Vec<_>>();
|
||||
names.sort_unstable();
|
||||
names
|
||||
}
|
||||
|
||||
pub fn upgrade_configured_git_marketplaces(
|
||||
codex_home: &Path,
|
||||
config_layer_stack: &ConfigLayerStack,
|
||||
marketplace_name: Option<&str>,
|
||||
reload_config: &ConfigLayerReload,
|
||||
) -> ConfiguredMarketplaceUpgradeOutcome {
|
||||
upgrade_configured_git_marketplaces_with_mode(
|
||||
codex_home,
|
||||
config_layer_stack,
|
||||
marketplace_name,
|
||||
PluginGitMode::Manual,
|
||||
reload_config,
|
||||
)
|
||||
}
|
||||
|
||||
/// Applies the initiating operation's Git trust policy to every selected marketplace.
|
||||
pub(crate) fn upgrade_configured_git_marketplaces_with_mode(
|
||||
codex_home: &Path,
|
||||
config_layer_stack: &ConfigLayerStack,
|
||||
marketplace_name: Option<&str>,
|
||||
mode: PluginGitMode,
|
||||
reload_config: &ConfigLayerReload,
|
||||
) -> ConfiguredMarketplaceUpgradeOutcome {
|
||||
let install_root = marketplace_install_root(codex_home);
|
||||
cleanup_marketplace_staging(&install_root);
|
||||
let loaded = load_configured_git_marketplaces(config_layer_stack);
|
||||
let marketplaces = loaded
|
||||
.marketplaces
|
||||
.into_iter()
|
||||
.filter(|marketplace| marketplace_name.is_none_or(|name| marketplace.name.as_str() == name))
|
||||
.collect::<Vec<_>>();
|
||||
let mut errors = loaded
|
||||
.errors
|
||||
.into_iter()
|
||||
.filter(|error| marketplace_name.is_none_or(|name| error.marketplace_name.as_str() == name))
|
||||
.collect::<Vec<_>>();
|
||||
if marketplaces.is_empty() && errors.is_empty() {
|
||||
return ConfiguredMarketplaceUpgradeOutcome::default();
|
||||
}
|
||||
|
||||
let mut selected_marketplaces = marketplaces
|
||||
.iter()
|
||||
.map(|marketplace| marketplace.name.clone())
|
||||
.chain(errors.iter().map(|error| error.marketplace_name.clone()))
|
||||
.collect::<Vec<_>>();
|
||||
selected_marketplaces.sort_unstable();
|
||||
selected_marketplaces.dedup();
|
||||
let mut upgraded_roots = Vec::new();
|
||||
let policy = MarketplacePolicy::from_requirements(config_layer_stack.requirements());
|
||||
for marketplace in marketplaces {
|
||||
let normalized_source =
|
||||
match validate_marketplace_name_for_add(/*expected_name*/ None, &marketplace.name)
|
||||
.and_then(|()| {
|
||||
policy.validate_git_source(&marketplace.source, marketplace.ref_name.clone())
|
||||
}) {
|
||||
Ok(normalized_source) => normalized_source,
|
||||
Err(message) => {
|
||||
errors.push(ConfiguredMarketplaceUpgradeError {
|
||||
marketplace_name: marketplace.name,
|
||||
message,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
};
|
||||
match upgrade_configured_git_marketplace(
|
||||
codex_home,
|
||||
&install_root,
|
||||
&marketplace,
|
||||
reload_config,
|
||||
normalized_source.as_ref(),
|
||||
mode,
|
||||
) {
|
||||
Ok(Some(upgraded_root)) => upgraded_roots.push(upgraded_root),
|
||||
Ok(None) => {}
|
||||
Err(err) => {
|
||||
errors.push(ConfiguredMarketplaceUpgradeError {
|
||||
marketplace_name: marketplace.name,
|
||||
message: err,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ConfiguredMarketplaceUpgradeOutcome {
|
||||
selected_marketplaces,
|
||||
upgraded_roots,
|
||||
errors,
|
||||
}
|
||||
}
|
||||
|
||||
fn load_configured_git_marketplaces(
|
||||
config_layer_stack: &ConfigLayerStack,
|
||||
) -> ConfiguredGitMarketplaceLoadOutcome {
|
||||
let effective_config = config_layer_stack.effective_config();
|
||||
let Some(marketplaces) = effective_config
|
||||
.get("marketplaces")
|
||||
.and_then(toml::Value::as_table)
|
||||
else {
|
||||
return ConfiguredGitMarketplaceLoadOutcome::default();
|
||||
};
|
||||
|
||||
let mut outcome = ConfiguredGitMarketplaceLoadOutcome::default();
|
||||
for (name, marketplace) in marketplaces {
|
||||
match parse_configured_git_marketplace(name, marketplace) {
|
||||
Ok(Some(marketplace)) => outcome.marketplaces.push(marketplace),
|
||||
Ok(None) => {}
|
||||
Err(message) => outcome.errors.push(ConfiguredMarketplaceUpgradeError {
|
||||
marketplace_name: name.clone(),
|
||||
message,
|
||||
}),
|
||||
}
|
||||
}
|
||||
outcome
|
||||
.marketplaces
|
||||
.sort_unstable_by(|left, right| left.name.cmp(&right.name));
|
||||
outcome
|
||||
.errors
|
||||
.sort_unstable_by(|left, right| left.marketplace_name.cmp(&right.marketplace_name));
|
||||
outcome
|
||||
}
|
||||
|
||||
fn parse_configured_git_marketplace(
|
||||
name: &str,
|
||||
marketplace: &toml::Value,
|
||||
) -> Result<Option<ConfiguredGitMarketplace>, String> {
|
||||
if marketplace.get("source_type").and_then(toml::Value::as_str) != Some("git") {
|
||||
return Ok(None);
|
||||
}
|
||||
let marketplace = marketplace
|
||||
.clone()
|
||||
.try_into::<MarketplaceConfig>()
|
||||
.map_err(|err| format!("invalid configured Git marketplace: {err}"))?;
|
||||
let MarketplaceConfig {
|
||||
last_updated: _,
|
||||
last_revision: _,
|
||||
source_type,
|
||||
source,
|
||||
ref_name,
|
||||
sparse_paths,
|
||||
} = marketplace;
|
||||
if source_type != Some(MarketplaceSourceType::Git) {
|
||||
return Ok(None);
|
||||
}
|
||||
let source =
|
||||
source.ok_or_else(|| "configured Git marketplace is missing source".to_string())?;
|
||||
Ok(Some(ConfiguredGitMarketplace {
|
||||
name: name.to_string(),
|
||||
source,
|
||||
ref_name,
|
||||
sparse_paths: sparse_paths.unwrap_or_default(),
|
||||
}))
|
||||
}
|
||||
|
||||
fn upgrade_configured_git_marketplace(
|
||||
codex_home: &Path,
|
||||
install_root: &Path,
|
||||
marketplace: &ConfiguredGitMarketplace,
|
||||
reload_config: &ConfigLayerReload,
|
||||
normalized_source: Option<&MarketplaceSource>,
|
||||
mode: PluginGitMode,
|
||||
) -> Result<Option<AbsolutePathBuf>, String> {
|
||||
validate_plugin_segment(&marketplace.name, "marketplace name")?;
|
||||
let (source, ref_name) = match normalized_source {
|
||||
Some(MarketplaceSource::Git { url, ref_name }) => (url.as_str(), ref_name.as_deref()),
|
||||
Some(MarketplaceSource::Local { .. }) => {
|
||||
return Err("validated Git marketplace source resolved to a local path".to_string());
|
||||
}
|
||||
None => (marketplace.source.as_str(), marketplace.ref_name.as_deref()),
|
||||
};
|
||||
let remote_revision = git_remote_revision(
|
||||
codex_home,
|
||||
source,
|
||||
ref_name,
|
||||
MARKETPLACE_UPGRADE_GIT_TIMEOUT,
|
||||
mode,
|
||||
)?;
|
||||
let destination = install_root.join(&marketplace.name);
|
||||
let previous_snapshot = read_installed_marketplace_snapshot(&destination, &marketplace.name);
|
||||
if validate_marketplace_root(&destination)
|
||||
.is_ok_and(|marketplace_name| marketplace_name == marketplace.name)
|
||||
&& installed_marketplace_metadata_matches(&previous_snapshot, marketplace, &remote_revision)
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let name_mismatch = |found: &str| {
|
||||
format!(
|
||||
"upgraded marketplace name `{found}` does not match configured marketplace `{}`",
|
||||
marketplace.name
|
||||
)
|
||||
};
|
||||
// An unchanged checkout will declare the same name. Keep one rejection per
|
||||
// marketplace outside its untrusted checkout, without persisting the source URL.
|
||||
let rejection = match mode {
|
||||
PluginGitMode::Manual => None,
|
||||
PluginGitMode::Automatic => {
|
||||
let path = codex_home
|
||||
.join("cache/marketplaces")
|
||||
.join(format!("{}.json", marketplace.name));
|
||||
let inputs = CheckoutInputs {
|
||||
configured_name: Box::from(marketplace.name.as_str()),
|
||||
source_sha256: format!("{:x}", Sha256::digest(source)).into_boxed_str(),
|
||||
ref_name: ref_name.map(Box::from),
|
||||
sparse_paths: marketplace
|
||||
.sparse_paths
|
||||
.iter()
|
||||
.map(|path| Box::from(path.as_str()))
|
||||
.collect(),
|
||||
revision: remote_revision.into_boxed_str(),
|
||||
};
|
||||
Some((path, inputs))
|
||||
}
|
||||
};
|
||||
if let Some((path, inputs)) = &rejection
|
||||
&& let Ok(contents) = std::fs::read(path)
|
||||
&& let Ok(cached) = serde_json::from_slice::<MarketplaceNameMismatch>(&contents)
|
||||
&& cached.inputs == *inputs
|
||||
{
|
||||
return Err(name_mismatch(&cached.found_name));
|
||||
}
|
||||
|
||||
let staged_dir = MarketplaceStagingDir::new(install_root).map_err(|err| {
|
||||
format!(
|
||||
"failed to create temporary marketplace upgrade directory in {}: {err}",
|
||||
install_root.display()
|
||||
)
|
||||
})?;
|
||||
|
||||
let activated_revision = clone_git_source(
|
||||
codex_home,
|
||||
source,
|
||||
ref_name,
|
||||
&marketplace.sparse_paths,
|
||||
staged_dir.path(),
|
||||
MARKETPLACE_UPGRADE_GIT_TIMEOUT,
|
||||
mode,
|
||||
)?;
|
||||
let marketplace_name = validate_marketplace_root(staged_dir.path())
|
||||
.map_err(|err| format!("failed to validate upgraded marketplace root: {err}"))?;
|
||||
if marketplace_name != marketplace.name {
|
||||
let error = name_mismatch(&marketplace_name);
|
||||
// HEAD may have moved since ls-remote. Only cache the revision we validated.
|
||||
if let Some((path, inputs)) = rejection
|
||||
&& activated_revision.as_str() == inputs.revision.as_ref()
|
||||
&& !has_symlinked_marketplace_manifest(staged_dir.path())
|
||||
&& let Ok(contents) = serde_json::to_string_pretty(&MarketplaceNameMismatch {
|
||||
inputs,
|
||||
found_name: marketplace_name.into_boxed_str(),
|
||||
})
|
||||
{
|
||||
let _ = akode_utils_path::write_atomically(&path, &contents);
|
||||
}
|
||||
return Err(error);
|
||||
}
|
||||
write_installed_marketplace_metadata(staged_dir.path(), marketplace, &activated_revision)?;
|
||||
activate_marketplace_root(&destination, staged_dir.path(), &previous_snapshot, || {
|
||||
ensure_configured_git_marketplace_unchanged(reload_config, marketplace)
|
||||
})?;
|
||||
|
||||
AbsolutePathBuf::try_from(destination)
|
||||
.map(Some)
|
||||
.map_err(|err| format!("upgraded marketplace path is not absolute: {err}"))
|
||||
}
|
||||
fn ensure_configured_git_marketplace_unchanged(
|
||||
reload_config: &ConfigLayerReload,
|
||||
expected: &ConfiguredGitMarketplace,
|
||||
) -> Result<(), String> {
|
||||
let current = read_configured_git_marketplace(reload_config, &expected.name)?;
|
||||
match current {
|
||||
Some(current) if current == *expected => Ok(()),
|
||||
Some(_) => Err(format!(
|
||||
"configured marketplace `{}` changed while auto-upgrade was in flight",
|
||||
expected.name
|
||||
)),
|
||||
None => Err(format!(
|
||||
"configured marketplace `{}` was removed or is no longer a Git marketplace",
|
||||
expected.name
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn read_configured_git_marketplace(
|
||||
reload_config: &ConfigLayerReload,
|
||||
marketplace_name: &str,
|
||||
) -> Result<Option<ConfiguredGitMarketplace>, String> {
|
||||
let effective_config = reload_config()
|
||||
.map_err(|err| {
|
||||
format!("failed to reload config while checking marketplace upgrade: {err}")
|
||||
})?
|
||||
.effective_config();
|
||||
let Some(marketplace) = effective_config
|
||||
.get("marketplaces")
|
||||
.and_then(toml::Value::as_table)
|
||||
.and_then(|marketplaces| marketplaces.get(marketplace_name))
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
parse_configured_git_marketplace(marketplace_name, marketplace)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "marketplace_upgrade_tests.rs"]
|
||||
mod tests;
|
||||
222
akode-rs/core-plugins/src/marketplace_upgrade/activation.rs
Normal file
222
akode-rs/core-plugins/src/marketplace_upgrade/activation.rs
Normal file
@@ -0,0 +1,222 @@
|
||||
use super::ConfiguredGitMarketplace;
|
||||
use akode_config::types::MarketplaceSourceType;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use tracing::warn;
|
||||
|
||||
const MARKETPLACE_INSTALL_METADATA_FILE: &str = ".codex-marketplace-install.json";
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
struct InstalledMarketplaceMetadata {
|
||||
source_type: MarketplaceSourceType,
|
||||
source: String,
|
||||
ref_name: Option<String>,
|
||||
sparse_paths: Vec<String>,
|
||||
revision: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(super) struct InstalledMarketplaceSnapshot {
|
||||
marketplace_name: String,
|
||||
exists: bool,
|
||||
metadata: Option<InstalledMarketplaceMetadata>,
|
||||
}
|
||||
|
||||
pub(super) fn read_installed_marketplace_snapshot(
|
||||
root: &Path,
|
||||
marketplace_name: &str,
|
||||
) -> InstalledMarketplaceSnapshot {
|
||||
if !root.exists() {
|
||||
return InstalledMarketplaceSnapshot {
|
||||
marketplace_name: marketplace_name.to_string(),
|
||||
exists: false,
|
||||
metadata: None,
|
||||
};
|
||||
}
|
||||
let metadata = match std::fs::read_to_string(installed_marketplace_metadata_path(root)) {
|
||||
Ok(metadata) => metadata,
|
||||
Err(_) => {
|
||||
return InstalledMarketplaceSnapshot {
|
||||
marketplace_name: marketplace_name.to_string(),
|
||||
exists: true,
|
||||
metadata: None,
|
||||
};
|
||||
}
|
||||
};
|
||||
let metadata = match serde_json::from_str::<InstalledMarketplaceMetadata>(&metadata) {
|
||||
Ok(metadata) => Some(metadata),
|
||||
Err(err) => {
|
||||
warn!(
|
||||
marketplace = marketplace_name,
|
||||
error = %err,
|
||||
"failed to parse activated marketplace metadata"
|
||||
);
|
||||
None
|
||||
}
|
||||
};
|
||||
InstalledMarketplaceSnapshot {
|
||||
marketplace_name: marketplace_name.to_string(),
|
||||
exists: true,
|
||||
metadata,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn installed_marketplace_metadata_matches(
|
||||
snapshot: &InstalledMarketplaceSnapshot,
|
||||
marketplace: &ConfiguredGitMarketplace,
|
||||
revision: &str,
|
||||
) -> bool {
|
||||
snapshot.metadata.as_ref() == Some(&installed_marketplace_metadata(marketplace, revision))
|
||||
}
|
||||
|
||||
pub(super) fn write_installed_marketplace_metadata(
|
||||
root: &Path,
|
||||
marketplace: &ConfiguredGitMarketplace,
|
||||
revision: &str,
|
||||
) -> Result<(), String> {
|
||||
let metadata = installed_marketplace_metadata(marketplace, revision);
|
||||
let contents = serde_json::to_string_pretty(&metadata)
|
||||
.map_err(|err| format!("failed to serialize activated marketplace metadata: {err}"))?;
|
||||
std::fs::write(installed_marketplace_metadata_path(root), contents)
|
||||
.map_err(|err| format!("failed to write activated marketplace metadata: {err}"))
|
||||
}
|
||||
|
||||
pub(super) fn activate_marketplace_root(
|
||||
destination: &Path,
|
||||
staged_root: &Path,
|
||||
previous_snapshot: &InstalledMarketplaceSnapshot,
|
||||
after_activate: impl FnOnce() -> Result<(), String>,
|
||||
) -> Result<(), String> {
|
||||
let Some(parent) = destination.parent() else {
|
||||
return Err(format!(
|
||||
"failed to determine marketplace install parent for {}",
|
||||
destination.display()
|
||||
));
|
||||
};
|
||||
std::fs::create_dir_all(parent).map_err(|err| {
|
||||
format!(
|
||||
"failed to create marketplace install parent {}: {err}",
|
||||
parent.display()
|
||||
)
|
||||
})?;
|
||||
|
||||
if destination.exists() {
|
||||
let backup_dir = tempfile::Builder::new()
|
||||
.prefix("marketplace-backup-")
|
||||
.tempdir_in(parent)
|
||||
.map_err(|err| {
|
||||
format!(
|
||||
"failed to create marketplace backup directory in {}: {err}",
|
||||
parent.display()
|
||||
)
|
||||
})?;
|
||||
let backup_root = backup_dir.path().join("root");
|
||||
std::fs::rename(destination, &backup_root).map_err(|err| {
|
||||
format!(
|
||||
"failed to move previous marketplace root out of the way at {}: {err}",
|
||||
destination.display()
|
||||
)
|
||||
})?;
|
||||
|
||||
if let Err(err) = std::fs::rename(staged_root, destination) {
|
||||
let rollback_result = std::fs::rename(&backup_root, destination);
|
||||
return match rollback_result {
|
||||
Ok(()) => Err(format!(
|
||||
"failed to activate upgraded marketplace at {}: {err}",
|
||||
destination.display()
|
||||
)),
|
||||
Err(rollback_err) => {
|
||||
let backup_path = backup_dir.keep().join("root");
|
||||
Err(format!(
|
||||
"failed to activate upgraded marketplace at {}: {err}; failed to restore previous marketplace root (left at {}): {rollback_err}",
|
||||
destination.display(),
|
||||
backup_path.display()
|
||||
))
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
let activation_result = if read_installed_marketplace_snapshot(
|
||||
&backup_root,
|
||||
&previous_snapshot.marketplace_name,
|
||||
) != *previous_snapshot
|
||||
{
|
||||
Err(installed_marketplace_snapshot_changed_error(
|
||||
previous_snapshot,
|
||||
))
|
||||
} else {
|
||||
after_activate()
|
||||
};
|
||||
if let Err(err) = activation_result {
|
||||
let remove_result = std::fs::remove_dir_all(destination);
|
||||
let rollback_result =
|
||||
remove_result.and_then(|()| std::fs::rename(&backup_root, destination));
|
||||
return match rollback_result {
|
||||
Ok(()) => Err(err),
|
||||
Err(rollback_err) => {
|
||||
let backup_path = backup_dir.keep().join("root");
|
||||
Err(format!(
|
||||
"{err}; failed to restore previous marketplace root at {} (left at {}): {rollback_err}",
|
||||
destination.display(),
|
||||
backup_path.display()
|
||||
))
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
std::fs::rename(staged_root, destination).map_err(|err| {
|
||||
format!(
|
||||
"failed to activate upgraded marketplace at {}: {err}",
|
||||
destination.display()
|
||||
)
|
||||
})?;
|
||||
let activation_result = if previous_snapshot.exists {
|
||||
Err(installed_marketplace_snapshot_changed_error(
|
||||
previous_snapshot,
|
||||
))
|
||||
} else {
|
||||
after_activate()
|
||||
};
|
||||
if let Err(err) = activation_result {
|
||||
let remove_result = std::fs::remove_dir_all(destination);
|
||||
return match remove_result {
|
||||
Ok(()) => Err(err),
|
||||
Err(remove_err) => Err(format!(
|
||||
"{err}; failed to remove newly activated marketplace root at {}: {remove_err}",
|
||||
destination.display()
|
||||
)),
|
||||
};
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn installed_marketplace_snapshot_changed_error(snapshot: &InstalledMarketplaceSnapshot) -> String {
|
||||
format!(
|
||||
"installed marketplace `{}` changed while auto-upgrade was in flight",
|
||||
snapshot.marketplace_name
|
||||
)
|
||||
}
|
||||
|
||||
fn installed_marketplace_metadata(
|
||||
marketplace: &ConfiguredGitMarketplace,
|
||||
revision: &str,
|
||||
) -> InstalledMarketplaceMetadata {
|
||||
InstalledMarketplaceMetadata {
|
||||
source_type: MarketplaceSourceType::Git,
|
||||
source: marketplace.source.clone(),
|
||||
ref_name: marketplace.ref_name.clone(),
|
||||
sparse_paths: marketplace.sparse_paths.clone(),
|
||||
revision: revision.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn installed_marketplace_metadata_path(root: &Path) -> PathBuf {
|
||||
root.join(MARKETPLACE_INSTALL_METADATA_FILE)
|
||||
}
|
||||
309
akode-rs/core-plugins/src/marketplace_upgrade/git.rs
Normal file
309
akode-rs/core-plugins/src/marketplace_upgrade/git.rs
Normal file
@@ -0,0 +1,309 @@
|
||||
use crate::PluginGitMode;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
use std::process::Output;
|
||||
use std::process::Stdio;
|
||||
use std::time::Duration;
|
||||
|
||||
pub(super) fn git_remote_revision(
|
||||
codex_home: &Path,
|
||||
source: &str,
|
||||
ref_name: Option<&str>,
|
||||
timeout: Duration,
|
||||
mode: PluginGitMode,
|
||||
) -> Result<String, String> {
|
||||
if let Some(ref_name) = ref_name
|
||||
&& is_full_git_sha(ref_name)
|
||||
{
|
||||
return Ok(ref_name.to_string());
|
||||
}
|
||||
|
||||
let ref_name = ref_name.unwrap_or("HEAD");
|
||||
let mut command = git_command(mode);
|
||||
let _trusted_repository = matches!(mode, PluginGitMode::Automatic)
|
||||
.then(|| crate::configure_trusted_git_repository(&mut command, codex_home))
|
||||
.transpose()?;
|
||||
let output = run_git_command_with_timeout(
|
||||
command.arg("ls-remote").arg(source).arg(ref_name),
|
||||
"git ls-remote marketplace source",
|
||||
timeout,
|
||||
)?;
|
||||
ensure_git_success(&output, "git ls-remote marketplace source")?;
|
||||
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let Some(first_line) = stdout.lines().next() else {
|
||||
return Err("git ls-remote returned empty output for marketplace source".to_string());
|
||||
};
|
||||
let Some((revision, _)) = first_line.split_once('\t') else {
|
||||
return Err(format!(
|
||||
"unexpected git ls-remote output for marketplace source: {first_line}"
|
||||
));
|
||||
};
|
||||
let revision = revision.trim();
|
||||
if revision.is_empty() {
|
||||
return Err("git ls-remote returned empty revision for marketplace source".to_string());
|
||||
}
|
||||
Ok(revision.to_string())
|
||||
}
|
||||
|
||||
pub(super) fn clone_git_source(
|
||||
codex_home: &Path,
|
||||
source: &str,
|
||||
ref_name: Option<&str>,
|
||||
sparse_paths: &[String],
|
||||
destination: &Path,
|
||||
timeout: Duration,
|
||||
mode: PluginGitMode,
|
||||
) -> Result<String, String> {
|
||||
let git_destination = git_path_arg(destination);
|
||||
let mut command = git_command(mode);
|
||||
let _trusted_repository = matches!(mode, PluginGitMode::Automatic)
|
||||
.then(|| crate::configure_trusted_git_repository(&mut command, codex_home))
|
||||
.transpose()?;
|
||||
if sparse_paths.is_empty() {
|
||||
let output = run_git_command_with_timeout(
|
||||
command.arg("clone").arg(source).arg(&git_destination),
|
||||
"git clone marketplace source",
|
||||
timeout,
|
||||
)?;
|
||||
ensure_git_success(&output, "git clone marketplace source")?;
|
||||
if let Some(ref_name) = ref_name {
|
||||
let output = run_git_command_with_timeout(
|
||||
git_command(mode)
|
||||
.arg("-C")
|
||||
.arg(&git_destination)
|
||||
.arg("checkout")
|
||||
.arg(ref_name),
|
||||
"git checkout marketplace ref",
|
||||
timeout,
|
||||
)?;
|
||||
ensure_git_success(&output, "git checkout marketplace ref")?;
|
||||
}
|
||||
return git_worktree_revision(&git_destination, timeout, mode);
|
||||
}
|
||||
|
||||
let output = run_git_command_with_timeout(
|
||||
command
|
||||
.arg("clone")
|
||||
.arg("--filter=blob:none")
|
||||
.arg("--no-checkout")
|
||||
.arg(source)
|
||||
.arg(&git_destination),
|
||||
"git clone marketplace source",
|
||||
timeout,
|
||||
)?;
|
||||
ensure_git_success(&output, "git clone marketplace source")?;
|
||||
|
||||
let mut sparse_checkout = git_command(mode);
|
||||
sparse_checkout
|
||||
.arg("-C")
|
||||
.arg(&git_destination)
|
||||
.arg("sparse-checkout")
|
||||
.arg("set")
|
||||
.args(sparse_paths);
|
||||
let output = run_git_command_with_timeout(
|
||||
&mut sparse_checkout,
|
||||
"git sparse-checkout marketplace source",
|
||||
timeout,
|
||||
)?;
|
||||
ensure_git_success(&output, "git sparse-checkout marketplace source")?;
|
||||
|
||||
let output = run_git_command_with_timeout(
|
||||
git_command(mode)
|
||||
.arg("-C")
|
||||
.arg(&git_destination)
|
||||
.arg("checkout")
|
||||
.arg(ref_name.unwrap_or("HEAD")),
|
||||
"git checkout marketplace ref",
|
||||
timeout,
|
||||
)?;
|
||||
ensure_git_success(&output, "git checkout marketplace ref")?;
|
||||
git_worktree_revision(&git_destination, timeout, mode)
|
||||
}
|
||||
|
||||
fn git_worktree_revision(
|
||||
destination: &Path,
|
||||
timeout: Duration,
|
||||
mode: PluginGitMode,
|
||||
) -> Result<String, String> {
|
||||
let output = run_git_command_with_timeout(
|
||||
git_command(mode)
|
||||
.arg("-C")
|
||||
.arg(destination)
|
||||
.arg("rev-parse")
|
||||
.arg("HEAD"),
|
||||
"git rev-parse marketplace revision",
|
||||
timeout,
|
||||
)?;
|
||||
ensure_git_success(&output, "git rev-parse marketplace revision")?;
|
||||
|
||||
let revision = String::from_utf8_lossy(&output.stdout).trim().to_string();
|
||||
if revision.is_empty() {
|
||||
Err("git rev-parse returned empty revision for marketplace source".to_string())
|
||||
} else {
|
||||
Ok(revision)
|
||||
}
|
||||
}
|
||||
|
||||
fn is_full_git_sha(value: &str) -> bool {
|
||||
value.len() == 40 && value.chars().all(|ch| ch.is_ascii_hexdigit())
|
||||
}
|
||||
|
||||
fn git_command(mode: PluginGitMode) -> Command {
|
||||
let mut command = mode.command(Path::new("git"));
|
||||
command
|
||||
.env("GIT_OPTIONAL_LOCKS", "0")
|
||||
.env("GIT_TERMINAL_PROMPT", "0");
|
||||
command
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn git_path_arg(path: &Path) -> PathBuf {
|
||||
strip_windows_verbatim_path_prefix(&path.to_string_lossy())
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| path.to_path_buf())
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
fn git_path_arg(path: &Path) -> PathBuf {
|
||||
path.to_path_buf()
|
||||
}
|
||||
|
||||
#[cfg(any(windows, test))]
|
||||
fn strip_windows_verbatim_path_prefix(path: &str) -> Option<String> {
|
||||
let stripped = path.strip_prefix(r"\\?\")?;
|
||||
let stripped = stripped
|
||||
.strip_prefix(r"UNC\")
|
||||
.map(|unc_path| format!(r"\\{unc_path}"))
|
||||
.unwrap_or_else(|| stripped.to_string());
|
||||
Some(stripped)
|
||||
}
|
||||
|
||||
fn run_git_command_with_timeout(
|
||||
command: &mut Command,
|
||||
context: &str,
|
||||
timeout: Duration,
|
||||
) -> Result<Output, String> {
|
||||
let mut child = command
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.map_err(|err| format!("failed to run {context}: {err}"))?;
|
||||
let start = std::time::Instant::now();
|
||||
loop {
|
||||
match child.try_wait() {
|
||||
Ok(Some(_)) => {
|
||||
return child
|
||||
.wait_with_output()
|
||||
.map_err(|err| format!("failed to wait for {context}: {err}"));
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(err) => return Err(format!("failed to poll {context}: {err}")),
|
||||
}
|
||||
|
||||
if start.elapsed() >= timeout {
|
||||
let _ = child.kill();
|
||||
let output = child
|
||||
.wait_with_output()
|
||||
.map_err(|err| format!("failed to wait for {context} after timeout: {err}"))?;
|
||||
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
|
||||
return if stderr.is_empty() {
|
||||
Err(format!("{context} timed out after {}s", timeout.as_secs()))
|
||||
} else {
|
||||
Err(format!(
|
||||
"{context} timed out after {}s: {stderr}",
|
||||
timeout.as_secs()
|
||||
))
|
||||
};
|
||||
}
|
||||
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
}
|
||||
|
||||
fn ensure_git_success(output: &Output, context: &str) -> Result<(), String> {
|
||||
if output.status.success() {
|
||||
return Ok(());
|
||||
}
|
||||
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
|
||||
if stderr.is_empty() {
|
||||
Err(format!("{context} failed with status {}", output.status))
|
||||
} else {
|
||||
Err(format!(
|
||||
"{context} failed with status {}: {stderr}",
|
||||
output.status
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::git_command;
|
||||
use super::is_full_git_sha;
|
||||
use super::strip_windows_verbatim_path_prefix;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::ffi::OsStr;
|
||||
|
||||
#[test]
|
||||
fn full_git_sha_ref_is_already_a_remote_revision() {
|
||||
assert!(is_full_git_sha("0123456789abcdef0123456789abcdef01234567"));
|
||||
assert!(!is_full_git_sha("main"));
|
||||
assert!(!is_full_git_sha("0123456"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn git_command_uses_path_lookup_with_stable_noninteractive_env() {
|
||||
let command = git_command(crate::PluginGitMode::Automatic);
|
||||
|
||||
assert_eq!(command.get_program(), OsStr::new("git"));
|
||||
assert_eq!(
|
||||
command.get_args().collect::<Vec<_>>(),
|
||||
[
|
||||
OsStr::new("-c"),
|
||||
OsStr::new(akode_git_utils::SAFE_BARE_REPOSITORY_CONFIG),
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
command_env(&command, "GIT_OPTIONAL_LOCKS"),
|
||||
Some(Some(OsStr::new("0")))
|
||||
);
|
||||
assert_eq!(
|
||||
command_env(&command, "GIT_TERMINAL_PROMPT"),
|
||||
Some(Some(OsStr::new("0")))
|
||||
);
|
||||
assert_eq!(command_env(&command, "PATH"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strips_windows_verbatim_disk_prefix_for_git() {
|
||||
assert_eq!(
|
||||
strip_windows_verbatim_path_prefix(r"\\?\C:\Users\alice\marketplace"),
|
||||
Some(r"C:\Users\alice\marketplace".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strips_windows_verbatim_unc_prefix_for_git() {
|
||||
assert_eq!(
|
||||
strip_windows_verbatim_path_prefix(r"\\?\UNC\server\share\marketplace"),
|
||||
Some(r"\\server\share\marketplace".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leaves_non_verbatim_path_without_rewrite() {
|
||||
assert_eq!(strip_windows_verbatim_path_prefix(r"C:\Users\alice"), None);
|
||||
}
|
||||
|
||||
fn command_env<'a>(
|
||||
command: &'a std::process::Command,
|
||||
name: &str,
|
||||
) -> Option<Option<&'a OsStr>> {
|
||||
command
|
||||
.get_envs()
|
||||
.find(|(key, _)| key == &OsStr::new(name))
|
||||
.map(|(_, value)| value)
|
||||
}
|
||||
}
|
||||
633
akode-rs/core-plugins/src/marketplace_upgrade_tests.rs
Normal file
633
akode-rs/core-plugins/src/marketplace_upgrade_tests.rs
Normal file
@@ -0,0 +1,633 @@
|
||||
use super::*;
|
||||
use crate::PluginGitMode;
|
||||
use akode_config::CONFIG_TOML_FILE;
|
||||
use akode_config::LoaderOverrides;
|
||||
use akode_config::loader::load_config_layers_state;
|
||||
use akode_exec_server::LOCAL_FS;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
use tempfile::TempDir;
|
||||
|
||||
#[test]
|
||||
fn readback_ignores_unrelated_malformed_marketplace() {
|
||||
let codex_home = TempDir::new().expect("create Codex home");
|
||||
std::fs::write(
|
||||
codex_home.path().join(CONFIG_TOML_FILE),
|
||||
r#"
|
||||
[marketplaces.bad]
|
||||
source_type = "git"
|
||||
source = 17
|
||||
|
||||
[marketplaces.good]
|
||||
source_type = "git"
|
||||
source = "https://github.com/example/good.git"
|
||||
ref = "main"
|
||||
sparse_paths = ["plugins"]
|
||||
last_revision = "abc123"
|
||||
"#,
|
||||
)
|
||||
.expect("write config");
|
||||
|
||||
assert_eq!(
|
||||
read_configured_git_marketplace(&config_reloader(codex_home.path()), "good")
|
||||
.expect("read configured marketplace"),
|
||||
Some(ConfiguredGitMarketplace {
|
||||
name: "good".to_string(),
|
||||
source: "https://github.com/example/good.git".to_string(),
|
||||
ref_name: Some("main".to_string()),
|
||||
sparse_paths: vec!["plugins".to_string()],
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_upgrade_failure_does_not_block_another_marketplace() {
|
||||
let codex_home = TempDir::new().expect("create Codex home");
|
||||
let remote_repo = TempDir::new().expect("create remote repository");
|
||||
init_marketplace_repo(remote_repo.path(), "good");
|
||||
let good_url = url::Url::from_directory_path(remote_repo.path())
|
||||
.expect("remote repository URL")
|
||||
.to_string();
|
||||
let missing_url = url::Url::from_directory_path(codex_home.path().join("missing-repository"))
|
||||
.expect("missing repository URL")
|
||||
.to_string();
|
||||
let config = format!(
|
||||
r#"
|
||||
[marketplaces.bad]
|
||||
source_type = "git"
|
||||
source = {missing_url:?}
|
||||
|
||||
[marketplaces.good]
|
||||
source_type = "git"
|
||||
source = {good_url:?}
|
||||
"#
|
||||
);
|
||||
std::fs::write(codex_home.path().join(CONFIG_TOML_FILE), &config).expect("write config");
|
||||
let reload_config = config_reloader(codex_home.path());
|
||||
let stack = reload_config().expect("load config");
|
||||
|
||||
let outcome = upgrade_configured_git_marketplaces(
|
||||
codex_home.path(),
|
||||
&stack,
|
||||
/*marketplace_name*/ None,
|
||||
&reload_config,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
outcome.selected_marketplaces,
|
||||
vec!["bad".to_string(), "good".to_string()]
|
||||
);
|
||||
assert_eq!(outcome.errors.len(), 1);
|
||||
assert_eq!(outcome.errors[0].marketplace_name, "bad");
|
||||
assert_eq!(
|
||||
outcome.upgraded_roots,
|
||||
vec![
|
||||
AbsolutePathBuf::try_from(marketplace_install_root(codex_home.path()).join("good"))
|
||||
.expect("installed marketplace root")
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(codex_home.path().join(CONFIG_TOML_FILE)).unwrap(),
|
||||
config
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn automatic_marketplace_git_ignores_inherited_repository_configuration() {
|
||||
const CHILD_HOME: &str = "AKODE_MARKETPLACE_GIT_ISOLATION_CHILD_HOME";
|
||||
const CHILD_SOURCE: &str = "AKODE_MARKETPLACE_GIT_ISOLATION_CHILD_SOURCE";
|
||||
|
||||
if let Some(codex_home) = std::env::var_os(CHILD_HOME) {
|
||||
let codex_home = PathBuf::from(codex_home);
|
||||
let source = std::env::var(CHILD_SOURCE).expect("read configured marketplace source");
|
||||
let config =
|
||||
format!("[marketplaces.trusted]\nsource_type = \"git\"\nsource = {source:?}\n");
|
||||
std::fs::write(codex_home.join(CONFIG_TOML_FILE), &config).expect("write config");
|
||||
let reload_config = config_reloader(&codex_home);
|
||||
let stack = reload_config().expect("load config");
|
||||
let outcome = upgrade_configured_git_marketplaces_with_mode(
|
||||
&codex_home,
|
||||
&stack,
|
||||
/*marketplace_name*/ None,
|
||||
PluginGitMode::Automatic,
|
||||
&reload_config,
|
||||
);
|
||||
assert_eq!(
|
||||
outcome,
|
||||
ConfiguredMarketplaceUpgradeOutcome {
|
||||
selected_marketplaces: vec!["trusted".to_string()],
|
||||
upgraded_roots: vec![
|
||||
AbsolutePathBuf::try_from(
|
||||
marketplace_install_root(&codex_home).join("trusted")
|
||||
)
|
||||
.expect("installed marketplace root"),
|
||||
],
|
||||
errors: Vec::new(),
|
||||
}
|
||||
);
|
||||
for (url, mode) in [
|
||||
("global:marketplace", PluginGitMode::Automatic),
|
||||
("manual:marketplace", PluginGitMode::Manual),
|
||||
] {
|
||||
let materialized = crate::loader::materialize_marketplace_plugin_source_with_mode(
|
||||
&codex_home,
|
||||
&crate::marketplace::MarketplacePluginSource::Git {
|
||||
url: url.to_string(),
|
||||
path: None,
|
||||
ref_name: matches!(mode, PluginGitMode::Manual)
|
||||
.then(|| "manual-filter".to_string()),
|
||||
sha: None,
|
||||
},
|
||||
mode,
|
||||
)
|
||||
.expect("materialize automatic or manually installed Git plugin");
|
||||
if matches!(mode, PluginGitMode::Manual) {
|
||||
assert!(
|
||||
std::fs::read_to_string(materialized.path.as_path().join("manual.txt"))
|
||||
.expect("read manually filtered checkout")
|
||||
.starts_with("git version ")
|
||||
);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
let root = TempDir::new().expect("create temporary directory");
|
||||
let project = root.path().join("project");
|
||||
let codex_home = project.join("akode-home");
|
||||
let remote = root.path().join("remote");
|
||||
std::fs::create_dir_all(&codex_home).expect("create Codex home");
|
||||
std::fs::create_dir_all(&remote).expect("create remote marketplace");
|
||||
init_marketplace_repo(&remote, "trusted");
|
||||
run_git(&remote, &["switch", "--create", "manual-filter"]);
|
||||
std::fs::write(
|
||||
remote.join(".gitattributes"),
|
||||
"manual.txt filter=codex-required\n",
|
||||
)
|
||||
.expect("write required manual checkout filter");
|
||||
std::fs::write(remote.join("manual.txt"), "manual checkout")
|
||||
.expect("write manual checkout fixture");
|
||||
run_git(&remote, &["add", "."]);
|
||||
run_git(
|
||||
&remote,
|
||||
&["commit", "-m", "add required manual checkout filter"],
|
||||
);
|
||||
run_git(&remote, &["switch", "-"]);
|
||||
run_git(&project, &["init", "--quiet"]);
|
||||
|
||||
let source = url::Url::from_directory_path(&remote)
|
||||
.expect("remote marketplace URL")
|
||||
.to_string();
|
||||
let untrusted = url::Url::from_directory_path(root.path().join("missing"))
|
||||
.expect("malicious replacement URL")
|
||||
.to_string();
|
||||
let rewrite_key = format!("url.{untrusted}.insteadOf");
|
||||
run_git(&project, &["config", &rewrite_key, &source]);
|
||||
std::fs::write(
|
||||
root.path().join("global.conf"),
|
||||
"[url \"../remote\"]\n\tinsteadOf = global:marketplace\n[protocol \"file\"]\n\tallow = always\n",
|
||||
)
|
||||
.expect("write global Git configuration");
|
||||
std::fs::write(
|
||||
root.path().join("system.conf"),
|
||||
"[protocol \"file\"]\n\tallow = never\n",
|
||||
)
|
||||
.expect("write system Git configuration");
|
||||
let output = Command::new(std::env::current_exe().expect("locate test binary"))
|
||||
.args([
|
||||
"--exact",
|
||||
"marketplace_upgrade::tests::automatic_marketplace_git_ignores_inherited_repository_configuration",
|
||||
"--nocapture",
|
||||
])
|
||||
.current_dir(&project)
|
||||
.env(CHILD_HOME, &codex_home)
|
||||
.env(CHILD_SOURCE, &source)
|
||||
.env("GIT_CONFIG_GLOBAL", "../global.conf")
|
||||
.env("GIT_CONFIG_SYSTEM", "../system.conf")
|
||||
.env("GIT_DIR", project.join(".git"))
|
||||
.env("GIT_CONFIG_COUNT", "3")
|
||||
.env("GIT_CONFIG_KEY_0", &rewrite_key)
|
||||
.env("GIT_CONFIG_VALUE_0", &source)
|
||||
.env("GIT_CONFIG_KEY_1", "url.../remote.insteadOf")
|
||||
.env("GIT_CONFIG_VALUE_1", "manual:marketplace")
|
||||
.env("GIT_CONFIG_KEY_2", "filter.codex-required.smudge")
|
||||
.env("GIT_CONFIG_VALUE_2", "git version")
|
||||
.output()
|
||||
.expect("run marketplace Git isolation regression");
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"marketplace Git isolation failed: {}{}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn upgrade_uses_validated_source_for_git_operations() {
|
||||
let codex_home = TempDir::new().expect("create Codex home");
|
||||
let remote_repo = TempDir::new().expect("create remote repository");
|
||||
init_marketplace_repo(remote_repo.path(), "good");
|
||||
let normalized_url = url::Url::from_directory_path(remote_repo.path())
|
||||
.expect("remote repository URL")
|
||||
.to_string();
|
||||
let raw_source = codex_home.path().join("missing-raw-source");
|
||||
let raw_source = raw_source.to_string_lossy().into_owned();
|
||||
let config = format!(
|
||||
r#"
|
||||
[marketplaces.good]
|
||||
source_type = "git"
|
||||
source = {raw_source:?}
|
||||
ref = "missing-ref"
|
||||
"#
|
||||
);
|
||||
std::fs::write(codex_home.path().join(CONFIG_TOML_FILE), config).expect("write config");
|
||||
let marketplace = ConfiguredGitMarketplace {
|
||||
name: "good".to_string(),
|
||||
source: raw_source,
|
||||
ref_name: Some("missing-ref".to_string()),
|
||||
sparse_paths: Vec::new(),
|
||||
};
|
||||
let normalized_source = MarketplaceSource::Git {
|
||||
url: normalized_url,
|
||||
ref_name: Some("HEAD".to_string()),
|
||||
};
|
||||
let install_root = marketplace_install_root(codex_home.path());
|
||||
|
||||
let upgraded_root = upgrade_configured_git_marketplace(
|
||||
codex_home.path(),
|
||||
&install_root,
|
||||
&marketplace,
|
||||
&config_reloader(codex_home.path()),
|
||||
Some(&normalized_source),
|
||||
PluginGitMode::Manual,
|
||||
)
|
||||
.expect("upgrade should use the validated source")
|
||||
.expect("marketplace should be upgraded");
|
||||
|
||||
assert_eq!(
|
||||
upgraded_root,
|
||||
AbsolutePathBuf::try_from(install_root.join("good")).expect("installed marketplace root")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn up_to_date_fast_path_validates_marketplace_name() {
|
||||
const REVISION: &str = "0123456789abcdef0123456789abcdef01234567";
|
||||
let codex_home = TempDir::new().expect("create Codex home");
|
||||
let install_root = marketplace_install_root(codex_home.path());
|
||||
let destination = install_root.join("good");
|
||||
let manifest_dir = destination.join(".agents/plugins");
|
||||
std::fs::create_dir_all(&manifest_dir).expect("create marketplace manifest directory");
|
||||
std::fs::write(
|
||||
manifest_dir.join("marketplace.json"),
|
||||
r#"{"name":"wrong","plugins":[]}"#,
|
||||
)
|
||||
.expect("write mismatched marketplace manifest");
|
||||
let missing_source = codex_home.path().join("missing-source");
|
||||
let missing_source = missing_source.to_string_lossy().into_owned();
|
||||
let marketplace = ConfiguredGitMarketplace {
|
||||
name: "good".to_string(),
|
||||
source: missing_source.clone(),
|
||||
ref_name: Some(REVISION.to_string()),
|
||||
sparse_paths: Vec::new(),
|
||||
};
|
||||
super::activation::write_installed_marketplace_metadata(&destination, &marketplace, REVISION)
|
||||
.expect("write installed marketplace metadata");
|
||||
let normalized_source = MarketplaceSource::Git {
|
||||
url: missing_source,
|
||||
ref_name: Some(REVISION.to_string()),
|
||||
};
|
||||
|
||||
let err = upgrade_configured_git_marketplace(
|
||||
codex_home.path(),
|
||||
&install_root,
|
||||
&marketplace,
|
||||
&config_reloader(codex_home.path()),
|
||||
Some(&normalized_source),
|
||||
PluginGitMode::Manual,
|
||||
)
|
||||
.expect_err("mismatched marketplace name must not use the up-to-date fast path");
|
||||
|
||||
assert!(err.contains("git clone marketplace source failed"));
|
||||
assert_eq!(
|
||||
std::fs::read_dir(install_root.join(".staging"))
|
||||
.expect("read marketplace staging directory")
|
||||
.count(),
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_activation_restores_newer_concurrently_installed_marketplace() {
|
||||
const INITIAL_REVISION: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
|
||||
const STALE_REVISION: &str = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
|
||||
const NEWER_REVISION: &str = "cccccccccccccccccccccccccccccccccccccccc";
|
||||
|
||||
let codex_home = TempDir::new().expect("create Codex home");
|
||||
let install_root = marketplace_install_root(codex_home.path());
|
||||
let destination = install_root.join("good");
|
||||
std::fs::create_dir_all(&destination).expect("create installed marketplace root");
|
||||
let marketplace = ConfiguredGitMarketplace {
|
||||
name: "good".to_string(),
|
||||
source: "https://github.com/example/good.git".to_string(),
|
||||
ref_name: Some("main".to_string()),
|
||||
sparse_paths: Vec::new(),
|
||||
};
|
||||
super::activation::write_installed_marketplace_metadata(
|
||||
&destination,
|
||||
&marketplace,
|
||||
INITIAL_REVISION,
|
||||
)
|
||||
.expect("write initial installed marketplace metadata");
|
||||
let previous_snapshot =
|
||||
super::activation::read_installed_marketplace_snapshot(&destination, &marketplace.name);
|
||||
|
||||
std::fs::write(destination.join("marker.txt"), "newer snapshot")
|
||||
.expect("write newer installed marketplace snapshot");
|
||||
super::activation::write_installed_marketplace_metadata(
|
||||
&destination,
|
||||
&marketplace,
|
||||
NEWER_REVISION,
|
||||
)
|
||||
.expect("write newer installed marketplace metadata");
|
||||
|
||||
let staged_dir =
|
||||
MarketplaceStagingDir::new(&install_root).expect("create stale upgrade staging directory");
|
||||
std::fs::create_dir_all(staged_dir.path()).expect("create stale upgrade checkout");
|
||||
std::fs::write(staged_dir.path().join("marker.txt"), "stale snapshot")
|
||||
.expect("write stale staged marketplace snapshot");
|
||||
super::activation::write_installed_marketplace_metadata(
|
||||
staged_dir.path(),
|
||||
&marketplace,
|
||||
STALE_REVISION,
|
||||
)
|
||||
.expect("write stale staged marketplace metadata");
|
||||
|
||||
let err = super::activation::activate_marketplace_root(
|
||||
&destination,
|
||||
staged_dir.path(),
|
||||
&previous_snapshot,
|
||||
|| Ok(()),
|
||||
)
|
||||
.expect_err("stale upgrade must not replace a newer installed snapshot");
|
||||
|
||||
assert_eq!(
|
||||
err,
|
||||
"installed marketplace `good` changed while auto-upgrade was in flight"
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(destination.join("marker.txt"))
|
||||
.expect("read restored marketplace snapshot"),
|
||||
"newer snapshot"
|
||||
);
|
||||
let restored_snapshot =
|
||||
super::activation::read_installed_marketplace_snapshot(&destination, &marketplace.name);
|
||||
assert!(super::activation::installed_marketplace_metadata_matches(
|
||||
&restored_snapshot,
|
||||
&marketplace,
|
||||
NEWER_REVISION
|
||||
));
|
||||
drop(staged_dir);
|
||||
assert_eq!(
|
||||
std::fs::read_dir(install_root.join(".staging"))
|
||||
.expect("read marketplace staging directory")
|
||||
.count(),
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
fn config_reloader(codex_home: &Path) -> ConfigLayerReload {
|
||||
let codex_home = codex_home.to_path_buf();
|
||||
let options = LoaderOverrides {
|
||||
system_config_path: Some(codex_home.join("system.toml")),
|
||||
managed_config_path: Some(codex_home.join("managed.toml")),
|
||||
system_requirements_path: Some(codex_home.join("requirements.toml")),
|
||||
..LoaderOverrides::without_managed_config_for_tests()
|
||||
};
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.expect("create config loading runtime");
|
||||
Arc::new(move || {
|
||||
runtime.block_on(load_config_layers_state(
|
||||
LOCAL_FS.as_ref(),
|
||||
&codex_home,
|
||||
Some(AbsolutePathBuf::try_from(codex_home.join("project"))?),
|
||||
&[],
|
||||
options.clone(),
|
||||
&akode_config::NoopThreadConfigLoader,
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
fn system_marketplace_stack(codex_home: &Path, system: &str, user: &str) -> ConfigLayerStack {
|
||||
let system_file = AbsolutePathBuf::try_from(codex_home.join("system.toml")).unwrap();
|
||||
std::fs::write(&system_file, system).unwrap();
|
||||
if !user.is_empty() {
|
||||
std::fs::write(codex_home.join(CONFIG_TOML_FILE), user).unwrap();
|
||||
}
|
||||
config_reloader(codex_home)().expect("load system and user config")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn system_marketplace_downloads_and_updates_without_writing_user_config() {
|
||||
for user_config in ["", "[marketplaces.good]\nsparse_paths = []\n"] {
|
||||
let codex_home = TempDir::new().unwrap();
|
||||
let remote = TempDir::new().unwrap();
|
||||
init_marketplace_repo(remote.path(), "good");
|
||||
run_git(remote.path(), &["checkout", "-b", "release"]);
|
||||
std::fs::write(remote.path().join("marker"), "release").unwrap();
|
||||
run_git(remote.path(), &["add", "."]);
|
||||
run_git(remote.path(), &["commit", "-m", "release"]);
|
||||
run_git(remote.path(), &["checkout", "-b", "other"]);
|
||||
std::fs::write(remote.path().join("marker"), "wrong branch").unwrap();
|
||||
run_git(remote.path(), &["commit", "-am", "other"]);
|
||||
let source = url::Url::from_directory_path(remote.path())
|
||||
.unwrap()
|
||||
.to_string();
|
||||
let system = format!(
|
||||
"[marketplaces.good]\nsource_type = \"git\"\nsource = {source:?}\nref = \"release\"\n"
|
||||
);
|
||||
let stack = system_marketplace_stack(codex_home.path(), &system, user_config);
|
||||
let reload_config = config_reloader(codex_home.path());
|
||||
let root =
|
||||
AbsolutePathBuf::try_from(marketplace_install_root(codex_home.path()).join("good"))
|
||||
.unwrap();
|
||||
for marker in ["release", "updated"] {
|
||||
if marker == "updated" {
|
||||
run_git(remote.path(), &["checkout", "release"]);
|
||||
std::fs::write(remote.path().join("marker"), marker).unwrap();
|
||||
run_git(remote.path(), &["commit", "-am", "update release"]);
|
||||
}
|
||||
assert_eq!(
|
||||
upgrade_configured_git_marketplaces_with_mode(
|
||||
codex_home.path(),
|
||||
&stack,
|
||||
Some("good"),
|
||||
PluginGitMode::Automatic,
|
||||
&reload_config,
|
||||
),
|
||||
ConfiguredMarketplaceUpgradeOutcome {
|
||||
selected_marketplaces: vec!["good".to_string()],
|
||||
upgraded_roots: vec![root.clone()],
|
||||
errors: Vec::new(),
|
||||
},
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(root.join("marker")).unwrap(),
|
||||
marker
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(codex_home.path().join("system.toml")).unwrap(),
|
||||
system
|
||||
);
|
||||
let user_file = codex_home.path().join(CONFIG_TOML_FILE);
|
||||
if user_config.is_empty() {
|
||||
assert!(!user_file.exists());
|
||||
} else {
|
||||
assert_eq!(std::fs::read_to_string(user_file).unwrap(), user_config);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changed_config_rolls_back_marketplace_activation() {
|
||||
let codex_home = TempDir::new().unwrap();
|
||||
let remote = TempDir::new().unwrap();
|
||||
init_marketplace_repo(remote.path(), "good");
|
||||
let source = url::Url::from_directory_path(remote.path())
|
||||
.unwrap()
|
||||
.to_string();
|
||||
let system = format!("[marketplaces.good]\nsource_type = \"git\"\nsource = {source:?}\n");
|
||||
let stack = system_marketplace_stack(codex_home.path(), &system, "");
|
||||
let reload_config = config_reloader(codex_home.path());
|
||||
let initial = upgrade_configured_git_marketplaces(
|
||||
codex_home.path(),
|
||||
&stack,
|
||||
Some("good"),
|
||||
&reload_config,
|
||||
);
|
||||
assert!(initial.all_succeeded());
|
||||
let root = &initial.upgraded_roots[0];
|
||||
let original_metadata = std::fs::read(root.join(".codex-marketplace-install.json")).unwrap();
|
||||
std::fs::write(remote.path().join("new-file"), "new revision").unwrap();
|
||||
run_git(remote.path(), &["add", "."]);
|
||||
run_git(remote.path(), &["commit", "-m", "update"]);
|
||||
for (file, changed_config) in [
|
||||
("system.toml", format!("{system}ref = \"different\"\n")),
|
||||
("system.toml", String::new()),
|
||||
(
|
||||
CONFIG_TOML_FILE,
|
||||
"[marketplaces.good]\nref = \"user-override\"\n".to_string(),
|
||||
),
|
||||
(CONFIG_TOML_FILE, "invalid = [".to_string()),
|
||||
] {
|
||||
std::fs::write(codex_home.path().join("system.toml"), &system).unwrap();
|
||||
std::fs::write(codex_home.path().join(file), changed_config).unwrap();
|
||||
let outcome = upgrade_configured_git_marketplaces(
|
||||
codex_home.path(),
|
||||
&stack,
|
||||
Some("good"),
|
||||
&reload_config,
|
||||
);
|
||||
assert_eq!(outcome.upgraded_roots, Vec::new());
|
||||
assert_eq!(outcome.errors.len(), 1);
|
||||
assert!(!root.join("new-file").exists());
|
||||
assert_eq!(
|
||||
std::fs::read(root.join(".codex-marketplace-install.json")).unwrap(),
|
||||
original_metadata
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn automatic_upgrade_skips_known_name_mismatch_until_the_ref_or_revision_changes() {
|
||||
let codex_home = TempDir::new().unwrap();
|
||||
let home = codex_home.path();
|
||||
let remote = TempDir::new().unwrap();
|
||||
init_marketplace_repo(remote.path(), "renamed");
|
||||
let config = format!(
|
||||
"[marketplaces.original]\nsource_type = 'git'\nsource = {:?}\n",
|
||||
remote.path().to_str().unwrap()
|
||||
);
|
||||
let config_path = home.join(CONFIG_TOML_FILE);
|
||||
std::fs::write(&config_path, &config).unwrap();
|
||||
let reload = config_reloader(home);
|
||||
let upgrade = |mode| {
|
||||
upgrade_configured_git_marketplaces_with_mode(
|
||||
home,
|
||||
&reload().unwrap(),
|
||||
/*marketplace_name*/ None,
|
||||
mode,
|
||||
&reload,
|
||||
)
|
||||
};
|
||||
|
||||
let first = upgrade(PluginGitMode::Automatic);
|
||||
assert_eq!(first.errors.len(), 1);
|
||||
assert!(
|
||||
first.errors[0]
|
||||
.message
|
||||
.contains("upgraded marketplace name `renamed`")
|
||||
);
|
||||
|
||||
// Only a fresh checkout recreates the staging directory.
|
||||
let staging = marketplace_install_root(home).join(".staging");
|
||||
std::fs::remove_dir(&staging).unwrap();
|
||||
assert_eq!(upgrade(PluginGitMode::Automatic).errors, first.errors);
|
||||
assert!(!staging.exists());
|
||||
assert_eq!(upgrade(PluginGitMode::Manual).errors, first.errors);
|
||||
assert!(staging.is_dir());
|
||||
|
||||
// A different ref still needs a checkout even when it points to the same commit.
|
||||
run_git(remote.path(), &["checkout", "-b", "same-revision"]);
|
||||
std::fs::write(&config_path, format!("{config}ref = 'same-revision'\n")).unwrap();
|
||||
std::fs::remove_dir(&staging).unwrap();
|
||||
assert_eq!(upgrade(PluginGitMode::Automatic).errors, first.errors);
|
||||
assert!(staging.is_dir());
|
||||
|
||||
std::fs::write(
|
||||
remote.path().join(".agents/plugins/marketplace.json"),
|
||||
r#"{"name":"original","plugins":[]}"#,
|
||||
)
|
||||
.unwrap();
|
||||
run_git(
|
||||
remote.path(),
|
||||
&["commit", "-am", "restore marketplace name"],
|
||||
);
|
||||
let recovered = upgrade(PluginGitMode::Automatic);
|
||||
assert!(recovered.errors.is_empty());
|
||||
assert_eq!(recovered.upgraded_roots.len(), 1);
|
||||
}
|
||||
|
||||
fn init_marketplace_repo(repo: &Path, marketplace_name: &str) {
|
||||
let manifest_dir = repo.join(".agents/plugins");
|
||||
std::fs::create_dir_all(&manifest_dir).expect("create marketplace manifest directory");
|
||||
std::fs::write(
|
||||
manifest_dir.join("marketplace.json"),
|
||||
format!(r#"{{"name":"{marketplace_name}","plugins":[]}}"#),
|
||||
)
|
||||
.expect("write marketplace manifest");
|
||||
run_git(repo, &["init"]);
|
||||
run_git(repo, &["config", "user.email", "codex-test@example.com"]);
|
||||
run_git(repo, &["config", "user.name", "Codex Test"]);
|
||||
run_git(repo, &["add", "."]);
|
||||
run_git(repo, &["commit", "-m", "initial"]);
|
||||
}
|
||||
|
||||
fn run_git(repo: &Path, args: &[&str]) {
|
||||
let output = Command::new("git")
|
||||
.arg("-C")
|
||||
.arg(repo)
|
||||
.args(args)
|
||||
.output()
|
||||
.expect("run git");
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"git {args:?} failed: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
}
|
||||
187
akode-rs/core-plugins/src/npm_source.rs
Normal file
187
akode-rs/core-plugins/src/npm_source.rs
Normal file
@@ -0,0 +1,187 @@
|
||||
use crate::plugin_bundle_archive::unpack_plugin_bundle_tar_gz;
|
||||
use akode_utils_absolute_path::AbsolutePathBuf;
|
||||
use serde::Deserialize;
|
||||
use std::ffi::OsStr;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use tempfile::TempDir;
|
||||
|
||||
const NPM_PLUGIN_SOURCE_STAGING_DIR: &str = "plugins/.marketplace-plugin-source-staging";
|
||||
const NPM_PLUGIN_SOURCE_MAX_ARCHIVE_BYTES: u64 = 50 * 1024 * 1024;
|
||||
const NPM_PLUGIN_SOURCE_MAX_EXTRACTED_BYTES: u64 = 250 * 1024 * 1024;
|
||||
const NPM_PACKAGE_ARCHIVE_ROOT: &str = "package";
|
||||
|
||||
pub(crate) fn materialize_npm_plugin_source(
|
||||
codex_home: &Path,
|
||||
package: &str,
|
||||
version: Option<&str>,
|
||||
registry: Option<&str>,
|
||||
) -> Result<(AbsolutePathBuf, TempDir), String> {
|
||||
materialize_npm_plugin_source_with_command(
|
||||
codex_home,
|
||||
package,
|
||||
version,
|
||||
registry,
|
||||
OsStr::new(npm_command()),
|
||||
)
|
||||
}
|
||||
|
||||
fn materialize_npm_plugin_source_with_command(
|
||||
codex_home: &Path,
|
||||
package: &str,
|
||||
version: Option<&str>,
|
||||
registry: Option<&str>,
|
||||
npm_command: &OsStr,
|
||||
) -> Result<(AbsolutePathBuf, TempDir), String> {
|
||||
let staging_root = codex_home.join(NPM_PLUGIN_SOURCE_STAGING_DIR);
|
||||
fs::create_dir_all(&staging_root).map_err(|err| {
|
||||
format!(
|
||||
"failed to create marketplace plugin source staging directory {}: {err}",
|
||||
staging_root.display()
|
||||
)
|
||||
})?;
|
||||
let tempdir = tempfile::Builder::new()
|
||||
.prefix("marketplace-plugin-source-")
|
||||
.tempdir_in(&staging_root)
|
||||
.map_err(|err| {
|
||||
format!(
|
||||
"failed to create marketplace plugin source staging directory in {}: {err}",
|
||||
staging_root.display()
|
||||
)
|
||||
})?;
|
||||
|
||||
pack_npm_package(tempdir.path(), package, version, registry, npm_command)?;
|
||||
let archive_path = find_npm_package_archive(tempdir.path())?;
|
||||
let archive_bytes = read_npm_package_archive(&archive_path)?;
|
||||
|
||||
let extraction_root = tempdir.path().join("extracted");
|
||||
unpack_plugin_bundle_tar_gz(
|
||||
&archive_bytes,
|
||||
&extraction_root,
|
||||
NPM_PLUGIN_SOURCE_MAX_EXTRACTED_BYTES,
|
||||
)
|
||||
.map_err(|err| format!("failed to extract npm plugin package: {err}"))?;
|
||||
let plugin_root = extraction_root.join(NPM_PACKAGE_ARCHIVE_ROOT);
|
||||
if !plugin_root.is_dir() {
|
||||
return Err(format!(
|
||||
"npm pack completed without creating plugin package directory {}",
|
||||
plugin_root.display()
|
||||
));
|
||||
}
|
||||
validate_npm_package_metadata(&plugin_root, package)?;
|
||||
let plugin_root = AbsolutePathBuf::try_from(plugin_root)
|
||||
.map_err(|err| format!("failed to resolve materialized plugin source path: {err}"))?;
|
||||
Ok((plugin_root, tempdir))
|
||||
}
|
||||
|
||||
fn pack_npm_package(
|
||||
destination: &Path,
|
||||
package: &str,
|
||||
version: Option<&str>,
|
||||
registry: Option<&str>,
|
||||
npm_command: &OsStr,
|
||||
) -> Result<(), String> {
|
||||
let package_spec = version.map_or_else(
|
||||
|| package.to_string(),
|
||||
|version| format!("{package}@{version}"),
|
||||
);
|
||||
let mut command = akode_utils_process::background_command(npm_command);
|
||||
command
|
||||
.current_dir(destination)
|
||||
.arg("pack")
|
||||
.arg("--ignore-scripts")
|
||||
.arg("--pack-destination")
|
||||
.arg(destination);
|
||||
if let Some(registry) = registry {
|
||||
command.arg("--registry").arg(registry);
|
||||
}
|
||||
command.arg("--").arg(package_spec);
|
||||
|
||||
let output = command
|
||||
.output()
|
||||
.map_err(|err| format!("failed to run npm pack: {err}"))?;
|
||||
if output.status.success() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
Err(format!(
|
||||
"npm pack failed with status {}\nstdout:\n{}\nstderr:\n{}",
|
||||
output.status,
|
||||
String::from_utf8_lossy(&output.stdout).trim(),
|
||||
String::from_utf8_lossy(&output.stderr).trim()
|
||||
))
|
||||
}
|
||||
|
||||
fn find_npm_package_archive(destination: &Path) -> Result<PathBuf, String> {
|
||||
let mut archives = fs::read_dir(destination)
|
||||
.map_err(|err| format!("failed to read npm pack destination: {err}"))?
|
||||
.filter_map(std::result::Result::ok)
|
||||
.filter_map(|entry| {
|
||||
let path = entry.path();
|
||||
let is_file = entry.file_type().is_ok_and(|file_type| file_type.is_file());
|
||||
(is_file && path.extension() == Some(OsStr::new("tgz"))).then_some(path)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
if archives.len() != 1 {
|
||||
return Err(format!(
|
||||
"npm pack completed with {} package archives; expected exactly one",
|
||||
archives.len()
|
||||
));
|
||||
}
|
||||
Ok(archives.remove(0))
|
||||
}
|
||||
|
||||
fn read_npm_package_archive(archive_path: &Path) -> Result<Vec<u8>, String> {
|
||||
let archive_size = fs::metadata(archive_path)
|
||||
.map_err(|err| format!("failed to inspect npm package archive: {err}"))?
|
||||
.len();
|
||||
if archive_size > NPM_PLUGIN_SOURCE_MAX_ARCHIVE_BYTES {
|
||||
return Err(format!(
|
||||
"npm package archive is {archive_size} bytes, exceeding maximum size of {NPM_PLUGIN_SOURCE_MAX_ARCHIVE_BYTES} bytes"
|
||||
));
|
||||
}
|
||||
fs::read(archive_path).map_err(|err| format!("failed to read npm package archive: {err}"))
|
||||
}
|
||||
|
||||
fn validate_npm_package_metadata(plugin_root: &Path, package: &str) -> Result<(), String> {
|
||||
#[derive(Deserialize)]
|
||||
struct NpmPackageMetadata {
|
||||
name: String,
|
||||
}
|
||||
|
||||
let package_json_path = plugin_root.join("package.json");
|
||||
let package_json = fs::read_to_string(&package_json_path).map_err(|err| {
|
||||
format!(
|
||||
"failed to read npm plugin package metadata {}: {err}",
|
||||
package_json_path.display()
|
||||
)
|
||||
})?;
|
||||
let metadata: NpmPackageMetadata = serde_json::from_str(&package_json).map_err(|err| {
|
||||
format!(
|
||||
"failed to parse npm plugin package metadata {}: {err}",
|
||||
package_json_path.display()
|
||||
)
|
||||
})?;
|
||||
if metadata.name != package {
|
||||
return Err(format!(
|
||||
"npm plugin package name '{}' does not match requested package '{package}'",
|
||||
metadata.name
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn npm_command() -> &'static str {
|
||||
"npm.cmd"
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
fn npm_command() -> &'static str {
|
||||
"npm"
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
#[path = "npm_source_tests.rs"]
|
||||
mod tests;
|
||||
104
akode-rs/core-plugins/src/npm_source_tests.rs
Normal file
104
akode-rs/core-plugins/src/npm_source_tests.rs
Normal file
@@ -0,0 +1,104 @@
|
||||
use super::*;
|
||||
use flate2::Compression;
|
||||
use flate2::write::GzEncoder;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::io::Cursor;
|
||||
use std::io::Write;
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn materialize_npm_plugin_source_uses_packed_package_root() {
|
||||
let codex_home = tempfile::tempdir().expect("create codex home");
|
||||
let fake_npm_dir = tempfile::tempdir().expect("create fake npm directory");
|
||||
let archive_bytes =
|
||||
npm_package_archive_bytes("@acme/plugin", "1.2.0").expect("build fixture archive");
|
||||
let archive_path = fake_npm_dir.path().join("fixture.tgz");
|
||||
fs::write(&archive_path, &archive_bytes).expect("write fixture archive");
|
||||
let fake_npm = fake_npm_dir.path().join("npm");
|
||||
akode_utils_cargo_bin::write_executable(
|
||||
&fake_npm,
|
||||
&format!(
|
||||
r#"#!/bin/sh
|
||||
destination=""
|
||||
previous=""
|
||||
for argument in "$@"; do
|
||||
if [ "$previous" = "--pack-destination" ]; then
|
||||
destination="$argument"
|
||||
fi
|
||||
previous="$argument"
|
||||
done
|
||||
cp "{}" "$destination/acme-plugin-1.2.0.tgz"
|
||||
printf '%s\n' "$@" > "$destination/args.txt"
|
||||
pwd > "$destination/pwd.txt"
|
||||
"#,
|
||||
archive_path.display()
|
||||
),
|
||||
)
|
||||
.expect("write fake npm");
|
||||
|
||||
let (plugin_root, tempdir) = materialize_npm_plugin_source_with_command(
|
||||
codex_home.path(),
|
||||
"@acme/plugin",
|
||||
Some("^1.2.0"),
|
||||
Some("https://npm.example.com"),
|
||||
fake_npm.as_os_str(),
|
||||
)
|
||||
.expect("materialize npm source");
|
||||
|
||||
assert_eq!(
|
||||
plugin_root.as_path(),
|
||||
tempdir.path().join("extracted/package")
|
||||
);
|
||||
assert!(
|
||||
plugin_root
|
||||
.as_path()
|
||||
.join(".codex-plugin/plugin.json")
|
||||
.is_file()
|
||||
);
|
||||
let args = fs::read_to_string(tempdir.path().join("args.txt")).expect("read npm arguments");
|
||||
assert!(args.contains("pack"));
|
||||
assert!(args.contains("--ignore-scripts"));
|
||||
assert!(args.contains("--registry"));
|
||||
assert!(args.contains("https://npm.example.com"));
|
||||
assert!(args.contains("@acme/plugin@^1.2.0"));
|
||||
assert!(!args.contains("install"));
|
||||
let npm_working_directory = fs::canonicalize(
|
||||
fs::read_to_string(tempdir.path().join("pwd.txt"))
|
||||
.expect("read npm working directory")
|
||||
.trim(),
|
||||
)
|
||||
.expect("canonicalize npm working directory");
|
||||
assert_eq!(
|
||||
npm_working_directory,
|
||||
fs::canonicalize(tempdir.path()).expect("canonicalize tempdir")
|
||||
);
|
||||
}
|
||||
|
||||
fn npm_package_archive_bytes(package: &str, version: &str) -> std::io::Result<Vec<u8>> {
|
||||
let encoder = GzEncoder::new(Vec::new(), Compression::default());
|
||||
let mut archive = tar::Builder::new(encoder);
|
||||
append_archive_file(
|
||||
&mut archive,
|
||||
"package/package.json",
|
||||
format!(r#"{{"name":"{package}","version":"{version}"}}"#).as_bytes(),
|
||||
)?;
|
||||
append_archive_file(
|
||||
&mut archive,
|
||||
"package/.codex-plugin/plugin.json",
|
||||
br#"{"name":"plugin"}"#,
|
||||
)?;
|
||||
let encoder = archive.into_inner()?;
|
||||
encoder.finish()
|
||||
}
|
||||
|
||||
fn append_archive_file<W: Write>(
|
||||
archive: &mut tar::Builder<W>,
|
||||
path: &str,
|
||||
contents: &[u8],
|
||||
) -> std::io::Result<()> {
|
||||
let mut header = tar::Header::new_gnu();
|
||||
header.set_size(contents.len() as u64);
|
||||
header.set_mode(0o644);
|
||||
header.set_cksum();
|
||||
archive.append_data(&mut header, path, Cursor::new(contents))
|
||||
}
|
||||
164
akode-rs/core-plugins/src/plugin_bundle_archive.rs
Normal file
164
akode-rs/core-plugins/src/plugin_bundle_archive.rs
Normal file
@@ -0,0 +1,164 @@
|
||||
use flate2::read::GzDecoder;
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::io::Read;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use tar::Archive;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub(crate) enum PluginBundleUnpackError {
|
||||
#[error(
|
||||
"plugin bundle extracted size would be {bytes} bytes, exceeding maximum total size of {max_bytes} bytes"
|
||||
)]
|
||||
ExtractedBundleTooLarge { bytes: u64, max_bytes: u64 },
|
||||
|
||||
#[error("{context}: {source}")]
|
||||
Io {
|
||||
context: &'static str,
|
||||
#[source]
|
||||
source: io::Error,
|
||||
},
|
||||
|
||||
#[error("{0}")]
|
||||
InvalidBundle(String),
|
||||
}
|
||||
|
||||
impl PluginBundleUnpackError {
|
||||
fn io(context: &'static str, source: io::Error) -> Self {
|
||||
Self::Io { context, source }
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn unpack_plugin_bundle_tar_gz(
|
||||
bytes: &[u8],
|
||||
destination: &Path,
|
||||
max_total_bytes: u64,
|
||||
) -> Result<(), PluginBundleUnpackError> {
|
||||
fs::create_dir_all(destination).map_err(|source| {
|
||||
PluginBundleUnpackError::io(
|
||||
"failed to create plugin bundle extraction directory",
|
||||
source,
|
||||
)
|
||||
})?;
|
||||
|
||||
let archive = GzDecoder::new(std::io::Cursor::new(bytes));
|
||||
let mut archive = Archive::new(archive);
|
||||
unpack_plugin_bundle_tar(&mut archive, destination, max_total_bytes)
|
||||
}
|
||||
|
||||
fn unpack_plugin_bundle_tar<R: Read>(
|
||||
archive: &mut Archive<R>,
|
||||
destination: &Path,
|
||||
max_total_bytes: u64,
|
||||
) -> Result<(), PluginBundleUnpackError> {
|
||||
let mut extracted_bytes = 0u64;
|
||||
let entries = archive.entries().map_err(|source| {
|
||||
PluginBundleUnpackError::io("failed to read plugin bundle tar", source)
|
||||
})?;
|
||||
for entry in entries {
|
||||
let mut entry = entry.map_err(|source| {
|
||||
PluginBundleUnpackError::io("failed to read plugin bundle tar entry", source)
|
||||
})?;
|
||||
let entry_type = entry.header().entry_type();
|
||||
let entry_size = entry.size();
|
||||
let entry_path = entry
|
||||
.path()
|
||||
.map_err(|source| {
|
||||
PluginBundleUnpackError::io("failed to read plugin bundle tar entry path", source)
|
||||
})?
|
||||
.into_owned();
|
||||
let output_path = checked_tar_output_path(destination, &entry_path)?;
|
||||
|
||||
if entry_type.is_dir() {
|
||||
fs::create_dir_all(&output_path).map_err(|source| {
|
||||
PluginBundleUnpackError::io("failed to create plugin bundle directory", source)
|
||||
})?;
|
||||
continue;
|
||||
}
|
||||
|
||||
if entry_type.is_file() {
|
||||
enforce_total_extracted_size(entry_size, &mut extracted_bytes, max_total_bytes)?;
|
||||
let Some(parent) = output_path.parent() else {
|
||||
return Err(PluginBundleUnpackError::InvalidBundle(format!(
|
||||
"plugin bundle output path has no parent: {}",
|
||||
output_path.display()
|
||||
)));
|
||||
};
|
||||
fs::create_dir_all(parent).map_err(|source| {
|
||||
PluginBundleUnpackError::io("failed to create plugin bundle directory", source)
|
||||
})?;
|
||||
entry.unpack(&output_path).map_err(|source| {
|
||||
PluginBundleUnpackError::io("failed to unpack plugin bundle entry", source)
|
||||
})?;
|
||||
continue;
|
||||
}
|
||||
|
||||
if entry_type.is_hard_link() || entry_type.is_symlink() {
|
||||
return Err(PluginBundleUnpackError::InvalidBundle(format!(
|
||||
"plugin bundle tar entry `{}` is a link",
|
||||
entry_path.display()
|
||||
)));
|
||||
}
|
||||
|
||||
return Err(PluginBundleUnpackError::InvalidBundle(format!(
|
||||
"plugin bundle tar entry `{}` has unsupported type {:?}",
|
||||
entry_path.display(),
|
||||
entry_type
|
||||
)));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn checked_tar_output_path(
|
||||
destination: &Path,
|
||||
entry_name: &Path,
|
||||
) -> Result<PathBuf, PluginBundleUnpackError> {
|
||||
let mut output_path = destination.to_path_buf();
|
||||
let mut has_component = false;
|
||||
for component in entry_name.components() {
|
||||
match component {
|
||||
std::path::Component::Normal(component) => {
|
||||
has_component = true;
|
||||
output_path.push(component);
|
||||
}
|
||||
std::path::Component::CurDir => {}
|
||||
std::path::Component::ParentDir
|
||||
| std::path::Component::RootDir
|
||||
| std::path::Component::Prefix(_) => {
|
||||
return Err(PluginBundleUnpackError::InvalidBundle(format!(
|
||||
"plugin bundle tar entry `{}` escapes extraction root",
|
||||
entry_name.display()
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
if !has_component {
|
||||
return Err(PluginBundleUnpackError::InvalidBundle(
|
||||
"plugin bundle tar entry has an empty path".to_string(),
|
||||
));
|
||||
}
|
||||
Ok(output_path)
|
||||
}
|
||||
|
||||
fn enforce_total_extracted_size(
|
||||
entry_size: u64,
|
||||
extracted_bytes: &mut u64,
|
||||
max_total_bytes: u64,
|
||||
) -> Result<(), PluginBundleUnpackError> {
|
||||
let next_total = extracted_bytes.checked_add(entry_size).ok_or(
|
||||
PluginBundleUnpackError::ExtractedBundleTooLarge {
|
||||
bytes: u64::MAX,
|
||||
max_bytes: max_total_bytes,
|
||||
},
|
||||
)?;
|
||||
if next_total > max_total_bytes {
|
||||
return Err(PluginBundleUnpackError::ExtractedBundleTooLarge {
|
||||
bytes: next_total,
|
||||
max_bytes: max_total_bytes,
|
||||
});
|
||||
}
|
||||
*extracted_bytes = next_total;
|
||||
Ok(())
|
||||
}
|
||||
46
akode-rs/core-plugins/src/provider.rs
Normal file
46
akode-rs/core-plugins/src/provider.rs
Normal file
@@ -0,0 +1,46 @@
|
||||
//! Plugin catalog listing interface and source inputs used to request snapshots.
|
||||
|
||||
use crate::ExecutorPluginProviderError;
|
||||
use crate::PluginCatalog;
|
||||
use akode_exec_server::ExecutorCapabilityDiscoveryV2Snapshot;
|
||||
use akode_mcp::McpResourceClient;
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use thiserror::Error;
|
||||
|
||||
/// Identifiers, MCP client, and executor inventories used to request one catalog snapshot.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct PluginListQuery {
|
||||
pub thread_id: String,
|
||||
pub turn_id: String,
|
||||
pub mcp_resources: Option<Arc<McpResourceClient>>,
|
||||
/// Already-acquired V2 inventories; empty for cloud listing.
|
||||
pub snapshots: Vec<ExecutorCapabilityDiscoveryV2Snapshot>,
|
||||
}
|
||||
|
||||
/// Failure to list plugin metadata.
|
||||
#[derive(Debug, Error)]
|
||||
pub enum PluginProviderError {
|
||||
#[error(transparent)]
|
||||
Executor(#[from] ExecutorPluginProviderError),
|
||||
#[error("{0}")]
|
||||
Message(String),
|
||||
}
|
||||
|
||||
pub type PluginProviderResult<T> = Result<T, PluginProviderError>;
|
||||
|
||||
pub type PluginProviderFuture<'a, T> =
|
||||
Pin<Box<dyn Future<Output = PluginProviderResult<T>> + Send + 'a>>;
|
||||
|
||||
/// Lists plugin metadata without resolving packages or binding filesystems.
|
||||
///
|
||||
/// Cloud providers implement `list`; executor listing is not yet supported.
|
||||
/// Package access uses [`crate::ExecutorPluginProvider::resolve_bound`] directly.
|
||||
pub trait PluginProvider: Send + Sync {
|
||||
/// Returns a snapshot; on error, callers retain the previous snapshot.
|
||||
/// Providers set `is_partial` when listing omits entries; warnings are diagnostic only.
|
||||
fn list(&self, _query: PluginListQuery) -> PluginProviderFuture<'_, PluginCatalog> {
|
||||
Box::pin(async { Ok(PluginCatalog::default()) })
|
||||
}
|
||||
}
|
||||
545
akode-rs/core-plugins/src/script_attribution.rs
Normal file
545
akode-rs/core-plugins/src/script_attribution.rs
Normal file
@@ -0,0 +1,545 @@
|
||||
use crate::OPENAI_API_CURATED_MARKETPLACE_NAME;
|
||||
use crate::OPENAI_CURATED_MARKETPLACE_NAME;
|
||||
use crate::OPENAI_PRIMARY_RUNTIME_MARKETPLACE_NAME;
|
||||
use crate::PluginLoadOutcome;
|
||||
use crate::loader::curated_plugin_cache_version;
|
||||
use crate::marketplace::MarketplacePluginSource;
|
||||
use crate::marketplace::find_marketplace_plugin;
|
||||
use crate::marketplace_policy::primary_runtime_marketplace_root;
|
||||
use crate::startup_sync::curated_plugins_api_marketplace_path;
|
||||
use crate::startup_sync::curated_plugins_repo_path;
|
||||
use crate::startup_sync::read_curated_plugins_sha;
|
||||
use crate::store::PluginStore;
|
||||
use crate::store::plugin_version_for_source;
|
||||
use akode_exec_server::ExecutorFileSystem;
|
||||
use akode_exec_server::GetMetadataOptions;
|
||||
use akode_exec_server::ReadFileOptions;
|
||||
use akode_plugin::PluginId;
|
||||
use akode_protocol::items::is_safe_plugin_relative_path;
|
||||
use akode_shell_command::bash::extract_bash_command;
|
||||
use akode_shell_command::bash::parse_shell_lc_plain_commands;
|
||||
use akode_shell_command::parse_command::is_pathish;
|
||||
use akode_utils_absolute_path::AbsolutePathBuf;
|
||||
use akode_utils_path_uri::PathUri;
|
||||
use std::collections::HashSet;
|
||||
use std::path::Component;
|
||||
use std::path::Path;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
struct TrustedPluginRoot {
|
||||
plugin_id: PluginId,
|
||||
version: String,
|
||||
root: AbsolutePathBuf,
|
||||
}
|
||||
|
||||
/// Trusted plugin command attribution carried into local command events.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct PluginCommandAttribution {
|
||||
pub plugin_id: PluginId,
|
||||
pub normalized_relative_path: String,
|
||||
}
|
||||
|
||||
impl PluginCommandAttribution {
|
||||
/// Returns the paired fields used at command protocol boundaries.
|
||||
pub fn serialized_fields(&self) -> (String, String) {
|
||||
(
|
||||
self.plugin_id.as_key(),
|
||||
self.normalized_relative_path.clone(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Active first-party roots eligible for command attribution.
|
||||
/// Trusted means OpenAI-shipped synced or bundled runtime code, not a local override.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct TrustedPluginRoots {
|
||||
roots: Vec<TrustedPluginRoot>,
|
||||
}
|
||||
|
||||
impl TrustedPluginRoots {
|
||||
/// Adds already-trusted roots, preserving the existing root for each plugin and version.
|
||||
/// Distinct versions remain eligible for exact executor-version matching.
|
||||
pub fn extend(&mut self, other: &Self) {
|
||||
let mut seen = self
|
||||
.roots
|
||||
.iter()
|
||||
.map(|root| (root.plugin_id.as_key(), root.version.clone()))
|
||||
.collect::<HashSet<_>>();
|
||||
self.roots.extend(
|
||||
other
|
||||
.roots
|
||||
.iter()
|
||||
.filter(|root| seen.insert((root.plugin_id.as_key(), root.version.clone())))
|
||||
.cloned(),
|
||||
);
|
||||
}
|
||||
|
||||
pub fn from_plugin_load_outcome(loaded_plugins: &PluginLoadOutcome, codex_home: &Path) -> Self {
|
||||
let primary_runtime_marketplace_root = primary_runtime_marketplace_root();
|
||||
let Ok(store) = PluginStore::try_new(codex_home.to_path_buf()) else {
|
||||
return Self::default();
|
||||
};
|
||||
let mut seen = HashSet::new();
|
||||
let roots = loaded_plugins
|
||||
.plugins()
|
||||
.iter()
|
||||
.filter(|plugin| plugin.is_active())
|
||||
.filter_map(|plugin| {
|
||||
let plugin_id = PluginId::parse(&plugin.config_name).ok()?;
|
||||
let expected_root = Self::expected_plugin_root(
|
||||
&store,
|
||||
codex_home,
|
||||
&plugin_id,
|
||||
primary_runtime_marketplace_root.as_deref(),
|
||||
)?;
|
||||
if plugin.root != expected_root || !expected_root.as_path().is_dir() {
|
||||
return None;
|
||||
}
|
||||
let version = expected_root.as_path().file_name()?.to_str()?.to_owned();
|
||||
let root = expected_root.canonicalize().ok()?;
|
||||
root.as_path().is_dir().then(|| TrustedPluginRoot {
|
||||
plugin_id,
|
||||
version,
|
||||
root,
|
||||
})
|
||||
})
|
||||
.filter(|root| seen.insert((root.plugin_id.as_key(), root.root.clone())))
|
||||
.collect();
|
||||
Self { roots }
|
||||
}
|
||||
|
||||
fn expected_plugin_root(
|
||||
store: &PluginStore,
|
||||
codex_home: &Path,
|
||||
plugin_id: &PluginId,
|
||||
primary_runtime_marketplace_root: Option<&Path>,
|
||||
) -> Option<AbsolutePathBuf> {
|
||||
match plugin_id.marketplace_name.as_str() {
|
||||
OPENAI_CURATED_MARKETPLACE_NAME | OPENAI_API_CURATED_MARKETPLACE_NAME => {
|
||||
let curated_sha = read_curated_plugins_sha(codex_home)?;
|
||||
let expected_root =
|
||||
store.plugin_root(plugin_id, &curated_plugin_cache_version(&curated_sha));
|
||||
let marketplace_path = match plugin_id.marketplace_name.as_str() {
|
||||
OPENAI_CURATED_MARKETPLACE_NAME => curated_plugins_repo_path(codex_home)
|
||||
.join(".agents/plugins/marketplace.json"),
|
||||
OPENAI_API_CURATED_MARKETPLACE_NAME => {
|
||||
curated_plugins_api_marketplace_path(codex_home)
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
Self::marketplace_plugin(marketplace_path, plugin_id)?;
|
||||
Some(expected_root)
|
||||
}
|
||||
OPENAI_PRIMARY_RUNTIME_MARKETPLACE_NAME => {
|
||||
let marketplace_root = primary_runtime_marketplace_root?;
|
||||
let expected_source_root = AbsolutePathBuf::from_absolute_path_checked(
|
||||
marketplace_root
|
||||
.join("plugins")
|
||||
.join(&plugin_id.plugin_name),
|
||||
)
|
||||
.ok()?;
|
||||
let marketplace_plugin = Self::marketplace_plugin(
|
||||
marketplace_root.join(".agents/plugins/marketplace.json"),
|
||||
plugin_id,
|
||||
)?;
|
||||
let MarketplacePluginSource::Local { path: source_root } =
|
||||
marketplace_plugin.source
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
if source_root != expected_source_root {
|
||||
return None;
|
||||
}
|
||||
let plugin_version = plugin_version_for_source(source_root.as_path()).ok()?;
|
||||
Some(store.plugin_root(plugin_id, &plugin_version))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn marketplace_plugin(
|
||||
marketplace_path: std::path::PathBuf,
|
||||
plugin_id: &PluginId,
|
||||
) -> Option<crate::marketplace::ResolvedMarketplacePlugin> {
|
||||
let marketplace_path =
|
||||
AbsolutePathBuf::from_absolute_path_checked(marketplace_path).ok()?;
|
||||
let plugin = find_marketplace_plugin(&marketplace_path, &plugin_id.plugin_name).ok()?;
|
||||
(plugin.plugin_id == *plugin_id).then_some(plugin)
|
||||
}
|
||||
|
||||
/// Resolves one exact command to one trusted plugin script.
|
||||
///
|
||||
/// Complex shell syntax, missing files, symlink escapes, and overlapping
|
||||
/// matches are all unattributed by design.
|
||||
pub fn resolve_attribution(
|
||||
&self,
|
||||
command: &[String],
|
||||
cwd: &AbsolutePathBuf,
|
||||
) -> Option<PluginCommandAttribution> {
|
||||
self.local_candidate(command, cwd)
|
||||
.map(|candidate| candidate.attribution())
|
||||
}
|
||||
|
||||
fn local_candidate(
|
||||
&self,
|
||||
command: &[String],
|
||||
cwd: &AbsolutePathBuf,
|
||||
) -> Option<MatchedPluginScript<'_>> {
|
||||
let command = single_plain_command(command)?;
|
||||
let invocation = script_invocation(command.as_slice())?;
|
||||
let script = if Path::new(invocation.script).is_absolute() {
|
||||
AbsolutePathBuf::from_absolute_path_checked(invocation.script).ok()?
|
||||
} else {
|
||||
cwd.join(invocation.script)
|
||||
}
|
||||
.canonicalize()
|
||||
.ok()?;
|
||||
if !script.as_path().is_file() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut matches = self.roots.iter().filter_map(|root| {
|
||||
let relative_path = script
|
||||
.as_path()
|
||||
.strip_prefix(root.root.as_path())
|
||||
.ok()
|
||||
.filter(|relative_path| !relative_path.as_os_str().is_empty())?;
|
||||
Some(MatchedPluginScript {
|
||||
root,
|
||||
normalized_relative_path: normalized_relative_script_path(relative_path)?,
|
||||
})
|
||||
});
|
||||
let attribution = matches.next()?;
|
||||
matches.next().is_none().then_some(attribution)
|
||||
}
|
||||
|
||||
/// Resolves a trusted script on the selected executor filesystem.
|
||||
///
|
||||
/// Remote commands can use a path convention that the app-server host cannot
|
||||
/// canonicalize. Resolve aliases on that executor first, then match the
|
||||
/// canonical target to a trusted local plugin script with the same contents.
|
||||
/// Generic attribution accepts matching script bytes across plugin versions.
|
||||
pub async fn resolve_executor_attribution(
|
||||
&self,
|
||||
command: &[String],
|
||||
cwd: &PathUri,
|
||||
file_system: &dyn ExecutorFileSystem,
|
||||
) -> Option<PluginCommandAttribution> {
|
||||
self.executor_candidate(command, cwd, file_system)
|
||||
.await
|
||||
.map(|candidate| candidate.matched.attribution())
|
||||
}
|
||||
|
||||
async fn executor_candidate(
|
||||
&self,
|
||||
command: &[String],
|
||||
cwd: &PathUri,
|
||||
file_system: &dyn ExecutorFileSystem,
|
||||
) -> Option<ExecutorAttributionCandidate<'_>> {
|
||||
if self.roots.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let command = single_plain_command(command)?;
|
||||
let invocation = script_invocation(command.as_slice())?;
|
||||
let script = cwd.join(invocation.script).ok()?;
|
||||
// Preserve known script suffixes (including directory aliases), but avoid
|
||||
// an executor round trip for unrelated workspace scripts.
|
||||
let suffixes = normalized_script_suffixes(&script);
|
||||
if !self.roots.iter().any(|root| {
|
||||
suffixes.iter().any(|suffix| {
|
||||
executor_plugin_root_matches(&script, root, suffix)
|
||||
|| root.root.join(suffix).as_path().is_file()
|
||||
})
|
||||
}) {
|
||||
return None;
|
||||
}
|
||||
let script = file_system
|
||||
.canonicalize(&script, /*sandbox*/ None)
|
||||
.await
|
||||
.ok()?;
|
||||
let candidates = self.local_candidates_for_executor_script(&script);
|
||||
if candidates.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let metadata = file_system
|
||||
.get_metadata(
|
||||
&script,
|
||||
GetMetadataOptions::default(),
|
||||
/*sandbox*/ None,
|
||||
)
|
||||
.await
|
||||
.ok()?;
|
||||
if !metadata.is_file
|
||||
|| !candidates
|
||||
.iter()
|
||||
.any(|candidate| metadata.size == candidate.contents.len() as u64)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let contents = file_system
|
||||
.read_file(&script, ReadFileOptions::default(), /*sandbox*/ None)
|
||||
.await
|
||||
.ok()?;
|
||||
let mut matches = candidates
|
||||
.into_iter()
|
||||
.filter(|candidate| contents == candidate.contents);
|
||||
let candidate = matches.next()?;
|
||||
matches
|
||||
.all(|other| other.matched.attribution() == candidate.matched.attribution())
|
||||
.then_some(candidate)
|
||||
}
|
||||
|
||||
fn local_candidates_for_executor_script(
|
||||
&self,
|
||||
script: &PathUri,
|
||||
) -> Vec<ExecutorAttributionCandidate<'_>> {
|
||||
let suffixes = normalized_script_suffixes(script);
|
||||
self.roots
|
||||
.iter()
|
||||
.filter_map(|root| {
|
||||
let (script, normalized_relative_path) = suffixes.iter().find_map(|suffix| {
|
||||
if !executor_plugin_root_matches(script, root, suffix) {
|
||||
return None;
|
||||
}
|
||||
let script = root.root.join(suffix).canonicalize().ok()?;
|
||||
let relative_path = script.as_path().strip_prefix(root.root.as_path()).ok()?;
|
||||
if !script.as_path().is_file() {
|
||||
return None;
|
||||
}
|
||||
let normalized_relative_path = normalized_relative_script_path(relative_path)?;
|
||||
Some((script, normalized_relative_path))
|
||||
})?;
|
||||
Some(ExecutorAttributionCandidate {
|
||||
matched: MatchedPluginScript {
|
||||
root,
|
||||
normalized_relative_path,
|
||||
},
|
||||
contents: std::fs::read(script.as_path()).ok()?,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
struct MatchedPluginScript<'a> {
|
||||
root: &'a TrustedPluginRoot,
|
||||
normalized_relative_path: String,
|
||||
}
|
||||
|
||||
impl MatchedPluginScript<'_> {
|
||||
fn attribution(&self) -> PluginCommandAttribution {
|
||||
PluginCommandAttribution {
|
||||
plugin_id: self.root.plugin_id.clone(),
|
||||
normalized_relative_path: self.normalized_relative_path.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct ExecutorAttributionCandidate<'a> {
|
||||
matched: MatchedPluginScript<'a>,
|
||||
contents: Vec<u8>,
|
||||
}
|
||||
|
||||
fn normalized_script_suffixes(script: &PathUri) -> Vec<String> {
|
||||
let path = script.inferred_native_path_string().replace('\\', "/");
|
||||
let components = path
|
||||
.split('/')
|
||||
.filter(|component| !component.is_empty())
|
||||
.collect::<Vec<_>>();
|
||||
(0..components.len())
|
||||
.filter_map(|start| {
|
||||
let suffix = components[start..].join("/");
|
||||
is_safe_plugin_relative_path(&suffix).then_some(suffix)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn executor_plugin_root_matches(
|
||||
script: &PathUri,
|
||||
trusted: &TrustedPluginRoot,
|
||||
relative_path: &str,
|
||||
) -> bool {
|
||||
let relative_depth = relative_path.split('/').count();
|
||||
let Some(root) = script.ancestors().nth(relative_depth) else {
|
||||
return false;
|
||||
};
|
||||
let Some(cache_parent) = root.ancestors().nth(5) else {
|
||||
return false;
|
||||
};
|
||||
let Ok(plugin_root) = cache_parent.join(&format!(
|
||||
"plugins/cache/{}/{}",
|
||||
trusted.plugin_id.marketplace_name, trusted.plugin_id.plugin_name
|
||||
)) else {
|
||||
return false;
|
||||
};
|
||||
root.parent().as_ref() == Some(&plugin_root)
|
||||
}
|
||||
|
||||
/// Returns the structurally parsed arguments following a single script command.
|
||||
/// Callers must keep the values in-process and must not log or serialize them.
|
||||
pub fn command_script_arguments(command: &[String]) -> Option<Vec<String>> {
|
||||
let command = single_plain_command(command)?;
|
||||
Some(script_invocation(command.as_slice())?.arguments.to_vec())
|
||||
}
|
||||
|
||||
/// Converts a path already proven to be below a trusted plugin root into the
|
||||
/// only path shape that may leave the resolver: non-empty, relative, and
|
||||
/// slash-separated with no traversal or platform-specific prefixes.
|
||||
pub(crate) fn normalized_relative_script_path(relative_path: &Path) -> Option<String> {
|
||||
let normalized = relative_path
|
||||
.components()
|
||||
.map(|component| {
|
||||
let Component::Normal(component) = component else {
|
||||
return None;
|
||||
};
|
||||
component.to_str()
|
||||
})
|
||||
.collect::<Option<Vec<_>>>()?
|
||||
.join("/");
|
||||
|
||||
is_safe_plugin_relative_path(&normalized).then_some(normalized)
|
||||
}
|
||||
|
||||
fn single_plain_command(command: &[String]) -> Option<Vec<String>> {
|
||||
if let Some(commands) = parse_shell_lc_plain_commands(command) {
|
||||
let [command] = commands.as_slice() else {
|
||||
return None;
|
||||
};
|
||||
return single_plain_command(command);
|
||||
}
|
||||
if let Some(script) = windows_shell_script(command) {
|
||||
let wrapper = ["sh".to_string(), "-lc".to_string(), script.to_string()];
|
||||
return single_plain_command(&wrapper);
|
||||
}
|
||||
if extract_bash_command(command).is_some() {
|
||||
return None;
|
||||
}
|
||||
Some(command.to_vec())
|
||||
}
|
||||
|
||||
struct ScriptInvocation<'a> {
|
||||
script: &'a str,
|
||||
arguments: &'a [String],
|
||||
}
|
||||
|
||||
fn script_invocation(command: &[String]) -> Option<ScriptInvocation<'_>> {
|
||||
let [program, args @ ..] = command else {
|
||||
return None;
|
||||
};
|
||||
if let Some(interpreter) = interpreter_name(program) {
|
||||
return interpreter_script_invocation(&interpreter, args);
|
||||
}
|
||||
is_pathish(program).then_some(ScriptInvocation {
|
||||
script: program,
|
||||
arguments: args,
|
||||
})
|
||||
}
|
||||
|
||||
fn interpreter_name(program: &str) -> Option<String> {
|
||||
let basename = executable_basename(program)?;
|
||||
let basename = basename.to_ascii_lowercase();
|
||||
let basename = basename.strip_suffix(".exe").unwrap_or(&basename);
|
||||
matches!(
|
||||
basename,
|
||||
"bash"
|
||||
| "node"
|
||||
| "nodejs"
|
||||
| "perl"
|
||||
| "php"
|
||||
| "powershell"
|
||||
| "pwsh"
|
||||
| "python"
|
||||
| "python3"
|
||||
| "ruby"
|
||||
| "sh"
|
||||
| "zsh"
|
||||
)
|
||||
.then(|| basename.to_string())
|
||||
}
|
||||
|
||||
fn interpreter_script_invocation<'a>(
|
||||
interpreter: &str,
|
||||
args: &'a [String],
|
||||
) -> Option<ScriptInvocation<'a>> {
|
||||
if matches!(interpreter, "powershell" | "pwsh") {
|
||||
let [file_flag, script, arguments @ ..] = args else {
|
||||
return None;
|
||||
};
|
||||
return (file_flag.eq_ignore_ascii_case("-file") && !script.starts_with('-'))
|
||||
.then_some(ScriptInvocation { script, arguments });
|
||||
}
|
||||
|
||||
let mut args = args;
|
||||
loop {
|
||||
match args {
|
||||
[separator, script, arguments @ ..]
|
||||
if separator == "--" && !script.starts_with('-') =>
|
||||
{
|
||||
return Some(ScriptInvocation { script, arguments });
|
||||
}
|
||||
[flag, remaining @ ..] if safe_interpreter_flag(interpreter, flag) => {
|
||||
args = remaining;
|
||||
}
|
||||
[script, arguments @ ..] if !script.starts_with('-') => {
|
||||
return Some(ScriptInvocation { script, arguments });
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn safe_interpreter_flag(interpreter: &str, flag: &str) -> bool {
|
||||
matches!(
|
||||
(interpreter, flag),
|
||||
("python" | "python3", "-u") | ("bash" | "sh" | "zsh", "-e")
|
||||
)
|
||||
}
|
||||
|
||||
fn executable_basename(program: &str) -> Option<&str> {
|
||||
program
|
||||
.rsplit(['/', '\\'])
|
||||
.next()
|
||||
.filter(|basename| !basename.is_empty())
|
||||
}
|
||||
|
||||
fn windows_shell_script(command: &[String]) -> Option<&str> {
|
||||
let [program, args @ ..] = command else {
|
||||
return None;
|
||||
};
|
||||
let basename = executable_basename(program)?.to_ascii_lowercase();
|
||||
if matches!(basename.as_str(), "cmd" | "cmd.exe") {
|
||||
let [flag, script] = args else {
|
||||
return None;
|
||||
};
|
||||
return flag.eq_ignore_ascii_case("/c").then_some(script);
|
||||
}
|
||||
if !matches!(
|
||||
basename.as_str(),
|
||||
"powershell" | "powershell.exe" | "pwsh" | "pwsh.exe"
|
||||
) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let [flags @ .., command_flag, script] = args else {
|
||||
return None;
|
||||
};
|
||||
if !matches!(
|
||||
command_flag.to_ascii_lowercase().as_str(),
|
||||
"-command" | "-c"
|
||||
) {
|
||||
return None;
|
||||
}
|
||||
flags
|
||||
.iter()
|
||||
.all(|flag| {
|
||||
matches!(
|
||||
flag.to_ascii_lowercase().as_str(),
|
||||
"-nologo" | "-noprofile" | "-noninteractive"
|
||||
)
|
||||
})
|
||||
.then_some(script)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "script_attribution_tests.rs"]
|
||||
mod tests;
|
||||
647
akode-rs/core-plugins/src/script_attribution_tests.rs
Normal file
647
akode-rs/core-plugins/src/script_attribution_tests.rs
Normal file
@@ -0,0 +1,647 @@
|
||||
use super::*;
|
||||
use crate::LoadedPlugin;
|
||||
use crate::loader::curated_plugin_cache_version;
|
||||
use crate::startup_sync::curated_plugins_repo_path;
|
||||
use crate::store::DEFAULT_PLUGIN_VERSION;
|
||||
use crate::store::PluginStore;
|
||||
use crate::test_support::TEST_CURATED_PLUGIN_SHA;
|
||||
use crate::test_support::write_curated_plugin_sha_with;
|
||||
use crate::test_support::write_openai_api_curated_marketplace;
|
||||
use crate::test_support::write_openai_curated_marketplace;
|
||||
use akode_exec_server::ExecServerError;
|
||||
use akode_exec_server::LOCAL_FS;
|
||||
use akode_exec_server::NoiseChannelPublicKey;
|
||||
use akode_exec_server::NoiseRendezvousConnectBundle;
|
||||
use akode_exec_server::NoiseRendezvousConnectProvider;
|
||||
use akode_exec_server_test_support::environment_manager_without_environments;
|
||||
use akode_plugin::PluginLoadOutcome;
|
||||
use akode_utils_path_uri::PathUri;
|
||||
use akode_utils_plugins::SkillDiscoveryMode;
|
||||
use futures::FutureExt;
|
||||
use futures::future::BoxFuture;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
use std::fs;
|
||||
use std::sync::Arc;
|
||||
use tempfile::TempDir;
|
||||
const ENABLED: bool = true;
|
||||
const DISABLED: bool = false;
|
||||
/// Marketplace name formerly used by the removed remote plugin catalog.
|
||||
const LEGACY_REMOTE_MARKETPLACE_NAME: &str = "openai-curated-remote";
|
||||
|
||||
fn path(path: &Path) -> AbsolutePathBuf {
|
||||
AbsolutePathBuf::from_absolute_path_checked(path).expect("absolute path")
|
||||
}
|
||||
fn loaded_plugin(config_name: &str, root: &Path, enabled: bool) -> LoadedPlugin {
|
||||
LoadedPlugin {
|
||||
config_name: config_name.to_string(),
|
||||
manifest_name: None,
|
||||
plugin_namespace: None,
|
||||
manifest_description: None,
|
||||
root: path(root),
|
||||
enabled,
|
||||
skill_roots: Vec::new(),
|
||||
skill_discovery_mode: SkillDiscoveryMode::Recursive,
|
||||
disabled_skill_paths: HashSet::new(),
|
||||
has_enabled_skills: false,
|
||||
mcp_servers: HashMap::new(),
|
||||
hook_sources: Vec::new(),
|
||||
hook_load_warnings: Vec::new(),
|
||||
error: None,
|
||||
}
|
||||
}
|
||||
fn synced_plugin_root(codex_home: &Path, marketplace: &str, plugin_name: &str) -> AbsolutePathBuf {
|
||||
let synced_root = curated_plugins_repo_path(codex_home);
|
||||
match marketplace {
|
||||
OPENAI_CURATED_MARKETPLACE_NAME => {
|
||||
write_openai_curated_marketplace(&synced_root, &[plugin_name])
|
||||
}
|
||||
OPENAI_API_CURATED_MARKETPLACE_NAME => {
|
||||
write_openai_api_curated_marketplace(&synced_root, &[plugin_name])
|
||||
}
|
||||
_ => panic!("unsupported test marketplace"),
|
||||
}
|
||||
let plugin_id =
|
||||
PluginId::new(plugin_name.to_string(), marketplace.to_string()).expect("plugin id");
|
||||
let root = PluginStore::new(codex_home.to_path_buf()).plugin_root(
|
||||
&plugin_id,
|
||||
&curated_plugin_cache_version(TEST_CURATED_PLUGIN_SHA),
|
||||
);
|
||||
fs::create_dir_all(root.as_path()).expect("create cached plugin root");
|
||||
root
|
||||
}
|
||||
/// Cache entry under the legacy remote marketplace name, which no longer carries any trust.
|
||||
fn cached_legacy_remote_plugin_root(codex_home: &Path, plugin_name: &str) -> AbsolutePathBuf {
|
||||
let plugin_id = PluginId::new(
|
||||
plugin_name.to_string(),
|
||||
LEGACY_REMOTE_MARKETPLACE_NAME.to_string(),
|
||||
)
|
||||
.expect("plugin id");
|
||||
let root = PluginStore::new(codex_home.to_path_buf()).plugin_root(&plugin_id, "1.2.3");
|
||||
fs::create_dir_all(root.as_path()).expect("create cached legacy remote plugin root");
|
||||
root
|
||||
}
|
||||
fn script_fixture() -> (TempDir, AbsolutePathBuf, AbsolutePathBuf) {
|
||||
let temp = TempDir::new().expect("temp dir");
|
||||
write_curated_plugin_sha_with(temp.path(), TEST_CURATED_PLUGIN_SHA);
|
||||
let root = synced_plugin_root(temp.path(), OPENAI_CURATED_MARKETPLACE_NAME, "sample");
|
||||
let script = root.join("scripts/run.py");
|
||||
fs::create_dir_all(script.as_path().parent().expect("script parent")).expect("create scripts");
|
||||
fs::write(script.as_path(), "#!/usr/bin/env python3\n").expect("write script");
|
||||
let script = script.canonicalize().expect("canonical script");
|
||||
(temp, root, script)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolves_primary_runtime_scripts_from_the_installed_plugin_cache() {
|
||||
let temp = TempDir::new().expect("temp dir");
|
||||
let marketplace_root = temp.path().join("openai-primary-runtime");
|
||||
let source_root = marketplace_root.join("plugins/presentations");
|
||||
fs::create_dir_all(source_root.join(".codex-plugin")).expect("create manifest directory");
|
||||
fs::write(
|
||||
source_root.join(".codex-plugin/plugin.json"),
|
||||
r#"{"name":"presentations","version":"0.1.29"}"#,
|
||||
)
|
||||
.expect("write plugin manifest");
|
||||
let relative_script_path =
|
||||
"skills/presentations/container_tools/mark_artifact_operation_started.mjs";
|
||||
let source_script = source_root.join(relative_script_path);
|
||||
fs::create_dir_all(source_script.parent().expect("script parent")).expect("create scripts");
|
||||
fs::write(&source_script, "#!/usr/bin/env node\n").expect("write script");
|
||||
fs::create_dir_all(marketplace_root.join(".agents/plugins"))
|
||||
.expect("create marketplace directory");
|
||||
fs::write(
|
||||
marketplace_root.join(".agents/plugins/marketplace.json"),
|
||||
r#"{
|
||||
"name": "openai-primary-runtime",
|
||||
"plugins": [
|
||||
{
|
||||
"name": "presentations",
|
||||
"source": {
|
||||
"source": "local",
|
||||
"path": "./plugins/presentations"
|
||||
}
|
||||
}
|
||||
]
|
||||
}"#,
|
||||
)
|
||||
.expect("write marketplace manifest");
|
||||
let plugin_id = PluginId::parse("presentations@openai-primary-runtime").expect("plugin id");
|
||||
let plugin_root = PluginStore::new(temp.path().to_path_buf())
|
||||
.install(path(&source_root), plugin_id.clone())
|
||||
.expect("install plugin")
|
||||
.installed_path;
|
||||
let script = plugin_root.join(relative_script_path);
|
||||
let store = PluginStore::new(temp.path().to_path_buf());
|
||||
assert_eq!(
|
||||
TrustedPluginRoots::expected_plugin_root(
|
||||
&store,
|
||||
temp.path(),
|
||||
&plugin_id,
|
||||
Some(&marketplace_root),
|
||||
),
|
||||
Some(plugin_root.clone())
|
||||
);
|
||||
let roots = TrustedPluginRoots {
|
||||
roots: vec![TrustedPluginRoot {
|
||||
plugin_id: plugin_id.clone(),
|
||||
version: "0.1.29".to_string(),
|
||||
root: plugin_root.canonicalize().expect("canonical plugin root"),
|
||||
}],
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
roots.resolve_attribution(
|
||||
&command(&[
|
||||
"node",
|
||||
script.to_string_lossy().as_ref(),
|
||||
"--operation-kind",
|
||||
"create",
|
||||
]),
|
||||
&path(temp.path()),
|
||||
),
|
||||
Some(PluginCommandAttribution {
|
||||
plugin_id,
|
||||
normalized_relative_path: relative_script_path.to_string(),
|
||||
})
|
||||
);
|
||||
}
|
||||
fn roots_for(codex_home: &Path, plugins: Vec<LoadedPlugin>) -> TrustedPluginRoots {
|
||||
TrustedPluginRoots::from_plugin_load_outcome(
|
||||
&PluginLoadOutcome::from_plugins(plugins),
|
||||
codex_home,
|
||||
)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn resolves_relocated_script_through_executor_filesystem() {
|
||||
let (temp, root, script) = script_fixture();
|
||||
let roots = roots_for(
|
||||
temp.path(),
|
||||
vec![loaded_plugin(
|
||||
"sample@openai-curated",
|
||||
root.as_path(),
|
||||
ENABLED,
|
||||
)],
|
||||
);
|
||||
let executor = TempDir::new().expect("executor temp dir");
|
||||
let executor_root = executor
|
||||
.path()
|
||||
.join("plugins/cache/openai-curated/sample")
|
||||
.join(curated_plugin_cache_version(TEST_CURATED_PLUGIN_SHA));
|
||||
let executor_script = executor_root.join("scripts/run.py");
|
||||
fs::create_dir_all(executor_script.parent().expect("script parent"))
|
||||
.expect("create executor scripts");
|
||||
fs::copy(script.as_path(), &executor_script).expect("copy script to executor");
|
||||
let cwd = PathUri::from_host_native_path(&executor_root).expect("executor root URI");
|
||||
|
||||
assert_eq!(
|
||||
roots
|
||||
.resolve_executor_attribution(
|
||||
&command(&["python", "scripts/run.py"]),
|
||||
&cwd,
|
||||
LOCAL_FS.as_ref(),
|
||||
)
|
||||
.await,
|
||||
Some(PluginCommandAttribution {
|
||||
plugin_id: PluginId::parse("sample@openai-curated").expect("plugin id"),
|
||||
normalized_relative_path: "scripts/run.py".to_string(),
|
||||
})
|
||||
);
|
||||
|
||||
fs::write(&executor_script, "print('modified')\n").expect("modify executor script");
|
||||
assert_eq!(
|
||||
roots
|
||||
.resolve_executor_attribution(
|
||||
&command(&["python", "scripts/run.py"]),
|
||||
&cwd,
|
||||
LOCAL_FS.as_ref(),
|
||||
)
|
||||
.await,
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recognizes_windows_executor_plugin_cache_root() {
|
||||
let reference = TempDir::new().expect("reference root");
|
||||
let trusted = TrustedPluginRoot {
|
||||
plugin_id: PluginId::parse("presentations@openai-primary-runtime").expect("plugin id"),
|
||||
version: "0.1.29".to_string(),
|
||||
root: path(reference.path()),
|
||||
};
|
||||
let relative_path = "skills/presentations/container_tools/mark_artifact_operation_started.mjs";
|
||||
let script = PathUri::parse(
|
||||
"file:///C:/Users/user/.akode/plugins/cache/openai-primary-runtime/presentations/0.1.29/skills/presentations/container_tools/mark_artifact_operation_started.mjs",
|
||||
)
|
||||
.expect("Windows script URI");
|
||||
|
||||
assert!(executor_plugin_root_matches(
|
||||
&script,
|
||||
&trusted,
|
||||
relative_path
|
||||
));
|
||||
let other_plugin = PathUri::parse(
|
||||
"file:///C:/Users/user/.akode/plugins/cache/openai-primary-runtime/other/0.1.29/skills/presentations/container_tools/mark_artifact_operation_started.mjs",
|
||||
)
|
||||
.expect("other-plugin Windows script URI");
|
||||
assert!(!executor_plugin_root_matches(
|
||||
&other_plugin,
|
||||
&trusted,
|
||||
relative_path
|
||||
));
|
||||
}
|
||||
fn assert_untrusted(codex_home: &Path, config_name: &str, root: &Path) {
|
||||
assert!(
|
||||
roots_for(codex_home, vec![loaded_plugin(config_name, root, ENABLED)])
|
||||
.roots
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
fn command(parts: &[&str]) -> Vec<String> {
|
||||
parts.iter().map(ToString::to_string).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trusted_roots_require_verified_curated_cache() {
|
||||
let temp = TempDir::new().expect("temp dir");
|
||||
write_curated_plugin_sha_with(temp.path(), TEST_CURATED_PLUGIN_SHA);
|
||||
let root = synced_plugin_root(temp.path(), OPENAI_CURATED_MARKETPLACE_NAME, "sample");
|
||||
let api_root = synced_plugin_root(
|
||||
temp.path(),
|
||||
OPENAI_API_CURATED_MARKETPLACE_NAME,
|
||||
"api-sample",
|
||||
);
|
||||
let remote_root = cached_legacy_remote_plugin_root(temp.path(), "remote-sample");
|
||||
let _ = cached_legacy_remote_plugin_root(temp.path(), "overridden-remote");
|
||||
let overridden_plugin_id = PluginId::new(
|
||||
"overridden-remote".to_string(),
|
||||
LEGACY_REMOTE_MARKETPLACE_NAME.to_string(),
|
||||
)
|
||||
.expect("plugin id");
|
||||
let remote_local_override = PluginStore::new(temp.path().to_path_buf())
|
||||
.plugin_root(&overridden_plugin_id, DEFAULT_PLUGIN_VERSION);
|
||||
let local_root = temp
|
||||
.path()
|
||||
.join("plugins/cache/openai-curated/sample/local");
|
||||
let spoofed_root = temp.path().join("spoofed/openai-curated/sample");
|
||||
let spoofed_remote_root = temp.path().join(format!(
|
||||
"spoofed/{LEGACY_REMOTE_MARKETPLACE_NAME}/remote-sample"
|
||||
));
|
||||
fs::create_dir_all(&local_root).expect("create local root");
|
||||
fs::create_dir_all(&spoofed_root).expect("create spoofed root");
|
||||
fs::create_dir_all(&spoofed_remote_root).expect("create spoofed remote root");
|
||||
fs::create_dir_all(remote_local_override.as_path()).expect("create remote local override");
|
||||
let roots = roots_for(
|
||||
temp.path(),
|
||||
vec![
|
||||
loaded_plugin("sample@openai-curated", root.as_path(), ENABLED),
|
||||
loaded_plugin("api-sample@openai-api-curated", api_root.as_path(), ENABLED),
|
||||
loaded_plugin("sample@openai-curated", &local_root, ENABLED),
|
||||
loaded_plugin("sample@openai-curated", &spoofed_root, ENABLED),
|
||||
loaded_plugin("disabled@openai-curated", root.as_path(), DISABLED),
|
||||
],
|
||||
);
|
||||
assert_eq!(
|
||||
roots.roots,
|
||||
vec![
|
||||
TrustedPluginRoot {
|
||||
plugin_id: PluginId::parse("sample@openai-curated").expect("plugin id"),
|
||||
version: curated_plugin_cache_version(TEST_CURATED_PLUGIN_SHA),
|
||||
root: root.canonicalize().expect("canonical root"),
|
||||
},
|
||||
TrustedPluginRoot {
|
||||
plugin_id: PluginId::parse("api-sample@openai-api-curated").expect("plugin id"),
|
||||
version: curated_plugin_cache_version(TEST_CURATED_PLUGIN_SHA),
|
||||
root: api_root.canonicalize().expect("canonical root"),
|
||||
},
|
||||
]
|
||||
);
|
||||
// Cache entries under the legacy remote marketplace name are never trusted, wherever they live.
|
||||
let remote_sample = format!("remote-sample@{LEGACY_REMOTE_MARKETPLACE_NAME}");
|
||||
assert_untrusted(temp.path(), &remote_sample, remote_root.as_path());
|
||||
assert_untrusted(temp.path(), &remote_sample, &spoofed_remote_root);
|
||||
assert_untrusted(
|
||||
temp.path(),
|
||||
&format!("overridden-remote@{LEGACY_REMOTE_MARKETPLACE_NAME}"),
|
||||
remote_local_override.as_path(),
|
||||
);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let alias = temp.path().join("sample-alias");
|
||||
std::os::unix::fs::symlink(root.as_path(), &alias).expect("symlink root");
|
||||
assert_untrusted(temp.path(), "sample@openai-curated", &alias);
|
||||
}
|
||||
let _ = synced_plugin_root(temp.path(), OPENAI_CURATED_MARKETPLACE_NAME, "listed");
|
||||
let unlisted_root = PluginStore::new(temp.path().to_path_buf()).plugin_root(
|
||||
&PluginId::parse("missing@openai-curated").expect("plugin id"),
|
||||
&curated_plugin_cache_version(TEST_CURATED_PLUGIN_SHA),
|
||||
);
|
||||
fs::create_dir_all(unlisted_root.as_path()).expect("create unlisted root");
|
||||
assert_untrusted(
|
||||
temp.path(),
|
||||
"missing@openai-curated",
|
||||
unlisted_root.as_path(),
|
||||
);
|
||||
let no_sha = TempDir::new().expect("temp dir");
|
||||
let no_sha_root = synced_plugin_root(no_sha.path(), OPENAI_CURATED_MARKETPLACE_NAME, "sample");
|
||||
assert_untrusted(
|
||||
no_sha.path(),
|
||||
"sample@openai-curated",
|
||||
no_sha_root.as_path(),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolves_local_attribution_for_safe_interpreters_and_wrappers() {
|
||||
let (temp, root, script) = script_fixture();
|
||||
let roots = roots_for(
|
||||
temp.path(),
|
||||
vec![loaded_plugin(
|
||||
"sample@openai-curated",
|
||||
root.as_path(),
|
||||
ENABLED,
|
||||
)],
|
||||
);
|
||||
let expected = Some(PluginCommandAttribution {
|
||||
plugin_id: PluginId::parse("sample@openai-curated").expect("plugin id"),
|
||||
normalized_relative_path: "scripts/run.py".to_string(),
|
||||
});
|
||||
let script = script.to_string_lossy().to_string();
|
||||
// Preserve native path separators and any shell metacharacters as literal argv.
|
||||
let quoted_script = format!("'{}'", script.replace('\'', "'\"'\"'"));
|
||||
let unix_wrapper = format!("python -u {quoted_script}");
|
||||
for command in [
|
||||
command(&["scripts/run.py"]),
|
||||
command(&["/usr/bin/python", "-u", &script]),
|
||||
command(&["sh", "-e", &script]),
|
||||
command(&["bash", "-e", &script]),
|
||||
command(&["zsh", "-e", &script]),
|
||||
command(&["pwsh", "-File", &script]),
|
||||
command(&["powershell", "-File", &script]),
|
||||
command(&["bash", "-lc", &unix_wrapper]),
|
||||
command(&["pwsh.exe", "-NoProfile", "-Command", "scripts/run.py"]),
|
||||
command(&["cmd.exe", "/c", "scripts/run.py"]),
|
||||
] {
|
||||
assert_eq!(
|
||||
roots.resolve_attribution(&command, &root),
|
||||
expected,
|
||||
"{command:?}"
|
||||
);
|
||||
}
|
||||
|
||||
let wrapped_command = command(&[
|
||||
"bash",
|
||||
"-lc",
|
||||
&format!("node {quoted_script} --operation-kind create"),
|
||||
]);
|
||||
assert_eq!(roots.resolve_attribution(&wrapped_command, &root), expected);
|
||||
assert_eq!(
|
||||
command_script_arguments(&wrapped_command),
|
||||
Some(command(&["--operation-kind", "create"]))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_emits_safe_normalized_relative_script_paths() {
|
||||
assert_eq!(
|
||||
normalized_relative_script_path(Path::new("scripts/run.py")),
|
||||
Some("scripts/run.py".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
normalized_relative_script_path(Path::new(
|
||||
"/home/user/.akode/plugins/cache/openai-curated/sample/scripts/run.py"
|
||||
)),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_ambiguous_commands_overlaps_and_symlink_escapes() {
|
||||
let (temp, root, script) = script_fixture();
|
||||
let roots = roots_for(
|
||||
temp.path(),
|
||||
vec![loaded_plugin(
|
||||
"sample@openai-curated",
|
||||
root.as_path(),
|
||||
ENABLED,
|
||||
)],
|
||||
);
|
||||
let script = script.to_string_lossy().to_string();
|
||||
let complex = format!("python {script} && echo done");
|
||||
for command in [
|
||||
command(&["bash", "-lc", &complex]),
|
||||
command(&["node", "--require", "scripts/bootstrap.js", &script]),
|
||||
command(&["python", "-m", "scripts.run"]),
|
||||
command(&[
|
||||
"pwsh.exe",
|
||||
"-NoProfile",
|
||||
"-Command",
|
||||
"scripts/run.py; echo done",
|
||||
]),
|
||||
command(&["python", "scripts/missing.py"]),
|
||||
] {
|
||||
assert_eq!(roots.resolve_attribution(&command, &root), None);
|
||||
}
|
||||
let overlapping = TrustedPluginRoots {
|
||||
roots: vec![
|
||||
TrustedPluginRoot {
|
||||
plugin_id: PluginId::parse("sample@openai-curated").expect("plugin id"),
|
||||
version: curated_plugin_cache_version(TEST_CURATED_PLUGIN_SHA),
|
||||
root: root.canonicalize().expect("canonical root"),
|
||||
},
|
||||
TrustedPluginRoot {
|
||||
plugin_id: PluginId::parse("nested@openai-curated").expect("plugin id"),
|
||||
version: curated_plugin_cache_version(TEST_CURATED_PLUGIN_SHA),
|
||||
root: root.join("scripts").canonicalize().expect("nested root"),
|
||||
},
|
||||
],
|
||||
};
|
||||
assert_eq!(
|
||||
overlapping.resolve_attribution(&command(&["scripts/run.py"]), &root),
|
||||
None
|
||||
);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let outside = temp.path().join("outside.py");
|
||||
fs::write(&outside, "print('outside')\n").expect("write outside script");
|
||||
std::os::unix::fs::symlink(&outside, root.join("scripts/escape.py")).expect("symlink");
|
||||
assert_eq!(
|
||||
roots.resolve_attribution(&command(&["python", "scripts/escape.py"]), &root),
|
||||
None
|
||||
);
|
||||
|
||||
for unsafe_name in [r"scripts\run.py", "C:run.py"] {
|
||||
let unsafe_script = root.join(unsafe_name);
|
||||
fs::write(unsafe_script.as_path(), "print('unsafe')\n").expect("write unsafe script");
|
||||
assert_eq!(
|
||||
roots.resolve_attribution(
|
||||
&command(&["python", &unsafe_script.to_string_lossy()]),
|
||||
&root,
|
||||
),
|
||||
None
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const REFERENCE_HELPER: &str = "scripts/install-dependencies.sh";
|
||||
|
||||
fn reference_identity_fixture(root: &Path, contents: &str) -> AbsolutePathBuf {
|
||||
fs::create_dir_all(root.join("scripts")).expect("create reference scripts");
|
||||
fs::write(root.join(REFERENCE_HELPER), contents).expect("write helper");
|
||||
path(root).canonicalize().expect("canonical reference root")
|
||||
}
|
||||
|
||||
fn reference_fixture(bundles: &[(&str, &str, &str)]) -> (TempDir, TrustedPluginRoots) {
|
||||
let home = TempDir::new().expect("references");
|
||||
let roots = TrustedPluginRoots {
|
||||
roots: bundles
|
||||
.iter()
|
||||
.map(|(name, version, contents)| {
|
||||
let root =
|
||||
reference_identity_fixture(&home.path().join(name).join(version), contents);
|
||||
TrustedPluginRoot {
|
||||
plugin_id: PluginId::parse(&format!(
|
||||
"{name}@{OPENAI_CURATED_MARKETPLACE_NAME}"
|
||||
))
|
||||
.expect("plugin id"),
|
||||
version: version.to_string(),
|
||||
root,
|
||||
}
|
||||
})
|
||||
.collect(),
|
||||
};
|
||||
(home, roots)
|
||||
}
|
||||
|
||||
fn executor_plugin(home: &Path, name: &str, version: &str, contents: &str) -> AbsolutePathBuf {
|
||||
reference_identity_fixture(
|
||||
&home.join(format!(
|
||||
"plugins/cache/{OPENAI_CURATED_MARKETPLACE_NAME}/{name}/{version}"
|
||||
)),
|
||||
contents,
|
||||
)
|
||||
}
|
||||
|
||||
// Ordinary attribution can survive version differences.
|
||||
async fn assert_executor_resolution(
|
||||
roots: &TrustedPluginRoots,
|
||||
command: &[String],
|
||||
cwd: &PathUri,
|
||||
plugin_id: &PluginId,
|
||||
) {
|
||||
assert_eq!(
|
||||
roots
|
||||
.resolve_executor_attribution(command, cwd, LOCAL_FS.as_ref())
|
||||
.await,
|
||||
Some(PluginCommandAttribution {
|
||||
plugin_id: plugin_id.clone(),
|
||||
normalized_relative_path: REFERENCE_HELPER.to_string(),
|
||||
}),
|
||||
"attribution for {command:?} at {cwd:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extending_trusted_roots_preserves_existing_plugins_and_deduplicates_snapshots() {
|
||||
let contents = "printf shared\\n\n";
|
||||
let (_frontend, mut roots) = reference_fixture(&[("sites", "1.2.3", contents)]);
|
||||
let original = roots.clone();
|
||||
let (_snapshot, additional) =
|
||||
reference_fixture(&[("sites", "1.2.3", contents), ("other", "1.2.3", contents)]);
|
||||
|
||||
roots.extend(&additional);
|
||||
let expected = TrustedPluginRoots {
|
||||
roots: vec![original.roots[0].clone(), additional.roots[1].clone()],
|
||||
};
|
||||
assert_eq!(roots, expected);
|
||||
roots.extend(&additional);
|
||||
assert_eq!(roots, expected, "repeated snapshots must remain idempotent");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn same_helper_path_in_two_plugins_resolves_by_executor_identity() {
|
||||
// Identical bytes: neither suffix nor content identifies a plugin.
|
||||
let contents = "printf shared\\n\n";
|
||||
let (_reference, roots) =
|
||||
reference_fixture(&[("sites", "2.0.0", contents), ("other", "2.0.0", contents)]);
|
||||
let executor = TempDir::new().expect("executor");
|
||||
for name in ["sites", "other"] {
|
||||
let root = executor_plugin(executor.path(), name, "2.0.0", contents);
|
||||
let cwd = PathUri::from_host_native_path(root.as_path()).expect("executor URI");
|
||||
let plugin_id = PluginId::parse(&format!("{name}@{OPENAI_CURATED_MARKETPLACE_NAME}"))
|
||||
.expect("plugin id");
|
||||
assert_executor_resolution(
|
||||
&roots,
|
||||
&command(&["sh", REFERENCE_HELPER]),
|
||||
&cwd,
|
||||
&plugin_id,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn executor_aliases_use_canonical_plugin_paths() {
|
||||
let contents = "printf shared\\n\n";
|
||||
let (_reference, roots) =
|
||||
reference_fixture(&[("sites", "1.2.3", contents), ("sites", "2.0.0", contents)]);
|
||||
let plugin_id =
|
||||
PluginId::parse(&format!("sites@{OPENAI_CURATED_MARKETPLACE_NAME}")).expect("plugin id");
|
||||
let executor = TempDir::new().expect("executor");
|
||||
let target = executor_plugin(executor.path(), "sites", "2.0.0", contents);
|
||||
let alias = executor.path().join("plugin-link");
|
||||
std::os::unix::fs::symlink(target.as_path(), &alias).expect("directory alias");
|
||||
let version_alias = executor.path().join(format!(
|
||||
"plugins/cache/{OPENAI_CURATED_MARKETPLACE_NAME}/sites/1.2.3/scripts/renamed-entry.sh"
|
||||
));
|
||||
fs::create_dir_all(version_alias.parent().expect("alias parent")).expect("V1 alias directory");
|
||||
std::os::unix::fs::symlink(target.join(REFERENCE_HELPER), &version_alias).expect("V1 alias");
|
||||
let cwd = PathUri::from_host_native_path(executor.path()).expect("executor URI");
|
||||
// An already loaded reference still supports directory aliases. Preparation
|
||||
// only probes cache paths, so ordinary workspace scripts need no executor I/O.
|
||||
assert_executor_resolution(
|
||||
&roots,
|
||||
&command(&["sh", &alias.join(REFERENCE_HELPER).to_string_lossy()]),
|
||||
&cwd,
|
||||
&plugin_id,
|
||||
)
|
||||
.await;
|
||||
let command = command(&["sh", &version_alias.to_string_lossy()]);
|
||||
assert_executor_resolution(&roots, &command, &cwd, &plugin_id).await;
|
||||
}
|
||||
|
||||
struct UnusedConnectProvider;
|
||||
|
||||
impl NoiseRendezvousConnectProvider for UnusedConnectProvider {
|
||||
fn connect_bundle(
|
||||
&self,
|
||||
_: NoiseChannelPublicKey,
|
||||
) -> BoxFuture<'_, Result<NoiseRendezvousConnectBundle, ExecServerError>> {
|
||||
panic!("unrelated script must not connect to the executor")
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unrelated_scripts_skip_executor_lookup() -> anyhow::Result<()> {
|
||||
let (_reference, roots) = reference_fixture(&[("sites", "2.0.0", "printf shared\\n\n")]);
|
||||
let manager = environment_manager_without_environments();
|
||||
let pending = manager.materialize_pending_noise_environment(
|
||||
"tools".to_string(),
|
||||
Arc::new(UnusedConnectProvider),
|
||||
)?;
|
||||
let fs = pending.get_filesystem();
|
||||
let cwd = PathUri::parse("file:///workspace")?;
|
||||
let command = command(&["node", "build.js"]);
|
||||
// An executor lookup waits for provisioning; unrelated scripts must finish immediately.
|
||||
assert_eq!(
|
||||
roots
|
||||
.resolve_executor_attribution(&command, &cwd, fs.as_ref())
|
||||
.now_or_never(),
|
||||
Some(None),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
34
akode-rs/core-plugins/src/skill_snapshots.rs
Normal file
34
akode-rs/core-plugins/src/skill_snapshots.rs
Normal file
@@ -0,0 +1,34 @@
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
|
||||
use akode_skills::LoadedSkillRoot;
|
||||
use akode_skills::SkillRootSnapshotCache;
|
||||
use akode_skills::SkillRootSnapshots;
|
||||
use akode_utils_plugins::PluginSkillRoot;
|
||||
|
||||
#[derive(Default)]
|
||||
struct PluginSkillSnapshotCache {
|
||||
snapshots_by_root: Mutex<HashMap<PluginSkillRoot, LoadedSkillRoot>>,
|
||||
}
|
||||
|
||||
impl SkillRootSnapshotCache<PluginSkillRoot> for PluginSkillSnapshotCache {
|
||||
fn get(&self, root: &PluginSkillRoot) -> Option<LoadedSkillRoot> {
|
||||
self.snapshots_by_root
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.get(root)
|
||||
.cloned()
|
||||
}
|
||||
|
||||
fn insert(&self, root: PluginSkillRoot, snapshot: LoadedSkillRoot) {
|
||||
self.snapshots_by_root
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.insert(root, snapshot);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn new_plugin_skill_snapshots() -> SkillRootSnapshots<PluginSkillRoot> {
|
||||
SkillRootSnapshots::new(Arc::new(PluginSkillSnapshotCache::default()))
|
||||
}
|
||||
58
akode-rs/core-plugins/src/startup_sync.rs
Normal file
58
akode-rs/core-plugins/src/startup_sync.rs
Normal file
@@ -0,0 +1,58 @@
|
||||
//! Paths of the local curated plugins snapshot.
|
||||
//!
|
||||
//! aKode: the upstream startup sync (git clone of github.com/openai/plugins, GitHub API
|
||||
//! zipball download and the ChatGPT plugins export fallback) was removed. Only the on-disk
|
||||
//! layout helpers remain, so an existing local snapshot keeps working and is never refreshed
|
||||
//! from the network.
|
||||
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// Git source identifier of the upstream curated marketplace. aKode: used only to match
|
||||
/// marketplace policy rules; nothing is ever fetched from it.
|
||||
pub(crate) const OPENAI_PLUGINS_GIT_URL: &str = "https://github.com/openai/plugins.git";
|
||||
const CURATED_PLUGINS_RELATIVE_DIR: &str = ".tmp/plugins";
|
||||
const CURATED_PLUGINS_SHA_FILE: &str = ".tmp/plugins.sha";
|
||||
|
||||
pub fn curated_plugins_repo_path(codex_home: &Path) -> PathBuf {
|
||||
codex_home.join(CURATED_PLUGINS_RELATIVE_DIR)
|
||||
}
|
||||
|
||||
pub fn curated_plugins_api_marketplace_path(codex_home: &Path) -> PathBuf {
|
||||
curated_plugins_repo_path(codex_home).join(".agents/plugins/api_marketplace.json")
|
||||
}
|
||||
|
||||
pub fn read_curated_plugins_sha(codex_home: &Path) -> Option<String> {
|
||||
std::fs::read_to_string(codex_home.join(CURATED_PLUGINS_SHA_FILE))
|
||||
.ok()
|
||||
.map(|sha| sha.trim().to_string())
|
||||
.filter(|sha| !sha.is_empty())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::tempdir;
|
||||
|
||||
#[test]
|
||||
fn curated_plugins_repo_path_uses_codex_home_tmp_dir() {
|
||||
let tmp = tempdir().expect("tempdir");
|
||||
assert_eq!(
|
||||
curated_plugins_repo_path(tmp.path()),
|
||||
tmp.path().join(".tmp/plugins")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_curated_plugins_sha_reads_trimmed_sha_file() {
|
||||
let tmp = tempdir().expect("tempdir");
|
||||
std::fs::create_dir_all(tmp.path().join(".tmp")).expect("create tmp");
|
||||
std::fs::write(tmp.path().join(".tmp/plugins.sha"), "abc123\n").expect("write sha");
|
||||
|
||||
assert_eq!(
|
||||
read_curated_plugins_sha(tmp.path()).as_deref(),
|
||||
Some("abc123")
|
||||
);
|
||||
}
|
||||
}
|
||||
635
akode-rs/core-plugins/src/store.rs
Normal file
635
akode-rs/core-plugins/src/store.rs
Normal file
@@ -0,0 +1,635 @@
|
||||
use crate::command_migration::migrate_plugin_commands;
|
||||
use crate::manifest::ManifestCache;
|
||||
use crate::manifest::PluginManifest;
|
||||
use crate::manifest::PluginManifestFormat;
|
||||
use crate::manifest::load_plugin_manifest;
|
||||
use crate::manifest::parse_plugin_manifest;
|
||||
use akode_plugin::PluginId;
|
||||
use akode_plugin::validate_plugin_segment;
|
||||
use akode_utils_absolute_path::AbsolutePathBuf;
|
||||
use akode_utils_plugins::AgentPluginSchemaStatus;
|
||||
use akode_utils_plugins::agent_plugin_schema_status;
|
||||
use akode_utils_plugins::find_plugin_manifest_path;
|
||||
use serde::Deserialize;
|
||||
use serde_json::Value as JsonValue;
|
||||
use sha2::Digest;
|
||||
use sha2::Sha256;
|
||||
use std::cmp::Ordering;
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub use akode_core_plugin_common::installed::DEFAULT_PLUGIN_VERSION;
|
||||
pub use akode_core_plugin_common::installed::PLUGINS_CACHE_DIR;
|
||||
pub const PLUGINS_DATA_DIR: &str = "plugins/data";
|
||||
const AGENT_PLUGINS_DATA_DIR: &str = "agent-plugins";
|
||||
const DEFAULT_AGENT_PLUGIN_VERSION: &str = "1.0.0";
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct PluginInstallResult {
|
||||
pub plugin_id: PluginId,
|
||||
pub plugin_version: String,
|
||||
pub installed_path: AbsolutePathBuf,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct PluginStore {
|
||||
pub(crate) manifest_cache: Arc<ManifestCache>,
|
||||
codex_home: AbsolutePathBuf,
|
||||
root: AbsolutePathBuf,
|
||||
data_root: AbsolutePathBuf,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum InstallManifest<'a> {
|
||||
OnDisk,
|
||||
Fallback(&'a str),
|
||||
}
|
||||
|
||||
impl PluginStore {
|
||||
pub fn new(codex_home: PathBuf) -> Self {
|
||||
Self::try_new(codex_home)
|
||||
.unwrap_or_else(|err| panic!("plugin cache root should be absolute: {err}"))
|
||||
}
|
||||
|
||||
pub fn try_new(codex_home: PathBuf) -> Result<Self, PluginStoreError> {
|
||||
let root = AbsolutePathBuf::from_absolute_path_checked(codex_home.join(PLUGINS_CACHE_DIR))
|
||||
.map_err(|err| PluginStoreError::io("failed to resolve plugin cache root", err))?;
|
||||
let data_root =
|
||||
AbsolutePathBuf::from_absolute_path_checked(codex_home.join(PLUGINS_DATA_DIR))
|
||||
.map_err(|err| PluginStoreError::io("failed to resolve plugin data root", err))?;
|
||||
let codex_home = AbsolutePathBuf::from_absolute_path_checked(codex_home)
|
||||
.map_err(|err| PluginStoreError::io("failed to resolve Codex home", err))?;
|
||||
|
||||
Ok(Self {
|
||||
manifest_cache: Arc::new(ManifestCache::default()),
|
||||
codex_home,
|
||||
root,
|
||||
data_root,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn root(&self) -> &AbsolutePathBuf {
|
||||
&self.root
|
||||
}
|
||||
|
||||
pub(crate) fn codex_home(&self) -> &AbsolutePathBuf {
|
||||
&self.codex_home
|
||||
}
|
||||
|
||||
pub fn plugin_base_root(&self, plugin_id: &PluginId) -> AbsolutePathBuf {
|
||||
self.root
|
||||
.join(&plugin_id.marketplace_name)
|
||||
.join(&plugin_id.plugin_name)
|
||||
}
|
||||
|
||||
pub fn plugin_root(&self, plugin_id: &PluginId, plugin_version: &str) -> AbsolutePathBuf {
|
||||
self.plugin_base_root(plugin_id).join(plugin_version)
|
||||
}
|
||||
|
||||
pub fn plugin_data_root(&self, plugin_id: &PluginId) -> AbsolutePathBuf {
|
||||
self.data_root.join(format!(
|
||||
"{}-{}",
|
||||
plugin_id.plugin_name, plugin_id.marketplace_name
|
||||
))
|
||||
}
|
||||
|
||||
pub(crate) fn agent_plugin_data_root(&self, plugin_id: &PluginId) -> AbsolutePathBuf {
|
||||
let mut digest = Sha256::new();
|
||||
digest.update(plugin_id.marketplace_name.as_bytes());
|
||||
digest.update([0]);
|
||||
digest.update(plugin_id.plugin_name.as_bytes());
|
||||
self.data_root
|
||||
.join(AGENT_PLUGINS_DATA_DIR)
|
||||
.join(hex_prefix(&digest.finalize(), /*count*/ 32))
|
||||
}
|
||||
|
||||
pub(crate) fn mcp_data_root(
|
||||
&self,
|
||||
plugin_id: &PluginId,
|
||||
manifest_format: PluginManifestFormat,
|
||||
) -> AbsolutePathBuf {
|
||||
match manifest_format {
|
||||
PluginManifestFormat::AgentPlugin => self.agent_plugin_data_root(plugin_id),
|
||||
PluginManifestFormat::Legacy => self.plugin_data_root(plugin_id),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn active_plugin_version(&self, plugin_id: &PluginId) -> Option<String> {
|
||||
akode_core_plugin_common::installed::active_plugin_version(
|
||||
&self.plugin_base_root(plugin_id),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn active_plugin_root(&self, plugin_id: &PluginId) -> Option<AbsolutePathBuf> {
|
||||
self.active_plugin_version(plugin_id)
|
||||
.map(|plugin_version| self.plugin_root(plugin_id, &plugin_version))
|
||||
}
|
||||
|
||||
pub fn is_installed(&self, plugin_id: &PluginId) -> bool {
|
||||
self.active_plugin_version(plugin_id).is_some()
|
||||
}
|
||||
|
||||
pub fn install(
|
||||
&self,
|
||||
source_path: AbsolutePathBuf,
|
||||
plugin_id: PluginId,
|
||||
) -> Result<PluginInstallResult, PluginStoreError> {
|
||||
self.install_with_manifest(source_path, plugin_id, InstallManifest::OnDisk)
|
||||
}
|
||||
|
||||
pub(crate) fn install_with_fallback_manifest(
|
||||
&self,
|
||||
source_path: AbsolutePathBuf,
|
||||
plugin_id: PluginId,
|
||||
manifest_contents: &str,
|
||||
) -> Result<PluginInstallResult, PluginStoreError> {
|
||||
self.install_with_manifest(
|
||||
source_path,
|
||||
plugin_id,
|
||||
InstallManifest::Fallback(manifest_contents),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn install_with_version(
|
||||
&self,
|
||||
source_path: AbsolutePathBuf,
|
||||
plugin_id: PluginId,
|
||||
plugin_version: String,
|
||||
) -> Result<PluginInstallResult, PluginStoreError> {
|
||||
self.install_with_version_and_manifest(
|
||||
source_path,
|
||||
plugin_id,
|
||||
plugin_version,
|
||||
InstallManifest::OnDisk,
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn install_with_version_and_fallback_manifest(
|
||||
&self,
|
||||
source_path: AbsolutePathBuf,
|
||||
plugin_id: PluginId,
|
||||
plugin_version: String,
|
||||
manifest_contents: &str,
|
||||
) -> Result<PluginInstallResult, PluginStoreError> {
|
||||
self.install_with_version_and_manifest(
|
||||
source_path,
|
||||
plugin_id,
|
||||
plugin_version,
|
||||
InstallManifest::Fallback(manifest_contents),
|
||||
)
|
||||
}
|
||||
|
||||
fn install_with_manifest(
|
||||
&self,
|
||||
source_path: AbsolutePathBuf,
|
||||
plugin_id: PluginId,
|
||||
manifest: InstallManifest<'_>,
|
||||
) -> Result<PluginInstallResult, PluginStoreError> {
|
||||
let manifest = resolve_install_manifest(source_path.as_path(), manifest);
|
||||
let plugin_version = plugin_version_for_install_manifest(source_path.as_path(), manifest)?;
|
||||
self.install_with_version_and_manifest(source_path, plugin_id, plugin_version, manifest)
|
||||
}
|
||||
|
||||
fn install_with_version_and_manifest(
|
||||
&self,
|
||||
source_path: AbsolutePathBuf,
|
||||
plugin_id: PluginId,
|
||||
plugin_version: String,
|
||||
manifest: InstallManifest<'_>,
|
||||
) -> Result<PluginInstallResult, PluginStoreError> {
|
||||
if !source_path.as_path().is_dir() {
|
||||
return Err(PluginStoreError::Invalid(format!(
|
||||
"plugin source path is not a directory: {}",
|
||||
source_path.display()
|
||||
)));
|
||||
}
|
||||
|
||||
let manifest = resolve_install_manifest(source_path.as_path(), manifest);
|
||||
let plugin_name = plugin_name_for_source(source_path.as_path(), manifest)?;
|
||||
if plugin_name != plugin_id.plugin_name {
|
||||
return Err(PluginStoreError::Invalid(format!(
|
||||
"plugin.json name `{plugin_name}` does not match marketplace plugin name `{}`",
|
||||
plugin_id.plugin_name
|
||||
)));
|
||||
}
|
||||
validate_plugin_version_segment(&plugin_version).map_err(PluginStoreError::Invalid)?;
|
||||
let installed_path = self.plugin_root(&plugin_id, &plugin_version);
|
||||
replace_plugin_root_atomically(
|
||||
source_path.as_path(),
|
||||
self.plugin_base_root(&plugin_id).as_path(),
|
||||
&plugin_version,
|
||||
manifest,
|
||||
)?;
|
||||
|
||||
Ok(PluginInstallResult {
|
||||
plugin_id,
|
||||
plugin_version,
|
||||
installed_path,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn uninstall(&self, plugin_id: &PluginId) -> Result<(), PluginStoreError> {
|
||||
remove_existing_target(self.plugin_base_root(plugin_id).as_path())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum PluginStoreError {
|
||||
#[error("{context}: {source}")]
|
||||
Io {
|
||||
context: &'static str,
|
||||
#[source]
|
||||
source: io::Error,
|
||||
},
|
||||
|
||||
#[error("{0}")]
|
||||
Invalid(String),
|
||||
}
|
||||
|
||||
impl PluginStoreError {
|
||||
fn io(context: &'static str, source: io::Error) -> Self {
|
||||
Self::Io { context, source }
|
||||
}
|
||||
|
||||
pub(crate) fn sub_error_type(&self) -> Option<String> {
|
||||
match self {
|
||||
Self::Io { context, .. } => Some(error_context_sub_error_type(context)),
|
||||
Self::Invalid(_) => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn error_context_sub_error_type(context: &str) -> String {
|
||||
context.to_ascii_lowercase().replace(' ', "_")
|
||||
}
|
||||
|
||||
pub fn plugin_version_for_source(source_path: &Path) -> Result<String, PluginStoreError> {
|
||||
plugin_version_for_install_manifest(source_path, InstallManifest::OnDisk)
|
||||
}
|
||||
|
||||
pub(crate) fn plugin_version_for_source_with_fallback_manifest(
|
||||
source_path: &Path,
|
||||
manifest_contents: &str,
|
||||
) -> Result<String, PluginStoreError> {
|
||||
let manifest =
|
||||
resolve_install_manifest(source_path, InstallManifest::Fallback(manifest_contents));
|
||||
plugin_version_for_install_manifest(source_path, manifest)
|
||||
}
|
||||
|
||||
fn resolve_install_manifest<'a>(
|
||||
source_path: &Path,
|
||||
manifest: InstallManifest<'a>,
|
||||
) -> InstallManifest<'a> {
|
||||
// A real plugin manifest always wins. The fallback only fills the gap for marketplace
|
||||
// sources that cannot be changed in place because they may be user-owned directories.
|
||||
match manifest {
|
||||
InstallManifest::Fallback(_) if find_plugin_manifest_path(source_path).is_some() => {
|
||||
InstallManifest::OnDisk
|
||||
}
|
||||
manifest => manifest,
|
||||
}
|
||||
}
|
||||
|
||||
fn plugin_version_for_install_manifest(
|
||||
source_path: &Path,
|
||||
manifest: InstallManifest<'_>,
|
||||
) -> Result<String, PluginStoreError> {
|
||||
let (plugin_version, is_agent_plugin) =
|
||||
plugin_manifest_version_for_source(source_path, manifest)?;
|
||||
let plugin_version = plugin_version.unwrap_or_else(|| {
|
||||
if is_agent_plugin {
|
||||
DEFAULT_AGENT_PLUGIN_VERSION.to_string()
|
||||
} else {
|
||||
DEFAULT_PLUGIN_VERSION.to_string()
|
||||
}
|
||||
});
|
||||
match validate_plugin_version_segment(&plugin_version) {
|
||||
Ok(()) => Ok(plugin_version),
|
||||
Err(_) if is_agent_plugin => {
|
||||
let digest = Sha256::digest(plugin_version.as_bytes());
|
||||
Ok(format!(
|
||||
"agent-plugins-{}",
|
||||
hex_prefix(&digest, /*count*/ 12)
|
||||
))
|
||||
}
|
||||
Err(message) => Err(PluginStoreError::Invalid(message)),
|
||||
}
|
||||
}
|
||||
|
||||
fn hex_prefix(bytes: &[u8], count: usize) -> String {
|
||||
const HEX: &[u8; 16] = b"0123456789abcdef";
|
||||
let mut output = String::with_capacity(count.saturating_mul(2));
|
||||
for byte in bytes.iter().take(count) {
|
||||
output.push(HEX[usize::from(byte >> 4)] as char);
|
||||
output.push(HEX[usize::from(byte & 0x0f)] as char);
|
||||
}
|
||||
output
|
||||
}
|
||||
|
||||
pub fn validate_plugin_version_segment(plugin_version: &str) -> Result<(), String> {
|
||||
akode_core_plugin_common::installed::validate_plugin_version_segment(plugin_version)
|
||||
}
|
||||
|
||||
fn plugin_manifest_for_source(
|
||||
source_path: &Path,
|
||||
manifest: InstallManifest<'_>,
|
||||
) -> Result<PluginManifest, PluginStoreError> {
|
||||
match manifest {
|
||||
InstallManifest::OnDisk => load_plugin_manifest(source_path)
|
||||
.ok_or_else(|| PluginStoreError::Invalid("missing or invalid plugin.json".to_string())),
|
||||
InstallManifest::Fallback(contents) => parse_plugin_manifest(
|
||||
source_path,
|
||||
&source_path.join(".codex-plugin/plugin.json"),
|
||||
contents,
|
||||
)
|
||||
.map_err(|err| PluginStoreError::Invalid(format!("failed to parse plugin.json: {err}"))),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct RawPluginManifestVersion {
|
||||
#[serde(default)]
|
||||
version: Option<JsonValue>,
|
||||
}
|
||||
|
||||
fn plugin_manifest_version_for_source(
|
||||
source_path: &Path,
|
||||
manifest: InstallManifest<'_>,
|
||||
) -> Result<(Option<String>, bool), PluginStoreError> {
|
||||
let contents = match manifest {
|
||||
InstallManifest::OnDisk => {
|
||||
let manifest_path = find_plugin_manifest_path(source_path)
|
||||
.ok_or_else(|| PluginStoreError::Invalid("missing plugin.json".to_string()))?;
|
||||
fs::read_to_string(&manifest_path)
|
||||
.map_err(|err| PluginStoreError::io("failed to read plugin.json", err))?
|
||||
}
|
||||
InstallManifest::Fallback(contents) => contents.to_string(),
|
||||
};
|
||||
let is_agent_plugin =
|
||||
agent_plugin_schema_status(&contents) == AgentPluginSchemaStatus::Supported;
|
||||
let manifest: RawPluginManifestVersion = serde_json::from_str(&contents)
|
||||
.map_err(|err| PluginStoreError::Invalid(format!("failed to parse plugin.json: {err}")))?;
|
||||
let Some(version) = manifest.version else {
|
||||
return Ok((None, is_agent_plugin));
|
||||
};
|
||||
let Some(version) = version.as_str() else {
|
||||
return Err(PluginStoreError::Invalid(
|
||||
"invalid plugin version in plugin.json: expected string".to_string(),
|
||||
));
|
||||
};
|
||||
if is_agent_plugin {
|
||||
let version = version.trim();
|
||||
return Ok(((!version.is_empty()).then(|| version.to_string()), true));
|
||||
}
|
||||
let version = version.trim();
|
||||
if version.is_empty() {
|
||||
return Err(PluginStoreError::Invalid(
|
||||
"invalid plugin version in plugin.json: must not be blank".to_string(),
|
||||
));
|
||||
}
|
||||
Ok((Some(version.to_string()), false))
|
||||
}
|
||||
|
||||
fn plugin_name_for_source(
|
||||
source_path: &Path,
|
||||
manifest: InstallManifest<'_>,
|
||||
) -> Result<String, PluginStoreError> {
|
||||
let manifest = plugin_manifest_for_source(source_path, manifest)?;
|
||||
|
||||
let plugin_name = manifest.name;
|
||||
validate_plugin_segment(&plugin_name, "plugin name")
|
||||
.map_err(PluginStoreError::Invalid)
|
||||
.map(|_| plugin_name)
|
||||
}
|
||||
|
||||
fn remove_existing_target(path: &Path) -> Result<(), PluginStoreError> {
|
||||
if !path.exists() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if path.is_dir() {
|
||||
fs::remove_dir_all(path).map_err(|err| {
|
||||
PluginStoreError::io("failed to remove existing plugin cache entry", err)
|
||||
})
|
||||
} else {
|
||||
fs::remove_file(path).map_err(|err| {
|
||||
PluginStoreError::io("failed to remove existing plugin cache entry", err)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn replace_plugin_root_atomically(
|
||||
source: &Path,
|
||||
target_root: &Path,
|
||||
plugin_version: &str,
|
||||
manifest: InstallManifest<'_>,
|
||||
) -> Result<(), PluginStoreError> {
|
||||
let Some(parent) = target_root.parent() else {
|
||||
return Err(PluginStoreError::Invalid(format!(
|
||||
"plugin cache path has no parent: {}",
|
||||
target_root.display()
|
||||
)));
|
||||
};
|
||||
|
||||
fs::create_dir_all(parent)
|
||||
.map_err(|err| PluginStoreError::io("failed to create plugin cache directory", err))?;
|
||||
|
||||
let Some(plugin_dir_name) = target_root.file_name() else {
|
||||
return Err(PluginStoreError::Invalid(format!(
|
||||
"plugin cache path has no directory name: {}",
|
||||
target_root.display()
|
||||
)));
|
||||
};
|
||||
let staged_dir = tempfile::Builder::new()
|
||||
.prefix("plugin-install-")
|
||||
.tempdir_in(parent)
|
||||
.map_err(|err| {
|
||||
PluginStoreError::io("failed to create temporary plugin cache directory", err)
|
||||
})?;
|
||||
let staged_root = staged_dir.path().join(plugin_dir_name);
|
||||
let staged_version_root = staged_root.join(plugin_version);
|
||||
let (source_manifest_relative_path, source_manifest_contents) = match manifest {
|
||||
InstallManifest::OnDisk => {
|
||||
let manifest_path = find_plugin_manifest_path(source)
|
||||
.ok_or_else(|| PluginStoreError::Invalid("missing plugin.json".to_string()))?;
|
||||
let relative_path = manifest_path
|
||||
.strip_prefix(source)
|
||||
.map_err(|_| {
|
||||
PluginStoreError::Invalid(
|
||||
"plugin manifest is outside the plugin source".to_string(),
|
||||
)
|
||||
})?
|
||||
.to_path_buf();
|
||||
let contents = fs::read(&manifest_path)
|
||||
.map_err(|err| PluginStoreError::io("failed to read plugin.json", err))?;
|
||||
(relative_path, contents)
|
||||
}
|
||||
InstallManifest::Fallback(contents) => (
|
||||
PathBuf::from(".codex-plugin/plugin.json"),
|
||||
contents.as_bytes().to_vec(),
|
||||
),
|
||||
};
|
||||
copy_dir_recursive(source, &staged_version_root)?;
|
||||
if let InstallManifest::Fallback(contents) = manifest {
|
||||
// Inject the generated manifest into Store's existing atomic copy so install does not
|
||||
// mutate the original source or require a second staging directory.
|
||||
let manifest_path = staged_version_root.join(".codex-plugin/plugin.json");
|
||||
let Some(manifest_parent) = manifest_path.parent() else {
|
||||
return Err(PluginStoreError::Invalid(
|
||||
"plugin manifest path has no parent".to_string(),
|
||||
));
|
||||
};
|
||||
fs::create_dir_all(manifest_parent).map_err(|err| {
|
||||
PluginStoreError::io("failed to create plugin manifest directory", err)
|
||||
})?;
|
||||
fs::write(&manifest_path, contents)
|
||||
.map_err(|err| PluginStoreError::io("failed to write fallback plugin manifest", err))?;
|
||||
}
|
||||
let staged_manifest_path =
|
||||
find_plugin_manifest_path(&staged_version_root).ok_or_else(|| {
|
||||
PluginStoreError::Invalid(
|
||||
"plugin manifest is missing after installation staging".to_string(),
|
||||
)
|
||||
})?;
|
||||
if staged_manifest_path != staged_version_root.join(&source_manifest_relative_path) {
|
||||
return Err(PluginStoreError::Invalid(
|
||||
"plugin manifest changed during installation staging".to_string(),
|
||||
));
|
||||
}
|
||||
let staged_manifest_contents = fs::read(&staged_manifest_path)
|
||||
.map_err(|err| PluginStoreError::io("failed to read staged plugin.json", err))?;
|
||||
if staged_manifest_contents != source_manifest_contents {
|
||||
return Err(PluginStoreError::Invalid(
|
||||
"plugin manifest contents changed during installation staging".to_string(),
|
||||
));
|
||||
}
|
||||
let is_agent_plugin = fs::read_to_string(staged_version_root.join("plugin.json"))
|
||||
.ok()
|
||||
.is_some_and(|contents| {
|
||||
agent_plugin_schema_status(&contents) == AgentPluginSchemaStatus::Supported
|
||||
});
|
||||
if !is_agent_plugin && let Err(err) = migrate_plugin_commands(&staged_version_root) {
|
||||
tracing::warn!(%err, "failed to migrate plugin commands into skills");
|
||||
}
|
||||
|
||||
let target_version_root = target_root.join(plugin_version);
|
||||
if target_root.exists() && !target_version_root.exists() {
|
||||
fs::rename(&staged_version_root, &target_version_root).map_err(|err| {
|
||||
PluginStoreError::io("failed to activate updated plugin cache version", err)
|
||||
})?;
|
||||
remove_old_plugin_versions(target_root, plugin_version)?;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if target_root.exists() {
|
||||
let backup_dir = tempfile::Builder::new()
|
||||
.prefix("plugin-backup-")
|
||||
.tempdir_in(parent)
|
||||
.map_err(|err| {
|
||||
PluginStoreError::io("failed to create plugin cache backup directory", err)
|
||||
})?;
|
||||
let backup_root = backup_dir.path().join(plugin_dir_name);
|
||||
fs::rename(target_root, &backup_root)
|
||||
.map_err(|err| PluginStoreError::io("failed to back up plugin cache entry", err))?;
|
||||
|
||||
if let Err(err) = fs::rename(&staged_root, target_root) {
|
||||
let rollback_result = fs::rename(&backup_root, target_root);
|
||||
return match rollback_result {
|
||||
Ok(()) => Err(PluginStoreError::io(
|
||||
"failed to activate updated plugin cache entry",
|
||||
err,
|
||||
)),
|
||||
Err(rollback_err) => {
|
||||
let backup_path = backup_dir.keep().join(plugin_dir_name);
|
||||
Err(PluginStoreError::Invalid(format!(
|
||||
"failed to activate updated plugin cache entry at {}: {err}; failed to restore previous cache entry (left at {}): {rollback_err}",
|
||||
target_root.display(),
|
||||
backup_path.display()
|
||||
)))
|
||||
}
|
||||
};
|
||||
}
|
||||
} else {
|
||||
fs::rename(&staged_root, target_root)
|
||||
.map_err(|err| PluginStoreError::io("failed to activate plugin cache entry", err))?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn remove_old_plugin_versions(
|
||||
target_root: &Path,
|
||||
plugin_version: &str,
|
||||
) -> Result<(), PluginStoreError> {
|
||||
let Ok(entries) = fs::read_dir(target_root) else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
for entry in entries.filter_map(Result::ok) {
|
||||
let Ok(file_type) = entry.file_type() else {
|
||||
continue;
|
||||
};
|
||||
if !file_type.is_dir() {
|
||||
continue;
|
||||
}
|
||||
let Ok(version) = entry.file_name().into_string() else {
|
||||
continue;
|
||||
};
|
||||
if version == plugin_version || validate_plugin_version_segment(&version).is_err() {
|
||||
continue;
|
||||
}
|
||||
|
||||
if fs::remove_dir_all(entry.path()).is_err()
|
||||
&& old_plugin_version_would_stay_active(&version, plugin_version)
|
||||
{
|
||||
return Err(PluginStoreError::Invalid(format!(
|
||||
"failed to activate updated plugin cache version `{plugin_version}` while `{version}` remains active"
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn old_plugin_version_would_stay_active(old_version: &str, new_version: &str) -> bool {
|
||||
old_version == DEFAULT_PLUGIN_VERSION
|
||||
|| compare_plugin_versions(old_version, new_version).is_gt()
|
||||
}
|
||||
|
||||
fn compare_plugin_versions(left: &str, right: &str) -> Ordering {
|
||||
akode_core_plugin_common::installed::compare_plugin_versions(left, right)
|
||||
}
|
||||
|
||||
fn copy_dir_recursive(source: &Path, target: &Path) -> Result<(), PluginStoreError> {
|
||||
fs::create_dir_all(target)
|
||||
.map_err(|err| PluginStoreError::io("failed to create plugin target directory", err))?;
|
||||
|
||||
for entry in fs::read_dir(source)
|
||||
.map_err(|err| PluginStoreError::io("failed to read plugin source directory", err))?
|
||||
{
|
||||
let entry =
|
||||
entry.map_err(|err| PluginStoreError::io("failed to enumerate plugin source", err))?;
|
||||
let source_path = entry.path();
|
||||
let target_path = target.join(entry.file_name());
|
||||
let file_type = entry
|
||||
.file_type()
|
||||
.map_err(|err| PluginStoreError::io("failed to inspect plugin source entry", err))?;
|
||||
|
||||
if file_type.is_dir() {
|
||||
copy_dir_recursive(&source_path, &target_path)?;
|
||||
} else if file_type.is_file() {
|
||||
fs::copy(&source_path, &target_path)
|
||||
.map_err(|err| PluginStoreError::io("failed to copy plugin file", err))?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "store_tests.rs"]
|
||||
mod tests;
|
||||
643
akode-rs/core-plugins/src/store_tests.rs
Normal file
643
akode-rs/core-plugins/src/store_tests.rs
Normal file
@@ -0,0 +1,643 @@
|
||||
use super::*;
|
||||
use akode_plugin::PluginId;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::tempdir;
|
||||
|
||||
fn write_plugin_with_version(
|
||||
root: &Path,
|
||||
dir_name: &str,
|
||||
manifest_name: &str,
|
||||
manifest_version: Option<&str>,
|
||||
) {
|
||||
let plugin_root = root.join(dir_name);
|
||||
fs::create_dir_all(plugin_root.join(".codex-plugin")).unwrap();
|
||||
fs::create_dir_all(plugin_root.join("skills")).unwrap();
|
||||
let version = manifest_version
|
||||
.map(|manifest_version| format!(r#","version":"{manifest_version}""#))
|
||||
.unwrap_or_default();
|
||||
fs::write(
|
||||
plugin_root.join(".codex-plugin/plugin.json"),
|
||||
format!(r#"{{"name":"{manifest_name}"{version}}}"#),
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(plugin_root.join("skills/SKILL.md"), "skill").unwrap();
|
||||
fs::write(plugin_root.join(".mcp.json"), r#"{"mcpServers":{}}"#).unwrap();
|
||||
}
|
||||
|
||||
fn write_plugin(root: &Path, dir_name: &str, manifest_name: &str) {
|
||||
write_plugin_with_version(
|
||||
root,
|
||||
dir_name,
|
||||
manifest_name,
|
||||
/*manifest_version*/ None,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn try_new_rejects_relative_codex_home() {
|
||||
let err = PluginStore::try_new(PathBuf::from("relative"))
|
||||
.expect_err("relative codex home should fail");
|
||||
let err = err.to_string().replace('\\', "/");
|
||||
|
||||
assert_eq!(
|
||||
err,
|
||||
"failed to resolve plugin cache root: path is not absolute: relative/plugins/cache"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn install_copies_plugin_into_default_marketplace() {
|
||||
let tmp = tempdir().unwrap();
|
||||
write_plugin(tmp.path(), "sample-plugin", "sample-plugin");
|
||||
let plugin_id = PluginId::new("sample-plugin".to_string(), "debug".to_string()).unwrap();
|
||||
|
||||
let result = PluginStore::new(tmp.path().to_path_buf())
|
||||
.install(
|
||||
AbsolutePathBuf::try_from(tmp.path().join("sample-plugin")).unwrap(),
|
||||
plugin_id.clone(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let installed_path = tmp.path().join("plugins/cache/debug/sample-plugin/local");
|
||||
assert_eq!(
|
||||
result,
|
||||
PluginInstallResult {
|
||||
plugin_id,
|
||||
plugin_version: "local".to_string(),
|
||||
installed_path: AbsolutePathBuf::try_from(installed_path.clone()).unwrap(),
|
||||
}
|
||||
);
|
||||
assert!(installed_path.join(".codex-plugin/plugin.json").is_file());
|
||||
assert!(installed_path.join("skills/SKILL.md").is_file());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn install_accepts_manifest_mcp_server_objects() {
|
||||
let tmp = tempdir().unwrap();
|
||||
let plugin_root = tmp.path().join("counter-sample");
|
||||
fs::create_dir_all(plugin_root.join(".codex-plugin")).unwrap();
|
||||
fs::write(
|
||||
plugin_root.join(".codex-plugin/plugin.json"),
|
||||
r#"{
|
||||
"name": "counter-sample",
|
||||
"version": "1.1.1",
|
||||
"mcpServers": {
|
||||
"counter": {
|
||||
"type": "http",
|
||||
"url": "https://sample.example/counter/mcp"
|
||||
}
|
||||
}
|
||||
}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let plugin_id = PluginId::new("counter-sample".to_string(), "debug".to_string()).unwrap();
|
||||
|
||||
let result = PluginStore::new(tmp.path().to_path_buf())
|
||||
.install(
|
||||
AbsolutePathBuf::try_from(plugin_root).unwrap(),
|
||||
plugin_id.clone(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let installed_path = tmp.path().join("plugins/cache/debug/counter-sample/1.1.1");
|
||||
assert_eq!(
|
||||
result,
|
||||
PluginInstallResult {
|
||||
plugin_id,
|
||||
plugin_version: "1.1.1".to_string(),
|
||||
installed_path: AbsolutePathBuf::try_from(installed_path.clone()).unwrap(),
|
||||
}
|
||||
);
|
||||
assert!(installed_path.join(".codex-plugin/plugin.json").is_file());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn install_rejects_symlinked_manifest_that_hides_lower_precedence_mcp_server() {
|
||||
let tmp = tempdir().unwrap();
|
||||
let plugin_root = tmp.path().join("manifest-switch");
|
||||
let codex_path = plugin_root.join(".codex-plugin/plugin.json");
|
||||
let claude_path = plugin_root.join(".claude-plugin/plugin.json");
|
||||
fs::create_dir_all(codex_path.parent().unwrap()).unwrap();
|
||||
fs::create_dir_all(claude_path.parent().unwrap()).unwrap();
|
||||
fs::write(
|
||||
plugin_root.join("benign.json"),
|
||||
r#"{"name":"manifest-switch","version":"1.2.3"}"#,
|
||||
)
|
||||
.unwrap();
|
||||
std::os::unix::fs::symlink("../benign.json", &codex_path).unwrap();
|
||||
fs::write(
|
||||
&claude_path,
|
||||
r#"{"name":"manifest-switch","version":"1.2.3","mcpServers":{"hidden":{"command":"/bin/sh"}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let plugin_id = PluginId::new("manifest-switch".to_string(), "debug".to_string()).unwrap();
|
||||
|
||||
let err = PluginStore::new(tmp.path().to_path_buf())
|
||||
.install(AbsolutePathBuf::try_from(plugin_root).unwrap(), plugin_id)
|
||||
.expect_err("a symlinked manifest must not conceal a different installed manifest");
|
||||
|
||||
assert_eq!(err.to_string(), "missing plugin.json");
|
||||
assert!(
|
||||
!tmp.path()
|
||||
.join("plugins/cache/debug/manifest-switch")
|
||||
.exists()
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn install_rejects_symlinked_manifest_directory() {
|
||||
let tmp = tempdir().unwrap();
|
||||
let plugin_root = tmp.path().join("manifest-switch");
|
||||
let manifest_directory = tmp.path().join("manifest-directory");
|
||||
let claude_path = plugin_root.join(".claude-plugin/plugin.json");
|
||||
fs::create_dir_all(&manifest_directory).unwrap();
|
||||
fs::create_dir_all(claude_path.parent().unwrap()).unwrap();
|
||||
fs::write(
|
||||
manifest_directory.join("plugin.json"),
|
||||
r#"{"name":"manifest-switch"}"#,
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(&claude_path, r#"{"name":"manifest-switch"}"#).unwrap();
|
||||
std::os::unix::fs::symlink(&manifest_directory, plugin_root.join(".codex-plugin")).unwrap();
|
||||
let plugin_id = PluginId::new("manifest-switch".to_string(), "debug".to_string()).unwrap();
|
||||
|
||||
let err = PluginStore::new(tmp.path().to_path_buf())
|
||||
.install(AbsolutePathBuf::try_from(plugin_root).unwrap(), plugin_id)
|
||||
.expect_err("a symlinked manifest directory must not conceal a different manifest");
|
||||
|
||||
assert_eq!(err.to_string(), "missing plugin.json");
|
||||
assert!(
|
||||
!tmp.path()
|
||||
.join("plugins/cache/debug/manifest-switch")
|
||||
.exists()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn install_uses_manifest_name_for_destination_and_key() {
|
||||
let tmp = tempdir().unwrap();
|
||||
write_plugin(tmp.path(), "source-dir", "manifest-name");
|
||||
let plugin_id = PluginId::new("manifest-name".to_string(), "market".to_string()).unwrap();
|
||||
|
||||
let result = PluginStore::new(tmp.path().to_path_buf())
|
||||
.install(
|
||||
AbsolutePathBuf::try_from(tmp.path().join("source-dir")).unwrap(),
|
||||
plugin_id.clone(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
result,
|
||||
PluginInstallResult {
|
||||
plugin_id,
|
||||
plugin_version: "local".to_string(),
|
||||
installed_path: AbsolutePathBuf::try_from(
|
||||
tmp.path().join("plugins/cache/market/manifest-name/local"),
|
||||
)
|
||||
.unwrap(),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plugin_root_derives_path_from_key_and_version() {
|
||||
let tmp = tempdir().unwrap();
|
||||
let store = PluginStore::new(tmp.path().to_path_buf());
|
||||
let plugin_id = PluginId::new("sample".to_string(), "debug".to_string()).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
store.plugin_root(&plugin_id, "local").as_path(),
|
||||
tmp.path().join("plugins/cache/debug/sample/local")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plugin_data_root_derives_path_from_key() {
|
||||
let tmp = tempdir().unwrap();
|
||||
let store = PluginStore::new(tmp.path().to_path_buf());
|
||||
let plugin_id = PluginId::new("sample".to_string(), "debug".to_string()).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
store.plugin_data_root(&plugin_id).as_path(),
|
||||
tmp.path().join("plugins/data/sample-debug")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agent_plugin_data_root_is_stable_and_unambiguous() {
|
||||
let tmp = tempdir().unwrap();
|
||||
let store = PluginStore::new(tmp.path().to_path_buf());
|
||||
let first = PluginId::new("a-b".to_string(), "c".to_string()).unwrap();
|
||||
let second = PluginId::new("a".to_string(), "b-c".to_string()).unwrap();
|
||||
|
||||
let first_root = store.agent_plugin_data_root(&first);
|
||||
let second_root = store.agent_plugin_data_root(&second);
|
||||
let expected_parent = tmp.path().join("plugins/data/agent-plugins");
|
||||
|
||||
assert_ne!(first_root, second_root);
|
||||
assert_eq!(
|
||||
first_root.as_path(),
|
||||
expected_parent.join("6920dd17774030852d11d1b94758fcaae4f894c7b2f36301ed174bc3b33e0743")
|
||||
);
|
||||
assert_eq!(
|
||||
second_root.as_path(),
|
||||
expected_parent.join("fa89b988ebbe54a68fdcbeb87fb913a5238d482084a3cee49a86288c2d45fa90")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn install_with_version_uses_requested_cache_version() {
|
||||
let tmp = tempdir().unwrap();
|
||||
write_plugin(tmp.path(), "sample-plugin", "sample-plugin");
|
||||
let plugin_id =
|
||||
PluginId::new("sample-plugin".to_string(), "openai-curated".to_string()).unwrap();
|
||||
let plugin_version = "0123456789abcdef".to_string();
|
||||
|
||||
let result = PluginStore::new(tmp.path().to_path_buf())
|
||||
.install_with_version(
|
||||
AbsolutePathBuf::try_from(tmp.path().join("sample-plugin")).unwrap(),
|
||||
plugin_id.clone(),
|
||||
plugin_version.clone(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let installed_path = tmp.path().join(format!(
|
||||
"plugins/cache/openai-curated/sample-plugin/{plugin_version}"
|
||||
));
|
||||
assert_eq!(
|
||||
result,
|
||||
PluginInstallResult {
|
||||
plugin_id,
|
||||
plugin_version,
|
||||
installed_path: AbsolutePathBuf::try_from(installed_path.clone()).unwrap(),
|
||||
}
|
||||
);
|
||||
assert!(installed_path.join(".codex-plugin/plugin.json").is_file());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn install_prefers_on_disk_manifest_version_over_fallback() {
|
||||
let tmp = tempdir().unwrap();
|
||||
write_plugin_with_version(
|
||||
tmp.path(),
|
||||
"sample-plugin",
|
||||
"sample-plugin",
|
||||
Some("1.2.3-beta+7"),
|
||||
);
|
||||
let plugin_id = PluginId::new("sample-plugin".to_string(), "debug".to_string()).unwrap();
|
||||
|
||||
let result = PluginStore::new(tmp.path().to_path_buf())
|
||||
.install_with_fallback_manifest(
|
||||
AbsolutePathBuf::try_from(tmp.path().join("sample-plugin")).unwrap(),
|
||||
plugin_id.clone(),
|
||||
r#"{"name":"sample-plugin","version":"9.9.9"}"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let installed_path = tmp
|
||||
.path()
|
||||
.join("plugins/cache/debug/sample-plugin/1.2.3-beta+7");
|
||||
assert_eq!(
|
||||
result,
|
||||
PluginInstallResult {
|
||||
plugin_id,
|
||||
plugin_version: "1.2.3-beta+7".to_string(),
|
||||
installed_path: AbsolutePathBuf::try_from(installed_path.clone()).unwrap(),
|
||||
}
|
||||
);
|
||||
assert!(installed_path.join(".codex-plugin/plugin.json").is_file());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn install_stages_fallback_manifest_when_source_has_no_manifest() {
|
||||
let tmp = tempdir().unwrap();
|
||||
let plugin_root = tmp.path().join("fallback-plugin");
|
||||
fs::create_dir_all(plugin_root.join("skills")).unwrap();
|
||||
let manifest = r#"{"name":"fallback-plugin","version":"1.2.3"}"#;
|
||||
let plugin_id = PluginId::new("fallback-plugin".to_string(), "debug".to_string()).unwrap();
|
||||
|
||||
let result = PluginStore::new(tmp.path().to_path_buf())
|
||||
.install_with_fallback_manifest(
|
||||
AbsolutePathBuf::try_from(plugin_root).unwrap(),
|
||||
plugin_id,
|
||||
manifest,
|
||||
)
|
||||
.expect("install plugin with fallback manifest");
|
||||
|
||||
assert_eq!(
|
||||
fs::read_to_string(result.installed_path.join(".codex-plugin/plugin.json")).unwrap(),
|
||||
manifest,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn install_rejects_blank_manifest_version() {
|
||||
let tmp = tempdir().unwrap();
|
||||
write_plugin_with_version(tmp.path(), "sample-plugin", "sample-plugin", Some(" "));
|
||||
let plugin_id = PluginId::new("sample-plugin".to_string(), "debug".to_string()).unwrap();
|
||||
|
||||
let err = PluginStore::new(tmp.path().to_path_buf())
|
||||
.install(
|
||||
AbsolutePathBuf::try_from(tmp.path().join("sample-plugin")).unwrap(),
|
||||
plugin_id,
|
||||
)
|
||||
.expect_err("blank manifest version should be rejected");
|
||||
let err = err.to_string().replace('\\', "/");
|
||||
|
||||
assert_eq!(
|
||||
err,
|
||||
"invalid plugin version in plugin.json: must not be blank"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agent_plugin_blank_version_uses_default_version() {
|
||||
let tmp = tempdir().unwrap();
|
||||
let plugin_root = tmp.path().join("agent-plugin");
|
||||
fs::create_dir_all(&plugin_root).unwrap();
|
||||
fs::write(
|
||||
plugin_root.join("plugin.json"),
|
||||
r#"{"$schema":"https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","name":"agent-plugin","version":" "}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let plugin_id = PluginId::new("agent-plugin".to_string(), "debug".to_string()).unwrap();
|
||||
|
||||
let result = PluginStore::new(tmp.path().to_path_buf())
|
||||
.install(AbsolutePathBuf::try_from(plugin_root).unwrap(), plugin_id)
|
||||
.expect("install Agent Plugin");
|
||||
|
||||
assert_eq!(result.plugin_version, DEFAULT_AGENT_PLUGIN_VERSION);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agent_plugin_install_does_not_migrate_commands() {
|
||||
let tmp = tempdir().unwrap();
|
||||
let plugin_root = tmp.path().join("agent-plugin");
|
||||
fs::create_dir_all(plugin_root.join("commands")).unwrap();
|
||||
fs::write(
|
||||
plugin_root.join("plugin.json"),
|
||||
r#"{"$schema":"https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","name":"agent-plugin","commands":"./commands"}"#,
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(plugin_root.join("commands/demo.md"), "# Demo").unwrap();
|
||||
let plugin_id = PluginId::new("agent-plugin".to_string(), "debug".to_string()).unwrap();
|
||||
|
||||
let result = PluginStore::new(tmp.path().to_path_buf())
|
||||
.install(AbsolutePathBuf::try_from(plugin_root).unwrap(), plugin_id)
|
||||
.expect("install Agent Plugin");
|
||||
|
||||
assert!(
|
||||
!result
|
||||
.installed_path
|
||||
.join(".codex-plugin/migrated-command-skills")
|
||||
.exists()
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn agent_plugin_install_skips_symlinked_skill_file() {
|
||||
let tmp = tempdir().unwrap();
|
||||
let plugin_root = tmp.path().join("agent-plugin");
|
||||
let skill_root = plugin_root.join("skills/greet");
|
||||
fs::create_dir_all(&skill_root).unwrap();
|
||||
fs::write(
|
||||
plugin_root.join("plugin.json"),
|
||||
r#"{"$schema":"https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","name":"agent-plugin"}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let outside_skill = tmp.path().join("outside-SKILL.md");
|
||||
fs::write(&outside_skill, "---\nname: greet\n---\n").unwrap();
|
||||
std::os::unix::fs::symlink(&outside_skill, skill_root.join("SKILL.md")).unwrap();
|
||||
let plugin_id = PluginId::new("agent-plugin".to_string(), "debug".to_string()).unwrap();
|
||||
|
||||
let result = PluginStore::new(tmp.path().to_path_buf())
|
||||
.install(AbsolutePathBuf::try_from(plugin_root).unwrap(), plugin_id)
|
||||
.expect("install Agent Plugin");
|
||||
|
||||
assert!(result.installed_path.join("plugin.json").is_file());
|
||||
assert!(!result.installed_path.join("skills/greet/SKILL.md").exists());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn agent_plugin_install_skips_symlinked_executable() {
|
||||
let tmp = tempdir().unwrap();
|
||||
let plugin_root = tmp.path().join("agent-plugin");
|
||||
let bin_root = plugin_root.join("bin");
|
||||
fs::create_dir_all(&bin_root).unwrap();
|
||||
fs::write(
|
||||
plugin_root.join("plugin.json"),
|
||||
r#"{"$schema":"https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","name":"agent-plugin"}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let outside_executable = tmp.path().join("outside-tool");
|
||||
fs::write(&outside_executable, "#!/bin/sh\n").unwrap();
|
||||
std::os::unix::fs::symlink(&outside_executable, bin_root.join("tool")).unwrap();
|
||||
let plugin_id = PluginId::new("agent-plugin".to_string(), "debug".to_string()).unwrap();
|
||||
|
||||
let result = PluginStore::new(tmp.path().to_path_buf())
|
||||
.install(AbsolutePathBuf::try_from(plugin_root).unwrap(), plugin_id)
|
||||
.expect("install Agent Plugin");
|
||||
|
||||
assert!(result.installed_path.join("plugin.json").is_file());
|
||||
assert!(!result.installed_path.join("bin/tool").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn active_plugin_version_reads_version_directory_name() {
|
||||
let tmp = tempdir().unwrap();
|
||||
write_plugin(
|
||||
&tmp.path().join("plugins/cache/debug"),
|
||||
"sample-plugin/local",
|
||||
"sample-plugin",
|
||||
);
|
||||
let store = PluginStore::new(tmp.path().to_path_buf());
|
||||
let plugin_id = PluginId::new("sample-plugin".to_string(), "debug".to_string()).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
store.active_plugin_version(&plugin_id),
|
||||
Some("local".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
store.active_plugin_root(&plugin_id).unwrap().as_path(),
|
||||
tmp.path().join("plugins/cache/debug/sample-plugin/local")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn active_plugin_version_prefers_default_local_version_when_multiple_versions_exist() {
|
||||
let tmp = tempdir().unwrap();
|
||||
write_plugin(
|
||||
&tmp.path().join("plugins/cache/debug"),
|
||||
"sample-plugin/0123456789abcdef",
|
||||
"sample-plugin",
|
||||
);
|
||||
write_plugin(
|
||||
&tmp.path().join("plugins/cache/debug"),
|
||||
"sample-plugin/local",
|
||||
"sample-plugin",
|
||||
);
|
||||
let store = PluginStore::new(tmp.path().to_path_buf());
|
||||
let plugin_id = PluginId::new("sample-plugin".to_string(), "debug".to_string()).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
store.active_plugin_version(&plugin_id),
|
||||
Some("local".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn active_plugin_version_returns_latest_version_when_default_is_missing() {
|
||||
let tmp = tempdir().unwrap();
|
||||
write_plugin(
|
||||
&tmp.path().join("plugins/cache/debug"),
|
||||
"sample-plugin/0123456789abcdef",
|
||||
"sample-plugin",
|
||||
);
|
||||
write_plugin(
|
||||
&tmp.path().join("plugins/cache/debug"),
|
||||
"sample-plugin/fedcba9876543210",
|
||||
"sample-plugin",
|
||||
);
|
||||
let store = PluginStore::new(tmp.path().to_path_buf());
|
||||
let plugin_id = PluginId::new("sample-plugin".to_string(), "debug".to_string()).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
store.active_plugin_version(&plugin_id),
|
||||
Some("fedcba9876543210".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn active_plugin_version_compares_semver_versions_semantically() {
|
||||
let tmp = tempdir().unwrap();
|
||||
write_plugin(
|
||||
&tmp.path().join("plugins/cache/debug"),
|
||||
"sample-plugin/9.0.0",
|
||||
"sample-plugin",
|
||||
);
|
||||
write_plugin(
|
||||
&tmp.path().join("plugins/cache/debug"),
|
||||
"sample-plugin/10.0.0",
|
||||
"sample-plugin",
|
||||
);
|
||||
let store = PluginStore::new(tmp.path().to_path_buf());
|
||||
let plugin_id = PluginId::new("sample-plugin".to_string(), "debug".to_string()).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
store.active_plugin_version(&plugin_id),
|
||||
Some("10.0.0".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn install_with_new_version_keeps_existing_plugin_root_and_prunes_old_versions() {
|
||||
let tmp = tempdir().unwrap();
|
||||
let store = PluginStore::new(tmp.path().to_path_buf());
|
||||
let plugin_id = PluginId::new("sample-plugin".to_string(), "debug".to_string()).unwrap();
|
||||
|
||||
write_plugin_with_version(tmp.path(), "v1", "sample-plugin", Some("1.0.0"));
|
||||
store
|
||||
.install(
|
||||
AbsolutePathBuf::try_from(tmp.path().join("v1")).unwrap(),
|
||||
plugin_id.clone(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
write_plugin_with_version(tmp.path(), "v2", "sample-plugin", Some("2.0.0"));
|
||||
store
|
||||
.install(
|
||||
AbsolutePathBuf::try_from(tmp.path().join("v2")).unwrap(),
|
||||
plugin_id.clone(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
store.active_plugin_version(&plugin_id),
|
||||
Some("2.0.0".to_string())
|
||||
);
|
||||
assert!(
|
||||
tmp.path()
|
||||
.join("plugins/cache/debug/sample-plugin/2.0.0")
|
||||
.is_dir()
|
||||
);
|
||||
assert!(
|
||||
!tmp.path()
|
||||
.join("plugins/cache/debug/sample-plugin/1.0.0")
|
||||
.exists()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn old_plugin_version_would_stay_active_for_local_or_later_versions() {
|
||||
assert!(old_plugin_version_would_stay_active(
|
||||
DEFAULT_PLUGIN_VERSION,
|
||||
"1.0.0"
|
||||
));
|
||||
assert!(old_plugin_version_would_stay_active("10.0.0", "9.0.0"));
|
||||
assert!(!old_plugin_version_would_stay_active("1.0.0", "2.0.0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plugin_root_rejects_path_separators_in_key_segments() {
|
||||
let err = PluginId::parse("../../etc@debug").unwrap_err();
|
||||
assert_eq!(
|
||||
err.to_string(),
|
||||
"invalid plugin name: dots must separate non-empty name segments in `../../etc@debug`"
|
||||
);
|
||||
|
||||
let err = PluginId::parse("sample@../../etc").unwrap_err();
|
||||
assert_eq!(
|
||||
err.to_string(),
|
||||
"invalid marketplace name: only ASCII letters, digits, `_`, and `-` are allowed in `sample@../../etc`"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn install_rejects_manifest_names_with_path_separators() {
|
||||
let tmp = tempdir().unwrap();
|
||||
write_plugin(tmp.path(), "source-dir", "../../etc");
|
||||
|
||||
let err = PluginStore::new(tmp.path().to_path_buf())
|
||||
.install(
|
||||
AbsolutePathBuf::try_from(tmp.path().join("source-dir")).unwrap(),
|
||||
PluginId::new("source-dir".to_string(), "debug".to_string()).unwrap(),
|
||||
)
|
||||
.unwrap_err();
|
||||
|
||||
assert_eq!(
|
||||
err.to_string(),
|
||||
"invalid plugin name: dots must separate non-empty name segments"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn install_rejects_marketplace_names_with_path_separators() {
|
||||
let err = PluginId::new("sample-plugin".to_string(), "../../etc".to_string()).unwrap_err();
|
||||
|
||||
assert_eq!(
|
||||
err.to_string(),
|
||||
"invalid marketplace name: only ASCII letters, digits, `_`, and `-` are allowed"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn install_rejects_manifest_names_that_do_not_match_marketplace_plugin_name() {
|
||||
let tmp = tempdir().unwrap();
|
||||
write_plugin(tmp.path(), "source-dir", "manifest-name");
|
||||
|
||||
let err = PluginStore::new(tmp.path().to_path_buf())
|
||||
.install(
|
||||
AbsolutePathBuf::try_from(tmp.path().join("source-dir")).unwrap(),
|
||||
PluginId::new("different-name".to_string(), "debug".to_string()).unwrap(),
|
||||
)
|
||||
.unwrap_err();
|
||||
|
||||
assert_eq!(
|
||||
err.to_string(),
|
||||
"plugin.json name `manifest-name` does not match marketplace plugin name `different-name`"
|
||||
);
|
||||
}
|
||||
452
akode-rs/core-plugins/src/test_support.rs
Normal file
452
akode-rs/core-plugins/src/test_support.rs
Normal file
@@ -0,0 +1,452 @@
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::OPENAI_API_CURATED_MARKETPLACE_NAME;
|
||||
use crate::OPENAI_CURATED_MARKETPLACE_NAME;
|
||||
use crate::PluginsConfigInput;
|
||||
use crate::PluginsManager;
|
||||
use akode_config::LoaderOverrides;
|
||||
use akode_config::NoopThreadConfigLoader;
|
||||
use akode_config::loader::load_config_layers_state;
|
||||
use akode_exec_server::LOCAL_FS;
|
||||
use akode_login::AuthHeaders;
|
||||
use akode_login::AuthManager;
|
||||
use akode_login::CodexAuth;
|
||||
use akode_login::ExternalAuth;
|
||||
use akode_login::ExternalAuthFuture;
|
||||
use akode_login::ExternalAuthRefreshContext;
|
||||
use akode_login::auth::BedrockAccessKeysAuth;
|
||||
use akode_login::auth::BedrockApiKeyAuth;
|
||||
use akode_login::test_support::auth_manager_from_optional_auth;
|
||||
use akode_protocol::auth::AuthMode;
|
||||
use akode_protocol::protocol::Product;
|
||||
use akode_protocol::protocol::SkillScope;
|
||||
use akode_skills::LoadedSkillRoot;
|
||||
use akode_skills::LoadedSkills;
|
||||
use akode_skills::SkillError;
|
||||
use akode_skills::SkillLoadFuture;
|
||||
use akode_skills::SkillMetadata;
|
||||
use akode_skills::SkillRootLoadRequest;
|
||||
use akode_skills::SkillRootLoader;
|
||||
use akode_skills::parse_skill_frontmatter_metadata;
|
||||
use akode_utils_absolute_path::AbsolutePathBuf;
|
||||
use akode_utils_path_uri::PathUri;
|
||||
use akode_utils_plugins::PluginSkillRoot;
|
||||
use akode_utils_plugins::SkillDiscoveryMode;
|
||||
use akode_utils_plugins::migrated_command_skills_root;
|
||||
use toml::Value;
|
||||
|
||||
pub(crate) const TEST_CURATED_PLUGIN_SHA: &str = "0123456789abcdef0123456789abcdef01234567";
|
||||
pub(crate) const TEST_CURATED_PLUGIN_CACHE_VERSION: &str = "01234567";
|
||||
|
||||
#[cfg(windows)]
|
||||
/// Model redirected directories without requiring Windows symlink privileges.
|
||||
pub(crate) fn create_directory_junction(target: &Path, alias: &Path) {
|
||||
let output = akode_utils_process::background_command("cmd")
|
||||
.args(["/D", "/C", "mklink", "/J"])
|
||||
.arg(alias)
|
||||
.arg(target)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(output.status.success(), "mklink /J failed: {output:?}");
|
||||
}
|
||||
|
||||
pub(crate) fn test_plugins_manager(codex_home: PathBuf) -> PluginsManager {
|
||||
PluginsManager::new(
|
||||
codex_home,
|
||||
test_auth_manager(/*auth_mode*/ None),
|
||||
test_skill_root_loader(),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn test_plugins_manager_with_options(
|
||||
codex_home: PathBuf,
|
||||
restriction_product: Option<Product>,
|
||||
auth_mode: Option<AuthMode>,
|
||||
) -> PluginsManager {
|
||||
PluginsManager::new_with_options(
|
||||
codex_home,
|
||||
restriction_product,
|
||||
test_auth_manager(auth_mode),
|
||||
test_skill_root_loader(),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn test_plugins_manager_with_auth_manager(
|
||||
codex_home: PathBuf,
|
||||
restriction_product: Option<Product>,
|
||||
auth_manager: Arc<AuthManager>,
|
||||
) -> PluginsManager {
|
||||
PluginsManager::new_with_options(
|
||||
codex_home,
|
||||
restriction_product,
|
||||
auth_manager,
|
||||
test_skill_root_loader(),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn test_auth_manager(auth_mode: Option<AuthMode>) -> Arc<AuthManager> {
|
||||
auth_manager_from_optional_auth(test_codex_auth(auth_mode))
|
||||
}
|
||||
|
||||
pub(crate) async fn set_test_auth_mode(auth_manager: &AuthManager, auth_mode: Option<AuthMode>) {
|
||||
set_test_auth(auth_manager, test_codex_auth(auth_mode)).await;
|
||||
}
|
||||
|
||||
pub(crate) async fn set_test_auth(auth_manager: &AuthManager, auth: Option<CodexAuth>) {
|
||||
let Some(auth) = auth else {
|
||||
auth_manager.clear_external_auth();
|
||||
return;
|
||||
};
|
||||
auth_manager
|
||||
.set_external_auth(Arc::new(StaticExternalAuth(auth)))
|
||||
.await
|
||||
.expect("test auth should update");
|
||||
}
|
||||
|
||||
fn test_codex_auth(auth_mode: Option<AuthMode>) -> Option<CodexAuth> {
|
||||
auth_mode.map(|auth_mode| match auth_mode {
|
||||
AuthMode::ApiKey => CodexAuth::from_api_key("test-api-key"),
|
||||
AuthMode::Headers => CodexAuth::Headers(AuthHeaders::new(http::HeaderMap::new())),
|
||||
AuthMode::BedrockApiKey => CodexAuth::BedrockApiKey(BedrockApiKeyAuth {
|
||||
api_key: "test-api-key".to_string(),
|
||||
region: "us-east-1".to_string(),
|
||||
}),
|
||||
AuthMode::BedrockAccessKeys => CodexAuth::BedrockAccessKeys(BedrockAccessKeysAuth {
|
||||
access_key_id: "test-access-key-id".to_string(),
|
||||
secret_access_key: "test-secret-access-key".to_string(),
|
||||
session_token: None,
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
struct StaticExternalAuth(CodexAuth);
|
||||
|
||||
impl ExternalAuth for StaticExternalAuth {
|
||||
fn resolve(&self) -> ExternalAuthFuture<'_, CodexAuth> {
|
||||
Box::pin(async { Ok(self.0.clone()) })
|
||||
}
|
||||
|
||||
fn refresh(&self, _context: ExternalAuthRefreshContext) -> ExternalAuthFuture<'_, CodexAuth> {
|
||||
Box::pin(async { Ok(self.0.clone()) })
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn test_skill_root_loader() -> Arc<dyn SkillRootLoader<PluginSkillRoot>> {
|
||||
Arc::new(TestSkillRootLoader)
|
||||
}
|
||||
|
||||
struct TestSkillRootLoader;
|
||||
|
||||
impl SkillRootLoader<PluginSkillRoot> for TestSkillRootLoader {
|
||||
fn load_roots(
|
||||
&self,
|
||||
request: SkillRootLoadRequest<PluginSkillRoot>,
|
||||
) -> SkillLoadFuture<'_, LoadedSkills> {
|
||||
Box::pin(async move {
|
||||
let mut loaded_roots = Vec::new();
|
||||
for root in request.roots {
|
||||
let cached = request
|
||||
.snapshots
|
||||
.as_ref()
|
||||
.and_then(|cache| cache.get(&root));
|
||||
let snapshot = match cached {
|
||||
Some(snapshot) => snapshot,
|
||||
None => {
|
||||
let snapshot = load_test_skill_root(&root);
|
||||
if let Some(snapshots) = &request.snapshots {
|
||||
snapshots.insert(root.clone(), snapshot.clone());
|
||||
}
|
||||
snapshot
|
||||
}
|
||||
};
|
||||
let migrated_root = migrated_command_skills_root(&root.plugin_root);
|
||||
let canonical_migrated_root = fs::canonicalize(migrated_root.as_path())
|
||||
.ok()
|
||||
.and_then(|path| AbsolutePathBuf::from_absolute_path_checked(path).ok())
|
||||
.unwrap_or(migrated_root);
|
||||
loaded_roots.push((snapshot.root == canonical_migrated_root, snapshot));
|
||||
}
|
||||
|
||||
let native_names = loaded_roots
|
||||
.iter()
|
||||
.filter(|(migrated, _)| !migrated)
|
||||
.flat_map(|(_, snapshot)| &snapshot.skills)
|
||||
.map(|skill| (skill.plugin_id.clone(), skill.name.clone()))
|
||||
.collect::<HashSet<_>>();
|
||||
let mut seen_paths = HashSet::new();
|
||||
let mut outcome = LoadedSkills::default();
|
||||
for (migrated, snapshot) in loaded_roots {
|
||||
outcome
|
||||
.skills
|
||||
.extend(snapshot.skills.into_iter().filter(|skill| {
|
||||
(!migrated
|
||||
|| !native_names
|
||||
.contains(&(skill.plugin_id.clone(), skill.name.clone())))
|
||||
&& skill.matches_product_restriction_for_product(
|
||||
request.restriction_product,
|
||||
)
|
||||
&& seen_paths.insert(skill.path_to_skills_md.clone())
|
||||
}));
|
||||
outcome.errors.extend(snapshot.errors);
|
||||
}
|
||||
outcome.skills.sort_by(|left, right| {
|
||||
left.name.cmp(&right.name).then_with(|| {
|
||||
left.path_to_skills_md
|
||||
.to_abs_path()
|
||||
.expect("host test skill path")
|
||||
.cmp(
|
||||
&right
|
||||
.path_to_skills_md
|
||||
.to_abs_path()
|
||||
.expect("host test skill path"),
|
||||
)
|
||||
})
|
||||
});
|
||||
outcome
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn load_test_skill_root(root: &PluginSkillRoot) -> LoadedSkillRoot {
|
||||
let canonical_root = fs::canonicalize(root.path.as_path())
|
||||
.ok()
|
||||
.and_then(|path| AbsolutePathBuf::from_absolute_path_checked(path).ok())
|
||||
.unwrap_or_else(|| root.path.clone());
|
||||
let mut skills = Vec::new();
|
||||
let mut errors = Vec::new();
|
||||
let mut discovery_paths = HashMap::new();
|
||||
let mut directories = vec![root.path.clone()];
|
||||
while let Some(directory) = directories.pop() {
|
||||
let Ok(entries) = fs::read_dir(directory.as_path()) else {
|
||||
continue;
|
||||
};
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path.is_dir() {
|
||||
if (root.discovery_mode == SkillDiscoveryMode::Recursive || directory == root.path)
|
||||
&& let Ok(path) = AbsolutePathBuf::from_absolute_path_checked(path)
|
||||
{
|
||||
directories.push(path);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if path.file_name().is_none_or(|name| name != "SKILL.md")
|
||||
|| (root.discovery_mode == SkillDiscoveryMode::DirectChildren
|
||||
&& directory == root.path)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let Ok(path) = AbsolutePathBuf::from_absolute_path_checked(path) else {
|
||||
continue;
|
||||
};
|
||||
let canonical_path = fs::canonicalize(path.as_path())
|
||||
.ok()
|
||||
.and_then(|path| AbsolutePathBuf::from_absolute_path_checked(path).ok())
|
||||
.unwrap_or_else(|| path.clone());
|
||||
let parsed = fs::read_to_string(path.as_path())
|
||||
.map_err(|error| error.to_string())
|
||||
.and_then(|contents| {
|
||||
parse_skill_frontmatter_metadata(&contents, || {
|
||||
directory
|
||||
.as_path()
|
||||
.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.unwrap_or_default()
|
||||
.to_string()
|
||||
})
|
||||
.map_err(|error| error.to_string())
|
||||
});
|
||||
match parsed {
|
||||
Ok(parsed) => {
|
||||
discovery_paths.insert(
|
||||
PathUri::from_abs_path(&canonical_path),
|
||||
PathUri::from_abs_path(&path),
|
||||
);
|
||||
skills.push(SkillMetadata {
|
||||
name: format!("{}:{}", root.plugin_namespace, parsed.name),
|
||||
description: parsed.description,
|
||||
short_description: parsed.short_description,
|
||||
interface: None,
|
||||
dependencies: None,
|
||||
policy: None,
|
||||
path_to_skills_md: PathUri::from_abs_path(&canonical_path),
|
||||
scope: SkillScope::User,
|
||||
plugin_id: Some(root.plugin_identity.plugin_id.clone()),
|
||||
});
|
||||
}
|
||||
Err(message) => errors.push(SkillError {
|
||||
path: canonical_path,
|
||||
message,
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
LoadedSkillRoot {
|
||||
root: canonical_root,
|
||||
skills,
|
||||
skill_discovery_path_by_path: Arc::new(discovery_paths),
|
||||
errors,
|
||||
is_agent_plugin: root.discovery_mode == SkillDiscoveryMode::DirectChildren,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn write_file(path: &Path, contents: &str) {
|
||||
fs::create_dir_all(path.parent().expect("file should have a parent")).unwrap();
|
||||
fs::write(path, contents).unwrap();
|
||||
}
|
||||
|
||||
pub(crate) fn write_curated_plugin(root: &Path, plugin_name: &str) {
|
||||
let plugin_root = root.join("plugins").join(plugin_name);
|
||||
write_file(
|
||||
&plugin_root.join(".codex-plugin/plugin.json"),
|
||||
&format!(
|
||||
r#"{{
|
||||
"name": "{plugin_name}",
|
||||
"description": "Plugin that includes skills, MCP servers, and app connectors"
|
||||
}}"#
|
||||
),
|
||||
);
|
||||
write_file(
|
||||
&plugin_root.join("skills/SKILL.md"),
|
||||
"---\nname: sample\ndescription: sample\n---\n",
|
||||
);
|
||||
write_file(
|
||||
&plugin_root.join(".mcp.json"),
|
||||
r#"{
|
||||
"mcpServers": {
|
||||
"sample-docs": {
|
||||
"type": "http",
|
||||
"url": "https://sample.example/mcp"
|
||||
}
|
||||
}
|
||||
}"#,
|
||||
);
|
||||
write_file(
|
||||
&plugin_root.join(".app.json"),
|
||||
r#"{
|
||||
"apps": {
|
||||
"calendar": {
|
||||
"id": "connector_calendar"
|
||||
}
|
||||
}
|
||||
}"#,
|
||||
);
|
||||
}
|
||||
|
||||
pub(crate) fn write_openai_curated_marketplace(root: &Path, plugin_names: &[&str]) {
|
||||
write_curated_marketplace(
|
||||
root,
|
||||
"marketplace.json",
|
||||
OPENAI_CURATED_MARKETPLACE_NAME,
|
||||
/*display_name*/ None,
|
||||
plugin_names,
|
||||
);
|
||||
}
|
||||
|
||||
pub(crate) fn write_openai_api_curated_marketplace(root: &Path, plugin_names: &[&str]) {
|
||||
write_curated_marketplace(
|
||||
root,
|
||||
"api_marketplace.json",
|
||||
OPENAI_API_CURATED_MARKETPLACE_NAME,
|
||||
Some("OpenAI Curated"),
|
||||
plugin_names,
|
||||
);
|
||||
}
|
||||
|
||||
fn write_curated_marketplace(
|
||||
root: &Path,
|
||||
manifest_name: &str,
|
||||
marketplace_name: &str,
|
||||
display_name: Option<&str>,
|
||||
plugin_names: &[&str],
|
||||
) {
|
||||
let plugins = plugin_names
|
||||
.iter()
|
||||
.map(|plugin_name| {
|
||||
format!(
|
||||
r#"{{
|
||||
"name": "{plugin_name}",
|
||||
"source": {{
|
||||
"source": "local",
|
||||
"path": "./plugins/{plugin_name}"
|
||||
}}
|
||||
}}"#
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(",\n");
|
||||
let interface = display_name
|
||||
.map(|display_name| {
|
||||
format!(
|
||||
r#"
|
||||
"interface": {{
|
||||
"displayName": "{display_name}"
|
||||
}},"#
|
||||
)
|
||||
})
|
||||
.unwrap_or_default();
|
||||
write_file(
|
||||
&root.join(".agents/plugins").join(manifest_name),
|
||||
&format!(
|
||||
r#"{{
|
||||
"name": "{marketplace_name}",{interface}
|
||||
"plugins": [
|
||||
{plugins}
|
||||
]
|
||||
}}"#
|
||||
),
|
||||
);
|
||||
for plugin_name in plugin_names {
|
||||
write_curated_plugin(root, plugin_name);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn write_curated_plugin_sha_with(codex_home: &Path, sha: &str) {
|
||||
write_file(&codex_home.join(".tmp/plugins.sha"), &format!("{sha}\n"));
|
||||
}
|
||||
|
||||
pub(crate) async fn load_plugins_config(codex_home: &Path, cwd: &Path) -> PluginsConfigInput {
|
||||
let codex_home = AbsolutePathBuf::try_from(codex_home).expect("codex home should be absolute");
|
||||
let cwd = AbsolutePathBuf::try_from(cwd).expect("cwd should be absolute");
|
||||
let config_layer_stack = load_config_layers_state(
|
||||
LOCAL_FS.as_ref(),
|
||||
codex_home.as_path(),
|
||||
Some(cwd),
|
||||
&[],
|
||||
LoaderOverrides::without_managed_config_for_tests(),
|
||||
&NoopThreadConfigLoader,
|
||||
)
|
||||
.await
|
||||
.expect("config should load");
|
||||
let effective_config = config_layer_stack.effective_config();
|
||||
let model_provider_id = effective_config
|
||||
.get("model_provider")
|
||||
.and_then(toml::Value::as_str)
|
||||
.unwrap_or_default()
|
||||
.to_string();
|
||||
PluginsConfigInput::new(
|
||||
config_layer_stack,
|
||||
effective_config
|
||||
.clone()
|
||||
.try_into::<akode_config::config_toml::ConfigToml>()
|
||||
.unwrap()
|
||||
.plugins,
|
||||
model_provider_id,
|
||||
feature_enabled(&effective_config, "plugins", /*default_enabled*/ true),
|
||||
)
|
||||
}
|
||||
|
||||
fn feature_enabled(config: &Value, key: &str, default_enabled: bool) -> bool {
|
||||
config
|
||||
.get("features")
|
||||
.and_then(Value::as_table)
|
||||
.and_then(|features| features.get(key))
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(default_enabled)
|
||||
}
|
||||
100
akode-rs/core-plugins/src/toggles.rs
Normal file
100
akode-rs/core-plugins/src/toggles.rs
Normal file
@@ -0,0 +1,100 @@
|
||||
use serde_json::Value as JsonValue;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
pub fn collect_plugin_enabled_candidates<'a>(
|
||||
edits: impl Iterator<Item = (&'a String, &'a JsonValue)>,
|
||||
) -> BTreeMap<String, bool> {
|
||||
let mut pending_changes = BTreeMap::new();
|
||||
for (key_path, value) in edits {
|
||||
let segments = key_path
|
||||
.split('.')
|
||||
.map(str::to_string)
|
||||
.collect::<Vec<String>>();
|
||||
match segments.as_slice() {
|
||||
[plugins, plugin_id, enabled]
|
||||
if plugins == "plugins" && enabled == "enabled" && value.is_boolean() =>
|
||||
{
|
||||
if let Some(enabled) = value.as_bool() {
|
||||
pending_changes.insert(plugin_id.clone(), enabled);
|
||||
}
|
||||
}
|
||||
[plugins, plugin_id] if plugins == "plugins" => {
|
||||
if let Some(enabled) = value.get("enabled").and_then(JsonValue::as_bool) {
|
||||
pending_changes.insert(plugin_id.clone(), enabled);
|
||||
}
|
||||
}
|
||||
[plugins] if plugins == "plugins" => {
|
||||
let Some(entries) = value.as_object() else {
|
||||
continue;
|
||||
};
|
||||
for (plugin_id, plugin_value) in entries {
|
||||
let Some(enabled) = plugin_value.get("enabled").and_then(JsonValue::as_bool)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
pending_changes.insert(plugin_id.clone(), enabled);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
pending_changes
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::collect_plugin_enabled_candidates;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[test]
|
||||
fn collect_plugin_enabled_candidates_tracks_direct_and_table_writes() {
|
||||
let candidates = collect_plugin_enabled_candidates(
|
||||
[
|
||||
(&"plugins.sample@test.enabled".to_string(), &json!(true)),
|
||||
(
|
||||
&"plugins.other@test".to_string(),
|
||||
&json!({ "enabled": false, "ignored": true }),
|
||||
),
|
||||
(
|
||||
&"plugins".to_string(),
|
||||
&json!({
|
||||
"nested@test": { "enabled": true },
|
||||
"skip@test": { "name": "skip" },
|
||||
}),
|
||||
),
|
||||
]
|
||||
.into_iter(),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
candidates,
|
||||
BTreeMap::from([
|
||||
("nested@test".to_string(), true),
|
||||
("other@test".to_string(), false),
|
||||
("sample@test".to_string(), true),
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collect_plugin_enabled_candidates_uses_last_write_for_same_plugin() {
|
||||
let candidates = collect_plugin_enabled_candidates(
|
||||
[
|
||||
(&"plugins.sample@test.enabled".to_string(), &json!(true)),
|
||||
(
|
||||
&"plugins.sample@test".to_string(),
|
||||
&json!({ "enabled": false }),
|
||||
),
|
||||
]
|
||||
.into_iter(),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
candidates,
|
||||
BTreeMap::from([("sample@test".to_string(), false)])
|
||||
);
|
||||
}
|
||||
}
|
||||
241
akode-rs/core-plugins/src/tool_suggest_metadata.rs
Normal file
241
akode-rs/core-plugins/src/tool_suggest_metadata.rs
Normal file
@@ -0,0 +1,241 @@
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::sync::RwLock;
|
||||
|
||||
use akode_config::SkillConfigRules;
|
||||
use akode_plugin::PluginCapabilitySummary;
|
||||
use akode_plugin::PluginId;
|
||||
use akode_plugin::PluginIdError;
|
||||
use akode_plugin::prompt_safe_plugin_description;
|
||||
use akode_protocol::protocol::Product;
|
||||
use akode_skills::SkillRootLoader;
|
||||
use akode_utils_plugins::PluginIdentity;
|
||||
use akode_utils_plugins::PluginSkillRoot;
|
||||
use tokio::sync::Semaphore;
|
||||
|
||||
use crate::loader::PluginSkillInventory;
|
||||
use crate::loader::load_plugin_mcp_servers_from_manifest_with_format;
|
||||
use crate::loader::load_plugin_skill_inventory;
|
||||
use crate::manager::ConfiguredMarketplacePlugin;
|
||||
use crate::manager::source_install_required_description;
|
||||
use crate::manifest::ManifestCache;
|
||||
use crate::marketplace::MarketplaceError;
|
||||
use crate::marketplace::MarketplacePluginSource;
|
||||
|
||||
const MAX_TOOL_SUGGEST_METADATA_CACHE_ENTRIES: usize = 1024;
|
||||
|
||||
type ToolSuggestMetadataEntry = Result<Arc<ToolSuggestMetadataFragment>, String>;
|
||||
|
||||
/// Source-derived plugin metadata cached for tool suggestions.
|
||||
///
|
||||
/// `PluginsManager` clears these entries alongside its loaded-plugin cache. Current skill config
|
||||
/// and auth routing are projected after each lookup and are not part of this cache.
|
||||
pub(crate) struct ToolSuggestMetadataCache {
|
||||
manifest_cache: Arc<ManifestCache>,
|
||||
state: RwLock<ToolSuggestMetadataCacheState>,
|
||||
load_semaphore: Semaphore,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct ToolSuggestMetadataCacheState {
|
||||
generation: u64,
|
||||
entries: HashMap<PluginArtifactIdentity, ToolSuggestMetadataEntry>,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Hash)]
|
||||
struct PluginArtifactIdentity {
|
||||
plugin_id: String,
|
||||
source: MarketplacePluginSource,
|
||||
}
|
||||
|
||||
pub(crate) struct ToolSuggestMetadataFragment {
|
||||
config_name: String,
|
||||
display_name: String,
|
||||
plugin_namespace: Option<String>,
|
||||
description: Option<String>,
|
||||
mcp_server_names: Vec<String>,
|
||||
skill_inventory: Option<PluginSkillInventory>,
|
||||
}
|
||||
|
||||
impl ToolSuggestMetadataFragment {
|
||||
pub(crate) fn project(&self, skill_config_rules: &SkillConfigRules) -> PluginCapabilitySummary {
|
||||
let mut mcp_server_names = self.mcp_server_names.clone();
|
||||
mcp_server_names.sort_unstable();
|
||||
mcp_server_names.dedup();
|
||||
|
||||
PluginCapabilitySummary {
|
||||
config_name: self.config_name.clone(),
|
||||
display_name: self.display_name.clone(),
|
||||
plugin_namespace: self.plugin_namespace.clone(),
|
||||
description: self.description.clone(),
|
||||
has_skills: self
|
||||
.skill_inventory
|
||||
.as_ref()
|
||||
.is_some_and(|inventory| inventory.has_enabled_skills(skill_config_rules)),
|
||||
mcp_server_names,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ToolSuggestMetadataCache {
|
||||
pub(crate) fn new(manifest_cache: Arc<ManifestCache>) -> Self {
|
||||
Self {
|
||||
manifest_cache,
|
||||
state: RwLock::new(ToolSuggestMetadataCacheState::default()),
|
||||
load_semaphore: Semaphore::new(/*permits*/ 1),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn clear(&self) {
|
||||
let mut state = match self.state.write() {
|
||||
Ok(state) => state,
|
||||
Err(err) => err.into_inner(),
|
||||
};
|
||||
state.generation = state.generation.wrapping_add(1);
|
||||
state.entries.clear();
|
||||
}
|
||||
|
||||
pub(crate) async fn metadata_for_plugin(
|
||||
&self,
|
||||
marketplace_name: &str,
|
||||
plugin: &ConfiguredMarketplacePlugin,
|
||||
restriction_product: Option<Product>,
|
||||
skill_root_loader: &dyn SkillRootLoader<PluginSkillRoot>,
|
||||
) -> Result<Arc<ToolSuggestMetadataFragment>, MarketplaceError> {
|
||||
let artifact = PluginArtifactIdentity {
|
||||
plugin_id: plugin.id.clone(),
|
||||
source: plugin.source.clone(),
|
||||
};
|
||||
loop {
|
||||
if let Some(entry) = self.cached_entry(&artifact) {
|
||||
return entry.map_err(MarketplaceError::InvalidPlugin);
|
||||
}
|
||||
|
||||
let _load_permit = self.load_semaphore.acquire().await.map_err(|_| {
|
||||
MarketplaceError::InvalidPlugin(
|
||||
"tool-suggest metadata cache loader closed".to_string(),
|
||||
)
|
||||
})?;
|
||||
if let Some(entry) = self.cached_entry(&artifact) {
|
||||
return entry.map_err(MarketplaceError::InvalidPlugin);
|
||||
}
|
||||
|
||||
let generation = self.generation();
|
||||
let entry = load_plugin_metadata(
|
||||
&self.manifest_cache,
|
||||
marketplace_name,
|
||||
plugin,
|
||||
restriction_product,
|
||||
skill_root_loader,
|
||||
)
|
||||
.await;
|
||||
if self.cache_entry_if_current(generation, artifact.clone(), entry.clone()) {
|
||||
return entry.map_err(MarketplaceError::InvalidPlugin);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn cached_entry(&self, artifact: &PluginArtifactIdentity) -> Option<ToolSuggestMetadataEntry> {
|
||||
match self.state.read() {
|
||||
Ok(state) => state.entries.get(artifact).cloned(),
|
||||
Err(err) => err.into_inner().entries.get(artifact).cloned(),
|
||||
}
|
||||
}
|
||||
|
||||
fn generation(&self) -> u64 {
|
||||
match self.state.read() {
|
||||
Ok(state) => state.generation,
|
||||
Err(err) => err.into_inner().generation,
|
||||
}
|
||||
}
|
||||
|
||||
fn cache_entry_if_current(
|
||||
&self,
|
||||
generation: u64,
|
||||
artifact: PluginArtifactIdentity,
|
||||
entry: ToolSuggestMetadataEntry,
|
||||
) -> bool {
|
||||
let mut state = match self.state.write() {
|
||||
Ok(state) => state,
|
||||
Err(err) => err.into_inner(),
|
||||
};
|
||||
if state.generation != generation {
|
||||
return false;
|
||||
}
|
||||
if state.entries.len() >= MAX_TOOL_SUGGEST_METADATA_CACHE_ENTRIES
|
||||
&& !state.entries.contains_key(&artifact)
|
||||
{
|
||||
state.entries.clear();
|
||||
}
|
||||
state.entries.insert(artifact, entry);
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
async fn load_plugin_metadata(
|
||||
manifest_cache: &ManifestCache,
|
||||
marketplace_name: &str,
|
||||
plugin: &ConfiguredMarketplacePlugin,
|
||||
restriction_product: Option<Product>,
|
||||
skill_root_loader: &dyn SkillRootLoader<PluginSkillRoot>,
|
||||
) -> ToolSuggestMetadataEntry {
|
||||
let plugin_id = PluginId::new(plugin.name.clone(), marketplace_name.to_string()).map_err(
|
||||
|err| match err {
|
||||
PluginIdError::Invalid(message) => message,
|
||||
},
|
||||
)?;
|
||||
|
||||
let MarketplacePluginSource::Local { path: plugin_root } = &plugin.source else {
|
||||
return Ok(Arc::new(ToolSuggestMetadataFragment {
|
||||
config_name: plugin.id.clone(),
|
||||
display_name: plugin.name.clone(),
|
||||
plugin_namespace: Some(plugin.name.clone()),
|
||||
description: prompt_safe_plugin_description(Some(
|
||||
&source_install_required_description(&plugin.source),
|
||||
)),
|
||||
mcp_server_names: Vec::new(),
|
||||
skill_inventory: None,
|
||||
}));
|
||||
};
|
||||
if !plugin_root.as_path().is_dir() {
|
||||
return Err("path does not exist or is not a directory".to_string());
|
||||
}
|
||||
let loaded_manifest = manifest_cache
|
||||
.load(plugin_root.as_path())
|
||||
.ok_or_else(|| "missing or invalid plugin.json".to_string())?;
|
||||
let plugin_identity = PluginIdentity {
|
||||
plugin_id: plugin_id.as_key(),
|
||||
};
|
||||
let manifest = loaded_manifest.manifest;
|
||||
let skill_inventory = load_plugin_skill_inventory(
|
||||
plugin_root,
|
||||
&plugin_identity,
|
||||
&manifest,
|
||||
loaded_manifest.format,
|
||||
restriction_product,
|
||||
/*plugin_skill_snapshots*/ None,
|
||||
skill_root_loader,
|
||||
)
|
||||
.await;
|
||||
let mut mcp_server_names = load_plugin_mcp_servers_from_manifest_with_format(
|
||||
plugin_root.as_path(),
|
||||
&manifest.paths,
|
||||
/*plugin_policy*/ None,
|
||||
/*plugin_data_root*/ None,
|
||||
loaded_manifest.format,
|
||||
)
|
||||
.await
|
||||
.into_keys()
|
||||
.collect::<Vec<_>>();
|
||||
mcp_server_names.sort_unstable();
|
||||
mcp_server_names.dedup();
|
||||
|
||||
Ok(Arc::new(ToolSuggestMetadataFragment {
|
||||
config_name: plugin.id.clone(),
|
||||
display_name: plugin.name.clone(),
|
||||
plugin_namespace: Some(manifest.name.clone()),
|
||||
description: prompt_safe_plugin_description(manifest.description.as_deref()),
|
||||
mcp_server_names,
|
||||
skill_inventory: Some(skill_inventory),
|
||||
}))
|
||||
}
|
||||
Reference in New Issue
Block a user