Base: codex-main originale (prima del fork aKode)
This commit is contained in:
229
codex-rs/ext/skills/src/loader/discovery.rs
Normal file
229
codex-rs/ext/skills/src/loader/discovery.rs
Normal file
@@ -0,0 +1,229 @@
|
||||
use std::collections::HashSet;
|
||||
use std::io;
|
||||
|
||||
use codex_exec_server::EnvironmentAccess;
|
||||
use codex_exec_server::WalkEntryKind;
|
||||
use codex_exec_server::WalkOptions;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use codex_utils_plugins::DISCOVERABLE_PLUGIN_MANIFEST_PATHS;
|
||||
use codex_utils_plugins::SkillDiscoveryMode;
|
||||
|
||||
use super::MAX_SCAN_DEPTH;
|
||||
use super::MAX_SKILLS_DIRS_PER_ROOT;
|
||||
use super::SKILLS_FILENAME;
|
||||
use super::SKILLS_METADATA_DIR;
|
||||
use super::SKILLS_METADATA_FILENAME;
|
||||
|
||||
const MAX_SKILLS_ENTRIES_PER_ROOT: usize = 20_000;
|
||||
pub(crate) const MAX_CONCURRENT_SKILL_LOADS: usize = 64;
|
||||
|
||||
pub(super) enum DirectorySymlinkPolicy {
|
||||
Follow,
|
||||
Ignore,
|
||||
}
|
||||
|
||||
pub(super) enum HiddenDirectoryPolicy {
|
||||
Include,
|
||||
Skip,
|
||||
}
|
||||
|
||||
pub(super) struct SkillDiscoveryOptions {
|
||||
pub directory_symlinks: DirectorySymlinkPolicy,
|
||||
pub hidden_directories: HiddenDirectoryPolicy,
|
||||
pub mode: SkillDiscoveryMode,
|
||||
}
|
||||
|
||||
pub(super) struct SkillDiscovery {
|
||||
pub skills: Vec<DiscoveredSkill>,
|
||||
pub plugin_roots: HashSet<PathUri>,
|
||||
pub namespace_roots: HashSet<PathUri>,
|
||||
pub warnings: Vec<String>,
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
pub(super) struct DiscoveredSkill {
|
||||
pub path: PathUri,
|
||||
pub metadata: SkillMetadataDiscovery,
|
||||
}
|
||||
|
||||
pub(super) enum SkillMetadataDiscovery {
|
||||
Present(PathUri),
|
||||
Absent,
|
||||
Probe(PathUri),
|
||||
}
|
||||
|
||||
pub(super) async fn discover_skills(
|
||||
file_system: &dyn EnvironmentAccess,
|
||||
root: &PathUri,
|
||||
options: SkillDiscoveryOptions,
|
||||
) -> SkillDiscovery {
|
||||
let empty_discovery = || SkillDiscovery {
|
||||
skills: Vec::new(),
|
||||
plugin_roots: HashSet::new(),
|
||||
namespace_roots: HashSet::new(),
|
||||
warnings: Vec::new(),
|
||||
error: None,
|
||||
};
|
||||
let walk = match file_system
|
||||
.walk(
|
||||
root,
|
||||
WalkOptions {
|
||||
max_depth: match options.mode {
|
||||
SkillDiscoveryMode::Recursive => MAX_SCAN_DEPTH,
|
||||
SkillDiscoveryMode::DirectChildren => 2,
|
||||
},
|
||||
max_directories: MAX_SKILLS_DIRS_PER_ROOT,
|
||||
max_entries: MAX_SKILLS_ENTRIES_PER_ROOT,
|
||||
follow_directory_symlinks: matches!(
|
||||
options.directory_symlinks,
|
||||
DirectorySymlinkPolicy::Follow
|
||||
),
|
||||
prune_hidden_directories: matches!(
|
||||
options.hidden_directories,
|
||||
HiddenDirectoryPolicy::Skip
|
||||
),
|
||||
},
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(walk) => walk,
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => return empty_discovery(),
|
||||
Err(error) => {
|
||||
let mut discovery = empty_discovery();
|
||||
if error.kind() == io::ErrorKind::Unsupported {
|
||||
discovery.error = Some(error.to_string());
|
||||
}
|
||||
discovery
|
||||
.warnings
|
||||
.push(format!("failed to walk skills root {root}: {error:#}"));
|
||||
return discovery;
|
||||
}
|
||||
};
|
||||
|
||||
let inventory_complete = !walk.truncated && walk.errors.is_empty();
|
||||
let mut warnings = walk
|
||||
.errors
|
||||
.into_iter()
|
||||
.map(|error| {
|
||||
format!(
|
||||
"failed to scan skill path {}: {}",
|
||||
error.path, error.message
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
if walk.truncated {
|
||||
warnings.push(format!(
|
||||
"skills scan reached its traversal limit (root: {root})"
|
||||
));
|
||||
}
|
||||
|
||||
let skip_hidden = matches!(options.hidden_directories, HiddenDirectoryPolicy::Skip);
|
||||
let mut skill_files = Vec::new();
|
||||
let mut file_paths = HashSet::new();
|
||||
let mut metadata_directory_parents = HashSet::new();
|
||||
let mut plugin_roots = HashSet::new();
|
||||
for entry in walk.entries {
|
||||
if skip_hidden && has_hidden_ancestor_below_root(&entry.path, root) {
|
||||
continue;
|
||||
}
|
||||
match entry.kind {
|
||||
WalkEntryKind::Directory => {
|
||||
if entry
|
||||
.path
|
||||
.basename()
|
||||
.is_some_and(|name| name.eq_ignore_ascii_case(SKILLS_METADATA_DIR))
|
||||
&& let Some(skill_dir) = entry.path.parent()
|
||||
{
|
||||
metadata_directory_parents.insert(skill_dir);
|
||||
}
|
||||
if DISCOVERABLE_PLUGIN_MANIFEST_PATHS
|
||||
.iter()
|
||||
.any(|path| path.split('/').next() == entry.path.basename().as_deref())
|
||||
&& let Some(plugin_root) = entry.path.parent()
|
||||
{
|
||||
plugin_roots.insert(plugin_root);
|
||||
}
|
||||
}
|
||||
WalkEntryKind::File => {
|
||||
file_paths.insert(entry.path.clone());
|
||||
if entry.path.basename().as_deref() == Some(SKILLS_FILENAME)
|
||||
&& (options.mode == SkillDiscoveryMode::Recursive
|
||||
|| entry
|
||||
.path
|
||||
.parent()
|
||||
.and_then(|parent| parent.parent())
|
||||
.as_ref()
|
||||
== Some(root))
|
||||
{
|
||||
skill_files.push(entry.path);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let skills = skill_files
|
||||
.into_iter()
|
||||
.map(|path| DiscoveredSkill {
|
||||
metadata: discover_skill_metadata(
|
||||
&path,
|
||||
&file_paths,
|
||||
&metadata_directory_parents,
|
||||
inventory_complete,
|
||||
),
|
||||
path,
|
||||
})
|
||||
.collect();
|
||||
|
||||
SkillDiscovery {
|
||||
skills,
|
||||
plugin_roots,
|
||||
namespace_roots: HashSet::from([root.clone()]),
|
||||
warnings,
|
||||
error: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn has_hidden_ancestor_below_root(path: &PathUri, root: &PathUri) -> bool {
|
||||
let mut ancestor = path.parent();
|
||||
while let Some(current) = ancestor {
|
||||
if ¤t == root {
|
||||
return false;
|
||||
}
|
||||
if current.basename().is_some_and(|name| name.starts_with('.')) {
|
||||
return true;
|
||||
}
|
||||
ancestor = current.parent();
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn discover_skill_metadata(
|
||||
skill_path: &PathUri,
|
||||
file_paths: &HashSet<PathUri>,
|
||||
metadata_directory_parents: &HashSet<PathUri>,
|
||||
inventory_complete: bool,
|
||||
) -> SkillMetadataDiscovery {
|
||||
let Some(skill_dir) = skill_path.parent() else {
|
||||
return SkillMetadataDiscovery::Absent;
|
||||
};
|
||||
let Ok(metadata_dir) = skill_dir.join(SKILLS_METADATA_DIR) else {
|
||||
return SkillMetadataDiscovery::Absent;
|
||||
};
|
||||
let Ok(metadata_path) = metadata_dir.join(SKILLS_METADATA_FILENAME) else {
|
||||
return SkillMetadataDiscovery::Absent;
|
||||
};
|
||||
if file_paths.contains(&metadata_path) {
|
||||
return SkillMetadataDiscovery::Present(metadata_path);
|
||||
}
|
||||
|
||||
if inventory_complete && !metadata_directory_parents.contains(&skill_dir) {
|
||||
SkillMetadataDiscovery::Absent
|
||||
} else {
|
||||
// A complete walk proves ordinary absence, but keep a filesystem probe for case aliases,
|
||||
// file symlinks omitted by the walk, and incomplete inventories.
|
||||
SkillMetadataDiscovery::Probe(metadata_path)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "discovery_tests.rs"]
|
||||
mod tests;
|
||||
126
codex-rs/ext/skills/src/loader/discovery_tests.rs
Normal file
126
codex-rs/ext/skills/src/loader/discovery_tests.rs
Normal file
@@ -0,0 +1,126 @@
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
use codex_exec_server::FileSystemEnvironmentAccessor;
|
||||
use codex_exec_server::LOCAL_FS;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use codex_utils_plugins::SkillDiscoveryMode;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
|
||||
use super::DirectorySymlinkPolicy;
|
||||
use super::HiddenDirectoryPolicy;
|
||||
use super::SkillDiscovery;
|
||||
use super::SkillDiscoveryOptions;
|
||||
use super::discover_skills;
|
||||
|
||||
fn write_skill(root: &Path, directory: &str) {
|
||||
let path = root.join(directory).join("SKILL.md");
|
||||
fs::create_dir_all(path.parent().expect("skill parent")).expect("create skill directory");
|
||||
fs::write(path, "---\nname: demo\ndescription: Demo skill\n---\n")
|
||||
.expect("write skill frontmatter");
|
||||
}
|
||||
|
||||
fn canonical_uri(path: &Path) -> PathUri {
|
||||
PathUri::from_host_native_path(fs::canonicalize(path).expect("canonical path"))
|
||||
.expect("absolute path URI")
|
||||
}
|
||||
|
||||
async fn discover(root: &Path) -> SkillDiscovery {
|
||||
discover_skills(
|
||||
&FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS),
|
||||
&canonical_uri(root),
|
||||
SkillDiscoveryOptions {
|
||||
directory_symlinks: DirectorySymlinkPolicy::Follow,
|
||||
hidden_directories: HiddenDirectoryPolicy::Skip,
|
||||
mode: SkillDiscoveryMode::Recursive,
|
||||
},
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn discovers_hidden_directory_through_visible_symlink() {
|
||||
let root = TempDir::new().expect("root temp dir");
|
||||
write_skill(root.path(), ".hidden/search");
|
||||
std::os::unix::fs::symlink(root.path().join(".hidden"), root.path().join("visible"))
|
||||
.expect("create visible skill directory symlink");
|
||||
|
||||
let discovery = discover(root.path()).await;
|
||||
|
||||
assert_eq!(discovery.warnings, Vec::<String>::new());
|
||||
assert_eq!(
|
||||
discovery
|
||||
.skills
|
||||
.into_iter()
|
||||
.map(|skill| skill.path)
|
||||
.collect::<Vec<_>>(),
|
||||
vec![
|
||||
canonical_uri(root.path())
|
||||
.join("visible/search/SKILL.md")
|
||||
.expect("visible skill URI"),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn ignores_symlinked_skill_files_and_directory_cycles() {
|
||||
let root = TempDir::new().expect("root temp dir");
|
||||
let external = TempDir::new().expect("external temp dir");
|
||||
write_skill(external.path(), "external");
|
||||
write_skill(root.path(), "cycle/demo");
|
||||
fs::create_dir_all(root.path().join("linked-file")).expect("create linked skill directory");
|
||||
std::os::unix::fs::symlink(
|
||||
external.path().join("external/SKILL.md"),
|
||||
root.path().join("linked-file/SKILL.md"),
|
||||
)
|
||||
.expect("create skill file symlink");
|
||||
std::os::unix::fs::symlink(root.path().join("cycle"), root.path().join("cycle/loop"))
|
||||
.expect("create directory symlink cycle");
|
||||
|
||||
let discovery = tokio::time::timeout(
|
||||
std::time::Duration::from_secs(/*secs*/ 5),
|
||||
discover(root.path()),
|
||||
)
|
||||
.await
|
||||
.expect("directory symlink cycles must not prevent discovery from completing");
|
||||
|
||||
assert_eq!(
|
||||
discovery
|
||||
.skills
|
||||
.into_iter()
|
||||
.map(|skill| skill.path)
|
||||
.collect::<Vec<_>>(),
|
||||
vec![
|
||||
canonical_uri(root.path())
|
||||
.join("cycle/demo/SKILL.md")
|
||||
.expect("valid skill URI"),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn respects_maximum_skill_scan_depth() {
|
||||
let root = TempDir::new().expect("root temp dir");
|
||||
let within_depth = "d0/d1/d2/d3/d4/d5";
|
||||
let beyond_depth = "d0/d1/d2/d3/d4/d5/d6";
|
||||
write_skill(root.path(), within_depth);
|
||||
write_skill(root.path(), beyond_depth);
|
||||
|
||||
let discovery = discover(root.path()).await;
|
||||
|
||||
assert_eq!(
|
||||
discovery
|
||||
.skills
|
||||
.into_iter()
|
||||
.map(|skill| skill.path)
|
||||
.collect::<Vec<_>>(),
|
||||
vec![
|
||||
canonical_uri(root.path())
|
||||
.join(&format!("{within_depth}/SKILL.md"))
|
||||
.expect("reachable skill URI"),
|
||||
]
|
||||
);
|
||||
}
|
||||
388
codex-rs/ext/skills/src/loader/environment.rs
Normal file
388
codex-rs/ext/skills/src/loader/environment.rs
Normal file
@@ -0,0 +1,388 @@
|
||||
use std::collections::HashMap;
|
||||
use std::io;
|
||||
|
||||
use codex_exec_server::CapabilityRootDiscovery;
|
||||
use codex_exec_server::EnvironmentAccess;
|
||||
use codex_exec_server::EnvironmentAccessExt;
|
||||
use codex_exec_server::GetMetadataOptions;
|
||||
use codex_exec_server::ReadFileOptions;
|
||||
use codex_protocol::protocol::Product;
|
||||
use codex_skills::EnvironmentSkillMetadata;
|
||||
use codex_skills::ParsedSkillFrontmatter;
|
||||
use codex_skills::SkillDependencies;
|
||||
use codex_skills::SkillPolicy;
|
||||
use codex_skills::parse_skill_frontmatter_metadata;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use codex_utils_plugins::SkillDiscoveryMode;
|
||||
use futures::StreamExt;
|
||||
|
||||
use super::MAX_QUALIFIED_NAME_LEN;
|
||||
use super::discovery::DirectorySymlinkPolicy;
|
||||
use super::discovery::DiscoveredSkill;
|
||||
use super::discovery::HiddenDirectoryPolicy;
|
||||
use super::discovery::MAX_CONCURRENT_SKILL_LOADS;
|
||||
use super::discovery::SkillDiscoveryOptions;
|
||||
use super::discovery::SkillMetadataDiscovery;
|
||||
use super::discovery::discover_skills;
|
||||
use super::metadata::sanitize_single_line;
|
||||
use super::metadata::validate_len;
|
||||
use super::namespace::SkillNamespaceResolver;
|
||||
use codex_skills::parse_skill_metadata;
|
||||
|
||||
struct ParsedEnvironmentSkill {
|
||||
path_to_skills_md: PathUri,
|
||||
base_name: String,
|
||||
description: String,
|
||||
short_description: Option<String>,
|
||||
dependencies: Option<SkillDependencies>,
|
||||
policy: Option<SkillPolicy>,
|
||||
}
|
||||
|
||||
/// Parsed executor skill plus the instructions already materialized by capability discovery.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct EnvironmentSkillSnapshot {
|
||||
pub metadata: EnvironmentSkillMetadata,
|
||||
pub instructions: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct EnvironmentSkillSnapshotOutcome {
|
||||
pub skills: Vec<EnvironmentSkillSnapshot>,
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
impl ParsedEnvironmentSkill {
|
||||
async fn load(
|
||||
file_system: &dyn EnvironmentAccess,
|
||||
skill: &DiscoveredSkill,
|
||||
) -> Result<Self, String> {
|
||||
let (contents, discovered_metadata) = match &skill.metadata {
|
||||
SkillMetadataDiscovery::Present(metadata_path) => {
|
||||
let (contents, metadata) = tokio::join!(
|
||||
read_skill_contents(file_system, &skill.path),
|
||||
read_skill_metadata(file_system, metadata_path),
|
||||
);
|
||||
(contents?, metadata)
|
||||
}
|
||||
SkillMetadataDiscovery::Absent | SkillMetadataDiscovery::Probe(_) => (
|
||||
read_skill_contents(file_system, &skill.path).await?,
|
||||
(None, None),
|
||||
),
|
||||
};
|
||||
let ParsedSkillFrontmatter {
|
||||
name: base_name,
|
||||
description,
|
||||
short_description,
|
||||
} = parse_skill_frontmatter_metadata(&contents, || default_skill_name(&skill.path))
|
||||
.map_err(|err| err.to_string())?;
|
||||
let (dependencies, policy) = match &skill.metadata {
|
||||
SkillMetadataDiscovery::Present(_) | SkillMetadataDiscovery::Absent => {
|
||||
discovered_metadata
|
||||
}
|
||||
SkillMetadataDiscovery::Probe(metadata_path) => {
|
||||
probe_skill_metadata(file_system, metadata_path).await
|
||||
}
|
||||
};
|
||||
|
||||
Ok(Self {
|
||||
path_to_skills_md: skill.path.clone(),
|
||||
base_name,
|
||||
description,
|
||||
short_description,
|
||||
dependencies,
|
||||
policy,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct EnvironmentSkillLoadOutcome {
|
||||
pub skills: Vec<EnvironmentSkillMetadata>,
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// Discovers skills without converting environment-owned paths to host paths.
|
||||
#[tracing::instrument(
|
||||
name = "skills.environment.load",
|
||||
level = "info",
|
||||
skip_all,
|
||||
fields(skill_count = tracing::field::Empty)
|
||||
)]
|
||||
pub async fn load_environment_skills_from_root(
|
||||
file_system: &dyn EnvironmentAccess,
|
||||
root: &PathUri,
|
||||
restriction_product: Option<Product>,
|
||||
) -> EnvironmentSkillLoadOutcome {
|
||||
let mut outcome = EnvironmentSkillLoadOutcome::default();
|
||||
// Preserve environment discovery behavior by following directory aliases and including
|
||||
// hidden directories exposed by the executor.
|
||||
let discovery = discover_skills(
|
||||
file_system,
|
||||
root,
|
||||
SkillDiscoveryOptions {
|
||||
directory_symlinks: DirectorySymlinkPolicy::Follow,
|
||||
hidden_directories: HiddenDirectoryPolicy::Include,
|
||||
mode: SkillDiscoveryMode::Recursive,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
tracing::Span::current().record("skill_count", discovery.skills.len());
|
||||
outcome.warnings.extend(discovery.warnings);
|
||||
if discovery.skills.is_empty() {
|
||||
return outcome;
|
||||
}
|
||||
|
||||
let skill_paths = discovery
|
||||
.skills
|
||||
.iter()
|
||||
.map(|skill| skill.path.clone())
|
||||
.collect::<Vec<_>>();
|
||||
let namespace_resolver = SkillNamespaceResolver::discover(
|
||||
file_system,
|
||||
root,
|
||||
&skill_paths,
|
||||
discovery.plugin_roots,
|
||||
discovery.namespace_roots,
|
||||
);
|
||||
|
||||
// Remote executors can multiplex these independent per-skill reads, so polling a bounded
|
||||
// number together allows the I/O for each skill and its metadata to happen concurrently.
|
||||
let skill_results = futures::stream::iter(discovery.skills)
|
||||
.map(|skill| {
|
||||
let path = skill.path.clone();
|
||||
async move {
|
||||
(
|
||||
path,
|
||||
ParsedEnvironmentSkill::load(file_system, &skill).await,
|
||||
)
|
||||
}
|
||||
})
|
||||
.buffered(MAX_CONCURRENT_SKILL_LOADS)
|
||||
.collect::<Vec<_>>();
|
||||
let (namespace_resolver, skill_results) = tokio::join!(namespace_resolver, skill_results);
|
||||
|
||||
for (path, result) in skill_results {
|
||||
let result = result.and_then(|skill| {
|
||||
let name = namespace_resolver
|
||||
.for_skill(root, &skill.path_to_skills_md)
|
||||
.qualify(&skill.base_name);
|
||||
validate_len(&name, MAX_QUALIFIED_NAME_LEN, "qualified name")
|
||||
.map_err(|err| err.to_string())?;
|
||||
|
||||
Ok(EnvironmentSkillMetadata {
|
||||
path_to_skills_md: skill.path_to_skills_md,
|
||||
name,
|
||||
description: skill.description,
|
||||
short_description: skill.short_description,
|
||||
dependencies: skill.dependencies,
|
||||
policy: skill.policy,
|
||||
})
|
||||
});
|
||||
match result {
|
||||
Ok(skill) if skill.matches_product_restriction(restriction_product) => {
|
||||
outcome.skills.push(skill);
|
||||
}
|
||||
Ok(_) => {}
|
||||
Err(message) => outcome.warnings.push(format!(
|
||||
"Failed to load environment skill at {path}: {message}"
|
||||
)),
|
||||
}
|
||||
}
|
||||
outcome.skills.sort_by(|left, right| {
|
||||
left.name.cmp(&right.name).then_with(|| {
|
||||
left.path_to_skills_md
|
||||
.to_string()
|
||||
.cmp(&right.path_to_skills_md.to_string())
|
||||
})
|
||||
});
|
||||
outcome
|
||||
}
|
||||
|
||||
/// Parses an executor-produced manifest bundle without issuing additional filesystem requests.
|
||||
pub fn load_environment_skills_from_discovery(
|
||||
discovery: &CapabilityRootDiscovery,
|
||||
restriction_product: Option<Product>,
|
||||
) -> EnvironmentSkillSnapshotOutcome {
|
||||
let mut outcome = EnvironmentSkillSnapshotOutcome {
|
||||
warnings: discovery.warnings.clone(),
|
||||
..Default::default()
|
||||
};
|
||||
if let Some(error) = &discovery.error {
|
||||
outcome.warnings.push(error.clone());
|
||||
return outcome;
|
||||
}
|
||||
|
||||
let mut plugin_namespaces = HashMap::new();
|
||||
for (plugin_root, name) in discovery.namespace_manifests.iter().filter_map(|manifest| {
|
||||
#[derive(serde::Deserialize)]
|
||||
struct ManifestName {
|
||||
#[serde(default)]
|
||||
name: String,
|
||||
}
|
||||
|
||||
let plugin_root = manifest.path.parent()?.parent()?;
|
||||
let parsed = serde_json::from_str::<ManifestName>(&manifest.contents).ok()?;
|
||||
let name = if parsed.name.trim().is_empty() {
|
||||
plugin_root.basename()?
|
||||
} else {
|
||||
parsed.name
|
||||
};
|
||||
Some((plugin_root, name))
|
||||
}) {
|
||||
// Exec-server orders manifests by the same precedence as local discovery. Preserve the
|
||||
// first manifest if an older or alternate server returns duplicates for one plugin root.
|
||||
plugin_namespaces.entry(plugin_root).or_insert(name);
|
||||
}
|
||||
|
||||
for skill in &discovery.skills {
|
||||
let plugin_namespace =
|
||||
nearest_plugin_namespace(&skill.instructions.path, &plugin_namespaces);
|
||||
let ParsedSkillFrontmatter {
|
||||
name: base_name,
|
||||
description,
|
||||
short_description,
|
||||
} = match parse_skill_frontmatter_metadata(&skill.instructions.contents, || {
|
||||
default_skill_name(&skill.instructions.path)
|
||||
}) {
|
||||
Ok(frontmatter) => frontmatter,
|
||||
Err(error) => {
|
||||
outcome.warnings.push(format!(
|
||||
"Failed to load environment skill at {}: {error}",
|
||||
skill.instructions.path
|
||||
));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let name = plugin_namespace
|
||||
.map(|namespace| format!("{namespace}:{base_name}"))
|
||||
.unwrap_or(base_name);
|
||||
if let Err(error) = validate_len(&name, MAX_QUALIFIED_NAME_LEN, "qualified name") {
|
||||
outcome.warnings.push(format!(
|
||||
"Failed to load environment skill at {}: {error}",
|
||||
skill.instructions.path
|
||||
));
|
||||
continue;
|
||||
}
|
||||
let (dependencies, policy) = skill
|
||||
.metadata
|
||||
.as_ref()
|
||||
.and_then(|metadata| {
|
||||
parse_skill_metadata(&metadata.contents)
|
||||
.map_err(|error| {
|
||||
tracing::warn!(
|
||||
path = %metadata.path,
|
||||
"ignoring invalid discovered skill metadata: {error}"
|
||||
);
|
||||
})
|
||||
.ok()
|
||||
})
|
||||
.map(|metadata| (metadata.dependencies, metadata.policy))
|
||||
.unwrap_or((None, None));
|
||||
let metadata = EnvironmentSkillMetadata {
|
||||
path_to_skills_md: skill.instructions.path.clone(),
|
||||
name,
|
||||
description,
|
||||
short_description,
|
||||
dependencies,
|
||||
policy,
|
||||
};
|
||||
if metadata.matches_product_restriction(restriction_product) {
|
||||
outcome.skills.push(EnvironmentSkillSnapshot {
|
||||
metadata,
|
||||
instructions: skill.instructions.contents.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
outcome.skills.sort_by(|left, right| {
|
||||
left.metadata.name.cmp(&right.metadata.name).then_with(|| {
|
||||
left.metadata
|
||||
.path_to_skills_md
|
||||
.to_string()
|
||||
.cmp(&right.metadata.path_to_skills_md.to_string())
|
||||
})
|
||||
});
|
||||
outcome
|
||||
}
|
||||
|
||||
fn nearest_plugin_namespace<'a>(
|
||||
skill_path: &PathUri,
|
||||
plugin_namespaces: &'a HashMap<PathUri, String>,
|
||||
) -> Option<&'a str> {
|
||||
let mut ancestor = skill_path.parent();
|
||||
while let Some(path) = ancestor {
|
||||
if let Some(namespace) = plugin_namespaces.get(&path) {
|
||||
return Some(namespace);
|
||||
}
|
||||
ancestor = path.parent();
|
||||
}
|
||||
None
|
||||
}
|
||||
async fn read_skill_contents(
|
||||
file_system: &dyn EnvironmentAccess,
|
||||
skill_path: &PathUri,
|
||||
) -> Result<String, String> {
|
||||
file_system
|
||||
.read_file_text(skill_path, ReadFileOptions::default())
|
||||
.await
|
||||
.map_err(|err| format!("failed to read file: {err}"))
|
||||
}
|
||||
|
||||
async fn probe_skill_metadata(
|
||||
file_system: &dyn EnvironmentAccess,
|
||||
metadata_path: &PathUri,
|
||||
) -> (Option<SkillDependencies>, Option<SkillPolicy>) {
|
||||
match file_system
|
||||
.get_metadata(metadata_path, GetMetadataOptions::default())
|
||||
.await
|
||||
{
|
||||
Ok(metadata) if metadata.is_file => {}
|
||||
Ok(_) => return (None, None),
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => return (None, None),
|
||||
Err(error) => {
|
||||
tracing::warn!("ignoring {metadata_path}: failed to stat metadata: {error}");
|
||||
return (None, None);
|
||||
}
|
||||
}
|
||||
read_skill_metadata(file_system, metadata_path).await
|
||||
}
|
||||
|
||||
async fn read_skill_metadata(
|
||||
file_system: &dyn EnvironmentAccess,
|
||||
metadata_path: &PathUri,
|
||||
) -> (Option<SkillDependencies>, Option<SkillPolicy>) {
|
||||
let contents = match file_system
|
||||
.read_file_text(metadata_path, ReadFileOptions::default())
|
||||
.await
|
||||
{
|
||||
Ok(contents) => contents,
|
||||
Err(error) => {
|
||||
tracing::warn!("ignoring {metadata_path}: failed to read metadata: {error}");
|
||||
return (None, None);
|
||||
}
|
||||
};
|
||||
let parsed = match parse_skill_metadata(&contents) {
|
||||
Ok(parsed) => parsed,
|
||||
Err(error) => {
|
||||
tracing::warn!("ignoring {metadata_path}: invalid metadata: {error}");
|
||||
return (None, None);
|
||||
}
|
||||
};
|
||||
|
||||
(parsed.dependencies, parsed.policy)
|
||||
}
|
||||
|
||||
fn default_skill_name(path: &PathUri) -> String {
|
||||
path.parent()
|
||||
.and_then(|parent| parent.basename())
|
||||
.map(|name| sanitize_single_line(&name))
|
||||
.filter(|name| !name.is_empty())
|
||||
.unwrap_or_else(|| "skill".to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "environment_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "environment_io_tests.rs"]
|
||||
mod io_tests;
|
||||
233
codex-rs/ext/skills/src/loader/environment_io_tests.rs
Normal file
233
codex-rs/ext/skills/src/loader/environment_io_tests.rs
Normal file
@@ -0,0 +1,233 @@
|
||||
use std::fs;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use codex_exec_server::ExecutorFileSystem;
|
||||
use codex_exec_server::FileSystemEnvironmentAccessor;
|
||||
use codex_exec_server::LOCAL_FS;
|
||||
use codex_skills::EnvironmentSkillMetadata;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::tempdir;
|
||||
|
||||
use crate::loader::io_test_support::FileSystemCalls;
|
||||
use crate::loader::io_test_support::ManifestMetadataBehavior;
|
||||
use crate::loader::io_test_support::RecordingFileSystem;
|
||||
|
||||
use super::load_environment_skills_from_root;
|
||||
|
||||
#[tokio::test]
|
||||
async fn loads_nearest_plugin_namespaces_without_reading_unused_sibling_manifests() {
|
||||
let root = tempdir().expect("tempdir");
|
||||
let standalone_skill = root.path().join("standalone/SKILL.md");
|
||||
let outer_root = root.path().join("plugins/outer");
|
||||
let outer_skill = outer_root.join("skills/deploy/SKILL.md");
|
||||
let inner_root = outer_root.join("nested/inner");
|
||||
let inner_skill = inner_root.join("skills/audit/SKILL.md");
|
||||
let unused_root = root.path().join("plugins/unused");
|
||||
|
||||
for path in [&standalone_skill, &outer_skill, &inner_skill] {
|
||||
fs::create_dir_all(path.parent().expect("skill parent")).expect("skill dir");
|
||||
}
|
||||
for (plugin_root, name) in [
|
||||
(&outer_root, "outer"),
|
||||
(&inner_root, "inner"),
|
||||
(&unused_root, "unused"),
|
||||
] {
|
||||
fs::create_dir_all(plugin_root.join(".codex-plugin")).expect("manifest dir");
|
||||
fs::write(
|
||||
plugin_root.join(".codex-plugin/plugin.json"),
|
||||
format!(r#"{{"name":"{name}"}}"#),
|
||||
)
|
||||
.expect("manifest");
|
||||
}
|
||||
for (path, name) in [
|
||||
(&standalone_skill, "standalone"),
|
||||
(&outer_skill, "deploy"),
|
||||
(&inner_skill, "audit"),
|
||||
] {
|
||||
fs::write(
|
||||
path,
|
||||
format!("---\nname: {name}\ndescription: {name} skill.\n---\n"),
|
||||
)
|
||||
.expect("skill");
|
||||
}
|
||||
|
||||
let file_system = Arc::new(RecordingFileSystem::new(
|
||||
LOCAL_FS.as_ref(),
|
||||
ManifestMetadataBehavior::Immediate,
|
||||
));
|
||||
let executor: Arc<dyn ExecutorFileSystem> = file_system.clone();
|
||||
let root_uri = PathUri::from_host_native_path(root.path()).expect("root URI");
|
||||
let outcome = load_environment_skills_from_root(
|
||||
&FileSystemEnvironmentAccessor::unrestricted(&executor),
|
||||
&root_uri,
|
||||
/*restriction_product*/ None,
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(outcome.warnings, Vec::<String>::new());
|
||||
assert_eq!(
|
||||
outcome.skills,
|
||||
vec![
|
||||
EnvironmentSkillMetadata {
|
||||
path_to_skills_md: PathUri::from_host_native_path(&inner_skill).unwrap(),
|
||||
name: "inner:audit".to_string(),
|
||||
description: "audit skill.".to_string(),
|
||||
short_description: None,
|
||||
dependencies: None,
|
||||
policy: None,
|
||||
},
|
||||
EnvironmentSkillMetadata {
|
||||
path_to_skills_md: PathUri::from_host_native_path(&outer_skill).unwrap(),
|
||||
name: "outer:deploy".to_string(),
|
||||
description: "deploy skill.".to_string(),
|
||||
short_description: None,
|
||||
dependencies: None,
|
||||
policy: None,
|
||||
},
|
||||
EnvironmentSkillMetadata {
|
||||
path_to_skills_md: PathUri::from_host_native_path(&standalone_skill).unwrap(),
|
||||
name: "standalone".to_string(),
|
||||
description: "standalone skill.".to_string(),
|
||||
short_description: None,
|
||||
dependencies: None,
|
||||
policy: None,
|
||||
},
|
||||
]
|
||||
);
|
||||
|
||||
let mut manifest_reads = file_system
|
||||
.calls()
|
||||
.read_files
|
||||
.into_iter()
|
||||
.filter(|path| path.basename().as_deref() == Some("plugin.json"))
|
||||
.collect::<Vec<_>>();
|
||||
manifest_reads.sort_by_key(ToString::to_string);
|
||||
let mut expected_manifest_reads = [&outer_root, &inner_root]
|
||||
.into_iter()
|
||||
.map(|plugin_root| {
|
||||
PathUri::from_host_native_path(plugin_root.join(".codex-plugin/plugin.json")).unwrap()
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
expected_manifest_reads.sort_by_key(ToString::to_string);
|
||||
assert_eq!(manifest_reads, expected_manifest_reads);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reuses_walk_inventory_for_missing_skill_metadata() {
|
||||
const SKILL_COUNT: usize = 66;
|
||||
|
||||
let root = tempdir().expect("tempdir");
|
||||
let manifest_path = root.path().join(".codex-plugin/plugin.json");
|
||||
fs::create_dir_all(manifest_path.parent().expect("manifest parent")).expect("manifest dir");
|
||||
fs::write(&manifest_path, r#"{"name":"inventory"}"#).expect("manifest");
|
||||
|
||||
let mut skill_paths = Vec::new();
|
||||
for index in 0..SKILL_COUNT {
|
||||
let name = format!("skill-{index}");
|
||||
let skill_path = root.path().join(&name).join("SKILL.md");
|
||||
fs::create_dir_all(skill_path.parent().expect("skill parent")).expect("skill dir");
|
||||
fs::write(
|
||||
&skill_path,
|
||||
format!("---\nname: {name}\ndescription: {name} skill.\n---\n"),
|
||||
)
|
||||
.expect("skill");
|
||||
skill_paths.push(skill_path);
|
||||
}
|
||||
|
||||
let file_system = Arc::new(RecordingFileSystem::new(
|
||||
LOCAL_FS.as_ref(),
|
||||
ManifestMetadataBehavior::Immediate,
|
||||
));
|
||||
let executor: Arc<dyn ExecutorFileSystem> = file_system.clone();
|
||||
let root_uri = PathUri::from_host_native_path(root.path()).expect("root URI");
|
||||
let outcome = load_environment_skills_from_root(
|
||||
&FileSystemEnvironmentAccessor::unrestricted(&executor),
|
||||
&root_uri,
|
||||
/*restriction_product*/ None,
|
||||
)
|
||||
.await;
|
||||
|
||||
let mut expected_skills = skill_paths
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, skill_path)| EnvironmentSkillMetadata {
|
||||
path_to_skills_md: PathUri::from_host_native_path(skill_path).unwrap(),
|
||||
name: format!("inventory:skill-{index}"),
|
||||
description: format!("skill-{index} skill."),
|
||||
short_description: None,
|
||||
dependencies: None,
|
||||
policy: None,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
expected_skills.sort_by(|left, right| {
|
||||
left.name.cmp(&right.name).then_with(|| {
|
||||
left.path_to_skills_md
|
||||
.to_string()
|
||||
.cmp(&right.path_to_skills_md.to_string())
|
||||
})
|
||||
});
|
||||
assert_eq!(outcome.skills, expected_skills);
|
||||
assert_eq!(outcome.warnings, Vec::<String>::new());
|
||||
|
||||
let mut expected_read_files = skill_paths
|
||||
.iter()
|
||||
.map(|path| PathUri::from_host_native_path(path).unwrap())
|
||||
.collect::<Vec<_>>();
|
||||
let manifest_uri = PathUri::from_host_native_path(manifest_path).unwrap();
|
||||
expected_read_files.push(manifest_uri.clone());
|
||||
expected_read_files.sort_by_key(ToString::to_string);
|
||||
assert_eq!(
|
||||
file_system.calls(),
|
||||
FileSystemCalls {
|
||||
walks: 1,
|
||||
read_files: expected_read_files,
|
||||
metadata_files: vec![manifest_uri],
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reads_skill_files_while_resolving_plugin_namespaces() {
|
||||
let root = tempdir().expect("tempdir");
|
||||
let manifest_path = root.path().join(".codex-plugin/plugin.json");
|
||||
fs::create_dir_all(manifest_path.parent().expect("manifest parent")).expect("manifest dir");
|
||||
fs::write(&manifest_path, r#"{"name":"parallel"}"#).expect("manifest");
|
||||
let skill_path = root.path().join("demo/SKILL.md");
|
||||
fs::create_dir_all(skill_path.parent().expect("skill parent")).expect("skill dir");
|
||||
fs::write(
|
||||
&skill_path,
|
||||
"---\nname: demo\ndescription: demo skill.\n---\n",
|
||||
)
|
||||
.expect("skill");
|
||||
|
||||
let file_system: Arc<dyn ExecutorFileSystem> = Arc::new(RecordingFileSystem::new(
|
||||
LOCAL_FS.as_ref(),
|
||||
ManifestMetadataBehavior::WaitForSkillRead,
|
||||
));
|
||||
let root_uri = PathUri::from_host_native_path(root.path()).expect("root URI");
|
||||
let outcome = tokio::time::timeout(
|
||||
Duration::from_secs(5),
|
||||
load_environment_skills_from_root(
|
||||
&FileSystemEnvironmentAccessor::unrestricted(&file_system),
|
||||
&root_uri,
|
||||
/*restriction_product*/ None,
|
||||
),
|
||||
)
|
||||
.await
|
||||
.expect("skill reads should start before namespace resolution finishes");
|
||||
|
||||
assert_eq!(outcome.warnings, Vec::<String>::new());
|
||||
assert_eq!(
|
||||
outcome.skills,
|
||||
vec![EnvironmentSkillMetadata {
|
||||
path_to_skills_md: PathUri::from_host_native_path(skill_path).unwrap(),
|
||||
name: "parallel:demo".to_string(),
|
||||
description: "demo skill.".to_string(),
|
||||
short_description: None,
|
||||
dependencies: None,
|
||||
policy: None,
|
||||
}]
|
||||
);
|
||||
}
|
||||
227
codex-rs/ext/skills/src/loader/environment_tests.rs
Normal file
227
codex-rs/ext/skills/src/loader/environment_tests.rs
Normal file
@@ -0,0 +1,227 @@
|
||||
use std::fs;
|
||||
|
||||
use codex_exec_server::CapabilityRootDiscoverRequest;
|
||||
use codex_exec_server::CapabilityRootsDiscoverParams;
|
||||
use codex_exec_server::FileSystemEnvironmentAccessor;
|
||||
use codex_exec_server::LOCAL_FS;
|
||||
use codex_exec_server::discover_capability_roots;
|
||||
use codex_protocol::protocol::Product;
|
||||
use codex_skills::EnvironmentSkillMetadata;
|
||||
use codex_skills::SkillDependencies;
|
||||
use codex_skills::SkillPolicy;
|
||||
use codex_skills::SkillToolDependency;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::tempdir;
|
||||
|
||||
use super::load_environment_skills_from_discovery;
|
||||
use super::load_environment_skills_from_root;
|
||||
|
||||
#[tokio::test]
|
||||
async fn direct_environment_loader_preserves_plugin_dependencies_and_product_policy() {
|
||||
let root = tempdir().expect("tempdir");
|
||||
let skill_dir = root.path().join("skills/deploy");
|
||||
fs::create_dir_all(root.path().join(".codex-plugin")).expect("manifest dir");
|
||||
fs::create_dir_all(skill_dir.join("agents")).expect("metadata dir");
|
||||
fs::write(
|
||||
root.path().join(".codex-plugin/plugin.json"),
|
||||
r#"{"name":"demo-plugin"}"#,
|
||||
)
|
||||
.expect("manifest");
|
||||
fs::write(
|
||||
skill_dir.join("SKILL.md"),
|
||||
"---\nname: deploy\ndescription: Deploy the service.\n---\n",
|
||||
)
|
||||
.expect("skill");
|
||||
fs::write(
|
||||
skill_dir.join("agents/openai.yaml"),
|
||||
r#"
|
||||
dependencies:
|
||||
tools:
|
||||
- type: mcp
|
||||
value: deploy-server
|
||||
description: Deploy MCP
|
||||
transport: stdio
|
||||
command: deploy-mcp
|
||||
policy:
|
||||
allow_implicit_invocation: false
|
||||
products: [codex, atlas]
|
||||
"#,
|
||||
)
|
||||
.expect("metadata");
|
||||
|
||||
let root_uri = PathUri::from_host_native_path(root.path()).expect("root URI");
|
||||
let file_system = FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS);
|
||||
let outcome =
|
||||
load_environment_skills_from_root(&file_system, &root_uri, Some(Product::Codex)).await;
|
||||
|
||||
assert_eq!(
|
||||
outcome.skills,
|
||||
vec![EnvironmentSkillMetadata {
|
||||
path_to_skills_md: PathUri::from_host_native_path(skill_dir.join("SKILL.md")).unwrap(),
|
||||
name: "demo-plugin:deploy".to_string(),
|
||||
description: "Deploy the service.".to_string(),
|
||||
short_description: None,
|
||||
dependencies: Some(SkillDependencies {
|
||||
tools: vec![SkillToolDependency {
|
||||
r#type: "mcp".to_string(),
|
||||
value: "deploy-server".to_string(),
|
||||
description: Some("Deploy MCP".to_string()),
|
||||
transport: Some("stdio".to_string()),
|
||||
command: Some("deploy-mcp".to_string()),
|
||||
url: None,
|
||||
oauth_callback_port: None,
|
||||
}],
|
||||
}),
|
||||
policy: Some(SkillPolicy {
|
||||
allow_implicit_invocation: Some(false),
|
||||
products: vec![Product::Codex, Product::Atlas],
|
||||
}),
|
||||
}]
|
||||
);
|
||||
let atlas =
|
||||
load_environment_skills_from_root(&file_system, &root_uri, Some(Product::Atlas)).await;
|
||||
assert_eq!(atlas.skills, outcome.skills);
|
||||
let filtered =
|
||||
load_environment_skills_from_root(&file_system, &root_uri, Some(Product::Chatgpt)).await;
|
||||
assert!(filtered.skills.is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn executor_bundle_parser_matches_direct_environment_loader() {
|
||||
let root = tempdir().expect("tempdir");
|
||||
let plugin_manifest = root.path().join(".codex-plugin/plugin.json");
|
||||
let nested_manifest = root.path().join("nested/.claude-plugin/plugin.json");
|
||||
let deploy_skill = root.path().join("skills/deploy/SKILL.md");
|
||||
let deploy_metadata = root.path().join("skills/deploy/agents/openai.yaml");
|
||||
let audit_skill = root.path().join("nested/skills/audit/SKILL.md");
|
||||
for (path, contents) in [
|
||||
(&plugin_manifest, r#"{"name":"demo"}"#),
|
||||
(&nested_manifest, r#"{"name":"nested"}"#),
|
||||
(
|
||||
&deploy_skill,
|
||||
"---\nname: deploy\ndescription: Deploy the service.\n---\n\nDeploy.\n",
|
||||
),
|
||||
(
|
||||
&deploy_metadata,
|
||||
"policy:\n allow_implicit_invocation: false\n",
|
||||
),
|
||||
(
|
||||
&audit_skill,
|
||||
"---\nname: audit\ndescription: Audit the service.\n---\n\nAudit.\n",
|
||||
),
|
||||
] {
|
||||
fs::create_dir_all(path.parent().expect("test file parent")).expect("test directory");
|
||||
fs::write(path, contents).expect("test file");
|
||||
}
|
||||
|
||||
let root_uri = PathUri::from_host_native_path(root.path()).expect("root URI");
|
||||
let existing = load_environment_skills_from_root(
|
||||
&FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS),
|
||||
&root_uri,
|
||||
/*restriction_product*/ None,
|
||||
)
|
||||
.await;
|
||||
let response = discover_capability_roots(
|
||||
LOCAL_FS.as_ref(),
|
||||
CapabilityRootsDiscoverParams {
|
||||
roots: vec![CapabilityRootDiscoverRequest {
|
||||
id: "demo@1".to_string(),
|
||||
path: root_uri,
|
||||
sandbox: None,
|
||||
}],
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("capability discovery");
|
||||
let bundled = load_environment_skills_from_discovery(
|
||||
response.roots.first().expect("discovered root"),
|
||||
/*restriction_product*/ None,
|
||||
);
|
||||
|
||||
assert_eq!(bundled.warnings, existing.warnings);
|
||||
assert_eq!(
|
||||
bundled
|
||||
.skills
|
||||
.iter()
|
||||
.map(|skill| skill.metadata.clone())
|
||||
.collect::<Vec<_>>(),
|
||||
existing.skills
|
||||
);
|
||||
assert_eq!(
|
||||
bundled
|
||||
.skills
|
||||
.iter()
|
||||
.map(|skill| skill.instructions.as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
vec![
|
||||
"---\nname: deploy\ndescription: Deploy the service.\n---\n\nDeploy.\n",
|
||||
"---\nname: audit\ndescription: Audit the service.\n---\n\nAudit.\n",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn executor_bundle_preserves_parent_namespace_and_manifest_precedence() {
|
||||
let plugin = tempdir().expect("tempdir");
|
||||
for (relative_path, name) in [
|
||||
(".codex-plugin/plugin.json", "codex-name"),
|
||||
(".claude-plugin/plugin.json", "claude-name"),
|
||||
(".cursor-plugin/plugin.json", "cursor-name"),
|
||||
] {
|
||||
let manifest = plugin.path().join(relative_path);
|
||||
fs::create_dir_all(manifest.parent().expect("manifest parent"))
|
||||
.expect("manifest directory");
|
||||
fs::write(&manifest, format!(r#"{{"name":"{name}"}}"#)).expect("manifest");
|
||||
}
|
||||
let skills_root = plugin.path().join("skills");
|
||||
let skill_path = skills_root.join("search/SKILL.md");
|
||||
fs::create_dir_all(skill_path.parent().expect("skill parent")).expect("skill directory");
|
||||
fs::write(
|
||||
&skill_path,
|
||||
"---\nname: search\ndescription: Search the project.\n---\n\nSearch.\n",
|
||||
)
|
||||
.expect("skill");
|
||||
|
||||
let root_uri = PathUri::from_host_native_path(&skills_root).expect("skills root URI");
|
||||
let existing = load_environment_skills_from_root(
|
||||
&FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS),
|
||||
&root_uri,
|
||||
/*restriction_product*/ None,
|
||||
)
|
||||
.await;
|
||||
let response = discover_capability_roots(
|
||||
LOCAL_FS.as_ref(),
|
||||
CapabilityRootsDiscoverParams {
|
||||
roots: vec![CapabilityRootDiscoverRequest {
|
||||
id: "skills-only".to_string(),
|
||||
path: root_uri,
|
||||
sandbox: None,
|
||||
}],
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("capability discovery");
|
||||
let discovery = response.roots.first().expect("discovered root");
|
||||
let bundled =
|
||||
load_environment_skills_from_discovery(discovery, /*restriction_product*/ None);
|
||||
|
||||
assert_eq!(discovery.plugin, None);
|
||||
assert_eq!(discovery.namespace_manifests.len(), 1);
|
||||
assert!(
|
||||
discovery.namespace_manifests[0]
|
||||
.path
|
||||
.to_string()
|
||||
.ends_with("/.codex-plugin/plugin.json")
|
||||
);
|
||||
assert_eq!(bundled.warnings, existing.warnings);
|
||||
assert_eq!(
|
||||
bundled
|
||||
.skills
|
||||
.iter()
|
||||
.map(|skill| skill.metadata.clone())
|
||||
.collect::<Vec<_>>(),
|
||||
existing.skills
|
||||
);
|
||||
assert_eq!(bundled.skills[0].metadata.name, "codex-name:search");
|
||||
}
|
||||
427
codex-rs/ext/skills/src/loader/host.rs
Normal file
427
codex-rs/ext/skills/src/loader/host.rs
Normal file
@@ -0,0 +1,427 @@
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use codex_exec_server::EnvironmentAccess;
|
||||
use codex_exec_server::EnvironmentAccessExt;
|
||||
use codex_exec_server::EnvironmentAccessKey;
|
||||
use codex_exec_server::GetMetadataOptions;
|
||||
use codex_exec_server::ReadFileOptions;
|
||||
use codex_protocol::protocol::SkillScope;
|
||||
use codex_skills::ParsedSkillFrontmatter;
|
||||
use codex_skills::SkillError;
|
||||
use codex_skills::SkillMetadata;
|
||||
use codex_skills::parse_skill_frontmatter_metadata;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use codex_utils_plugins::PluginIdentity;
|
||||
use codex_utils_plugins::PluginSkillRoot;
|
||||
use codex_utils_plugins::SkillDiscoveryMode;
|
||||
use futures::StreamExt;
|
||||
use tracing::error;
|
||||
|
||||
use super::MAX_QUALIFIED_NAME_LEN;
|
||||
use super::SKILLS_METADATA_DIR;
|
||||
use super::SKILLS_METADATA_FILENAME;
|
||||
use super::discovery::DirectorySymlinkPolicy;
|
||||
use super::discovery::DiscoveredSkill;
|
||||
use super::discovery::HiddenDirectoryPolicy;
|
||||
use super::discovery::MAX_CONCURRENT_SKILL_LOADS;
|
||||
use super::discovery::SkillDiscovery;
|
||||
use super::discovery::SkillDiscoveryOptions;
|
||||
use super::discovery::SkillMetadataDiscovery;
|
||||
use super::discovery::discover_skills;
|
||||
use super::metadata::LoadedSkillMetadata;
|
||||
use super::metadata::load_host_skill_metadata;
|
||||
use super::metadata::sanitize_single_line;
|
||||
use super::metadata::validate_len;
|
||||
use super::namespace::SkillNamespaceResolver;
|
||||
|
||||
/// A resolved host skill root ready for filesystem discovery.
|
||||
pub(crate) struct HostSkillRoot<'a> {
|
||||
pub(crate) path: AbsolutePathBuf,
|
||||
pub(crate) scope: SkillScope,
|
||||
pub(crate) file_system: &'a dyn EnvironmentAccess,
|
||||
plugin: Option<PluginSkillRootContext>,
|
||||
}
|
||||
|
||||
struct PluginSkillRootContext {
|
||||
identity: PluginIdentity,
|
||||
namespace: String,
|
||||
root: AbsolutePathBuf,
|
||||
discovery_mode: SkillDiscoveryMode,
|
||||
}
|
||||
|
||||
impl<'a> HostSkillRoot<'a> {
|
||||
pub(crate) fn host(
|
||||
path: AbsolutePathBuf,
|
||||
scope: SkillScope,
|
||||
file_system: &'a dyn EnvironmentAccess,
|
||||
) -> Self {
|
||||
Self {
|
||||
path,
|
||||
scope,
|
||||
file_system,
|
||||
plugin: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn plugin(root: PluginSkillRoot, file_system: &'a dyn EnvironmentAccess) -> Self {
|
||||
Self {
|
||||
path: root.path,
|
||||
scope: SkillScope::User,
|
||||
file_system,
|
||||
plugin: Some(PluginSkillRootContext {
|
||||
identity: root.plugin_identity,
|
||||
namespace: root.plugin_namespace,
|
||||
root: root.plugin_root,
|
||||
discovery_mode: root.discovery_mode,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the owning plugin identity when this root belongs to a plugin.
|
||||
pub(crate) fn plugin_identity(&self) -> Option<&PluginIdentity> {
|
||||
self.plugin.as_ref().map(|plugin| &plugin.identity)
|
||||
}
|
||||
|
||||
pub(crate) fn plugin_namespace(&self) -> Option<&str> {
|
||||
self.plugin.as_ref().map(|plugin| plugin.namespace.as_str())
|
||||
}
|
||||
|
||||
pub(crate) fn plugin_root(&self) -> Option<&AbsolutePathBuf> {
|
||||
self.plugin.as_ref().map(|plugin| &plugin.root)
|
||||
}
|
||||
|
||||
pub(crate) fn plugin_skill_root(&self) -> Option<PluginSkillRoot> {
|
||||
self.plugin.as_ref().map(|plugin| PluginSkillRoot {
|
||||
path: self.path.clone(),
|
||||
plugin_identity: plugin.identity.clone(),
|
||||
plugin_namespace: plugin.namespace.clone(),
|
||||
plugin_root: plugin.root.clone(),
|
||||
discovery_mode: plugin.discovery_mode,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn discovery_mode(&self) -> SkillDiscoveryMode {
|
||||
self.plugin
|
||||
.as_ref()
|
||||
.map_or(SkillDiscoveryMode::Recursive, |plugin| {
|
||||
plugin.discovery_mode
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Skills and errors loaded from one canonical host root.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct HostSkillRootSnapshot {
|
||||
pub(crate) root: AbsolutePathBuf,
|
||||
pub(crate) skills: Vec<SkillMetadata>,
|
||||
pub(crate) skill_discovery_path_by_path: Arc<HashMap<PathUri, PathUri>>,
|
||||
pub(crate) errors: Vec<SkillError>,
|
||||
pub(crate) file_system: EnvironmentAccessKey,
|
||||
pub(crate) is_agent_plugin: bool,
|
||||
}
|
||||
|
||||
struct ResolvedDiscoveredSkill {
|
||||
skill: DiscoveredSkill,
|
||||
path: AbsolutePathBuf,
|
||||
path_uri: PathUri,
|
||||
}
|
||||
|
||||
pub(crate) async fn load_host_skill_root(root: HostSkillRoot<'_>) -> HostSkillRootSnapshot {
|
||||
let is_agent_plugin = root.discovery_mode() == SkillDiscoveryMode::DirectChildren;
|
||||
let canonical_root = canonicalize_for_skill_identity(root.file_system, &root.path).await;
|
||||
let (skills, skill_discovery_path_by_path, errors) =
|
||||
load_skills_under_root(&root, &canonical_root).await;
|
||||
HostSkillRootSnapshot {
|
||||
root: canonical_root,
|
||||
skills,
|
||||
skill_discovery_path_by_path,
|
||||
errors,
|
||||
file_system: root.file_system.cache_key(),
|
||||
is_agent_plugin,
|
||||
}
|
||||
}
|
||||
|
||||
async fn load_skills_under_root(
|
||||
skill_root: &HostSkillRoot<'_>,
|
||||
root: &AbsolutePathBuf,
|
||||
) -> (
|
||||
Vec<SkillMetadata>,
|
||||
Arc<HashMap<PathUri, PathUri>>,
|
||||
Vec<SkillError>,
|
||||
) {
|
||||
let file_system = skill_root.file_system;
|
||||
let plugin_identity = skill_root.plugin_identity();
|
||||
let plugin_root = match skill_root.plugin_root() {
|
||||
Some(plugin_root) => Some(canonicalize_for_skill_identity(file_system, plugin_root).await),
|
||||
None => None,
|
||||
};
|
||||
let discovery_mode = skill_root.discovery_mode();
|
||||
let directory_symlinks = match skill_root.scope {
|
||||
SkillScope::User | SkillScope::Repo | SkillScope::Admin => DirectorySymlinkPolicy::Follow,
|
||||
SkillScope::System => DirectorySymlinkPolicy::Ignore,
|
||||
};
|
||||
let SkillDiscovery {
|
||||
skills,
|
||||
plugin_roots,
|
||||
mut namespace_roots,
|
||||
warnings,
|
||||
error,
|
||||
} = discover_skills(
|
||||
file_system,
|
||||
&PathUri::from_abs_path(root),
|
||||
SkillDiscoveryOptions {
|
||||
directory_symlinks,
|
||||
hidden_directories: HiddenDirectoryPolicy::Skip,
|
||||
mode: discovery_mode,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
for warning in warnings {
|
||||
error!("{warning}");
|
||||
}
|
||||
if let Some(message) = error {
|
||||
return (
|
||||
Vec::new(),
|
||||
Arc::default(),
|
||||
vec![SkillError {
|
||||
path: root.clone(),
|
||||
message,
|
||||
}],
|
||||
);
|
||||
}
|
||||
if skills.is_empty() {
|
||||
return (Vec::new(), Arc::default(), Vec::new());
|
||||
}
|
||||
|
||||
let root_uri = PathUri::from_abs_path(root);
|
||||
let resolved_plugin_root = plugin_root.as_ref();
|
||||
let resolved_skills = futures::stream::iter(skills)
|
||||
.map(|skill| async move {
|
||||
let path_uri = match file_system.canonicalize(&skill.path).await {
|
||||
Ok(path) => path,
|
||||
Err(error) if discovery_mode == SkillDiscoveryMode::DirectChildren => {
|
||||
error!(
|
||||
"failed to resolve Agent Plugin skill path {}: {error}",
|
||||
skill.path
|
||||
);
|
||||
return None;
|
||||
}
|
||||
Err(_) => skill.path.clone(),
|
||||
};
|
||||
let path = match path_uri.to_abs_path() {
|
||||
Ok(path) => path,
|
||||
Err(error) => {
|
||||
error!("failed to convert discovered skill path {path_uri}: {error}");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
if discovery_mode == SkillDiscoveryMode::DirectChildren {
|
||||
let Some(plugin_root) = resolved_plugin_root else {
|
||||
error!("Agent Plugin skill root is missing its plugin root");
|
||||
return None;
|
||||
};
|
||||
if !path.as_path().starts_with(plugin_root.as_path()) {
|
||||
error!(
|
||||
"Agent Plugin skill path {} resolves outside plugin root {}",
|
||||
path.display(),
|
||||
plugin_root.display()
|
||||
);
|
||||
return None;
|
||||
}
|
||||
match file_system
|
||||
.get_metadata(&path_uri, GetMetadataOptions::default())
|
||||
.await
|
||||
{
|
||||
Ok(metadata) if metadata.is_file => {}
|
||||
Ok(_) => {
|
||||
error!(
|
||||
"Agent Plugin skill path {} is not a regular file",
|
||||
path.display()
|
||||
);
|
||||
return None;
|
||||
}
|
||||
Err(error) => {
|
||||
error!(
|
||||
"failed to inspect Agent Plugin skill path {}: {error}",
|
||||
path.display()
|
||||
);
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(ResolvedDiscoveredSkill {
|
||||
skill,
|
||||
path,
|
||||
path_uri,
|
||||
})
|
||||
})
|
||||
.buffered(MAX_CONCURRENT_SKILL_LOADS)
|
||||
.filter_map(futures::future::ready)
|
||||
.collect::<Vec<_>>()
|
||||
.await;
|
||||
namespace_roots.extend(resolved_skills.iter().filter_map(|skill| {
|
||||
(skill.path_uri != skill.skill.path)
|
||||
.then(|| skill.path_uri.parent())
|
||||
.flatten()
|
||||
}));
|
||||
let skill_paths = resolved_skills
|
||||
.iter()
|
||||
.map(|skill| skill.path_uri.clone())
|
||||
.collect::<Vec<_>>();
|
||||
let namespace_resolver = async {
|
||||
match skill_root.plugin_namespace() {
|
||||
Some(namespace) => SkillNamespaceResolver::with_provided_namespace(namespace),
|
||||
None => {
|
||||
SkillNamespaceResolver::discover(
|
||||
file_system,
|
||||
&root_uri,
|
||||
&skill_paths,
|
||||
plugin_roots,
|
||||
namespace_roots,
|
||||
)
|
||||
.await
|
||||
}
|
||||
}
|
||||
};
|
||||
let skill_results = futures::stream::iter(resolved_skills)
|
||||
.map(|skill| {
|
||||
let plugin_root = plugin_root.as_ref();
|
||||
async move {
|
||||
let discovery_path = skill
|
||||
.skill
|
||||
.path
|
||||
.to_abs_path()
|
||||
.unwrap_or_else(|_| skill.path.clone());
|
||||
let result = parse_skill_file(
|
||||
file_system,
|
||||
&skill.skill,
|
||||
&skill.path,
|
||||
&skill.path_uri,
|
||||
skill_root.scope,
|
||||
plugin_identity,
|
||||
plugin_root,
|
||||
)
|
||||
.await;
|
||||
(skill.path, skill.path_uri, discovery_path, result)
|
||||
}
|
||||
})
|
||||
.buffered(MAX_CONCURRENT_SKILL_LOADS)
|
||||
.collect::<Vec<_>>();
|
||||
let (namespace_resolver, skill_results) = tokio::join!(namespace_resolver, skill_results);
|
||||
|
||||
let mut loaded_skills = Vec::new();
|
||||
let mut skill_discovery_path_by_path = HashMap::new();
|
||||
let mut errors = Vec::new();
|
||||
for (path, path_uri, discovery_path, result) in skill_results {
|
||||
let result = result.and_then(|mut skill| {
|
||||
skill.name = namespace_resolver
|
||||
.for_skill(&root_uri, &path_uri)
|
||||
.qualify(&skill.name);
|
||||
validate_len(&skill.name, MAX_QUALIFIED_NAME_LEN, "qualified name")
|
||||
.map_err(|error| error.to_string())?;
|
||||
Ok(skill)
|
||||
});
|
||||
match result {
|
||||
Ok(skill) => {
|
||||
skill_discovery_path_by_path.insert(
|
||||
skill.path_to_skills_md.clone(),
|
||||
PathUri::from_abs_path(&discovery_path),
|
||||
);
|
||||
loaded_skills.push(skill);
|
||||
}
|
||||
Err(message) if skill_root.scope != SkillScope::System => {
|
||||
errors.push(SkillError { path, message });
|
||||
}
|
||||
Err(_) => {}
|
||||
}
|
||||
}
|
||||
(
|
||||
loaded_skills,
|
||||
Arc::new(skill_discovery_path_by_path),
|
||||
errors,
|
||||
)
|
||||
}
|
||||
|
||||
async fn parse_skill_file(
|
||||
file_system: &dyn EnvironmentAccess,
|
||||
skill: &DiscoveredSkill,
|
||||
path: &AbsolutePathBuf,
|
||||
path_uri: &PathUri,
|
||||
scope: SkillScope,
|
||||
plugin_identity: Option<&PluginIdentity>,
|
||||
plugin_root: Option<&AbsolutePathBuf>,
|
||||
) -> Result<SkillMetadata, String> {
|
||||
let metadata_path = path_uri
|
||||
.parent()
|
||||
.and_then(|parent| parent.join(SKILLS_METADATA_DIR).ok())
|
||||
.and_then(|directory| directory.join(SKILLS_METADATA_FILENAME).ok());
|
||||
let metadata = match &skill.metadata {
|
||||
SkillMetadataDiscovery::Present(_) => metadata_path.map(SkillMetadataDiscovery::Present),
|
||||
SkillMetadataDiscovery::Probe(_) => metadata_path.map(SkillMetadataDiscovery::Probe),
|
||||
SkillMetadataDiscovery::Absent => None,
|
||||
}
|
||||
.unwrap_or(SkillMetadataDiscovery::Absent);
|
||||
let (contents, loaded_metadata) = tokio::join!(
|
||||
file_system.read_file_text(path_uri, ReadFileOptions::default(),),
|
||||
load_host_skill_metadata(file_system, path, &metadata, plugin_root),
|
||||
);
|
||||
let contents = contents.map_err(|error| format!("failed to read file: {error}"))?;
|
||||
let ParsedSkillFrontmatter {
|
||||
name,
|
||||
description,
|
||||
short_description,
|
||||
} = parse_skill_frontmatter_metadata(&contents, || default_skill_name(path))
|
||||
.map_err(|error| error.to_string())?;
|
||||
let LoadedSkillMetadata {
|
||||
interface,
|
||||
dependencies,
|
||||
policy,
|
||||
} = loaded_metadata;
|
||||
|
||||
Ok(SkillMetadata {
|
||||
name,
|
||||
description,
|
||||
short_description,
|
||||
interface,
|
||||
dependencies,
|
||||
policy,
|
||||
path_to_skills_md: path_uri.clone(),
|
||||
scope,
|
||||
plugin_id: plugin_identity.map(|identity| identity.plugin_id.clone()),
|
||||
remote_plugin_id: plugin_identity.and_then(|identity| identity.remote_plugin_id.clone()),
|
||||
})
|
||||
}
|
||||
|
||||
fn default_skill_name(path: &AbsolutePathBuf) -> String {
|
||||
path.parent()
|
||||
.and_then(|parent| {
|
||||
parent
|
||||
.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.map(sanitize_single_line)
|
||||
})
|
||||
.filter(|value| !value.is_empty())
|
||||
.unwrap_or_else(|| "skill".to_string())
|
||||
}
|
||||
|
||||
pub(crate) async fn canonicalize_for_skill_identity(
|
||||
file_system: &dyn EnvironmentAccess,
|
||||
path: &AbsolutePathBuf,
|
||||
) -> AbsolutePathBuf {
|
||||
let path_uri = PathUri::from_abs_path(path);
|
||||
file_system
|
||||
.canonicalize(&path_uri)
|
||||
.await
|
||||
.and_then(|path| path.to_abs_path())
|
||||
.unwrap_or_else(|_| path.clone())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "host_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
#[path = "host_io_tests.rs"]
|
||||
mod io_tests;
|
||||
140
codex-rs/ext/skills/src/loader/host_io_tests.rs
Normal file
140
codex-rs/ext/skills/src/loader/host_io_tests.rs
Normal file
@@ -0,0 +1,140 @@
|
||||
use std::fs;
|
||||
use std::os::unix::fs::symlink;
|
||||
use std::sync::Arc;
|
||||
|
||||
use codex_exec_server::ExecutorFileSystem;
|
||||
use codex_exec_server::FileSystemEnvironmentAccessor;
|
||||
use codex_exec_server::LOCAL_FS;
|
||||
use codex_protocol::protocol::SkillScope;
|
||||
use codex_skills::SkillMetadata;
|
||||
use codex_skills::SkillPolicy;
|
||||
use codex_utils_absolute_path::test_support::PathBufExt;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::tempdir;
|
||||
use tokio::sync::Semaphore;
|
||||
|
||||
use crate::loader::HostSkillRoot;
|
||||
use crate::loader::MAX_CONCURRENT_ROOT_SCANS;
|
||||
use crate::loader::io_test_support::ManifestMetadataBehavior;
|
||||
use crate::loader::io_test_support::RecordingFileSystem;
|
||||
use crate::loader::load_and_merge_host_skill_roots;
|
||||
|
||||
#[tokio::test]
|
||||
async fn host_loading_reuses_walk_inventory_for_symlinked_skill_pack() {
|
||||
let root = tempdir().expect("tempdir");
|
||||
let shared_plugin_root = tempdir().expect("tempdir");
|
||||
let manifest_path = shared_plugin_root.path().join(".codex-plugin/plugin.json");
|
||||
fs::create_dir_all(manifest_path.parent().expect("manifest parent")).expect("manifest dir");
|
||||
fs::write(&manifest_path, r#"{"name":"linked"}"#).expect("manifest");
|
||||
|
||||
let skills_root = shared_plugin_root.path().join("skills");
|
||||
for name in ["first", "second"] {
|
||||
let skill_path = skills_root.join(name).join("SKILL.md");
|
||||
fs::create_dir_all(skill_path.parent().expect("skill parent")).expect("skill dir");
|
||||
fs::write(
|
||||
&skill_path,
|
||||
format!("---\nname: {name}\ndescription: {name} skill.\n---\n"),
|
||||
)
|
||||
.expect("skill");
|
||||
}
|
||||
let metadata_path = skills_root.join("first/agents/openai.yaml");
|
||||
fs::create_dir_all(metadata_path.parent().expect("metadata parent")).expect("metadata dir");
|
||||
fs::write(
|
||||
&metadata_path,
|
||||
"policy:\n allow_implicit_invocation: false\n",
|
||||
)
|
||||
.expect("metadata");
|
||||
|
||||
let host_root = root.path().join("skills");
|
||||
fs::create_dir_all(&host_root).expect("host skills dir");
|
||||
let linked_root = host_root.join("linked-plugin");
|
||||
symlink(&skills_root, &linked_root).expect("skill pack symlink");
|
||||
|
||||
let recording = Arc::new(RecordingFileSystem::new(
|
||||
LOCAL_FS.as_ref(),
|
||||
ManifestMetadataBehavior::Immediate,
|
||||
));
|
||||
let file_system: Arc<dyn ExecutorFileSystem> = recording.clone();
|
||||
let access = FileSystemEnvironmentAccessor::unrestricted(&file_system);
|
||||
let root_scan_slots = Semaphore::new(MAX_CONCURRENT_ROOT_SCANS);
|
||||
let future = load_and_merge_host_skill_roots(
|
||||
vec![HostSkillRoot::host(
|
||||
host_root.abs(),
|
||||
SkillScope::User,
|
||||
&access,
|
||||
)],
|
||||
&root_scan_slots,
|
||||
/*restriction_product*/ None,
|
||||
/*plugin_skill_snapshots*/ None,
|
||||
);
|
||||
fn assert_send<T: Send>(_: &T) {}
|
||||
assert_send(&future);
|
||||
let outcome = future.await;
|
||||
|
||||
assert_eq!(outcome.errors, Vec::new());
|
||||
let first_skill_path = dunce::canonicalize(skills_root.join("first/SKILL.md"))
|
||||
.unwrap()
|
||||
.abs();
|
||||
let second_skill_path = dunce::canonicalize(skills_root.join("second/SKILL.md"))
|
||||
.unwrap()
|
||||
.abs();
|
||||
assert_eq!(
|
||||
outcome.skills,
|
||||
vec![
|
||||
SkillMetadata {
|
||||
name: "linked:first".to_string(),
|
||||
description: "first skill.".to_string(),
|
||||
short_description: None,
|
||||
interface: None,
|
||||
dependencies: None,
|
||||
policy: Some(SkillPolicy {
|
||||
allow_implicit_invocation: Some(false),
|
||||
products: Vec::new(),
|
||||
}),
|
||||
path_to_skills_md: PathUri::from_abs_path(&first_skill_path),
|
||||
scope: SkillScope::User,
|
||||
plugin_id: None,
|
||||
remote_plugin_id: None,
|
||||
},
|
||||
SkillMetadata {
|
||||
name: "linked:second".to_string(),
|
||||
description: "second skill.".to_string(),
|
||||
short_description: None,
|
||||
interface: None,
|
||||
dependencies: None,
|
||||
policy: None,
|
||||
path_to_skills_md: PathUri::from_abs_path(&second_skill_path),
|
||||
scope: SkillScope::User,
|
||||
plugin_id: None,
|
||||
remote_plugin_id: None,
|
||||
},
|
||||
]
|
||||
);
|
||||
|
||||
let calls = recording.calls();
|
||||
assert_eq!(calls.walks, 1);
|
||||
let linked_root = PathUri::from_host_native_path(linked_root).unwrap();
|
||||
assert!(
|
||||
calls
|
||||
.read_files
|
||||
.iter()
|
||||
.all(|path| !path.starts_with(&linked_root))
|
||||
);
|
||||
assert!(
|
||||
calls
|
||||
.metadata_files
|
||||
.iter()
|
||||
.all(|path| path.basename().as_deref() != Some("openai.yaml"))
|
||||
);
|
||||
let manifest_uri =
|
||||
PathUri::from_host_native_path(dunce::canonicalize(manifest_path).unwrap()).unwrap();
|
||||
assert_eq!(
|
||||
calls
|
||||
.metadata_files
|
||||
.iter()
|
||||
.filter(|path| **path == manifest_uri)
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
}
|
||||
271
codex-rs/ext/skills/src/loader/host_merge.rs
Normal file
271
codex-rs/ext/skills/src/loader/host_merge.rs
Normal file
@@ -0,0 +1,271 @@
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
use codex_exec_server::EnvironmentAccessKey;
|
||||
use codex_protocol::protocol::Product;
|
||||
use codex_protocol::protocol::SkillScope;
|
||||
use codex_skills::LoadedSkillRoot;
|
||||
use codex_skills::SkillRootSnapshots;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use codex_utils_plugins::PluginSkillRoot;
|
||||
use codex_utils_plugins::migrated_command_skills_root;
|
||||
use futures::FutureExt;
|
||||
use futures::StreamExt;
|
||||
use tokio::sync::OnceCell;
|
||||
use tokio::sync::Semaphore;
|
||||
|
||||
use super::HostSkillRoot;
|
||||
use super::MAX_CONCURRENT_ROOT_SCANS;
|
||||
use super::canonicalize_for_skill_identity;
|
||||
use super::host::HostSkillRootSnapshot;
|
||||
use super::load_host_skill_root;
|
||||
use crate::SkillLoadOutcome;
|
||||
use crate::host_service::RequestSkillRootSnapshots;
|
||||
use crate::host_service::config_skill_root_cache_key;
|
||||
|
||||
pub(crate) async fn load_and_merge_host_skill_roots(
|
||||
roots: Vec<HostSkillRoot<'_>>,
|
||||
root_scan_slots: &Semaphore,
|
||||
restriction_product: Option<Product>,
|
||||
plugin_skill_snapshots: Option<&SkillRootSnapshots<PluginSkillRoot>>,
|
||||
) -> SkillLoadOutcome {
|
||||
load_and_merge_host_skill_roots_with_request_snapshots(
|
||||
roots,
|
||||
root_scan_slots,
|
||||
restriction_product,
|
||||
plugin_skill_snapshots,
|
||||
/*request_root_snapshots*/ None,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(crate) async fn load_and_merge_host_skill_roots_with_request_snapshots(
|
||||
roots: Vec<HostSkillRoot<'_>>,
|
||||
root_scan_slots: &Semaphore,
|
||||
restriction_product: Option<Product>,
|
||||
plugin_skill_snapshots: Option<&SkillRootSnapshots<PluginSkillRoot>>,
|
||||
request_root_snapshots: Option<&RequestSkillRootSnapshots>,
|
||||
) -> SkillLoadOutcome {
|
||||
let migrated_command_roots_by_plugin = roots
|
||||
.iter()
|
||||
.filter_map(HostSkillRoot::plugin_root)
|
||||
.map(|plugin_root| (plugin_root.clone(), Arc::new(OnceCell::new())))
|
||||
.collect::<HashMap<_, _>>();
|
||||
let migrated_command_roots = &migrated_command_roots_by_plugin;
|
||||
let mut loads = Vec::with_capacity(roots.len());
|
||||
for (root_index, root) in roots.into_iter().enumerate() {
|
||||
loads.push(async move {
|
||||
let plugin_root = root.plugin_root().cloned();
|
||||
let migrated_command_root = plugin_root
|
||||
.as_ref()
|
||||
.and_then(|plugin_root| migrated_command_roots.get(plugin_root))
|
||||
.cloned();
|
||||
let plugin_skill_root = root.plugin_skill_root();
|
||||
let file_system = root.file_system;
|
||||
let request_snapshot = if plugin_skill_root.is_none() {
|
||||
request_root_snapshots.map(|snapshots| {
|
||||
Arc::clone(
|
||||
snapshots
|
||||
.write()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.entry(config_skill_root_cache_key(&root))
|
||||
.or_insert_with(|| Arc::new(OnceCell::new())),
|
||||
)
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let load = async {
|
||||
let _root_scan_slot = root_scan_slots
|
||||
.acquire()
|
||||
.await
|
||||
.unwrap_or_else(|_| unreachable!());
|
||||
let cached_snapshot = plugin_skill_root
|
||||
.as_ref()
|
||||
.and_then(|plugin_skill_root| plugin_skill_snapshots?.get(plugin_skill_root));
|
||||
match cached_snapshot {
|
||||
Some(snapshot) => HostSkillRootSnapshot {
|
||||
root: snapshot.root,
|
||||
skills: snapshot.skills,
|
||||
skill_discovery_path_by_path: snapshot.skill_discovery_path_by_path,
|
||||
errors: snapshot.errors,
|
||||
file_system: file_system.cache_key(),
|
||||
is_agent_plugin: snapshot.is_agent_plugin,
|
||||
},
|
||||
None => {
|
||||
let snapshot = load_host_skill_root(root).await;
|
||||
if let Some(plugin_skill_snapshots) = plugin_skill_snapshots
|
||||
&& let Some(plugin_skill_root) = plugin_skill_root
|
||||
{
|
||||
plugin_skill_snapshots.insert(
|
||||
plugin_skill_root,
|
||||
LoadedSkillRoot {
|
||||
root: snapshot.root.clone(),
|
||||
skills: snapshot.skills.clone(),
|
||||
skill_discovery_path_by_path: Arc::clone(
|
||||
&snapshot.skill_discovery_path_by_path,
|
||||
),
|
||||
errors: snapshot.errors.clone(),
|
||||
is_agent_plugin: snapshot.is_agent_plugin,
|
||||
},
|
||||
);
|
||||
}
|
||||
snapshot
|
||||
}
|
||||
}
|
||||
}
|
||||
.boxed();
|
||||
let snapshot = if let Some(snapshot) = request_snapshot {
|
||||
snapshot.get_or_init(|| load).await.clone()
|
||||
} else {
|
||||
load.await
|
||||
};
|
||||
let migrated_command_root = match (plugin_root.as_ref(), migrated_command_root) {
|
||||
(Some(plugin_root), Some(migrated_command_root)) => Some(
|
||||
migrated_command_root
|
||||
.get_or_init(|| async {
|
||||
canonicalize_for_skill_identity(
|
||||
file_system,
|
||||
&migrated_command_skills_root(plugin_root),
|
||||
)
|
||||
.await
|
||||
})
|
||||
.await
|
||||
.clone(),
|
||||
),
|
||||
_ => None,
|
||||
};
|
||||
(root_index, migrated_command_root, snapshot)
|
||||
});
|
||||
}
|
||||
let mut indexed_snapshots = futures::stream::iter(loads)
|
||||
.buffer_unordered(MAX_CONCURRENT_ROOT_SCANS)
|
||||
.collect::<Vec<_>>()
|
||||
.await;
|
||||
indexed_snapshots.sort_unstable_by_key(|(root_index, _, _)| *root_index);
|
||||
|
||||
for (_, _, snapshot) in &mut indexed_snapshots {
|
||||
snapshot
|
||||
.skills
|
||||
.retain(|skill| skill.matches_product_restriction_for_product(restriction_product));
|
||||
}
|
||||
|
||||
let mut native_plugin_skill_names = HashMap::<String, HashSet<String>>::new();
|
||||
for skill in indexed_snapshots
|
||||
.iter()
|
||||
.flat_map(|(_, migrated_command_root, snapshot)| {
|
||||
snapshot.skills.iter().filter(|skill| {
|
||||
!migrated_command_root.as_ref().is_some_and(|migrated_root| {
|
||||
skill
|
||||
.path_to_skills_md
|
||||
.starts_with(&PathUri::from_abs_path(migrated_root))
|
||||
})
|
||||
})
|
||||
})
|
||||
{
|
||||
if let Some(plugin_id) = &skill.plugin_id {
|
||||
native_plugin_skill_names
|
||||
.entry(plugin_id.clone())
|
||||
.or_default()
|
||||
.insert(skill.name.clone());
|
||||
}
|
||||
}
|
||||
for (_, migrated_command_root, snapshot) in &mut indexed_snapshots {
|
||||
let Some(migrated_command_root) = migrated_command_root else {
|
||||
continue;
|
||||
};
|
||||
snapshot.skills.retain(|skill| {
|
||||
!skill
|
||||
.path_to_skills_md
|
||||
.starts_with(&PathUri::from_abs_path(migrated_command_root))
|
||||
|| skill.plugin_id.as_ref().is_none_or(|plugin_id| {
|
||||
native_plugin_skill_names
|
||||
.get(plugin_id)
|
||||
.is_none_or(|names| !names.contains(&skill.name))
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
merge_host_skill_root_snapshots(
|
||||
indexed_snapshots
|
||||
.into_iter()
|
||||
.map(|(_, _, snapshot)| snapshot)
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
fn merge_host_skill_root_snapshots(snapshots: Vec<HostSkillRootSnapshot>) -> SkillLoadOutcome {
|
||||
let mut skills = Vec::new();
|
||||
let mut errors = Vec::new();
|
||||
let mut skill_roots = Vec::new();
|
||||
let mut skill_root_by_path = HashMap::new();
|
||||
let mut skill_discovery_path_by_path = HashMap::new();
|
||||
let mut agent_plugin_skill_paths = HashSet::new();
|
||||
let mut file_systems_by_skill_path = HashMap::<PathUri, EnvironmentAccessKey>::new();
|
||||
|
||||
for snapshot in snapshots {
|
||||
if !snapshot.skills.is_empty() && !skill_roots.contains(&snapshot.root) {
|
||||
skill_roots.push(snapshot.root.clone());
|
||||
}
|
||||
for skill in &snapshot.skills {
|
||||
let path = skill.path_to_skills_md.clone();
|
||||
if !skill_root_by_path.contains_key(&path) {
|
||||
skill_root_by_path.insert(path.clone(), snapshot.root.clone());
|
||||
if let Some(discovery_path) = snapshot.skill_discovery_path_by_path.get(&path) {
|
||||
skill_discovery_path_by_path.insert(path.clone(), discovery_path.clone());
|
||||
}
|
||||
file_systems_by_skill_path.insert(path.clone(), snapshot.file_system.clone());
|
||||
if snapshot.is_agent_plugin {
|
||||
agent_plugin_skill_paths.insert(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
skills.extend(snapshot.skills);
|
||||
errors.extend(snapshot.errors);
|
||||
}
|
||||
|
||||
let mut seen_paths = HashSet::new();
|
||||
skills.retain(|skill| seen_paths.insert(skill.path_to_skills_md.clone()));
|
||||
let retained_paths = skills
|
||||
.iter()
|
||||
.map(|skill| skill.path_to_skills_md.clone())
|
||||
.collect::<HashSet<_>>();
|
||||
skill_root_by_path.retain(|path, _| retained_paths.contains(path));
|
||||
skill_discovery_path_by_path.retain(|path, _| retained_paths.contains(path));
|
||||
let retained_roots = skill_root_by_path.values().collect::<HashSet<_>>();
|
||||
skill_roots.retain(|root| retained_roots.contains(root));
|
||||
file_systems_by_skill_path.retain(|path, _| retained_paths.contains(path));
|
||||
agent_plugin_skill_paths.retain(|path| retained_paths.contains(path));
|
||||
// Keep native path ordering: URI escaping can reorder same-name skills.
|
||||
skills.sort_by_cached_key(|skill| {
|
||||
(
|
||||
scope_rank(skill.scope),
|
||||
skill.name.clone(),
|
||||
skill.path_to_skills_md.to_abs_path().ok(),
|
||||
)
|
||||
});
|
||||
|
||||
SkillLoadOutcome::from_parts(
|
||||
skills,
|
||||
errors,
|
||||
skill_roots,
|
||||
skill_root_by_path,
|
||||
skill_discovery_path_by_path,
|
||||
agent_plugin_skill_paths,
|
||||
file_systems_by_skill_path,
|
||||
)
|
||||
}
|
||||
|
||||
fn scope_rank(scope: SkillScope) -> u8 {
|
||||
match scope {
|
||||
SkillScope::Repo => 0,
|
||||
SkillScope::User => 1,
|
||||
SkillScope::System => 2,
|
||||
SkillScope::Admin => 3,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "host_merge_tests.rs"]
|
||||
mod tests;
|
||||
546
codex-rs/ext/skills/src/loader/host_merge_tests.rs
Normal file
546
codex-rs/ext/skills/src/loader/host_merge_tests.rs
Normal file
@@ -0,0 +1,546 @@
|
||||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
use codex_exec_server::ExecutorFileSystem;
|
||||
use codex_exec_server::FileSystemEnvironmentAccessor;
|
||||
use codex_exec_server::LOCAL_FS;
|
||||
use codex_protocol::protocol::Product;
|
||||
use codex_protocol::protocol::SkillScope;
|
||||
use codex_skills::LoadedSkillRoot;
|
||||
use codex_skills::SkillError;
|
||||
use codex_skills::SkillRootSnapshotCache;
|
||||
use codex_skills::SkillRootSnapshots;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_absolute_path::test_support::PathBufExt;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use codex_utils_plugins::PluginIdentity;
|
||||
use codex_utils_plugins::PluginSkillRoot;
|
||||
use codex_utils_plugins::SkillDiscoveryMode;
|
||||
use codex_utils_plugins::migrated_command_skills_root;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
use tokio::sync::Semaphore;
|
||||
|
||||
use crate::loader::MAX_CONCURRENT_ROOT_SCANS;
|
||||
use crate::loader::io_test_support::ManifestMetadataBehavior;
|
||||
use crate::loader::io_test_support::RecordingFileSystem;
|
||||
|
||||
use super::HostSkillRoot;
|
||||
use super::load_and_merge_host_skill_roots;
|
||||
|
||||
#[derive(Default)]
|
||||
struct TestPluginSkillSnapshots {
|
||||
snapshots: Mutex<HashMap<PluginSkillRoot, LoadedSkillRoot>>,
|
||||
}
|
||||
|
||||
impl SkillRootSnapshotCache<PluginSkillRoot> for TestPluginSkillSnapshots {
|
||||
fn get(&self, root: &PluginSkillRoot) -> Option<LoadedSkillRoot> {
|
||||
self.snapshots.lock().unwrap().get(root).cloned()
|
||||
}
|
||||
|
||||
fn insert(&self, root: PluginSkillRoot, snapshot: LoadedSkillRoot) {
|
||||
self.snapshots.lock().unwrap().insert(root, snapshot);
|
||||
}
|
||||
}
|
||||
|
||||
fn write_skill(root: &AbsolutePathBuf, directory: &str, name: &str, description: &str) {
|
||||
let skill_dir = root.join(directory);
|
||||
fs::create_dir_all(&skill_dir).expect("create skill directory");
|
||||
fs::write(
|
||||
skill_dir.join("SKILL.md"),
|
||||
format!("---\nname: {name}\ndescription: {description}\n---\n"),
|
||||
)
|
||||
.expect("write skill");
|
||||
}
|
||||
|
||||
struct PluginSkillsFixture {
|
||||
_temp_dir: TempDir,
|
||||
plugin_path: AbsolutePathBuf,
|
||||
native_root: AbsolutePathBuf,
|
||||
migrated_root: AbsolutePathBuf,
|
||||
identity: PluginIdentity,
|
||||
access: FileSystemEnvironmentAccessor<'static>,
|
||||
}
|
||||
|
||||
impl PluginSkillsFixture {
|
||||
fn new() -> Self {
|
||||
let temp_dir = TempDir::new().expect("temp dir");
|
||||
let plugin_path = AbsolutePathBuf::from_absolute_path_checked(temp_dir.path())
|
||||
.expect("absolute plugin path");
|
||||
let native_root = plugin_path.join("skills");
|
||||
let migrated_root = migrated_command_skills_root(&plugin_path);
|
||||
write_skill(&native_root, "review", "source-command-review", "native");
|
||||
write_skill(
|
||||
&migrated_root,
|
||||
"review",
|
||||
"source-command-review",
|
||||
"migrated duplicate",
|
||||
);
|
||||
write_skill(
|
||||
&migrated_root,
|
||||
"only",
|
||||
"source-command-only",
|
||||
"migrated only",
|
||||
);
|
||||
Self {
|
||||
_temp_dir: temp_dir,
|
||||
plugin_path,
|
||||
native_root,
|
||||
migrated_root,
|
||||
access: FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS),
|
||||
identity: PluginIdentity {
|
||||
plugin_id: "sample@test".to_string(),
|
||||
remote_plugin_id: Some("remote-sample".to_string()),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn root(&self, path: AbsolutePathBuf) -> HostSkillRoot<'_> {
|
||||
HostSkillRoot::plugin(
|
||||
PluginSkillRoot {
|
||||
path,
|
||||
plugin_identity: self.identity.clone(),
|
||||
plugin_namespace: "sample".to_string(),
|
||||
plugin_root: self.plugin_path.clone(),
|
||||
discovery_mode: SkillDiscoveryMode::Recursive,
|
||||
},
|
||||
&self.access,
|
||||
)
|
||||
}
|
||||
|
||||
fn roots(&self) -> Vec<HostSkillRoot<'_>> {
|
||||
[self.migrated_root.clone(), self.native_root.clone()]
|
||||
.into_iter()
|
||||
.map(|path| self.root(path))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn native_plugin_skill_replaces_migrated_command_with_the_same_name() {
|
||||
let fixture = PluginSkillsFixture::new();
|
||||
|
||||
let outcome = load_and_merge_host_skill_roots(
|
||||
fixture.roots(),
|
||||
&Semaphore::new(2),
|
||||
/*restriction_product*/ None,
|
||||
/*plugin_skill_snapshots*/ None,
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(
|
||||
outcome
|
||||
.skills
|
||||
.iter()
|
||||
.map(|skill| (skill.name.as_str(), skill.description.as_str()))
|
||||
.collect::<Vec<_>>(),
|
||||
vec![
|
||||
("sample:source-command-only", "migrated only"),
|
||||
("sample:source-command-review", "native"),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn nested_migrated_command_root_preserves_native_skill_precedence() {
|
||||
let fixture = PluginSkillsFixture::new();
|
||||
|
||||
let outcome = load_and_merge_host_skill_roots(
|
||||
vec![
|
||||
fixture.root(fixture.migrated_root.join("review")),
|
||||
fixture.root(fixture.native_root.clone()),
|
||||
fixture.root(fixture.migrated_root.clone()),
|
||||
],
|
||||
&Semaphore::new(3),
|
||||
/*restriction_product*/ None,
|
||||
/*plugin_skill_snapshots*/ None,
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(
|
||||
outcome
|
||||
.skills
|
||||
.iter()
|
||||
.map(|skill| (skill.name.as_str(), skill.description.as_str()))
|
||||
.collect::<Vec<_>>(),
|
||||
vec![
|
||||
("sample:source-command-only", "migrated only"),
|
||||
("sample:source-command-review", "native"),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn product_filtered_native_skill_does_not_hide_migrated_command() {
|
||||
let fixture = PluginSkillsFixture::new();
|
||||
let metadata_dir = fixture.native_root.join("review/agents");
|
||||
fs::create_dir_all(&metadata_dir).expect("create metadata directory");
|
||||
fs::write(
|
||||
metadata_dir.join("openai.yaml"),
|
||||
"policy:\n products: [CHATGPT]\n",
|
||||
)
|
||||
.expect("write product policy");
|
||||
|
||||
let outcome = load_and_merge_host_skill_roots(
|
||||
fixture.roots(),
|
||||
&Semaphore::new(2),
|
||||
Some(Product::Codex),
|
||||
/*plugin_skill_snapshots*/ None,
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(
|
||||
outcome
|
||||
.skills
|
||||
.iter()
|
||||
.map(|skill| (skill.name.as_str(), skill.description.as_str()))
|
||||
.collect::<Vec<_>>(),
|
||||
vec![
|
||||
("sample:source-command-only", "migrated only"),
|
||||
("sample:source-command-review", "migrated duplicate"),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn overlapping_plugin_roots_keep_one_canonical_skill() {
|
||||
let fixture = PluginSkillsFixture::new();
|
||||
|
||||
let outcome = load_and_merge_host_skill_roots(
|
||||
vec![
|
||||
fixture.root(fixture.native_root.clone()),
|
||||
fixture.root(fixture.native_root.join("review")),
|
||||
],
|
||||
&Semaphore::new(2),
|
||||
/*restriction_product*/ None,
|
||||
/*plugin_skill_snapshots*/ None,
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(
|
||||
outcome
|
||||
.skills
|
||||
.iter()
|
||||
.map(|skill| skill.name.as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
vec!["sample:source-command-review"]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reuses_owner_managed_plugin_root_snapshots() {
|
||||
let fixture = PluginSkillsFixture::new();
|
||||
let snapshots = SkillRootSnapshots::new(Arc::new(TestPluginSkillSnapshots::default()));
|
||||
let first_outcome = load_and_merge_host_skill_roots(
|
||||
vec![fixture.root(fixture.native_root.clone())],
|
||||
&Semaphore::new(2),
|
||||
/*restriction_product*/ None,
|
||||
Some(&snapshots),
|
||||
)
|
||||
.await;
|
||||
write_skill(
|
||||
&fixture.native_root,
|
||||
"review",
|
||||
"source-command-review",
|
||||
"updated",
|
||||
);
|
||||
|
||||
let cached_outcome = load_and_merge_host_skill_roots(
|
||||
vec![fixture.root(fixture.native_root.clone())],
|
||||
&Semaphore::new(2),
|
||||
/*restriction_product*/ None,
|
||||
Some(&snapshots),
|
||||
)
|
||||
.await;
|
||||
let refreshed_outcome = load_and_merge_host_skill_roots(
|
||||
vec![fixture.root(fixture.native_root.clone())],
|
||||
&Semaphore::new(2),
|
||||
/*restriction_product*/ None,
|
||||
/*plugin_skill_snapshots*/ None,
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(first_outcome.skills, cached_outcome.skills);
|
||||
assert_eq!(cached_outcome.skills[0].description, "native");
|
||||
assert_eq!(refreshed_outcome.skills[0].description, "updated");
|
||||
assert_eq!(
|
||||
cached_outcome.skills[0].remote_plugin_id.as_deref(),
|
||||
Some("remote-sample")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn preserves_plugin_skill_errors() {
|
||||
let fixture = PluginSkillsFixture::new();
|
||||
fs::write(
|
||||
fixture.native_root.join("review/SKILL.md"),
|
||||
"missing frontmatter",
|
||||
)
|
||||
.expect("write invalid plugin skill");
|
||||
|
||||
let outcome = load_and_merge_host_skill_roots(
|
||||
vec![fixture.root(fixture.native_root.clone())],
|
||||
&Semaphore::new(2),
|
||||
/*restriction_product*/ None,
|
||||
/*plugin_skill_snapshots*/ None,
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(outcome.skills, Vec::new());
|
||||
assert_eq!(outcome.errors.len(), 1);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn recognizes_symlinked_migrated_command_roots() {
|
||||
let fixture = PluginSkillsFixture::new();
|
||||
let alias = fixture.plugin_path.join("migrated-alias");
|
||||
std::os::unix::fs::symlink(fixture.migrated_root.as_path(), alias.as_path())
|
||||
.expect("create migrated root alias");
|
||||
|
||||
let outcome = load_and_merge_host_skill_roots(
|
||||
vec![
|
||||
fixture.root(alias),
|
||||
fixture.root(fixture.native_root.clone()),
|
||||
],
|
||||
&Semaphore::new(2),
|
||||
/*restriction_product*/ None,
|
||||
/*plugin_skill_snapshots*/ None,
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(
|
||||
outcome
|
||||
.skills
|
||||
.iter()
|
||||
.map(|skill| (skill.name.as_str(), skill.description.as_str()))
|
||||
.collect::<Vec<_>>(),
|
||||
vec![
|
||||
("sample:source-command-only", "migrated only"),
|
||||
("sample:source-command-review", "native"),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn host_root_scans_wait_for_shared_capacity() {
|
||||
let access = FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS);
|
||||
let temp = TempDir::new().expect("temp dir");
|
||||
let root = AbsolutePathBuf::from_absolute_path(temp.path()).expect("absolute skill root");
|
||||
let root_scan_slots = Semaphore::new(/*permits*/ 1);
|
||||
let held_slot = root_scan_slots
|
||||
.try_acquire()
|
||||
.expect("root scan slot should be available");
|
||||
let load = load_and_merge_host_skill_roots(
|
||||
vec![HostSkillRoot::host(root, SkillScope::Repo, &access)],
|
||||
&root_scan_slots,
|
||||
/*restriction_product*/ None,
|
||||
/*plugin_skill_snapshots*/ None,
|
||||
);
|
||||
tokio::pin!(load);
|
||||
|
||||
assert!(futures::poll!(load.as_mut()).is_pending());
|
||||
drop(held_slot);
|
||||
let outcome = load.await;
|
||||
|
||||
assert_eq!(outcome.skills, Vec::new());
|
||||
assert_eq!(outcome.errors, Vec::new());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn duplicate_host_root_paths_preserve_first_root_scope() {
|
||||
let access = FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS);
|
||||
let temp = TempDir::new().expect("temp dir");
|
||||
let root = AbsolutePathBuf::from_absolute_path(temp.path()).expect("absolute skill root");
|
||||
write_skill(&root, "demo", "demo", "Shared skill");
|
||||
|
||||
let outcome = load_and_merge_host_skill_roots(
|
||||
vec![
|
||||
HostSkillRoot::host(root.clone(), SkillScope::Repo, &access),
|
||||
HostSkillRoot::host(root.clone(), SkillScope::User, &access),
|
||||
],
|
||||
&Semaphore::new(/*permits*/ 2),
|
||||
/*restriction_product*/ None,
|
||||
/*plugin_skill_snapshots*/ None,
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(outcome.errors, Vec::new());
|
||||
assert_eq!(outcome.skills.len(), 1);
|
||||
assert_eq!(outcome.skills[0].scope, SkillScope::Repo);
|
||||
let canonical_root = AbsolutePathBuf::from_absolute_path(
|
||||
fs::canonicalize(root.as_path()).expect("canonicalize skill root"),
|
||||
)
|
||||
.expect("absolute canonical skill root");
|
||||
assert_eq!(
|
||||
outcome.skill_root_for_path(&outcome.skills[0].path_to_skills_md),
|
||||
Some(&canonical_root)
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn deduplicated_symlinked_skill_preserves_first_discovery_path() {
|
||||
let access = FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS);
|
||||
let source = TempDir::new().expect("source temp dir");
|
||||
let first = TempDir::new().expect("first root temp dir");
|
||||
let second = TempDir::new().expect("second root temp dir");
|
||||
let source_root =
|
||||
AbsolutePathBuf::from_absolute_path(source.path()).expect("absolute source root");
|
||||
let first_root =
|
||||
AbsolutePathBuf::from_absolute_path(first.path()).expect("absolute first root");
|
||||
let second_root =
|
||||
AbsolutePathBuf::from_absolute_path(second.path()).expect("absolute second root");
|
||||
write_skill(&source_root, "demo", "demo", "Shared skill");
|
||||
std::os::unix::fs::symlink(source.path().join("demo"), first.path().join("first-link"))
|
||||
.expect("create first skill directory symlink");
|
||||
std::os::unix::fs::symlink(
|
||||
source.path().join("demo"),
|
||||
second.path().join("second-link"),
|
||||
)
|
||||
.expect("create second skill directory symlink");
|
||||
|
||||
let outcome = load_and_merge_host_skill_roots(
|
||||
vec![
|
||||
HostSkillRoot::host(first_root.clone(), SkillScope::Repo, &access),
|
||||
HostSkillRoot::host(second_root, SkillScope::User, &access),
|
||||
],
|
||||
&Semaphore::new(/*permits*/ 2),
|
||||
/*restriction_product*/ None,
|
||||
/*plugin_skill_snapshots*/ None,
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(outcome.errors, Vec::new());
|
||||
assert_eq!(outcome.skills.len(), 1);
|
||||
let skill_path = &outcome.skills[0].path_to_skills_md;
|
||||
let canonical_first_root = AbsolutePathBuf::from_absolute_path(
|
||||
fs::canonicalize(first_root.as_path()).expect("canonicalize first skill root"),
|
||||
)
|
||||
.expect("absolute first skill root");
|
||||
assert_eq!(
|
||||
(
|
||||
outcome.skill_root_for_path(skill_path),
|
||||
outcome.skill_discovery_path_for_path(skill_path),
|
||||
),
|
||||
(
|
||||
Some(&canonical_first_root),
|
||||
Some(&PathUri::from_abs_path(
|
||||
&canonical_first_root.join("first-link/SKILL.md")
|
||||
)),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn merges_host_root_results_in_input_order_when_scans_finish_out_of_order() {
|
||||
const ROOT_COUNT: usize = MAX_CONCURRENT_ROOT_SCANS + 1;
|
||||
|
||||
let temp = TempDir::new().expect("temp dir");
|
||||
let roots = (0..ROOT_COUNT)
|
||||
.map(|index| temp.path().join(format!("root-{index}")))
|
||||
.collect::<Vec<_>>();
|
||||
for root in &roots {
|
||||
fs::create_dir_all(root).expect("create skill root");
|
||||
}
|
||||
let first_skill = roots[0].join("broken/SKILL.md");
|
||||
let second_skill = roots[1].join("broken/SKILL.md");
|
||||
for path in [&first_skill, &second_skill] {
|
||||
fs::create_dir_all(path.parent().expect("skill parent"))
|
||||
.expect("create invalid skill directory");
|
||||
fs::write(path, "missing frontmatter").expect("write invalid skill");
|
||||
}
|
||||
|
||||
let mut recording =
|
||||
RecordingFileSystem::new(LOCAL_FS.as_ref(), ManifestMetadataBehavior::Immediate);
|
||||
recording.blocked_walk_root = Some(PathUri::from_abs_path(
|
||||
&dunce::canonicalize(&roots[0])
|
||||
.expect("canonical blocked skill root")
|
||||
.abs(),
|
||||
));
|
||||
let recording = Arc::new(recording);
|
||||
let file_system: Arc<dyn ExecutorFileSystem> = recording.clone();
|
||||
let load = tokio::spawn(async move {
|
||||
let access = FileSystemEnvironmentAccessor::unrestricted(&file_system);
|
||||
let host_roots = roots
|
||||
.iter()
|
||||
.map(|root| HostSkillRoot::host(root.clone().abs(), SkillScope::User, &access))
|
||||
.collect::<Vec<_>>();
|
||||
load_and_merge_host_skill_roots(
|
||||
host_roots,
|
||||
&Semaphore::new(MAX_CONCURRENT_ROOT_SCANS),
|
||||
/*restriction_product*/ None,
|
||||
/*plugin_skill_snapshots*/ None,
|
||||
)
|
||||
.await
|
||||
});
|
||||
|
||||
tokio::time::timeout(std::time::Duration::from_secs(/*secs*/ 5), async {
|
||||
loop {
|
||||
let walk_started = recording.walk_started.notified();
|
||||
if recording.walks.load(Ordering::Acquire) == ROOT_COUNT {
|
||||
break;
|
||||
}
|
||||
walk_started.await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("all host root scans should start despite the blocked first root");
|
||||
recording.blocked_walk_gate.add_permits(/*n*/ 1);
|
||||
let outcome = load.await.expect("host skill root loading should complete");
|
||||
|
||||
assert_eq!(outcome.skills, Vec::new());
|
||||
assert_eq!(
|
||||
outcome.errors,
|
||||
vec![
|
||||
SkillError {
|
||||
path: dunce::canonicalize(first_skill)
|
||||
.expect("canonical first invalid skill path")
|
||||
.abs(),
|
||||
message: "missing YAML frontmatter delimited by ---".to_string(),
|
||||
},
|
||||
SkillError {
|
||||
path: dunce::canonicalize(second_skill)
|
||||
.expect("canonical second invalid skill path")
|
||||
.abs(),
|
||||
message: "missing YAML frontmatter delimited by ---".to_string(),
|
||||
},
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/// Equal-name skills retain native path order so URI escaping does not reorder the catalog.
|
||||
#[tokio::test]
|
||||
async fn same_name_skills_preserve_native_path_order() {
|
||||
let access = FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS);
|
||||
let temp = TempDir::new().expect("temp dir");
|
||||
let root = dunce::canonicalize(temp.path())
|
||||
.expect("canonical skill root")
|
||||
.abs();
|
||||
write_skill(&root, "é", "demo", "Accented path");
|
||||
write_skill(&root, "a", "demo", "ASCII path");
|
||||
|
||||
let outcome = load_and_merge_host_skill_roots(
|
||||
vec![HostSkillRoot::host(root.clone(), SkillScope::User, &access)],
|
||||
&Semaphore::new(/*permits*/ 1),
|
||||
/*restriction_product*/ None,
|
||||
/*plugin_skill_snapshots*/ None,
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(outcome.errors, Vec::new());
|
||||
assert_eq!(
|
||||
outcome
|
||||
.skills
|
||||
.iter()
|
||||
.map(|skill| &skill.path_to_skills_md)
|
||||
.collect::<Vec<_>>(),
|
||||
vec![
|
||||
&PathUri::from_abs_path(&root.join("a/SKILL.md")),
|
||||
&PathUri::from_abs_path(&root.join("é/SKILL.md")),
|
||||
]
|
||||
);
|
||||
}
|
||||
742
codex-rs/ext/skills/src/loader/host_tests.rs
Normal file
742
codex-rs/ext/skills/src/loader/host_tests.rs
Normal file
@@ -0,0 +1,742 @@
|
||||
use std::fs;
|
||||
|
||||
use codex_exec_server::EnvironmentAccess;
|
||||
use codex_exec_server::FileSystemEnvironmentAccessor;
|
||||
use codex_exec_server::LOCAL_FS;
|
||||
use codex_protocol::protocol::Product;
|
||||
use codex_protocol::protocol::SkillScope;
|
||||
use codex_skills::SkillDependencies;
|
||||
use codex_skills::SkillInterface;
|
||||
use codex_skills::SkillMetadata;
|
||||
use codex_skills::SkillPolicy;
|
||||
use codex_skills::SkillToolDependency;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use codex_utils_plugins::PluginIdentity;
|
||||
use codex_utils_plugins::PluginSkillRoot;
|
||||
use codex_utils_plugins::SkillDiscoveryMode;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
|
||||
use crate::loader::MAX_NAME_LEN;
|
||||
|
||||
use super::HostSkillRoot;
|
||||
use super::load_host_skill_root;
|
||||
|
||||
fn write_skill(root: &TempDir, directory: &str, frontmatter: &str) -> AbsolutePathBuf {
|
||||
let skill_dir = root.path().join(directory);
|
||||
fs::create_dir_all(&skill_dir).expect("create skill directory");
|
||||
let skill_path = skill_dir.join("SKILL.md");
|
||||
fs::write(
|
||||
&skill_path,
|
||||
format!("---\n{frontmatter}\n---\n\n# Instructions\n"),
|
||||
)
|
||||
.expect("write skill");
|
||||
AbsolutePathBuf::from_absolute_path(fs::canonicalize(skill_path).expect("canonical skill path"))
|
||||
.expect("absolute skill path")
|
||||
}
|
||||
|
||||
fn write_metadata(root: &TempDir, directory: &str, contents: &str) {
|
||||
let metadata_dir = root.path().join(directory).join("agents");
|
||||
fs::create_dir_all(&metadata_dir).expect("create metadata directory");
|
||||
fs::write(metadata_dir.join("openai.yaml"), contents).expect("write metadata");
|
||||
}
|
||||
|
||||
fn root_for<'a>(
|
||||
temp_dir: &TempDir,
|
||||
scope: SkillScope,
|
||||
access: &'a dyn EnvironmentAccess,
|
||||
) -> HostSkillRoot<'a> {
|
||||
HostSkillRoot::host(
|
||||
AbsolutePathBuf::from_absolute_path(temp_dir.path()).expect("absolute root"),
|
||||
scope,
|
||||
access,
|
||||
)
|
||||
}
|
||||
|
||||
struct PluginSkillFixture {
|
||||
root: TempDir,
|
||||
plugin_root: AbsolutePathBuf,
|
||||
skill_path: AbsolutePathBuf,
|
||||
access: FileSystemEnvironmentAccessor<'static>,
|
||||
}
|
||||
|
||||
impl PluginSkillFixture {
|
||||
fn new() -> Self {
|
||||
let root = TempDir::new().expect("temp dir");
|
||||
let plugin_root = AbsolutePathBuf::from_absolute_path(
|
||||
fs::canonicalize(root.path()).expect("canonical plugin root"),
|
||||
)
|
||||
.expect("absolute plugin root");
|
||||
let skill_path = write_skill(
|
||||
&root,
|
||||
"skills/send-message",
|
||||
"name: send-message\ndescription: Send messages",
|
||||
);
|
||||
Self {
|
||||
root,
|
||||
plugin_root,
|
||||
skill_path,
|
||||
access: FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS),
|
||||
}
|
||||
}
|
||||
|
||||
fn write_asset(&self, relative_path: &str) {
|
||||
let asset_path = self.root.path().join(relative_path);
|
||||
fs::create_dir_all(asset_path.parent().expect("asset parent"))
|
||||
.expect("create asset directory");
|
||||
fs::write(asset_path, "<svg/>").expect("write asset");
|
||||
}
|
||||
|
||||
fn write_metadata(&self, contents: &str) {
|
||||
write_metadata(&self.root, "skills/send-message", contents);
|
||||
}
|
||||
|
||||
fn host_root(&self) -> HostSkillRoot<'_> {
|
||||
HostSkillRoot::plugin(
|
||||
PluginSkillRoot {
|
||||
path: self.plugin_root.join("skills"),
|
||||
plugin_identity: PluginIdentity {
|
||||
plugin_id: "fixture@test".to_string(),
|
||||
remote_plugin_id: None,
|
||||
},
|
||||
plugin_namespace: "plugin".to_string(),
|
||||
plugin_root: self.plugin_root.clone(),
|
||||
discovery_mode: SkillDiscoveryMode::Recursive,
|
||||
},
|
||||
&self.access,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn loads_host_frontmatter_dependencies_and_policy() {
|
||||
let access = FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS);
|
||||
let root = TempDir::new().expect("temp dir");
|
||||
let skill_path = write_skill(
|
||||
&root,
|
||||
"demo",
|
||||
"name: demo\ndescription: Demo skill\nmetadata:\n short-description: Short demo",
|
||||
);
|
||||
write_metadata(
|
||||
&root,
|
||||
"demo",
|
||||
r##"dependencies:
|
||||
tools:
|
||||
- type: mcp
|
||||
value: demo-tool
|
||||
description: Demo tool
|
||||
oauth:
|
||||
callbackPort: 3118
|
||||
policy:
|
||||
allow_implicit_invocation: false
|
||||
products: [codex, CHATGPT, atlas]
|
||||
"##,
|
||||
);
|
||||
|
||||
let snapshot = load_host_skill_root(root_for(&root, SkillScope::User, &access)).await;
|
||||
|
||||
assert_eq!(snapshot.errors, Vec::new());
|
||||
assert_eq!(
|
||||
snapshot.skills,
|
||||
vec![SkillMetadata {
|
||||
name: "demo".to_string(),
|
||||
description: "Demo skill".to_string(),
|
||||
short_description: Some("Short demo".to_string()),
|
||||
interface: None,
|
||||
dependencies: Some(SkillDependencies {
|
||||
tools: vec![SkillToolDependency {
|
||||
r#type: "mcp".to_string(),
|
||||
value: "demo-tool".to_string(),
|
||||
description: Some("Demo tool".to_string()),
|
||||
transport: None,
|
||||
command: None,
|
||||
url: None,
|
||||
oauth_callback_port: Some(3118),
|
||||
}],
|
||||
}),
|
||||
policy: Some(SkillPolicy {
|
||||
allow_implicit_invocation: Some(false),
|
||||
products: vec![Product::Codex, Product::Chatgpt, Product::Atlas],
|
||||
}),
|
||||
path_to_skills_md: PathUri::from_abs_path(&skill_path),
|
||||
scope: SkillScope::User,
|
||||
plugin_id: None,
|
||||
remote_plugin_id: None,
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn invalid_optional_metadata_fails_open() {
|
||||
let access = FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS);
|
||||
let root = TempDir::new().expect("temp dir");
|
||||
let skill_path = write_skill(&root, "demo", "name: demo\ndescription: Demo skill");
|
||||
write_metadata(&root, "demo", "interface: [not-an-interface]");
|
||||
|
||||
let snapshot = load_host_skill_root(root_for(&root, SkillScope::Repo, &access)).await;
|
||||
|
||||
assert_eq!(snapshot.errors, Vec::new());
|
||||
assert_eq!(
|
||||
snapshot.skills,
|
||||
vec![SkillMetadata {
|
||||
name: "demo".to_string(),
|
||||
description: "Demo skill".to_string(),
|
||||
short_description: None,
|
||||
interface: None,
|
||||
dependencies: None,
|
||||
policy: None,
|
||||
path_to_skills_md: PathUri::from_abs_path(&skill_path),
|
||||
scope: SkillScope::Repo,
|
||||
plugin_id: None,
|
||||
remote_plugin_id: None,
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn loads_host_interface_metadata_and_local_asset_paths() {
|
||||
let access = FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS);
|
||||
let root = TempDir::new().expect("temp dir");
|
||||
let skill_path = write_skill(&root, "demo", "name: demo\ndescription: Demo skill");
|
||||
fs::create_dir_all(root.path().join("demo/assets")).expect("create assets");
|
||||
write_metadata(
|
||||
&root,
|
||||
"demo",
|
||||
r##"interface:
|
||||
display_name: Demo
|
||||
short_description: Interface summary
|
||||
icon_small: assets/icon.svg
|
||||
icon_large: assets/icon-large.png
|
||||
brand_color: "#123ABC"
|
||||
default_prompt: Run the demo
|
||||
"##,
|
||||
);
|
||||
|
||||
let snapshot = load_host_skill_root(root_for(&root, SkillScope::User, &access)).await;
|
||||
let skill_dir = skill_path.parent().expect("skill parent");
|
||||
|
||||
assert_eq!(snapshot.errors, Vec::new());
|
||||
assert_eq!(
|
||||
snapshot.skills,
|
||||
vec![SkillMetadata {
|
||||
name: "demo".to_string(),
|
||||
description: "Demo skill".to_string(),
|
||||
short_description: None,
|
||||
interface: Some(SkillInterface {
|
||||
display_name: Some("Demo".to_string()),
|
||||
short_description: Some("Interface summary".to_string()),
|
||||
icon_small: Some(skill_dir.join("assets/icon.svg")),
|
||||
icon_large: Some(skill_dir.join("assets/icon-large.png")),
|
||||
brand_color: Some("#123ABC".to_string()),
|
||||
default_prompt: Some("Run the demo".to_string()),
|
||||
}),
|
||||
dependencies: None,
|
||||
policy: None,
|
||||
path_to_skills_md: PathUri::from_abs_path(&skill_path),
|
||||
scope: SkillScope::User,
|
||||
plugin_id: None,
|
||||
remote_plugin_id: None,
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn loads_plugin_skill_interface_icons_from_local_and_shared_assets() {
|
||||
let fixture = PluginSkillFixture::new();
|
||||
fixture.write_asset("skills/send-message/assets/icon.svg");
|
||||
fixture.write_asset("assets/logo.svg");
|
||||
fixture.write_metadata(
|
||||
r#"interface:
|
||||
icon_small: "assets/icon.svg"
|
||||
icon_large: "../../assets/logo.svg"
|
||||
"#,
|
||||
);
|
||||
|
||||
let snapshot = load_host_skill_root(fixture.host_root()).await;
|
||||
|
||||
assert_eq!(snapshot.errors, Vec::new());
|
||||
assert_eq!(
|
||||
snapshot.skills,
|
||||
vec![SkillMetadata {
|
||||
name: "plugin:send-message".to_string(),
|
||||
description: "Send messages".to_string(),
|
||||
short_description: None,
|
||||
interface: Some(SkillInterface {
|
||||
display_name: None,
|
||||
short_description: None,
|
||||
icon_small: Some(
|
||||
fixture
|
||||
.plugin_root
|
||||
.join("skills/send-message/assets/icon.svg"),
|
||||
),
|
||||
icon_large: Some(fixture.plugin_root.join("assets/logo.svg")),
|
||||
brand_color: None,
|
||||
default_prompt: None,
|
||||
}),
|
||||
dependencies: None,
|
||||
policy: None,
|
||||
path_to_skills_md: PathUri::from_abs_path(&fixture.skill_path),
|
||||
scope: SkillScope::User,
|
||||
plugin_id: Some("fixture@test".to_string()),
|
||||
remote_plugin_id: None,
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_plugin_skill_interface_icons_outside_shared_assets() {
|
||||
let fixture = PluginSkillFixture::new();
|
||||
fixture.write_asset("other/icon.svg");
|
||||
fixture.write_metadata(
|
||||
r#"interface:
|
||||
display_name: Send Message
|
||||
icon_small: "../../other/icon.svg"
|
||||
"#,
|
||||
);
|
||||
|
||||
let snapshot = load_host_skill_root(fixture.host_root()).await;
|
||||
|
||||
assert_eq!(snapshot.errors, Vec::new());
|
||||
assert_eq!(
|
||||
snapshot.skills,
|
||||
vec![SkillMetadata {
|
||||
name: "plugin:send-message".to_string(),
|
||||
description: "Send messages".to_string(),
|
||||
short_description: None,
|
||||
interface: Some(SkillInterface {
|
||||
display_name: Some("Send Message".to_string()),
|
||||
short_description: None,
|
||||
icon_small: None,
|
||||
icon_large: None,
|
||||
brand_color: None,
|
||||
default_prompt: None,
|
||||
}),
|
||||
dependencies: None,
|
||||
policy: None,
|
||||
path_to_skills_md: PathUri::from_abs_path(&fixture.skill_path),
|
||||
scope: SkillScope::User,
|
||||
plugin_id: Some("fixture@test".to_string()),
|
||||
remote_plugin_id: None,
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_interface_fields_that_escape_or_fail_validation() {
|
||||
let access = FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS);
|
||||
let root = TempDir::new().expect("temp dir");
|
||||
let skill_path = write_skill(&root, "demo", "name: demo\ndescription: Demo skill");
|
||||
write_metadata(
|
||||
&root,
|
||||
"demo",
|
||||
"interface:\n icon_small: ../outside.svg\n brand_color: blue\n",
|
||||
);
|
||||
|
||||
let snapshot = load_host_skill_root(root_for(&root, SkillScope::User, &access)).await;
|
||||
|
||||
assert_eq!(snapshot.errors, Vec::new());
|
||||
assert_eq!(
|
||||
snapshot.skills,
|
||||
vec![SkillMetadata {
|
||||
name: "demo".to_string(),
|
||||
description: "Demo skill".to_string(),
|
||||
short_description: None,
|
||||
interface: None,
|
||||
dependencies: None,
|
||||
policy: None,
|
||||
path_to_skills_md: PathUri::from_abs_path(&skill_path),
|
||||
scope: SkillScope::User,
|
||||
plugin_id: None,
|
||||
remote_plugin_id: None,
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn skips_hidden_host_skills() {
|
||||
let access = FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS);
|
||||
let root = TempDir::new().expect("temp dir");
|
||||
let visible_path = write_skill(
|
||||
&root,
|
||||
"visible",
|
||||
"name: visible\ndescription: Visible skill",
|
||||
);
|
||||
write_skill(&root, ".hidden", "name: hidden\ndescription: Hidden skill");
|
||||
|
||||
let snapshot = load_host_skill_root(root_for(&root, SkillScope::User, &access)).await;
|
||||
|
||||
assert_eq!(snapshot.errors, Vec::new());
|
||||
assert_eq!(snapshot.skills.len(), 1);
|
||||
assert_eq!(
|
||||
snapshot.skills[0].path_to_skills_md,
|
||||
PathUri::from_abs_path(&visible_path)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn discovers_nested_plugin_namespace_without_plugin_identity() {
|
||||
let access = FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS);
|
||||
let root = TempDir::new().expect("temp dir");
|
||||
let plugin_manifest = root.path().join("nested/.codex-plugin/plugin.json");
|
||||
fs::create_dir_all(plugin_manifest.parent().expect("plugin manifest parent"))
|
||||
.expect("create plugin manifest directory");
|
||||
fs::write(&plugin_manifest, r#"{"name":"plugin-name"}"#).expect("write plugin manifest");
|
||||
let skill_path = write_skill(
|
||||
&root,
|
||||
"nested/skills/demo",
|
||||
"name: demo\ndescription: Demo skill",
|
||||
);
|
||||
|
||||
let snapshot = load_host_skill_root(root_for(&root, SkillScope::User, &access)).await;
|
||||
|
||||
assert_eq!(snapshot.errors, Vec::new());
|
||||
assert_eq!(
|
||||
snapshot.skills,
|
||||
vec![SkillMetadata {
|
||||
name: "plugin-name:demo".to_string(),
|
||||
description: "Demo skill".to_string(),
|
||||
short_description: None,
|
||||
interface: None,
|
||||
dependencies: None,
|
||||
policy: None,
|
||||
path_to_skills_md: PathUri::from_abs_path(&skill_path),
|
||||
scope: SkillScope::User,
|
||||
plugin_id: None,
|
||||
remote_plugin_id: None,
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn plugin_root_accepts_maximum_length_qualified_skill_name() {
|
||||
let access = FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS);
|
||||
let root = TempDir::new().expect("temp dir");
|
||||
let plugin_namespace = "p".repeat(MAX_NAME_LEN);
|
||||
let skill_name = "s".repeat(MAX_NAME_LEN);
|
||||
let skill_path = write_skill(
|
||||
&root,
|
||||
"skills/search",
|
||||
&format!("name: {skill_name}\ndescription: Search skill"),
|
||||
);
|
||||
let plugin_root = AbsolutePathBuf::from_absolute_path(root.path()).expect("plugin root");
|
||||
|
||||
let snapshot = load_host_skill_root(HostSkillRoot::plugin(
|
||||
PluginSkillRoot {
|
||||
path: plugin_root.join("skills"),
|
||||
plugin_identity: PluginIdentity {
|
||||
plugin_id: "demo@test".to_string(),
|
||||
remote_plugin_id: None,
|
||||
},
|
||||
plugin_namespace: plugin_namespace.clone(),
|
||||
plugin_root,
|
||||
discovery_mode: SkillDiscoveryMode::Recursive,
|
||||
},
|
||||
&access,
|
||||
))
|
||||
.await;
|
||||
|
||||
assert_eq!(snapshot.errors, Vec::new());
|
||||
assert_eq!(
|
||||
snapshot.skills,
|
||||
vec![SkillMetadata {
|
||||
name: format!("{plugin_namespace}:{skill_name}"),
|
||||
description: "Search skill".to_string(),
|
||||
short_description: None,
|
||||
interface: None,
|
||||
dependencies: None,
|
||||
policy: None,
|
||||
path_to_skills_md: PathUri::from_abs_path(&skill_path),
|
||||
scope: SkillScope::User,
|
||||
plugin_id: Some("demo@test".to_string()),
|
||||
remote_plugin_id: None,
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn plugin_root_rejects_overlong_qualified_skill_name() {
|
||||
let access = FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS);
|
||||
let root = TempDir::new().expect("temp dir");
|
||||
let skill_name = "s".repeat(MAX_NAME_LEN);
|
||||
write_skill(
|
||||
&root,
|
||||
"skills/search",
|
||||
&format!("name: {skill_name}\ndescription: Search skill"),
|
||||
);
|
||||
let plugin_root = AbsolutePathBuf::from_absolute_path(root.path()).expect("plugin root");
|
||||
|
||||
let snapshot = load_host_skill_root(HostSkillRoot::plugin(
|
||||
PluginSkillRoot {
|
||||
path: plugin_root.join("skills"),
|
||||
plugin_identity: PluginIdentity {
|
||||
plugin_id: "demo@test".to_string(),
|
||||
remote_plugin_id: None,
|
||||
},
|
||||
plugin_namespace: "p".repeat(MAX_NAME_LEN + 1),
|
||||
plugin_root,
|
||||
discovery_mode: SkillDiscoveryMode::Recursive,
|
||||
},
|
||||
&access,
|
||||
))
|
||||
.await;
|
||||
|
||||
assert_eq!(snapshot.skills, Vec::new());
|
||||
assert_eq!(snapshot.errors.len(), 1);
|
||||
assert!(
|
||||
snapshot.errors[0]
|
||||
.message
|
||||
.contains("invalid qualified name")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn recursive_plugin_root_preserves_owner_namespace_and_shared_asset_policy() {
|
||||
let access = FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS);
|
||||
let root = TempDir::new().expect("temp dir");
|
||||
let skill_path = write_skill(
|
||||
&root,
|
||||
"skills/group/demo",
|
||||
"name: demo\ndescription: Demo skill",
|
||||
);
|
||||
let nested_manifest = root.path().join("skills/group/.codex-plugin/plugin.json");
|
||||
fs::create_dir_all(nested_manifest.parent().expect("nested manifest parent"))
|
||||
.expect("create nested plugin manifest directory");
|
||||
fs::write(nested_manifest, r#"{"name":"conflicting-plugin"}"#)
|
||||
.expect("write nested plugin manifest");
|
||||
write_metadata(
|
||||
&root,
|
||||
"skills/group/demo",
|
||||
"interface:\n icon_small: ../../../assets/logo.svg\n",
|
||||
);
|
||||
fs::create_dir_all(root.path().join("assets")).expect("create assets directory");
|
||||
fs::write(root.path().join("assets/logo.svg"), "<svg/>").expect("write asset");
|
||||
let plugin_root = AbsolutePathBuf::from_absolute_path(root.path()).expect("plugin root");
|
||||
let canonical_plugin_root = AbsolutePathBuf::from_absolute_path(
|
||||
fs::canonicalize(root.path()).expect("canonicalize plugin root"),
|
||||
)
|
||||
.expect("canonical plugin root");
|
||||
|
||||
let snapshot = load_host_skill_root(HostSkillRoot::plugin(
|
||||
PluginSkillRoot {
|
||||
path: plugin_root.join("skills"),
|
||||
plugin_identity: PluginIdentity {
|
||||
plugin_id: "demo@test".to_string(),
|
||||
remote_plugin_id: Some("remote-demo".to_string()),
|
||||
},
|
||||
plugin_namespace: "plugin".to_string(),
|
||||
plugin_root,
|
||||
discovery_mode: SkillDiscoveryMode::Recursive,
|
||||
},
|
||||
&access,
|
||||
))
|
||||
.await;
|
||||
|
||||
assert_eq!(snapshot.errors, Vec::new());
|
||||
assert_eq!(
|
||||
snapshot.skills,
|
||||
vec![SkillMetadata {
|
||||
name: "plugin:demo".to_string(),
|
||||
description: "Demo skill".to_string(),
|
||||
short_description: None,
|
||||
interface: Some(SkillInterface {
|
||||
display_name: None,
|
||||
short_description: None,
|
||||
icon_small: Some(canonical_plugin_root.join("assets/logo.svg")),
|
||||
icon_large: None,
|
||||
brand_color: None,
|
||||
default_prompt: None,
|
||||
}),
|
||||
dependencies: None,
|
||||
policy: None,
|
||||
path_to_skills_md: PathUri::from_abs_path(&skill_path),
|
||||
scope: SkillScope::User,
|
||||
plugin_id: Some("demo@test".to_string()),
|
||||
remote_plugin_id: Some("remote-demo".to_string()),
|
||||
}]
|
||||
);
|
||||
assert_eq!(
|
||||
snapshot
|
||||
.skill_discovery_path_by_path
|
||||
.get(&PathUri::from_abs_path(&skill_path)),
|
||||
Some(&PathUri::from_abs_path(&skill_path))
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn direct_child_plugin_root_ignores_nested_skills() {
|
||||
let access = FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS);
|
||||
let root = TempDir::new().expect("temp dir");
|
||||
let direct_path = write_skill(
|
||||
&root,
|
||||
"skills/direct",
|
||||
"name: direct\ndescription: Direct skill",
|
||||
);
|
||||
write_skill(
|
||||
&root,
|
||||
"skills/nested/too-deep",
|
||||
"name: nested\ndescription: Nested skill",
|
||||
);
|
||||
let plugin_root = AbsolutePathBuf::from_absolute_path(root.path()).expect("plugin root");
|
||||
|
||||
let snapshot = load_host_skill_root(HostSkillRoot::plugin(
|
||||
PluginSkillRoot {
|
||||
path: plugin_root.join("skills"),
|
||||
plugin_identity: PluginIdentity {
|
||||
plugin_id: "demo@test".to_string(),
|
||||
remote_plugin_id: None,
|
||||
},
|
||||
plugin_namespace: "plugin".to_string(),
|
||||
plugin_root,
|
||||
discovery_mode: SkillDiscoveryMode::DirectChildren,
|
||||
},
|
||||
&access,
|
||||
))
|
||||
.await;
|
||||
|
||||
assert_eq!(snapshot.errors, Vec::new());
|
||||
assert_eq!(
|
||||
snapshot.skills,
|
||||
vec![SkillMetadata {
|
||||
name: "plugin:direct".to_string(),
|
||||
description: "Direct skill".to_string(),
|
||||
short_description: None,
|
||||
interface: None,
|
||||
dependencies: None,
|
||||
policy: None,
|
||||
path_to_skills_md: PathUri::from_abs_path(&direct_path),
|
||||
scope: SkillScope::User,
|
||||
plugin_id: Some("demo@test".to_string()),
|
||||
remote_plugin_id: None,
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn direct_child_plugin_root_skips_skills_resolving_outside_plugin_root() {
|
||||
let access = FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS);
|
||||
let root = TempDir::new().expect("temp dir");
|
||||
let outside_root = TempDir::new().expect("outside temp dir");
|
||||
write_skill(
|
||||
&outside_root,
|
||||
"escaped",
|
||||
"name: escaped\ndescription: Escaped skill",
|
||||
);
|
||||
fs::create_dir_all(root.path().join("skills")).expect("create skills root");
|
||||
std::os::unix::fs::symlink(
|
||||
outside_root.path().join("escaped"),
|
||||
root.path().join("skills/escaped"),
|
||||
)
|
||||
.expect("create skill symlink");
|
||||
let plugin_root = AbsolutePathBuf::from_absolute_path(root.path()).expect("plugin root");
|
||||
|
||||
let snapshot = load_host_skill_root(HostSkillRoot::plugin(
|
||||
PluginSkillRoot {
|
||||
path: plugin_root.join("skills"),
|
||||
plugin_identity: PluginIdentity {
|
||||
plugin_id: "demo@test".to_string(),
|
||||
remote_plugin_id: None,
|
||||
},
|
||||
plugin_namespace: "plugin".to_string(),
|
||||
plugin_root,
|
||||
discovery_mode: SkillDiscoveryMode::DirectChildren,
|
||||
},
|
||||
&access,
|
||||
))
|
||||
.await;
|
||||
|
||||
assert_eq!(snapshot.errors, Vec::new());
|
||||
assert_eq!(snapshot.skills, Vec::new());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn recursive_plugin_root_preserves_symlinked_skill_discovery_path() {
|
||||
let access = FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS);
|
||||
let root = TempDir::new().expect("temp dir");
|
||||
let target = TempDir::new().expect("target temp dir");
|
||||
let target_skill = write_skill(&target, "demo", "name: demo\ndescription: Symlinked skill");
|
||||
fs::create_dir_all(root.path().join("skills")).expect("create skills root");
|
||||
std::os::unix::fs::symlink(target.path().join("demo"), root.path().join("skills/alias"))
|
||||
.expect("create skill symlink");
|
||||
let plugin_root = AbsolutePathBuf::from_absolute_path(root.path()).expect("plugin root");
|
||||
|
||||
let snapshot = load_host_skill_root(HostSkillRoot::plugin(
|
||||
PluginSkillRoot {
|
||||
path: plugin_root.join("skills"),
|
||||
plugin_identity: PluginIdentity {
|
||||
plugin_id: "demo@test".to_string(),
|
||||
remote_plugin_id: None,
|
||||
},
|
||||
plugin_namespace: "plugin".to_string(),
|
||||
plugin_root,
|
||||
discovery_mode: SkillDiscoveryMode::Recursive,
|
||||
},
|
||||
&access,
|
||||
))
|
||||
.await;
|
||||
|
||||
assert_eq!(snapshot.errors, Vec::new());
|
||||
assert_eq!(
|
||||
snapshot.skills,
|
||||
vec![SkillMetadata {
|
||||
name: "plugin:demo".to_string(),
|
||||
description: "Symlinked skill".to_string(),
|
||||
short_description: None,
|
||||
interface: None,
|
||||
dependencies: None,
|
||||
policy: None,
|
||||
path_to_skills_md: PathUri::from_abs_path(&target_skill),
|
||||
scope: SkillScope::User,
|
||||
plugin_id: Some("demo@test".to_string()),
|
||||
remote_plugin_id: None,
|
||||
}]
|
||||
);
|
||||
assert_eq!(
|
||||
snapshot
|
||||
.skill_discovery_path_by_path
|
||||
.get(&PathUri::from_abs_path(&target_skill)),
|
||||
Some(&PathUri::from_abs_path(
|
||||
&snapshot.root.join("alias/SKILL.md")
|
||||
))
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn follows_directory_symlinks_except_for_system_scope() {
|
||||
let access = FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS);
|
||||
use std::os::unix::fs::symlink;
|
||||
|
||||
let root = TempDir::new().expect("temp dir");
|
||||
let target = TempDir::new().expect("target temp dir");
|
||||
let target_skill = write_skill(&target, "demo", "name: demo\ndescription: Symlinked skill");
|
||||
symlink(target.path().join("demo"), root.path().join("alias")).expect("create symlink");
|
||||
|
||||
for scope in [SkillScope::User, SkillScope::Repo, SkillScope::Admin] {
|
||||
let snapshot = load_host_skill_root(root_for(&root, scope, &access)).await;
|
||||
|
||||
assert_eq!(snapshot.errors, Vec::new());
|
||||
assert_eq!(snapshot.skills.len(), 1);
|
||||
assert_eq!(
|
||||
(
|
||||
&snapshot.skills[0].path_to_skills_md,
|
||||
snapshot.skills[0].scope
|
||||
),
|
||||
(&PathUri::from_abs_path(&target_skill), scope)
|
||||
);
|
||||
assert_eq!(
|
||||
snapshot
|
||||
.skill_discovery_path_by_path
|
||||
.get(&PathUri::from_abs_path(&target_skill)),
|
||||
Some(&PathUri::from_abs_path(
|
||||
&snapshot.root.join("alias/SKILL.md")
|
||||
))
|
||||
);
|
||||
}
|
||||
|
||||
let system_snapshot = load_host_skill_root(root_for(&root, SkillScope::System, &access)).await;
|
||||
assert_eq!(system_snapshot.errors, Vec::new());
|
||||
assert_eq!(system_snapshot.skills, Vec::new());
|
||||
}
|
||||
220
codex-rs/ext/skills/src/loader/io_test_support.rs
Normal file
220
codex-rs/ext/skills/src/loader/io_test_support.rs
Normal file
@@ -0,0 +1,220 @@
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
use codex_exec_server::CopyOptions;
|
||||
use codex_exec_server::CreateDirectoryOptions;
|
||||
use codex_exec_server::ExecutorFileSystem;
|
||||
use codex_exec_server::ExecutorFileSystemFuture;
|
||||
use codex_exec_server::FileMetadata;
|
||||
use codex_exec_server::FileSystemReadStream;
|
||||
use codex_exec_server::FileSystemSandboxContext;
|
||||
use codex_exec_server::GetMetadataOptions;
|
||||
use codex_exec_server::ReadDirectoryEntry;
|
||||
use codex_exec_server::ReadFileOptions;
|
||||
use codex_exec_server::RemoveOptions;
|
||||
use codex_exec_server::WalkOptions;
|
||||
use codex_exec_server::WalkOutcome;
|
||||
use codex_exec_server::WriteFileOptions;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use tokio::sync::Notify;
|
||||
use tokio::sync::Semaphore;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) enum ManifestMetadataBehavior {
|
||||
Immediate,
|
||||
WaitForSkillRead,
|
||||
}
|
||||
|
||||
pub(super) struct RecordingFileSystem<'a> {
|
||||
inner: &'a dyn ExecutorFileSystem,
|
||||
read_files: Mutex<Vec<PathUri>>,
|
||||
metadata_files: Mutex<Vec<PathUri>>,
|
||||
pub(super) walks: AtomicUsize,
|
||||
manifest_metadata_behavior: ManifestMetadataBehavior,
|
||||
skill_read_started: AtomicBool,
|
||||
skill_read_started_notify: Notify,
|
||||
pub(super) blocked_walk_root: Option<PathUri>,
|
||||
pub(super) blocked_walk_gate: Semaphore,
|
||||
pub(super) walk_started: Notify,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub(super) struct FileSystemCalls {
|
||||
pub(super) walks: usize,
|
||||
pub(super) read_files: Vec<PathUri>,
|
||||
pub(super) metadata_files: Vec<PathUri>,
|
||||
}
|
||||
|
||||
impl<'a> RecordingFileSystem<'a> {
|
||||
pub(super) fn new(
|
||||
inner: &'a dyn ExecutorFileSystem,
|
||||
manifest_metadata_behavior: ManifestMetadataBehavior,
|
||||
) -> Self {
|
||||
Self {
|
||||
inner,
|
||||
read_files: Mutex::new(Vec::new()),
|
||||
metadata_files: Mutex::new(Vec::new()),
|
||||
walks: AtomicUsize::new(/*v*/ 0),
|
||||
manifest_metadata_behavior,
|
||||
skill_read_started: AtomicBool::new(/*v*/ false),
|
||||
skill_read_started_notify: Notify::new(),
|
||||
blocked_walk_root: None,
|
||||
blocked_walk_gate: Semaphore::new(/*permits*/ 0),
|
||||
walk_started: Notify::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn calls(&self) -> FileSystemCalls {
|
||||
let mut read_files = self
|
||||
.read_files
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.clone();
|
||||
read_files.sort_by_key(ToString::to_string);
|
||||
let mut metadata_files = self
|
||||
.metadata_files
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.clone();
|
||||
metadata_files.sort_by_key(ToString::to_string);
|
||||
FileSystemCalls {
|
||||
walks: self.walks.load(Ordering::Relaxed),
|
||||
read_files,
|
||||
metadata_files,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ExecutorFileSystem for RecordingFileSystem<'_> {
|
||||
fn canonicalize<'a>(
|
||||
&'a self,
|
||||
path: &'a PathUri,
|
||||
sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, PathUri> {
|
||||
self.inner.canonicalize(path, sandbox)
|
||||
}
|
||||
|
||||
fn read_file<'a>(
|
||||
&'a self,
|
||||
path: &'a PathUri,
|
||||
options: ReadFileOptions,
|
||||
sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, Vec<u8>> {
|
||||
self.read_files
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.push(path.clone());
|
||||
if path.basename().as_deref() == Some("SKILL.md") {
|
||||
self.skill_read_started.store(true, Ordering::Release);
|
||||
self.skill_read_started_notify.notify_waiters();
|
||||
}
|
||||
self.inner.read_file(path, options, sandbox)
|
||||
}
|
||||
|
||||
fn read_file_stream<'a>(
|
||||
&'a self,
|
||||
path: &'a PathUri,
|
||||
sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, FileSystemReadStream> {
|
||||
self.inner.read_file_stream(path, sandbox)
|
||||
}
|
||||
|
||||
fn write_file<'a>(
|
||||
&'a self,
|
||||
path: &'a PathUri,
|
||||
contents: Vec<u8>,
|
||||
options: WriteFileOptions,
|
||||
sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, ()> {
|
||||
self.inner.write_file(path, contents, options, sandbox)
|
||||
}
|
||||
|
||||
fn create_directory<'a>(
|
||||
&'a self,
|
||||
path: &'a PathUri,
|
||||
options: CreateDirectoryOptions,
|
||||
sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, ()> {
|
||||
self.inner.create_directory(path, options, sandbox)
|
||||
}
|
||||
|
||||
fn get_metadata<'a>(
|
||||
&'a self,
|
||||
path: &'a PathUri,
|
||||
options: GetMetadataOptions,
|
||||
sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, FileMetadata> {
|
||||
self.metadata_files
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.push(path.clone());
|
||||
if matches!(
|
||||
self.manifest_metadata_behavior,
|
||||
ManifestMetadataBehavior::WaitForSkillRead
|
||||
) && path.basename().as_deref() == Some("plugin.json")
|
||||
{
|
||||
return Box::pin(async move {
|
||||
loop {
|
||||
let notified = self.skill_read_started_notify.notified();
|
||||
if self.skill_read_started.load(Ordering::Acquire) {
|
||||
break;
|
||||
}
|
||||
notified.await;
|
||||
}
|
||||
self.inner.get_metadata(path, options, sandbox).await
|
||||
});
|
||||
}
|
||||
self.inner.get_metadata(path, options, sandbox)
|
||||
}
|
||||
|
||||
fn read_directory<'a>(
|
||||
&'a self,
|
||||
path: &'a PathUri,
|
||||
sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, Vec<ReadDirectoryEntry>> {
|
||||
self.inner.read_directory(path, sandbox)
|
||||
}
|
||||
|
||||
fn walk<'a>(
|
||||
&'a self,
|
||||
path: &'a PathUri,
|
||||
options: WalkOptions,
|
||||
sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, WalkOutcome> {
|
||||
self.walks.fetch_add(/*val*/ 1, Ordering::AcqRel);
|
||||
self.walk_started.notify_waiters();
|
||||
if self.blocked_walk_root.as_ref() != Some(path) {
|
||||
return self.inner.walk(path, options, sandbox);
|
||||
}
|
||||
Box::pin(async move {
|
||||
self.blocked_walk_gate
|
||||
.acquire()
|
||||
.await
|
||||
.expect("blocked walk gate should remain open")
|
||||
.forget();
|
||||
self.inner.walk(path, options, sandbox).await
|
||||
})
|
||||
}
|
||||
|
||||
fn remove<'a>(
|
||||
&'a self,
|
||||
path: &'a PathUri,
|
||||
options: RemoveOptions,
|
||||
sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, ()> {
|
||||
self.inner.remove(path, options, sandbox)
|
||||
}
|
||||
|
||||
fn copy<'a>(
|
||||
&'a self,
|
||||
source_path: &'a PathUri,
|
||||
destination_path: &'a PathUri,
|
||||
options: CopyOptions,
|
||||
sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, ()> {
|
||||
self.inner
|
||||
.copy(source_path, destination_path, options, sandbox)
|
||||
}
|
||||
}
|
||||
121
codex-rs/ext/skills/src/loader/metadata.rs
Normal file
121
codex-rs/ext/skills/src/loader/metadata.rs
Normal file
@@ -0,0 +1,121 @@
|
||||
use std::io;
|
||||
|
||||
use codex_exec_server::EnvironmentAccess;
|
||||
use codex_exec_server::EnvironmentAccessExt;
|
||||
use codex_exec_server::GetMetadataOptions;
|
||||
use codex_exec_server::ReadFileOptions;
|
||||
use codex_skills::ParsedSkillMetadata;
|
||||
use codex_skills::SkillDependencies;
|
||||
use codex_skills::SkillInterface;
|
||||
use codex_skills::SkillInterfaceAssetPolicy;
|
||||
use codex_skills::SkillParseError;
|
||||
use codex_skills::SkillPolicy;
|
||||
use codex_skills::parse_skill_metadata;
|
||||
use codex_skills::resolve_skill_interface;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
|
||||
use super::SKILLS_METADATA_FILENAME;
|
||||
use super::discovery::SkillMetadataDiscovery;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct LoadedSkillMetadata {
|
||||
pub(super) interface: Option<SkillInterface>,
|
||||
pub(super) dependencies: Option<SkillDependencies>,
|
||||
pub(super) policy: Option<SkillPolicy>,
|
||||
}
|
||||
|
||||
pub(super) async fn load_host_skill_metadata(
|
||||
file_system: &dyn EnvironmentAccess,
|
||||
skill_path: &AbsolutePathBuf,
|
||||
metadata: &SkillMetadataDiscovery,
|
||||
plugin_root: Option<&AbsolutePathBuf>,
|
||||
) -> LoadedSkillMetadata {
|
||||
// Fail open: optional metadata should not block loading SKILL.md.
|
||||
let Some(skill_dir) = skill_path.parent() else {
|
||||
return LoadedSkillMetadata::default();
|
||||
};
|
||||
let metadata_path = match metadata {
|
||||
SkillMetadataDiscovery::Present(path) => path,
|
||||
SkillMetadataDiscovery::Absent => return LoadedSkillMetadata::default(),
|
||||
SkillMetadataDiscovery::Probe(path) => {
|
||||
match file_system
|
||||
.get_metadata(path, GetMetadataOptions::default())
|
||||
.await
|
||||
{
|
||||
Ok(metadata) if metadata.is_file => {}
|
||||
Ok(_) => return LoadedSkillMetadata::default(),
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => {
|
||||
return LoadedSkillMetadata::default();
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::warn!(
|
||||
"ignoring {path}: failed to stat {label}: {error}",
|
||||
label = SKILLS_METADATA_FILENAME
|
||||
);
|
||||
return LoadedSkillMetadata::default();
|
||||
}
|
||||
}
|
||||
path
|
||||
}
|
||||
};
|
||||
|
||||
let contents = match file_system
|
||||
.read_file_text(metadata_path, ReadFileOptions::default())
|
||||
.await
|
||||
{
|
||||
Ok(contents) => contents,
|
||||
Err(error) => {
|
||||
tracing::warn!(
|
||||
"ignoring {metadata_path}: failed to read {label}: {error}",
|
||||
label = SKILLS_METADATA_FILENAME
|
||||
);
|
||||
return LoadedSkillMetadata::default();
|
||||
}
|
||||
};
|
||||
|
||||
let parsed = match parse_skill_metadata(&contents) {
|
||||
Ok(parsed) => parsed,
|
||||
Err(error) => {
|
||||
tracing::warn!(
|
||||
"ignoring {metadata_path}: invalid {label}: {error}",
|
||||
label = SKILLS_METADATA_FILENAME
|
||||
);
|
||||
return LoadedSkillMetadata::default();
|
||||
}
|
||||
};
|
||||
|
||||
let ParsedSkillMetadata {
|
||||
interface,
|
||||
dependencies,
|
||||
policy,
|
||||
} = parsed;
|
||||
let asset_policy = match plugin_root {
|
||||
Some(plugin_root) => SkillInterfaceAssetPolicy::PluginShared { plugin_root },
|
||||
None => SkillInterfaceAssetPolicy::LocalOnly,
|
||||
};
|
||||
LoadedSkillMetadata {
|
||||
interface: resolve_skill_interface(interface, &skill_dir, asset_policy),
|
||||
dependencies,
|
||||
policy,
|
||||
}
|
||||
}
|
||||
pub(super) fn sanitize_single_line(raw: &str) -> String {
|
||||
raw.split_whitespace().collect::<Vec<_>>().join(" ")
|
||||
}
|
||||
|
||||
pub(super) fn validate_len(
|
||||
value: &str,
|
||||
max_len: usize,
|
||||
field_name: &'static str,
|
||||
) -> Result<(), SkillParseError> {
|
||||
if value.is_empty() {
|
||||
return Err(SkillParseError::MissingField(field_name));
|
||||
}
|
||||
if value.chars().count() > max_len {
|
||||
return Err(SkillParseError::InvalidField {
|
||||
field: field_name,
|
||||
reason: format!("exceeds maximum length of {max_len} characters"),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
27
codex-rs/ext/skills/src/loader/mod.rs
Normal file
27
codex-rs/ext/skills/src/loader/mod.rs
Normal file
@@ -0,0 +1,27 @@
|
||||
mod discovery;
|
||||
mod environment;
|
||||
mod host;
|
||||
mod host_merge;
|
||||
#[cfg(test)]
|
||||
mod io_test_support;
|
||||
mod metadata;
|
||||
mod namespace;
|
||||
|
||||
pub(crate) use environment::load_environment_skills_from_discovery;
|
||||
pub(crate) use environment::load_environment_skills_from_root;
|
||||
pub(crate) use host::HostSkillRoot;
|
||||
pub(crate) use host::HostSkillRootSnapshot;
|
||||
pub(crate) use host::canonicalize_for_skill_identity;
|
||||
pub(crate) use host::load_host_skill_root;
|
||||
pub(crate) use host_merge::load_and_merge_host_skill_roots;
|
||||
pub(crate) use host_merge::load_and_merge_host_skill_roots_with_request_snapshots;
|
||||
|
||||
pub(crate) const MAX_CONCURRENT_ROOT_SCANS: usize = 8;
|
||||
pub(crate) use discovery::MAX_CONCURRENT_SKILL_LOADS;
|
||||
pub(super) const SKILLS_FILENAME: &str = "SKILL.md";
|
||||
pub(super) const SKILLS_METADATA_DIR: &str = "agents";
|
||||
pub(super) const SKILLS_METADATA_FILENAME: &str = "openai.yaml";
|
||||
pub(super) const MAX_NAME_LEN: usize = 64;
|
||||
pub(super) const MAX_QUALIFIED_NAME_LEN: usize = MAX_NAME_LEN * 2 + 1;
|
||||
pub(super) const MAX_SCAN_DEPTH: usize = 6;
|
||||
pub(super) const MAX_SKILLS_DIRS_PER_ROOT: usize = 2000;
|
||||
186
codex-rs/ext/skills/src/loader/namespace.rs
Normal file
186
codex-rs/ext/skills/src/loader/namespace.rs
Normal file
@@ -0,0 +1,186 @@
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
|
||||
use codex_exec_server::EnvironmentAccess;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use codex_utils_plugins::plugin_namespace_for_root_uri;
|
||||
use futures::StreamExt;
|
||||
|
||||
use super::discovery::MAX_CONCURRENT_SKILL_LOADS;
|
||||
|
||||
/// Resolves the namespace prefix applied to skill names during one skills scan.
|
||||
///
|
||||
/// A plugin namespace is the plugin name from the nearest valid plugin manifest
|
||||
/// above a skill path. For example, a skill named `search` beneath a plugin named
|
||||
/// `sample` is exposed as `sample:search`.
|
||||
///
|
||||
/// Resolving the namespace separately for every `SKILL.md` repeats the same
|
||||
/// ancestor manifest probes for sibling skills. This resolver resolves relevant
|
||||
/// roots once per scan, then selects the nearest matching root for each skill.
|
||||
///
|
||||
/// Namespace precedence is:
|
||||
///
|
||||
/// 1. the deepest matching canonical symlink root or nested plugin root;
|
||||
/// 2. the namespace inherited from the scanned skills root.
|
||||
pub(crate) struct SkillNamespaceResolver {
|
||||
inherited_namespace: ResolvedSkillNamespace,
|
||||
nested_namespaces: Vec<(PathUri, ResolvedSkillNamespace)>,
|
||||
}
|
||||
|
||||
impl SkillNamespaceResolver {
|
||||
/// Uses the authoritative namespace supplied by an owning plugin.
|
||||
pub(crate) fn with_provided_namespace(namespace: &str) -> Self {
|
||||
Self {
|
||||
inherited_namespace: ResolvedSkillNamespace::Plugin(namespace.to_string()),
|
||||
nested_namespaces: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn discover(
|
||||
fs: &dyn EnvironmentAccess,
|
||||
root: &PathUri,
|
||||
skill_paths: &[PathUri],
|
||||
plugin_roots: HashSet<PathUri>,
|
||||
namespace_roots: HashSet<PathUri>,
|
||||
) -> Self {
|
||||
// Only probe plugin roots above loaded skills; unused siblings cannot affect names.
|
||||
let mut skill_ancestors = HashSet::new();
|
||||
for skill_path in skill_paths {
|
||||
let mut ancestor = skill_path.parent();
|
||||
while let Some(path) = ancestor {
|
||||
skill_ancestors.insert(path.clone());
|
||||
ancestor = path.parent();
|
||||
}
|
||||
}
|
||||
let plugin_roots = plugin_roots
|
||||
.into_iter()
|
||||
.filter(|plugin_root| skill_ancestors.contains(plugin_root))
|
||||
.collect::<HashSet<_>>();
|
||||
|
||||
// The scan root is already the fallback above if nothing else matches, exclude from the search.
|
||||
let namespace_roots = namespace_roots
|
||||
.into_iter()
|
||||
.filter(|namespace_root| namespace_root != root)
|
||||
.collect::<Vec<_>>();
|
||||
let namespace_root_set = namespace_roots.iter().cloned().collect::<HashSet<_>>();
|
||||
let plugin_roots = plugin_roots
|
||||
.into_iter()
|
||||
.filter(|plugin_root| plugin_root != root && !namespace_root_set.contains(plugin_root))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let lookup_roots = std::iter::once(root.clone())
|
||||
.chain(namespace_roots.iter().cloned())
|
||||
.collect::<Vec<_>>();
|
||||
let mut pending_lookups = lookup_roots
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(|lookup_root| (lookup_root.clone(), lookup_root))
|
||||
.collect::<Vec<_>>();
|
||||
let mut direct_plugin_roots = plugin_roots.iter().cloned().collect::<HashSet<_>>();
|
||||
let mut namespaces_by_root = HashMap::new();
|
||||
let mut namespaces_by_lookup_root = HashMap::new();
|
||||
while !pending_lookups.is_empty() {
|
||||
let probe_roots = pending_lookups
|
||||
.iter()
|
||||
.map(|(_, ancestor)| ancestor.clone())
|
||||
.chain(direct_plugin_roots.drain())
|
||||
.filter(|ancestor| !namespaces_by_root.contains_key(ancestor))
|
||||
.collect::<HashSet<_>>();
|
||||
namespaces_by_root.extend(
|
||||
futures::stream::iter(probe_roots)
|
||||
.map(|manifest_root| async move {
|
||||
let namespace = plugin_namespace_for_root_uri(fs, &manifest_root).await;
|
||||
(manifest_root, namespace)
|
||||
})
|
||||
.buffered(MAX_CONCURRENT_SKILL_LOADS)
|
||||
.collect::<HashMap<_, _>>()
|
||||
.await,
|
||||
);
|
||||
|
||||
let mut next_lookups = Vec::new();
|
||||
for (lookup_root, ancestor) in pending_lookups {
|
||||
match namespaces_by_root.get(&ancestor) {
|
||||
Some(Some(namespace)) => {
|
||||
namespaces_by_lookup_root.insert(lookup_root, Some(namespace.clone()));
|
||||
}
|
||||
Some(None) => match ancestor.parent() {
|
||||
Some(parent) => next_lookups.push((lookup_root, parent)),
|
||||
None => {
|
||||
namespaces_by_lookup_root.insert(lookup_root, None);
|
||||
}
|
||||
},
|
||||
None => unreachable!("pending namespace ancestor was not probed"),
|
||||
}
|
||||
}
|
||||
pending_lookups = next_lookups;
|
||||
}
|
||||
|
||||
// Ordinary descendants fall back to the nearest valid manifest at or above the scan root.
|
||||
let inherited_namespace = namespaces_by_lookup_root
|
||||
.get(root)
|
||||
.and_then(Option::as_ref)
|
||||
.cloned()
|
||||
.map(ResolvedSkillNamespace::Plugin)
|
||||
.unwrap_or(ResolvedSkillNamespace::Plain);
|
||||
let namespace_lookups = namespace_roots.into_iter().map(|namespace_root| {
|
||||
let namespace = namespaces_by_lookup_root
|
||||
.get(&namespace_root)
|
||||
.and_then(Option::as_ref)
|
||||
.cloned()
|
||||
.map(ResolvedSkillNamespace::Plugin)
|
||||
.unwrap_or(ResolvedSkillNamespace::Plain);
|
||||
(namespace_root, namespace)
|
||||
});
|
||||
// Invalid nested manifests are omitted, so the deepest remaining match wins.
|
||||
let plugin_lookups = plugin_roots.into_iter().filter_map(|plugin_root| {
|
||||
namespaces_by_root
|
||||
.get(&plugin_root)
|
||||
.and_then(Option::as_ref)
|
||||
.cloned()
|
||||
.map(|namespace| (plugin_root, ResolvedSkillNamespace::Plugin(namespace)))
|
||||
});
|
||||
let nested_namespaces = namespace_lookups.chain(plugin_lookups).collect();
|
||||
|
||||
Self {
|
||||
inherited_namespace,
|
||||
nested_namespaces,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn for_skill(&self, root: &PathUri, path: &PathUri) -> &ResolvedSkillNamespace {
|
||||
// Ancestor symlink targets cannot override skills still owned by the scan root.
|
||||
let path_is_under_root = path.starts_with(root);
|
||||
// The deepest matching path prefix is the nearest applicable namespace.
|
||||
self.nested_namespaces
|
||||
.iter()
|
||||
.filter(|(namespace_root, _)| {
|
||||
path.starts_with(namespace_root)
|
||||
&& (!path_is_under_root || !root.starts_with(namespace_root))
|
||||
})
|
||||
.max_by_key(|(namespace_root, _)| namespace_root.ancestors().count())
|
||||
.map(|(_, namespace)| namespace)
|
||||
.unwrap_or(&self.inherited_namespace)
|
||||
}
|
||||
}
|
||||
|
||||
/// The completed namespace resolution for a skill root.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub(crate) enum ResolvedSkillNamespace {
|
||||
/// No plugin namespace applies to matching skills.
|
||||
Plain,
|
||||
/// Qualify matching skill names with this plugin namespace.
|
||||
Plugin(String),
|
||||
}
|
||||
|
||||
impl ResolvedSkillNamespace {
|
||||
pub(crate) fn qualify(&self, base_name: &str) -> String {
|
||||
match self {
|
||||
Self::Plain => base_name.to_string(),
|
||||
Self::Plugin(namespace) => format!("{namespace}:{base_name}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "namespace_tests.rs"]
|
||||
mod tests;
|
||||
172
codex-rs/ext/skills/src/loader/namespace_tests.rs
Normal file
172
codex-rs/ext/skills/src/loader/namespace_tests.rs
Normal file
@@ -0,0 +1,172 @@
|
||||
use codex_exec_server::FileSystemEnvironmentAccessor;
|
||||
use codex_exec_server::LOCAL_FS;
|
||||
#[cfg(unix)]
|
||||
use codex_protocol::protocol::SkillScope;
|
||||
#[cfg(unix)]
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::collections::HashSet;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
use tempfile::TempDir;
|
||||
|
||||
#[cfg(unix)]
|
||||
use crate::loader::HostSkillRoot;
|
||||
#[cfg(unix)]
|
||||
use crate::loader::load_host_skill_root;
|
||||
|
||||
use super::SkillNamespaceResolver;
|
||||
|
||||
fn canonical_uri(path: &Path) -> PathUri {
|
||||
PathUri::from_host_native_path(fs::canonicalize(path).expect("canonical path"))
|
||||
.expect("absolute path URI")
|
||||
}
|
||||
|
||||
fn write_skill(root: &Path, directory: &str) -> PathUri {
|
||||
let path = root.join(directory).join("SKILL.md");
|
||||
fs::create_dir_all(path.parent().expect("skill parent")).expect("create skill directory");
|
||||
fs::write(&path, "---\nname: skill\ndescription: Demo skill\n---\n")
|
||||
.expect("write skill frontmatter");
|
||||
canonical_uri(&path)
|
||||
}
|
||||
|
||||
fn write_manifest(root: &Path, contents: &str) -> PathUri {
|
||||
let path = root.join(".codex-plugin/plugin.json");
|
||||
fs::create_dir_all(path.parent().expect("manifest parent"))
|
||||
.expect("create plugin manifest directory");
|
||||
fs::write(path, contents).expect("write plugin manifest");
|
||||
canonical_uri(root)
|
||||
}
|
||||
|
||||
async fn namespaces_for(
|
||||
root: &Path,
|
||||
skill_paths: &[PathUri],
|
||||
plugin_roots: HashSet<PathUri>,
|
||||
mut namespace_roots: HashSet<PathUri>,
|
||||
) -> Vec<String> {
|
||||
let root = canonical_uri(root);
|
||||
namespace_roots.insert(root.clone());
|
||||
let resolver = SkillNamespaceResolver::discover(
|
||||
&FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS),
|
||||
&root,
|
||||
skill_paths,
|
||||
plugin_roots,
|
||||
namespace_roots,
|
||||
)
|
||||
.await;
|
||||
|
||||
skill_paths
|
||||
.iter()
|
||||
.map(|path| resolver.for_skill(&root, path).qualify("skill"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn nested_plugin_namespaces_do_not_apply_to_plain_siblings() {
|
||||
let root = TempDir::new().expect("root temp dir");
|
||||
let nested_plugin = root.path().join("nested-plugin");
|
||||
let plugin_root = write_manifest(&nested_plugin, r#"{"name":"nested"}"#);
|
||||
let plain_skill = write_skill(root.path(), "plain");
|
||||
let nested_skill = write_skill(&nested_plugin, "skills/search");
|
||||
|
||||
let namespaces = namespaces_for(
|
||||
root.path(),
|
||||
&[plain_skill, nested_skill],
|
||||
HashSet::from([plugin_root]),
|
||||
HashSet::new(),
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(namespaces, vec!["skill", "nested:skill"]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn nearest_valid_manifest_overrides_or_falls_back_to_outer_namespace() {
|
||||
let root = TempDir::new().expect("root temp dir");
|
||||
let plugin_root = root.path().join("outer");
|
||||
let skills_root = plugin_root.join("skills");
|
||||
let nested_plugin = skills_root.join("nested");
|
||||
let invalid_plugin = skills_root.join("invalid");
|
||||
write_manifest(&plugin_root, r#"{"name":"outer"}"#);
|
||||
let nested_root = write_manifest(&nested_plugin, r#"{"name":"nested"}"#);
|
||||
let invalid_root = write_manifest(&invalid_plugin, "not json");
|
||||
let direct_skill = write_skill(&skills_root, "direct");
|
||||
let nested_skill = write_skill(&nested_plugin, "skills/search");
|
||||
let fallback_skill = write_skill(&invalid_plugin, "skills/fallback");
|
||||
|
||||
let namespaces = namespaces_for(
|
||||
&skills_root,
|
||||
&[direct_skill, nested_skill, fallback_skill],
|
||||
HashSet::from([nested_root, invalid_root]),
|
||||
HashSet::new(),
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(
|
||||
namespaces,
|
||||
vec!["outer:skill", "nested:skill", "outer:skill"]
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn symlinked_external_directories_do_not_inherit_plugin_namespace() {
|
||||
let access = FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS);
|
||||
let root = TempDir::new().expect("root temp dir");
|
||||
let external = TempDir::new().expect("external temp dir");
|
||||
let plugin_root = root.path().join("outer");
|
||||
let skills_root = plugin_root.join("skills");
|
||||
write_manifest(&plugin_root, r#"{"name":"outer"}"#);
|
||||
write_skill(external.path(), "plain");
|
||||
fs::create_dir_all(&skills_root).expect("create skill root");
|
||||
std::os::unix::fs::symlink(external.path(), skills_root.join("linked"))
|
||||
.expect("create external directory symlink");
|
||||
|
||||
let snapshot = load_host_skill_root(HostSkillRoot::host(
|
||||
AbsolutePathBuf::from_absolute_path(&skills_root).expect("absolute skills root"),
|
||||
SkillScope::User,
|
||||
&access,
|
||||
))
|
||||
.await;
|
||||
|
||||
assert_eq!(snapshot.errors, Vec::new());
|
||||
assert_eq!(
|
||||
snapshot
|
||||
.skills
|
||||
.into_iter()
|
||||
.map(|skill| skill.name)
|
||||
.collect::<Vec<_>>(),
|
||||
vec!["skill"]
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn ancestor_symlink_roots_preserve_inherited_plugin_namespace() {
|
||||
let access = FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS);
|
||||
let root = TempDir::new().expect("root temp dir");
|
||||
let plugin_root = root.path().join("a/b/c/d/e/f/outer");
|
||||
let skills_root = plugin_root.join("skills");
|
||||
write_manifest(&plugin_root, r#"{"name":"outer"}"#);
|
||||
write_skill(&skills_root, "direct");
|
||||
std::os::unix::fs::symlink(root.path(), skills_root.join("ancestor"))
|
||||
.expect("create ancestor directory symlink");
|
||||
|
||||
let snapshot = load_host_skill_root(HostSkillRoot::host(
|
||||
AbsolutePathBuf::from_absolute_path(&skills_root).expect("absolute skills root"),
|
||||
SkillScope::User,
|
||||
&access,
|
||||
))
|
||||
.await;
|
||||
|
||||
assert_eq!(snapshot.errors, Vec::new());
|
||||
assert_eq!(
|
||||
snapshot
|
||||
.skills
|
||||
.into_iter()
|
||||
.map(|skill| skill.name)
|
||||
.collect::<Vec<_>>(),
|
||||
vec!["outer:skill"]
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user