aKode fase 5: rinomina interna (crate akode-*, akode-rs/, akode-cli/, binario akode, AKODE_*, ~/.akode, snapshot)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-11 11:06:46 +01:00
parent df99318392
commit 86e7c72e5f
10383 changed files with 749164 additions and 749170 deletions

View File

@@ -0,0 +1,321 @@
use std::collections::HashMap;
use std::collections::HashSet;
use akode_exec_server::EnvironmentAccess;
mod discovery_v2;
use akode_extension_api::SelectedPluginSnapshot;
use akode_protocol::capabilities::CapabilityRootLocation;
use akode_protocol::protocol::Product;
use akode_protocol::protocol::SkillScope;
use akode_skills::EnvironmentSkillMetadata;
use akode_utils_path_uri::PathConvention;
use akode_utils_path_uri::PathUri;
use futures::StreamExt;
use crate::catalog::SkillAuthority;
use crate::catalog::SkillCatalog;
use crate::catalog::SkillCatalogEntry;
use crate::catalog::SkillPackageId;
use crate::catalog::SkillProviderError;
use crate::catalog::SkillReadResult;
use crate::catalog::SkillResourceId;
use crate::catalog::SkillSearchResult;
use crate::catalog::SkillSourceKind;
use crate::loader::load_environment_skills_from_discovery;
use crate::loader::load_environment_skills_from_root;
use crate::provider::MAX_SKILL_RESOURCE_CONTENT_BYTES;
use crate::provider::SkillListQuery;
use crate::provider::SkillProvider;
use crate::provider::SkillProviderFuture;
use crate::provider::SkillReadContext;
use crate::provider::SkillReadRequest;
use crate::provider::SkillSearchRequest;
/// Discovers and reads skills through the filesystem owned by an execution environment.
#[derive(Clone, Debug)]
pub struct ExecutorSkillProvider {
restriction_product: Option<Product>,
disabled_skill_paths: HashMap<String, HashSet<PathUri>>,
}
impl ExecutorSkillProvider {
pub fn new_with_restriction_product(restriction_product: Option<Product>) -> Self {
Self {
restriction_product,
disabled_skill_paths: HashMap::new(),
}
}
/// Applies caller-owned disablement to executor catalogs. Paths identify SKILL.md
/// documents in their executor's filesystem; other executors are unaffected.
/// By default, all discovered skills remain enabled.
pub fn with_disabled_skill_paths(
mut self,
disabled_skill_paths: HashMap<String, HashSet<PathUri>>,
) -> Self {
self.disabled_skill_paths = disabled_skill_paths;
self
}
}
pub(crate) fn attribute_executor_plugins(
catalog: &mut SkillCatalog,
snapshot: &SelectedPluginSnapshot,
) {
catalog
.entries
.retain(|skill| !snapshot.disabled_plugin_roots.contains(&skill.authority.id));
for skill in &mut catalog.entries {
if let Some(plugin) = snapshot
.plugins
.iter()
.find(|plugin| plugin.selected_root_id.as_ref() == Some(&skill.authority.id))
{
skill.plugin_id = Some(plugin.plugin_id.as_str().to_string());
skill.invocation_scope = Some(SkillScope::User);
}
}
}
impl SkillProvider for ExecutorSkillProvider {
fn list<'a>(&'a self, query: SkillListQuery<'a>) -> SkillProviderFuture<'a, SkillCatalog> {
Box::pin(async move {
if let Some(snapshots) = &query.executor_capability_discovery_v2 {
return Ok(self.list_from_discovery_v2(snapshots));
}
if let Some(discovery) = query.executor_capability_discovery {
return Ok(self.list_from_discovery(&discovery));
}
let mut catalog = SkillCatalog::default();
for bound in query.executor_roots {
let fs = bound.fs;
let selected_root = bound.root;
let selected_root_id = &selected_root.id;
let CapabilityRootLocation::Environment {
environment_id,
path,
} = &selected_root.location;
let authority =
SkillAuthority::new(SkillSourceKind::Executor, selected_root_id.clone());
let outcome =
load_environment_skills_from_root(fs, path, self.restriction_product).await;
catalog.warnings.extend(outcome.warnings);
for skill in outcome.skills {
catalog.push_entry(catalog_entry_from_skill(
&skill,
authority.clone(),
selected_root_id,
path,
environment_id,
/*instructions*/ None,
&self.disabled_skill_paths,
));
}
}
Ok(catalog)
})
}
fn read<'a>(
&'a self,
request: SkillReadRequest<'a>,
) -> SkillProviderFuture<'a, SkillReadResult> {
Box::pin(async move {
if request.authority.kind != SkillSourceKind::Executor {
return Err(SkillProviderError::new(format!(
"executor skill provider cannot read {} resources",
request.authority.kind
)));
}
let expected_package_prefix = format!("skill://{}/", request.authority.id);
if !request.package.0.starts_with(&expected_package_prefix)
|| request
.package
.relative_resource_path(request.resource.as_str())
.is_none()
{
return Err(SkillProviderError::new(
"executor skill resource does not match its package",
));
}
let SkillReadContext::Executor { fs } = request.context else {
return Err(SkillProviderError::new(
"executor skill reads require filesystem access",
));
};
if let Some(contents) = request.resource.environment_contents() {
return Ok(SkillReadResult {
resource: request.resource.clone(),
contents: contents.to_string(),
});
}
let Some((_, resource_path)) = request.resource.environment_path() else {
return Err(SkillProviderError::new(
"executor skill resource is not bound to an environment",
));
};
let contents = read_bounded_text(fs, resource_path, request.resource.as_str()).await?;
Ok(SkillReadResult {
resource: request.resource,
contents,
})
})
}
fn search(&self, _request: SkillSearchRequest) -> SkillProviderFuture<'_, SkillSearchResult> {
Box::pin(async { Ok(SkillSearchResult::default()) })
}
}
impl ExecutorSkillProvider {
fn list_from_discovery(
&self,
snapshot: &akode_exec_server::ExecutorCapabilityDiscoverySnapshot,
) -> SkillCatalog {
let mut catalog = SkillCatalog::default();
for root in snapshot.roots() {
let selected_root_id = &root.selected_root.id;
let CapabilityRootLocation::Environment {
environment_id,
path,
} = &root.selected_root.location;
let discovery = match &root.result {
Ok(discovery) => discovery.as_ref(),
Err(error) => {
catalog.is_partial = true;
catalog.warnings.push(format!(
"Selected capability root `{selected_root_id}` discovery failed: {error}"
));
continue;
}
};
catalog.is_partial |= discovery.error.is_some();
let outcome =
load_environment_skills_from_discovery(discovery, self.restriction_product);
catalog.warnings.extend(outcome.warnings);
let authority =
SkillAuthority::new(SkillSourceKind::Executor, selected_root_id.clone());
for skill in outcome.skills {
catalog.push_entry(catalog_entry_from_skill(
&skill.metadata,
authority.clone(),
selected_root_id,
path,
environment_id,
Some(skill.instructions),
&self.disabled_skill_paths,
));
}
}
catalog
}
}
fn catalog_entry_from_skill(
skill: &EnvironmentSkillMetadata,
authority: SkillAuthority,
selected_root_id: &str,
selected_root_path: &PathUri,
environment_id: &str,
instructions: Option<String>,
disabled_skill_paths: &HashMap<String, HashSet<PathUri>>,
) -> SkillCatalogEntry {
let handle_prefix = format!("skill://{selected_root_id}/");
let alias_root = format!(
"{handle_prefix}{}",
normalized_environment_path(selected_root_path).trim_start_matches('/')
);
let normalized_main_path = normalized_environment_path(&skill.path_to_skills_md);
let normalized_package_path = skill.path_to_skills_md.parent().map_or_else(
|| normalized_main_path.clone(),
|path| normalized_environment_path(&path),
);
let package = format!(
"{handle_prefix}{}",
normalized_package_path.trim_start_matches('/')
);
let main_resource = format!(
"{handle_prefix}{}",
normalized_main_path.trim_start_matches('/')
);
let main_prompt = match instructions {
Some(contents) => SkillResourceId::environment_with_contents(
main_resource.clone(),
environment_id,
skill.path_to_skills_md.clone(),
contents,
),
None => SkillResourceId::environment(
main_resource.clone(),
environment_id,
skill.path_to_skills_md.clone(),
),
};
let mut entry = SkillCatalogEntry::new(
SkillPackageId(package),
authority,
skill.name.clone(),
skill.description.clone(),
main_prompt,
)
.with_short_description(skill.short_description.clone())
.with_display_path(main_resource)
.with_alias_root(alias_root)
.with_dependencies(skill.dependencies.clone());
if disabled_skill_paths
.get(environment_id)
.is_some_and(|paths| paths.contains(&skill.path_to_skills_md))
{
entry = entry.disabled();
}
if skill.allows_implicit_invocation() {
entry
} else {
entry.hidden_from_prompt()
}
}
fn normalized_environment_path(path: &PathUri) -> String {
let convention = path.infer_path_convention();
let path = path.inferred_native_path_string();
match convention {
Some(PathConvention::Windows) => path.replace('\\', "/"),
Some(PathConvention::Posix) | None => path,
}
}
async fn read_bounded_text(
file_system: &dyn EnvironmentAccess,
path: &PathUri,
resource: &str,
) -> Result<String, SkillProviderError> {
let read_error = |err| {
SkillProviderError::new(format!(
"failed to read executor skill resource {resource}: {err}"
))
};
let mut stream = file_system
.read_file_stream(path)
.await
.map_err(&read_error)?;
let mut contents = Vec::new();
while let Some(chunk) = stream.next().await {
let chunk = chunk.map_err(&read_error)?;
if contents.len().saturating_add(chunk.len()) > MAX_SKILL_RESOURCE_CONTENT_BYTES {
return Err(SkillProviderError::new(format!(
"executor skill resource {resource} exceeds {MAX_SKILL_RESOURCE_CONTENT_BYTES} bytes"
)));
}
contents.extend_from_slice(&chunk);
}
String::from_utf8(contents).map_err(|_| {
SkillProviderError::new(format!(
"executor skill resource {resource} is not valid UTF-8"
))
})
}

View File

@@ -0,0 +1,104 @@
//! Projects executor-owned discovery metadata into skill catalogs without reopening host paths.
use akode_exec_server::ExecutorCapabilityDiscoveryV2Snapshot;
use akode_exec_server::ExecutorSkill;
use akode_protocol::protocol::SkillScope;
use akode_skills::EnvironmentSkillMetadata;
use akode_utils_path_uri::PathUri;
use crate::catalog::SkillAuthority;
use crate::catalog::SkillCatalog;
use crate::catalog::SkillCatalogEntry;
use crate::catalog::SkillSourceKind;
use super::ExecutorSkillProvider;
use super::catalog_entry_from_skill;
impl ExecutorSkillProvider {
pub(super) fn list_from_discovery_v2(
&self,
snapshots: &[ExecutorCapabilityDiscoveryV2Snapshot],
) -> SkillCatalog {
let mut catalog = SkillCatalog::default();
for snapshot in snapshots {
let discovered = match &snapshot.result {
Ok(discovered) => discovered,
Err(error) => {
catalog.is_partial = true;
catalog.warnings.push(format!(
"Environment `{}` discovery failed: {error}",
snapshot.environment_id
));
continue;
}
};
catalog.warnings.extend(discovered.warnings.clone());
for plugin in &discovered.plugins {
for skill in &plugin.skills {
let Some(mut entry) = self.catalog_entry_from_discovered_skill(
skill,
&plugin.id,
&plugin.root,
&snapshot.environment_id,
) else {
continue;
};
entry.plugin_id = Some(plugin.id.clone());
entry.invocation_scope = Some(SkillScope::User);
catalog.push_entry(entry);
}
}
for skill in &discovered.skills {
// Use the skills namespace when discovery-root metadata is absent.
let fallback_root;
let (root_id, root_path) = if let Some(root) = &skill.discovery_root {
(root.id.as_str(), &root.path)
} else {
let Some(parent) = skill.path.parent() else {
continue;
};
fallback_root = parent;
("skills", &fallback_root)
};
if let Some(entry) = self.catalog_entry_from_discovered_skill(
skill,
root_id,
root_path,
&snapshot.environment_id,
) {
catalog.push_entry(entry);
}
}
}
catalog
}
fn catalog_entry_from_discovered_skill(
&self,
skill: &ExecutorSkill,
root_id: &str,
root: &PathUri,
environment_id: &str,
) -> Option<SkillCatalogEntry> {
let metadata = EnvironmentSkillMetadata {
path_to_skills_md: skill.path.clone(),
name: skill.name.clone(),
description: skill.description.clone(),
short_description: skill.short_description.clone(),
dependencies: skill.dependencies.clone(),
policy: skill.policy.clone(),
};
if !metadata.matches_product_restriction(self.restriction_product) {
return None;
}
Some(catalog_entry_from_skill(
&metadata,
SkillAuthority::new(SkillSourceKind::Executor, root_id),
root_id,
root,
environment_id,
/*instructions*/ None,
&self.disabled_skill_paths,
))
}
}

View File

@@ -0,0 +1,179 @@
use std::collections::HashMap;
use crate::SkillLoadOutcome;
use akode_skills::SkillMetadata;
use akode_utils_path_uri::PathUri;
use crate::catalog::SkillAuthority;
use crate::catalog::SkillCatalog;
use crate::catalog::SkillCatalogEntry;
use crate::catalog::SkillPackageId;
use crate::catalog::SkillProviderError;
use crate::catalog::SkillReadResult;
use crate::catalog::SkillResourceId;
use crate::catalog::SkillSearchResult;
use crate::catalog::SkillSourceKind;
use crate::provider::SkillListQuery;
use crate::provider::SkillProvider;
use crate::provider::SkillProviderFuture;
use crate::provider::SkillReadContext;
use crate::provider::SkillReadRequest;
use crate::provider::SkillSearchRequest;
const HOST_AUTHORITY_ID: &str = "host";
/// Host-owned skill provider backed by an immutable service snapshot.
///
/// Discovery and caching belong to `HostSkillsService`; this provider only maps a
/// snapshot into the authority-aware catalog/read contract.
#[derive(Clone, Default)]
pub struct HostSkillProvider;
impl HostSkillProvider {
pub fn new() -> Self {
Self
}
}
impl SkillProvider for HostSkillProvider {
fn list<'a>(&'a self, query: SkillListQuery<'a>) -> SkillProviderFuture<'a, SkillCatalog> {
Box::pin(async move {
let Some(host_snapshot) = query.host_snapshot else {
return Err(SkillProviderError::new(
"host skill provider requires a host skills snapshot",
));
};
Ok(catalog_from_outcome(host_snapshot.outcome()))
})
}
fn read<'a>(
&'a self,
request: SkillReadRequest<'a>,
) -> SkillProviderFuture<'a, SkillReadResult> {
Box::pin(async move {
let SkillReadContext::Host {
host_snapshot: Some(host_snapshot),
accessors,
} = request.context
else {
return Err(SkillProviderError::new(
"host skill provider requires a host skills snapshot",
));
};
// TODO(anp): Infer resource path conventions once foreign repository paths can reach this
// provider. Despite its name, it also serves repository skills from the caller's environment;
// the loader currently rejects foreign paths. Host-owned skills use the app-server's local
// filesystem.
let resource_path = PathUri::from_host_native_path(request.resource.as_str()).ok();
let Some(skill) = host_snapshot
.outcome()
.skills
.iter()
.find(|skill| Some(&skill.path_to_skills_md) == resource_path.as_ref())
else {
return Err(SkillProviderError::new(format!(
"host skill resource is not loaded: {}",
request.resource.as_str()
)));
};
let contents = host_snapshot
.read_skill_text(skill, &accessors)
.await
.map_err(|err| {
SkillProviderError::new(format!(
"failed to read host skill resource {}: {err}",
request.resource.as_str()
))
})?;
Ok(SkillReadResult {
resource: request.resource,
contents,
})
})
}
fn search(&self, _request: SkillSearchRequest) -> SkillProviderFuture<'_, SkillSearchResult> {
Box::pin(async { Ok(SkillSearchResult::default()) })
}
}
fn catalog_from_outcome(outcome: &SkillLoadOutcome) -> SkillCatalog {
let root_order_by_path = outcome
.skill_roots_in_discovery_order()
.enumerate()
.map(|(index, root)| (root.as_path(), index))
.collect::<HashMap<_, _>>();
let mut catalog = SkillCatalog {
is_partial: false,
entries: Vec::new(),
warnings: outcome
.errors
.iter()
.map(|err| {
format!(
"Failed to load skill at {}: {}",
err.path.display(),
err.message
)
})
.collect(),
};
for (skill, enabled) in outcome.skills_with_enabled() {
let mut entry = catalog_entry_from_skill(skill, enabled);
if let Some(discovery_path) =
outcome.skill_discovery_path_for_path(&skill.path_to_skills_md)
{
// Keep the catalog's existing forward-slash display on Windows; lookups use PathUri.
entry = entry.with_display_path(
discovery_path
.inferred_native_path_string()
.replace('\\', "/"),
);
}
if let Some(root) = outcome.skill_root_for_path(&skill.path_to_skills_md) {
// Alias labels share the display path's separators so catalog rendering stays stable.
entry = entry.with_alias_root(root.to_string_lossy().replace('\\', "/"));
if let Some(root_order) = root_order_by_path.get(root.as_path()) {
entry = entry.with_alias_root_order(*root_order);
}
}
catalog.push_entry(entry);
}
catalog
}
fn catalog_entry_from_skill(skill: &SkillMetadata, enabled: bool) -> SkillCatalogEntry {
let skill_path = skill.path_to_skills_md.inferred_native_path_string();
// Preserve model-visible paths while resource IDs retain the native spelling used by clients.
let display_path = skill_path.replace('\\', "/");
let mut entry = SkillCatalogEntry::new(
SkillPackageId(skill_path.clone()),
SkillAuthority::new(SkillSourceKind::Host, HOST_AUTHORITY_ID),
skill.name.clone(),
skill.description.clone(),
SkillResourceId::new(skill_path),
)
.with_short_description(skill.short_description.clone())
.with_display_path(display_path)
.with_prompt_scope(skill.scope)
.with_dependencies(skill.dependencies.clone());
if !enabled {
entry = entry.disabled();
}
if !skill.allows_implicit_invocation() {
entry = entry.hidden_from_prompt();
}
entry
}
#[cfg(test)]
#[path = "host_tests.rs"]
mod tests;

View File

@@ -0,0 +1,166 @@
use akode_exec_server::FileSystemEnvironmentAccessor;
use std::sync::Arc;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;
use akode_exec_server::LOCAL_FS;
use akode_protocol::protocol::SkillScope;
use akode_utils_absolute_path::AbsolutePathBuf;
use pretty_assertions::assert_eq;
use tokio::sync::Semaphore;
use super::HostSkillProvider;
use super::catalog_from_outcome;
use crate::HostSkillsSnapshot;
use crate::catalog::SkillReadResult;
use crate::catalog::SkillResourceId;
use crate::loader::HostSkillRoot;
use crate::loader::load_and_merge_host_skill_roots;
use crate::provider::SkillProvider;
use crate::provider::SkillReadContext;
use crate::provider::SkillReadRequest;
#[tokio::test]
async fn host_catalog_entries_carry_their_render_metadata() -> Result<(), Box<dyn std::error::Error>>
{
let access = FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS);
let unique = SystemTime::now().duration_since(UNIX_EPOCH)?.as_nanos();
let root = std::env::temp_dir().join(format!(
"codex-skills-extension-host-provider-{}-{unique}",
std::process::id()
));
let skill_path = root.join("demo").join("SKILL.md");
std::fs::create_dir_all(
skill_path
.parent()
.ok_or("skill path should have a parent")?,
)?;
std::fs::write(
&skill_path,
"---\nname: demo\ndescription: Demo skill.\n---\n# Demo\n",
)?;
let root = AbsolutePathBuf::try_from(std::fs::canonicalize(root)?)?;
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;
let catalog = catalog_from_outcome(&outcome);
assert_eq!(catalog.entries.len(), 1);
assert_eq!(
(
catalog.entries[0].alias_root(),
catalog.entries[0].prompt_scope(),
),
(
Some(root.to_string_lossy().replace('\\', "/").as_str()),
Some(SkillScope::User),
)
);
std::fs::remove_dir_all(root.as_path())?;
Ok(())
}
/// Host catalog IDs and displayed paths must resolve to the same discovered file,
/// including Windows slash spelling and characters that need URI escaping.
#[tokio::test]
async fn host_catalog_resource_spellings_read_the_discovered_skill()
-> Result<(), Box<dyn std::error::Error>> {
let access = FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS);
let root = tempfile::tempdir()?;
let skill_path = root.path().join("demo skill%23").join("SKILL.md");
std::fs::create_dir_all(
skill_path
.parent()
.ok_or("skill path should have a parent")?,
)?;
let contents = "---\nname: demo\ndescription: Demo skill.\n---\n# Demo\n";
std::fs::write(&skill_path, contents)?;
let root_path = AbsolutePathBuf::try_from(std::fs::canonicalize(root.path())?)?;
let outcome = load_and_merge_host_skill_roots(
vec![HostSkillRoot::host(root_path, SkillScope::User, &access)],
&Semaphore::new(/*permits*/ 1),
/*restriction_product*/ None,
/*plugin_skill_snapshots*/ None,
)
.await;
let catalog = catalog_from_outcome(&outcome);
let entry = catalog
.entries
.first()
.ok_or("skill should be discovered")?;
let snapshot = Arc::new(HostSkillsSnapshot::new(Arc::new(outcome)));
for resource in [
entry.main_prompt.clone(),
SkillResourceId::new(entry.display_path.as_ref().ok_or("skill display path")?),
] {
let result = HostSkillProvider::new()
.read(SkillReadRequest {
authority: entry.authority.clone(),
package: entry.id.clone(),
resource: resource.clone(),
context: SkillReadContext::Host {
accessors: Vec::new(),
host_snapshot: Some(Arc::clone(&snapshot)),
},
})
.await?;
assert_eq!(
result,
SkillReadResult {
resource,
contents: contents.to_string()
}
);
}
Ok(())
}
#[cfg(unix)]
#[tokio::test]
async fn host_catalog_preserves_symlinked_skill_discovery_paths()
-> Result<(), Box<dyn std::error::Error>> {
let access = FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS);
let root = tempfile::tempdir()?;
let source = tempfile::tempdir()?;
let source_skill_dir = source.path().join("linked-skill");
std::fs::create_dir_all(&source_skill_dir)?;
std::fs::write(
source_skill_dir.join("SKILL.md"),
"---\nname: linked-skill\ndescription: Linked skill.\n---\n# Linked skill\n",
)?;
std::os::unix::fs::symlink(&source_skill_dir, root.path().join("linked-skill"))?;
let root = AbsolutePathBuf::try_from(std::fs::canonicalize(root.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;
let catalog = catalog_from_outcome(&outcome);
let canonical_path = std::fs::canonicalize(source_skill_dir.join("SKILL.md"))?;
let discovery_path = root.join("linked-skill/SKILL.md");
assert_eq!(catalog.entries.len(), 1);
assert_eq!(
(
catalog.entries[0].main_prompt.as_str(),
catalog.entries[0].display_path.as_deref(),
catalog.entries[0].alias_root(),
),
(
canonical_path.to_string_lossy().as_ref(),
Some(discovery_path.to_string_lossy().as_ref()),
Some(root.to_string_lossy().as_ref()),
)
);
Ok(())
}