Base: codex-main originale (prima del fork aKode)

This commit is contained in:
Andrea
2026-11-09 10:37:42 +01:00
commit 7874033c81
10166 changed files with 2728937 additions and 0 deletions

View File

@@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "skills",
crate_name = "codex_skills_extension",
)

View File

@@ -0,0 +1,52 @@
[package]
edition.workspace = true
license.workspace = true
name = "codex-skills-extension"
version.workspace = true
[lib]
name = "codex_skills_extension"
path = "src/lib.rs"
doctest = false
[lints]
workspace = true
[dependencies]
blake3 = { workspace = true }
codex-analytics = { workspace = true }
codex-config = { workspace = true }
codex-exec-server = { workspace = true }
codex-extension-api = { workspace = true }
codex-mcp = { workspace = true }
codex-otel = { workspace = true }
codex-protocol = { workspace = true }
codex-skills = { workspace = true }
codex-tools = { workspace = true }
codex-utils-absolute-path = { workspace = true }
codex-utils-path-uri = { workspace = true }
codex-utils-plugins = { workspace = true }
codex-utils-string = { workspace = true }
dirs = { workspace = true }
futures = { workspace = true }
schemars = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
tokio = { workspace = true, features = ["rt", "sync", "time"] }
toml = { workspace = true }
tracing = { workspace = true }
[dev-dependencies]
assert_matches = { workspace = true }
codex-attachment-store = { workspace = true }
codex-core-plugin-common = { workspace = true }
codex-models-manager = { workspace = true }
codex-protocol-test-support = { workspace = true }
codex-utils-cargo-bin = { workspace = true }
dunce = { workspace = true }
insta = { workspace = true }
opentelemetry_sdk = { workspace = true }
pretty_assertions = { workspace = true }
tempfile = { workspace = true }
tokio = { workspace = true, features = ["macros", "rt-multi-thread", "test-util"] }
tracing-subscriber = { workspace = true }

View File

@@ -0,0 +1,257 @@
//! Bounded, append-only aliases shared by rendering and reads within a live thread.
//! Step snapshots retain their assignments; aliases are not persisted across resume or fork.
use std::collections::HashSet;
use std::sync::Arc;
use std::sync::Mutex;
use serde::Deserialize;
use serde::Serialize;
use crate::catalog::SkillSourceKind;
use crate::step_state::SkillToolAuthoritySelector;
fn alias_prefix(source: &SkillSourceKind) -> Option<&'static str> {
match source {
SkillSourceKind::Cloud => Some("c"),
SkillSourceKind::Executor => Some("e"),
SkillSourceKind::Host => Some("r"),
SkillSourceKind::Custom(_) => None,
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(from = "String", into = "String")]
pub(crate) struct SkillLocator {
value: String,
alias_source: Option<SkillSourceKind>,
}
impl From<String> for SkillLocator {
fn from(value: String) -> Self {
let alias_source = value.split_once('/').and_then(|(root, suffix)| {
if suffix.is_empty() {
return None;
}
let (prefix, index) = root.split_at_checked(1)?;
if index.is_empty()
|| !index.bytes().all(|byte| byte.is_ascii_digit())
|| (index.len() > 1 && index.starts_with('0'))
{
return None;
}
index.parse::<usize>().ok()?;
[
SkillSourceKind::Cloud,
SkillSourceKind::Executor,
SkillSourceKind::Host,
]
.into_iter()
.find(|source| alias_prefix(source) == Some(prefix))
});
Self {
value,
alias_source,
}
}
}
impl From<SkillLocator> for String {
fn from(locator: SkillLocator) -> Self {
locator.value
}
}
impl SkillLocator {
pub(crate) fn as_str(&self) -> &str {
&self.value
}
pub(crate) fn alias_source(&self) -> Option<&SkillSourceKind> {
self.alias_source.as_ref()
}
}
/// Owns thread-wide alias allocation independently of provider caches.
#[derive(Default)]
pub(crate) struct SkillAliasState {
aliases: Mutex<SkillCatalogAliases>,
}
impl SkillAliasState {
pub(crate) fn capture(
&self,
roots: impl IntoIterator<Item = (SkillSourceKind, String)>,
) -> SkillCatalogAliases {
let mut aliases = self
.aliases
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
for (kind, root) in roots {
let selector = match kind {
SkillSourceKind::Cloud => SkillToolAuthoritySelector::Cloud,
SkillSourceKind::Executor => SkillToolAuthoritySelector::Executor,
SkillSourceKind::Host | SkillSourceKind::Custom(_) => continue,
};
aliases.extend(selector, [root.as_str()]);
}
aliases.clone()
}
}
/// Thread-wide assignments, captured alongside each step's catalog.
#[derive(Clone, Debug, Default)]
pub(crate) struct SkillCatalogAliases {
cloud: Arc<AliasPlan>,
executor: Arc<AliasPlan>,
budget: AliasBudget,
}
impl SkillCatalogAliases {
pub(crate) fn resolve(&self, locator: &SkillLocator) -> Option<String> {
let plan = match locator.alias_source() {
Some(SkillSourceKind::Cloud) => &self.cloud,
Some(SkillSourceKind::Executor) => &self.executor,
Some(SkillSourceKind::Host | SkillSourceKind::Custom(_)) | None => return None,
};
plan.expand(locator.as_str())
}
fn extend<'a>(
&mut self,
selector: SkillToolAuthoritySelector,
roots: impl IntoIterator<Item = &'a str>,
) {
let (plan, prefix) = match selector {
SkillToolAuthoritySelector::Cloud => (&mut self.cloud, "c"),
SkillToolAuthoritySelector::Executor => (&mut self.executor, "e"),
};
plan.extend_alias_plan(prefix, roots, &mut self.budget);
}
pub(crate) fn for_authority(&self, selector: SkillToolAuthoritySelector) -> &AliasPlan {
match selector {
SkillToolAuthoritySelector::Cloud => &self.cloud,
SkillToolAuthoritySelector::Executor => &self.executor,
}
}
}
const MAX_ALIAS_ROOTS: usize = 2_048;
const MAX_ALIAS_BYTES: usize = 16 * 1024;
/// Shared bound on thread-local Cloud/executor alias assignments and their rendered mappings.
#[derive(Clone, Debug, Default)]
struct AliasBudget {
roots: usize,
bytes: usize,
}
#[derive(Clone, Debug)]
pub(crate) struct AliasRoot {
pub(crate) name: String,
pub(crate) value: Arc<str>,
}
impl AliasRoot {
pub(crate) fn line(&self) -> String {
format!("- `{}` = `{}`", self.name, self.value)
}
}
#[derive(Clone, Debug, Default)]
pub(crate) struct AliasPlan {
roots: Vec<AliasRoot>,
known_roots: HashSet<Arc<str>>,
}
impl AliasPlan {
pub(crate) fn build(source: &SkillSourceKind, candidates: &[&str]) -> Option<Self> {
let prefix = alias_prefix(source)?;
let mut roots = Vec::new();
let mut known_roots = HashSet::new();
for &root in candidates {
if known_roots.contains(root) {
continue;
}
let root: Arc<str> = root.into();
known_roots.insert(Arc::clone(&root));
let index = roots.len();
roots.push(AliasRoot {
name: format!("{prefix}{index}"),
value: root,
});
}
(!roots.is_empty()).then_some(Self { roots, known_roots })
}
/// Retains existing assignments and reserves new numbers for previously unseen roots.
fn extend_alias_plan<'a>(
self: &mut Arc<Self>,
prefix: &str,
roots: impl IntoIterator<Item = &'a str>,
budget: &mut AliasBudget,
) {
for root in roots {
if self.known_roots.contains(root) {
continue;
}
let name = format!("{prefix}{}", self.roots.len());
let bytes = name.len() + root.len() + "- `` = ``".len();
if budget.roots == MAX_ALIAS_ROOTS {
break;
}
if bytes > MAX_ALIAS_BYTES - budget.bytes {
continue;
}
budget.roots += 1;
budget.bytes += bytes;
let plan = Arc::make_mut(self);
let root: Arc<str> = root.into();
plan.known_roots.insert(Arc::clone(&root));
plan.roots.push(AliasRoot { name, value: root });
}
}
pub(crate) fn root_for_locator(&self, locator: &str) -> Option<&AliasRoot> {
self.roots
.iter()
.filter(|root| {
locator
.strip_prefix(root.value.trim_end_matches('/'))
.is_some_and(|suffix| suffix.starts_with('/'))
})
.max_by_key(|root| root.value.len())
}
pub(crate) fn shorten(&self, locator: &str) -> Option<String> {
let root = self.root_for_locator(locator)?;
let suffix = &locator[root.value.trim_end_matches('/').len()..];
Some(format!("{}{suffix}", root.name))
}
fn expand(&self, alias: &str) -> Option<String> {
let (name, suffix) = alias.split_once('/')?;
let root = self.roots.iter().find(|root| root.name == name)?;
Some(format!("{}/{suffix}", root.value.trim_end_matches('/')))
}
pub(crate) fn root_lines_for(&self, used: &HashSet<String>) -> Vec<String> {
self.roots
.iter()
.filter(|root| used.contains(&root.name))
.map(AliasRoot::line)
.collect()
}
pub(crate) fn root_lines(&self) -> Vec<String> {
self.roots.iter().map(AliasRoot::line).collect()
}
}
#[cfg(test)]
#[path = "aliases_tests.rs"]
mod tests;

View File

@@ -0,0 +1,178 @@
use pretty_assertions::assert_eq;
use super::AliasPlan;
use super::SkillLocator;
use crate::catalog::SkillSourceKind;
#[test]
fn assigns_aliases_in_first_seen_order() {
let roots = [
"/skills/beta",
"/skills/alpha",
"/skills/beta",
"/skills/alpha",
];
let plan = AliasPlan::build(&SkillSourceKind::Host, &roots).expect("alias plan should build");
assert_eq!(
vec!["- `r0` = `/skills/beta`", "- `r1` = `/skills/alpha`"],
plan.root_lines()
);
}
#[test]
fn reuses_aliases_for_duplicate_roots() {
let root = "/skills/shared";
let plan = AliasPlan::build(&SkillSourceKind::Host, &[root, root, root])
.expect("alias plan should build");
assert_eq!(vec!["- `r0` = `/skills/shared`"], plan.root_lines());
assert_eq!(
Some("r0/alpha/SKILL.md".to_string()),
plan.shorten("/skills/shared/alpha/SKILL.md")
);
assert_eq!(
Some("r0/beta/SKILL.md".to_string()),
plan.shorten("/skills/shared/beta/SKILL.md")
);
}
#[test]
fn shortens_filesystem_and_skill_resource_locators() {
for (source, root, locator, expected) in [
(
SkillSourceKind::Host,
"/skills/shared",
"/skills/shared/alpha/SKILL.md",
"r0/alpha/SKILL.md",
),
(
SkillSourceKind::Executor,
"skill://executor/workspace/skills",
"skill://executor/workspace/skills/alpha/SKILL.md",
"e0/alpha/SKILL.md",
),
(
SkillSourceKind::Cloud,
"skill://plugin",
"skill://plugin/alpha",
"c0/alpha",
),
] {
let plan = AliasPlan::build(&source, &[root, root]).expect("alias plan should build");
let shortened = plan.shorten(locator).expect("known root");
assert_eq!(shortened, expected);
assert_eq!(plan.expand(&shortened).as_deref(), Some(locator));
let json = serde_json::to_string(&shortened).unwrap();
let parsed: SkillLocator = serde_json::from_str(&json).unwrap();
assert_eq!(parsed.alias_source(), Some(&source));
assert_eq!(parsed.as_str(), expected);
assert_eq!(serde_json::to_string(&parsed).unwrap(), json);
}
}
#[test]
fn rejects_unknown_roots_and_locators_outside_the_root() {
let root = "/skills/shared";
let plan =
AliasPlan::build(&SkillSourceKind::Host, &[root, root]).expect("alias plan should build");
assert_eq!(None, plan.shorten("/skills/other/alpha"));
assert_eq!(None, plan.shorten("/skills/shared-other/alpha"));
assert_eq!(None, plan.shorten(root));
}
#[test]
fn returns_none_when_no_roots_are_provided() {
assert!(AliasPlan::build(&SkillSourceKind::Host, &[]).is_none());
}
#[test]
fn aliases_roots_used_by_only_one_skill() {
let root = "/skills/singleton";
let plan = AliasPlan::build(&SkillSourceKind::Host, &[root])
.expect("singleton root should produce an alias");
assert_eq!(vec!["- `r0` = `/skills/singleton`"], plan.root_lines());
assert_eq!(
Some("r0/alpha/SKILL.md".to_string()),
plan.shorten("/skills/singleton/alpha/SKILL.md")
);
}
#[test]
fn locator_serde_recognizes_aliases_and_preserves_package_strings() {
for (value, expected_source) in [
("c0/release", Some(SkillSourceKind::Cloud)),
("e12/references/details.md", Some(SkillSourceKind::Executor)),
("r1/release/SKILL.md", Some(SkillSourceKind::Host)),
("skill://Plugin_123/release", None),
("/skills/release/SKILL.md", None),
(r"C:\skills\release\SKILL.md", None),
("cloud/release", None),
("c/release", None),
("c00/release", None),
("e-1/release", None),
("e+1/release", None),
("c0", None),
("c0/", None),
("/release", None),
("é0/release", None),
("e999999999999999999999999999999/release", None),
] {
let json = serde_json::to_string(value).unwrap();
let locator: SkillLocator = serde_json::from_str(&json).unwrap();
assert_eq!(locator.alias_source(), expected_source.as_ref(), "{value}");
assert_eq!(locator.as_str(), value);
assert_eq!(serde_json::to_string(&locator).unwrap(), json);
}
}
#[test]
fn appended_aliases_preserve_captured_steps_and_existing_locators() {
let mut aliases = std::sync::Arc::new(AliasPlan::default());
let mut budget = super::AliasBudget::default();
aliases.extend_alias_plan("e", ["skill://root"], &mut budget);
let previous = std::sync::Arc::clone(&aliases);
let locator = "skill://root/nested/demo";
let original = aliases.shorten(locator).unwrap();
aliases.extend_alias_plan("e", ["skill://root/nested", "skill://root"], &mut budget);
assert_eq!(previous.root_lines(), vec!["- `e0` = `skill://root`"]);
assert_eq!(previous.shorten(locator), Some(original.clone()));
assert_eq!(aliases.shorten(locator), Some("e1/demo".into()));
assert_eq!(aliases.expand(&original).as_deref(), Some(locator));
assert_eq!(aliases.expand("e1/demo").as_deref(), Some(locator));
assert_eq!(
aliases.root_lines_for(&std::collections::HashSet::from(["e1".to_string()])),
vec!["- `e1` = `skill://root/nested`"]
);
}
#[test]
fn alias_number_and_byte_budgets_are_shared_without_reassigning_existing_roots() {
let mut cloud = std::sync::Arc::new(AliasPlan::default());
let mut executor = std::sync::Arc::new(AliasPlan::default());
let mut budget = super::AliasBudget {
roots: super::MAX_ALIAS_ROOTS - 2,
..Default::default()
};
cloud.extend_alias_plan("c", ["skill://cloud"], &mut budget);
executor.extend_alias_plan("e", ["skill://first", "skill://second"], &mut budget);
assert_eq!(budget.roots, super::MAX_ALIAS_ROOTS);
assert_eq!(executor.root_lines(), vec!["- `e0` = `skill://first`"]);
assert_eq!(executor.shorten("skill://second/demo"), None);
assert_eq!(cloud.shorten("skill://cloud/demo"), Some("c0/demo".into()));
let mut budget = super::AliasBudget::default();
let mut aliases = std::sync::Arc::new(AliasPlan::default());
let oversized = "x".repeat(super::MAX_ALIAS_BYTES);
aliases.extend_alias_plan("e", ["skill://first", &oversized], &mut budget);
aliases.extend_alias_plan("e", ["skill://second"], &mut budget);
assert_eq!(
aliases.root_lines(),
vec!["- `e0` = `skill://first`", "- `e1` = `skill://second`"]
);
assert_eq!(aliases.shorten(&format!("{oversized}/demo")), None);
}

View File

@@ -0,0 +1,517 @@
//! Skill catalog data and reconciliation, retaining source-local policy and read routes.
use codex_extension_api::SelectedPluginSnapshot;
use codex_protocol::protocol::SkillScope;
use codex_skills::SkillDependencies;
use codex_utils_path_uri::PathUri;
use std::sync::Arc;
/// Source authority that owns a skill package and must be used to read it.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum SkillSourceKind {
/// Codex-hosted skills, including bundled, user, repo, plugin-installed,
/// and downloaded/materialized remote skills.
Host,
/// Skills owned by an execution environment.
Executor,
/// Skills owned by the cloud rather than an execution environment.
Cloud,
/// Extension-private source kind for future providers that do not fit an
/// existing transport category.
Custom(String),
}
impl SkillSourceKind {
pub fn custom(kind: impl Into<String>) -> Self {
Self::Custom(kind.into())
}
fn as_str(&self) -> &str {
match self {
Self::Host => "host",
Self::Executor => "executor",
Self::Cloud => "cloud",
Self::Custom(kind) => kind,
}
}
}
impl std::fmt::Display for SkillSourceKind {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.as_str().fmt(formatter)
}
}
/// Opaque authority identity for list/read routing.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct SkillAuthority {
pub kind: SkillSourceKind,
pub id: String,
}
impl SkillAuthority {
pub fn new(kind: SkillSourceKind, id: impl Into<String>) -> Self {
Self {
kind,
id: id.into(),
}
}
}
/// Opaque package id. Callers should not parse local paths out of this value.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct SkillPackageId(pub String);
impl SkillPackageId {
pub(crate) fn relative_resource_path<'a>(&self, resource: &'a str) -> Option<&'a str> {
let relative = resource
.strip_prefix(self.0.trim_end_matches('/'))?
.strip_prefix('/')?;
(!relative.is_empty()
&& relative
.split('/')
.all(|segment| !matches!(segment, "" | "." | "..")))
.then_some(relative)
}
}
/// Opaque resource id inside a skill package, optionally bound to the
/// environment path that owns its contents.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct SkillResourceId {
id: String,
environment_path: Option<EnvironmentSkillResource>,
}
impl SkillResourceId {
pub fn new(id: impl Into<String>) -> Self {
Self {
id: id.into(),
environment_path: None,
}
}
pub fn environment(
id: impl Into<String>,
environment_id: impl Into<String>,
path: PathUri,
) -> Self {
let package_root = path.parent().unwrap_or_else(|| path.clone());
Self {
id: id.into(),
environment_path: Some(EnvironmentSkillResource {
environment_id: environment_id.into(),
package_root,
path,
contents: None,
}),
}
}
pub fn environment_with_contents(
id: impl Into<String>,
environment_id: impl Into<String>,
path: PathUri,
contents: String,
) -> Self {
let package_root = path.parent().unwrap_or_else(|| path.clone());
Self {
id: id.into(),
environment_path: Some(EnvironmentSkillResource {
environment_id: environment_id.into(),
package_root,
path,
contents: Some(contents.into()),
}),
}
}
pub fn as_str(&self) -> &str {
&self.id
}
pub fn environment_id(&self) -> Option<&str> {
self.environment_path
.as_ref()
.map(|resource| resource.environment_id.as_str())
}
pub(crate) fn bind_environment_package_resource(
&self,
package: &SkillPackageId,
resource: impl Into<String>,
) -> Option<Self> {
let resource = resource.into();
let relative = package.relative_resource_path(&resource)?;
let environment = self.environment_path.as_ref()?;
let path = environment.package_root.join(relative).ok()?;
path.starts_with(&environment.package_root).then(|| Self {
id: resource,
environment_path: Some(EnvironmentSkillResource {
environment_id: environment.environment_id.clone(),
package_root: environment.package_root.clone(),
path,
contents: None,
}),
})
}
pub(crate) fn environment_path(&self) -> Option<(&str, &PathUri)> {
self.environment_path
.as_ref()
.map(|resource| (resource.environment_id.as_str(), &resource.path))
}
pub(crate) fn environment_contents(&self) -> Option<&str> {
self.environment_path
.as_ref()
.and_then(|resource| resource.contents.as_deref())
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct EnvironmentSkillResource {
environment_id: String,
package_root: PathUri,
path: PathUri,
contents: Option<Arc<str>>,
}
/// Skill metadata and source-owned read routes.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SkillCatalogEntry {
pub id: SkillPackageId,
pub authority: SkillAuthority,
pub name: String,
pub description: String,
pub short_description: Option<String>,
pub main_prompt: SkillResourceId,
pub display_path: Option<String>,
pub canonical_skill_id: Option<String>,
pub plugin_id: Option<String>,
pub analytics_scope: Option<SkillScope>,
/// Plugin-service identity for cross-source matching.
pub remote_plugin_id: Option<String>,
/// Alternate read routes that retain their original authority.
pub sources: Vec<SkillSourceLocation>,
alias_root: Option<String>,
alias_root_order: Option<usize>,
prompt_scope: Option<SkillScope>,
pub dependencies: Option<SkillDependencies>,
pub enabled: bool,
pub prompt_visible: bool,
}
impl SkillCatalogEntry {
pub fn new(
id: SkillPackageId,
authority: SkillAuthority,
name: impl Into<String>,
description: impl Into<String>,
main_prompt: SkillResourceId,
) -> Self {
Self {
id,
authority,
name: name.into(),
description: description.into(),
short_description: None,
main_prompt,
display_path: None,
canonical_skill_id: None,
plugin_id: None,
analytics_scope: None,
remote_plugin_id: None,
sources: Vec::new(),
alias_root: None,
alias_root_order: None,
prompt_scope: None,
dependencies: None,
enabled: true,
prompt_visible: true,
}
}
pub fn with_remote_plugin_id(mut self, remote_plugin_id: Option<String>) -> Self {
self.remote_plugin_id = remote_plugin_id;
self
}
pub fn with_plugin_id(mut self, plugin_id: Option<String>) -> Self {
self.plugin_id = plugin_id;
self
}
pub fn with_short_description(mut self, short_description: Option<String>) -> Self {
self.short_description = short_description;
self
}
pub fn with_display_path(mut self, display_path: impl Into<String>) -> Self {
self.display_path = Some(display_path.into());
self
}
/// Sets the shared locator prefix that may be compacted in model-visible skill catalogs.
pub fn with_alias_root(mut self, alias_root: impl Into<String>) -> Self {
self.alias_root = Some(alias_root.into());
self
}
pub(crate) fn with_alias_root_order(mut self, alias_root_order: usize) -> Self {
self.alias_root_order = Some(alias_root_order);
self
}
pub(crate) fn with_prompt_scope(mut self, prompt_scope: SkillScope) -> Self {
self.prompt_scope = Some(prompt_scope);
self
}
pub fn with_dependencies(mut self, dependencies: Option<SkillDependencies>) -> Self {
self.dependencies = dependencies;
self
}
pub fn disabled(mut self) -> Self {
self.enabled = false;
self
}
pub fn hidden_from_prompt(mut self) -> Self {
self.prompt_visible = false;
self
}
pub(crate) fn is_model_visible(&self) -> bool {
self.enabled && self.prompt_visible
}
pub(crate) fn primary_source(&self) -> SkillSourceLocation {
SkillSourceLocation {
authority: self.authority.clone(),
package: self.id.clone(),
main_prompt: self.main_prompt.clone(),
display_path: self.display_path.clone(),
plugin_id: self.plugin_id.clone(),
enabled: self.enabled,
alias_root: self.alias_root.clone(),
prompt_visible: self.prompt_visible,
}
}
pub(crate) fn source_locations(&self) -> impl Iterator<Item = SkillSourceLocation> + '_ {
std::iter::once(self.primary_source()).chain(self.sources.iter().cloned())
}
pub(crate) fn unaliased_locator(&self) -> &str {
match &self.authority.kind {
SkillSourceKind::Executor | SkillSourceKind::Cloud => self.id.0.as_str(),
SkillSourceKind::Host | SkillSourceKind::Custom(_) => self.rendered_path(),
}
}
pub(crate) fn rendered_path(&self) -> &str {
self.display_path
.as_deref()
.unwrap_or_else(|| self.main_prompt.as_str())
}
pub(crate) fn alias_root(&self) -> Option<&str> {
self.alias_root.as_deref()
}
pub(crate) fn alias_root_order(&self) -> Option<usize> {
self.alias_root_order
}
pub(crate) fn prompt_scope(&self) -> Option<SkillScope> {
self.prompt_scope
}
}
/// One original provider route retained by a reconciled skill.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SkillSourceLocation {
pub authority: SkillAuthority,
pub package: SkillPackageId,
pub main_prompt: SkillResourceId,
pub display_path: Option<String>,
/// Installation attribution belongs to the route used, not the merged primary entry.
pub plugin_id: Option<String>,
pub enabled: bool,
pub alias_root: Option<String>,
pub prompt_visible: bool,
}
/// Merged catalog for one turn.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct SkillCatalog {
pub entries: Vec<SkillCatalogEntry>,
pub warnings: Vec<String>,
pub is_partial: bool,
}
impl SkillCatalog {
pub fn extend(&mut self, other: SkillCatalog) {
for entry in other.entries {
self.push_entry(entry);
}
self.warnings.extend(other.warnings);
self.is_partial |= other.is_partial;
}
pub fn push_entry(&mut self, entry: SkillCatalogEntry) {
if self.entries.iter().any(|existing| {
existing.authority == entry.authority
&& existing.id == entry.id
&& existing.main_prompt.environment_id() == entry.main_prompt.environment_id()
}) {
return;
}
self.entries.push(entry);
}
}
/// Applies plugin denials and requires accepted Cloud or executor roots before merging skills.
pub(crate) fn apply_plugin_denials(catalog: &mut SkillCatalog, snapshot: &SelectedPluginSnapshot) {
for skill in &mut catalog.entries {
if !matches!(
skill.authority.kind,
SkillSourceKind::Cloud | SkillSourceKind::Executor
) {
continue;
}
// Standalone skills do not require plugin acceptance.
if skill.remote_plugin_id.is_none() && skill.plugin_id.is_none() {
continue;
}
let accepted = if skill.authority.kind == SkillSourceKind::Executor {
let (Some(environment_id), Some(plugin_id)) =
(skill.main_prompt.environment_id(), &skill.plugin_id)
else {
skill.enabled = false;
continue;
};
let root_id = format!("{environment_id}:{plugin_id}");
snapshot
.plugins
.iter()
.any(|plugin| plugin.selected_root_id.as_deref() == Some(root_id.as_str()))
} else {
let Some(remote_plugin_id) = &skill.remote_plugin_id else {
skill.enabled = false;
continue;
};
snapshot.plugins.iter().any(|plugin| {
plugin.selected_root_id.is_none() && plugin.plugin_id.as_str() == remote_plugin_id
})
};
skill.enabled &= skill
.remote_plugin_id
.as_ref()
.is_none_or(|id| !snapshot.disabled_plugin_ids.contains(id))
&& skill
.plugin_id
.as_ref()
.is_none_or(|id| !snapshot.disabled_plugin_ids.contains(id))
&& accepted;
}
}
fn remote_key(entry: &SkillCatalogEntry) -> Option<(&str, &str)> {
Some((entry.remote_plugin_id.as_deref()?, entry.name.as_str()))
}
/// Merges available Cloud counterparts, disabling unmatched remote skills only when Cloud is complete.
pub fn merge_catalogs(cloud: Option<SkillCatalog>, executor: SkillCatalog) -> SkillCatalog {
let Some(mut merged) = cloud else {
return executor;
};
let cloud_is_partial = merged.is_partial;
merged.is_partial |= executor.is_partial;
let cloud_entry_count = merged.entries.len();
merged.warnings.extend(executor.warnings);
for mut entry in executor.entries {
let Some(key) = remote_key(&entry) else {
merged.entries.push(entry);
continue;
};
// Executor entries cannot authorize or merge with one another.
let Some(cloud_entry) = merged.entries[..cloud_entry_count]
.iter_mut()
.find(|cloud_entry| remote_key(cloud_entry) == Some(key))
else {
if !cloud_is_partial {
entry.enabled = false;
for source in &mut entry.sources {
source.enabled = false;
}
}
merged.entries.push(entry);
continue;
};
let primary_source = entry.primary_source();
for mut source in std::iter::once(primary_source).chain(entry.sources) {
source.enabled &= cloud_entry.enabled;
let already_present = cloud_entry.sources.iter().any(|existing| {
existing.authority == source.authority
&& existing.package == source.package
&& existing.main_prompt.environment_id() == source.main_prompt.environment_id()
});
if !already_present {
cloud_entry.sources.push(source);
}
}
}
merged
}
/// Contents returned after resolving a skill resource through its owner.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SkillReadResult {
pub resource: SkillResourceId,
pub contents: String,
}
/// Search results for a package whose files are not readable through ordinary
/// executor filesystem access.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct SkillSearchResult {
pub matches: Vec<SkillSearchMatch>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SkillSearchMatch {
pub resource: SkillResourceId,
pub title: String,
pub snippet: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SkillProviderError {
pub message: String,
}
impl SkillProviderError {
pub fn new(message: impl Into<String>) -> Self {
Self {
message: message.into(),
}
}
}
impl std::fmt::Display for SkillProviderError {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.message.fmt(formatter)
}
}
impl std::error::Error for SkillProviderError {}
pub type SkillProviderResult<T> = Result<T, SkillProviderError>;
#[cfg(test)]
#[path = "catalog_tests.rs"]
mod tests;

View File

@@ -0,0 +1,409 @@
//! Publishes skill changes within one metadata budget per context window.
//! Each snapshot remembers the full inventory and which skills the model has seen.
//! Compaction starts a fresh listing and budget.
use std::collections::BTreeMap;
use std::sync::LazyLock;
use codex_extension_api::ContextualUserFragment;
use codex_extension_api::PreviousWorldStateSection;
use codex_extension_api::RenderedWorldStateFragment;
use codex_extension_api::WorldStateSectionContribution;
use codex_protocol::models::ContentItemMetadata;
use codex_protocol::models::input_text;
use codex_protocol::protocol::SKILLS_INSTRUCTIONS_CLOSE_TAG;
use codex_protocol::protocol::SKILLS_INSTRUCTIONS_OPEN_TAG;
use serde::Deserialize;
use serde::Serialize;
use serde_json::json;
use crate::aliases::AliasRoot;
use crate::catalog_prompt::SkillPrompt;
use crate::catalog_prompt::SkillPromptKind;
use crate::fragments::AvailableSkillsInstructions;
use crate::render::AvailableSkillsRender;
use crate::render::SkillMetadataBudget;
use crate::render::SkillRenderReport;
use crate::render::aliased_metadata_overhead_cost;
use crate::render::metadata_line_cost;
use crate::world_state_catalogs::CatalogBudgetAllocation;
const SNAPSHOT_VERSION: u8 = 1;
const ROOTS_HEADING: &str =
"### Skill roots\nThese mappings replace earlier mappings for the same aliases.\n";
const SKILLS_HEADING: &str = "### Added or updated skills:\n";
const REVALIDATE_SKILLS: &str = "Some previously listed skills are no longer available. Verify current access before relying on a skill from this source.\n";
const RESTORED_SKILLS: &str = "Some previously unavailable skills are available again. Verify current access before relying on a skill from this source.\n";
#[derive(Clone, Copy, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) enum GrantStatus {
Active,
Withdrawn,
}
#[derive(Deserialize, Serialize)]
pub(crate) struct SkillEntrySnapshot {
pub(crate) fingerprint: String,
pub(crate) shown: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) grant: Option<GrantStatus>,
}
pub(crate) struct CatalogSkill {
pub(crate) snapshot: SkillEntrySnapshot,
pub(crate) line: String,
pub(crate) root: Option<AliasRoot>,
}
/// Retain both units so switching budget units cannot refund earlier emissions.
#[derive(Clone, Copy, Default, Deserialize, Serialize)]
pub(crate) struct CatalogUsage {
tokens: usize,
characters: usize,
}
impl CatalogUsage {
fn measure(cost: impl Fn(SkillMetadataBudget) -> usize) -> Self {
Self {
tokens: cost(SkillMetadataBudget::Tokens(0)),
characters: cost(SkillMetadataBudget::Characters(0)),
}
}
pub(crate) fn cost(self, budget: SkillMetadataBudget) -> usize {
match budget {
SkillMetadataBudget::Tokens(_) => self.tokens,
SkillMetadataBudget::Characters(_) => self.characters,
}
}
}
#[derive(Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
struct CatalogSnapshot {
version: u8,
entries: BTreeMap<String, SkillEntrySnapshot>,
roots: BTreeMap<String, String>,
usage: CatalogUsage,
instructions_sent: bool,
#[serde(default)]
omit_descriptions: bool,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
tracks_grants: bool,
allocation: Option<CatalogBudgetAllocation>,
}
pub(crate) struct CatalogDelta {
pub(crate) rendered: Option<AvailableSkillsRender>,
pub(crate) include_usage: bool,
pub(crate) tracks_grants: bool,
pub(crate) allocation: Option<CatalogBudgetAllocation>,
}
struct CatalogResult {
snapshot: CatalogSnapshot,
body: Option<String>,
report: SkillRenderReport,
}
pub(crate) fn skills_delta_section(
id: &'static str,
source: &'static str,
catalog: CatalogDelta,
previous: Option<&serde_json::Value>,
remaining: &mut SkillMetadataBudget,
on_render: impl Fn(&SkillRenderReport) + Send + Sync + 'static,
) -> WorldStateSectionContribution {
// Updates share their remaining budget in source order. A full render, including
// the one requested by compaction, always starts from the bounded initial listing.
let update = previous
.and_then(|value| CatalogSnapshot::deserialize(value).ok())
.filter(|snapshot| snapshot.version == SNAPSHOT_VERSION)
.map(|previous| build_catalog_update(source, &catalog, previous, remaining));
let initial = LazyLock::new(move || build_initial_catalog(source, catalog));
WorldStateSectionContribution::new(id, move |previous| {
let result = match previous {
PreviousWorldStateSection::Known(_) => update.as_ref().unwrap_or_else(|| &initial),
PreviousWorldStateSection::Absent | PreviousWorldStateSection::Unknown => &initial,
};
if result.body.is_some() || result.report.omitted_count > 0 {
on_render(&result.report);
}
let fragment = result.body.as_ref().map(|body| {
RenderedWorldStateFragment::new(
"developer",
(SKILLS_INSTRUCTIONS_OPEN_TAG, SKILLS_INSTRUCTIONS_CLOSE_TAG),
input_text(body.clone()),
)
.with_metadata(ContentItemMetadata::skills())
});
(Some(json!(result.snapshot)), fragment)
})
.with_legacy_matcher(|role, text| {
role == "developer"
&& text.trim_start().starts_with(SKILLS_INSTRUCTIONS_OPEN_TAG)
&& text.trim_end().ends_with(SKILLS_INSTRUCTIONS_CLOSE_TAG)
})
}
fn build_initial_catalog(source: &str, catalog: CatalogDelta) -> CatalogResult {
let mut snapshot = CatalogSnapshot {
version: SNAPSHOT_VERSION,
allocation: catalog.allocation,
tracks_grants: catalog.tracks_grants,
..CatalogSnapshot::default()
};
let mut report = SkillRenderReport::default();
let body = catalog.rendered.and_then(|mut rendered| {
report = std::mem::take(&mut rendered.report);
let usage =
CatalogUsage::measure(|budget| rendered.metadata_cost(budget, catalog.include_usage));
let entries = std::mem::take(&mut rendered.entries);
snapshot.omit_descriptions = rendered.prompt.omit_descriptions;
let fragment = rendered.into_fragment(catalog.include_usage);
for (id, skill) in entries {
if fragment.is_some()
&& let Some(root) = skill.root
{
snapshot.roots.insert(root.name, root.value.to_string());
}
snapshot.entries.insert(id, skill.snapshot);
}
let fragment = fragment?;
snapshot.instructions_sent = true;
snapshot.usage = usage;
Some(listing_body(source, fragment))
});
CatalogResult {
snapshot,
report,
body,
}
}
fn build_catalog_update(
source: &str,
catalog: &CatalogDelta,
mut previous: CatalogSnapshot,
remaining: &mut SkillMetadataBudget,
) -> CatalogResult {
let usage_update = catalog.rendered.as_ref().filter(|rendered| {
previous.instructions_sent
&& catalog.include_usage
&& previous.omit_descriptions != rendered.prompt.omit_descriptions
});
let message = if previous.instructions_sent {
CatalogMessage::Update {
heading: format!("\n## {source} skills update\n"),
}
} else {
CatalogMessage::FirstListing {
prompt: catalog.rendered.as_ref().map_or(
SkillPrompt {
kind: SkillPromptKind::Unaliased,
omit_descriptions: false,
},
|r| r.prompt,
),
include_usage: catalog.include_usage,
}
};
let mut draft = UpdateDraft {
message,
skill_lines: Vec::new(),
root_lines: Vec::new(),
};
let mut report = SkillRenderReport::default();
let mut entries = BTreeMap::new();
// Older snapshots did not record which shown skills depended on a grant.
let legacy_filesystem = catalog.tracks_grants && !previous.tracks_grants;
let mut restored = false;
for (id, skill) in catalog.rendered.iter().flat_map(|r| &r.entries) {
let old = previous.entries.get(id);
restored |= old.is_some_and(|old| old.grant == Some(GrantStatus::Withdrawn));
let mut shown = old.is_some_and(|old| old.shown);
// A grant doesn't make a skill temporary if the model already saw it without one.
let grant = skill.snapshot.grant.filter(|_| {
legacy_filesystem || old.is_none_or(|old| !old.shown || old.grant.is_some())
});
if old.is_none_or(|old| old.shown && old.fingerprint != skill.snapshot.fingerprint) {
report.total_count += 1;
if draft.try_append_skill(skill, &mut previous, remaining) {
shown = true;
report.included_count += 1;
} else {
report.omitted_count += 1;
}
}
entries.insert(
id.clone(),
SkillEntrySnapshot {
fingerprint: skill.snapshot.fingerprint.clone(),
shown,
grant,
},
);
}
let mut body = draft.into_body(source);
let mut withdrew = false;
// Keep only withdrawals the model has seen. Their count is bounded by the listing budget.
for (id, mut old) in previous.entries {
if old.shown && (old.grant.is_some() || legacy_filesystem) && !entries.contains_key(&id) {
withdrew |= old.grant != Some(GrantStatus::Withdrawn);
old.grant = Some(GrantStatus::Withdrawn);
entries.insert(id, old);
}
}
for notice in [
withdrew.then_some(REVALIDATE_SKILLS),
restored.then_some(RESTORED_SKILLS),
]
.into_iter()
.flatten()
{
body.get_or_insert_with(|| format!("\n## {source} skills update\n"))
.push_str(notice);
}
previous.tracks_grants = catalog.tracks_grants;
if let Some(rendered) = usage_update {
let instructions = rendered.prompt.usage_instructions();
body.get_or_insert_with(|| format!("\n## {source} skills update\n"))
.push_str(&format!("\n### How to use skills\n{instructions}\n"));
}
if let Some(rendered) = &catalog.rendered {
previous.omit_descriptions = rendered.prompt.omit_descriptions;
}
previous.entries = entries;
previous.instructions_sent |= body.is_some();
previous.allocation = catalog.allocation;
CatalogResult {
snapshot: previous,
report,
body,
}
}
fn listing_body(source: &str, instructions: AvailableSkillsInstructions) -> String {
format!(
"\n## {source} skills\n{}",
instructions.body().into_text().unwrap_or_default()
)
}
enum CatalogMessage {
FirstListing {
prompt: SkillPrompt,
include_usage: bool,
},
Update {
heading: String,
},
}
struct UpdateDraft {
message: CatalogMessage,
skill_lines: Vec<String>,
root_lines: Vec<String>,
}
impl UpdateDraft {
fn try_append_skill(
&mut self,
skill: &CatalogSkill,
snapshot: &mut CatalogSnapshot,
remaining: &mut SkillMetadataBudget,
) -> bool {
let new_mapping = skill
.root
.as_ref()
.filter(|root| {
snapshot.roots.get(&root.name).map(String::as_str) != Some(root.value.as_ref())
})
.map(|root| (root, root.line()));
let cost = CatalogUsage::measure(|budget| {
let mut cost = metadata_line_cost(budget, &skill.line);
if let CatalogMessage::Update { heading } = &self.message
&& self.skill_lines.is_empty()
{
cost += budget.cost(heading) + budget.cost(SKILLS_HEADING);
}
if let Some((_, line)) = &new_mapping {
cost += match &self.message {
CatalogMessage::FirstListing {
prompt,
include_usage,
} if self.root_lines.is_empty() => aliased_metadata_overhead_cost(
budget,
*prompt,
std::slice::from_ref(line),
*include_usage,
),
CatalogMessage::Update { .. } if self.root_lines.is_empty() => {
budget.cost(ROOTS_HEADING) + metadata_line_cost(budget, line)
}
CatalogMessage::FirstListing { .. } | CatalogMessage::Update { .. } => {
metadata_line_cost(budget, line)
}
};
}
cost
});
let charge = cost.cost(*remaining);
if charge > remaining.limit() {
return false;
}
*remaining = remaining.with_limit(remaining.limit() - charge);
snapshot.usage.tokens += cost.tokens;
snapshot.usage.characters += cost.characters;
if let Some((root, line)) = new_mapping {
snapshot
.roots
.insert(root.name.clone(), root.value.to_string());
self.root_lines.push(line);
}
self.skill_lines.push(skill.line.clone());
true
}
fn into_body(self, source: &str) -> Option<String> {
if self.skill_lines.is_empty() {
return None;
}
Some(match self.message {
CatalogMessage::FirstListing {
mut prompt,
include_usage,
} => {
if self.root_lines.is_empty() {
prompt.kind = SkillPromptKind::Unaliased;
}
listing_body(
source,
AvailableSkillsInstructions::from_skill_lines(
prompt,
self.root_lines,
self.skill_lines,
include_usage,
),
)
}
CatalogMessage::Update { mut heading } => {
if !self.root_lines.is_empty() {
heading.push_str(ROOTS_HEADING);
heading.push_str(&self.root_lines.join("\n"));
heading.push('\n');
}
heading.push_str(SKILLS_HEADING);
heading.push_str(&self.skill_lines.join("\n"));
heading.push('\n');
heading
}
})
}
}
#[cfg(test)]
#[path = "catalog_delta_tests.rs"]
mod tests;

View File

@@ -0,0 +1,47 @@
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn update_spends_budget_only_on_accepted_rows_and_their_new_roots() {
let mut draft = UpdateDraft {
message: CatalogMessage::Update {
heading: "\n## Cloud skills update\n".to_string(),
},
skill_lines: Vec::new(),
root_lines: Vec::new(),
};
let skill = |line: &str, alias: &str, root: &str| CatalogSkill {
snapshot: SkillEntrySnapshot {
fingerprint: String::new(),
shown: false,
grant: None,
},
line: line.to_string(),
root: Some(AliasRoot {
name: alias.to_string(),
value: root.into(),
}),
};
let notes = skill(
"- release-notes: (cloud package: c0/notes)",
"c0",
"skill://writing",
);
let docs = skill("- docs: (cloud package: c0/docs)", "c0", "skill://writing");
let expected = "\n## Cloud skills update\n### Skill roots\nThese mappings replace earlier mappings for the same aliases.\n- `c0` = `skill://writing`\n### Added or updated skills:\n- release-notes: (cloud package: c0/notes)\n- docs: (cloud package: c0/docs)\n";
let mut remaining = SkillMetadataBudget::Characters(expected.chars().count());
let mut snapshot = CatalogSnapshot::default();
let large = skill(&"a".repeat(remaining.limit()), "c1", "skill://design");
assert!(!draft.try_append_skill(&large, &mut snapshot, &mut remaining));
assert!(draft.try_append_skill(&notes, &mut snapshot, &mut remaining));
assert!(draft.try_append_skill(&docs, &mut snapshot, &mut remaining));
assert_eq!(draft.into_body("Cloud").as_deref(), Some(expected));
assert_eq!(
snapshot.roots,
BTreeMap::from([("c0".into(), "skill://writing".into())])
);
assert_eq!(snapshot.usage.characters, expected.chars().count());
assert_eq!(remaining, SkillMetadataBudget::Characters(0));
}

View File

@@ -0,0 +1,20 @@
//! Measures published skill catalogs, excluding cached reads.
use crate::catalog::SkillCatalog;
use codex_extension_api::ExtensionMetrics;
use codex_extension_api::record_catalog_entries;
pub(crate) fn record_catalog(
metrics: Option<&dyn ExtensionMetrics>,
stage: &'static str,
catalog: &SkillCatalog,
) {
record_catalog_entries(
metrics,
"codex.skills.catalog.entries",
stage,
catalog.entries.len(),
catalog.is_partial,
catalog.warnings.len(),
);
}

View File

@@ -0,0 +1,133 @@
use crate::catalog::SkillSourceKind;
const SKILLS_INTRO_WITH_SOURCE_LOCATORS: &str = "A skill is a set of instructions provided through a `SKILL.md` source. Below is the list of skills that can be used. Each entry includes a name, description, and source locator. `file` locators are on the host filesystem, `executor package` locators are owned by their execution environment, `cloud package` locators are opaque package identifiers, and `custom resource` locators use their provider's access mechanism.";
const SKILLS_INTRO_WITH_HOST_ALIASES: &str = "A skill is a set of local instructions to follow that is stored in a `SKILL.md` file. Below is the list of skills that can be used. Each entry includes a name, description, and a short path that can be expanded into an absolute path using the skill roots table.";
const SKILLS_INTRO_WITH_RESOURCE_ALIASES: &str = "A skill is a set of instructions provided through a `SKILL.md` source. Below is the list of skills that can be used. Each entry includes a name, description, and source locator. Short locators can be expanded using the skill roots table.";
const RESOURCE_ALIAS_INSTRUCTIONS: &str = "- Root aliases: Pass short package locators directly to `skills.read`; it resolves their matching alias from `### Skill roots`.";
const SKILLS_HOW_TO_USE_WITH_SOURCE_LOCATORS: &str = r###"- Discovery: The list above is the skills available in this session (name + description + source locator). `file` entries live on the host filesystem, `executor package` and `cloud package` entries are accessed directly through `skills.read`, and `custom resource` entries use their provider's access mechanism.
- Trigger rules: If the user names a skill (with `$SkillName` or plain text) OR the task clearly matches a skill's description shown above, you must use that skill for that turn. Multiple mentions mean use them all. Do not carry skills across turns unless re-mentioned.
- Missing/blocked: If a named skill isn't in the list or its source can't be read, say so briefly and continue with the best fallback.
- How to use a skill (progressive disclosure):
1) After deciding to use a skill, the main agent must read its `SKILL.md` completely before taking task actions. For a `file` entry, open the listed path. For an `executor package` or `cloud package`, pass the listed locator directly to `skills.read` as `package`; root aliases are resolved automatically. Omit `resource` to read `SKILL.md` directly without calling `skills.list`. If a read is paginated, follow `next_cursor` until EOF.
2) When `SKILL.md` references another resource, use the same access mechanism. For executor and cloud skills, pass the complete package-contained resource identifier with the same package to `skills.read`; do not treat `skill://` identifiers as filesystem paths.
3) If `SKILL.md` points to extra folders such as `references/`, use its routing instructions to identify the resources required for the task. The main agent must read each required instruction or reference file itself before acting on it. Do not delegate reading, summarizing, or interpreting skill instructions to a subagent. Subagents may still perform task work when the selected skill allows it.
4) For filesystem-backed skills, prefer running or patching provided scripts instead of retyping large code blocks. For executor and cloud skills, use `skills.read` and the available tools; do not invent a local path.
5) Reuse provided assets or templates through the same source access mechanism instead of recreating them.
- Coordination and sequencing:
- If multiple skills apply, choose the minimal set that covers the request and state the order you'll use them.
- Announce which skill(s) you're using and why (one short line). If you skip an obvious skill, say why.
- Context hygiene:
- Progressive disclosure applies to selecting relevant files, not partially reading a selected instruction file. Do not load unrelated references, scripts, or assets.
- Avoid deep reference-chasing: prefer opening only files directly linked from `SKILL.md` unless you're blocked.
- When variants exist (frameworks, providers, domains), pick only the relevant reference file(s) and note that choice.
- Safety and fallback: If a skill can't be applied cleanly (missing files, unclear instructions), state the issue, pick the next-best approach, and continue."###;
const SKILLS_HOW_TO_USE_WITH_HOST_ALIASES: &str = r###"- Discovery: The list above is the skills available in this session (name + description + short path). Skill bodies live on disk at the listed paths after expanding the matching alias from `### Skill roots`.
- Trigger rules: If the user names a skill (with `$SkillName` or plain text) OR the task clearly matches a skill's description shown above, you must use that skill for that turn. Multiple mentions mean use them all. Do not carry skills across turns unless re-mentioned.
- Missing/blocked: If a named skill isn't in the list or the path can't be read, say so briefly and continue with the best fallback.
- How to use a skill (progressive disclosure):
1) After deciding to use a skill, the main agent must expand the listed short `path` with the matching alias from `### Skill roots`, then open and read its `SKILL.md` completely before taking task actions. If a read is truncated or paginated, continue until EOF.
2) When `SKILL.md` references relative paths (e.g., `scripts/foo.py`), resolve them relative to the directory containing that expanded `SKILL.md` first, and only consider other paths if needed.
3) If `SKILL.md` points to extra folders such as `references/`, use its routing instructions to identify the files required for the task. The main agent must read each required instruction or reference file itself before acting on it. Do not delegate reading, summarizing, or interpreting skill instructions to a subagent. Subagents may still perform task work when the selected skill allows it.
4) If `scripts/` exist, prefer running or patching them instead of retyping large code blocks.
5) If `assets/` or templates exist, reuse them instead of recreating from scratch.
- Coordination and sequencing:
- If multiple skills apply, choose the minimal set that covers the request and state the order you'll use them.
- Announce which skill(s) you're using and why (one short line). If you skip an obvious skill, say why.
- Context hygiene:
- Progressive disclosure applies to selecting relevant files, not partially reading a selected instruction file. Do not load unrelated references, scripts, or assets.
- Avoid deep reference-chasing: prefer opening only files directly linked from `SKILL.md` unless you're blocked.
- When variants exist (frameworks, providers, domains), pick only the relevant reference file(s) and note that choice.
- Safety and fallback: If a skill can't be applied cleanly (missing files, unclear instructions), state the issue, pick the next-best approach, and continue."###;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum SkillPromptKind {
Unaliased,
HostAliases,
ResourceAliases,
ResourceAliasesV2,
}
impl SkillPromptKind {
pub(crate) fn for_aliased_source(source: &SkillSourceKind) -> Self {
match source {
SkillSourceKind::Host => Self::HostAliases,
SkillSourceKind::Executor | SkillSourceKind::Cloud => Self::ResourceAliases,
SkillSourceKind::Custom(_) => Self::Unaliased,
}
}
fn intro(self) -> &'static str {
match self {
Self::Unaliased => SKILLS_INTRO_WITH_SOURCE_LOCATORS,
Self::HostAliases => SKILLS_INTRO_WITH_HOST_ALIASES,
Self::ResourceAliases | Self::ResourceAliasesV2 => SKILLS_INTRO_WITH_RESOURCE_ALIASES,
}
}
pub(crate) fn alias_instructions(self) -> Option<&'static str> {
match self {
Self::ResourceAliases | Self::ResourceAliasesV2 => Some(RESOURCE_ALIAS_INSTRUCTIONS),
Self::Unaliased | Self::HostAliases => None,
}
}
}
/// Prompt layout and description policy shared by rendering and budget accounting.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct SkillPrompt {
pub(crate) kind: SkillPromptKind,
pub(crate) omit_descriptions: bool,
}
impl SkillPrompt {
pub(crate) fn usage_instructions(self) -> String {
let instructions = match self.kind {
SkillPromptKind::Unaliased
| SkillPromptKind::ResourceAliases
| SkillPromptKind::ResourceAliasesV2 => SKILLS_HOW_TO_USE_WITH_SOURCE_LOCATORS,
SkillPromptKind::HostAliases => SKILLS_HOW_TO_USE_WITH_HOST_ALIASES,
};
if self.omit_descriptions {
instructions
.replace("name + description +", "name +")
.replace("description shown above", "name shown above")
} else {
instructions.to_owned()
}
}
}
pub(crate) fn render_available_skills_body(
prompt: SkillPrompt,
skill_root_lines: &[String],
skill_lines: &[String],
) -> String {
let mut lines: Vec<String> = Vec::new();
lines.push("## Skills".to_string());
let intro = prompt.kind.intro();
lines.push(if prompt.omit_descriptions {
intro.replace("name, description, and", "name and")
} else {
intro.to_string()
});
if !skill_root_lines.is_empty() {
lines.push("### Skill roots".to_string());
if prompt.kind == SkillPromptKind::ResourceAliasesV2 {
lines.push("For each alias listed below, this mapping replaces any earlier mapping for that alias. Use it for subsequent skill calls.".to_string());
}
lines.extend(skill_root_lines.iter().cloned());
}
if skill_lines
.iter()
.any(|line| line.contains("(executor package: ") || line.contains("(cloud package: "))
{
lines.push(
"Read a skill package directly with `skills.read({\"package\":\"<package>\"})` to read its `SKILL.md`; root aliases are resolved automatically. To read another file from that skill, use the same `package` and pass the file's complete `skill://` identifier as `resource`. If the package is not provided, use `skills.list` to find it."
.to_string(),
);
}
lines.push("### Available skills".to_string());
lines.extend(skill_lines.iter().cloned());
format!("\n{}\n", lines.join("\n"))
}

View File

@@ -0,0 +1,245 @@
//! Reusable provider catalog caches and Cloud resource contents.
//! Provider catalogs remain unfiltered until step preparation applies policy.
//! Cloud discovery publishes only into its current auth and resource generation.
use std::collections::HashMap;
use std::sync::Arc;
use codex_exec_server::EnvironmentAccessKey;
use codex_exec_server::ExecutorCapabilityDiscoverySnapshot;
use codex_extension_api::CatalogRefreshBackoff;
use codex_mcp::McpResourceClient;
use codex_mcp::McpResourceClientAuthKey;
use codex_mcp::McpResourceServerCacheKey;
use codex_protocol::capabilities::SelectedCapabilityRoot;
use crate::catalog::SkillAuthority;
use crate::catalog::SkillCatalog;
use crate::catalog::SkillPackageId;
use crate::catalog::SkillReadResult;
use crate::catalog::SkillResourceId;
use crate::provider::SkillReadRequest;
const MAX_CACHED_CLOUD_RESOURCES: usize = 100;
const MAX_CACHED_CLOUD_CONTENT_BYTES: usize = 8 * 1024 * 1024;
/// Reusable provider catalogs, before step-specific plugin policy and merging.
#[derive(Clone, Debug, Default)]
pub(crate) struct SkillCatalogState {
// Roots-only discovery, reused within a turn.
pub(crate) executor_cache: Option<CachedExecutorCatalog>,
// DiscoveryV1.
pub(crate) executor_discovery_cache: Option<CachedExecutorDiscoveryCatalog>,
// DiscoveryV2.
pub(crate) executor_v2_cache: Option<CachedExecutorV2Catalog>,
// Shared by both discovery modes.
pub(crate) cloud_generation: Option<Arc<CloudSkillGeneration>>,
pub(crate) cloud_retry: Option<CatalogRefreshBackoff>,
pub(crate) cloud_resources: CloudResourceCache,
}
impl SkillCatalogState {
/// Reuses the auth scope or replaces it, clearing contents from the previous scope.
pub(crate) fn prepare_cloud_generation(
&mut self,
mcp_resources: Option<&McpResourceClient>,
) -> Arc<CloudSkillGeneration> {
let auth_cache_key = mcp_resources
.map(|client| client.auth_cache_key_for_server(codex_mcp::CODEX_APPS_MCP_SERVER_NAME));
if let Some(generation) = self
.cloud_generation
.as_ref()
.filter(|generation| generation.auth_cache_key == auth_cache_key)
{
return Arc::clone(generation);
}
let generation = Arc::new(CloudSkillGeneration {
auth_cache_key,
resource_cache_key: None,
mcp_resources: mcp_resources.cloned(),
catalog: None,
});
self.cloud_generation = Some(Arc::clone(&generation));
self.cloud_resources = CloudResourceCache::default();
generation
}
}
/// Keeps cloud metadata within one published auth scope and Apps availability state.
/// Warning-free discovery is reused until the Apps resource generation changes.
/// A published refresh replaces the Arc so late reads cannot populate its successor.
pub(crate) struct CloudSkillGeneration {
pub(crate) auth_cache_key: Option<McpResourceClientAuthKey>,
pub(crate) resource_cache_key: Option<McpResourceServerCacheKey>,
pub(crate) mcp_resources: Option<McpResourceClient>,
pub(crate) catalog: Option<SkillCatalog>,
}
impl CloudSkillGeneration {
pub(crate) fn current_resource_cache_key(&self) -> Option<McpResourceServerCacheKey> {
self.mcp_resources
.as_ref()
.and_then(|client| client.server_cache_key(codex_mcp::CODEX_APPS_MCP_SERVER_NAME))
}
pub(crate) fn is_auth_current(&self) -> bool {
self.auth_cache_key
== self.mcp_resources.as_ref().map(|client| {
client.auth_cache_key_for_server(codex_mcp::CODEX_APPS_MCP_SERVER_NAME)
})
}
}
impl std::fmt::Debug for CloudSkillGeneration {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("CloudSkillGeneration")
.field("catalog", &self.catalog)
.finish_non_exhaustive()
}
}
/// Reuses the projection of unchanged successful V2 inventories, before plugin policy.
#[derive(Clone, Debug)]
pub(crate) struct CachedExecutorV2Catalog {
pub(crate) snapshots: Vec<codex_exec_server::ExecutorCapabilityDiscoveryV2Snapshot>,
pub(crate) catalog: SkillCatalog,
}
impl CachedExecutorV2Catalog {
pub(crate) fn same_discovery(
&self,
snapshots: &[codex_exec_server::ExecutorCapabilityDiscoveryV2Snapshot],
) -> bool {
self.snapshots.len() == snapshots.len()
&& self
.snapshots
.iter()
.zip(snapshots)
.all(|(previous, current)| previous.same_discovery(current))
}
}
#[derive(Clone, Debug)]
pub(crate) struct ExecutorCatalogCacheKey {
pub(crate) turn_id: String,
pub(crate) roots: Vec<(SelectedCapabilityRoot, EnvironmentAccessKey)>,
pub(crate) include_bundled_skills: bool,
}
impl ExecutorCatalogCacheKey {
pub(crate) fn matches(&self, query: &crate::provider::SkillListQuery<'_>) -> bool {
self.turn_id == query.turn_id
&& self.include_bundled_skills == query.include_bundled_skills
&& self.roots.len() == query.executor_roots.len()
&& self
.roots
.iter()
.zip(&query.executor_roots)
.all(|((root, access), current)| {
root == current.root && *access == current.fs.cache_key()
})
}
}
#[derive(Clone, Debug)]
pub(crate) struct CachedExecutorCatalog {
pub(crate) key: ExecutorCatalogCacheKey,
pub(crate) catalog: SkillCatalog,
}
/// Keeps the latest result; only successful results for unchanged inputs can be reused.
#[derive(Clone, Debug)]
pub(crate) struct CachedExecutorDiscoveryCatalog {
pub(crate) discovery: ExecutorCapabilityDiscoverySnapshot,
pub(crate) include_bundled_skills: bool,
pub(crate) catalog: SkillCatalog,
}
impl CachedExecutorDiscoveryCatalog {
pub(crate) fn matches(
&self,
discovery: Option<&ExecutorCapabilityDiscoverySnapshot>,
include_bundled_skills: bool,
) -> bool {
discovery.is_some_and(|discovery| {
self.include_bundled_skills == include_bundled_skills
&& self.discovery.sandbox_contexts() == discovery.sandbox_contexts()
&& self.discovery.roots().len() == discovery.roots().len()
&& self.discovery.roots().iter().zip(discovery.roots()).all(
|(previous, current)| {
previous.selected_root == current.selected_root
&& match (&previous.result, &current.result) {
(Ok(previous), Ok(current)) => Arc::ptr_eq(previous, current),
(Err(previous), Err(current)) => previous == current,
(Ok(_), Err(_)) | (Err(_), Ok(_)) => false,
}
},
)
})
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub(crate) struct SkillReadCacheKey {
authority: SkillAuthority,
package: SkillPackageId,
pub(crate) resource: SkillResourceId,
}
impl From<&SkillReadRequest<'_>> for SkillReadCacheKey {
fn from(request: &SkillReadRequest<'_>) -> Self {
Self {
authority: request.authority.clone(),
package: request.package.clone(),
resource: request.resource.clone(),
}
}
}
#[derive(Clone, Default)]
pub(crate) struct CloudResourceCache {
entries: HashMap<SkillReadCacheKey, SkillReadResult>,
contents_bytes: usize,
}
impl CloudResourceCache {
pub(crate) fn get(&self, key: &SkillReadCacheKey) -> Option<SkillReadResult> {
self.entries.get(key).cloned()
}
pub(crate) fn insert(
&mut self,
key: SkillReadCacheKey,
result: SkillReadResult,
) -> SkillReadResult {
if let Some(cached) = self.entries.get(&key) {
return cached.clone();
}
let contents_bytes = result.contents.len();
let Some(next_contents_bytes) = self.contents_bytes.checked_add(contents_bytes) else {
return result;
};
if self.entries.len() >= MAX_CACHED_CLOUD_RESOURCES
|| next_contents_bytes > MAX_CACHED_CLOUD_CONTENT_BYTES
{
return result;
}
self.contents_bytes = next_contents_bytes;
self.entries.insert(key, result.clone());
result
}
}
impl std::fmt::Debug for CloudResourceCache {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("CloudResourceCache")
.field("entry_count", &self.entries.len())
.field("contents_bytes", &self.contents_bytes)
.finish_non_exhaustive()
}
}

View File

@@ -0,0 +1,77 @@
//! Tests partial Cloud reconciliation without changing source-specific enablement.
use super::*;
use pretty_assertions::assert_eq;
fn skill(kind: SkillSourceKind, name: &str) -> SkillCatalogEntry {
SkillCatalogEntry::new(
SkillPackageId(format!("skill://{kind}/{name}")),
SkillAuthority::new(kind.clone(), kind.to_string()),
name,
"",
SkillResourceId::new(format!("skill://{kind}/{name}/SKILL.md")),
)
.with_remote_plugin_id(Some("plugin_a".to_string()))
}
#[test]
fn partial_cloud_merges_matches_without_disabling_unmatched_installations() {
for (cloud_is_partial, cloud_has_match) in [
(None, false),
(Some(false), false),
(Some(true), false),
(Some(false), true),
(Some(true), true),
] {
for executor_is_partial in [false, true] {
let cloud_entry = skill(SkillSourceKind::Cloud, "matched");
let matched = skill(SkillSourceKind::Executor, "matched").disabled();
let mut unmatched = skill(SkillSourceKind::Executor, "unmatched");
let mut denied_source = unmatched.primary_source();
denied_source.enabled = false;
unmatched.sources.push(denied_source);
let denied = skill(SkillSourceKind::Executor, "denied").disabled();
let mut executor = SkillCatalog::default();
executor.extend(SkillCatalog {
entries: vec![matched.clone(), unmatched.clone(), denied.clone()],
is_partial: executor_is_partial,
..Default::default()
});
// Appending a complete provider must not clear an earlier partial result.
executor.extend(SkillCatalog::default());
let cloud = cloud_is_partial.map(|is_partial| SkillCatalog {
entries: if cloud_has_match {
vec![cloud_entry.clone()]
} else {
Vec::new()
},
is_partial,
// Diagnostic warnings alone do not make membership incomplete.
warnings: vec!["diagnostic".to_string()],
});
let expected_match = if cloud_has_match {
let mut entry = cloud_entry;
entry.sources.push(matched.primary_source());
entry
} else {
matched
};
if cloud_is_partial == Some(false) {
unmatched.enabled = false;
}
assert_eq!(
merge_catalogs(cloud, executor),
SkillCatalog {
entries: vec![expected_match, unmatched, denied],
warnings: if cloud_is_partial.is_some() {
vec!["diagnostic".to_string()]
} else {
Vec::new()
},
is_partial: cloud_is_partial.unwrap_or(false) || executor_is_partial,
},
"cloud_is_partial={cloud_is_partial:?}, cloud_has_match={cloud_has_match}, executor_is_partial={executor_is_partial}",
);
}
}
}

View File

@@ -0,0 +1,620 @@
//! Tests cloud cache isolation, refresh retries, and late completion.
use super::*;
use crate::catalog::SkillCatalogEntry;
use crate::catalog::SkillResourceId;
use crate::catalog::SkillSearchResult;
use crate::provider::SkillProvider;
use crate::provider::SkillProviderFuture;
use crate::provider::SkillReadContext;
use crate::provider::SkillSearchRequest;
use codex_extension_api::CatalogRefreshInput;
use codex_extension_api::ExtensionData;
use codex_extension_api::ExtensionEventSink;
use codex_extension_api::ExtensionRegistryBuilder;
use codex_extension_api::ExtensionWarning;
use codex_mcp::McpRuntime;
use codex_protocol::protocol::Event;
use pretty_assertions::assert_eq;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::time::Duration;
use tokio::sync::Notify;
#[derive(Default)]
struct Provider {
reads: AtomicUsize,
lists: AtomicUsize,
fail_list: AtomicBool,
partial_list: AtomicBool,
next_catalog: Mutex<Option<SkillCatalog>>,
pause_read: AtomicBool,
pause_list: AtomicBool,
entered: Notify,
resume: Notify,
}
impl SkillProvider for Provider {
fn list<'a>(&'a self, _query: SkillListQuery<'a>) -> SkillProviderFuture<'a, SkillCatalog> {
Box::pin(async move {
self.lists.fetch_add(1, Ordering::SeqCst);
let fail = self.fail_list.swap(false, Ordering::SeqCst);
let catalog = self
.next_catalog
.lock()
.expect("test provider catalog mutex should not be poisoned")
.take();
if self.pause_list.swap(false, Ordering::SeqCst) {
self.entered.notify_one();
self.resume.notified().await;
}
if fail {
return Err(SkillProviderError::new("discovery failed"));
}
if let Some(catalog) = catalog {
return Ok(catalog);
}
let is_partial = self.partial_list.swap(false, Ordering::SeqCst);
Ok(SkillCatalog {
is_partial,
warnings: if is_partial {
Vec::new()
} else {
vec!["account catalog".into()]
},
..Default::default()
})
})
}
fn read<'a>(
&'a self,
request: SkillReadRequest<'a>,
) -> SkillProviderFuture<'a, SkillReadResult> {
let revision = self.reads.fetch_add(1, Ordering::SeqCst);
Box::pin(async move {
if self.pause_read.swap(false, Ordering::SeqCst) {
self.entered.notify_one();
self.resume.notified().await;
}
Ok(SkillReadResult {
resource: request.resource,
contents: format!("contents {revision}"),
})
})
}
fn search(&self, _request: SkillSearchRequest) -> SkillProviderFuture<'_, SkillSearchResult> {
Box::pin(async { Ok(SkillSearchResult::default()) })
}
}
fn state() -> SkillsThreadState {
SkillsThreadState::new(
SkillsExtensionConfig {
include_instructions: true,
catalog_deltas_enabled: false,
omit_descriptions: false,
max_context_tokens: None,
bundled_skills_enabled: false,
cloud_skill_enabled: true,
shadow_selection_enabled: false,
},
/*cloud_skills_available*/ true,
/*extension_metrics*/ None,
)
}
fn client() -> Arc<McpResourceClient> {
Arc::new(McpResourceClient::new(Arc::new(McpRuntime::empty(
/*prefix_mcp_tool_names*/ false,
))))
}
fn query(client: Option<Arc<McpResourceClient>>) -> SkillListQuery<'static> {
SkillListQuery {
turn_id: "turn".into(),
executor_roots: Vec::new(),
host_snapshot: None,
include_host_skills: false,
include_bundled_skills: false,
include_cloud_skills: true,
mcp_resources: client,
executor_capability_discovery: None,
executor_capability_discovery_v2: None,
}
}
fn request(client: Option<Arc<McpResourceClient>>) -> SkillReadRequest<'static> {
SkillReadRequest {
authority: SkillAuthority::new(SkillSourceKind::Cloud, "codex_apps"),
package: SkillPackageId("skill://demo".into()),
resource: SkillResourceId::new("skill://demo/SKILL.md"),
context: SkillReadContext::Cloud {
mcp_resources: client,
},
}
}
#[tokio::test]
async fn frozen_cloud_catalog_and_reads_ignore_live_mcp_changes() {
let state = state();
let provider = crate::FrozenCloudSkillProvider::from_json(
serde_json::json!({"skills": [{
"package": "skill://demo/work", "name": "demo", "description": "Frozen skill",
"alias_root": "skill://demo", "main_resource": "skill://demo/work/SKILL.md",
"resources": {"skill://demo/work/SKILL.md": "Frozen contents"}
}]})
.to_string()
.as_bytes(),
)
.expect("frozen cloud skill fixture should be valid");
let providers = SkillProviders::new().with_cloud_provider(Arc::new(provider));
let turn_store = ExtensionData::new("turn");
state
.refresh_cloud_catalog(&providers, query(Some(client())), &turn_store)
.await
.expect("cloud catalog refresh should succeed");
assert!(
turn_store
.get::<LatestCloudSkillsAuth>()
.expect("successful discovery should record its auth scope")
.0
.is_none()
);
let catalog = state
.available_cloud_catalog()
.expect("cloud catalog should be available after refresh");
let generation = state
.catalog_state
.lock()
.expect("catalog state mutex should not be poisoned")
.cloud_generation
.clone()
.expect("initial refresh should publish a cloud generation");
for mcp_resources in [Some(client()), None, Some(client())] {
let request = SkillReadRequest {
package: SkillPackageId("skill://demo/work".into()),
resource: SkillResourceId::new("skill://demo/work/SKILL.md"),
..request(mcp_resources.clone())
};
assert_eq!(
state
.read_skill(&providers, request)
.await
.expect("cloud skill read should succeed"),
SkillReadResult {
resource: SkillResourceId::new("skill://demo/work/SKILL.md"),
contents: "Frozen contents".into(),
}
);
state
.refresh_cloud_catalog(&providers, query(mcp_resources), &turn_store)
.await
.expect("cloud catalog refresh should succeed");
assert_eq!(state.available_cloud_catalog(), Some(catalog.clone()));
assert!(Arc::ptr_eq(
&generation,
state
.catalog_state
.lock()
.expect("catalog state mutex should not be poisoned")
.cloud_generation
.as_ref()
.expect("frozen cloud generation should remain available")
));
}
}
#[tokio::test(start_paused = true)]
async fn step_cloud_refresh_serializes_waiters_and_retries() {
#[derive(Default)]
struct WarningCounter(AtomicUsize);
impl ExtensionEventSink for WarningCounter {
fn emit(&self, _event: Event) {}
fn emit_warning(&self, _warning: ExtensionWarning) {
self.0.fetch_add(1, Ordering::SeqCst);
}
}
let cloud = Arc::new(Provider::default());
let providers = SkillProviders::new().with_cloud_provider(cloud.clone());
let session_store = ExtensionData::new("session");
let thread_store = ExtensionData::new("thread");
thread_store.insert(state());
let thread_state = thread_store
.get::<SkillsThreadState>()
.expect("skills thread state should be initialized");
let turn_store = ExtensionData::new("turn");
let config = thread_state.config();
let warnings = Arc::new(WarningCounter::default());
let mut builder = ExtensionRegistryBuilder::with_event_sink(warnings.clone());
crate::install_with_providers(&mut builder, providers, move |_: &()| config.clone());
let registry = builder.build();
let contributor = registry
.turn_lifecycle_contributors()
.iter()
.find(|contributor| contributor.requires_mcp_runtime(&thread_store))
.expect("cloud skills contributor should be registered");
let refresh_input = CatalogRefreshInput {
turn_id: "turn",
session_store: &session_store,
thread_store: &thread_store,
turn_store: &turn_store,
};
for (index, delay) in [30, 60, 120, 240, 300, 300].into_iter().enumerate() {
cloud.fail_list.store(true, Ordering::SeqCst);
assert!(!contributor.refresh_catalog_for_step(refresh_input).await);
assert_eq!(thread_state.available_cloud_catalog(), None);
assert_eq!(cloud.lists.load(Ordering::SeqCst), index + 1);
assert_eq!(warnings.0.load(Ordering::SeqCst), 1);
tokio::time::advance(Duration::from_secs(delay - 1)).await;
assert!(!contributor.refresh_catalog_for_step(refresh_input).await);
assert_eq!(cloud.lists.load(Ordering::SeqCst), index + 1);
tokio::time::advance(Duration::from_secs(1)).await;
}
cloud.pause_list.store(true, Ordering::SeqCst);
let mut cancelled = contributor.refresh_catalog_for_step(refresh_input);
assert!(futures::poll!(&mut cancelled).is_pending());
drop(cancelled);
*cloud
.next_catalog
.lock()
.expect("test provider catalog mutex should not be poisoned") =
Some(SkillCatalog::default());
assert!(!contributor.refresh_catalog_for_step(refresh_input).await);
assert!(!contributor.refresh_catalog_for_step(refresh_input).await);
assert_eq!(cloud.lists.load(Ordering::SeqCst), 8);
// Waiting callers reuse success and share failures' cooldowns; cancellation allows retry.
for (fails, cancelled) in [(false, false), (true, false), (false, true)] {
session_store.insert(SkillsSessionState {
mcp_resources: Some(client()),
extension_metrics: None,
});
let previous_calls = cloud.lists.load(Ordering::SeqCst);
let prewarm_store = ExtensionData::new("prewarm");
let first_catalog = SkillCatalog {
warnings: vec!["catalog warning".into()],
..Default::default()
};
*cloud
.next_catalog
.lock()
.expect("test provider catalog mutex should not be poisoned") =
Some(first_catalog.clone());
cloud.fail_list.store(fails, Ordering::SeqCst);
cloud.pause_list.store(true, Ordering::SeqCst);
let mut turn_start = contributor.refresh_catalog_for_step(refresh_input);
assert!(futures::poll!(&mut turn_start).is_pending());
let prewarm_input = CatalogRefreshInput {
turn_id: "prewarm",
turn_store: &prewarm_store,
..refresh_input
};
let mut prewarm = contributor.refresh_catalog_for_step(prewarm_input);
assert!(futures::poll!(&mut prewarm).is_pending());
let mut cancelled_waiter = contributor.refresh_catalog_for_step(prewarm_input);
assert!(futures::poll!(&mut cancelled_waiter).is_pending());
drop(cancelled_waiter);
assert_eq!(cloud.lists.load(Ordering::SeqCst), previous_calls + 1);
*cloud
.next_catalog
.lock()
.expect("test provider catalog mutex should not be poisoned") =
Some(SkillCatalog::default());
if cancelled {
drop(turn_start);
} else {
cloud.resume.notify_one();
assert!(!turn_start.await);
}
assert!(
!tokio::time::timeout(std::time::Duration::from_secs(5), prewarm)
.await
.expect("waiting discovery should complete after its predecessor stops")
);
if fails {
assert_eq!(thread_state.available_cloud_catalog(), None);
assert_eq!(cloud.lists.load(Ordering::SeqCst), previous_calls + 1);
tokio::time::advance(Duration::from_secs(30)).await;
assert!(!contributor.refresh_catalog_for_step(prewarm_input).await);
}
assert_eq!(
thread_state.available_cloud_catalog(),
Some(if fails || cancelled {
SkillCatalog::default()
} else {
first_catalog
})
);
assert!(!contributor.refresh_catalog_for_step(prewarm_input).await);
assert!(!contributor.refresh_catalog_for_step(refresh_input).await);
assert_eq!(
cloud.lists.load(Ordering::SeqCst),
previous_calls + 1 + usize::from(fails || cancelled)
);
assert_eq!(warnings.0.load(Ordering::SeqCst), 1);
}
// New turns share the thread's cooldown and failure progression.
session_store.insert(SkillsSessionState {
mcp_resources: Some(client()),
extension_metrics: None,
});
let next_turn = ExtensionData::new("next turn");
let previous_calls = cloud.lists.load(Ordering::SeqCst);
for turn_store in [&turn_store, &next_turn] {
cloud.fail_list.store(true, Ordering::SeqCst);
assert!(
!contributor
.refresh_catalog_for_step(CatalogRefreshInput {
turn_store,
..refresh_input
})
.await
);
assert_eq!(cloud.lists.load(Ordering::SeqCst), previous_calls + 1);
}
assert_eq!(warnings.0.load(Ordering::SeqCst), 1);
let next_input = CatalogRefreshInput {
turn_id: "next turn",
turn_store: &next_turn,
..refresh_input
};
tokio::time::advance(Duration::from_secs(30)).await;
assert!(!contributor.refresh_catalog_for_step(next_input).await);
assert_eq!(cloud.lists.load(Ordering::SeqCst), previous_calls + 2);
tokio::time::advance(Duration::from_secs(59)).await;
assert!(!contributor.refresh_catalog_for_step(refresh_input).await);
assert_eq!(cloud.lists.load(Ordering::SeqCst), previous_calls + 2);
tokio::time::advance(Duration::from_secs(1)).await;
assert!(!contributor.refresh_catalog_for_step(next_input).await);
assert_eq!(cloud.lists.load(Ordering::SeqCst), previous_calls + 3);
assert_eq!(warnings.0.load(Ordering::SeqCst), 2);
}
#[tokio::test]
async fn late_read_cannot_return_or_populate_a_replaced_cache() {
for replacement in [Some(client()), None] {
let state = state();
let provider = Arc::new(Provider::default());
let providers = SkillProviders::new().with_cloud_provider(provider.clone());
let original = Some(client());
// None here exercises a successful per-turn refresh on the SAME generation.
let replacement = replacement.or_else(|| original.clone());
provider.pause_read.store(true, Ordering::SeqCst);
let (late, ()) = tokio::join!(state.read_skill(&providers, request(original)), async {
provider.entered.notified().await;
state
.refresh_cloud_catalog(
&providers,
query(replacement.clone()),
&ExtensionData::new("turn"),
)
.await
.expect("cloud catalog refresh should succeed");
provider.resume.notify_one();
});
assert!(late.is_err());
assert_eq!(
state
.read_skill(&providers, request(replacement))
.await
.expect("cloud skill read should succeed")
.contents,
"contents 1"
);
}
}
#[tokio::test]
async fn late_discovery_cannot_publish_into_a_new_generation() {
let state = state();
let provider = Arc::new(Provider::default());
let providers = SkillProviders::new().with_cloud_provider(provider.clone());
provider.pause_list.store(true, Ordering::SeqCst);
let turn_store = ExtensionData::new("turn");
let (late, ()) = tokio::join!(
state.refresh_cloud_catalog(&providers, query(Some(client())), &turn_store),
async {
provider.entered.notified().await;
state
.catalog_state
.lock()
.expect("catalog state mutex should not be poisoned")
.prepare_cloud_generation(Some(&client()));
provider.resume.notify_one();
}
);
late.expect("superseded discovery should be discarded without an error");
assert!(turn_store.get::<LatestCloudSkillsAuth>().is_none());
assert!(
state
.catalog_state
.lock()
.expect("catalog state mutex should not be poisoned")
.cloud_generation
.as_ref()
.expect("replacement cloud generation should exist")
.catalog
.is_none()
);
}
#[tokio::test(start_paused = true)]
async fn partial_cloud_catalog_without_warnings_is_refreshed_next_turn() {
let state = state();
let provider = Arc::new(Provider::default());
provider.partial_list.store(true, Ordering::SeqCst);
let providers = SkillProviders::new().with_cloud_provider(provider.clone());
let client = Some(client());
let turn_store = ExtensionData::new("turn");
state
.refresh_cloud_catalog(&providers, query(client.clone()), &turn_store)
.await
.expect("cloud catalog refresh should succeed");
// Reuse partial catalogs for the rest of the turn.
state
.refresh_cloud_catalog(&providers, query(client.clone()), &turn_store)
.await
.expect("cloud catalog refresh should succeed");
assert_eq!(provider.lists.load(Ordering::SeqCst), 1);
assert_eq!(
state
.available_cloud_catalog()
.expect("cloud catalog should be available after refresh"),
SkillCatalog {
is_partial: true,
..Default::default()
}
);
state
.refresh_cloud_catalog(
&providers,
query(client.clone()),
&ExtensionData::new("next turn"),
)
.await
.expect("cloud catalog refresh should succeed");
assert_eq!(
state
.available_cloud_catalog()
.expect("cloud catalog should be available after refresh"),
SkillCatalog {
is_partial: false,
warnings: vec!["account catalog".into()],
..Default::default()
}
);
// Retry failures even when the previous catalog remains available.
let retry_turn = ExtensionData::new("retry turn");
provider.fail_list.store(true, Ordering::SeqCst);
assert!(
state
.refresh_cloud_catalog(&providers, query(client.clone()), &retry_turn)
.await
.is_err()
);
assert!(state.available_cloud_catalog().is_some());
assert!(retry_turn.get::<LatestCloudSkillsAuth>().is_none());
tokio::time::advance(Duration::from_secs(30)).await;
state
.refresh_cloud_catalog(&providers, query(client), &retry_turn)
.await
.expect("cloud catalog refresh should succeed");
assert_eq!(provider.lists.load(Ordering::SeqCst), 4);
}
#[tokio::test]
async fn cloud_refresh_preserves_complete_catalogs_only_within_the_same_auth_scope() {
let catalog = |name: &str, is_partial| SkillCatalog {
entries: vec![SkillCatalogEntry::new(
SkillPackageId("skill://demo".into()),
SkillAuthority::new(SkillSourceKind::Cloud, "codex_apps"),
name,
"test catalog",
SkillResourceId::new("skill://demo/SKILL.md"),
)],
// Complete listings can have diagnostics; these also keep discovery eligible for refresh.
warnings: vec![format!("{name} catalog diagnostic")],
is_partial,
};
for previous_partial in [false, true] {
for incoming_partial in [false, true] {
for changed_auth in [false, true] {
let state = state();
let provider = Arc::new(Provider::default());
let providers = SkillProviders::new().with_cloud_provider(provider.clone());
let original_client = client();
let mut previous = catalog("previous", previous_partial);
*provider
.next_catalog
.lock()
.expect("test provider catalog mutex should not be poisoned") =
Some(previous.clone());
state
.refresh_cloud_catalog(
&providers,
query(Some(original_client.clone())),
&ExtensionData::new("turn"),
)
.await
.expect("cloud catalog refresh should succeed");
let generation = state
.catalog_state
.lock()
.expect("catalog state mutex should not be poisoned")
.cloud_generation
.clone()
.expect("initial refresh should publish a cloud generation");
let contents = state
.read_skill(&providers, request(Some(original_client.clone())))
.await
.expect("cloud skill read should succeed");
let incoming = catalog("incoming", incoming_partial);
*provider
.next_catalog
.lock()
.expect("test provider catalog mutex should not be poisoned") =
Some(incoming.clone());
let current_client = if changed_auth {
client()
} else {
original_client
};
state
.refresh_cloud_catalog(
&providers,
query(Some(current_client.clone())),
&ExtensionData::new("next turn"),
)
.await
.expect("cloud catalog refresh should succeed");
let retained = !changed_auth && !previous_partial && incoming_partial;
assert_eq!(
generation
.catalog
.as_ref()
.expect("published generation should contain a catalog")
.is_partial,
previous_partial
);
if retained {
previous.is_partial = true;
}
assert_eq!(
state.available_cloud_catalog(),
Some(if retained { previous } else { incoming })
);
assert!(!Arc::ptr_eq(
&generation,
state
.catalog_state
.lock()
.expect("catalog state mutex should not be poisoned")
.cloud_generation
.as_ref()
.expect("refresh should publish a cloud generation")
));
assert_eq!(
state
.read_skill(&providers, request(Some(current_client)))
.await
.expect("cloud skill read should succeed")
.contents,
if retained {
contents.contents
} else {
"contents 1".to_string()
},
);
}
}
}
}

View File

@@ -0,0 +1,98 @@
//! Refreshes cloud skills at turn start and after auth changes.
use codex_extension_api::CatalogRefreshInput;
use codex_extension_api::ExtensionData;
use codex_extension_api::ExtensionFuture;
use codex_extension_api::TurnLifecycleContributor;
use codex_extension_api::TurnStartInput;
use codex_extension_api::TurnStartPhase;
use super::SkillsExtension;
use crate::provider::SkillListQuery;
use crate::state::LatestCloudSkillsAuth;
use crate::state::SkillsSessionState;
use crate::state::SkillsThreadState;
struct CloudDiscoveryWarningEmitted;
impl<C: Send + Sync + 'static> SkillsExtension<C> {
async fn refresh_cloud_catalog(&self, input: CatalogRefreshInput<'_>) {
let Some(state) = input.thread_store.get::<SkillsThreadState>() else {
return;
};
if !state.cloud_skill_enabled() {
return;
}
let config = state.config();
let query = SkillListQuery {
turn_id: input.turn_id.to_string(),
executor_roots: Vec::new(),
host_snapshot: None,
include_host_skills: false,
include_bundled_skills: config.bundled_skills_enabled,
include_cloud_skills: true,
mcp_resources: input
.session_store
.get::<SkillsSessionState>()
.and_then(|state| state.mcp_resources.clone()),
executor_capability_discovery: None,
executor_capability_discovery_v2: None,
};
if let Err(error) = state
.refresh_cloud_catalog(&self.providers, query, input.turn_store)
.await
&& input
.turn_store
.insert(CloudDiscoveryWarningEmitted)
.is_none()
{
self.emit_warning(
input.thread_store.level_id(),
Some(input.turn_id),
format!(
"Cloud skill discovery failed; retaining any catalog from the same cloud auth scope: {error}"
),
);
}
}
}
impl<C: Send + Sync + 'static> TurnLifecycleContributor for SkillsExtension<C> {
fn turn_start_phase(&self, thread_store: &ExtensionData) -> TurnStartPhase {
if thread_store
.get::<SkillsThreadState>()
.is_some_and(|state| state.cloud_skill_enabled())
{
TurnStartPhase::RegularTaskStart
} else {
TurnStartPhase::BeforeTaskRegistration
}
}
fn requires_mcp_runtime(&self, thread_store: &ExtensionData) -> bool {
self.turn_start_phase(thread_store) == TurnStartPhase::RegularTaskStart
}
fn on_turn_start<'a>(&'a self, input: TurnStartInput<'a>) -> ExtensionFuture<'a, ()> {
Box::pin(async move {
input.turn_store.remove::<LatestCloudSkillsAuth>();
self.refresh_cloud_catalog(CatalogRefreshInput {
turn_id: input.turn_id,
session_store: input.session_store,
thread_store: input.thread_store,
turn_store: input.turn_store,
})
.await;
})
}
fn refresh_catalog_for_step<'a>(
&'a self,
input: CatalogRefreshInput<'a>,
) -> ExtensionFuture<'a, bool> {
Box::pin(async move {
self.refresh_cloud_catalog(input).await;
false
})
}
}

View File

@@ -0,0 +1,20 @@
use std::num::NonZeroUsize;
/// Host-supplied configuration used by the skills extension.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SkillsExtensionConfig {
/// Whether the available-skills catalog is included in model context.
pub include_instructions: bool,
/// Whether skill additions and edits share a cumulative metadata budget until compaction.
pub catalog_deltas_enabled: bool,
/// Whether descriptions are omitted from rendered catalogs only.
pub omit_descriptions: bool,
/// Optional token budget override for the available-skills catalog.
pub max_context_tokens: Option<NonZeroUsize>,
/// Whether bundled skills are eligible for discovery.
pub bundled_skills_enabled: bool,
/// Whether cloud skills are discovered and exposed to the model.
pub cloud_skill_enabled: bool,
/// Whether cheap skill selectors run in shadow mode without changing prompt contents.
pub shadow_selection_enabled: bool,
}

View File

@@ -0,0 +1,58 @@
mod character_ngram;
mod character_routing_card;
mod fielded_bm25;
mod lru;
mod lru_plus_character_routing;
mod lru_plus_lexical;
mod multi_query_lexical;
mod routing_card_lexical;
mod rrf_lexical_char;
mod weighted_lexical;
pub(crate) use character_ngram::CharacterNgramSkillSelector;
pub(crate) use character_routing_card::CharacterRoutingCardSkillSelector;
use codex_skills::SkillDependencies;
pub(crate) use fielded_bm25::FieldedBm25SkillSelector;
pub(crate) use lru::LruSkillSelector;
pub(crate) use lru_plus_character_routing::LruPlusCharacterRoutingSkillSelector;
pub(crate) use lru_plus_character_routing::LruPlusLexicalCharacterRoutingSkillSelector;
pub(crate) use lru_plus_lexical::LruPlusLexicalSkillSelector;
pub(crate) use multi_query_lexical::MultiQueryLexicalSkillSelector;
pub(crate) use routing_card_lexical::RoutingCardLexicalSkillSelector;
pub(crate) use rrf_lexical_char::RrfLexicalCharSkillSelector;
pub(crate) use weighted_lexical::WeightedLexicalSkillSelector;
/// Metadata searched by a cheap skill selector.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct SkillSelectionDocument<'a> {
/// Caller-owned identifier returned in [`CheapSkillSelection::candidate_ids`].
pub id: usize,
pub name: &'a str,
pub short_description: Option<&'a str>,
pub description: &'a str,
pub dependencies: Option<&'a SkillDependencies>,
}
/// Bounded output from one cheap skill-selection method.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct CheapSkillSelection {
pub candidate_ids: Vec<usize>,
pub query_term_count: usize,
pub query_truncated: bool,
pub candidate_set_truncated: bool,
}
/// Selects likely-relevant skills without changing the model-visible catalog.
///
/// Implementations must be deterministic, side-effect free, and cheap enough to run in shadow
/// mode on every turn. Callers must validate returned IDs against the supplied documents.
pub(crate) trait CheapSkillSelector: Send + Sync {
/// Low-cardinality identifier suitable for experiment metrics.
fn method(&self) -> &'static str;
fn select(
&self,
query: &str,
documents: &[SkillSelectionDocument<'_>],
limit: usize,
) -> CheapSkillSelection;
}

View File

@@ -0,0 +1,243 @@
use std::collections::HashMap;
use std::collections::HashSet;
use super::CheapSkillSelection;
use super::CheapSkillSelector;
use super::SkillSelectionDocument;
const MAX_QUERY_BYTES: usize = 4 * 1024;
const MAX_QUERY_TERMS: usize = 64;
const MAX_QUERY_GRAMS: usize = 512;
const MAX_DOCUMENT_BYTES: usize = 4 * 1024;
const MAX_DOCUMENT_TERMS: usize = 256;
const MAX_DOCUMENT_GRAMS: usize = 512;
const MAX_CANDIDATES: usize = 1_000;
const MAX_RESULTS: usize = 50;
const MIN_GRAM_CHARS: usize = 2;
const MAX_GRAM_CHARS: usize = 5;
const FIELD_WEIGHTS: [f64; 3] = [8.0, 4.0, 1.0];
const STOP_WORDS: &[&str] = &[
"a", "an", "and", "are", "as", "at", "be", "by", "do", "for", "from", "how", "i", "in", "is",
"it", "me", "my", "of", "on", "or", "please", "that", "the", "this", "to", "use", "we", "what",
"when", "where", "which", "with", "you", "your",
];
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct CharacterNgramSkillSelector;
impl CheapSkillSelector for CharacterNgramSkillSelector {
fn method(&self) -> &'static str {
"character_ngram_v1"
}
fn select(
&self,
query: &str,
documents: &[SkillSelectionDocument<'_>],
limit: usize,
) -> CheapSkillSelection {
let (query, query_bytes_truncated) = bounded(query, MAX_QUERY_BYTES);
let (query_terms, query_terms_truncated) = query_terms(query);
let (query_grams, query_grams_truncated) = grams(&query_terms, MAX_QUERY_GRAMS);
let query_truncated =
query_bytes_truncated || query_terms_truncated || query_grams_truncated;
let candidate_set_truncated = documents.len() > MAX_CANDIDATES;
if query_grams.is_empty() || limit == 0 {
return CheapSkillSelection {
query_term_count: query_terms.len(),
query_truncated,
candidate_set_truncated,
..Default::default()
};
}
let prepared = documents
.iter()
.take(MAX_CANDIDATES)
.map(PreparedDocument::new)
.collect::<Vec<_>>();
let document_frequencies = document_frequencies(&prepared);
let document_count = prepared.len() as f64;
let minimum_matches = query_grams.len().min(3);
let mut scored = prepared
.iter()
.filter_map(|document| {
let (score, matched_grams) = score_document(
document,
&query_grams,
&document_frequencies,
document_count,
);
(matched_grams >= minimum_matches).then_some((score, document.id, document.name))
})
.collect::<Vec<_>>();
scored.sort_by(|left, right| {
right
.0
.total_cmp(&left.0)
.then_with(|| left.2.cmp(right.2))
.then_with(|| left.1.cmp(&right.1))
});
CheapSkillSelection {
candidate_ids: scored
.into_iter()
.take(limit.min(MAX_RESULTS))
.map(|(_, id, _)| id)
.collect(),
query_term_count: query_terms.len(),
query_truncated,
candidate_set_truncated,
}
}
}
struct PreparedDocument<'a> {
id: usize,
name: &'a str,
fields: [HashSet<String>; 3],
}
impl<'a> PreparedDocument<'a> {
fn new(document: &'a SkillSelectionDocument<'a>) -> Self {
Self {
id: document.id,
name: document.name,
fields: [
document_grams(document.name),
document_grams(document.short_description.unwrap_or_default()),
document_grams(document.description),
],
}
}
}
fn score_document(
document: &PreparedDocument<'_>,
query_grams: &[String],
document_frequencies: &HashMap<String, usize>,
document_count: f64,
) -> (f64, usize) {
query_grams.iter().fold((0.0, 0), |(score, matched), gram| {
let frequency = document_frequencies.get(gram).copied().unwrap_or_default() as f64;
if frequency == 0.0 {
return (score, matched);
}
let inverse_document_frequency =
(1.0 + (document_count - frequency + 0.5) / (frequency + 0.5)).ln();
let field_weight = document
.fields
.iter()
.enumerate()
.filter(|(_, field)| field.contains(gram))
.map(|(index, _)| FIELD_WEIGHTS[index])
.sum::<f64>();
if field_weight == 0.0 {
(score, matched)
} else {
(
score + inverse_document_frequency * field_weight,
matched + 1,
)
}
})
}
fn document_frequencies(documents: &[PreparedDocument<'_>]) -> HashMap<String, usize> {
let mut frequencies = HashMap::new();
for document in documents {
let grams = document
.fields
.iter()
.flatten()
.map(String::as_str)
.collect::<HashSet<_>>();
for gram in grams {
*frequencies.entry(gram.to_string()).or_default() += 1;
}
}
frequencies
}
fn query_terms(query: &str) -> (Vec<String>, bool) {
let mut seen = HashSet::new();
let mut terms = Vec::new();
for term in normalized_terms(query)
.into_iter()
.filter(|term| term.chars().count() >= 2 && !STOP_WORDS.contains(&term.as_str()))
{
if !seen.insert(term.clone()) {
continue;
}
if terms.len() == MAX_QUERY_TERMS {
return (terms, true);
}
terms.push(term);
}
(terms, false)
}
fn document_grams(value: &str) -> HashSet<String> {
let (value, _) = bounded(value, MAX_DOCUMENT_BYTES);
let terms = normalized_terms(value)
.into_iter()
.take(MAX_DOCUMENT_TERMS)
.collect::<Vec<_>>();
grams(&terms, MAX_DOCUMENT_GRAMS).0.into_iter().collect()
}
fn grams(terms: &[String], limit: usize) -> (Vec<String>, bool) {
let mut seen = HashSet::new();
let mut grams = Vec::new();
for term in terms {
let characters = term.chars().collect::<Vec<_>>();
let minimum_gram_chars = if term.is_ascii() && characters.len() > MIN_GRAM_CHARS {
MIN_GRAM_CHARS + 1
} else {
MIN_GRAM_CHARS
};
for gram_size in minimum_gram_chars..=MAX_GRAM_CHARS.min(characters.len()) {
for start in 0..=characters.len() - gram_size {
let gram = characters[start..start + gram_size]
.iter()
.collect::<String>();
if !seen.insert(gram.clone()) {
continue;
}
if grams.len() == limit {
return (grams, true);
}
grams.push(gram);
}
}
}
(grams, false)
}
fn normalized_terms(value: &str) -> Vec<String> {
let mut normalized = String::with_capacity(value.len());
for character in value.chars() {
if character.is_alphanumeric() {
normalized.extend(character.to_lowercase());
} else {
normalized.push(' ');
}
}
normalized.split_whitespace().map(str::to_string).collect()
}
fn bounded(value: &str, max_bytes: usize) -> (&str, bool) {
if value.len() <= max_bytes {
return (value, false);
}
let mut end = max_bytes;
while !value.is_char_boundary(end) {
end = end.saturating_sub(1);
}
(&value[..end], true)
}
#[cfg(test)]
#[path = "character_ngram_tests.rs"]
mod tests;

View File

@@ -0,0 +1,79 @@
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn ngrams_match_related_word_forms() {
let documents = [
document(/*id*/ 1, "presentations", "Create visual decks."),
document(/*id*/ 2, "spreadsheets", "Analyze tabular data."),
];
let selection =
CharacterNgramSkillSelector.select("create a presentation", &documents, /*limit*/ 20);
assert_eq!(vec![1], selection.candidate_ids);
}
#[test]
fn ngrams_tolerate_a_typo() {
let documents = [
document(/*id*/ 1, "postgresql", "Manage a relational database."),
document(/*id*/ 2, "postscript", "Render printable documents."),
];
let selection = CharacterNgramSkillSelector.select(
"repair my postgrez database",
&documents,
/*limit*/ 20,
);
assert_eq!(vec![1, 2], selection.candidate_ids);
}
#[test]
fn ngrams_match_cjk_without_word_boundaries() {
let documents = [
document(/*id*/ 1, "演示文稿", "创建幻灯片。"),
document(/*id*/ 2, "电子表格", "分析表格数据。"),
];
let selection =
CharacterNgramSkillSelector.select("帮我制作演示文稿", &documents, /*limit*/ 20);
assert_eq!(vec![1], selection.candidate_ids);
}
#[test]
fn ngrams_report_bounded_inputs() {
let long_query = "match ".repeat(MAX_QUERY_BYTES);
let names = (0..=MAX_CANDIDATES)
.map(|index| format!("candidate-{index}"))
.collect::<Vec<_>>();
let documents = names
.iter()
.enumerate()
.map(|(id, name)| SkillSelectionDocument {
id,
name,
short_description: None,
description: "match",
dependencies: None,
})
.collect::<Vec<_>>();
let selection = CharacterNgramSkillSelector.select(&long_query, &documents, /*limit*/ 20);
assert!(selection.query_truncated);
assert!(selection.candidate_set_truncated);
assert_eq!(20, selection.candidate_ids.len());
}
fn document<'a>(id: usize, name: &'a str, description: &'a str) -> SkillSelectionDocument<'a> {
SkillSelectionDocument {
id,
name,
short_description: None,
description,
dependencies: None,
}
}

View File

@@ -0,0 +1,136 @@
use std::collections::HashMap;
use codex_utils_path_uri::LegacyAppPathString;
use crate::HostSkillsSnapshot;
use crate::catalog::SkillCatalog;
use crate::catalog::SkillSourceKind;
use super::CharacterNgramSkillSelector;
use super::CheapSkillSelection;
use super::CheapSkillSelector;
use super::SkillSelectionDocument;
const MAX_ROUTING_FIELD_BYTES: usize = 4 * 1024;
const MAX_DEPENDENCY_RECORDS: usize = 32;
const MAX_CANDIDATES: usize = 1_000;
#[derive(Clone, Debug, Default)]
pub(crate) struct CharacterRoutingCardSkillSelector {
routing_fields: HashMap<usize, String>,
}
impl CharacterRoutingCardSkillSelector {
pub(crate) fn new(catalog: &SkillCatalog, host_snapshot: Option<&HostSkillsSnapshot>) -> Self {
let host_skill_ids = catalog
.entries
.iter()
.enumerate()
.filter(|(_, entry)| {
entry.authority.kind == SkillSourceKind::Host && entry.is_model_visible()
})
.take(MAX_CANDIDATES)
.filter_map(|(id, entry)| {
let path = LegacyAppPathString::from_string(entry.main_prompt.as_str())
.to_inferred_path_uri()?;
Some((path, id))
})
.collect::<HashMap<_, _>>();
let routing_fields = host_snapshot
.into_iter()
.flat_map(|snapshot| snapshot.outcome().skills.iter())
.filter_map(|skill| {
let id = host_skill_ids.get(&skill.path_to_skills_md)?;
let interface = skill.interface.as_ref()?;
let mut field = String::new();
for value in [
interface.display_name.as_deref(),
interface.short_description.as_deref(),
interface.default_prompt.as_deref(),
]
.into_iter()
.flatten()
{
push_bounded(&mut field, value);
}
(!field.is_empty()).then_some((*id, field))
})
.take(MAX_CANDIDATES)
.collect();
Self { routing_fields }
}
}
impl CheapSkillSelector for CharacterRoutingCardSkillSelector {
fn method(&self) -> &'static str {
"character_routing_card_v1"
}
fn select(
&self,
query: &str,
documents: &[SkillSelectionDocument<'_>],
limit: usize,
) -> CheapSkillSelection {
if limit == 0 {
return CharacterNgramSkillSelector.select(query, documents, /*limit*/ 0);
}
let routing_fields = documents
.iter()
.take(MAX_CANDIDATES)
.map(|document| {
let mut field = String::new();
if let Some(description) = document.short_description {
push_bounded(&mut field, description);
}
if let Some(routing_field) = self.routing_fields.get(&document.id) {
push_bounded(&mut field, routing_field);
}
if let Some(dependencies) = document.dependencies {
for dependency in dependencies.tools.iter().take(MAX_DEPENDENCY_RECORDS) {
push_bounded(&mut field, dependency.value.as_str());
if let Some(description) = dependency.description.as_deref() {
push_bounded(&mut field, description);
}
}
}
field
})
.collect::<Vec<_>>();
let routing_documents = documents
.iter()
.zip(&routing_fields)
.map(|(document, field)| SkillSelectionDocument {
short_description: (!field.is_empty()).then_some(field.as_str()),
..*document
})
.collect::<Vec<_>>();
let selection = CharacterNgramSkillSelector.select(query, &routing_documents, limit);
CheapSkillSelection {
candidate_set_truncated: documents.len() > MAX_CANDIDATES
|| selection.candidate_set_truncated,
..selection
}
}
}
fn push_bounded(destination: &mut String, value: &str) {
if value.is_empty() || destination.len() == MAX_ROUTING_FIELD_BYTES {
return;
}
if !destination.is_empty() {
destination.push(' ');
}
let remaining = MAX_ROUTING_FIELD_BYTES.saturating_sub(destination.len());
let mut end = value.len().min(remaining);
while !value.is_char_boundary(end) {
end -= 1;
}
destination.push_str(&value[..end]);
}
#[cfg(test)]
#[path = "character_routing_card_tests.rs"]
mod tests;

View File

@@ -0,0 +1,155 @@
use crate::SkillLoadOutcome;
use codex_protocol::protocol::SkillScope;
use codex_skills::SkillDependencies;
use codex_skills::SkillInterface;
use codex_skills::SkillMetadata;
use codex_skills::SkillToolDependency;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::PathUri;
use pretty_assertions::assert_eq;
use crate::catalog::SkillAuthority;
use crate::catalog::SkillCatalogEntry;
use crate::catalog::SkillPackageId;
use crate::catalog::SkillResourceId;
use super::*;
#[test]
fn host_interface_metadata_makes_unlisted_workflow_discoverable() {
let path = AbsolutePathBuf::try_from(std::env::temp_dir().join("routing-card/SKILL.md"))
.expect("temporary directory should be absolute");
let resource = path.to_string_lossy().to_string();
let mut outcome = SkillLoadOutcome::default();
outcome.skills.push(SkillMetadata {
name: "content-tools".to_string(),
description: "Prepare visual content.".to_string(),
short_description: None,
interface: Some(SkillInterface {
display_name: Some("Visual Assets".to_string()),
short_description: Some("Create illustrated assets.".to_string()),
icon_small: None,
icon_large: None,
brand_color: None,
default_prompt: Some("Create an animated pet spritesheet.".to_string()),
}),
dependencies: None,
policy: None,
path_to_skills_md: PathUri::from_abs_path(&path),
scope: SkillScope::User,
plugin_id: None,
remote_plugin_id: None,
});
let snapshot = HostSkillsSnapshot::new(std::sync::Arc::new(outcome));
let catalog = SkillCatalog {
is_partial: false,
entries: vec![SkillCatalogEntry::new(
SkillPackageId(resource.clone()),
SkillAuthority::new(SkillSourceKind::Host, "host"),
"content-tools",
"Prepare visual content.",
SkillResourceId::new(resource),
)],
..Default::default()
};
let selector = CharacterRoutingCardSkillSelector::new(&catalog, Some(&snapshot));
let documents = [document(
/*id*/ 0,
"content-tools",
"Prepare visual content.",
)];
let selection = selector.select(
"make an animated pet spritesheet",
&documents,
/*limit*/ 20,
);
assert_eq!(vec![0], selection.candidate_ids);
}
#[test]
fn connector_dependencies_make_generic_skills_discoverable() {
let dependencies = SkillDependencies {
tools: vec![SkillToolDependency {
r#type: "app".to_string(),
value: "slack".to_string(),
description: Some("Post messages to team channels.".to_string()),
transport: None,
command: None,
url: None,
oauth_callback_port: None,
}],
};
let documents = [
SkillSelectionDocument {
dependencies: Some(&dependencies),
..document(
/*id*/ 3,
"team-communication",
"Share updates with the team.",
)
},
document(/*id*/ 4, "documents", "Write project updates."),
];
let selector = CharacterRoutingCardSkillSelector::new(
&SkillCatalog::default(),
/*host_snapshot*/ None,
);
let selection = selector.select("post this update in Slack", &documents, /*limit*/ 20);
assert_eq!(Some(3), selection.candidate_ids.first().copied());
}
#[test]
fn strong_baseline_match_is_preserved_alongside_routing_match() {
let documents = [
document(/*id*/ 1, "presentation-tools", "Build meeting decks."),
document(/*id*/ 2, "content-tools", "Prepare visual content."),
];
let selector = CharacterRoutingCardSkillSelector {
routing_fields: HashMap::from([(
2,
"Create a presentation with PowerPoint slides".to_string(),
)]),
};
let selection = selector.select(
"create a PowerPoint presentation",
&documents,
/*limit*/ 2,
);
assert_eq!(vec![2, 1], selection.candidate_ids);
}
#[test]
fn long_routing_metadata_preserves_original_short_description_matches() {
let metadata = (0_u64..60)
.map(|index| format!("{:016x}", index.wrapping_mul(/*rhs*/ 0x9e37_79b9_7f4a_7c15)))
.collect::<Vec<_>>()
.join(" ");
let short_description = "zebra xylophone quasar";
let documents = [SkillSelectionDocument {
short_description: Some(short_description),
..document(/*id*/ 0, "content-tools", "Prepare visual content.")
}];
let selector = CharacterRoutingCardSkillSelector {
routing_fields: HashMap::from([(/*id*/ 0, metadata)]),
};
let selection = selector.select(short_description, &documents, /*limit*/ 20);
assert_eq!(vec![0], selection.candidate_ids);
}
fn document<'a>(id: usize, name: &'a str, description: &'a str) -> SkillSelectionDocument<'a> {
SkillSelectionDocument {
id,
name,
short_description: None,
description,
dependencies: None,
}
}

View File

@@ -0,0 +1,239 @@
use std::collections::HashMap;
use std::collections::HashSet;
use super::CheapSkillSelection;
use super::CheapSkillSelector;
use super::SkillSelectionDocument;
const MAX_QUERY_BYTES: usize = 4 * 1024;
const MAX_QUERY_TERMS: usize = 64;
const MAX_DOCUMENT_BYTES: usize = 4 * 1024;
const MAX_DOCUMENT_TERMS: usize = 256;
const MAX_CANDIDATES: usize = 1_000;
const MAX_RESULTS: usize = 50;
const FIELD_WEIGHTS: [f64; 3] = [8.0, 4.0, 1.0];
const K1: f64 = 1.2;
const B: f64 = 0.75;
const STOP_WORDS: &[&str] = &[
"a", "an", "and", "are", "as", "at", "be", "by", "do", "for", "from", "how", "i", "in", "is",
"it", "me", "my", "of", "on", "or", "please", "that", "the", "this", "to", "use", "we", "what",
"when", "where", "which", "with", "you", "your",
];
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct FieldedBm25SkillSelector;
impl CheapSkillSelector for FieldedBm25SkillSelector {
fn method(&self) -> &'static str {
"fielded_bm25_v1"
}
fn select(
&self,
query: &str,
documents: &[SkillSelectionDocument<'_>],
limit: usize,
) -> CheapSkillSelection {
let (query, query_bytes_truncated) = bounded(query, MAX_QUERY_BYTES);
let (query_terms, query_terms_truncated) = query_terms(query);
let query_truncated = query_bytes_truncated || query_terms_truncated;
let candidate_set_truncated = documents.len() > MAX_CANDIDATES;
if query_terms.is_empty() || limit == 0 {
return CheapSkillSelection {
query_term_count: query_terms.len(),
query_truncated,
candidate_set_truncated,
..Default::default()
};
}
let prepared = documents
.iter()
.take(MAX_CANDIDATES)
.map(PreparedDocument::new)
.collect::<Vec<_>>();
let averages = average_field_lengths(&prepared);
let document_frequencies = document_frequencies(&prepared);
let document_count = prepared.len() as f64;
let mut scored = prepared
.iter()
.filter_map(|document| {
let score = score_document(
document,
&query_terms,
&document_frequencies,
document_count,
averages,
);
(score > 0.0).then_some((score, document.id, document.name))
})
.collect::<Vec<_>>();
scored.sort_by(|left, right| {
right
.0
.total_cmp(&left.0)
.then_with(|| left.2.cmp(right.2))
.then_with(|| left.1.cmp(&right.1))
});
CheapSkillSelection {
candidate_ids: scored
.into_iter()
.take(limit.min(MAX_RESULTS))
.map(|(_, id, _)| id)
.collect(),
query_term_count: query_terms.len(),
query_truncated,
candidate_set_truncated,
}
}
}
struct PreparedDocument<'a> {
id: usize,
name: &'a str,
fields: [Vec<String>; 3],
}
impl<'a> PreparedDocument<'a> {
fn new(document: &'a SkillSelectionDocument<'a>) -> Self {
Self {
id: document.id,
name: document.name,
fields: [
document_terms(document.name),
document_terms(document.short_description.unwrap_or_default()),
document_terms(document.description),
],
}
}
}
fn score_document(
document: &PreparedDocument<'_>,
query_terms: &[String],
document_frequencies: &HashMap<String, usize>,
document_count: f64,
average_field_lengths: [f64; 3],
) -> f64 {
query_terms.iter().fold(0.0, |score, query_term| {
let frequency = document_frequencies
.get(query_term)
.copied()
.unwrap_or_default() as f64;
if frequency == 0.0 {
return score;
}
let weighted_term_frequency =
document
.fields
.iter()
.enumerate()
.fold(0.0, |weighted, (field_index, terms)| {
let term_frequency =
terms.iter().filter(|term| *term == query_term).count() as f64;
if term_frequency == 0.0 {
return weighted;
}
let average_length = average_field_lengths[field_index];
let length_ratio = if average_length == 0.0 {
1.0
} else {
terms.len() as f64 / average_length
};
weighted
+ FIELD_WEIGHTS[field_index] * term_frequency / (1.0 - B + B * length_ratio)
});
if weighted_term_frequency == 0.0 {
return score;
}
let inverse_document_frequency =
(1.0 + (document_count - frequency + 0.5) / (frequency + 0.5)).ln();
score
+ inverse_document_frequency * weighted_term_frequency * (K1 + 1.0)
/ (weighted_term_frequency + K1)
})
}
fn average_field_lengths(documents: &[PreparedDocument<'_>]) -> [f64; 3] {
if documents.is_empty() {
return [0.0; 3];
}
let totals = documents.iter().fold([0usize; 3], |mut totals, document| {
for (index, field) in document.fields.iter().enumerate() {
totals[index] = totals[index].saturating_add(field.len());
}
totals
});
totals.map(|total| total as f64 / documents.len() as f64)
}
fn document_frequencies(documents: &[PreparedDocument<'_>]) -> HashMap<String, usize> {
let mut frequencies = HashMap::new();
for document in documents {
let terms = document
.fields
.iter()
.flatten()
.map(String::as_str)
.collect::<HashSet<_>>();
for term in terms {
*frequencies.entry(term.to_string()).or_default() += 1;
}
}
frequencies
}
fn query_terms(query: &str) -> (Vec<String>, bool) {
let mut seen = HashSet::new();
let mut terms = Vec::new();
for term in normalized_terms(query)
.into_iter()
.filter(|term| term.chars().count() >= 2 && !STOP_WORDS.contains(&term.as_str()))
{
if !seen.insert(term.clone()) {
continue;
}
if terms.len() == MAX_QUERY_TERMS {
return (terms, true);
}
terms.push(term);
}
(terms, false)
}
fn document_terms(value: &str) -> Vec<String> {
let (value, _) = bounded(value, MAX_DOCUMENT_BYTES);
normalized_terms(value)
.into_iter()
.take(MAX_DOCUMENT_TERMS)
.collect()
}
fn normalized_terms(value: &str) -> Vec<String> {
let mut normalized = String::with_capacity(value.len());
for character in value.chars() {
if character.is_alphanumeric() {
normalized.extend(character.to_lowercase());
} else {
normalized.push(' ');
}
}
normalized.split_whitespace().map(str::to_string).collect()
}
fn bounded(value: &str, max_bytes: usize) -> (&str, bool) {
if value.len() <= max_bytes {
return (value, false);
}
let mut end = max_bytes;
while !value.is_char_boundary(end) {
end = end.saturating_sub(1);
}
(&value[..end], true)
}
#[cfg(test)]
#[path = "fielded_bm25_tests.rs"]
mod tests;

View File

@@ -0,0 +1,81 @@
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn bm25_prioritizes_rare_terms() {
let documents = [
document(/*id*/ 1, "review-helper", "Review code and prose."),
document(
/*id*/ 2,
"terraform-review",
"Review Terraform infrastructure.",
),
document(/*id*/ 3, "document-review", "Review Word documents."),
];
let selection =
FieldedBm25SkillSelector.select("review terraform", &documents, /*limit*/ 20);
assert_eq!(vec![2, 3, 1], selection.candidate_ids);
}
#[test]
fn bm25_weights_names_above_descriptions() {
let documents = [
document(/*id*/ 1, "slides", "Create presentations."),
document(/*id*/ 2, "presentations", "Create and edit slides."),
];
let selection = FieldedBm25SkillSelector.select("slides", &documents, /*limit*/ 20);
assert_eq!(vec![1, 2], selection.candidate_ids);
}
#[test]
fn bm25_drops_candidates_without_matching_terms() {
let documents = [document(
/*id*/ 1,
"spreadsheets",
"Analyze tabular data.",
)];
let selection =
FieldedBm25SkillSelector.select("render a video", &documents, /*limit*/ 20);
assert!(selection.candidate_ids.is_empty());
}
#[test]
fn bm25_reports_bounded_inputs() {
let long_query = "match ".repeat(MAX_QUERY_BYTES);
let names = (0..=MAX_CANDIDATES)
.map(|index| format!("candidate-{index}"))
.collect::<Vec<_>>();
let documents = names
.iter()
.enumerate()
.map(|(id, name)| SkillSelectionDocument {
id,
name,
short_description: None,
description: "match",
dependencies: None,
})
.collect::<Vec<_>>();
let selection = FieldedBm25SkillSelector.select(&long_query, &documents, /*limit*/ 20);
assert!(selection.query_truncated);
assert!(selection.candidate_set_truncated);
assert_eq!(20, selection.candidate_ids.len());
}
fn document<'a>(id: usize, name: &'a str, description: &'a str) -> SkillSelectionDocument<'a> {
SkillSelectionDocument {
id,
name,
short_description: None,
description,
dependencies: None,
}
}

View File

@@ -0,0 +1,61 @@
use std::collections::HashSet;
use super::CheapSkillSelection;
use super::CheapSkillSelector;
use super::SkillSelectionDocument;
const MAX_CANDIDATES: usize = 1_000;
const MAX_QUERY_TERMS: usize = 64;
const MAX_RESULTS: usize = 50;
#[derive(Clone, Debug, Default)]
pub(crate) struct LruSkillSelector {
recent_skill_ids: Vec<usize>,
}
impl LruSkillSelector {
pub(crate) fn new(recent_skill_ids: Vec<usize>) -> Self {
Self { recent_skill_ids }
}
}
impl CheapSkillSelector for LruSkillSelector {
fn method(&self) -> &'static str {
"lru_v1"
}
fn select(
&self,
query: &str,
documents: &[SkillSelectionDocument<'_>],
limit: usize,
) -> CheapSkillSelection {
let mut query_terms = query.split_whitespace();
let query_term_count = query_terms.by_ref().take(MAX_QUERY_TERMS).count();
let query_truncated = query_terms.next().is_some();
let candidate_set_truncated = documents.len() > MAX_CANDIDATES;
let eligible_ids = documents
.iter()
.take(MAX_CANDIDATES)
.map(|document| document.id)
.collect::<HashSet<_>>();
let mut seen_ids = HashSet::new();
CheapSkillSelection {
candidate_ids: self
.recent_skill_ids
.iter()
.copied()
.filter(|id| eligible_ids.contains(id) && seen_ids.insert(*id))
.take(limit.min(MAX_RESULTS))
.collect(),
query_term_count,
query_truncated,
candidate_set_truncated,
}
}
}
#[cfg(test)]
#[path = "lru_tests.rs"]
mod tests;

View File

@@ -0,0 +1,136 @@
use super::CharacterRoutingCardSkillSelector;
use super::CheapSkillSelection;
use super::CheapSkillSelector;
use super::LruSkillSelector;
use super::SkillSelectionDocument;
use super::WeightedLexicalSkillSelector;
use super::rrf_lexical_char::fuse_rankings_with_constant;
const MAX_RESULTS: usize = 50;
const RRF_K: usize = 10;
#[derive(Clone, Debug, Default)]
pub(crate) struct LruPlusCharacterRoutingSkillSelector {
lru_selector: LruSkillSelector,
character_selector: CharacterRoutingCardSkillSelector,
}
impl LruPlusCharacterRoutingSkillSelector {
pub(crate) fn new(
lru_selector: LruSkillSelector,
character_selector: CharacterRoutingCardSkillSelector,
) -> Self {
Self {
lru_selector,
character_selector,
}
}
}
impl CheapSkillSelector for LruPlusCharacterRoutingSkillSelector {
fn method(&self) -> &'static str {
"lru_plus_character_routing_v1"
}
fn select(
&self,
query: &str,
documents: &[SkillSelectionDocument<'_>],
limit: usize,
) -> CheapSkillSelection {
if limit == 0 {
return CheapSkillSelection::default();
}
let recent = self
.lru_selector
.select(query, documents, /*limit*/ MAX_RESULTS);
let character =
self.character_selector
.select(query, documents, /*limit*/ MAX_RESULTS);
let candidate_ids = fuse_rankings_with_constant(
[&recent.candidate_ids, &character.candidate_ids],
limit.min(MAX_RESULTS),
/*rank_constant*/ RRF_K,
);
CheapSkillSelection {
candidate_ids,
query_term_count: recent.query_term_count.max(character.query_term_count),
query_truncated: recent.query_truncated || character.query_truncated,
candidate_set_truncated: recent.candidate_set_truncated
|| character.candidate_set_truncated,
}
}
}
#[derive(Clone, Debug, Default)]
pub(crate) struct LruPlusLexicalCharacterRoutingSkillSelector {
lru_selector: LruSkillSelector,
character_selector: CharacterRoutingCardSkillSelector,
}
impl LruPlusLexicalCharacterRoutingSkillSelector {
pub(crate) fn new(
lru_selector: LruSkillSelector,
character_selector: CharacterRoutingCardSkillSelector,
) -> Self {
Self {
lru_selector,
character_selector,
}
}
}
impl CheapSkillSelector for LruPlusLexicalCharacterRoutingSkillSelector {
fn method(&self) -> &'static str {
"lru_plus_lexical_character_routing_v1"
}
fn select(
&self,
query: &str,
documents: &[SkillSelectionDocument<'_>],
limit: usize,
) -> CheapSkillSelection {
if limit == 0 {
return CheapSkillSelection::default();
}
let recent = self
.lru_selector
.select(query, documents, /*limit*/ MAX_RESULTS);
let lexical =
WeightedLexicalSkillSelector.select(query, documents, /*limit*/ MAX_RESULTS);
let character =
self.character_selector
.select(query, documents, /*limit*/ MAX_RESULTS);
let candidate_ids = fuse_rankings_with_constant(
[
&recent.candidate_ids,
&lexical.candidate_ids,
&character.candidate_ids,
],
limit.min(MAX_RESULTS),
/*rank_constant*/ RRF_K,
);
CheapSkillSelection {
candidate_ids,
query_term_count: recent
.query_term_count
.max(lexical.query_term_count)
.max(character.query_term_count),
query_truncated: recent.query_truncated
|| lexical.query_truncated
|| character.query_truncated,
candidate_set_truncated: recent.candidate_set_truncated
|| lexical.candidate_set_truncated
|| character.candidate_set_truncated,
}
}
}
#[cfg(test)]
#[path = "lru_plus_character_routing_tests.rs"]
mod tests;

View File

@@ -0,0 +1,179 @@
use codex_skills::SkillDependencies;
use codex_skills::SkillToolDependency;
use pretty_assertions::assert_eq;
use super::*;
#[test]
fn cold_start_uses_character_routing_metadata() {
let dependencies = SkillDependencies {
tools: vec![SkillToolDependency {
r#type: "app".to_string(),
value: "slack".to_string(),
description: None,
transport: None,
command: None,
url: None,
oauth_callback_port: None,
}],
};
let documents = [
document(/*id*/ 10, "compilation", "Compile Rust crates."),
SkillSelectionDocument {
dependencies: Some(&dependencies),
..document(/*id*/ 20, "team-communication", "Share team updates.")
},
];
let expected = CheapSkillSelection {
candidate_ids: vec![20],
query_term_count: 1,
..Default::default()
};
for selector in selectors(Vec::new(), CharacterRoutingCardSkillSelector::default()) {
let method = selector.method();
assert_eq!(
expected,
selector.select("slack", &documents, /*limit*/ 50),
"{method}"
);
}
}
#[test]
fn recent_and_text_matches_are_merged_without_duplicates() {
let documents = [
document(/*id*/ 10, "rust-build", "Inspect compiler errors."),
document(
/*id*/ 20,
"python-tools",
"Manage Python environments.",
),
document(/*id*/ 30, "monorepo", "Repository conventions."),
];
let expected = CheapSkillSelection {
candidate_ids: vec![20, 30, 10],
query_term_count: 1,
..Default::default()
};
for selector in selectors(
vec![30, 10, 20, 20, 999],
CharacterRoutingCardSkillSelector::default(),
) {
let method = selector.method();
assert_eq!(
expected,
selector.select("python", &documents, /*limit*/ 50),
"{method}"
);
}
}
#[test]
fn three_way_fusion_retains_short_exact_matches() {
let documents = [
document(/*id*/ 10, "ci", ""),
document(/*id*/ 20, "python", ""),
document(/*id*/ 30, "rust", ""),
];
let expected_rankings = [vec![20, 30], vec![20, 10, 30]];
for (selector, candidate_ids) in
selectors(vec![30], CharacterRoutingCardSkillSelector::default())
.into_iter()
.zip(expected_rankings)
{
let method = selector.method();
assert_eq!(
CheapSkillSelection {
candidate_ids,
query_term_count: 2,
..Default::default()
},
selector.select("ci python", &documents, /*limit*/ 50),
"{method}"
);
}
}
#[test]
fn fusion_is_deterministic_capped_and_reports_input_bounds() {
let documents = (0..1_001)
.map(|id| document(id, "python", ""))
.collect::<Vec<_>>();
let query = "python ".repeat(4 * 1024);
let expected_rankings = [
[0, 999].into_iter().chain(1..49).collect::<Vec<_>>(),
(0..11)
.chain(std::iter::once(999))
.chain(11..49)
.collect::<Vec<_>>(),
];
for (selector, candidate_ids) in selectors(
vec![1_000, 999, 999, 1_002],
CharacterRoutingCardSkillSelector::default(),
)
.into_iter()
.zip(expected_rankings)
{
let method = selector.method();
let expected = CheapSkillSelection {
candidate_ids,
query_term_count: 64,
query_truncated: true,
candidate_set_truncated: true,
};
assert_eq!(
expected,
selector.select(&query, &documents, /*limit*/ 50),
"{method}"
);
assert_eq!(
expected,
selector.select(&query, &documents, usize::MAX),
"{method}"
);
assert_eq!(
CheapSkillSelection {
candidate_ids: expected.candidate_ids[..7].to_vec(),
..expected
},
selector.select(&query, &documents, /*limit*/ 7),
"{method}"
);
assert_eq!(
CheapSkillSelection::default(),
selector.select(&query, &documents, /*limit*/ 0),
"{method}"
);
}
}
fn selectors(
recent_skill_ids: Vec<usize>,
character_selector: CharacterRoutingCardSkillSelector,
) -> [Box<dyn CheapSkillSelector>; 2] {
let lru_selector = LruSkillSelector::new(recent_skill_ids);
[
Box::new(LruPlusCharacterRoutingSkillSelector::new(
lru_selector.clone(),
character_selector.clone(),
)),
Box::new(LruPlusLexicalCharacterRoutingSkillSelector::new(
lru_selector,
character_selector,
)),
]
}
fn document<'a>(id: usize, name: &'a str, description: &'a str) -> SkillSelectionDocument<'a> {
SkillSelectionDocument {
id,
name,
short_description: None,
description,
dependencies: None,
}
}

View File

@@ -0,0 +1,60 @@
use super::CheapSkillSelection;
use super::CheapSkillSelector;
use super::LruSkillSelector;
use super::SkillSelectionDocument;
use super::WeightedLexicalSkillSelector;
use super::rrf_lexical_char::fuse_rankings_with_constant;
const MAX_RESULTS: usize = 50;
const RRF_K: usize = 10;
#[derive(Clone, Debug, Default)]
pub(crate) struct LruPlusLexicalSkillSelector {
lru_selector: LruSkillSelector,
}
impl LruPlusLexicalSkillSelector {
pub(crate) fn new(lru_selector: LruSkillSelector) -> Self {
Self { lru_selector }
}
}
impl CheapSkillSelector for LruPlusLexicalSkillSelector {
fn method(&self) -> &'static str {
"lru_plus_lexical_v1"
}
fn select(
&self,
query: &str,
documents: &[SkillSelectionDocument<'_>],
limit: usize,
) -> CheapSkillSelection {
if limit == 0 {
return CheapSkillSelection::default();
}
let recent = self
.lru_selector
.select(query, documents, /*limit*/ MAX_RESULTS);
let lexical =
WeightedLexicalSkillSelector.select(query, documents, /*limit*/ MAX_RESULTS);
let candidate_ids = fuse_rankings_with_constant(
[&recent.candidate_ids, &lexical.candidate_ids],
limit.min(MAX_RESULTS),
/*rank_constant*/ RRF_K,
);
CheapSkillSelection {
candidate_ids,
query_term_count: recent.query_term_count.max(lexical.query_term_count),
query_truncated: recent.query_truncated || lexical.query_truncated,
candidate_set_truncated: recent.candidate_set_truncated
|| lexical.candidate_set_truncated,
}
}
}
#[cfg(test)]
#[path = "lru_plus_lexical_tests.rs"]
mod tests;

View File

@@ -0,0 +1,119 @@
use pretty_assertions::assert_eq;
use super::*;
#[test]
fn combined_selector_uses_lexical_results_before_invocation_history_exists() {
let documents = [
SkillSelectionDocument {
id: 10,
name: "ci",
short_description: None,
description: "Investigate failing checks.",
dependencies: None,
},
SkillSelectionDocument {
id: 20,
name: "python-tools",
short_description: None,
description: "Manage Python environments.",
dependencies: None,
},
];
let selection = LruPlusLexicalSkillSelector::new(LruSkillSelector::default()).select(
"manage python environments",
&documents,
/*limit*/ 50,
);
assert_eq!(vec![20], selection.candidate_ids);
}
#[test]
fn combined_selector_merges_recent_and_newly_matching_skills() {
let documents = [
SkillSelectionDocument {
id: 10,
name: "ci",
short_description: None,
description: "Investigate failing checks.",
dependencies: None,
},
SkillSelectionDocument {
id: 20,
name: "python-tools",
short_description: None,
description: "Manage Python environments.",
dependencies: None,
},
SkillSelectionDocument {
id: 30,
name: "monorepo",
short_description: None,
description: "Follow repository conventions.",
dependencies: None,
},
];
let selection = LruPlusLexicalSkillSelector::new(LruSkillSelector::new(vec![30, 10])).select(
"manage python environments",
&documents,
/*limit*/ 50,
);
assert_eq!(vec![20, 30, 10], selection.candidate_ids);
}
#[test]
fn combined_selector_promotes_skills_supported_by_both_signals() {
let documents = [
SkillSelectionDocument {
id: 10,
name: "ci",
short_description: None,
description: "Investigate failing checks.",
dependencies: None,
},
SkillSelectionDocument {
id: 30,
name: "monorepo",
short_description: None,
description: "Follow repository conventions.",
dependencies: None,
},
];
let selection = LruPlusLexicalSkillSelector::new(LruSkillSelector::new(vec![30, 10])).select(
"investigate failing ci checks",
&documents,
/*limit*/ 50,
);
assert_eq!(vec![10, 30], selection.candidate_ids);
}
#[test]
fn combined_fusion_keeps_a_top_ranked_skill_ahead_of_a_weak_overlap() {
let recent = std::iter::once(1)
.chain(100..148)
.chain(std::iter::once(2))
.collect::<Vec<_>>();
let lexical = (200..249).chain(std::iter::once(2)).collect::<Vec<_>>();
let fused = fuse_rankings_with_constant(
[&recent, &lexical],
/*limit*/ MAX_RESULTS,
/*rank_constant*/ RRF_K,
);
let top_ranked = fused
.iter()
.position(|candidate| *candidate == 1)
.expect("top-ranked skill should be selected");
let weak_overlap = fused
.iter()
.position(|candidate| *candidate == 2)
.expect("weak overlapping skill should be selected");
assert!(top_ranked < weak_overlap);
}

View File

@@ -0,0 +1,60 @@
use pretty_assertions::assert_eq;
use super::*;
#[test]
fn lru_selector_preserves_recent_invocation_order() {
let documents = [
SkillSelectionDocument {
id: 10,
name: "ci",
short_description: None,
description: "Investigate failing checks.",
dependencies: None,
},
SkillSelectionDocument {
id: 20,
name: "python-tools",
short_description: None,
description: "Manage Python environments.",
dependencies: None,
},
SkillSelectionDocument {
id: 30,
name: "monorepo",
short_description: None,
description: "Follow repository conventions.",
dependencies: None,
},
];
let selection =
LruSkillSelector::new(vec![30, 10]).select("continue", &documents, /*limit*/ 50);
assert_eq!(vec![30, 10], selection.candidate_ids);
}
#[test]
fn lru_selector_filters_stale_or_duplicate_skills_and_respects_the_limit() {
let documents = [
SkillSelectionDocument {
id: 10,
name: "ci",
short_description: None,
description: "Investigate failing checks.",
dependencies: None,
},
SkillSelectionDocument {
id: 20,
name: "python-tools",
short_description: None,
description: "Manage Python environments.",
dependencies: None,
},
];
let selection =
LruSkillSelector::new(vec![99, 10, 10, 20]).select("yes", &documents, /*limit*/ 1);
assert_eq!(vec![10], selection.candidate_ids);
}

View File

@@ -0,0 +1,166 @@
use std::collections::HashMap;
use std::collections::HashSet;
use super::CheapSkillSelection;
use super::CheapSkillSelector;
use super::SkillSelectionDocument;
use super::WeightedLexicalSkillSelector;
const MAX_QUERY_VIEWS: usize = 8;
const MAX_DECOMPOSITION_BYTES: usize = 4 * 1024;
const MAX_RESULTS: usize = 50;
const CONNECTORS: &[&str] = &[" and then ", " and ", " then ", " also "];
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct MultiQueryLexicalSkillSelector;
impl CheapSkillSelector for MultiQueryLexicalSkillSelector {
fn method(&self) -> &'static str {
"multi_query_lexical_v1"
}
fn select(
&self,
query: &str,
documents: &[SkillSelectionDocument<'_>],
limit: usize,
) -> CheapSkillSelection {
let full_selection =
WeightedLexicalSkillSelector.select(query, documents, limit.min(MAX_RESULTS));
let views = query_views(query);
if views.len() <= 1 || limit == 0 {
return full_selection;
}
let mut candidates = HashMap::new();
record_candidates(&mut candidates, &full_selection, /*view_index*/ 0);
let mut query_truncated = full_selection.query_truncated;
let mut candidate_set_truncated = full_selection.candidate_set_truncated;
for (view_index, view) in views.into_iter().enumerate().skip(1) {
let selection =
WeightedLexicalSkillSelector.select(view, documents, limit.min(MAX_RESULTS));
query_truncated |= selection.query_truncated;
candidate_set_truncated |= selection.candidate_set_truncated;
record_candidates(&mut candidates, &selection, view_index);
}
let mut candidates = candidates.into_values().collect::<Vec<_>>();
candidates.sort_by(|left, right| {
left.best_rank
.cmp(&right.best_rank)
.then_with(|| {
left.full_query_rank
.unwrap_or(usize::MAX)
.cmp(&right.full_query_rank.unwrap_or(usize::MAX))
})
.then_with(|| right.view_count.cmp(&left.view_count))
.then_with(|| left.first_view.cmp(&right.first_view))
.then_with(|| left.id.cmp(&right.id))
});
CheapSkillSelection {
candidate_ids: candidates
.into_iter()
.take(limit.min(MAX_RESULTS))
.map(|candidate| candidate.id)
.collect(),
query_term_count: full_selection.query_term_count,
query_truncated,
candidate_set_truncated,
}
}
}
struct RankedCandidate {
id: usize,
best_rank: usize,
full_query_rank: Option<usize>,
view_count: usize,
first_view: usize,
}
fn record_candidates(
candidates: &mut HashMap<usize, RankedCandidate>,
selection: &CheapSkillSelection,
view_index: usize,
) {
for (rank, id) in selection.candidate_ids.iter().copied().enumerate() {
let rank = rank + 1;
candidates
.entry(id)
.and_modify(|candidate| {
candidate.best_rank = candidate.best_rank.min(rank);
candidate.view_count = candidate.view_count.saturating_add(1);
if view_index == 0 {
candidate.full_query_rank = Some(rank);
}
})
.or_insert(RankedCandidate {
id,
best_rank: rank,
full_query_rank: (view_index == 0).then_some(rank),
view_count: 1,
first_view: view_index,
});
}
}
fn query_views(query: &str) -> Vec<&str> {
let full_query = bounded(query, MAX_DECOMPOSITION_BYTES).trim();
if full_query.is_empty() {
return Vec::new();
}
let mut views = vec![full_query];
let mut seen = HashSet::from([full_query]);
for sentence in full_query.split(['\n', '\r', '.', '!', '?', ';']) {
for clause in split_connectors(sentence) {
let clause = clause.trim();
if clause.chars().count() >= 2 && seen.insert(clause) {
views.push(clause);
if views.len() == MAX_QUERY_VIEWS {
return views;
}
}
}
}
views
}
fn bounded(value: &str, max_bytes: usize) -> &str {
if value.len() <= max_bytes {
return value;
}
let mut end = max_bytes;
while !value.is_char_boundary(end) {
end = end.saturating_sub(1);
}
&value[..end]
}
fn split_connectors(value: &str) -> Vec<&str> {
let lowercase = value.to_ascii_lowercase();
let mut segments = Vec::new();
let mut start = 0;
while start < value.len() {
let next = CONNECTORS
.iter()
.filter_map(|connector| {
lowercase[start..]
.find(connector)
.map(|offset| (start + offset, connector.len()))
})
.min_by_key(|(position, _)| *position);
let Some((position, connector_length)) = next else {
break;
};
segments.push(&value[start..position]);
start = position + connector_length;
}
segments.push(&value[start..]);
segments
}
#[cfg(test)]
#[path = "multi_query_lexical_tests.rs"]
mod tests;

View File

@@ -0,0 +1,92 @@
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn multi_query_promotes_each_clause_leader() {
let documents = [
document(/*id*/ 1, "rust-format", "Format Rust source code."),
document(/*id*/ 2, "rust-lint", "Fix Rust source lint errors."),
document(/*id*/ 3, "rust-review", "Review Rust source code."),
document(
/*id*/ 4,
"ci-fix",
"Diagnose failing GitHub Actions checks.",
),
];
let selection = MultiQueryLexicalSkillSelector.select(
"format and review Rust source code, and then diagnose failing GitHub Actions checks",
&documents,
/*limit*/ 4,
);
assert!(selection.candidate_ids[..3].contains(&1));
assert!(selection.candidate_ids[..3].contains(&4));
}
#[test]
fn single_query_matches_the_underlying_selector() {
let documents = [
document(/*id*/ 1, "presentations", "Create visual decks."),
document(/*id*/ 2, "spreadsheets", "Analyze tabular data."),
];
let expected =
WeightedLexicalSkillSelector.select("create presentations", &documents, /*limit*/ 20);
let actual = MultiQueryLexicalSkillSelector.select(
"create presentations",
&documents,
/*limit*/ 20,
);
assert_eq!(expected, actual);
}
#[test]
fn query_views_split_sentences_and_connectors() {
assert_eq!(
vec![
"format code and then fix tests; write a summary",
"format code",
"fix tests",
"write a summary",
],
query_views("format code and then fix tests; write a summary"),
);
}
#[test]
fn multi_query_preserves_bounded_input_signals() {
let long_query = format!("{}\nand inspect logs", "match ".repeat(4 * 1024));
let names = (0..=1_000)
.map(|index| format!("candidate-{index}"))
.collect::<Vec<_>>();
let documents = names
.iter()
.enumerate()
.map(|(id, name)| SkillSelectionDocument {
id,
name,
short_description: None,
description: "match logs",
dependencies: None,
})
.collect::<Vec<_>>();
let selection =
MultiQueryLexicalSkillSelector.select(&long_query, &documents, /*limit*/ 20);
assert!(selection.query_truncated);
assert!(selection.candidate_set_truncated);
assert_eq!(20, selection.candidate_ids.len());
}
fn document<'a>(id: usize, name: &'a str, description: &'a str) -> SkillSelectionDocument<'a> {
SkillSelectionDocument {
id,
name,
short_description: None,
description,
dependencies: None,
}
}

View File

@@ -0,0 +1,258 @@
use std::collections::HashSet;
use super::CheapSkillSelection;
use super::CheapSkillSelector;
use super::SkillSelectionDocument;
const MAX_QUERY_BYTES: usize = 4 * 1024;
const MAX_QUERY_TERMS: usize = 64;
const MAX_DOCUMENT_BYTES: usize = 4 * 1024;
const MAX_FIELD_TERMS: usize = 256;
const MAX_DEPENDENCY_RECORDS: usize = 32;
const MAX_CANDIDATES: usize = 1_000;
const MAX_RESULTS: usize = 50;
const STOP_WORDS: &[&str] = &[
"a", "an", "and", "are", "as", "at", "be", "by", "do", "for", "from", "how", "i", "in", "is",
"it", "me", "my", "of", "on", "or", "please", "that", "the", "this", "to", "use", "we", "what",
"when", "where", "which", "with", "you", "your",
];
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct RoutingCardLexicalSkillSelector;
impl CheapSkillSelector for RoutingCardLexicalSkillSelector {
fn method(&self) -> &'static str {
"routing_card_exact_v1"
}
fn select(
&self,
query: &str,
documents: &[SkillSelectionDocument<'_>],
limit: usize,
) -> CheapSkillSelection {
let (query, query_bytes_truncated) = bounded(query, MAX_QUERY_BYTES);
let query_phrase = normalize(query);
let (query_terms, query_terms_truncated) = query_terms(&query_phrase);
let query_truncated = query_bytes_truncated || query_terms_truncated;
let candidate_set_truncated = documents.len() > MAX_CANDIDATES;
if query_phrase.is_empty() || limit == 0 {
return CheapSkillSelection {
query_term_count: query_terms.len(),
query_truncated,
candidate_set_truncated,
..Default::default()
};
}
let mut scored = documents
.iter()
.take(MAX_CANDIDATES)
.filter_map(|document| {
let prepared = PreparedRoutingCard::new(document);
let score = prepared.score(&query_phrase, &query_terms);
(score > 0).then_some((score, document.id, document.name))
})
.collect::<Vec<_>>();
scored.sort_by(|left, right| {
right
.0
.cmp(&left.0)
.then_with(|| left.2.cmp(right.2))
.then_with(|| left.1.cmp(&right.1))
});
CheapSkillSelection {
candidate_ids: scored
.into_iter()
.take(limit.min(MAX_RESULTS))
.map(|(_, id, _)| id)
.collect(),
query_term_count: query_terms.len(),
query_truncated,
candidate_set_truncated,
}
}
}
struct PreparedRoutingCard {
name: String,
name_has_searchable_term: bool,
fields: RoutingFields,
}
struct RoutingFields {
name: HashSet<String>,
dependencies: HashSet<String>,
short_description: HashSet<String>,
description: HashSet<String>,
}
impl PreparedRoutingCard {
fn new(document: &SkillSelectionDocument<'_>) -> Self {
let name = normalize_bounded(document.name);
Self {
name_has_searchable_term: name.split_whitespace().any(is_searchable_query_term),
name,
fields: RoutingFields {
name: field_terms(document.name),
dependencies: dependency_terms(document),
short_description: field_terms(document.short_description.unwrap_or_default()),
description: field_terms(document.description),
},
}
}
fn score(&self, query_phrase: &str, query_terms: &[&str]) -> u32 {
let mut score = 0u32;
let name_phrase_matches = contains_phrase(query_phrase, &self.name);
if !self.name.is_empty()
&& ((self.name_has_searchable_term && name_phrase_matches) || query_phrase == self.name)
{
score = score.saturating_add(256);
}
let mut matched_query_terms = 0u32;
for query_term in query_terms {
let mut matched = false;
score = score.saturating_add(score_field(
&self.fields.name,
query_term,
/*weight*/ 80,
&mut matched,
));
score = score.saturating_add(score_field(
&self.fields.dependencies,
query_term,
/*weight*/ 24,
&mut matched,
));
score = score.saturating_add(score_field(
&self.fields.short_description,
query_term,
/*weight*/ 12,
&mut matched,
));
score = score.saturating_add(score_field(
&self.fields.description,
query_term,
/*weight*/ 3,
&mut matched,
));
if matched {
matched_query_terms = matched_query_terms.saturating_add(1);
}
}
score.saturating_add(matched_query_terms.saturating_mul(matched_query_terms))
}
}
fn score_field(terms: &HashSet<String>, query_term: &str, weight: u32, matched: &mut bool) -> u32 {
if terms.contains(query_term) {
*matched = true;
weight
} else {
0
}
}
fn dependency_terms(document: &SkillSelectionDocument<'_>) -> HashSet<String> {
let mut terms = HashSet::new();
let Some(dependencies) = document.dependencies else {
return terms;
};
let mut remaining_bytes = MAX_DOCUMENT_BYTES;
for tool in dependencies.tools.iter().take(MAX_DEPENDENCY_RECORDS) {
extend_terms(&mut terms, &tool.value, &mut remaining_bytes);
if let Some(description) = tool.description.as_deref() {
extend_terms(&mut terms, description, &mut remaining_bytes);
}
if remaining_bytes == 0 || terms.len() >= MAX_FIELD_TERMS {
break;
}
}
terms
}
fn field_terms(value: &str) -> HashSet<String> {
normalized_terms(bounded(value, MAX_DOCUMENT_BYTES).0)
.into_iter()
.take(MAX_FIELD_TERMS)
.collect()
}
fn extend_terms(terms: &mut HashSet<String>, value: &str, remaining_bytes: &mut usize) {
let value = bounded(value, *remaining_bytes).0;
*remaining_bytes = remaining_bytes.saturating_sub(value.len());
for term in normalized_terms(value) {
if terms.len() == MAX_FIELD_TERMS {
return;
}
terms.insert(term);
}
}
fn query_terms(query_phrase: &str) -> (Vec<&str>, bool) {
let mut seen = HashSet::new();
let mut terms = Vec::new();
for term in query_phrase
.split_whitespace()
.filter(|term| is_searchable_query_term(term))
{
if !seen.insert(term) {
continue;
}
if terms.len() == MAX_QUERY_TERMS {
return (terms, true);
}
terms.push(term);
}
(terms, false)
}
fn is_searchable_query_term(term: &str) -> bool {
term.chars().count() >= 2 && !STOP_WORDS.contains(&term)
}
fn normalize_bounded(value: &str) -> String {
normalize(bounded(value, MAX_DOCUMENT_BYTES).0)
}
fn normalize(value: &str) -> String {
normalized_terms(value).join(" ")
}
fn normalized_terms(value: &str) -> Vec<String> {
let mut normalized = String::with_capacity(value.len());
for character in value.chars() {
if character.is_alphanumeric() {
normalized.extend(character.to_lowercase());
} else {
normalized.push(' ');
}
}
normalized.split_whitespace().map(str::to_string).collect()
}
fn contains_phrase(haystack: &str, needle: &str) -> bool {
haystack == needle
|| haystack.starts_with(&format!("{needle} "))
|| haystack.ends_with(&format!(" {needle}"))
|| haystack.contains(&format!(" {needle} "))
}
fn bounded(value: &str, max_bytes: usize) -> (&str, bool) {
if value.len() <= max_bytes {
return (value, false);
}
let mut end = max_bytes;
while !value.is_char_boundary(end) {
end = end.saturating_sub(1);
}
(&value[..end], true)
}
#[cfg(test)]
#[path = "routing_card_lexical_tests.rs"]
mod tests;

View File

@@ -0,0 +1,134 @@
use codex_skills::SkillDependencies;
use codex_skills::SkillToolDependency;
use pretty_assertions::assert_eq;
use super::*;
#[test]
fn dependency_names_outrank_description_only_matches() {
let dependencies = SkillDependencies {
tools: vec![SkillToolDependency {
r#type: "app".to_string(),
value: "slack".to_string(),
description: Some("Send messages to Slack channels.".to_string()),
transport: None,
command: None,
url: None,
oauth_callback_port: None,
}],
};
let documents = [
SkillSelectionDocument {
id: 1,
name: "team-messaging",
short_description: None,
description: "Work with team communication.",
dependencies: Some(&dependencies),
},
document(
/*id*/ 2,
"documents",
"Send messages to Slack channels.",
),
];
let selection = RoutingCardLexicalSkillSelector.select(
"send this update to Slack",
&documents,
/*limit*/ 20,
);
assert_eq!(vec![1, 2], selection.candidate_ids);
}
#[test]
fn stop_word_name_requires_an_exact_query() {
let documents = [document(/*id*/ 1, "do", "Run a task.")];
let selection = RoutingCardLexicalSkillSelector.select("do", &documents, /*limit*/ 20);
assert_eq!(vec![1], selection.candidate_ids);
assert_eq!(0, selection.query_term_count);
let selection = RoutingCardLexicalSkillSelector.select(
"how do I format Rust",
&documents,
/*limit*/ 20,
);
assert_eq!(Vec::<usize>::new(), selection.candidate_ids);
}
#[test]
fn prefixes_do_not_match_field_terms() {
let documents = [document(
/*id*/ 1,
"presentations",
"Create presentations.",
)];
let selection =
RoutingCardLexicalSkillSelector.select("present", &documents, /*limit*/ 20);
assert_eq!(Vec::<usize>::new(), selection.candidate_ids);
}
#[test]
fn dependency_records_are_bounded() {
let mut tools = (0..MAX_DEPENDENCY_RECORDS)
.map(|_| SkillToolDependency {
r#type: "app".to_string(),
value: "shared".to_string(),
description: None,
transport: None,
command: None,
url: None,
oauth_callback_port: None,
})
.collect::<Vec<_>>();
tools.push(SkillToolDependency {
r#type: "app".to_string(),
value: "unbounded".to_string(),
description: None,
transport: None,
command: None,
url: None,
oauth_callback_port: None,
});
let dependencies = SkillDependencies { tools };
let document = SkillSelectionDocument {
id: 1,
name: "dependency-test",
short_description: None,
description: "Test dependencies.",
dependencies: Some(&dependencies),
};
assert_eq!(
HashSet::from(["shared".to_string()]),
dependency_terms(&document)
);
}
#[test]
fn selector_reports_bounded_inputs() {
let documents = [document(
/*id*/ 1,
"presentations",
"Create visual decks.",
)];
let query = "presentations ".repeat(MAX_QUERY_BYTES);
let selection = RoutingCardLexicalSkillSelector.select(&query, &documents, /*limit*/ 20);
assert_eq!(vec![1], selection.candidate_ids);
assert!(selection.query_truncated);
}
fn document<'a>(id: usize, name: &'a str, description: &'a str) -> SkillSelectionDocument<'a> {
SkillSelectionDocument {
id,
name,
short_description: None,
description,
dependencies: None,
}
}

View File

@@ -0,0 +1,93 @@
use std::collections::HashMap;
use super::CharacterNgramSkillSelector;
use super::CheapSkillSelection;
use super::CheapSkillSelector;
use super::SkillSelectionDocument;
use super::WeightedLexicalSkillSelector;
const MAX_FUSION_CANDIDATES: usize = 50;
const RRF_K: usize = 60;
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct RrfLexicalCharSkillSelector;
impl CheapSkillSelector for RrfLexicalCharSkillSelector {
fn method(&self) -> &'static str {
"rrf_lexical_char_v1"
}
fn select(
&self,
query: &str,
documents: &[SkillSelectionDocument<'_>],
limit: usize,
) -> CheapSkillSelection {
if limit == 0 {
return CheapSkillSelection::default();
}
let lexical = WeightedLexicalSkillSelector.select(
query,
documents,
/*limit*/ MAX_FUSION_CANDIDATES,
);
let character = CharacterNgramSkillSelector.select(
query,
documents,
/*limit*/ MAX_FUSION_CANDIDATES,
);
let candidate_ids = fuse_rankings(
[&lexical.candidate_ids, &character.candidate_ids],
limit.min(MAX_FUSION_CANDIDATES),
);
CheapSkillSelection {
candidate_ids,
query_term_count: lexical.query_term_count.max(character.query_term_count),
query_truncated: lexical.query_truncated || character.query_truncated,
candidate_set_truncated: lexical.candidate_set_truncated
|| character.candidate_set_truncated,
}
}
}
fn fuse_rankings<const N: usize>(rankings: [&[usize]; N], limit: usize) -> Vec<usize> {
fuse_rankings_with_constant(rankings, limit, RRF_K)
}
pub(super) fn fuse_rankings_with_constant<const N: usize>(
rankings: [&[usize]; N],
limit: usize,
rank_constant: usize,
) -> Vec<usize> {
let mut scores = HashMap::<usize, f64>::new();
let mut best_ranks = HashMap::<usize, usize>::new();
for ranking in rankings {
for (index, id) in ranking.iter().copied().enumerate() {
let rank = index + 1;
*scores.entry(id).or_default() += 1.0 / (rank_constant + rank) as f64;
best_ranks
.entry(id)
.and_modify(|best_rank| *best_rank = (*best_rank).min(rank))
.or_insert(rank);
}
}
let mut candidates = scores.into_iter().collect::<Vec<_>>();
candidates.sort_by(|(left_id, left_score), (right_id, right_score)| {
right_score
.total_cmp(left_score)
.then_with(|| best_ranks[left_id].cmp(&best_ranks[right_id]))
.then_with(|| left_id.cmp(right_id))
});
candidates
.into_iter()
.take(limit)
.map(|(id, _)| id)
.collect()
}
#[cfg(test)]
#[path = "rrf_lexical_char_tests.rs"]
mod tests;

View File

@@ -0,0 +1,35 @@
use pretty_assertions::assert_eq;
use super::*;
#[test]
fn fusion_prefers_candidates_supported_by_both_rankings() {
let fused = fuse_rankings([&[1, 2, 3], &[2, 3, 4]], /*limit*/ 4);
assert_eq!(vec![2, 3, 1, 4], fused);
}
#[test]
fn fusion_uses_rank_and_id_to_break_ties() {
let fused = fuse_rankings([&[20, 10], &[30]], /*limit*/ 3);
assert_eq!(vec![20, 30, 10], fused);
}
#[test]
fn selector_reports_the_combined_input_bounds() {
let documents = [SkillSelectionDocument {
id: 7,
name: "presentations",
short_description: None,
description: "Create visual decks.",
dependencies: None,
}];
let query = "presentation ".repeat(4 * 1024);
let selection = RrfLexicalCharSkillSelector.select(&query, &documents, /*limit*/ 20);
assert_eq!(vec![7], selection.candidate_ids);
assert!(selection.query_truncated);
assert!(!selection.candidate_set_truncated);
}

View File

@@ -0,0 +1,208 @@
use std::collections::HashSet;
use super::CheapSkillSelection;
use super::CheapSkillSelector;
use super::SkillSelectionDocument;
const MAX_QUERY_BYTES: usize = 4 * 1024;
const MAX_QUERY_TERMS: usize = 64;
const MAX_DOCUMENT_BYTES: usize = 4 * 1024;
const MAX_DOCUMENT_TERMS: usize = 256;
const MAX_CANDIDATES: usize = 1_000;
const MAX_RESULTS: usize = 50;
const STOP_WORDS: &[&str] = &[
"a", "an", "and", "are", "as", "at", "be", "by", "do", "for", "from", "how", "i", "in", "is",
"it", "me", "my", "of", "on", "or", "please", "that", "the", "this", "to", "use", "we", "what",
"when", "where", "which", "with", "you", "your",
];
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct WeightedLexicalSkillSelector;
impl CheapSkillSelector for WeightedLexicalSkillSelector {
fn method(&self) -> &'static str {
"weighted_lexical_v1"
}
fn select(
&self,
query: &str,
documents: &[SkillSelectionDocument<'_>],
limit: usize,
) -> CheapSkillSelection {
let (query, query_bytes_truncated) = bounded(query, MAX_QUERY_BYTES);
let query_phrase = normalize_phrase(query);
let (query_terms, query_terms_truncated) = query_terms(&query_phrase);
let query_truncated = query_bytes_truncated || query_terms_truncated;
let candidate_set_truncated = documents.len() > MAX_CANDIDATES;
if query_terms.is_empty() || limit == 0 {
return CheapSkillSelection {
query_term_count: query_terms.len(),
query_truncated,
candidate_set_truncated,
..Default::default()
};
}
let mut scored = documents
.iter()
.take(MAX_CANDIDATES)
.filter_map(|document| {
let score = score_document(&query_phrase, &query_terms, document);
(score > 0).then_some((score, document.id, document.name))
})
.collect::<Vec<_>>();
scored.sort_by(|left, right| {
right
.0
.cmp(&left.0)
.then_with(|| left.2.cmp(right.2))
.then_with(|| left.1.cmp(&right.1))
});
CheapSkillSelection {
candidate_ids: scored
.into_iter()
.take(limit.min(MAX_RESULTS))
.map(|(_, id, _)| id)
.collect(),
query_term_count: query_terms.len(),
query_truncated,
candidate_set_truncated,
}
}
}
fn score_document(
query_phrase: &str,
query_terms: &[&str],
document: &SkillSelectionDocument<'_>,
) -> u32 {
let name = normalize_bounded(document.name);
let short_description = document
.short_description
.map(normalize_bounded)
.unwrap_or_default();
let description = normalize_bounded(document.description);
let name_terms = phrase_terms(&name);
let short_description_terms = phrase_terms(&short_description);
let description_terms = phrase_terms(&description);
let mut score = 0u32;
if !name.is_empty() && contains_phrase(query_phrase, &name) {
score = score.saturating_add(256);
}
let mut matched_query_terms = 0u32;
for query_term in query_terms {
let mut matched = false;
if name == *query_term {
score = score.saturating_add(128);
matched = true;
} else if name_terms.contains(query_term) {
score = score.saturating_add(64);
matched = true;
} else if contains_related_term(&name_terms, query_term) {
score = score.saturating_add(24);
matched = true;
}
if short_description_terms.contains(query_term) {
score = score.saturating_add(16);
matched = true;
} else if contains_related_term(&short_description_terms, query_term) {
score = score.saturating_add(6);
matched = true;
}
if description_terms.contains(query_term) {
score = score.saturating_add(4);
matched = true;
} else if contains_related_term(&description_terms, query_term) {
score = score.saturating_add(1);
matched = true;
}
if matched {
matched_query_terms = matched_query_terms.saturating_add(1);
}
}
score.saturating_add(matched_query_terms.saturating_mul(matched_query_terms))
}
fn normalize_bounded(value: &str) -> String {
normalize_phrase(bounded(value, MAX_DOCUMENT_BYTES).0)
}
fn normalize_phrase(value: &str) -> String {
let mut normalized = String::with_capacity(value.len());
let mut previous_was_separator = true;
for character in value.chars() {
if character.is_alphanumeric() {
normalized.extend(character.to_lowercase());
previous_was_separator = false;
} else if !previous_was_separator {
normalized.push(' ');
previous_was_separator = true;
}
}
if previous_was_separator {
normalized.pop();
}
normalized
}
fn query_terms(query_phrase: &str) -> (Vec<&str>, bool) {
let mut seen = HashSet::new();
let mut terms = Vec::new();
for term in query_phrase
.split_whitespace()
.filter(|term| term.chars().count() >= 2 && !STOP_WORDS.contains(term))
{
if !seen.insert(term) {
continue;
}
if terms.len() == MAX_QUERY_TERMS {
return (terms, true);
}
terms.push(term);
}
(terms, false)
}
fn phrase_terms(phrase: &str) -> HashSet<&str> {
phrase.split_whitespace().take(MAX_DOCUMENT_TERMS).collect()
}
fn contains_phrase(haystack: &str, needle: &str) -> bool {
haystack == needle
|| haystack.starts_with(&format!("{needle} "))
|| haystack.ends_with(&format!(" {needle}"))
|| haystack.contains(&format!(" {needle} "))
}
fn contains_related_term(terms: &HashSet<&str>, query_term: &str) -> bool {
if query_term.chars().count() < 4 {
return false;
}
terms.iter().any(|term| {
term.chars().count() >= 4 && (term.starts_with(query_term) || query_term.starts_with(*term))
})
}
fn bounded(value: &str, max_bytes: usize) -> (&str, bool) {
if value.len() <= max_bytes {
return (value, false);
}
let mut end = max_bytes;
while !value.is_char_boundary(end) {
end = end.saturating_sub(1);
}
(&value[..end], true)
}
#[cfg(test)]
#[path = "weighted_lexical_tests.rs"]
mod tests;

View File

@@ -0,0 +1,176 @@
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn lexical_selector_prioritizes_an_exact_skill_name() {
let documents = [
SkillSelectionDocument {
id: 10,
name: "slides-helper",
short_description: None,
description: "Create presentations and visual decks.",
dependencies: None,
},
SkillSelectionDocument {
id: 20,
name: "presentations",
short_description: None,
description: "Create or edit PowerPoint presentations.",
dependencies: None,
},
SkillSelectionDocument {
id: 30,
name: "spreadsheets",
short_description: None,
description: "Analyze tabular data.",
dependencies: None,
},
];
let selection = WeightedLexicalSkillSelector.select(
"Use presentations to create a deck",
&documents,
/*limit*/ 20,
);
assert_eq!(vec![20, 10], selection.candidate_ids);
assert!(!selection.query_truncated);
assert!(!selection.candidate_set_truncated);
}
#[test]
fn lexical_selector_uses_descriptions_and_drops_zero_score_candidates() {
let documents = [
SkillSelectionDocument {
id: 1,
name: "ci-helper",
short_description: Some("Diagnose continuous integration failures."),
description: "Inspect failing GitHub Actions checks and logs.",
dependencies: None,
},
SkillSelectionDocument {
id: 2,
name: "document-editor",
short_description: None,
description: "Edit Word documents.",
dependencies: None,
},
];
let selection = WeightedLexicalSkillSelector.select(
"Please diagnose the failing GitHub Actions check",
&documents,
/*limit*/ 20,
);
assert_eq!(vec![1], selection.candidate_ids);
}
#[test]
fn lexical_selector_respects_requested_limit() {
let names = (0..10)
.map(|index| format!("lint-{index}"))
.collect::<Vec<_>>();
let documents = names
.iter()
.enumerate()
.map(|(id, name)| SkillSelectionDocument {
id,
name,
short_description: None,
description: "Fix lint errors.",
dependencies: None,
})
.collect::<Vec<_>>();
let selection =
WeightedLexicalSkillSelector.select("fix lint errors", &documents, /*limit*/ 3);
assert_eq!(3, selection.candidate_ids.len());
}
#[test]
fn lexical_selector_reports_bounded_inputs() {
let long_query = "match ".repeat(MAX_QUERY_BYTES);
let names = (0..=MAX_CANDIDATES)
.map(|index| format!("candidate-{index}"))
.collect::<Vec<_>>();
let documents = names
.iter()
.enumerate()
.map(|(id, name)| SkillSelectionDocument {
id,
name,
short_description: None,
description: "match",
dependencies: None,
})
.collect::<Vec<_>>();
let selection = WeightedLexicalSkillSelector.select(&long_query, &documents, /*limit*/ 20);
assert!(selection.query_truncated);
assert!(selection.candidate_set_truncated);
assert_eq!(20, selection.candidate_ids.len());
assert!(
selection
.candidate_ids
.iter()
.all(|id| *id < MAX_CANDIDATES)
);
}
#[test]
fn lexical_selector_caps_query_terms() {
let query = (0..=MAX_QUERY_TERMS)
.map(|index| format!("term{index}"))
.collect::<Vec<_>>()
.join(" ");
let documents = [SkillSelectionDocument {
id: 1,
name: "term0",
short_description: None,
description: "term0",
dependencies: None,
}];
let selection = WeightedLexicalSkillSelector.select(&query, &documents, /*limit*/ 20);
assert_eq!(MAX_QUERY_TERMS, selection.query_term_count);
assert!(selection.query_truncated);
}
#[test]
fn lexical_selector_returns_nothing_for_stop_words_only() {
let documents = [SkillSelectionDocument {
id: 1,
name: "anything",
short_description: None,
description: "Do anything.",
dependencies: None,
}];
let selection =
WeightedLexicalSkillSelector.select("please use the", &documents, /*limit*/ 20);
assert_eq!(CheapSkillSelection::default(), selection);
}
#[test]
fn selector_can_be_used_behind_the_shared_trait() {
fn run(selector: &dyn CheapSkillSelector) -> CheapSkillSelection {
selector.select(
"review code",
&[SkillSelectionDocument {
id: 7,
name: "code-review",
short_description: None,
description: "Review code.",
dependencies: None,
}],
/*limit*/ 20,
)
}
assert_eq!(vec![7], run(&WeightedLexicalSkillSelector).candidate_ids);
}

View File

@@ -0,0 +1,640 @@
use std::sync::Arc;
use crate::HostSkillsSnapshot;
use crate::InjectedHostSkillPrompts;
use codex_analytics::InvocationType;
use codex_exec_server::LOCAL_ENVIRONMENT_ID;
use codex_extension_api::ConfigContributor;
use codex_extension_api::ContextContributor;
use codex_extension_api::ContextualUserFragment;
use codex_extension_api::ExtensionData;
use codex_extension_api::ExtensionEventSink;
use codex_extension_api::ExtensionFuture;
use codex_extension_api::ExtensionMetrics;
use codex_extension_api::ExtensionRegistryBuilder;
use codex_extension_api::ExtensionWarning;
use codex_extension_api::PromptFragment;
use codex_extension_api::PromptSlot;
use codex_extension_api::SkillInvocationContributor;
use codex_extension_api::SkillInvocationInput;
use codex_extension_api::SkillInvocationKind;
use codex_extension_api::ThreadLifecycleContributor;
use codex_extension_api::ThreadStartInput;
use codex_extension_api::ToolCall;
use codex_extension_api::ToolContributor;
use codex_extension_api::ToolExecutor;
use codex_extension_api::TurnInputContext;
use codex_extension_api::TurnInputContributor;
use codex_extension_api::WorldStateContributionInput;
use codex_extension_api::WorldStateSectionContribution;
use codex_mcp::McpResourceClient;
use codex_otel::MetricsClient;
use codex_protocol::openai_models::ModelInfo;
use crate::SkillsExtensionConfig;
use crate::catalog::SkillCatalog;
use crate::catalog::SkillCatalogEntry;
use crate::catalog::SkillReadResult;
use crate::catalog::SkillSourceKind;
use crate::fragments::AvailableSkillsInstructions;
use crate::fragments::SkillInstructions;
use crate::fragments::SkillResourceAccess;
use crate::preparation::prepare_catalogs;
use crate::provider::HostSkillProvider;
use crate::provider::SkillListQuery;
use crate::provider::SkillReadContext;
use crate::provider::SkillReadRequest;
use crate::render::AvailableSkillsRender;
use crate::render::MAX_SKILL_NAME_BYTES;
use crate::render::MAX_SKILL_PATH_BYTES;
use crate::render::SkillCatalogRenderPolicy;
use crate::render::SkillMetadataBudget;
use crate::render::SkillRenderReport;
use crate::render::render_available_skills;
use crate::render::skill_metadata_budget;
use crate::render::truncate_main_prompt_contents;
use crate::render::truncate_utf8_to_bytes;
use crate::render_observability::CatalogSurface;
use crate::render_observability::record_catalog_render;
use crate::selection::collect_explicit_skill_mentions;
use crate::shadow_selection_experiment::ShadowSelectionExperiment;
use crate::sources::SkillProviders;
use crate::state::HostSkillsCatalogInWorldState;
use crate::state::SkillsSessionState;
use crate::state::SkillsThreadState;
use crate::step_state::SkillsStepState;
use crate::telemetry::SkillTelemetry;
use crate::tools::SkillAnalytics;
use crate::tools::SkillToolAuthority;
use crate::tools::skill_tools;
use crate::warnings::bounded_warnings;
use crate::world_state_catalogs::render_world_state_sections;
#[path = "cloud_skill.rs"]
mod cloud_skill;
struct SkillsExtension<C> {
providers: SkillProviders,
event_sink: Arc<dyn ExtensionEventSink>,
config_from_host: Arc<dyn Fn(&C) -> SkillsExtensionConfig + Send + Sync>,
shadow_selection: Arc<ShadowSelectionExperiment>,
}
#[derive(Default)]
struct RenderedCatalog {
fragment: Option<AvailableSkillsInstructions>,
warning_message: Option<String>,
}
fn render_catalog(
extension_metrics: Option<&dyn ExtensionMetrics>,
catalog_surface: CatalogSurface,
catalog: &SkillCatalog,
include_skills_usage_instructions: bool,
policy: SkillCatalogRenderPolicy,
budget: SkillMetadataBudget,
) -> RenderedCatalog {
render_prepared_catalog(
extension_metrics,
catalog_surface,
include_skills_usage_instructions,
budget,
render_available_skills(
catalog,
policy,
budget,
include_skills_usage_instructions,
/*alias_plan*/ None,
),
)
}
fn render_prepared_catalog(
extension_metrics: Option<&dyn ExtensionMetrics>,
catalog_surface: CatalogSurface,
include_skills_usage_instructions: bool,
budget: SkillMetadataBudget,
rendered: Option<AvailableSkillsRender>,
) -> RenderedCatalog {
let Some(rendered) = rendered else {
record_catalog_render(
extension_metrics,
catalog_surface,
budget,
&SkillRenderReport::default(),
);
return RenderedCatalog::default();
};
record_catalog_render(extension_metrics, catalog_surface, budget, &rendered.report);
let warning_message = rendered
.report
.warning_message(/*catalog_deltas_enabled*/ false);
let fragment = rendered.into_fragment(include_skills_usage_instructions);
RenderedCatalog {
fragment,
warning_message,
}
}
#[cfg(test)]
#[path = "extension_tests.rs"]
mod tests;
impl<C> ThreadLifecycleContributor<C> for SkillsExtension<C>
where
C: Send + Sync + 'static,
{
fn on_thread_start<'a>(&'a self, input: ThreadStartInput<'a, C>) -> ExtensionFuture<'a, ()> {
Box::pin(async move {
input.session_store.insert(SkillsSessionState {
mcp_resources: input.mcp_resource_client.clone(),
extension_metrics: input.extension_metrics.clone(),
});
let cloud_skills_available = self.providers.has_cloud_provider()
&& !input
.environments
.iter()
.any(|environment| environment.environment_id == LOCAL_ENVIRONMENT_ID);
input.thread_store.insert(SkillsThreadState::new(
(self.config_from_host)(input.config),
cloud_skills_available,
input.extension_metrics,
));
})
}
}
impl<C> ConfigContributor<C> for SkillsExtension<C>
where
C: Send + Sync + 'static,
{
fn on_config_changed(
&self,
session_store: &ExtensionData,
thread_store: &ExtensionData,
_previous_config: &C,
new_config: &C,
) {
let next_config = (self.config_from_host)(new_config);
if let Some(state) = thread_store.get::<SkillsThreadState>() {
state.set_config(next_config);
} else {
let cloud_skills_available = self.providers.has_cloud_provider();
thread_store.insert(SkillsThreadState::new(
next_config,
cloud_skills_available,
session_store
.get::<SkillsSessionState>()
.and_then(|state| state.extension_metrics.clone()),
));
}
}
}
impl<C> ContextContributor for SkillsExtension<C>
where
C: Send + Sync + 'static,
{
fn contribute_thread_context<'a>(
&'a self,
session_store: &'a ExtensionData,
thread_store: &'a ExtensionData,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = Vec<PromptFragment>> + Send + 'a>> {
Box::pin(async move {
let Some(thread_state) = thread_store.get::<SkillsThreadState>() else {
return Vec::new();
};
let config = thread_state.config();
if !config.include_instructions {
return Vec::new();
}
let catalog = self
.providers
.list_for_turn(SkillListQuery {
turn_id: thread_store.level_id().to_string(),
executor_roots: Vec::new(),
host_snapshot: None,
include_host_skills: false,
include_bundled_skills: config.bundled_skills_enabled,
include_cloud_skills: false,
mcp_resources: session_store
.get::<SkillsSessionState>()
.and_then(|state| state.mcp_resources.clone()),
executor_capability_discovery: None,
executor_capability_discovery_v2: None,
})
.await;
for warning in bounded_warnings(&catalog.warnings) {
self.emit_warning(thread_store.level_id(), /*turn_id*/ None, warning);
}
let include_usage = thread_store
.get::<ModelInfo>()
.is_some_and(|model_info| model_info.include_skills_usage_instructions);
let extension_metrics = session_store
.get::<SkillsSessionState>()
.and_then(|state| state.extension_metrics.clone());
let rendered = render_catalog(
extension_metrics.as_deref(),
CatalogSurface::ThreadContext,
&catalog,
include_usage,
SkillCatalogRenderPolicy::EXTENSION_COMPATIBLE
.with_omitted_descriptions(config.omit_descriptions),
skill_metadata_budget(/*context_window*/ None, config.max_context_tokens),
);
if let Some(message) = rendered.warning_message {
self.emit_warning(thread_store.level_id(), /*turn_id*/ None, message);
}
rendered
.fragment
.map(|fragment| {
PromptFragment::from_fragment(PromptSlot::DeveloperCapabilities, &fragment)
})
.into_iter()
.collect()
})
}
fn contribute_world_state<'a>(
&'a self,
input: WorldStateContributionInput<'a>,
) -> ExtensionFuture<'a, Vec<WorldStateSectionContribution>> {
Box::pin(async move { render_world_state_sections(Arc::clone(&self.event_sink), input) })
}
}
impl<C> ToolContributor for SkillsExtension<C>
where
C: Send + Sync + 'static,
{
fn prepare_for_step<'a>(
&'a self,
input: codex_extension_api::StepPreparationInput<'a>,
) -> ExtensionFuture<'a, ()> {
Box::pin(async move {
if input.step_store.get::<SkillsStepState>().is_some() {
return;
}
if let Some(thread_state) = input.thread_store.get::<SkillsThreadState>() {
let state = prepare_catalogs(&thread_state, &self.providers, &input).await;
input.step_store.insert(state);
}
})
}
fn tools_for_step(
&self,
session_store: &ExtensionData,
thread_store: &ExtensionData,
step_store: &ExtensionData,
) -> Vec<Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>> {
skill_tools(
self.providers.clone(),
session_store,
thread_store,
step_store,
)
}
}
impl<C> SkillInvocationContributor for SkillsExtension<C>
where
C: Send + Sync + 'static,
{
fn requires_host_skill_discovery(&self) -> bool {
self.providers.has_host_provider()
}
fn on_skill_invocation<'a>(
&'a self,
input: SkillInvocationInput<'a>,
) -> ExtensionFuture<'a, ()> {
Box::pin(async move {
match input.kind {
SkillInvocationKind::Implicit => {
if let Some(state) = input
.thread_store
.get::<SkillsThreadState>()
.and_then(|state| state.shadow_selection_turn(input.turn_id))
{
state.record_invocation(input.skill_resource);
}
}
SkillInvocationKind::Explicit => {}
}
})
}
}
impl<C> TurnInputContributor for SkillsExtension<C>
where
C: Send + Sync + 'static,
{
fn contribute<'a>(
&'a self,
input: TurnInputContext<'a>,
extension_metrics: Option<Arc<dyn ExtensionMetrics>>,
session_store: &'a ExtensionData,
thread_store: &'a ExtensionData,
turn_store: &'a ExtensionData,
) -> ExtensionFuture<'a, Vec<Box<dyn ContextualUserFragment + Send>>> {
Box::pin(async move {
let Some(thread_state) = thread_store.get::<SkillsThreadState>() else {
return Vec::new();
};
let mcp_resources = session_store
.get::<SkillsSessionState>()
.and_then(|state| state.mcp_resources.clone());
let host_snapshot = HostSkillsSnapshot::for_step(input.step_store, turn_store);
let host_catalog_in_world_state =
turn_store.get::<HostSkillsCatalogInWorldState>().is_some();
let Some(step_state) = input.step_store.get::<SkillsStepState>() else {
return Vec::new();
};
let config = &step_state.config;
let host_skills = step_state.host_catalog.as_ref();
let query = SkillListQuery {
turn_id: input.turn_id.clone(),
executor_roots: Vec::new(),
host_snapshot: host_snapshot.clone(),
include_host_skills: host_skills.is_none() && !host_catalog_in_world_state,
include_bundled_skills: config.bundled_skills_enabled,
// Cloud and executor catalogs come from the prepared step snapshot.
include_cloud_skills: false,
mcp_resources: mcp_resources.clone(),
executor_capability_discovery: None,
executor_capability_discovery_v2: None,
};
let mut catalog = step_state.catalog.merged.clone();
if !host_catalog_in_world_state && let Some(host_skills) = host_skills {
catalog.extend(host_skills.clone());
}
catalog.extend(self.providers.list_for_turn(query).await);
for warning in bounded_warnings(&catalog.warnings) {
self.emit_warning(thread_store.level_id(), Some(&input.turn_id), warning);
}
let selected_entries = collect_explicit_skill_mentions(&input.user_input, &catalog);
let shadow_selection_turn = if config.shadow_selection_enabled {
let mut shadow_catalog = catalog.clone();
if let Some(host_skills) = host_skills {
shadow_catalog.extend(host_skills.clone());
}
let shadow_selected_entries =
collect_explicit_skill_mentions(&input.user_input, &shadow_catalog);
Some(self.shadow_selection.start(
&input,
shadow_catalog,
&shadow_selected_entries,
host_snapshot.clone(),
Arc::clone(&thread_state.recent_skill_invocations),
Arc::clone(&thread_state.shadow_task_context),
))
} else {
None
};
thread_state
.replace_shadow_selection_turn(input.turn_id.clone(), shadow_selection_turn);
let mut fragments: Vec<Box<dyn ContextualUserFragment + Send>> = Vec::new();
if config.include_instructions && !host_catalog_in_world_state {
let mut turn_catalog = catalog.clone();
turn_catalog.entries.retain(|entry| {
entry.authority.kind != SkillSourceKind::Executor
&& entry.authority.kind != SkillSourceKind::Cloud
});
let model_info = thread_store.get::<ModelInfo>();
let include_usage = model_info
.as_deref()
.is_some_and(|model_info| model_info.include_skills_usage_instructions);
let context_window = model_info
.as_deref()
.and_then(ModelInfo::resolved_context_window);
let metadata_budget =
skill_metadata_budget(context_window, config.max_context_tokens);
let rendered = render_catalog(
extension_metrics.as_deref(),
CatalogSurface::TurnInput,
&turn_catalog,
include_usage,
SkillCatalogRenderPolicy::EXTENSION_COMPATIBLE
.with_omitted_descriptions(config.omit_descriptions),
metadata_budget,
);
if let Some(message) = rendered.warning_message {
self.emit_warning(thread_store.level_id(), Some(&input.turn_id), message);
}
if let Some(fragment) = rendered.fragment {
fragments.push(Box::new(fragment));
}
}
let mut injected_host_skill_prompts = InjectedHostSkillPrompts::default();
let analytics = SkillAnalytics::from_stores(session_store, thread_store);
for entry in &selected_entries {
match self
.read_main_prompt(
entry,
host_snapshot.clone(),
mcp_resources.clone(),
&thread_state,
&input,
)
.await
{
Ok(read_result) => {
let (contents, truncated) =
truncate_main_prompt_contents(read_result.contents.as_str());
if truncated {
let warning = format!(
"Skill `{}` exceeded the main prompt context limit and was truncated.",
entry.name
);
self.emit_warning(
thread_store.level_id(),
Some(&input.turn_id),
warning.clone(),
);
}
let fragment = SkillInstructions {
name: truncate_utf8_to_bytes(&entry.name, MAX_SKILL_NAME_BYTES).0,
path: truncate_utf8_to_bytes(
entry.rendered_path(),
MAX_SKILL_PATH_BYTES,
)
.0,
contents,
resource_access: (!entry.prompt_visible)
.then_some(&entry.authority)
.and_then(SkillToolAuthority::from_authority)
.map(|authority| SkillResourceAccess {
authority,
package: entry.id.0.clone(),
main_resource: entry.main_prompt.as_str().to_string(),
}),
};
fragments.push(Box::new(fragment));
if entry.authority.kind == SkillSourceKind::Host {
injected_host_skill_prompts.insert_path(entry.main_prompt.as_str());
} else if let Some(analytics) = analytics.as_ref()
&& let Some(model_info) = thread_store.get::<ModelInfo>()
{
analytics.track_skill_invocation(
entry,
&entry.primary_source(),
model_info.slug.clone(),
input.turn_id.clone(),
InvocationType::Explicit,
);
}
}
Err(message) => {
let warning = format!("Failed to load skill `{}`: {message}", entry.name);
self.emit_warning(
thread_store.level_id(),
Some(&input.turn_id),
warning.clone(),
);
}
}
}
if let Some(host_snapshot) = &host_snapshot {
for entry in selected_entries
.iter()
.filter(|entry| entry.authority.kind != SkillSourceKind::Host)
{
for host_skill in host_snapshot
.outcome()
.skills
.iter()
.filter(|host_skill| host_skill.name == entry.name)
{
injected_host_skill_prompts.insert_superseded_path(
host_skill.path_to_skills_md.inferred_native_path_string(),
);
}
}
}
if !injected_host_skill_prompts.is_empty() {
turn_store.insert(injected_host_skill_prompts);
}
fragments
})
}
}
impl<C> SkillsExtension<C> {
#[tracing::instrument(level = "trace", skip_all, fields(skill = %entry.name))]
async fn read_main_prompt(
&self,
entry: &SkillCatalogEntry,
host_snapshot: Option<Arc<HostSkillsSnapshot>>,
mcp_resources: Option<Arc<McpResourceClient>>,
thread_state: &SkillsThreadState,
input: &TurnInputContext<'_>,
) -> Result<SkillReadResult, String> {
let context = match entry.authority.kind {
SkillSourceKind::Cloud => SkillReadContext::Cloud { mcp_resources },
SkillSourceKind::Custom(_) => SkillReadContext::Custom { mcp_resources },
SkillSourceKind::Host => SkillReadContext::Host {
host_snapshot,
accessors: input
.environments
.iter()
.map(|environment| environment.fs)
.collect(),
},
SkillSourceKind::Executor => {
let fs = entry
.main_prompt
.environment_path()
.and_then(|(id, _)| {
input
.environments
.iter()
.find(|env| env.environment_id == id)
.map(|env| env.fs)
})
.ok_or_else(|| {
"skill environment is not available for this callback".to_string()
})?;
SkillReadContext::Executor { fs }
}
};
thread_state
.read_skill(
&self.providers,
SkillReadRequest {
authority: entry.authority.clone(),
package: entry.id.clone(),
resource: entry.main_prompt.clone(),
context,
},
)
.await
.map_err(|err| err.message)
}
fn emit_warning(&self, thread_id: &str, turn_id: Option<&str>, message: String) {
self.event_sink.emit_warning(ExtensionWarning {
thread_id: thread_id.to_string(),
turn_id: turn_id.map(str::to_string),
message,
});
}
}
pub fn install<C>(
registry: &mut ExtensionRegistryBuilder<C>,
config_from_host: impl Fn(&C) -> SkillsExtensionConfig + Send + Sync + 'static,
) where
C: Send + Sync + 'static,
{
install_with_providers(
registry,
SkillProviders::new().with_host_provider(Arc::new(HostSkillProvider::new())),
config_from_host,
);
}
pub fn install_with_providers<C>(
registry: &mut ExtensionRegistryBuilder<C>,
providers: SkillProviders,
config_from_host: impl Fn(&C) -> SkillsExtensionConfig + Send + Sync + 'static,
) where
C: Send + Sync + 'static,
{
install_with_providers_and_metrics(
registry,
providers,
/*metrics_client*/ None,
config_from_host,
);
}
pub fn install_with_providers_and_metrics<C>(
registry: &mut ExtensionRegistryBuilder<C>,
providers: SkillProviders,
metrics_client: Option<MetricsClient>,
config_from_host: impl Fn(&C) -> SkillsExtensionConfig + Send + Sync + 'static,
) where
C: Send + Sync + 'static,
{
let extension = Arc::new(SkillsExtension {
providers,
event_sink: registry.event_sink(),
config_from_host: Arc::new(config_from_host),
shadow_selection: Arc::new(ShadowSelectionExperiment::new(metrics_client)),
});
registry.thread_lifecycle_contributor(extension.clone());
registry.turn_lifecycle_contributor(Arc::new(SkillTelemetry));
registry.turn_lifecycle_contributor(extension.clone());
registry.config_contributor(extension.clone());
registry.prompt_contributor(extension.clone());
registry.turn_input_contributor(extension.clone());
registry.skill_invocation_contributor(extension.clone());
registry.tool_contributor(extension);
}

View File

@@ -0,0 +1,71 @@
use std::sync::Mutex;
use codex_extension_api::ExtensionMetrics;
use codex_otel::THREAD_SKILLS_DESCRIPTION_TRUNCATED_CHARS_METRIC;
use codex_otel::THREAD_SKILLS_ENABLED_TOTAL_METRIC;
use codex_otel::THREAD_SKILLS_KEPT_TOTAL_METRIC;
use codex_otel::THREAD_SKILLS_TRUNCATED_METRIC;
use pretty_assertions::assert_eq;
use super::*;
#[derive(Default)]
struct RecordingMetrics {
samples: Mutex<Vec<(String, i64)>>,
}
impl ExtensionMetrics for RecordingMetrics {
fn histogram_with_boundaries(
&self,
name: &str,
value: i64,
_boundaries: &[f64],
tags: &[(&str, &str)],
) {
self.histogram(name, value, tags);
}
fn counter(&self, name: &str, _inc: i64, _tags: &[(&str, &str)]) {
panic!("unexpected counter: {name}");
}
fn histogram(&self, name: &str, value: i64, _tags: &[(&str, &str)]) {
self.samples
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.push((name.to_string(), value));
}
}
#[test]
fn empty_catalog_records_zero_metrics_without_a_fragment() {
let metrics = RecordingMetrics::default();
let rendered = render_catalog(
Some(&metrics),
CatalogSurface::ThreadContext,
&SkillCatalog::default(),
/*include_skills_usage_instructions*/ false,
SkillCatalogRenderPolicy::EXTENSION_COMPATIBLE,
SkillMetadataBudget::Characters(8_000),
);
assert!(rendered.fragment.is_none());
assert_eq!(rendered.warning_message, None);
assert_eq!(
*metrics
.samples
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner),
vec![
(THREAD_SKILLS_ENABLED_TOTAL_METRIC.to_string(), 0),
(THREAD_SKILLS_KEPT_TOTAL_METRIC.to_string(), 0),
(THREAD_SKILLS_TRUNCATED_METRIC.to_string(), 0),
(
THREAD_SKILLS_DESCRIPTION_TRUNCATED_CHARS_METRIC.to_string(),
0,
),
]
);
}

View File

@@ -0,0 +1,128 @@
use codex_extension_api::ContextualUserFragment;
use codex_protocol::models::ContentItem;
use codex_protocol::models::ContentItemKind;
use codex_protocol::models::ContentItemMetadata;
use codex_protocol::models::input_text;
use codex_protocol::protocol::SKILLS_INSTRUCTIONS_CLOSE_TAG;
use codex_protocol::protocol::SKILLS_INSTRUCTIONS_OPEN_TAG;
use crate::catalog_prompt::SkillPrompt;
use crate::catalog_prompt::render_available_skills_body;
use crate::tools::SkillToolAuthority;
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct AvailableSkillsInstructions {
prompt: SkillPrompt,
skill_root_lines: Vec<String>,
skill_lines: Vec<String>,
}
impl AvailableSkillsInstructions {
pub(crate) fn from_skill_lines(
prompt: SkillPrompt,
skill_root_lines: Vec<String>,
mut skill_lines: Vec<String>,
include_skills_usage_instructions: bool,
) -> Self {
if include_skills_usage_instructions {
skill_lines.push("### How to use skills".to_string());
if let Some(instructions) = prompt.kind.alias_instructions() {
skill_lines.push(instructions.to_string());
}
skill_lines.push(prompt.usage_instructions());
}
Self {
prompt,
skill_root_lines,
skill_lines,
}
}
}
impl ContextualUserFragment for AvailableSkillsInstructions {
fn content_metadata(&self) -> ContentItemMetadata {
ContentItemMetadata::skills()
}
fn role(&self) -> &'static str {
"developer"
}
fn content_kind(&self) -> ContentItemKind {
ContentItemKind("skills.catalog".to_string())
}
fn markers(&self) -> (&'static str, &'static str) {
Self::type_markers()
}
fn type_markers() -> (&'static str, &'static str) {
(SKILLS_INSTRUCTIONS_OPEN_TAG, SKILLS_INSTRUCTIONS_CLOSE_TAG)
}
fn body(&self) -> ContentItem {
input_text(render_available_skills_body(
self.prompt,
&self.skill_root_lines,
&self.skill_lines,
))
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct SkillInstructions {
pub(crate) name: String,
pub(crate) path: String,
pub(crate) contents: String,
pub(crate) resource_access: Option<SkillResourceAccess>,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct SkillResourceAccess {
pub(crate) authority: SkillToolAuthority,
pub(crate) package: String,
pub(crate) main_resource: String,
}
impl ContextualUserFragment for SkillInstructions {
fn content_metadata(&self) -> ContentItemMetadata {
ContentItemMetadata::skills()
}
fn role(&self) -> &'static str {
"user"
}
fn content_kind(&self) -> ContentItemKind {
ContentItemKind("skills.selected_skill_instructions".to_string())
}
fn markers(&self) -> (&'static str, &'static str) {
Self::type_markers()
}
fn type_markers() -> (&'static str, &'static str) {
("<skill>", "</skill>")
}
fn body(&self) -> ContentItem {
let name = &self.name;
let path = &self.path;
let contents = &self.contents;
let resource_access = self
.resource_access
.as_ref()
.map(|access| {
let metadata = serde_json::json!({
"authority": access.authority,
"package": access.package,
"main_resource": access.main_resource,
});
format!("\n<resource_access>{metadata}</resource_access>")
})
.unwrap_or_default();
input_text(format!(
"\n<name>{name}</name>\n<path>{path}</path>{resource_access}\n{contents}\n"
))
}
}

View File

@@ -0,0 +1,68 @@
use std::collections::HashMap;
use std::path::Component;
use std::path::Path;
use std::path::PathBuf;
use crate::catalog::SkillCatalogEntry;
pub(crate) fn shared_host_alias_roots(entries: &[&SkillCatalogEntry]) -> Vec<String> {
let mut plugin_version_skill_counts = HashMap::new();
for root in entries.iter().filter_map(|entry| entry.alias_root()) {
let Some(plugin_version) = plugin_version_base(Path::new(root)) else {
continue;
};
let count = plugin_version_skill_counts
.entry(plugin_version)
.or_insert(0usize);
*count = count.saturating_add(1);
}
entries
.iter()
.filter_map(|entry| entry.alias_root())
.map(|root| {
let root = Path::new(root);
let shared_root = match plugin_version_base(root) {
Some(plugin_version)
if plugin_version_skill_counts
.get(&plugin_version)
.copied()
.unwrap_or_default()
<= 1 =>
{
plugin_marketplace_base(root).unwrap_or_else(|| root.to_path_buf())
}
Some(_) | None => root.to_path_buf(),
};
shared_root.to_string_lossy().replace('\\', "/")
})
.collect()
}
fn plugin_marketplace_base(path: &Path) -> Option<PathBuf> {
let mut candidate = path;
while let Some(parent) = candidate.parent() {
if parent.file_name()?.to_str()? == "cache"
&& parent.parent()?.file_name()?.to_str()? == "plugins"
{
return Some(candidate.to_path_buf());
}
candidate = parent;
}
None
}
fn plugin_version_base(path: &Path) -> Option<PathBuf> {
let marketplace_base = plugin_marketplace_base(path)?;
let mut relative_components = path.strip_prefix(&marketplace_base).ok()?.components();
let plugin = match relative_components.next()? {
Component::Normal(plugin) => plugin,
_ => return None,
};
let version = match relative_components.next()? {
Component::Normal(version) => version,
_ => return None,
};
Some(marketplace_base.join(plugin).join(version))
}

View File

@@ -0,0 +1,233 @@
use std::collections::HashMap;
use std::collections::HashSet;
use std::fmt;
use std::io;
use std::sync::Arc;
use codex_exec_server::EnvironmentAccess;
use codex_exec_server::EnvironmentAccessExt;
use codex_exec_server::EnvironmentAccessKey;
use codex_exec_server::FileSystemEnvironmentAccessor;
use codex_exec_server::LOCAL_FS;
use codex_exec_server::ReadFileOptions;
use codex_protocol::protocol::SkillScope;
use codex_skills::SkillError;
use codex_skills::SkillMetadata;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::PathUri;
use futures::StreamExt;
use crate::loader::MAX_CONCURRENT_SKILL_LOADS;
use crate::loader::canonicalize_for_skill_identity;
#[derive(Debug, Clone, Default)]
pub struct SkillLoadOutcome {
pub skills: Vec<SkillMetadata>,
pub errors: Vec<SkillError>,
pub disabled_paths: HashSet<PathUri>,
pub(crate) skill_roots: Vec<AbsolutePathBuf>,
pub(crate) skill_root_by_path: Arc<HashMap<PathUri, AbsolutePathBuf>>,
pub(crate) skill_discovery_path_by_path: Arc<HashMap<PathUri, PathUri>>,
pub(crate) agent_plugin_skill_paths: HashSet<PathUri>,
pub(crate) file_systems_by_skill_path: SkillFileSystemsByPath,
pub(crate) implicit_skills_by_scripts_dir: Arc<HashMap<PathUri, SkillMetadata>>,
pub(crate) implicit_skills_by_doc_path: Arc<HashMap<PathUri, SkillMetadata>>,
}
impl SkillLoadOutcome {
/// Builds an already-composed outcome while retaining the filesystem that supplied each skill.
pub(crate) fn from_parts(
skills: Vec<SkillMetadata>,
errors: Vec<SkillError>,
skill_roots: Vec<AbsolutePathBuf>,
skill_root_by_path: HashMap<PathUri, AbsolutePathBuf>,
skill_discovery_path_by_path: HashMap<PathUri, PathUri>,
agent_plugin_skill_paths: HashSet<PathUri>,
file_systems_by_skill_path: HashMap<PathUri, EnvironmentAccessKey>,
) -> Self {
Self {
skills,
errors,
skill_roots,
skill_root_by_path: Arc::new(skill_root_by_path),
skill_discovery_path_by_path: Arc::new(skill_discovery_path_by_path),
agent_plugin_skill_paths,
file_systems_by_skill_path: SkillFileSystemsByPath::new(file_systems_by_skill_path),
..Self::default()
}
}
pub fn is_skill_enabled(&self, skill: &SkillMetadata) -> bool {
!self.disabled_paths.contains(&skill.path_to_skills_md)
}
pub(crate) fn skills_with_enabled(&self) -> impl Iterator<Item = (&SkillMetadata, bool)> {
self.skills
.iter()
.map(|skill| (skill, self.is_skill_enabled(skill)))
}
pub(crate) async fn with_disabled_paths(
mut self,
disabled_paths: HashSet<PathUri>,
accessors: &[&dyn EnvironmentAccess],
) -> Self {
self.disabled_paths = disabled_paths;
let mut by_scripts_dir = HashMap::new();
let mut by_doc_path = HashMap::new();
let mut scans = Vec::new();
for skill in self
.skills
.iter()
.filter(|skill| self.is_skill_enabled(skill))
{
let Some(source) = self.file_system_for_skill(skill) else {
continue;
};
let Some(access) = accessors
.iter()
.copied()
.find(|access| source == &access.cache_key())
else {
continue;
};
// Only native paths participate in implicit command detection.
let Ok(path) = skill.path_to_skills_md.to_abs_path() else {
continue;
};
scans.push(async move {
let skill_doc_path = canonicalize_for_skill_identity(access, &path).await;
let scripts_dir = match path.parent() {
Some(skill_dir) => Some(
canonicalize_for_skill_identity(access, &skill_dir.join("scripts")).await,
),
None => None,
};
(skill, skill_doc_path, scripts_dir)
});
}
let mut scans = futures::stream::iter(scans).buffered(MAX_CONCURRENT_SKILL_LOADS);
while let Some((skill, doc_path, scripts_dir)) = scans.next().await {
by_doc_path.insert(PathUri::from_abs_path(&doc_path), skill.clone());
if let Some(scripts_dir) = scripts_dir {
by_scripts_dir.insert(PathUri::from_abs_path(&scripts_dir), skill.clone());
}
}
drop(scans);
self.implicit_skills_by_scripts_dir = Arc::new(by_scripts_dir);
self.implicit_skills_by_doc_path = Arc::new(by_doc_path);
self
}
pub(crate) fn is_agent_plugin_skill(&self, skill: &SkillMetadata) -> bool {
self.agent_plugin_skill_paths
.contains(&skill.path_to_skills_md)
}
/// Returns the discovery root that supplied a loaded skill path.
pub(crate) fn skill_root_for_path(&self, path: &PathUri) -> Option<&AbsolutePathBuf> {
self.skill_root_by_path.get(path)
}
/// Returns the logical path used to discover a canonical skill path.
pub(crate) fn skill_discovery_path_for_path(&self, path: &PathUri) -> Option<&PathUri> {
self.skill_discovery_path_by_path.get(path)
}
/// Returns loaded skill roots in discovery order.
pub(crate) fn skill_roots_in_discovery_order(&self) -> impl Iterator<Item = &AbsolutePathBuf> {
self.skill_roots.iter()
}
pub(crate) fn file_system_for_skill(
&self,
skill: &SkillMetadata,
) -> Option<&EnvironmentAccessKey> {
self.file_systems_by_skill_path
.get(&skill.path_to_skills_md)
}
/// Reads through current access to the original filesystem; cached metadata grants no access.
pub(crate) async fn read_skill_text(
&self,
skill: &SkillMetadata,
accessors: &[&dyn EnvironmentAccess],
) -> io::Result<String> {
let host = FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS);
let access: &dyn EnvironmentAccess = match skill.scope {
SkillScope::Repo => self
.file_system_for_skill(skill)
.and_then(|source| {
accessors
.iter()
.copied()
.find(|access| source.same_file_system(&access.cache_key()))
})
.ok_or_else(|| {
io::Error::new(
io::ErrorKind::PermissionDenied,
"skill discovery filesystem is unavailable for this callback",
)
})?,
SkillScope::User | SkillScope::System | SkillScope::Admin => &host,
};
access
.read_file_text(&skill.path_to_skills_md, ReadFileOptions::default())
.await
}
}
impl codex_skills::ImplicitSkillLookup for SkillLoadOutcome {
fn implicit_skill_for_scripts_dir(&self, path: &AbsolutePathBuf) -> Option<&SkillMetadata> {
self.implicit_skills_by_scripts_dir
.get(&PathUri::from_abs_path(path))
}
fn implicit_skill_for_doc_path(&self, path: &AbsolutePathBuf) -> Option<&SkillMetadata> {
self.implicit_skills_by_doc_path
.get(&PathUri::from_abs_path(path))
}
}
impl codex_skills::ExplicitSkillLookup for SkillLoadOutcome {
fn skills(&self) -> &[SkillMetadata] {
&self.skills
}
fn disabled_paths(&self) -> &HashSet<PathUri> {
&self.disabled_paths
}
fn skill_discovery_path_for_path(&self, path: &PathUri) -> Option<&PathUri> {
SkillLoadOutcome::skill_discovery_path_for_path(self, path)
}
fn is_skill_enabled(&self, skill: &SkillMetadata) -> bool {
SkillLoadOutcome::is_skill_enabled(self, skill)
}
}
#[derive(Clone, Default)]
pub(crate) struct SkillFileSystemsByPath {
values: Arc<HashMap<PathUri, EnvironmentAccessKey>>,
}
impl SkillFileSystemsByPath {
pub(crate) fn new(values: HashMap<PathUri, EnvironmentAccessKey>) -> Self {
Self {
values: Arc::new(values),
}
}
fn get(&self, path: &PathUri) -> Option<&EnvironmentAccessKey> {
self.values.get(path)
}
}
impl fmt::Debug for SkillFileSystemsByPath {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SkillFileSystemsByPath")
.field("len", &self.values.len())
.finish()
}
}

View File

@@ -0,0 +1,115 @@
use std::collections::HashSet;
use codex_exec_server::EnvironmentAccess;
use codex_extension_api::ContextualUserFragment;
use codex_skills::SkillMetadata;
use codex_skills::normalize_skill_path;
use crate::HostSkillsSnapshot;
use crate::fragments::SkillInstructions;
use crate::render::truncate_main_prompt_contents;
/// Host skill prompts already supplied or superseded by an extension.
///
/// Core preserves its host skill invocation lifecycle while avoiding duplicate
/// prompts and retaining executor/cloud skill precedence.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct InjectedHostSkillPrompts {
paths: HashSet<String>,
superseded_paths: HashSet<String>,
}
impl InjectedHostSkillPrompts {
pub fn insert_path(&mut self, path: impl Into<String>) {
let path = path.into();
self.paths.insert(normalize_host_skill_path(&path));
self.paths.insert(path);
}
pub fn insert_superseded_path(&mut self, path: impl Into<String>) {
let path = path.into();
self.superseded_paths
.insert(normalize_host_skill_path(&path));
self.insert_path(path);
}
pub fn is_empty(&self) -> bool {
self.paths.is_empty()
}
pub fn contains_path(&self, path: &str) -> bool {
self.paths.contains(path) || self.paths.contains(&normalize_host_skill_path(path))
}
pub fn is_superseded_path(&self, path: &str) -> bool {
self.superseded_paths
.contains(&normalize_host_skill_path(path))
}
}
/// Prompt fragments and read outcomes for a set of selected host skills.
pub struct HostSkillPrompts {
pub fragments: Vec<Box<dyn ContextualUserFragment + Send>>,
pub injected: Vec<SkillMetadata>,
pub warnings: Vec<String>,
}
fn normalize_host_skill_path(path: &str) -> String {
normalize_skill_path(path).replace('\\', "/")
}
impl HostSkillsSnapshot {
/// Reads selected host skills and builds their model-visible prompt fragments.
///
/// Core calls this directly, including for hosts without an installed skills extension.
#[tracing::instrument(
level = "trace",
skip_all,
fields(selected_skill_count = selected_skills.len())
)]
pub async fn load_skill_prompts(
&self,
selected_skills: &[SkillMetadata],
accessors: &[&dyn EnvironmentAccess],
) -> HostSkillPrompts {
let mut prompts = HostSkillPrompts {
fragments: Vec::with_capacity(selected_skills.len()),
injected: Vec::with_capacity(selected_skills.len()),
warnings: Vec::new(),
};
for skill in selected_skills {
match self.read_skill_text(skill, accessors).await {
Ok(contents) => {
let (contents, truncated) = if self.outcome().is_agent_plugin_skill(skill) {
truncate_main_prompt_contents(&contents)
} else {
(contents, false)
};
if truncated {
prompts.warnings.push(format!(
"Skill `{}` exceeded the main prompt context limit and was truncated.",
skill.name
));
}
prompts.fragments.push(Box::new(SkillInstructions {
name: skill.name.clone(),
path: skill.path_to_skills_md.inferred_native_path_string(),
contents,
resource_access: None,
}));
prompts.injected.push(skill.clone());
}
Err(err) => {
prompts.warnings.push(format!(
"Failed to load skill {} at {}: {err:#}",
skill.name,
skill.path_to_skills_md.inferred_native_path_string()
));
}
}
}
prompts
}
}

View File

@@ -0,0 +1,450 @@
use std::collections::HashSet;
use std::io;
use std::sync::Mutex;
use tokio::sync::oneshot;
use codex_config::ConfigLayerSource;
use codex_config::ConfigLayerStack;
use codex_config::default_project_root_markers;
use codex_config::merge_toml_values;
use codex_config::project_root_markers_from_config;
use codex_exec_server::EnvironmentAccess;
use codex_exec_server::EnvironmentAccessKey;
use codex_exec_server::FileSystemEnvironmentAccessor;
use codex_exec_server::GetMetadataOptions;
use codex_exec_server::LOCAL_FS;
use codex_protocol::protocol::SkillScope;
use codex_skills::system_cache_root_dir;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::PathUri;
use codex_utils_plugins::PluginSkillRoot;
use dirs::home_dir;
use futures::StreamExt;
use toml::Value as TomlValue;
use crate::loader::HostSkillRoot;
const AGENTS_DIR_NAME: &str = ".agents";
const SKILLS_DIR_NAME: &str = "skills";
const MAX_CONCURRENT_ANCESTOR_PROBES: usize = 8;
#[derive(Default)]
pub(crate) struct EmptyRemoteRootsCache {
generation: u64,
entry: Option<EmptyRemoteRoots>,
}
struct EmptyRemoteRoots {
fs: EnvironmentAccessKey,
cwd: AbsolutePathBuf,
markers: Vec<String>,
watch: EmptyRootsWatch,
}
enum EmptyRootsWatch {
Registering(oneshot::Receiver<oneshot::Receiver<()>>),
Watching(oneshot::Receiver<()>),
}
impl EmptyRemoteRootsCache {
pub(crate) fn clear(&mut self) {
self.generation = self.generation.wrapping_add(1);
self.entry = None;
}
}
#[expect(
clippy::too_many_arguments,
reason = "explicit discovery inputs and cache"
)]
pub(crate) async fn resolve_skill_roots<'a>(
repository_file_system: Option<&'a dyn EnvironmentAccess>,
host: &'a dyn EnvironmentAccess,
config_layer_stack: &ConfigLayerStack,
cwd: &AbsolutePathBuf,
project_markers: Option<&dyn EnvironmentAccess>,
plugin_skill_roots: Vec<PluginSkillRoot>,
extra_skill_roots: Vec<AbsolutePathBuf>,
empty_remote_roots: Option<&Mutex<EmptyRemoteRootsCache>>,
) -> Vec<HostSkillRoot<'a>> {
let home_dir =
home_dir().and_then(|path| AbsolutePathBuf::from_absolute_path_checked(path).ok());
resolve_skill_roots_with_home_dir(
repository_file_system,
host,
config_layer_stack,
cwd,
project_markers,
home_dir.as_ref(),
plugin_skill_roots,
extra_skill_roots,
empty_remote_roots,
)
.await
}
#[expect(
clippy::too_many_arguments,
reason = "explicit filesystem authorities and a home override keep root-order tests deterministic"
)]
async fn resolve_skill_roots_with_home_dir<'a>(
repository_file_system: Option<&'a dyn EnvironmentAccess>,
host: &'a dyn EnvironmentAccess,
config_layer_stack: &ConfigLayerStack,
cwd: &AbsolutePathBuf,
project_markers: Option<&dyn EnvironmentAccess>,
home_dir: Option<&AbsolutePathBuf>,
plugin_skill_roots: Vec<PluginSkillRoot>,
extra_skill_roots: Vec<AbsolutePathBuf>,
empty_remote_roots: Option<&Mutex<EmptyRemoteRootsCache>>,
) -> Vec<HostSkillRoot<'a>> {
let mut roots =
roots_from_layer_stack(config_layer_stack, home_dir, repository_file_system, host);
roots.extend(
plugin_skill_roots
.into_iter()
.map(|root| HostSkillRoot::plugin(root, host)),
);
roots.extend(
extra_skill_roots
.into_iter()
.map(|path| HostSkillRoot::host(path, SkillScope::User, host)),
);
roots.extend(
repo_agents_skill_roots(
repository_file_system,
config_layer_stack,
cwd,
project_markers,
empty_remote_roots,
)
.await,
);
dedupe_skill_roots_by_path(&mut roots);
roots
}
fn roots_from_layer_stack<'a>(
config_layer_stack: &ConfigLayerStack,
home_dir: Option<&AbsolutePathBuf>,
repository_file_system: Option<&'a dyn EnvironmentAccess>,
host: &'a dyn EnvironmentAccess,
) -> Vec<HostSkillRoot<'a>> {
let mut roots = Vec::new();
for layer in config_layer_stack.all_layers_high_to_low() {
let Some(config_folder) = layer.config_folder() else {
continue;
};
match &layer.name {
ConfigLayerSource::Project { .. } => {
if let Some(repository_file_system) = repository_file_system {
roots.push(HostSkillRoot::host(
config_folder.join(SKILLS_DIR_NAME),
SkillScope::Repo,
repository_file_system,
));
}
}
ConfigLayerSource::User { .. } => {
// Deprecated user skills location (`$CODEX_HOME/skills`), kept for backward
// compatibility.
roots.push(HostSkillRoot::host(
config_folder.join(SKILLS_DIR_NAME),
SkillScope::User,
host,
));
if let Some(home_dir) = home_dir {
roots.push(HostSkillRoot::host(
home_dir.join(AGENTS_DIR_NAME).join(SKILLS_DIR_NAME),
SkillScope::User,
host,
));
}
roots.push(HostSkillRoot::host(
system_cache_root_dir(&config_folder),
SkillScope::System,
host,
));
}
ConfigLayerSource::System { .. } => {
roots.push(HostSkillRoot::host(
config_folder.join(SKILLS_DIR_NAME),
SkillScope::Admin,
host,
));
}
ConfigLayerSource::PackagedDefaults { .. }
| ConfigLayerSource::Mdm { .. }
| ConfigLayerSource::EnterpriseManaged { .. }
| ConfigLayerSource::SessionFlags
| ConfigLayerSource::LegacyManagedConfigTomlFromFile { .. }
| ConfigLayerSource::LegacyManagedConfigTomlFromMdm => {}
}
}
roots
}
async fn repo_agents_skill_roots<'a>(
repository_fs_accessor: Option<&'a dyn EnvironmentAccess>,
config_layer_stack: &ConfigLayerStack,
cwd: &AbsolutePathBuf,
project_markers: Option<&dyn EnvironmentAccess>,
empty_remote_roots: Option<&Mutex<EmptyRemoteRootsCache>>,
) -> Vec<HostSkillRoot<'a>> {
let Some(repository_fs_accessor) = repository_fs_accessor else {
return Vec::new();
};
let project_root_markers = project_root_markers_from_stack(config_layer_stack);
let file_system = repository_fs_accessor.cache_key();
let host = FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS);
let cache = empty_remote_roots.filter(|_| !file_system.same_file_system(&host.cache_key()));
let generation = if let Some(cache) = cache {
let mut cache = cache
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let mut register = true;
if let Some(entry) = cache.entry.as_mut().filter(|entry| {
entry.fs == file_system && entry.cwd == *cwd && entry.markers == project_root_markers
}) {
if let EmptyRootsWatch::Registering(registered) = &mut entry.watch {
match registered.try_recv() {
Ok(invalidated) => entry.watch = EmptyRootsWatch::Watching(invalidated),
Err(oneshot::error::TryRecvError::Empty) => register = false,
Err(oneshot::error::TryRecvError::Closed) => {}
}
}
if let EmptyRootsWatch::Watching(invalidated) = &mut entry.watch
&& invalidated.try_recv() == Err(oneshot::error::TryRecvError::Empty)
{
tracing::debug!("reused watched empty remote repository skills discovery");
return Vec::new();
}
}
register.then_some(cache.generation)
} else {
None
};
let ResolvedProjectRoot {
path: project_root,
marker,
mut complete,
} = find_project_root(
project_markers.unwrap_or(repository_fs_accessor),
config_layer_stack,
cwd,
)
.await;
let directories = dirs_between_project_root_and_cwd(cwd, &project_root);
let mut roots = Vec::new();
let mut missing = Vec::new();
let mut results = futures::stream::iter(directories)
.map(|directory| async move {
let agents_skills = directory.join(AGENTS_DIR_NAME).join(SKILLS_DIR_NAME);
let agents_skills_uri = PathUri::from_abs_path(&agents_skills);
let result = repository_fs_accessor
.get_metadata(&agents_skills_uri, GetMetadataOptions::default())
.await;
(agents_skills, result)
})
.buffered(MAX_CONCURRENT_ANCESTOR_PROBES);
while let Some((agents_skills, result)) = results.next().await {
match result {
Ok(metadata) if metadata.is_directory => roots.push(HostSkillRoot::host(
agents_skills,
SkillScope::Repo,
repository_fs_accessor,
)),
Ok(_) => complete = false,
Err(error) if error.kind() == io::ErrorKind::NotFound => {
if generation.is_some() {
missing.push(PathUri::from_abs_path(&agents_skills));
}
}
Err(error) if error.kind() == io::ErrorKind::Unsupported => {
complete = false;
// Let loading report an unsupported sandbox backend instead of hiding this root.
roots.push(HostSkillRoot::host(
agents_skills,
SkillScope::Repo,
repository_fs_accessor,
));
}
Err(error) => {
complete = false;
tracing::warn!(
"failed to stat repo skills root {}: {error:#}",
agents_skills.display()
);
}
}
}
if complete
&& roots.is_empty()
&& let (Some(cache), Some(generation)) = (cache, generation)
{
// A nearer marker can only narrow an empty scan. Losing the selected marker
// can widen it. With no marker, a new marker above cwd can widen it too.
if marker.is_none() {
for ancestor in cwd.ancestors() {
missing.extend(
project_root_markers
.iter()
.map(|name| PathUri::from_abs_path(&ancestor.join(name))),
);
}
}
let mut cache = cache
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if cache.generation == generation {
let (mut ready, registered) = oneshot::channel();
cache.entry = Some(EmptyRemoteRoots {
fs: file_system,
cwd: cwd.clone(),
markers: project_root_markers,
watch: EmptyRootsWatch::Registering(registered),
});
// A cold question never waits for an extra round trip. Until the executor
// acknowledges coverage, other questions take the ordinary live scan.
let present = marker.as_ref().map(PathUri::from_abs_path);
let watch = repository_fs_accessor.watch_missing(missing, present);
tokio::spawn(async move {
tokio::select! {
biased;
_ = ready.closed() => {}
watch = watch => match watch {
Ok(Some(invalidated)) => {
tracing::debug!("watch established for empty remote repository skills");
let _ = ready.send(invalidated);
}
Ok(None) => {}
Err(error) => tracing::debug!(%error, "remote skills watch failed; retaining live discovery"),
}
}
});
}
}
roots
}
fn project_root_markers_from_stack(config_layer_stack: &ConfigLayerStack) -> Vec<String> {
let mut merged = TomlValue::Table(toml::map::Map::new());
for layer in config_layer_stack.layers_low_to_high() {
if matches!(layer.name, ConfigLayerSource::Project { .. }) {
continue;
}
merge_toml_values(&mut merged, &layer.config);
}
match project_root_markers_from_config(&merged) {
Ok(Some(markers)) => markers,
Ok(None) => default_project_root_markers(),
Err(error) => {
tracing::warn!("invalid project_root_markers: {error}");
default_project_root_markers()
}
}
}
/// Repository boundary and the observations required to watch an empty discovery result.
struct ResolvedProjectRoot {
path: AbsolutePathBuf,
marker: Option<AbsolutePathBuf>,
complete: bool,
}
async fn find_project_root(
repository_file_system: &dyn EnvironmentAccess,
config_layer_stack: &ConfigLayerStack,
cwd: &AbsolutePathBuf,
) -> ResolvedProjectRoot {
let project_root_markers = project_root_markers_from_stack(config_layer_stack);
if project_root_markers.is_empty() {
return ResolvedProjectRoot {
path: cwd.clone(),
marker: None,
complete: true,
};
}
let mut probes = Vec::new();
for ancestor in cwd.ancestors() {
for marker in &project_root_markers {
probes.push((ancestor.clone(), ancestor.join(marker)));
}
}
let mut results = futures::stream::iter(probes)
.map(|(ancestor, marker_path)| async move {
let marker_path_uri = PathUri::from_abs_path(&marker_path);
let result = repository_file_system
.get_metadata(&marker_path_uri, GetMetadataOptions::default())
.await;
(ancestor, marker_path, result)
})
.buffered(MAX_CONCURRENT_ANCESTOR_PROBES);
while let Some((ancestor, marker_path, result)) = results.next().await {
match result {
Ok(_) => {
return ResolvedProjectRoot {
path: ancestor,
marker: Some(marker_path),
complete: true,
};
}
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
Err(error) => {
tracing::warn!(
"failed to stat project root marker {}: {error:#}",
marker_path.display()
);
// An inconclusive nearer marker must not expose a parent repository's skills.
return ResolvedProjectRoot {
path: ancestor,
marker: None,
complete: false,
};
}
}
}
ResolvedProjectRoot {
path: cwd.clone(),
marker: None,
complete: true,
}
}
fn dirs_between_project_root_and_cwd(
cwd: &AbsolutePathBuf,
project_root: &AbsolutePathBuf,
) -> Vec<AbsolutePathBuf> {
let mut directories = cwd
.ancestors()
.scan(false, |done, directory| {
if *done {
None
} else {
if &directory == project_root {
*done = true;
}
Some(directory)
}
})
.collect::<Vec<_>>();
directories.reverse();
directories
}
fn dedupe_skill_roots_by_path(roots: &mut Vec<HostSkillRoot>) {
let mut seen = HashSet::new();
roots.retain(|root| seen.insert(root.path.clone()));
}
#[cfg(test)]
#[path = "host_roots_tests.rs"]
mod tests;

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,588 @@
use std::collections::HashMap;
use std::collections::VecDeque;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::RwLock;
use codex_config::ConfigLayerStack;
use codex_config::SkillConfigRules;
use codex_config::bundled_skills_enabled_from_stack;
use codex_config::skill_config_rules_from_stack;
use codex_exec_server::EnvironmentAccess;
use codex_exec_server::EnvironmentAccessKey;
use codex_exec_server::ExecutorFileSystem;
use codex_exec_server::FileSystemEnvironmentAccessor;
use codex_exec_server::LOCAL_ENVIRONMENT_ID;
use codex_exec_server::LOCAL_FS;
use codex_protocol::protocol::Product;
use codex_protocol::protocol::SkillScope;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_plugins::PluginIdentity;
use codex_utils_plugins::PluginSkillRoot;
use tokio::sync::OnceCell;
use tokio::sync::Semaphore;
use tracing::info;
use tracing::instrument;
use codex_skills::LoadedSkills;
use codex_skills::SkillLoadFuture;
use codex_skills::SkillRootLoadRequest;
use codex_skills::SkillRootLoader;
use codex_skills::SkillRootSnapshots;
use codex_skills::install_system_skills;
use crate::HostSkillsSnapshot;
use crate::SkillLoadOutcome;
use crate::host_roots::EmptyRemoteRootsCache;
use crate::host_roots::resolve_skill_roots;
use crate::loader::HostSkillRoot;
use crate::loader::HostSkillRootSnapshot;
use crate::loader::MAX_CONCURRENT_ROOT_SCANS;
use crate::loader::load_and_merge_host_skill_roots;
use crate::loader::load_and_merge_host_skill_roots_with_request_snapshots;
const CONFIG_SKILLS_CACHE_CAPACITY: usize = 32;
struct ConfigSkillsCacheEntry {
key: ConfigSkillsCacheKey,
snapshot: Arc<OnceCell<HostSkillsSnapshot>>,
}
#[derive(Debug, Clone)]
pub struct HostSkillsLoadInput {
cwd: AbsolutePathBuf,
implicit_repository_skills: bool,
effective_skill_roots: Vec<PluginSkillRoot>,
config_layer_stack: ConfigLayerStack,
plugin_skill_snapshots: Option<SkillRootSnapshots<PluginSkillRoot>>,
}
impl HostSkillsLoadInput {
pub fn new(
cwd: AbsolutePathBuf,
effective_skill_roots: Vec<PluginSkillRoot>,
config_layer_stack: ConfigLayerStack,
) -> Self {
Self {
cwd,
implicit_repository_skills: true,
effective_skill_roots,
config_layer_stack,
plugin_skill_snapshots: None,
}
}
/// Retains the turn's configuration and plugin selection for a new repository location.
pub fn for_cwd(&self, cwd: AbsolutePathBuf) -> Self {
Self {
cwd,
..self.clone()
}
}
/// Host implicit command attribution only runs for the local environment.
pub fn with_environment_id(mut self, environment_id: &str) -> Self {
self.implicit_repository_skills = environment_id == LOCAL_ENVIRONMENT_ID;
self
}
/// Attaches plugin skill snapshots parsed during plugin loading, when available.
pub fn with_plugin_skill_snapshots(
mut self,
plugin_skill_snapshots: Option<SkillRootSnapshots<PluginSkillRoot>>,
) -> Self {
self.plugin_skill_snapshots = plugin_skill_snapshots;
self
}
}
/// Owns host skill discovery, immutable snapshots, cache invalidation, and extra roots.
///
/// Source-specific model exposure remains the responsibility of the skills extension.
pub struct HostSkillsService {
codex_home: AbsolutePathBuf,
restriction_product: Option<Product>,
extra_roots: RwLock<Vec<AbsolutePathBuf>>,
cache_by_cwd: RwLock<HashMap<AbsolutePathBuf, HostSkillsSnapshot>>,
cache_by_config: RwLock<VecDeque<ConfigSkillsCacheEntry>>,
empty_remote_roots: Mutex<EmptyRemoteRootsCache>,
// Shared across cwds so root scheduling cannot multiply per-root I/O fanout.
root_scan_slots: Arc<Semaphore>,
}
pub(crate) type RequestSkillRootSnapshots =
RwLock<HashMap<ConfigSkillRootCacheKey, Arc<OnceCell<HostSkillRootSnapshot>>>>;
/// Shares host-root scans between workspaces for the lifetime of one request.
pub struct HostSkillsRequest<'a> {
service: &'a HostSkillsService,
root_snapshots: RequestSkillRootSnapshots,
}
impl HostSkillsRequest<'_> {
pub async fn snapshot_for_cwd(
&self,
input: &HostSkillsLoadInput,
force_reload: bool,
fs: Option<Arc<dyn ExecutorFileSystem>>,
) -> HostSkillsSnapshot {
let repository = fs.as_ref().map(FileSystemEnvironmentAccessor::unrestricted);
self.service
.snapshot_for_cwd_with_root_snapshots(
input,
force_reload,
repository
.as_ref()
.map(|access| access as &dyn EnvironmentAccess),
Some(&self.root_snapshots),
)
.await
}
}
impl HostSkillsService {
pub fn new(codex_home: AbsolutePathBuf, bundled_skills_enabled: bool) -> Self {
Self::new_with_restriction_product(codex_home, bundled_skills_enabled, Some(Product::Codex))
}
pub fn new_with_restriction_product(
codex_home: AbsolutePathBuf,
bundled_skills_enabled: bool,
restriction_product: Option<Product>,
) -> Self {
let service = Self {
codex_home,
restriction_product,
extra_roots: RwLock::new(Vec::new()),
cache_by_cwd: RwLock::new(HashMap::new()),
cache_by_config: RwLock::new(VecDeque::new()),
empty_remote_roots: Mutex::default(),
root_scan_slots: Arc::new(Semaphore::new(MAX_CONCURRENT_ROOT_SCANS)),
};
// The cache is shared by every process using this CODEX_HOME. Disabled services filter
// system roots when loading rather than mutating shared state.
if bundled_skills_enabled {
service.ensure_system_skills_installed();
}
service
}
/// Creates a request-local view without changing persistent plugin snapshots.
pub fn for_request(&self) -> HostSkillsRequest<'_> {
HostSkillsRequest {
service: self,
root_snapshots: RwLock::new(HashMap::new()),
}
}
pub fn set_extra_roots(&self, extra_roots: Vec<AbsolutePathBuf>) {
{
let mut roots = self
.extra_roots
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner);
*roots = extra_roots;
}
self.clear_cache();
}
/// Load skills for an already-constructed [`Config`], avoiding any additional config-layer
/// loading.
///
/// This path uses a cache keyed by the effective skill-relevant config state rather than just
/// cwd so role-local and session-local skill overrides cannot bleed across sessions that happen
/// to share a directory.
pub async fn snapshot_for_config(
&self,
input: &HostSkillsLoadInput,
repository: Option<&dyn EnvironmentAccess>,
) -> HostSkillsSnapshot {
self.snapshot_for_config_with_project_markers(input, repository, repository)
.await
}
/// Load repository skills with current access and marker metadata from the same executor.
/// Unrestricted marker checks preserve hidden repository boundaries and run only on watch misses.
pub async fn snapshot_for_config_on_executor(
&self,
input: &HostSkillsLoadInput,
repository: Option<(&Arc<dyn ExecutorFileSystem>, &dyn EnvironmentAccess)>,
) -> HostSkillsSnapshot {
let project_markers = repository
.map(|(file_system, _)| FileSystemEnvironmentAccessor::unrestricted(file_system));
self.snapshot_for_config_with_project_markers(
input,
repository.map(|(_, access)| access),
project_markers
.as_ref()
.map(|access| access as &dyn EnvironmentAccess),
)
.await
}
#[instrument(
name = "skills_for_config",
level = "info",
skip_all,
fields(otel.name = "skills_for_config")
)]
async fn snapshot_for_config_with_project_markers(
&self,
input: &HostSkillsLoadInput,
repository: Option<&dyn EnvironmentAccess>,
project_markers: Option<&dyn EnvironmentAccess>,
) -> HostSkillsSnapshot {
// User and plugin roots retain host authority independently of the selected executor.
let host = FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS);
let roots = self
.skill_roots_for_config(
input,
repository,
project_markers,
&host,
Some(&self.empty_remote_roots),
)
.await;
let skill_config_rules = skill_config_rules_from_stack(&input.config_layer_stack);
let cache_key = config_skills_cache_key(&roots, &skill_config_rules, input);
self.snapshot_for_skill_roots(
input,
roots,
&skill_config_rules,
cache_key,
/*force_reload*/ false,
/*request_root_snapshots*/ None,
)
.await
}
/// Returns filesystem roots whose changes should invalidate discovered host skills.
///
/// Plugin roots have their own lifecycle invalidation, and bundled roots are installed before
/// filesystem watching begins.
pub async fn watchable_skill_root_paths(
&self,
input: &HostSkillsLoadInput,
fs: Arc<dyn ExecutorFileSystem>,
) -> Vec<AbsolutePathBuf> {
let repository = FileSystemEnvironmentAccessor::unrestricted(&fs);
let host = FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS);
self.skill_roots_for_config(
input,
Some(&repository),
Some(&repository),
&host,
/*empty_remote_roots*/ None,
)
.await
.into_iter()
.filter(|root| root.plugin_identity().is_none() && root.scope != SkillScope::System)
.map(|root| root.path)
.collect()
}
async fn skill_roots_for_config<'a>(
&self,
input: &HostSkillsLoadInput,
repository: Option<&'a dyn EnvironmentAccess>,
project_markers: Option<&dyn EnvironmentAccess>,
host: &'a dyn EnvironmentAccess,
empty_remote_roots: Option<&Mutex<EmptyRemoteRootsCache>>,
) -> Vec<HostSkillRoot<'a>> {
let bundled_skills_enabled = bundled_skills_enabled_from_stack(&input.config_layer_stack);
if bundled_skills_enabled {
self.ensure_system_skills_installed();
}
let mut roots = resolve_skill_roots(
repository,
host,
&input.config_layer_stack,
&input.cwd,
project_markers,
input.effective_skill_roots.clone(),
self.extra_roots(),
empty_remote_roots,
)
.await;
if !bundled_skills_enabled {
roots.retain(|root| root.scope != SkillScope::System);
}
roots
}
async fn snapshot_for_cwd_with_root_snapshots(
&self,
input: &HostSkillsLoadInput,
force_reload: bool,
repository: Option<&dyn EnvironmentAccess>,
request_root_snapshots: Option<&RequestSkillRootSnapshots>,
) -> HostSkillsSnapshot {
let bundled_skills_enabled = bundled_skills_enabled_from_stack(&input.config_layer_stack);
if bundled_skills_enabled {
self.ensure_system_skills_installed();
}
let host = FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS);
let use_cwd_cache = repository.is_some();
let cache_snapshot_by_cwd = use_cwd_cache && input.effective_skill_roots.is_empty();
if cache_snapshot_by_cwd
&& !force_reload
&& let Some(snapshot) = self.cached_snapshot_for_cwd(&input.cwd)
{
return snapshot;
}
if force_reload {
self.empty_remote_roots
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clear();
}
let mut roots = resolve_skill_roots(
repository,
&host,
&input.config_layer_stack,
&input.cwd,
repository,
input.effective_skill_roots.clone(),
self.extra_roots(),
Some(&self.empty_remote_roots),
)
.await;
if !bundled_skills_enabled {
roots.retain(|root| root.scope != SkillScope::System);
}
let skill_config_rules = skill_config_rules_from_stack(&input.config_layer_stack);
let snapshot = if use_cwd_cache {
let cache_key = config_skills_cache_key(&roots, &skill_config_rules, input);
self.snapshot_for_skill_roots(
input,
roots,
&skill_config_rules,
cache_key,
force_reload,
request_root_snapshots,
)
.await
} else {
HostSkillsSnapshot::new(Arc::new(
self.build_skill_outcome(input, roots, &skill_config_rules, request_root_snapshots)
.await,
))
};
if cache_snapshot_by_cwd {
let mut cache = self
.cache_by_cwd
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner);
cache.insert(input.cwd.clone(), snapshot.clone());
}
snapshot
}
async fn snapshot_for_skill_roots(
&self,
input: &HostSkillsLoadInput,
roots: Vec<HostSkillRoot<'_>>,
skill_config_rules: &SkillConfigRules,
cache_key: ConfigSkillsCacheKey,
force_reload: bool,
request_root_snapshots: Option<&RequestSkillRootSnapshots>,
) -> HostSkillsSnapshot {
let snapshot_cell = {
let mut cache = self
.cache_by_config
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let snapshot_cell = cache
.iter()
.position(|entry| entry.key == cache_key)
.and_then(|index| cache.remove(index))
.filter(|_| !force_reload)
.map(|entry| entry.snapshot)
.unwrap_or_else(|| Arc::new(OnceCell::new()));
cache.push_front(ConfigSkillsCacheEntry {
key: cache_key,
snapshot: Arc::clone(&snapshot_cell),
});
// Keys retain parsed plugin generations; eviction releases obsolete catalogs while
// callers and in-flight loads keep their own snapshots alive.
cache.truncate(CONFIG_SKILLS_CACHE_CAPACITY);
snapshot_cell
};
snapshot_cell
.get_or_init(|| async {
HostSkillsSnapshot::new(Arc::new(
self.build_skill_outcome(
input,
roots,
skill_config_rules,
request_root_snapshots,
)
.await,
))
})
.await
.clone()
}
#[instrument(level = "trace", skip_all)]
async fn build_skill_outcome(
&self,
input: &HostSkillsLoadInput,
roots: Vec<HostSkillRoot<'_>>,
skill_config_rules: &SkillConfigRules,
request_root_snapshots: Option<&RequestSkillRootSnapshots>,
) -> SkillLoadOutcome {
let accessors = roots
.iter()
.filter(|root| input.implicit_repository_skills || root.scope != SkillScope::Repo)
.map(|root| root.file_system)
.collect::<Vec<_>>();
let outcome = load_and_merge_host_skill_roots_with_request_snapshots(
roots,
&self.root_scan_slots,
self.restriction_product,
input.plugin_skill_snapshots.as_ref(),
request_root_snapshots,
)
.await;
let disabled_paths = skill_config_rules.resolve_disabled_paths(
outcome
.skills
.iter()
.map(|skill| (skill.name.as_str(), &skill.path_to_skills_md)),
);
outcome
.with_disabled_paths(disabled_paths, &accessors)
.await
}
pub fn clear_cache(&self) {
self.empty_remote_roots
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clear();
let cleared_cwd = {
let mut cache = self
.cache_by_cwd
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let cleared = cache.len();
cache.clear();
cleared
};
let cleared_config = {
let mut cache = self
.cache_by_config
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let cleared = cache.len();
cache.clear();
cleared
};
let cleared = cleared_cwd + cleared_config;
info!("skills cache cleared ({cleared} entries)");
}
fn cached_snapshot_for_cwd(&self, cwd: &AbsolutePathBuf) -> Option<HostSkillsSnapshot> {
match self.cache_by_cwd.read() {
Ok(cache) => cache.get(cwd).cloned(),
Err(err) => err.into_inner().get(cwd).cloned(),
}
}
fn extra_roots(&self) -> Vec<AbsolutePathBuf> {
match self.extra_roots.read() {
Ok(roots) => roots.clone(),
Err(err) => err.into_inner().clone(),
}
}
fn ensure_system_skills_installed(&self) {
if let Err(err) = install_system_skills(&self.codex_home) {
tracing::error!("failed to install system skills: {err}");
}
}
}
impl SkillRootLoader<PluginSkillRoot> for HostSkillsService {
fn load_roots(
&self,
request: SkillRootLoadRequest<PluginSkillRoot>,
) -> SkillLoadFuture<'_, LoadedSkills> {
Box::pin(async move {
let host = FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS);
let roots = request
.roots
.into_iter()
.map(|root| HostSkillRoot::plugin(root, &host))
.collect();
let outcome = load_and_merge_host_skill_roots(
roots,
&self.root_scan_slots,
request.restriction_product,
request.snapshots.as_ref(),
)
.await;
LoadedSkills {
skills: outcome.skills,
errors: outcome.errors,
}
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct ConfigSkillsCacheKey {
roots: Vec<ConfigSkillRootCacheKey>,
implicit_repository_skills: bool,
skill_config_rules: SkillConfigRules,
plugin_skill_snapshots: Option<SkillRootSnapshots<PluginSkillRoot>>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(crate) struct ConfigSkillRootCacheKey {
path: AbsolutePathBuf,
scope_rank: u8,
plugin_identity: Option<PluginIdentity>,
plugin_namespace: Option<String>,
access: EnvironmentAccessKey,
}
fn config_skills_cache_key(
roots: &[HostSkillRoot<'_>],
skill_config_rules: &SkillConfigRules,
input: &HostSkillsLoadInput,
) -> ConfigSkillsCacheKey {
ConfigSkillsCacheKey {
roots: roots.iter().map(config_skill_root_cache_key).collect(),
implicit_repository_skills: input.implicit_repository_skills,
skill_config_rules: skill_config_rules.clone(),
plugin_skill_snapshots: input
.plugin_skill_snapshots
.as_ref()
.filter(|_| roots.iter().any(|root| root.plugin_identity().is_some()))
.cloned(),
}
}
pub(crate) fn config_skill_root_cache_key(root: &HostSkillRoot<'_>) -> ConfigSkillRootCacheKey {
let scope_rank = match root.scope {
SkillScope::Repo => 0,
SkillScope::User => 1,
SkillScope::System => 2,
SkillScope::Admin => 3,
};
ConfigSkillRootCacheKey {
path: root.path.clone(),
scope_rank,
plugin_identity: root.plugin_identity().cloned(),
plugin_namespace: root.plugin_namespace().map(str::to_string),
access: root.file_system.cache_key(),
}
}
#[cfg(test)]
#[path = "host_service_tests.rs"]
mod tests;

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,38 @@
use std::io;
use std::sync::Arc;
use crate::SkillLoadOutcome;
use codex_exec_server::EnvironmentAccess;
use codex_extension_api::ExtensionData;
use codex_skills::SkillMetadata;
/// Immutable snapshot of host-owned skills and their source filesystems.
#[derive(Debug, Clone)]
pub struct HostSkillsSnapshot {
outcome: Arc<SkillLoadOutcome>,
}
impl HostSkillsSnapshot {
pub fn new(outcome: Arc<SkillLoadOutcome>) -> Self {
Self { outcome }
}
/// Prefer the snapshot prepared with this step's permissions when the host supplies one.
pub fn for_step(step_store: &ExtensionData, turn_store: &ExtensionData) -> Option<Arc<Self>> {
step_store
.get::<Self>()
.or_else(|| turn_store.get::<Self>())
}
pub fn outcome(&self) -> &SkillLoadOutcome {
self.outcome.as_ref()
}
pub async fn read_skill_text(
&self,
skill: &SkillMetadata,
accessors: &[&dyn EnvironmentAccess],
) -> io::Result<String> {
self.outcome.read_skill_text(skill, accessors).await
}
}

View File

@@ -0,0 +1,116 @@
use codex_analytics::InvocationType;
use codex_analytics::SkillInvocation;
use codex_analytics::SkillInvocationLocation;
use codex_exec_server::LOCAL_ENVIRONMENT_ID;
use codex_extension_api::ExtensionData;
use codex_skills::ImplicitSkillAccess;
use codex_skills::detect_implicit_skill_invocation_for_command;
use codex_skills::implicit_skill_accesses_for_command;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::PathUri;
use crate::HostSkillsSnapshot;
use crate::catalog::SkillAuthority;
use crate::catalog::SkillCatalogEntry;
use crate::catalog::SkillResourceId;
use crate::catalog::SkillSourceKind;
use crate::catalog::SkillSourceLocation;
impl SkillCatalogEntry {
/// Uses merged identity and scope, with plugin attribution from the route actually used.
pub(crate) fn invocation(
&self,
source: &SkillSourceLocation,
invocation_type: InvocationType,
) -> SkillInvocation {
SkillInvocation {
skill_name: self.name.clone(),
location: SkillInvocationLocation::Resource {
id: self.main_prompt.as_str().to_owned(),
skill_id: self.canonical_skill_id.clone(),
scope: self.analytics_scope,
},
plugin_id: source.plugin_id.clone(),
remote_plugin_id: self.remote_plugin_id.clone(),
invocation_type,
}
}
}
/// Identifies the executor-owned or host-owned skill referenced by a command.
pub fn detect_implicit_skill_invocation(
turn_store: &ExtensionData,
step_store: &ExtensionData,
environment_id: &str,
command: &str,
workdir: &PathUri,
native_workdir: Option<&AbsolutePathBuf>,
) -> Option<SkillInvocation> {
if environment_id == LOCAL_ENVIRONMENT_ID
&& let Some(native_workdir) = native_workdir
&& let Some(host_snapshot) = HostSkillsSnapshot::for_step(step_store, turn_store)
&& let Some(skill) = detect_implicit_skill_invocation_for_command(
host_snapshot.outcome(),
command,
native_workdir,
)
{
return Some(SkillInvocation {
skill_name: skill.name,
location: SkillInvocationLocation::Host {
path: skill.path_to_skills_md,
scope: skill.scope,
},
plugin_id: skill.plugin_id,
remote_plugin_id: skill.remote_plugin_id,
invocation_type: InvocationType::Implicit,
});
}
let accesses = implicit_skill_accesses_for_command(command, workdir);
if accesses.is_empty() {
return None;
}
let step_state = step_store.get::<crate::step_state::SkillsStepState>()?;
let step_catalog = &step_state.catalog;
for access in accesses {
let matches_route = |authority: &SkillAuthority, main_prompt: &SkillResourceId| {
if authority.kind != SkillSourceKind::Executor
|| main_prompt.environment_id() != Some(environment_id)
{
return false;
}
let Some((_, skill_path)) = main_prompt.environment_path() else {
return false;
};
match &access {
ImplicitSkillAccess::Document(path) => path == skill_path,
ImplicitSkillAccess::Script(path) => skill_path
.parent()
.and_then(|skill_dir| skill_dir.join("scripts").ok())
.is_some_and(|scripts_dir| path.starts_with(&scripts_dir)),
}
};
for entry in step_catalog.merged.entries.iter().filter(|entry| {
matches!(
entry.authority.kind,
SkillSourceKind::Cloud | SkillSourceKind::Executor
)
}) {
if entry.enabled && matches_route(&entry.authority, &entry.main_prompt) {
return Some(entry.invocation(&entry.primary_source(), InvocationType::Implicit));
}
if let Some(source) = entry.sources.iter().find(|source| {
source.enabled && matches_route(&source.authority, &source.main_prompt)
}) {
return Some(entry.invocation(source, InvocationType::Implicit));
}
}
}
None
}
#[cfg(test)]
#[path = "invocation_tests.rs"]
mod tests;

View File

@@ -0,0 +1,100 @@
use pretty_assertions::assert_eq;
use super::*;
use crate::catalog::SkillAuthority;
use crate::catalog::SkillCatalog;
use crate::catalog::SkillCatalogEntry;
use crate::catalog::SkillPackageId;
use crate::catalog::SkillResourceId;
fn detect_executor_skill(command: &str, environments: &[&str]) -> Option<SkillInvocation> {
let skill_path = PathUri::parse("file:///skills/demo/SKILL.md").expect("valid skill URI");
let catalog = SkillCatalog {
is_partial: false,
entries: environments
.iter()
.map(|environment| {
SkillCatalogEntry::new(
SkillPackageId(format!("skill://{environment}/demo")),
SkillAuthority::new(SkillSourceKind::Executor, *environment),
format!("{environment}-skill"),
"test skill",
SkillResourceId::environment(
format!("skill://{environment}/demo/SKILL.md"),
*environment,
skill_path.clone(),
),
)
})
.collect(),
warnings: Vec::new(),
};
let turn_store = ExtensionData::new("test-turn");
let step_catalog = crate::step_state::SkillStepCatalog::new(
/*cloud*/ None,
catalog,
/*discovery_v2*/ false,
Default::default(),
);
let step_store = ExtensionData::new("step");
step_store.insert(crate::step_state::SkillsStepState {
discovery_v2: false,
tools_enabled: true,
catalog: step_catalog,
host_catalog: None,
cloud_status: crate::step_state::CatalogStatus::Unavailable,
config: crate::SkillsExtensionConfig {
include_instructions: true,
catalog_deltas_enabled: false,
omit_descriptions: false,
max_context_tokens: None,
bundled_skills_enabled: false,
cloud_skill_enabled: false,
shadow_selection_enabled: false,
},
});
detect_implicit_skill_invocation(
&turn_store,
&step_store,
"executor-a",
command,
&PathUri::parse("file:///skills").expect("valid workdir URI"),
/*native_workdir*/ None,
)
}
#[test]
fn detects_executor_skill_document_reads() {
let invocation = detect_executor_skill("cat demo/SKILL.md", &["executor-a"])
.expect("document read should identify the executor skill");
assert_eq!(invocation.skill_name, "executor-a-skill");
assert!(matches!(
invocation.location,
SkillInvocationLocation::Resource { id, .. }
if id == "skill://executor-a/demo/SKILL.md"
));
}
#[test]
fn detects_executor_skill_script_runs() {
let invocation = detect_executor_skill("python demo/scripts/run.py", &["executor-a"])
.expect("script execution should identify the executor skill");
assert_eq!(invocation.skill_name, "executor-a-skill");
}
#[test]
fn ignores_matching_paths_from_other_environments() {
let invocation = detect_executor_skill("cat demo/SKILL.md", &["executor-b", "executor-a"])
.expect("matching path should resolve to the execution environment");
assert_eq!(invocation.skill_name, "executor-a-skill");
assert!(detect_executor_skill("cat demo/SKILL.md", &["executor-b"]).is_none());
}
#[test]
fn ignores_commands_without_skill_access() {
assert!(detect_executor_skill("echo hello", &["executor-a"]).is_none());
}

View File

@@ -0,0 +1,69 @@
mod aliases;
pub mod catalog;
mod catalog_delta;
mod catalog_observability;
mod catalog_prompt;
mod catalog_state;
mod config;
mod dynamic_skill_selector;
mod extension;
mod fragments;
mod host_aliases;
mod host_outcome;
mod host_prompt;
mod host_roots;
mod host_service;
mod host_snapshot;
mod invocation;
mod loader;
mod preparation;
pub mod provider;
mod render;
mod render_observability;
mod required;
mod selection;
mod shadow_selection_experiment;
mod sources;
mod state;
mod step_state;
mod telemetry;
mod tools;
mod warnings;
mod world_state;
mod world_state_catalogs;
pub use catalog::merge_catalogs;
pub use config::SkillsExtensionConfig;
pub use extension::install;
pub use extension::install_with_providers;
pub use extension::install_with_providers_and_metrics;
pub use host_outcome::SkillLoadOutcome;
pub use host_prompt::HostSkillPrompts;
pub use host_prompt::InjectedHostSkillPrompts;
pub use host_service::HostSkillsLoadInput;
pub use host_service::HostSkillsRequest;
pub use host_service::HostSkillsService;
pub use host_snapshot::HostSkillsSnapshot;
pub use invocation::detect_implicit_skill_invocation;
pub use provider::ExecutorSkillProvider;
pub use provider::FrozenCloudSkillProvider;
pub use provider::HostSkillProvider;
pub use provider::SkillProvider;
pub use required::EnvironmentSkillRequirements;
pub use required::validate_required_skills;
pub use sources::SkillProviderSource;
pub use sources::SkillProviders;
pub use state::SkillsThreadState;
pub use telemetry::record_plugin_turn_usage;
/// Selected environments whose discovery can use a turn-scoped filesystem grant.
pub struct TurnSkillFilesystemGrants {
pub environment_ids: std::collections::HashSet<String>,
}
/// Recognizes persisted explicit skill prompts without exposing their fragment implementation.
pub fn is_skill_prompt_fragment(text: &str) -> bool {
<fragments::SkillInstructions as codex_extension_api::ContextualUserFragment>::matches_text(
text,
)
}

View 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 &current == 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;

View 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"),
]
);
}

View 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;

View 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,
}]
);
}

View 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");
}

View 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;

View 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
);
}

View 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;

View 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")),
]
);
}

View 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());
}

View 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)
}
}

View 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(())
}

View 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;

View 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;

View 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"]
);
}

View File

@@ -0,0 +1,110 @@
//! Resolves step policy once and prepares immutable catalogs before tool construction.
//! Cache operations and live read-time authorization remain on the thread state.
use crate::HostSkillsSnapshot;
use crate::SkillsExtensionConfig;
use crate::catalog::SkillCatalog;
use crate::catalog::apply_plugin_denials;
use crate::provider::SkillListQuery;
use crate::provider::attribute_executor_plugins;
use crate::sources::SkillProviders;
use crate::state::SkillsSessionState;
use crate::state::SkillsThreadState;
use crate::step_state::CatalogStatus;
use crate::step_state::SkillsStepState;
use codex_extension_api::StepPreparationInput;
pub(crate) async fn prepare_catalogs(
thread_state: &SkillsThreadState,
providers: &SkillProviders,
input: &StepPreparationInput<'_>,
) -> SkillsStepState {
let config = thread_state.config();
let cloud_enabled = config.cloud_skill_enabled && thread_state.cloud_skills_available();
let discovery_v2 = input.executor_capability_discovery_v2.is_some();
let mut cloud = cloud_enabled
.then(|| thread_state.available_cloud_catalog())
.flatten();
let (mut executor, host_catalog) = futures::join!(
discover_executor_catalog(thread_state, providers, input, &config, cloud_enabled),
discover_host_catalog(providers, input, &config),
);
if discovery_v2 {
apply_plugin_denials(&mut executor, input.selected_plugins);
if let Some(cloud) = &mut cloud {
apply_plugin_denials(cloud, input.selected_plugins);
}
} else {
attribute_executor_plugins(&mut executor, input.selected_plugins);
}
let cloud_status = if !providers.has_cloud_provider() {
CatalogStatus::Unavailable
} else if cloud_enabled {
CatalogStatus::Enabled
} else {
CatalogStatus::Disabled
};
SkillsStepState {
discovery_v2,
tools_enabled: cloud_enabled
|| !input.ready_selected_capability_roots.is_empty()
|| discovery_v2,
catalog: thread_state.prepare_step_catalog(cloud, executor, discovery_v2),
host_catalog,
cloud_status,
config,
}
}
async fn discover_executor_catalog(
thread_state: &SkillsThreadState,
providers: &SkillProviders,
input: &StepPreparationInput<'_>,
config: &SkillsExtensionConfig,
cloud_enabled: bool,
) -> SkillCatalog {
let query = SkillListQuery {
turn_id: input.turn_id.to_string(),
executor_roots: input.ready_selected_capability_roots.to_vec(),
host_snapshot: None,
include_host_skills: false,
include_bundled_skills: config.bundled_skills_enabled,
include_cloud_skills: cloud_enabled,
mcp_resources: input
.session_store
.get::<SkillsSessionState>()
.and_then(|state| state.mcp_resources.clone()),
executor_capability_discovery: input.executor_capability_discovery.cloned(),
executor_capability_discovery_v2: input.executor_capability_discovery_v2.map(Vec::from),
};
thread_state
.refresh_executor_catalog(providers, query)
.await
}
async fn discover_host_catalog(
providers: &SkillProviders,
input: &StepPreparationInput<'_>,
config: &SkillsExtensionConfig,
) -> Option<SkillCatalog> {
let host_snapshot = HostSkillsSnapshot::for_step(input.step_store, input.turn_store)
.filter(|_| providers.has_host_provider())?;
if !config.include_instructions && !config.shadow_selection_enabled {
return Some(SkillCatalog::default());
}
Some(
providers
.list_host_for_turn(SkillListQuery {
turn_id: input.turn_id.to_string(),
executor_roots: Vec::new(),
host_snapshot: Some(host_snapshot),
include_host_skills: true,
include_bundled_skills: false,
include_cloud_skills: false,
mcp_resources: None,
executor_capability_discovery: None,
executor_capability_discovery_v2: None,
})
.await,
)
}

View File

@@ -0,0 +1,105 @@
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
mod executor;
mod frozen_cloud;
mod host;
use crate::HostSkillsSnapshot;
use codex_exec_server::EnvironmentAccess;
use codex_exec_server::ExecutorCapabilityDiscoverySnapshot;
use codex_exec_server::ExecutorCapabilityDiscoveryV2Snapshot;
use codex_extension_api::AccessedSelectedCapabilityRoot;
use codex_mcp::McpResourceClient;
use crate::catalog::SkillAuthority;
use crate::catalog::SkillCatalog;
use crate::catalog::SkillPackageId;
use crate::catalog::SkillProviderResult;
use crate::catalog::SkillReadResult;
use crate::catalog::SkillResourceId;
use crate::catalog::SkillSearchResult;
pub use executor::ExecutorSkillProvider;
pub(crate) use executor::attribute_executor_plugins;
pub use frozen_cloud::FrozenCloudSkillProvider;
pub use host::HostSkillProvider;
pub(crate) const MAX_SKILL_RESOURCE_CONTENT_BYTES: usize = 1024 * 1024;
/// Catalog inputs with executor roots bound to filesystem access for this callback.
#[derive(Clone)]
pub struct SkillListQuery<'a> {
pub turn_id: String,
pub executor_roots: Vec<AccessedSelectedCapabilityRoot<'a>>,
pub host_snapshot: Option<Arc<HostSkillsSnapshot>>,
pub include_host_skills: bool,
pub include_bundled_skills: bool,
pub include_cloud_skills: bool,
pub mcp_resources: Option<Arc<McpResourceClient>>,
/// Present only when the opt-in high-level executor discovery path is selected.
pub executor_capability_discovery: Option<ExecutorCapabilityDiscoverySnapshot>,
/// Present when V2 is selected, including empty or failed discovery. Never falls back to V1.
pub executor_capability_discovery_v2: Option<Vec<ExecutorCapabilityDiscoveryV2Snapshot>>,
}
/// A skill read with the source access supplied by its callback.
#[derive(Clone)]
pub struct SkillReadRequest<'a> {
pub authority: SkillAuthority,
pub package: SkillPackageId,
pub resource: SkillResourceId,
pub context: SkillReadContext<'a>,
}
/// Repository and executor reads require callback access; other sources retain provider context.
#[derive(Clone)]
pub enum SkillReadContext<'a> {
Host {
host_snapshot: Option<Arc<HostSkillsSnapshot>>,
accessors: Vec<&'a dyn EnvironmentAccess>,
},
Executor {
fs: &'a dyn EnvironmentAccess,
},
Cloud {
mcp_resources: Option<Arc<McpResourceClient>>,
},
Custom {
mcp_resources: Option<Arc<McpResourceClient>>,
},
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SkillSearchRequest {
pub authority: SkillAuthority,
pub package: SkillPackageId,
pub query: String,
}
pub type SkillProviderFuture<'a, T> =
Pin<Box<dyn Future<Output = SkillProviderResult<T>> + Send + 'a>>;
/// Source-specific skill catalog and resource access.
///
/// Implementations must preserve authority boundaries: a resource listed by a
/// provider must be read or searched through the same provider/authority rather
/// than converted into an ambient local path.
pub trait SkillProvider: Send + Sync {
/// Whether Cloud catalog and read caches must follow the live MCP auth/resource scope.
/// When all configured Cloud providers opt out, their caches are independent of MCP.
fn uses_mcp_resources(&self) -> bool {
true
}
/// Providers set `is_partial` when listing omits entries; warnings are diagnostic only.
fn list<'a>(&'a self, query: SkillListQuery<'a>) -> SkillProviderFuture<'a, SkillCatalog>;
fn read<'a>(
&'a self,
request: SkillReadRequest<'a>,
) -> SkillProviderFuture<'a, SkillReadResult>;
fn search(&self, request: SkillSearchRequest) -> SkillProviderFuture<'_, SkillSearchResult>;
}

View File

@@ -0,0 +1,321 @@
use std::collections::HashMap;
use std::collections::HashSet;
use codex_exec_server::EnvironmentAccess;
mod discovery_v2;
use codex_extension_api::SelectedPluginSnapshot;
use codex_protocol::capabilities::CapabilityRootLocation;
use codex_protocol::protocol::Product;
use codex_protocol::protocol::SkillScope;
use codex_skills::EnvironmentSkillMetadata;
use codex_utils_path_uri::PathConvention;
use codex_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.analytics_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: &codex_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,105 @@
//! Projects executor-owned discovery metadata into skill catalogs without reopening host paths.
use codex_exec_server::ExecutorCapabilityDiscoveryV2Snapshot;
use codex_exec_server::ExecutorSkill;
use codex_protocol::protocol::SkillScope;
use codex_skills::EnvironmentSkillMetadata;
use codex_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.remote_plugin_id = plugin.remote_plugin_id.clone();
entry.plugin_id = Some(plugin.id.clone());
entry.analytics_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,164 @@
//! Immutable cloud skill snapshots for offline sources. Only declared package resources are
//! readable; the normal skills extension owns aliases, tool schemas, rendering, and pagination.
use std::collections::HashMap;
use std::io::Read;
use std::path::Path;
use codex_mcp::CODEX_APPS_MCP_SERVER_NAME;
use serde::Deserialize;
use super::MAX_SKILL_RESOURCE_CONTENT_BYTES;
use super::SkillListQuery;
use super::SkillProvider;
use super::SkillProviderFuture;
use super::SkillReadRequest;
use super::SkillSearchRequest;
use crate::catalog::SkillAuthority;
use crate::catalog::SkillCatalog;
use crate::catalog::SkillCatalogEntry;
use crate::catalog::SkillPackageId;
use crate::catalog::SkillProviderError;
use crate::catalog::SkillProviderResult;
use crate::catalog::SkillReadResult;
use crate::catalog::SkillResourceId;
use crate::catalog::SkillSearchResult;
use crate::catalog::SkillSourceKind;
const MAX_SNAPSHOT_BYTES: usize = 64 * 1024 * 1024;
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Snapshot {
skills: Vec<SnapshotSkill>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct SnapshotSkill {
package: String,
name: String,
description: String,
alias_root: String,
main_resource: String,
#[serde(default = "default_prompt_visible")]
prompt_visible: bool,
resources: HashMap<String, String>,
}
fn default_prompt_visible() -> bool {
true
}
/// Supplies a fixed cloud catalog and resource contents without contacting a skill service.
pub struct FrozenCloudSkillProvider {
catalog: SkillCatalog,
resources: HashMap<SkillPackageId, HashMap<String, String>>,
}
impl FrozenCloudSkillProvider {
/// Loads once from a host-owned file; subsequent reads never access the filesystem.
pub fn from_file(path: &Path) -> SkillProviderResult<Self> {
let mut bytes = Vec::new();
std::fs::File::open(path)
.and_then(|file| {
file.take((MAX_SNAPSHOT_BYTES + 1) as u64)
.read_to_end(&mut bytes)
})
.map_err(|err| SkillProviderError::new(format!("cannot read skill snapshot: {err}")))?;
Self::from_json(&bytes)
}
/// Rejects missing main resources, duplicate packages, and resources outside their package.
pub fn from_json(bytes: &[u8]) -> SkillProviderResult<Self> {
if bytes.len() > MAX_SNAPSHOT_BYTES {
return Err(SkillProviderError::new("skill snapshot exceeds 64 MiB"));
}
let snapshot: Snapshot = serde_json::from_slice(bytes)
.map_err(|err| SkillProviderError::new(format!("invalid skill snapshot: {err}")))?;
let mut catalog = SkillCatalog::default();
let mut resources = HashMap::new();
for skill in snapshot.skills {
let package = SkillPackageId(skill.package);
let root = SkillPackageId(skill.alias_root.clone());
if !skill.alias_root.starts_with("skill://")
|| root.relative_resource_path(&package.0).is_none()
|| skill.name.trim().is_empty()
|| !skill.resources.contains_key(&skill.main_resource)
|| skill.resources.iter().any(|(resource, contents)| {
package.relative_resource_path(resource).is_none()
|| contents.len() > MAX_SKILL_RESOURCE_CONTENT_BYTES
})
{
return Err(SkillProviderError::new("invalid skill package or resource"));
}
let mut entry = SkillCatalogEntry::new(
package.clone(),
SkillAuthority::new(SkillSourceKind::Cloud, CODEX_APPS_MCP_SERVER_NAME),
skill.name,
skill.description,
SkillResourceId::new(skill.main_resource),
)
.with_display_path(&package.0)
.with_alias_root(skill.alias_root);
if !skill.prompt_visible {
entry = entry.hidden_from_prompt();
}
catalog.entries.push(entry);
if resources.insert(package, skill.resources).is_some() {
return Err(SkillProviderError::new("duplicate skill package"));
}
}
Ok(Self { catalog, resources })
}
}
impl SkillProvider for FrozenCloudSkillProvider {
fn uses_mcp_resources(&self) -> bool {
false
}
fn list<'a>(&'a self, query: SkillListQuery<'a>) -> SkillProviderFuture<'a, SkillCatalog> {
Box::pin(async move {
Ok(if query.include_cloud_skills {
self.catalog.clone()
} else {
SkillCatalog::default()
})
})
}
fn read<'a>(
&'a self,
request: SkillReadRequest<'a>,
) -> SkillProviderFuture<'a, SkillReadResult> {
Box::pin(async move {
if request.authority
!= SkillAuthority::new(SkillSourceKind::Cloud, CODEX_APPS_MCP_SERVER_NAME)
{
return Err(SkillProviderError::new("invalid frozen skill authority"));
}
let contents = self
.resources
.get(&request.package)
.and_then(|resources| resources.get(request.resource.as_str()))
.ok_or_else(|| SkillProviderError::new("unknown frozen skill resource"))?;
Ok(SkillReadResult {
resource: request.resource,
contents: contents.clone(),
})
})
}
fn search(&self, _request: SkillSearchRequest) -> SkillProviderFuture<'_, SkillSearchResult> {
Box::pin(async {
Err(SkillProviderError::new(
"frozen skill snapshots do not support search",
))
})
}
}
#[cfg(test)]
#[path = "frozen_cloud_tests.rs"]
mod tests;

View File

@@ -0,0 +1,92 @@
//! Snapshot validation and immutable resource reads across authority boundaries.
use super::*;
use crate::provider::SkillReadContext;
use pretty_assertions::assert_eq;
use serde_json::json;
fn snapshot() -> serde_json::Value {
json!({"skills": [{
"package": "skill://demo/work",
"name": "demo:work",
"description": "Do the work.",
"alias_root": "skill://demo",
"main_resource": "skill://demo/work/SKILL.md",
"resources": {"skill://demo/work/SKILL.md": "# Work\nKeep it readable.\n"}
}]})
}
fn request() -> SkillReadRequest<'static> {
SkillReadRequest {
authority: SkillAuthority::new(SkillSourceKind::Cloud, CODEX_APPS_MCP_SERVER_NAME),
package: SkillPackageId("skill://demo/work".into()),
resource: SkillResourceId::new("skill://demo/work/SKILL.md"),
context: SkillReadContext::Cloud {
mcp_resources: None,
},
}
}
#[tokio::test]
async fn file_is_loaded_once_and_reads_preserve_the_exact_contents() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("skills.json");
std::fs::write(&path, snapshot().to_string()).unwrap();
let provider = FrozenCloudSkillProvider::from_file(&path).unwrap();
std::fs::remove_file(path).unwrap();
assert_eq!(
provider.read(request()).await.unwrap(),
SkillReadResult {
resource: request().resource,
contents: "# Work\nKeep it readable.\n".into(),
}
);
assert_eq!(provider.catalog.entries.len(), 1);
assert!(provider.catalog.entries[0].prompt_visible);
assert_eq!(
provider.catalog.entries[0].rendered_path(),
"skill://demo/work"
);
}
#[tokio::test]
async fn hidden_skills_remain_readable_without_implicit_prompt_exposure() {
let mut value = snapshot();
value["skills"][0]["prompt_visible"] = json!(false);
let provider = FrozenCloudSkillProvider::from_json(value.to_string().as_bytes()).unwrap();
assert!(!provider.catalog.entries[0].prompt_visible);
assert_eq!(
provider.read(request()).await.unwrap().contents,
"# Work\nKeep it readable.\n"
);
}
#[tokio::test]
async fn reads_cannot_cross_authority_or_package_boundaries() {
let provider = FrozenCloudSkillProvider::from_json(snapshot().to_string().as_bytes()).unwrap();
let mut other_authority = request();
other_authority.authority = SkillAuthority::new(SkillSourceKind::Executor, "demo");
let mut other_package = request();
other_package.package = SkillPackageId("skill://other/work".into());
let mut other_resource = request();
other_resource.resource = SkillResourceId::new("skill://demo/work/../SKILL.md");
for request in [other_authority, other_package, other_resource] {
assert!(provider.read(request).await.is_err());
}
}
#[test]
fn malformed_snapshots_are_rejected_before_inference() {
let mut missing_main = snapshot();
missing_main["skills"][0]["main_resource"] = json!("skill://demo/work/missing.md");
let mut escaped = snapshot();
escaped["skills"][0]["resources"]["skill://other/secret.md"] = json!("secret");
let mut oversized = snapshot();
oversized["skills"][0]["resources"]["skill://demo/work/SKILL.md"] =
json!("x".repeat(MAX_SKILL_RESOURCE_CONTENT_BYTES + 1));
let mut duplicate = snapshot();
duplicate["skills"] = json!([snapshot()["skills"][0], snapshot()["skills"][0]]);
for value in [missing_main, escaped, oversized, duplicate] {
assert!(FrozenCloudSkillProvider::from_json(value.to_string().as_bytes()).is_err());
}
}

View File

@@ -0,0 +1,179 @@
use std::collections::HashMap;
use crate::SkillLoadOutcome;
use codex_skills::SkillMetadata;
use codex_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 codex_exec_server::FileSystemEnvironmentAccessor;
use std::sync::Arc;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;
use codex_exec_server::LOCAL_FS;
use codex_protocol::protocol::SkillScope;
use codex_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(())
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,196 @@
//! Prefers cloud skills before budgeting while retaining aliases from the full visible inventory.
//! Collects comparison metadata after the final rendering has been selected.
use std::borrow::Cow;
use std::collections::BTreeMap;
use std::collections::HashSet;
use codex_protocol::protocol::SkillScope;
use super::AvailableSkillsRender;
use super::CatalogLines;
use super::SkillCatalogRenderPolicy;
use super::SkillCatalogRenderStyle;
use super::SkillMetadataBudget;
use super::aliased_render_is_better;
use super::build_alias_plan;
use super::build_aliased_catalog;
use super::render_catalog;
use crate::aliases::AliasPlan;
use crate::catalog::SkillCatalog;
use crate::catalog::SkillCatalogEntry;
use crate::catalog::SkillSourceKind;
use crate::catalog_delta::CatalogSkill;
use crate::catalog_delta::GrantStatus;
use crate::catalog_delta::SkillEntrySnapshot;
use crate::catalog_prompt::SkillPromptKind;
pub(crate) struct PreparedSkillCatalog<'a> {
pub(super) entries: Vec<&'a SkillCatalogEntry>,
alias_plan: Option<Cow<'a, AliasPlan>>,
policy: SkillCatalogRenderPolicy,
}
impl<'a> PreparedSkillCatalog<'a> {
pub(crate) fn new(catalog: &'a SkillCatalog, policy: SkillCatalogRenderPolicy) -> Self {
Self::with_alias_plan(catalog, policy, /*alias_plan*/ None)
}
pub(crate) fn with_alias_plan(
catalog: &'a SkillCatalog,
policy: SkillCatalogRenderPolicy,
alias_plan: Option<&'a AliasPlan>,
) -> Self {
let mut entries = catalog
.entries
.iter()
.filter(|entry| entry.is_model_visible())
.collect::<Vec<_>>();
policy.order_entries(&mut entries);
let alias_plan = alias_plan
.map(Cow::Borrowed)
.or_else(|| build_alias_plan(&entries).map(Cow::Owned));
Self {
entries,
alias_plan,
policy,
}
}
pub(crate) fn prefer_cloud_skills(&mut self, cloud: &SkillCatalog) {
let cloud_names: HashSet<_> = cloud
.entries
.iter()
.filter(|entry| entry.is_model_visible())
.map(|entry| entry.name.as_str())
.filter(|name| {
name.split_once(':')
.is_some_and(|(plugin, skill)| !plugin.is_empty() && !skill.is_empty())
})
.collect();
self.entries
.retain(|entry| !cloud_names.contains(entry.name.as_str()));
}
pub(super) fn unaliased(&self) -> CatalogLines<'a> {
CatalogLines::unaliased(&self.entries, self.policy)
}
pub(super) fn aliased(&self) -> CatalogLines<'a> {
CatalogLines::aliased(&self.entries, self.policy, self.alias_plan.as_ref())
}
/// Collect comparison metadata once the final layout and budget have been selected.
/// Include every eligible entry, even when its rendered row was omitted.
pub(crate) fn entries_for_render(
&self,
rendered: &AvailableSkillsRender,
grants: Option<&crate::TurnSkillFilesystemGrants>,
primary_environment: Option<&str>,
) -> BTreeMap<String, CatalogSkill> {
let lines = if rendered.skill_root_lines.is_empty() {
self.unaliased()
} else {
self.aliased()
};
let shown = rendered
.included_ids
.as_ref()
.map(|ids| ids.iter().collect::<HashSet<_>>());
lines
.skills
.into_iter()
.map(|line| {
let id = line.catalog_id();
let entry = line.entry;
let fingerprint = blake3::hash(
serde_json::json!([
entry.name,
line.description,
entry.main_prompt.as_str(),
line.locator,
])
.to_string()
.as_bytes(),
)
.to_hex()
.to_string();
let locator = entry.unaliased_locator();
let root = self
.alias_plan
.as_ref()
.filter(|_| line.locator != locator)
.and_then(|plan| plan.root_for_locator(locator))
.cloned();
let shown = shown.as_ref().is_none_or(|ids| ids.contains(&id));
let environment = match &entry.authority.kind {
SkillSourceKind::Executor => entry.main_prompt.environment_id(),
SkillSourceKind::Host if entry.prompt_scope() == Some(SkillScope::Repo) => {
primary_environment
}
SkillSourceKind::Host | SkillSourceKind::Cloud | SkillSourceKind::Custom(_) => {
None
}
};
let granted = environment.is_some_and(|id| {
grants.is_some_and(|grants| grants.environment_ids.contains(id))
});
(
id,
CatalogSkill {
snapshot: SkillEntrySnapshot {
fingerprint,
shown,
grant: granted.then_some(GrantStatus::Active),
},
line: line.render_full(),
root,
},
)
})
.collect()
}
pub(crate) fn render(
&self,
budget: SkillMetadataBudget,
include_skills_usage_instructions: bool,
) -> Option<AvailableSkillsRender> {
if self.entries.is_empty() {
return None;
}
let absolute = render_catalog(
self.unaliased().skills,
budget,
Vec::new(),
self.policy.prompt(SkillPromptKind::Unaliased),
self.policy,
);
let selected = if let Some(aliased) = build_aliased_catalog(
self.aliased(),
self.policy,
budget,
include_skills_usage_instructions,
) && aliased_render_is_better(
&aliased,
&absolute,
budget,
include_skills_usage_instructions,
) {
aliased
} else {
absolute
};
Some(AvailableSkillsRender {
prompt: selected.prompt,
skill_root_lines: selected.skill_root_lines,
skill_lines: selected.skill_lines,
included_ids: selected.included_ids,
entries: BTreeMap::new(),
preserve_empty_fragment: self.policy.style == SkillCatalogRenderStyle::CoreCompatible,
report: selected.report,
})
}
}

View File

@@ -0,0 +1,110 @@
use codex_extension_api::ExtensionMetrics;
use codex_otel::THREAD_SKILLS_COUNT_METRIC_BUCKETS;
use codex_otel::THREAD_SKILLS_DESCRIPTION_TRUNCATED_CHARS_BUCKETS;
use codex_otel::THREAD_SKILLS_DESCRIPTION_TRUNCATED_CHARS_METRIC;
use codex_otel::THREAD_SKILLS_ENABLED_TOTAL_METRIC;
use codex_otel::THREAD_SKILLS_KEPT_TOTAL_METRIC;
use codex_otel::THREAD_SKILLS_TRUNCATED_BUCKETS;
use codex_otel::THREAD_SKILLS_TRUNCATED_METRIC;
use crate::render::SkillMetadataBudget;
use crate::render::SkillRenderReport;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum CatalogSurface {
ThreadContext,
ExecutorWorldState,
CloudWorldState,
HostWorldState,
TurnInput,
}
impl CatalogSurface {
fn as_str(self) -> &'static str {
match self {
Self::ThreadContext => "thread_context",
Self::ExecutorWorldState => "executor_world_state",
Self::CloudWorldState => "cloud_world_state",
Self::HostWorldState => "host_world_state",
Self::TurnInput => "turn_input",
}
}
}
pub(crate) fn record_catalog_render(
extension_metrics: Option<&dyn ExtensionMetrics>,
catalog_surface: CatalogSurface,
budget: SkillMetadataBudget,
report: &SkillRenderReport,
) {
record_catalog_metrics(
extension_metrics,
catalog_surface,
report.total_count,
report.included_count,
report.omitted_count,
report.truncated_description_chars,
);
trace_catalog_budget_pressure(budget, report);
}
pub(crate) fn trace_catalog_budget_pressure(
budget: SkillMetadataBudget,
report: &SkillRenderReport,
) {
if report.omitted_count > 0 || report.truncated_description_chars > 0 {
tracing::info!(
budget_limit = budget.limit(),
total_skills = report.total_count,
included_skills = report.included_count,
omitted_skills = report.omitted_count,
truncated_description_chars_per_skill = report.average_truncated_description_chars(),
truncated_skill_descriptions = report.truncated_description_count,
"truncated skill metadata to fit skills context budget"
);
}
}
pub(crate) fn record_catalog_metrics(
extension_metrics: Option<&dyn ExtensionMetrics>,
catalog_surface: CatalogSurface,
total_count: usize,
included_count: usize,
omitted_count: usize,
truncated_description_chars: usize,
) {
let Some(extension_metrics) = extension_metrics else {
return;
};
let samples = [
(
THREAD_SKILLS_ENABLED_TOTAL_METRIC,
i64::try_from(total_count).unwrap_or(i64::MAX),
THREAD_SKILLS_COUNT_METRIC_BUCKETS.as_slice(),
),
(
THREAD_SKILLS_KEPT_TOTAL_METRIC,
i64::try_from(included_count).unwrap_or(i64::MAX),
THREAD_SKILLS_COUNT_METRIC_BUCKETS.as_slice(),
),
(
THREAD_SKILLS_TRUNCATED_METRIC,
if omitted_count > 0 { 1 } else { 0 },
THREAD_SKILLS_TRUNCATED_BUCKETS,
),
(
THREAD_SKILLS_DESCRIPTION_TRUNCATED_CHARS_METRIC,
i64::try_from(truncated_description_chars).unwrap_or(i64::MAX),
THREAD_SKILLS_DESCRIPTION_TRUNCATED_CHARS_BUCKETS.as_slice(),
),
];
let tags = [("catalog_surface", catalog_surface.as_str())];
for (name, value, boundaries) in samples {
extension_metrics.histogram_with_boundaries(name, value, boundaries, &tags);
}
}
#[cfg(test)]
#[path = "render_observability_tests.rs"]
mod tests;

View File

@@ -0,0 +1,102 @@
use std::sync::Mutex;
use codex_extension_api::ExtensionMetrics;
use pretty_assertions::assert_eq;
use super::*;
#[derive(Debug, PartialEq)]
struct RecordedHistogram {
name: String,
value: i64,
boundaries: Vec<f64>,
tags: Vec<(String, String)>,
}
#[derive(Default)]
struct RecordingMetrics {
samples: Mutex<Vec<RecordedHistogram>>,
}
impl ExtensionMetrics for RecordingMetrics {
fn histogram_with_boundaries(
&self,
name: &str,
value: i64,
boundaries: &[f64],
tags: &[(&str, &str)],
) {
self.samples
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.push(RecordedHistogram {
name: name.to_string(),
value,
boundaries: boundaries.to_vec(),
tags: tags
.iter()
.map(|(key, value)| ((*key).to_string(), (*value).to_string()))
.collect(),
});
}
fn counter(&self, name: &str, _inc: i64, _tags: &[(&str, &str)]) {
panic!("unexpected counter: {name}");
}
fn histogram(&self, name: &str, _value: i64, _tags: &[(&str, &str)]) {
panic!("unexpected histogram without context boundaries: {name}");
}
}
#[test]
fn records_core_equivalent_catalog_render_metrics_with_surface() {
let metrics = RecordingMetrics::default();
let report = SkillRenderReport {
total_count: 5,
included_count: 3,
omitted_count: 2,
truncated_description_chars: 700,
truncated_description_count: 4,
};
record_catalog_render(
Some(&metrics),
CatalogSurface::TurnInput,
SkillMetadataBudget::Tokens(400),
&report,
);
assert_eq!(
*metrics
.samples
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner),
vec![
RecordedHistogram {
name: THREAD_SKILLS_ENABLED_TOTAL_METRIC.to_string(),
value: 5,
boundaries: THREAD_SKILLS_COUNT_METRIC_BUCKETS.to_vec(),
tags: vec![("catalog_surface".to_string(), "turn_input".to_string())],
},
RecordedHistogram {
name: THREAD_SKILLS_KEPT_TOTAL_METRIC.to_string(),
value: 3,
boundaries: THREAD_SKILLS_COUNT_METRIC_BUCKETS.to_vec(),
tags: vec![("catalog_surface".to_string(), "turn_input".to_string())],
},
RecordedHistogram {
name: THREAD_SKILLS_TRUNCATED_METRIC.to_string(),
value: 1,
boundaries: THREAD_SKILLS_TRUNCATED_BUCKETS.to_vec(),
tags: vec![("catalog_surface".to_string(), "turn_input".to_string())],
},
RecordedHistogram {
name: THREAD_SKILLS_DESCRIPTION_TRUNCATED_CHARS_METRIC.to_string(),
value: 700,
boundaries: THREAD_SKILLS_DESCRIPTION_TRUNCATED_CHARS_BUCKETS.to_vec(),
tags: vec![("catalog_surface".to_string(), "turn_input".to_string())],
},
]
);
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,49 @@
//! Checks source-scoped requirements against skills discovered before inference.
use codex_extension_api::ExtensionData;
use crate::step_state::SkillsStepState;
/// Skill names that must be supplied by one selected environment before inference.
pub struct EnvironmentSkillRequirements<'a> {
pub environment_id: &'a str,
pub skill_names: &'a [String],
}
/// Validates requirements against the policy-checked catalog prepared for this step.
pub fn validate_required_skills<'a>(
step_store: &ExtensionData,
environments: impl IntoIterator<Item = EnvironmentSkillRequirements<'a>>,
) -> Result<(), String> {
let mut environments = environments.into_iter().peekable();
if environments.peek().is_none() {
return Ok(());
}
let step_state = step_store.get::<SkillsStepState>().ok_or_else(|| {
"Required skills cannot be validated because the skills extension is unavailable"
.to_string()
})?;
for EnvironmentSkillRequirements {
environment_id,
skill_names,
} in environments
{
for name in skill_names {
let available = step_state.catalog.merged.entries.iter().any(|entry| {
entry.enabled
&& entry.name == name.as_str()
&& (entry.main_prompt.environment_id() == Some(environment_id)
|| entry.sources.iter().any(|source| {
source.enabled
&& source.main_prompt.environment_id() == Some(environment_id)
}))
});
if !available {
return Err(format!(
"Required skill {name:?} from environment {environment_id:?} is unavailable"
));
}
}
}
Ok(())
}

View File

@@ -0,0 +1,144 @@
use std::collections::HashSet;
use codex_protocol::user_input::UserInput;
use codex_skills::extract_tool_mentions;
use crate::catalog::SkillAuthority;
use crate::catalog::SkillCatalog;
use crate::catalog::SkillCatalogEntry;
use crate::catalog::SkillPackageId;
const SKILL_PATH_PREFIX: &str = "skill://";
#[tracing::instrument(
level = "trace",
skip_all,
fields(
input_count = inputs.len(),
catalog_entry_count = catalog.entries.len()
)
)]
pub(crate) fn collect_explicit_skill_mentions(
inputs: &[UserInput],
catalog: &SkillCatalog,
) -> Vec<SkillCatalogEntry> {
let mut selected = Vec::new();
let mut seen = HashSet::new();
let mut blocked_plain_names = HashSet::new();
for input in inputs {
match input {
UserInput::Skill { name, path } => {
blocked_plain_names.insert(name.clone());
select_by_path(catalog, &path.to_string_lossy(), &mut seen, &mut selected);
}
UserInput::Mention { name, path } if path_is_skill(path) => {
blocked_plain_names.insert(name.clone());
select_by_path(catalog, path, &mut seen, &mut selected);
}
UserInput::Text { .. }
| UserInput::Image { .. }
| UserInput::LocalImage { .. }
| UserInput::Audio { .. }
| UserInput::LocalAudio { .. } => {}
UserInput::Mention { .. } => {}
_ => {}
}
}
for input in inputs {
let UserInput::Text { text, .. } = input else {
continue;
};
let mentions = extract_tool_mentions(text);
for path in mentions.paths() {
if path_is_skill(path) {
select_by_path(
catalog,
normalize_skill_path(path),
&mut seen,
&mut selected,
);
}
}
for name in mentions.plain_names() {
if blocked_plain_names.contains(name) {
continue;
}
if let Some(entry) = catalog
.entries
.iter()
.find(|entry| entry.enabled && entry.name == name)
{
push_selected(entry, &mut seen, &mut selected);
}
}
}
selected
}
fn select_by_path(
catalog: &SkillCatalog,
path: &str,
seen: &mut HashSet<SkillCatalogEntryKey>,
selected: &mut Vec<SkillCatalogEntry>,
) {
let normalized_path = normalize_skill_path(path);
for entry in catalog.entries.iter().filter(|entry| entry.enabled) {
if entry_matches_path(entry, normalized_path) {
push_selected(entry, seen, selected);
}
}
}
fn push_selected(
entry: &SkillCatalogEntry,
seen: &mut HashSet<SkillCatalogEntryKey>,
selected: &mut Vec<SkillCatalogEntry>,
) {
let key = SkillCatalogEntryKey::from(entry);
if seen.insert(key) {
selected.push(entry.clone());
}
}
fn entry_matches_path(entry: &SkillCatalogEntry, path: &str) -> bool {
entry.source_locations().any(|source| {
source.enabled
&& (source.main_prompt.as_str() == path
|| source.package.0 == path
|| source
.display_path
.as_deref()
.is_some_and(|display_path| normalize_skill_path(display_path) == path))
})
}
fn path_is_skill(path: &str) -> bool {
path.starts_with(SKILL_PATH_PREFIX)
|| path
.rsplit(['/', '\\'])
.next()
.is_some_and(|file_name| file_name.eq_ignore_ascii_case("SKILL.md"))
}
fn normalize_skill_path(path: &str) -> &str {
path.strip_prefix(SKILL_PATH_PREFIX).unwrap_or(path)
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct SkillCatalogEntryKey {
authority: SkillAuthority,
package: SkillPackageId,
}
impl From<&SkillCatalogEntry> for SkillCatalogEntryKey {
fn from(entry: &SkillCatalogEntry) -> Self {
Self {
authority: entry.authority.clone(),
package: entry.id.clone(),
}
}
}

View File

@@ -0,0 +1,370 @@
use pretty_assertions::assert_eq;
use super::*;
#[test]
fn recent_invocations_refresh_recency_and_evict_old_skills() {
let history = RecentSkillInvocations::default();
for index in 0..=MAX_SHADOW_RESULTS {
history.record(format!("skill-{index}"));
}
history.record("skill-1".to_string());
let recent = history.snapshot();
assert_eq!(MAX_SHADOW_RESULTS, recent.len());
assert_eq!(Some("skill-1"), recent.first().map(String::as_str));
assert_eq!(Some("skill-2"), recent.last().map(String::as_str));
assert!(!recent.iter().any(|skill| skill == "skill-0"));
}
#[test]
fn rank_buckets_distinguish_results_above_twenty() {
assert_eq!("11_20", rank_bucket(Some(20)));
assert_eq!("21_50", rank_bucket(Some(21)));
assert_eq!("21_50", rank_bucket(Some(50)));
assert_eq!("miss", rank_bucket(Some(51)));
}
// These tests deliberately occupy the process-wide budget and must drain their
// workers before the next test starts.
static RANKING_TESTS: Semaphore = Semaphore::const_new(1);
#[tokio::test]
async fn turn_input_and_history_advance_while_ranking_is_blocked()
-> Result<(), Box<dyn std::error::Error>> {
use std::collections::BTreeMap;
use codex_extension_api::ExtensionData;
use codex_extension_api::ExtensionRegistryBuilder;
use codex_extension_api::SkillInvocationInput;
use codex_extension_api::SkillInvocationKind;
use codex_extension_api::ThreadStartInput;
use codex_otel::MetricsConfig;
use codex_protocol::protocol::SessionSource;
use opentelemetry_sdk::metrics::InMemoryMetricExporter;
use opentelemetry_sdk::metrics::data::AggregatedMetrics;
use opentelemetry_sdk::metrics::data::MetricData;
use opentelemetry_sdk::metrics::data::ScopeMetrics;
use crate::SkillProviders;
use crate::SkillsExtensionConfig;
use crate::SkillsThreadState;
use crate::catalog::SkillAuthority;
use crate::catalog::SkillPackageId;
use crate::catalog::SkillResourceId;
use crate::install_with_providers_and_metrics;
use crate::step_state::CatalogStatus;
use crate::step_state::SkillsStepState;
let _serial = RANKING_TESTS.acquire().await.unwrap();
let slots = RANKING_SLOTS.acquire_many(2).await?;
let metrics = MetricsClient::new(
MetricsConfig::in_memory(
"test",
"codex-skills-extension",
env!("CARGO_PKG_VERSION"),
InMemoryMetricExporter::default(),
)
.with_runtime_reader(),
)?;
let mut builder = ExtensionRegistryBuilder::new();
install_with_providers_and_metrics(
&mut builder,
SkillProviders::new(),
Some(metrics.clone()),
SkillsExtensionConfig::clone,
);
let registry = builder.build();
let config = SkillsExtensionConfig {
include_instructions: false,
catalog_deltas_enabled: false,
omit_descriptions: false,
max_context_tokens: None,
bundled_skills_enabled: false,
cloud_skill_enabled: false,
shadow_selection_enabled: true,
};
let session_store = ExtensionData::new("session");
let thread_store = ExtensionData::new("thread");
registry.thread_lifecycle_contributors()[0]
.on_thread_start(ThreadStartInput {
config: &config,
session_source: &SessionSource::Cli,
persistent_thread_state_available: true,
environments: &[],
mcp_resource_client: None,
extension_metrics: None,
session_store: &session_store,
thread_store: &thread_store,
})
.await;
for turn_id in ["first", "second"] {
let turn_store = ExtensionData::new(turn_id);
let host_catalog = SkillCatalog {
is_partial: false,
entries: ["x", "hidden", "selected"]
.into_iter()
.map(|name| {
let mut entry = SkillCatalogEntry::new(
SkillPackageId(name.to_string()),
SkillAuthority::new(SkillSourceKind::Host, "host"),
name,
"zzzz",
SkillResourceId::new(format!("{name}/SKILL.md")),
);
entry.prompt_visible = name != "hidden";
entry
})
.collect(),
warnings: Vec::new(),
};
turn_store.insert(SkillsStepState {
discovery_v2: false,
tools_enabled: false,
catalog: thread_store
.get::<SkillsThreadState>()
.unwrap()
.prepare_step_catalog(
/*cloud*/ None,
SkillCatalog::default(),
/*discovery_v2*/ false,
),
host_catalog: Some(host_catalog),
cloud_status: CatalogStatus::Unavailable,
config: config.clone(),
});
let fragments = tokio::time::timeout(
Duration::from_secs(10),
registry.turn_input_contributors()[0].contribute(
TurnInputContext {
step_store: &turn_store,
turn_id: turn_id.to_string(),
user_input: vec![UserInput::Skill {
name: "selected".to_string(),
path: "selected/SKILL.md".into(),
}],
environments: Vec::new(),
},
/*extension_metrics*/ None,
&session_store,
&thread_store,
&turn_store,
),
)
.await?;
assert!(fragments.is_empty());
tokio::task::yield_now().await;
// Synchronous ranking would emit run metrics despite the occupied budget;
// awaiting admission in contribute would instead time out above.
assert!(
metrics
.snapshot()?
.scope_metrics()
.all(|scope| { scope.metrics().all(|metric| metric.name() != RUN_METRIC) })
);
for resource in [
"x/SKILL.md",
"x\\SKILL.md",
"hidden/SKILL.md",
"selected/SKILL.md",
] {
registry.skill_invocation_contributors()[0]
.on_skill_invocation(SkillInvocationInput {
session_store: &session_store,
thread_store: &thread_store,
turn_store: &turn_store,
turn_id,
skill_resource: resource,
kind: SkillInvocationKind::Implicit,
})
.await;
}
assert_eq!(
vec!["x/SKILL.md"],
thread_store
.get::<SkillsThreadState>()
.unwrap()
.recent_skill_invocations
.snapshot()
);
}
// Both observers disappear before either ranking starts. Their queued unique
// invocations must still be scored against their own turn-start histories.
drop(thread_store);
drop(slots);
let mut runs = BTreeMap::new();
let mut hits = BTreeMap::new();
tokio::time::timeout(Duration::from_secs(10), async {
loop {
// snapshot() exports deltas, so retain observations across polls.
let snapshot = metrics.snapshot().unwrap();
for metric in snapshot.scope_metrics().flat_map(ScopeMetrics::metrics) {
let AggregatedMetrics::U64(MetricData::Sum(sum)) = metric.data() else {
continue;
};
for point in sum.data_points() {
let attribute = |key: &str| {
point
.attributes()
.find(|attribute| attribute.key.as_str() == key)
.unwrap()
.value
.as_str()
.to_string()
};
match metric.name() {
RUN_METRIC => {
*runs.entry(attribute("method")).or_insert(0) += point.value()
}
"codex.skills.shadow_selection.invocation" => {
assert_eq!("ascii_latin", attribute("query_script"));
*hits
.entry((attribute("method"), attribute("hit"), attribute("rank")))
.or_insert(0) += point.value();
}
_ => {}
}
}
}
if hits.values().sum::<u64>() >= 24 {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await?;
let mut expected_runs = BTreeMap::new();
let mut expected_hits = BTreeMap::new();
for (method, uses_history) in [
("weighted_lexical_v1", false),
("fielded_bm25_v1", false),
("character_ngram_v1", false),
("multi_query_lexical_v1", false),
("rrf_lexical_char_v1", false),
("routing_card_exact_v1", false),
("character_routing_card_v1", false),
("lru_v1", true),
("lru_plus_lexical_v1", true),
("lru_plus_character_routing_v1", true),
("lru_plus_lexical_character_routing_v1", true),
("task_context_fusion_v1", true),
] {
expected_runs.insert(method.to_string(), 2);
expected_hits.insert(
(method.to_string(), "false".to_string(), "miss".to_string()),
if uses_history { 1 } else { 2 },
);
if uses_history {
expected_hits.insert((method.to_string(), "true".to_string(), "1".to_string()), 1);
}
}
assert_eq!(expected_runs, runs);
assert_eq!(expected_hits, hits);
Ok(())
}
/// Hold an actual blocking worker until the test releases it. The timeout keeps a
/// failing assertion from leaving runtime shutdown stuck on the test worker.
struct BlockedSelector {
started: tokio::sync::mpsc::UnboundedSender<()>,
release: Mutex<std::sync::mpsc::Receiver<()>>,
}
impl CheapSkillSelector for BlockedSelector {
fn method(&self) -> &'static str {
"blocked_test"
}
fn select(
&self,
_query: &str,
_documents: &[SkillSelectionDocument<'_>],
_limit: usize,
) -> CheapSkillSelection {
self.started.send(()).unwrap();
self.release
.lock()
.unwrap()
.recv_timeout(Duration::from_secs(10))
.unwrap();
CheapSkillSelection::default()
}
}
#[tokio::test]
async fn ranking_budget_is_shared_and_held_until_blocking_work_finishes() {
let _serial = RANKING_TESTS.acquire().await.unwrap();
let mut workers = Vec::new();
for index in 0..3 {
let (started, mut starts) = tokio::sync::mpsc::unbounded_channel();
let (release, releases) = std::sync::mpsc::channel();
// Separate experiment instances must share the same process-wide budget.
let experiment = Arc::new(ShadowSelectionExperiment {
selectors: vec![Box::new(BlockedSelector {
started,
release: Mutex::new(releases),
})],
metrics_client: None,
});
let query = ShadowQuery {
text: "test".to_string(),
truncated: false,
};
let input = ShadowSelectionInput {
catalog: SkillCatalog::default(),
host_snapshot: None,
task_snapshot: TaskContextSnapshot {
query: query.clone(),
recent_skills: Vec::new(),
},
query,
eligible_ids: HashSet::new(),
recent_skill_resources: Vec::new(),
};
let (invocations, pending) = tokio::sync::mpsc::unbounded_channel();
drop(invocations);
let mut worker = Box::pin(experiment.evaluate(input, pending, tracing::Span::none()));
// Polling to the first await deterministically attempts admission.
assert!(futures::poll!(worker.as_mut()).is_pending());
if index < 2 {
assert_eq!(
Some(()),
tokio::time::timeout(Duration::from_secs(10), starts.recv())
.await
.unwrap()
);
assert_eq!(1 - index, RANKING_SLOTS.available_permits());
} else {
assert!(starts.try_recv().is_err());
}
workers.push((tokio::spawn(worker), release, starts));
}
let (first, release_first, _) = workers.remove(0);
release_first.send(()).unwrap();
first.await.unwrap();
let (second, release_second, _) = workers.remove(0);
let (third, release_third, mut third_starts) = workers.remove(0);
assert_eq!(
Some(()),
tokio::time::timeout(Duration::from_secs(10), third_starts.recv())
.await
.unwrap()
);
assert_eq!(0, RANKING_SLOTS.available_permits());
// Cancelling evaluation cannot free a slot still occupied by blocking work.
third.abort();
assert!(third.await.unwrap_err().is_cancelled());
assert_eq!(0, RANKING_SLOTS.available_permits());
release_second.send(()).unwrap();
release_third.send(()).unwrap();
second.await.unwrap();
let _all_returned =
tokio::time::timeout(Duration::from_secs(10), RANKING_SLOTS.acquire_many(2))
.await
.unwrap()
.unwrap();
}

View File

@@ -0,0 +1,616 @@
//! Shadow-only skill ranking. Capture turn inputs before recording new relevance signals,
//! then evaluate on a blocking worker without delaying model input construction.
//! This experiment is temporary and should be removed after evaluation.
mod task_context;
use task_context::TaskContextSnapshot;
pub(crate) use task_context::ShadowTaskContext;
use std::collections::HashMap;
use std::collections::HashSet;
use std::collections::VecDeque;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::PoisonError;
use std::time::Duration;
use std::time::Instant;
use crate::HostSkillsSnapshot;
use codex_extension_api::TurnInputContext;
use codex_otel::MetricsClient;
use codex_protocol::user_input::UserInput;
use tokio::sync::Semaphore;
use crate::catalog::SkillCatalog;
use crate::catalog::SkillCatalogEntry;
use crate::catalog::SkillSourceKind;
use crate::dynamic_skill_selector::CharacterNgramSkillSelector;
use crate::dynamic_skill_selector::CharacterRoutingCardSkillSelector;
use crate::dynamic_skill_selector::CheapSkillSelection;
use crate::dynamic_skill_selector::CheapSkillSelector;
use crate::dynamic_skill_selector::FieldedBm25SkillSelector;
use crate::dynamic_skill_selector::LruPlusCharacterRoutingSkillSelector;
use crate::dynamic_skill_selector::LruPlusLexicalCharacterRoutingSkillSelector;
use crate::dynamic_skill_selector::LruPlusLexicalSkillSelector;
use crate::dynamic_skill_selector::LruSkillSelector;
use crate::dynamic_skill_selector::MultiQueryLexicalSkillSelector;
use crate::dynamic_skill_selector::RoutingCardLexicalSkillSelector;
use crate::dynamic_skill_selector::RrfLexicalCharSkillSelector;
use crate::dynamic_skill_selector::SkillSelectionDocument;
use crate::dynamic_skill_selector::WeightedLexicalSkillSelector;
const MAX_SHADOW_QUERY_BYTES: usize = 16 * 1024;
const MAX_SHADOW_RESULTS: usize = 50;
// Share the CPU budget across threads and extension registries. Admission happens
// only in the background; turn preparation never waits for a ranking slot.
static RANKING_SLOTS: Semaphore = Semaphore::const_new(2);
const RUN_METRIC: &str = "codex.skills.shadow_selection";
const DURATION_METRIC: &str = "codex.skills.shadow_selection.duration_ms";
const CATALOG_ENTRY_COUNT_METRIC: &str = "codex.skills.shadow_selection.catalog_entries";
const SELECTED_ENTRY_COUNT_METRIC: &str = "codex.skills.shadow_selection.selected_entries";
const QUERY_TERM_COUNT_METRIC: &str = "codex.skills.shadow_selection.query_terms";
const REDUCTION_BPS_METRIC: &str = "codex.skills.shadow_selection.reduction_bps";
pub(crate) struct ShadowSelectionExperiment {
selectors: Vec<Box<dyn CheapSkillSelector>>,
metrics_client: Option<MetricsClient>,
}
impl ShadowSelectionExperiment {
pub(crate) fn new(metrics_client: Option<MetricsClient>) -> Self {
Self {
selectors: vec![
Box::new(WeightedLexicalSkillSelector),
Box::new(FieldedBm25SkillSelector),
Box::new(CharacterNgramSkillSelector),
Box::new(MultiQueryLexicalSkillSelector),
Box::new(RrfLexicalCharSkillSelector),
Box::new(RoutingCardLexicalSkillSelector),
],
metrics_client,
}
}
/// Freeze prediction inputs before this turn can contribute new invocation history.
/// The returned state observes invocations even while its rankings are still pending.
pub(crate) fn start(
self: &Arc<Self>,
input: &TurnInputContext<'_>,
catalog: SkillCatalog,
explicitly_selected: &[SkillCatalogEntry],
host_snapshot: Option<Arc<HostSkillsSnapshot>>,
recent_skill_invocations: Arc<RecentSkillInvocations>,
task_context: Arc<ShadowTaskContext>,
) -> ShadowSelectionTurnState {
let query = build_shadow_query(&input.user_input);
let task_snapshot = task_context.begin_turn(&input.turn_id, &query, &input.user_input);
let recent_skill_resources = recent_skill_invocations.snapshot();
let explicitly_selected_skill_resources = explicitly_selected
.iter()
.map(|entry| normalize_skill_resource(entry.main_prompt.as_str()))
.collect::<HashSet<_>>();
let mut eligible_ids = HashSet::new();
let mut eligible_skill_resources = HashSet::new();
for (id, entry) in catalog.entries.iter().enumerate() {
// Invocation observation covers host shell use and reads of Cloud-primary skills.
if !entry.is_model_visible()
|| !matches!(
&entry.authority.kind,
SkillSourceKind::Host | SkillSourceKind::Cloud
)
{
continue;
}
let resource = normalize_skill_resource(entry.main_prompt.as_str());
if !explicitly_selected_skill_resources.contains(&resource) {
eligible_ids.insert(id);
eligible_skill_resources.insert(resource);
}
}
let (invocations, pending_invocations) = tokio::sync::mpsc::unbounded_channel();
let state = ShadowSelectionTurnState {
turn_id: input.turn_id.clone(),
eligible_skill_resources,
seen_skill_resources: Mutex::new(HashSet::new()),
recent_skill_invocations,
task_context: Arc::clone(&task_context),
invocations,
};
// Explicit intent is a relevance signal even if the subsequent prompt read fails.
// It can update future turns now that this turn's prediction inputs are frozen.
for entry in explicitly_selected.iter().filter(|entry| {
entry.is_model_visible()
&& matches!(
&entry.authority.kind,
SkillSourceKind::Host | SkillSourceKind::Cloud
)
}) {
task_context.record(
&input.turn_id,
normalize_skill_resource(entry.main_prompt.as_str()),
);
}
let selection_input = ShadowSelectionInput {
catalog,
host_snapshot,
query,
eligible_ids,
recent_skill_resources,
task_snapshot,
};
tokio::spawn(Arc::clone(self).evaluate(
selection_input,
pending_invocations,
tracing::Span::current(),
));
state
}
/// Own the rankings and drain observations for this turn, including those queued
/// during ranking. Dropping the turn's observer closes the channel after its last read.
async fn evaluate(
self: Arc<Self>,
input: ShadowSelectionInput,
mut invocations: tokio::sync::mpsc::UnboundedReceiver<String>,
parent: tracing::Span,
) {
let query_script = query_script_tag(&input.query.text);
let experiment = Arc::clone(&self);
let Ok(permit) = RANKING_SLOTS.acquire().await else {
return;
};
let ranked_selections = match tokio::task::spawn_blocking(move || {
// A cancelled async task must not release capacity while its blocking
// worker is still running. Release it before waiting for invocations.
let _permit = permit;
experiment.rank(input, parent)
})
.await
{
Ok(rankings) => rankings,
Err(error) => {
tracing::warn!(%error, "shadow skill selection failed");
return;
}
};
let Some(metrics_client) = self.metrics_client.as_ref() else {
return;
};
while let Some(skill_resource) = invocations.recv().await {
for selection in &ranked_selections {
let rank = selection
.skill_resources
.iter()
.position(|candidate| candidate == &skill_resource)
.map(|index| index + 1);
let tags = [
("method", selection.method),
("hit", bool_tag(rank.is_some())),
("rank", rank_bucket(rank)),
("query_script", query_script),
];
let _ = metrics_client.counter(
"codex.skills.shadow_selection.invocation",
/*inc*/ 1,
&tags,
);
}
}
}
#[tracing::instrument(
name = "skills.shadow_selection.rank",
level = "info",
parent = &parent,
skip_all,
fields(catalog_entries = input.eligible_ids.len())
)]
fn rank(&self, input: ShadowSelectionInput, parent: tracing::Span) -> Vec<RankedSelection> {
let ShadowSelectionInput {
catalog,
host_snapshot,
query,
eligible_ids,
recent_skill_resources,
task_snapshot,
} = input;
let documents = catalog
.entries
.iter()
.enumerate()
.filter(|(id, _)| eligible_ids.contains(id))
.map(|(id, entry)| SkillSelectionDocument {
id,
name: entry.name.as_str(),
short_description: entry.short_description.as_deref(),
description: entry.description.as_str(),
dependencies: entry.dependencies.as_ref(),
})
.collect::<Vec<_>>();
let eligible_skill_ids_by_resource = documents
.iter()
.map(|document| {
(
normalize_skill_resource(catalog.entries[document.id].main_prompt.as_str()),
document.id,
)
})
.collect::<HashMap<_, _>>();
let recent_skill_ids = recent_skill_resources
.iter()
.filter_map(|resource| eligible_skill_ids_by_resource.get(resource).copied())
.collect();
let routing_selector =
CharacterRoutingCardSkillSelector::new(&catalog, host_snapshot.as_deref());
let lru_selector = LruSkillSelector::new(recent_skill_ids);
let lru_plus_lexical_selector = LruPlusLexicalSkillSelector::new(lru_selector.clone());
let lru_plus_character_selector = LruPlusCharacterRoutingSkillSelector::new(
lru_selector.clone(),
routing_selector.clone(),
);
let lru_plus_lexical_character_selector = LruPlusLexicalCharacterRoutingSkillSelector::new(
lru_selector.clone(),
routing_selector.clone(),
);
let task_selector = LruPlusLexicalCharacterRoutingSkillSelector::new(
LruSkillSelector::new(
task_snapshot
.recent_skills
.iter()
.filter_map(|resource| eligible_skill_ids_by_resource.get(resource).copied())
.collect(),
),
routing_selector.clone(),
);
let mut ranked_selections = Vec::with_capacity(self.selectors.len() + 6);
for (method, selector, query) in self
.selectors
.iter()
.map(std::convert::AsRef::as_ref)
.chain([
&routing_selector as &dyn CheapSkillSelector,
&lru_selector as &dyn CheapSkillSelector,
&lru_plus_lexical_selector as &dyn CheapSkillSelector,
&lru_plus_character_selector as &dyn CheapSkillSelector,
&lru_plus_lexical_character_selector as &dyn CheapSkillSelector,
])
.map(|selector| (selector.method(), selector, &query))
.chain([(
"task_context_fusion_v1",
&task_selector as &dyn CheapSkillSelector,
&task_snapshot.query,
)])
{
let query_script = query_script_tag(&query.text);
let start = Instant::now();
let selection =
selector.select(&query.text, &documents, /*limit*/ MAX_SHADOW_RESULTS);
let duration = start.elapsed();
let selected_ids = sanitize_selected_ids(&selection, &eligible_ids);
self.record_metrics(ShadowSelectionObservation {
method,
selection: &selection,
query_truncated_before_selection: query.truncated,
query_script,
catalog_entry_count: documents.len(),
selected_entry_count: selected_ids.len(),
duration,
});
ranked_selections.push(RankedSelection {
method,
skill_resources: selected_ids
.iter()
.map(|id| normalize_skill_resource(catalog.entries[*id].main_prompt.as_str()))
.collect(),
});
tracing::debug!(
method,
catalog_entries = documents.len(),
selected_entries = selected_ids.len(),
query_terms = selection.query_term_count,
query_script,
query_truncated = query.truncated || selection.query_truncated,
candidate_set_truncated = selection.candidate_set_truncated,
"ran shadow skill selection"
);
}
ranked_selections
}
fn record_metrics(&self, observation: ShadowSelectionObservation<'_>) {
let Some(metrics_client) = self.metrics_client.as_ref() else {
return;
};
let ShadowSelectionObservation {
method,
selection,
query_truncated_before_selection,
query_script,
catalog_entry_count,
selected_entry_count,
duration,
} = observation;
let status = selection_status(selection, selected_entry_count);
let query_truncated =
bool_tag(query_truncated_before_selection || selection.query_truncated);
let candidate_set_truncated = bool_tag(selection.candidate_set_truncated);
let tags = [
("method", method),
("status", status),
("query_script", query_script),
("query_truncated", query_truncated),
("candidate_set_truncated", candidate_set_truncated),
];
let _ = metrics_client.counter(RUN_METRIC, /*inc*/ 1, &tags);
let _ = metrics_client.record_duration(DURATION_METRIC, duration, &tags);
let _ = metrics_client.histogram(
CATALOG_ENTRY_COUNT_METRIC,
metric_value(catalog_entry_count),
&tags,
);
let _ = metrics_client.histogram(
SELECTED_ENTRY_COUNT_METRIC,
metric_value(selected_entry_count),
&tags,
);
let _ = metrics_client.histogram(
QUERY_TERM_COUNT_METRIC,
metric_value(selection.query_term_count),
&tags,
);
let _ = metrics_client.histogram(
REDUCTION_BPS_METRIC,
reduction_bps(catalog_entry_count, selected_entry_count),
&tags,
);
}
}
pub(crate) struct ShadowSelectionTurnState {
turn_id: String,
eligible_skill_resources: HashSet<String>,
seen_skill_resources: Mutex<HashSet<String>>,
recent_skill_invocations: Arc<RecentSkillInvocations>,
task_context: Arc<ShadowTaskContext>,
invocations: tokio::sync::mpsc::UnboundedSender<String>,
}
impl ShadowSelectionTurnState {
/// Advance relevance history immediately; scoring can wait for the frozen rankings.
pub(crate) fn record_invocation(&self, skill_resource: &str) {
let skill_resource = normalize_skill_resource(skill_resource);
if !self.eligible_skill_resources.contains(&skill_resource)
|| !self
.seen_skill_resources
.lock()
.unwrap_or_else(PoisonError::into_inner)
.insert(skill_resource.clone())
{
return;
}
self.recent_skill_invocations.record(skill_resource.clone());
self.task_context
.record(&self.turn_id, skill_resource.clone());
let _ = self.invocations.send(skill_resource);
}
}
/// Owned turn-start inputs; workers never read the evolving relevance histories.
struct ShadowSelectionInput {
catalog: SkillCatalog,
host_snapshot: Option<Arc<HostSkillsSnapshot>>,
query: ShadowQuery,
eligible_ids: HashSet<usize>,
recent_skill_resources: Vec<String>,
task_snapshot: TaskContextSnapshot,
}
#[derive(Default)]
pub(crate) struct RecentSkillInvocations {
skill_resources: Mutex<VecDeque<String>>,
}
impl RecentSkillInvocations {
fn snapshot(&self) -> Vec<String> {
self.skill_resources
.lock()
.unwrap_or_else(PoisonError::into_inner)
.iter()
.cloned()
.collect()
}
fn record(&self, skill_resource: String) {
let mut skill_resources = self
.skill_resources
.lock()
.unwrap_or_else(PoisonError::into_inner);
if let Some(index) = skill_resources
.iter()
.position(|resource| resource == &skill_resource)
{
skill_resources.remove(index);
}
skill_resources.push_front(skill_resource);
skill_resources.truncate(MAX_SHADOW_RESULTS);
}
}
struct RankedSelection {
method: &'static str,
skill_resources: Vec<String>,
}
struct ShadowSelectionObservation<'a> {
method: &'static str,
selection: &'a CheapSkillSelection,
query_truncated_before_selection: bool,
query_script: &'static str,
catalog_entry_count: usize,
selected_entry_count: usize,
duration: Duration,
}
fn sanitize_selected_ids(
selection: &CheapSkillSelection,
eligible_ids: &HashSet<usize>,
) -> Vec<usize> {
let mut seen = HashSet::new();
selection
.candidate_ids
.iter()
.copied()
.filter(|id| eligible_ids.contains(id) && seen.insert(*id))
.take(MAX_SHADOW_RESULTS)
.collect()
}
fn selection_status(selection: &CheapSkillSelection, selected_entry_count: usize) -> &'static str {
if selected_entry_count > 0 {
"selected"
} else if selection.query_term_count == 0 {
"no_query_terms"
} else {
"no_matches"
}
}
fn reduction_bps(catalog_entry_count: usize, selected_entry_count: usize) -> i64 {
if catalog_entry_count == 0 {
return 0;
}
10_000i64.saturating_sub(ratio_bps(selected_entry_count, catalog_entry_count))
}
fn ratio_bps(numerator: usize, denominator: usize) -> i64 {
if denominator == 0 {
return 0;
}
let numerator = u128::try_from(numerator).unwrap_or(u128::MAX);
let denominator = u128::try_from(denominator).unwrap_or(u128::MAX);
let basis_points = numerator.saturating_mul(10_000) / denominator;
i64::try_from(basis_points).unwrap_or(i64::MAX)
}
fn metric_value(value: usize) -> i64 {
i64::try_from(value).unwrap_or(i64::MAX)
}
fn bool_tag(value: bool) -> &'static str {
if value { "true" } else { "false" }
}
fn rank_bucket(rank: Option<usize>) -> &'static str {
match rank {
Some(1) => "1",
Some(2..=5) => "2_5",
Some(6..=10) => "6_10",
Some(11..=20) => "11_20",
Some(21..=MAX_SHADOW_RESULTS) => "21_50",
Some(_) | None => "miss",
}
}
fn normalize_skill_resource(skill_resource: &str) -> String {
skill_resource.replace('\\', "/")
}
fn query_script_tag(query: &str) -> &'static str {
let mut has_ascii_latin = false;
let mut has_cjk = false;
let mut has_other = false;
for character in query.chars().filter(|character| character.is_alphabetic()) {
if character.is_ascii_alphabetic() {
has_ascii_latin = true;
} else if is_cjk(character) {
has_cjk = true;
} else {
has_other = true;
}
}
match (has_ascii_latin, has_cjk, has_other) {
(false, false, false) => "none",
(true, false, false) => "ascii_latin",
(false, true, false) => "cjk",
(false, false, true) => "other",
(true, true, false) | (true, false, true) | (false, true, true) | (true, true, true) => {
"mixed"
}
}
}
fn is_cjk(character: char) -> bool {
matches!(
character,
'\u{1100}'..='\u{11ff}'
| '\u{3040}'..='\u{30ff}'
| '\u{3100}'..='\u{312f}'
| '\u{3130}'..='\u{318f}'
| '\u{31a0}'..='\u{31bf}'
| '\u{31f0}'..='\u{31ff}'
| '\u{3400}'..='\u{4dbf}'
| '\u{4e00}'..='\u{9fff}'
| '\u{a960}'..='\u{a97f}'
| '\u{ac00}'..='\u{d7af}'
| '\u{d7b0}'..='\u{d7ff}'
| '\u{f900}'..='\u{faff}'
| '\u{20000}'..='\u{2fa1f}'
)
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct ShadowQuery {
text: String,
truncated: bool,
}
fn build_shadow_query(inputs: &[UserInput]) -> ShadowQuery {
let mut text = String::new();
let mut truncated = false;
for input in inputs {
let part = match input {
UserInput::Text { text, .. } => text.as_str(),
UserInput::Skill { name, .. } | UserInput::Mention { name, .. } => name.as_str(),
_ => continue,
};
if part.is_empty() {
continue;
}
if !text.is_empty() && !push_bounded(&mut text, " ") {
truncated = true;
break;
}
if !push_bounded(&mut text, part) {
truncated = true;
break;
}
}
ShadowQuery { text, truncated }
}
fn push_bounded(destination: &mut String, value: &str) -> bool {
let remaining = MAX_SHADOW_QUERY_BYTES.saturating_sub(destination.len());
if value.len() <= remaining {
destination.push_str(value);
return true;
}
let mut end = remaining;
while !value.is_char_boundary(end) {
end = end.saturating_sub(1);
}
destination.push_str(&value[..end]);
false
}
#[cfg(test)]
#[path = "experiment_tests.rs"]
mod tests;

View File

@@ -0,0 +1,155 @@
use std::collections::VecDeque;
use std::sync::Mutex;
use std::sync::PoisonError;
use codex_protocol::user_input::UserInput;
use codex_utils_string::take_bytes_at_char_boundary;
use super::ShadowQuery;
const MAX_PRIOR_REQUESTS: usize = 2;
const MAX_REQUEST_BYTES: usize = 2 * 1024;
const MAX_QUERY_BYTES: usize = 4 * 1024;
const MAX_RECENT_SKILLS: usize = 50;
/// Shadow-only relevance history. New and reconstructed thread runtimes start cold.
#[derive(Default)]
pub(crate) struct ShadowTaskContext(Mutex<TaskContextState>);
#[derive(Default)]
struct TaskContextState {
prior_requests: VecDeque<ShadowQuery>,
recent_skills: VecDeque<String>,
pending: Option<PendingTurn>,
}
struct PendingTurn {
id: String,
request: Option<ShadowQuery>,
recent_skills: VecDeque<String>,
}
#[derive(Debug, PartialEq, Eq)]
pub(super) struct TaskContextSnapshot {
pub(super) query: ShadowQuery,
pub(super) recent_skills: Vec<String>,
}
impl ShadowTaskContext {
pub(super) fn begin_turn(
&self,
turn_id: &str,
current: &ShadowQuery,
inputs: &[UserInput],
) -> TaskContextSnapshot {
let mut state = self.0.lock().unwrap_or_else(PoisonError::into_inner);
if state.pending.as_ref().is_none_or(|turn| turn.id != turn_id) {
if let Some(previous) = state.pending.take() {
if let Some(request) = previous.request {
state
.prior_requests
.retain(|prior| prior.text != request.text);
state.prior_requests.push_front(request);
state.prior_requests.truncate(MAX_PRIOR_REQUESTS);
}
for resource in previous.recent_skills.into_iter().rev() {
remember_skill(&mut state.recent_skills, resource);
}
}
state.pending = Some(PendingTurn {
id: turn_id.to_string(),
request: None,
recent_skills: VecDeque::new(),
});
}
let retained = take_bytes_at_char_boundary(&current.text, MAX_REQUEST_BYTES);
let text = take_bytes_at_char_boundary(&current.text, MAX_QUERY_BYTES);
let mut query = ShadowQuery {
text: text.to_string(),
truncated: current.truncated || text.len() < current.text.len(),
};
for prior in &state.prior_requests {
if prior.text == retained {
continue;
}
if !query.text.is_empty() && query.text.len() < MAX_QUERY_BYTES {
query.text.push('\n');
}
let part = take_bytes_at_char_boundary(
&prior.text,
MAX_QUERY_BYTES.saturating_sub(query.text.len()),
);
query.text.push_str(part);
query.truncated |= prior.truncated || part.len() < prior.text.len();
if part.len() < prior.text.len() {
break;
}
}
let recent_skills = state.recent_skills.iter().cloned().collect();
if is_substantive(&current.text, inputs)
&& let Some(pending) = state.pending.as_mut()
{
pending.request = Some(ShadowQuery {
text: retained.to_string(),
truncated: current.truncated || retained.len() < current.text.len(),
});
}
TaskContextSnapshot {
query,
recent_skills,
}
}
/// Records relevance evidence for future turns, never the active turn's predictions.
pub(super) fn record(&self, turn_id: &str, resource: String) {
let mut state = self.0.lock().unwrap_or_else(PoisonError::into_inner);
if let Some(pending) = state.pending.as_mut().filter(|turn| turn.id == turn_id) {
remember_skill(&mut pending.recent_skills, resource);
}
}
}
fn remember_skill(skills: &mut VecDeque<String>, resource: String) {
skills.retain(|previous| previous != &resource);
skills.push_front(resource);
skills.truncate(MAX_RECENT_SKILLS);
}
fn is_substantive(text: &str, inputs: &[UserInput]) -> bool {
if inputs.iter().any(|input| {
matches!(input, UserInput::Skill { name, .. } | UserInput::Mention { name, .. } if !name.trim().is_empty())
}) {
return true;
}
let normalized = text
.split(|character: char| !character.is_alphanumeric())
.filter(|part| !part.is_empty())
.map(str::to_lowercase)
.collect::<Vec<_>>()
.join(" ");
!matches!(
normalized.as_str(),
"" | "yes"
| "yep"
| "yeah"
| "ok"
| "okay"
| "sure"
| "go"
| "go ahead"
| "continue"
| "please continue"
| "proceed"
| "do it"
| "do that"
| "try again"
| "retry"
| "thanks"
| "thank you"
)
}
#[cfg(test)]
#[path = "task_context_tests.rs"]
mod tests;

View File

@@ -0,0 +1,112 @@
use pretty_assertions::assert_eq;
use super::*;
fn query(text: &str) -> ShadowQuery {
ShadowQuery {
text: text.to_string(),
truncated: false,
}
}
fn begin(context: &ShadowTaskContext, turn_id: &str, text: &str) -> TaskContextSnapshot {
context.begin_turn(turn_id, &query(text), &[])
}
#[test]
fn prior_requests_survive_continuations_and_keep_short_substantive_input() {
let context = ShadowTaskContext::default();
begin(&context, "1", "Fix lint errors.");
assert_eq!(
query("continue\nFix lint errors."),
begin(&context, "2", "continue").query
);
begin(&context, "3", "OK!!!");
begin(&context, "4", "deploy");
begin(&context, "5", "修复测试");
assert_eq!(
query("continue\n修复测试\ndeploy"),
begin(&context, "6", "continue").query
);
assert_eq!(
query("deploy\n修复测试"),
begin(&context, "7", "deploy").query
);
assert!(is_substantive(
"go",
&[UserInput::Mention {
name: "go".to_string(),
path: "skill://go".to_string(),
}]
));
}
#[test]
fn current_turn_observations_are_pending_and_late_observations_are_ignored() {
let context = ShadowTaskContext::default();
begin(&context, "1", "continue");
context.record("1", "a".to_string());
assert_eq!(
Vec::<String>::new(),
begin(&context, "1", "continue").recent_skills
);
assert_eq!(vec!["a"], begin(&context, "2", "continue").recent_skills);
context.record("1", "late".to_string());
context.record("2", "a".to_string());
context.record("2", "b".to_string());
assert_eq!(vec!["a"], begin(&context, "2", "continue").recent_skills);
assert_eq!(
TaskContextSnapshot {
query: query("continue"),
recent_skills: vec!["b".to_string(), "a".to_string()],
},
begin(&context, "3", "continue")
);
assert_eq!(
TaskContextSnapshot {
query: query("continue"),
recent_skills: Vec::new(),
},
begin(&ShadowTaskContext::default(), "3", "continue")
);
}
#[test]
fn history_and_augmented_query_are_bounded_at_utf8_boundaries() {
let context = ShadowTaskContext::default();
let first = "界".repeat(MAX_REQUEST_BYTES);
let initial = begin(&context, "1", &first);
assert_eq!(
ShadowQuery {
text: take_bytes_at_char_boundary(&first, MAX_QUERY_BYTES).to_string(),
truncated: true,
},
initial.query
);
for index in 0..=MAX_RECENT_SKILLS {
context.record("1", format!("skill-{index}"));
}
begin(&context, "2", &"é".repeat(MAX_REQUEST_BYTES));
context.record("2", "skill-1".to_string());
let expected = format!(
"continue\n{}\n{}",
"é".repeat(MAX_REQUEST_BYTES / 2),
take_bytes_at_char_boundary(&first, MAX_REQUEST_BYTES)
);
assert_eq!(
TaskContextSnapshot {
query: ShadowQuery {
text: take_bytes_at_char_boundary(&expected, MAX_QUERY_BYTES).to_string(),
truncated: true,
},
recent_skills: std::iter::once("skill-1".to_string())
.chain(
(2..=MAX_RECENT_SKILLS)
.rev()
.map(|index| format!("skill-{index}"))
)
.collect(),
},
begin(&context, "3", "continue")
);
}

View File

@@ -0,0 +1,247 @@
use std::fmt;
use std::sync::Arc;
use crate::catalog::SkillCatalog;
use crate::catalog::SkillProviderError;
use crate::catalog::SkillProviderResult;
use crate::catalog::SkillReadResult;
use crate::catalog::SkillSearchResult;
use crate::catalog::SkillSourceKind;
use crate::provider::SkillListQuery;
use crate::provider::SkillProvider;
use crate::provider::SkillReadRequest;
use crate::provider::SkillSearchRequest;
#[derive(Clone)]
pub struct SkillProviderSource {
kind: SkillSourceKind,
label: String,
provider: Arc<dyn SkillProvider>,
}
impl SkillProviderSource {
pub fn new(
kind: SkillSourceKind,
label: impl Into<String>,
provider: Arc<dyn SkillProvider>,
) -> Self {
Self {
kind,
label: label.into(),
provider,
}
}
pub fn host(label: impl Into<String>, provider: Arc<dyn SkillProvider>) -> Self {
Self::new(SkillSourceKind::Host, label, provider)
}
pub fn executor(label: impl Into<String>, provider: Arc<dyn SkillProvider>) -> Self {
Self::new(SkillSourceKind::Executor, label, provider)
}
pub fn cloud(label: impl Into<String>, provider: Arc<dyn SkillProvider>) -> Self {
Self::new(SkillSourceKind::Cloud, label, provider)
}
fn should_list(&self, query: &SkillListQuery<'_>) -> bool {
match &self.kind {
SkillSourceKind::Host => query.include_host_skills,
SkillSourceKind::Executor => {
query.executor_capability_discovery_v2.is_some() || !query.executor_roots.is_empty()
}
SkillSourceKind::Cloud => query.include_cloud_skills,
SkillSourceKind::Custom(_) => true,
}
}
fn owns_kind(&self, kind: &SkillSourceKind) -> bool {
&self.kind == kind
}
}
impl fmt::Debug for SkillProviderSource {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("SkillProviderSource")
.field("kind", &self.kind)
.field("label", &self.label)
.finish()
}
}
#[derive(Clone, Default, Debug)]
pub struct SkillProviders {
sources: Vec<SkillProviderSource>,
}
impl SkillProviders {
pub fn new() -> Self {
Self::default()
}
pub fn with_provider(mut self, source: SkillProviderSource) -> Self {
self.sources.push(source);
self
}
pub fn with_host_provider(mut self, provider: Arc<dyn SkillProvider>) -> Self {
self.sources
.push(SkillProviderSource::host("host", provider));
self
}
pub fn with_executor_provider(mut self, provider: Arc<dyn SkillProvider>) -> Self {
self.sources
.push(SkillProviderSource::executor("executor", provider));
self
}
pub fn with_cloud_provider(mut self, provider: Arc<dyn SkillProvider>) -> Self {
self.sources
.push(SkillProviderSource::cloud("cloud", provider));
self
}
pub(crate) fn has_cloud_provider(&self) -> bool {
self.sources
.iter()
.any(|source| source.kind == SkillSourceKind::Cloud)
}
pub(crate) fn cloud_mcp_resources<'a>(
&self,
resources: Option<&'a codex_mcp::McpResourceClient>,
) -> Option<&'a codex_mcp::McpResourceClient> {
resources.filter(|_| {
self.sources.iter().any(|source| {
source.kind == SkillSourceKind::Cloud && source.provider.uses_mcp_resources()
})
})
}
pub(crate) fn has_host_provider(&self) -> bool {
self.sources
.iter()
.any(|source| source.kind == SkillSourceKind::Host)
}
pub(crate) async fn list_for_turn(&self, query: SkillListQuery<'_>) -> SkillCatalog {
self.list_matching(&query, |source| source.should_list(&query))
.await
}
pub(crate) async fn list_cloud_for_turn(
&self,
query: SkillListQuery<'_>,
) -> SkillProviderResult<SkillCatalog> {
let mut catalog = SkillCatalog::default();
for source in self
.sources
.iter()
.filter(|source| source.kind == SkillSourceKind::Cloud)
{
let source_catalog = source.provider.list(query.clone()).await.map_err(|err| {
SkillProviderError::new(format!(
"{} skills unavailable: {}",
source.label, err.message
))
})?;
catalog.extend(source_catalog);
}
Ok(catalog)
}
pub(crate) async fn list_executor_for_turn(&self, query: SkillListQuery<'_>) -> SkillCatalog {
self.list_matching(&query, |source| source.kind == SkillSourceKind::Executor)
.await
}
pub(crate) async fn list_host_for_turn(&self, query: SkillListQuery<'_>) -> SkillCatalog {
self.list_matching(&query, |source| source.kind == SkillSourceKind::Host)
.await
}
async fn list_matching(
&self,
query: &SkillListQuery<'_>,
should_list: impl Fn(&SkillProviderSource) -> bool,
) -> SkillCatalog {
let mut catalog = SkillCatalog::default();
for source in self.sources.iter().filter(|source| should_list(source)) {
extend_catalog(
&mut catalog,
source.provider.list(query.clone()).await,
source.label.as_str(),
);
}
catalog
}
pub(crate) async fn read(
&self,
request: SkillReadRequest<'_>,
) -> Result<SkillReadResult, SkillProviderError> {
let mut last_error = None;
for source in self
.sources
.iter()
.filter(|source| source.owns_kind(&request.authority.kind))
{
match source.provider.read(request.clone()).await {
Ok(result) => return Ok(result),
Err(err) => last_error = Some(err),
}
}
match last_error {
Some(err) => Err(err),
None => Err(SkillProviderError::new(format!(
"{} skill provider is not configured",
request.authority.kind
))),
}
}
pub async fn search(
&self,
request: SkillSearchRequest,
) -> Result<SkillSearchResult, SkillProviderError> {
let mut last_error = None;
for source in self
.sources
.iter()
.filter(|source| source.owns_kind(&request.authority.kind))
{
match source.provider.search(request.clone()).await {
Ok(result) => return Ok(result),
Err(err) => last_error = Some(err),
}
}
match last_error {
Some(err) => Err(err),
None => Err(SkillProviderError::new(format!(
"{} skill provider is not configured",
request.authority.kind
))),
}
}
}
fn extend_catalog(
catalog: &mut SkillCatalog,
result: Result<SkillCatalog, SkillProviderError>,
label: &str,
) {
match result {
Ok(source_catalog) => catalog.extend(source_catalog),
Err(err) => catalog
.warnings
.push(format!("{label} skills unavailable: {}", err.message)),
}
}

View File

@@ -0,0 +1,526 @@
//! Shared skill lifecycle state, including session resources and thread-owned caches.
//! Keeps discovery caches and live authorization checks separate from step preparation.
use std::collections::HashSet;
use std::sync::Arc;
use std::sync::Mutex;
use tokio::sync::Mutex as AsyncMutex;
use codex_exec_server::EnvironmentAccessKey;
use codex_extension_api::CatalogRefreshBackoff;
use codex_extension_api::ExtensionData;
use codex_extension_api::ExtensionMetrics;
use codex_mcp::McpResourceClient;
use codex_mcp::McpResourceClientAuthKey;
use crate::SkillsExtensionConfig;
use crate::aliases::SkillAliasState;
use crate::catalog::SkillAuthority;
use crate::catalog::SkillCatalog;
use crate::catalog::SkillPackageId;
use crate::catalog::SkillProviderError;
use crate::catalog::SkillProviderResult;
use crate::catalog::SkillReadResult;
use crate::catalog::SkillSourceKind;
use crate::catalog_observability::record_catalog;
use crate::catalog_state::CachedExecutorCatalog;
use crate::catalog_state::CachedExecutorDiscoveryCatalog;
use crate::catalog_state::CachedExecutorV2Catalog;
use crate::catalog_state::CloudResourceCache;
use crate::catalog_state::CloudSkillGeneration;
use crate::catalog_state::ExecutorCatalogCacheKey;
use crate::catalog_state::SkillCatalogState;
use crate::catalog_state::SkillReadCacheKey;
use crate::provider::SkillListQuery;
use crate::provider::SkillReadContext;
use crate::provider::SkillReadRequest;
use crate::shadow_selection_experiment::RecentSkillInvocations;
use crate::shadow_selection_experiment::ShadowSelectionTurnState;
use crate::shadow_selection_experiment::ShadowTaskContext;
use crate::sources::SkillProviders;
use crate::step_state::SkillStepCatalog;
#[cfg(test)]
#[path = "cloud_cache_tests.rs"]
mod cloud_cache_tests;
pub(crate) struct SkillsSessionState {
pub(crate) mcp_resources: Option<Arc<McpResourceClient>>,
pub(crate) extension_metrics: Option<Arc<dyn ExtensionMetrics>>,
}
/// Auth scope of the latest catalog accepted for this turn.
pub(crate) struct LatestCloudSkillsAuth(Option<McpResourceClientAuthKey>);
/// Thread-owned skill configuration and caches; consumers can only read catalog snapshots.
pub struct SkillsThreadState {
/// Serializes discovery; true only when the last refresh published successfully.
cloud_refresh_lock: AsyncMutex<bool>,
config: Mutex<SkillsExtensionConfig>,
cloud_skills_available: bool,
catalog_state: Mutex<SkillCatalogState>,
extension_metrics: Option<Arc<dyn ExtensionMetrics>>,
aliases: SkillAliasState,
shadow_selection_turn: Mutex<Option<ShadowSelectionTurn>>,
pub(crate) executor_read_snapshot: Mutex<Option<ExecutorReadSnapshot>>,
pub(crate) recent_skill_invocations: Arc<RecentSkillInvocations>,
pub(crate) shadow_task_context: Arc<ShadowTaskContext>,
}
impl SkillsThreadState {
pub(crate) fn new(
config: SkillsExtensionConfig,
cloud_skills_available: bool,
extension_metrics: Option<Arc<dyn ExtensionMetrics>>,
) -> Self {
Self {
cloud_refresh_lock: AsyncMutex::new(false),
config: Mutex::new(config),
cloud_skills_available,
catalog_state: Mutex::new(SkillCatalogState::default()),
extension_metrics,
aliases: SkillAliasState::default(),
shadow_selection_turn: Mutex::new(None),
executor_read_snapshot: Mutex::new(None),
recent_skill_invocations: Arc::new(RecentSkillInvocations::default()),
shadow_task_context: Arc::new(ShadowTaskContext::default()),
}
}
pub(crate) fn config(&self) -> SkillsExtensionConfig {
self.config
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone()
}
pub(crate) fn set_config(&self, config: SkillsExtensionConfig) {
let mut previous = self
.config
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if previous.cloud_skill_enabled != config.cloud_skill_enabled {
let mut catalogs = self
.catalog_state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
catalogs.cloud_generation = None;
catalogs.cloud_retry = None;
catalogs.cloud_resources = CloudResourceCache::default();
}
*previous = config;
}
pub(crate) fn cloud_skills_available(&self) -> bool {
self.cloud_skills_available
}
pub(crate) fn cloud_skill_enabled(&self) -> bool {
self.cloud_skills_available && self.config().cloud_skill_enabled
}
pub(crate) fn prepare_step_catalog(
&self,
cloud: Option<SkillCatalog>,
executor: SkillCatalog,
discovery_v2: bool,
) -> SkillStepCatalog {
let mut step = SkillStepCatalog::new(cloud, executor, discovery_v2, Default::default());
step.aliases = self.aliases.capture(
step.merged
.entries
.iter()
.flat_map(super::catalog::SkillCatalogEntry::source_locations)
.filter(|source| source.enabled && source.prompt_visible)
.filter_map(|source| source.alias_root.map(|root| (source.authority.kind, root))),
);
step
}
/// Returns the executor catalog, reusing matching discovery caches.
#[tracing::instrument(
name = "skills.executor.refresh_executor_catalog",
level = "info",
skip_all,
fields(root_count = query.executor_roots.len())
)]
pub(crate) async fn refresh_executor_catalog(
&self,
providers: &SkillProviders,
query: SkillListQuery<'_>,
) -> SkillCatalog {
if let Some(snapshots) = &query.executor_capability_discovery_v2 {
let snapshots = snapshots.clone();
let (cached, already_observed) = {
let state = self
.catalog_state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let cached = state.executor_v2_cache.as_ref();
let already_observed =
cached.is_some_and(|cached| cached.same_discovery(&snapshots));
(
cached
.filter(|_| {
already_observed
&& snapshots.iter().all(|snapshot| snapshot.result.is_ok())
})
.map(|cached| cached.catalog.clone()),
already_observed,
)
};
match cached {
Some(catalog) => catalog,
None => {
let catalog = providers.list_executor_for_turn(query).await;
// Failed snapshots are rebuilt for callers, but each is still one observation.
if !already_observed {
record_catalog(self.extension_metrics.as_deref(), "executor", &catalog);
}
self.catalog_state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.executor_v2_cache = Some(CachedExecutorV2Catalog {
snapshots,
catalog: catalog.clone(),
});
catalog
}
}
} else if query.executor_capability_discovery.is_some() {
self.executor_discovery_catalog_snapshot(providers, query)
.await
} else {
if let Some(cached) = self
.catalog_state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.executor_cache
.as_ref()
.filter(|cached| cached.key.matches(&query))
{
return cached.catalog.clone();
}
let key = ExecutorCatalogCacheKey {
turn_id: query.turn_id.clone(),
roots: query
.executor_roots
.iter()
.map(|root| (root.root.clone(), root.fs.cache_key()))
.collect(),
include_bundled_skills: query.include_bundled_skills,
};
let catalog = if query.executor_roots.is_empty() {
SkillCatalog::default()
} else {
providers.list_executor_for_turn(query).await
};
record_catalog(self.extension_metrics.as_deref(), "executor", &catalog);
self.catalog_state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.executor_cache = Some(CachedExecutorCatalog {
key,
catalog: catalog.clone(),
});
catalog
}
}
/// Reuses matching successful discovery; otherwise returns the result of this request.
async fn executor_discovery_catalog_snapshot(
&self,
providers: &SkillProviders,
query: SkillListQuery<'_>,
) -> SkillCatalog {
let discovery = query.executor_capability_discovery.clone();
let discovery_failed = discovery.as_ref().is_some_and(|discovery| {
discovery.roots().iter().any(|root| {
root.result
.as_ref()
.ok()
.is_none_or(|discovered| discovered.error.is_some())
})
});
let already_observed = {
let state = self
.catalog_state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let cached = state
.executor_discovery_cache
.as_ref()
.filter(|cached| cached.matches(discovery.as_ref(), query.include_bundled_skills));
if !discovery_failed && let Some(cached) = cached {
return cached.catalog.clone();
}
cached.is_some()
};
let include_bundled_skills = query.include_bundled_skills;
let discovered = providers.list_executor_for_turn(query).await;
if !already_observed {
record_catalog(self.extension_metrics.as_deref(), "executor", &discovered);
}
let mut state = self
.catalog_state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
// Failed discovery is returned to this caller but is never reused by another request.
state.executor_discovery_cache =
discovery.map(|discovery| CachedExecutorDiscoveryCatalog {
discovery,
include_bundled_skills,
catalog: discovered.clone(),
});
discovered
}
/// Returns the currently authorized cached Cloud catalog without refreshing it.
/// Preparation decides whether Cloud is enabled using its captured config.
pub(crate) fn available_cloud_catalog(&self) -> Option<SkillCatalog> {
self.catalog_state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.cloud_generation
.as_ref()
.filter(|cache| cache.is_auth_current())
.and_then(|cache| cache.catalog.clone())
}
/// Reuses discovery within a turn; backs off failures.
#[expect(
clippy::await_holding_invalid_type,
reason = "cloud discovery must remain serialized through fetching and catalog publication"
)]
#[tracing::instrument(name = "skills.cloud.refresh_cloud_catalog", level = "info", skip_all)]
pub(crate) async fn refresh_cloud_catalog(
&self,
providers: &SkillProviders,
query: SkillListQuery<'_>,
turn_store: &ExtensionData,
) -> SkillProviderResult<()> {
// Wait without holding config/catalog state or the MCP runtime permit.
let (mut refresh_succeeded, waited) = match self.cloud_refresh_lock.try_lock() {
Ok(guard) => (guard, false),
Err(_) => (self.cloud_refresh_lock.lock().await, true),
};
let (cache, resource_cache_key) = {
let config = self
.config
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if !config.cloud_skill_enabled || !self.cloud_skills_available {
return Ok(());
}
let mut catalogs = self
.catalog_state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
// Check this turn's discovery using the provider's auth scope.
let cache = catalogs.prepare_cloud_generation(
providers.cloud_mcp_resources(query.mcp_resources.as_deref()),
);
if cache.is_auth_current()
&& cache.catalog.is_some()
&& turn_store
.get::<LatestCloudSkillsAuth>()
.is_some_and(|previous| previous.0 == cache.auth_cache_key)
{
return Ok(());
}
let resource_cache_key = cache.current_resource_cache_key();
if catalogs.cloud_retry.as_ref().is_some_and(|retry| {
retry.is_pending(cache.auth_cache_key.as_ref(), resource_cache_key.as_ref())
}) {
return Ok(());
}
turn_store.remove::<LatestCloudSkillsAuth>();
if cache.is_auth_current()
&& cache.catalog.as_ref().is_some_and(|catalog| {
(waited && *refresh_succeeded)
|| (!catalog.is_partial && catalog.warnings.is_empty())
})
&& cache.resource_cache_key == resource_cache_key
{
catalogs.cloud_retry = None;
turn_store.insert(LatestCloudSkillsAuth(cache.auth_cache_key.clone()));
return Ok(());
}
// Waiting callers must not reuse a failed or cancelled refresh.
*refresh_succeeded = false;
(cache, resource_cache_key)
};
let mut result = providers.list_cloud_for_turn(query).await;
if let Ok(catalog) = &mut result {
catalog.entries.sort_by(|a, b| a.id.0.cmp(&b.id.0));
}
let mut catalogs = self
.catalog_state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if !cache.is_auth_current()
|| cache.current_resource_cache_key() != resource_cache_key
|| !catalogs
.cloud_generation
.as_ref()
.is_some_and(|current| Arc::ptr_eq(current, &cache))
{
// Ignore superseded results, including errors.
return Ok(());
}
let mut catalog = match result {
Ok(catalog) => catalog,
Err(error) => {
catalogs.cloud_retry = Some(CatalogRefreshBackoff::after_failure(
cache.auth_cache_key.clone(),
resource_cache_key,
catalogs.cloud_retry.as_ref(),
));
return Err(error);
}
};
catalogs.cloud_retry = None;
if catalog.is_partial
&& let Some(previous) = cache
.catalog
.as_ref()
.filter(|previous| !previous.is_partial)
{
catalog = previous.clone();
catalog.is_partial = true;
} else {
catalogs.cloud_resources = CloudResourceCache::default();
}
record_catalog(self.extension_metrics.as_deref(), "cloud", &catalog);
let generation = Arc::new(CloudSkillGeneration {
auth_cache_key: cache.auth_cache_key.clone(),
resource_cache_key,
mcp_resources: cache.mcp_resources.clone(),
catalog: Some(catalog),
});
catalogs.cloud_generation = Some(Arc::clone(&generation));
turn_store.insert(LatestCloudSkillsAuth(generation.auth_cache_key.clone()));
*refresh_succeeded = true;
Ok(())
}
pub(crate) async fn read_skill(
&self,
providers: &SkillProviders,
request: SkillReadRequest<'_>,
) -> SkillProviderResult<SkillReadResult> {
if request.authority.kind != SkillSourceKind::Cloud {
return providers.read(request).await;
}
let SkillReadContext::Cloud { mcp_resources } = &request.context else {
return Err(SkillProviderError::new(
"cloud skill reads require a cloud context",
));
};
let cache_key = SkillReadCacheKey::from(&request);
let cache = {
let config = self
.config
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if !config.cloud_skill_enabled || !self.cloud_skills_available {
return Err(SkillProviderError::new("cloud skills are disabled"));
}
let mut catalogs = self
.catalog_state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let cache = catalogs
.prepare_cloud_generation(providers.cloud_mcp_resources(mcp_resources.as_deref()));
if !cache.is_auth_current() {
return Err(SkillProviderError::new(
"cloud skill cache changed before read",
));
}
if let Some(result) = catalogs.cloud_resources.get(&cache_key) {
return Ok(result);
}
cache
};
let result = providers.read(request).await?;
let mut catalogs = self
.catalog_state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if !cache.is_auth_current()
|| !catalogs
.cloud_generation
.as_ref()
.is_some_and(|current| Arc::ptr_eq(current, &cache))
{
return Err(SkillProviderError::new(
"cloud skill cache changed during read",
));
}
if result.resource != cache_key.resource {
return Ok(result);
}
Ok(catalogs.cloud_resources.insert(cache_key, result))
}
pub(crate) fn replace_shadow_selection_turn(
&self,
turn_id: String,
state: Option<ShadowSelectionTurnState>,
) {
*self
.shadow_selection_turn
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) =
state.map(|state| ShadowSelectionTurn {
turn_id,
state: Arc::new(state),
});
}
pub(crate) fn shadow_selection_turn(
&self,
turn_id: &str,
) -> Option<Arc<ShadowSelectionTurnState>> {
self.shadow_selection_turn
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.as_ref()
.filter(|turn| turn.turn_id == turn_id)
.map(|turn| Arc::clone(&turn.state))
}
}
/// One bounded executor resource, retained for continuations until replacement or thread drop.
/// Interleaved resources may evict it; misses reread and validate the content-bound cursor.
pub(crate) struct ExecutorReadSnapshot {
pub(crate) authority: SkillAuthority,
pub(crate) package: SkillPackageId,
// The key binds cached contents to their source filesystem and callback permissions.
pub(crate) access: EnvironmentAccessKey,
pub(crate) result: Arc<SkillReadResult>,
}
struct ShadowSelectionTurn {
turn_id: String,
state: Arc<ShadowSelectionTurnState>,
}
#[derive(Default)]
pub(crate) struct EmittedCatalogBudgetWarnings(Mutex<HashSet<String>>);
impl EmittedCatalogBudgetWarnings {
pub(crate) fn insert(&self, warning: &str) -> bool {
self.0
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.insert(warning.to_string())
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct HostSkillsCatalogInWorldState;

View File

@@ -0,0 +1,121 @@
//! Immutable, policy-checked skill catalogs captured for one step.
use crate::aliases::SkillCatalogAliases;
use crate::catalog::SkillAuthority;
use crate::catalog::SkillCatalog;
use crate::catalog::SkillSourceKind;
use crate::catalog::merge_catalogs;
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
/// Fully prepared before tool construction; retained unchanged by all step consumers.
#[derive(Debug)]
pub(crate) struct SkillsStepState {
pub(crate) discovery_v2: bool,
pub(crate) tools_enabled: bool,
pub(crate) catalog: SkillStepCatalog,
pub(crate) host_catalog: Option<SkillCatalog>,
pub(crate) cloud_status: CatalogStatus,
pub(crate) config: crate::SkillsExtensionConfig,
}
/// Policy-checked, enabled skill routes for one step. Hidden skills remain explicitly readable.
#[derive(Debug)]
pub(crate) struct SkillStepCatalog {
pub(super) merged: SkillCatalog,
pub(crate) aliases: SkillCatalogAliases,
/// None means no Cloud catalog was captured for this step.
cloud_warnings: Option<Vec<String>>,
executor_warnings: Vec<String>,
}
impl SkillStepCatalog {
pub(crate) fn new(
cloud: Option<SkillCatalog>,
executor: SkillCatalog,
discovery_v2: bool,
aliases: SkillCatalogAliases,
) -> Self {
let cloud_skill_count = cloud.as_ref().map(|catalog| catalog.entries.len());
let executor_skill_count = executor.entries.len();
let cloud_warnings = cloud.as_ref().map(|catalog| catalog.warnings.clone());
let executor_warnings = executor.warnings.clone();
let mut catalog = if discovery_v2 {
merge_catalogs(cloud, executor)
} else {
let mut catalog = cloud.unwrap_or_default();
catalog.is_partial |= executor.is_partial;
catalog.entries.extend(executor.entries);
catalog.warnings.extend(executor.warnings);
catalog
};
catalog.entries.retain_mut(|entry| {
if !entry.enabled {
return false;
}
entry.sources.retain(|source| source.enabled);
true
});
tracing::debug!(
discovery_v2,
?cloud_skill_count,
executor_skill_count,
enabled_skill_count = catalog.entries.len(),
warning_count = catalog.warnings.len(),
"prepared step skill catalog"
);
Self {
merged: catalog,
aliases,
cloud_warnings,
executor_warnings,
}
}
/// Selects one authority from the prepared catalog without consulting thread state.
pub(crate) fn select_from_catalog(
&self,
authority: SkillToolAuthoritySelector,
) -> SkillCatalog {
let entries = self
.merged
.entries
.iter()
.filter(|entry| authority.matches(&entry.authority))
.cloned()
.collect();
let warnings = match authority {
SkillToolAuthoritySelector::Cloud => self.cloud_warnings.clone().unwrap_or_default(),
SkillToolAuthoritySelector::Executor => self.executor_warnings.clone(),
};
SkillCatalog {
is_partial: self.merged.is_partial,
entries,
warnings,
}
}
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub(crate) enum SkillToolAuthoritySelector {
Cloud,
Executor,
}
impl SkillToolAuthoritySelector {
pub(crate) fn matches(self, authority: &SkillAuthority) -> bool {
match self {
Self::Cloud => authority.kind == SkillSourceKind::Cloud,
Self::Executor => authority.kind == SkillSourceKind::Executor,
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum CatalogStatus {
Unavailable,
Disabled,
Enabled,
}

View File

@@ -0,0 +1,164 @@
use std::collections::HashSet;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::Weak;
use std::time::Instant;
use codex_extension_api::ExtensionData;
use codex_extension_api::ExtensionFuture;
use codex_extension_api::TurnAbortInput;
use codex_extension_api::TurnErrorInput;
use codex_extension_api::TurnLifecycleContributor;
use codex_extension_api::TurnStartInput;
use codex_extension_api::TurnStopInput;
use codex_otel::sanitize_metric_tag_value;
use codex_protocol::openai_models::ModelInfo;
use crate::state::SkillsSessionState;
/// Attributes a successful host skill invocation to its turn's plugin latency metrics.
pub fn record_plugin_turn_usage(turn_store: &ExtensionData, plugin_id: Option<&str>) {
if let Some(turn) = turn_store.get::<SkillTurnMetrics>() {
turn.record_plugin(plugin_id);
}
}
pub(crate) struct SkillTurnMetrics {
pub(crate) turn_id: String,
pub(crate) turn_metadata: Option<Arc<dyn codex_analytics::TurnAnalyticsMetadata>>,
model_slug: String,
pub(crate) reasoning_effort: String,
started_at: Instant,
usage: Mutex<Option<TurnUsage>>,
}
#[derive(Default)]
struct TurnUsage {
plugins: HashSet<String>,
failed: bool,
}
impl SkillTurnMetrics {
pub(crate) fn record_plugin(&self, plugin_id: Option<&str>) {
if let Some(usage) = self
.usage
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.as_mut()
{
usage
.plugins
.insert(plugin_id.unwrap_or("unattributed").to_string());
}
}
fn finish(&self, session_store: &ExtensionData, status: &str) {
let Some(usage) = self
.usage
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.take()
else {
return;
};
let Some(metrics) = session_store
.get::<SkillsSessionState>()
.and_then(|state| state.extension_metrics.clone())
else {
return;
};
let status = if status == "completed" && usage.failed {
"error"
} else {
status
};
// Seconds keep multi-minute turns within the standard histogram buckets.
// Round up so integer-second bucket boundaries classify fractional durations correctly.
let duration_seconds = self.started_at.elapsed().as_secs_f64().ceil() as i64;
for plugin_id in usage.plugins {
let plugin_id = sanitize_metric_tag_value(&plugin_id);
metrics.histogram(
"codex.skill.turn.duration_seconds",
duration_seconds,
&[
("plugin_id", plugin_id.as_str()),
("model_slug", self.model_slug.as_str()),
("reasoning_effort", self.reasoning_effort.as_str()),
("status", status),
],
);
}
}
}
#[derive(Default)]
pub(crate) struct ActiveSkillTurnMetrics(pub(crate) Mutex<Weak<SkillTurnMetrics>>);
pub(crate) struct SkillTelemetry;
impl TurnLifecycleContributor for SkillTelemetry {
fn on_turn_start<'a>(&'a self, input: TurnStartInput<'a>) -> ExtensionFuture<'a, ()> {
Box::pin(async move {
let reasoning_effort = input
.collaboration_mode
.reasoning_effort()
.or_else(|| {
input
.thread_store
.get::<ModelInfo>()
.and_then(|model| model.default_reasoning_level.clone())
})
.map(|effort| effort.to_string())
.unwrap_or_else(|| "default".to_string());
input.turn_store.insert(SkillTurnMetrics {
turn_id: input.turn_id.to_string(),
turn_metadata: input
.turn_store
.get::<Arc<dyn codex_analytics::TurnAnalyticsMetadata>>()
.map(|metadata| metadata.as_ref().clone()),
model_slug: sanitize_metric_tag_value(input.collaboration_mode.model()),
reasoning_effort,
started_at: Instant::now(),
usage: Mutex::new(Some(TurnUsage::default())),
});
if let Some(turn) = input.turn_store.get::<SkillTurnMetrics>() {
*input
.thread_store
.get_or_init(ActiveSkillTurnMetrics::default)
.0
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) = Arc::downgrade(&turn);
}
})
}
fn on_turn_stop<'a>(&'a self, input: TurnStopInput<'a>) -> ExtensionFuture<'a, ()> {
Box::pin(async move {
if let Some(turn) = input.turn_store.get::<SkillTurnMetrics>() {
turn.finish(input.session_store, "completed");
}
})
}
fn on_turn_abort<'a>(&'a self, input: TurnAbortInput<'a>) -> ExtensionFuture<'a, ()> {
Box::pin(async move {
if let Some(turn) = input.turn_store.get::<SkillTurnMetrics>() {
turn.finish(input.session_store, "aborted");
}
})
}
fn on_turn_error<'a>(&'a self, input: TurnErrorInput<'a>) -> ExtensionFuture<'a, ()> {
Box::pin(async move {
if let Some(turn) = input.turn_store.get::<SkillTurnMetrics>()
&& let Some(usage) = turn
.usage
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.as_mut()
{
usage.failed = true;
}
})
}
}

View File

@@ -0,0 +1,204 @@
//! Retrieves installation locations from the prepared catalog without reading skill contents.
use std::collections::HashSet;
use std::sync::Arc;
use codex_extension_api::ExtensionMetrics;
use codex_extension_api::FunctionCallError;
use codex_extension_api::ToolCall;
use codex_extension_api::ToolExecutor;
use codex_extension_api::ToolExecutorFuture;
use codex_extension_api::ToolName;
use codex_extension_api::ToolSpec;
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use crate::aliases::SkillLocator;
use super::InstallationLocation;
use super::InstallationSource;
use super::MAX_HANDLE_BYTES;
use super::SkillToolAuthoritySelector;
use super::SkillToolContext;
use super::parse_args;
use super::parse_pagination_cursor;
use super::serialized_len;
use super::skill_function_tool;
use super::skill_json_output;
use super::skill_tool_name;
use super::validate_handle;
use super::value_fingerprint;
const TOOL_NAME: &str = "installations";
const MAX_INSTALLATIONS_RESPONSE_BYTES: usize = 8 * 1024;
#[derive(Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
struct InstallationsArgs {
#[schemars(with = "String")]
package: SkillLocator,
source: Option<InstallationSource>,
cursor: Option<String>,
}
#[derive(JsonSchema, Serialize)]
#[schemars(deny_unknown_fields)]
struct InstallationsResponse {
installations: Vec<InstallationLocation>,
next_cursor: Option<String>,
}
pub(super) struct InstallationsTool {
pub(super) context: SkillToolContext,
pub(super) metrics: Option<Arc<dyn ExtensionMetrics>>,
}
impl<'call> ToolExecutor<ToolCall<'call>> for InstallationsTool {
fn tool_name(&self) -> ToolName {
skill_tool_name(TOOL_NAME)
}
fn supports_parallel_tool_calls(&self) -> bool {
true
}
fn spec(&self) -> ToolSpec {
skill_function_tool::<InstallationsArgs, InstallationsResponse>(
TOOL_NAME,
"Find a skill's enabled Cloud and executor locations, including those omitted by skills.read. Pass its provided package directly; root aliases are resolved automatically. Use source {kind: cloud} for Cloud or {kind: executor, environment_id: ...} for one environment. Omit source for all locations. Cloud locations return package and resource: pass both directly to skills.read to read the main instruction file, usually SKILL.md. Executor locations return environment_id and skill_root, the absolute directory containing instructions and supporting files such as scripts. Pass next_cursor back as cursor with the same package and source to continue listing locations. Omit cursor to start again. An empty list without next_cursor means no enabled location matches.",
)
}
fn handle<'a>(&'a self, call: ToolCall<'call>) -> ToolExecutorFuture<'a>
where
'call: 'a,
{
Box::pin(async move {
let mut outcome = "internal_error";
let mut source_filter = "unparsed";
let result = (|| {
let args: InstallationsArgs =
parse_args(&call).inspect_err(|_| outcome = "invalid_arguments")?;
source_filter = match &args.source {
None => "all",
Some(InstallationSource::Cloud) => "cloud",
Some(InstallationSource::Executor { .. }) => "executor",
};
validate_handle("package", args.package.as_str(), MAX_HANDLE_BYTES)
.inspect_err(|_| outcome = "invalid_package")?;
if let Some(source) = &args.source {
source
.validate()
.inspect_err(|_| outcome = "invalid_source")?;
}
let matches = self
.context
.matching_packages(&args.package)
.inspect_err(|_| outcome = "ambiguous_name")?;
let (entry, _) = matches.first().ok_or_else(|| {
outcome = if args.package.alias_source().is_some()
&& self
.context
.step_state
.catalog
.aliases
.resolve(&args.package)
.is_none()
{
"unresolved_alias"
} else {
"package_unavailable"
};
FunctionCallError::RespondToModel("skill package is not available".to_string())
})?;
let mut installations = Vec::new();
let mut seen = HashSet::new();
for installation in matches
.iter()
.flat_map(|(entry, matched_source)| {
std::iter::once(matched_source.clone()).chain(entry.source_locations())
})
.filter(|source| {
args.source
.as_ref()
.is_none_or(|filter| filter.matches(source))
})
.filter_map(|source| InstallationLocation::from_source(&source))
{
if seen.insert(installation.clone()) {
installations.push(installation);
}
}
let identity = (&entry.id.0, &args.source, &installations);
let start = parse_pagination_cursor(
args.cursor.as_deref(),
&identity,
"skills.installations",
)
.inspect_err(|_| outcome = "invalid_cursor")?;
if start > installations.len() {
outcome = "invalid_cursor";
return Err(FunctionCallError::RespondToModel(
"skills.installations cursor is invalid".to_string(),
));
}
let fingerprint = value_fingerprint(&identity);
let cursor_at = |offset| format!("{fingerprint:016x}:{offset}");
let budget = call.response_byte_budget(MAX_INSTALLATIONS_RESPONSE_BYTES);
let mut response = InstallationsResponse {
installations: Vec::new(),
next_cursor: None,
};
let installation_count = installations.len();
for (index, installation) in installations.into_iter().enumerate().skip(start) {
response.installations.push(installation);
response.next_cursor =
(index + 1 < installation_count).then(|| cursor_at(index + 1));
if serialized_len(&response)? > budget {
response.installations.pop();
response.next_cursor = Some(cursor_at(index));
break;
}
}
if (start < installation_count && response.installations.is_empty())
|| serialized_len(&response)? > budget
{
outcome = "response_budget";
return Err(FunctionCallError::RespondToModel(
"skills.installations response budget leaves no room for an installation"
.to_string(),
));
}
let authority = if response
.installations
.iter()
.any(|location| matches!(location, InstallationLocation::Cloud { .. }))
{
SkillToolAuthoritySelector::Cloud
} else {
SkillToolAuthoritySelector::Executor
};
let output = skill_json_output(&response, authority)?;
outcome = if response.installations.is_empty() {
"empty"
} else {
"success"
};
Ok(output)
})();
if let Some(metrics) = &self.metrics {
metrics.counter(
"codex.skills.installations.result",
/*inc*/ 1,
&[
("outcome", outcome),
("source_filter", source_filter),
("discovery_version", "v2"),
],
);
}
result
})
}
}

View File

@@ -0,0 +1,241 @@
use codex_extension_api::FunctionCallError;
use codex_extension_api::ToolCall;
use codex_extension_api::ToolExecutor;
use codex_extension_api::ToolExecutorFuture;
use codex_extension_api::ToolName;
use codex_extension_api::ToolSpec;
use codex_utils_string::take_bytes_at_char_boundary;
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use crate::catalog::SkillCatalogEntry;
use crate::render::MAX_SKILL_NAME_BYTES;
use crate::render::truncate_catalog_skill_description;
use crate::warnings::bounded_warnings;
use super::MAX_HANDLE_BYTES;
use super::MAX_SKILL_RESPONSE_BYTES;
use super::SkillToolAuthority;
use super::SkillToolAuthoritySelector;
use super::SkillToolContext;
use super::is_bounded_handle;
use super::parse_args;
use super::parse_pagination_cursor;
use super::serialized_len;
use super::skill_function_tool;
use super::skill_json_output;
use super::skill_tool_name;
use super::value_fingerprint;
const TOOL_NAME: &str = "list";
const MAX_SKILLS_PER_PAGE: usize = 20;
const OVERSIZED_ENTRY_WARNING: &str =
"Some skills were omitted because their metadata is too large.";
#[derive(Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
struct ListArgs {
authority: SkillToolAuthoritySelector,
cursor: Option<String>,
}
#[derive(Clone, Debug, Eq, Hash, JsonSchema, PartialEq, Serialize)]
#[schemars(deny_unknown_fields)]
struct ListedSkill {
authority: SkillToolAuthority,
package: String,
name: String,
description: String,
main_resource: String,
}
#[derive(Debug, Eq, JsonSchema, PartialEq, Serialize)]
#[schemars(deny_unknown_fields)]
struct ListResponse {
skills: Vec<ListedSkill>,
warnings: Vec<String>,
next_cursor: Option<String>,
}
#[derive(Clone)]
pub(super) struct ListTool {
pub(super) context: SkillToolContext,
}
impl<'call> ToolExecutor<ToolCall<'call>> for ListTool {
fn tool_name(&self) -> ToolName {
skill_tool_name(TOOL_NAME)
}
fn supports_parallel_tool_calls(&self) -> bool {
true
}
fn spec(&self) -> ToolSpec {
skill_function_tool::<ListArgs, ListResponse>(
TOOL_NAME,
"List skills owned by the requested authority. Returns each skill's authority, package, and main_resource. Pass the package to skills.read, and pass next_cursor back as cursor to continue.",
)
}
fn handle<'a>(&'a self, call: ToolCall<'call>) -> ToolExecutorFuture<'a>
where
'call: 'a,
{
Box::pin(async move {
let args: ListArgs = parse_args(&call)?;
let response_byte_budget = call.response_byte_budget(MAX_SKILL_RESPONSE_BYTES);
let catalog = self
.context
.step_state
.catalog
.select_from_catalog(args.authority);
let mut omitted_oversized_entry = false;
let canonical_skills = catalog
.entries
.into_iter()
.filter(SkillCatalogEntry::is_model_visible)
.filter_map(|entry| {
let listed = listed_skill(entry);
omitted_oversized_entry |= listed.is_none();
listed
})
.collect::<Vec<_>>();
// Older cursors contain only the catalog fingerprint and offset. New cursors
// also record the budget whose omissions have already been reported.
let (cursor, previous_byte_budget) = match args.cursor.as_deref() {
Some(cursor) => match cursor.rsplit_once(':') {
Some((canonical_cursor, byte_budget)) => {
if canonical_cursor.contains(':') {
let byte_budget = byte_budget.parse::<usize>().map_err(|_| {
FunctionCallError::RespondToModel(
"skills.list cursor is invalid".to_string(),
)
})?;
(Some(canonical_cursor), Some(byte_budget))
} else {
(Some(cursor), None)
}
}
None => (Some(cursor), None),
},
None => (None, None),
};
let start = parse_pagination_cursor(cursor, &canonical_skills, "skills.list")?;
if start > canonical_skills.len() {
return Err(FunctionCallError::RespondToModel(
"skills.list cursor is invalid".to_string(),
));
}
let cursor_fingerprint = value_fingerprint(&canonical_skills);
let cursor_at =
|offset| format!("{cursor_fingerprint:016x}:{offset}:{response_byte_budget}");
let mut skills = Vec::with_capacity(canonical_skills.len().saturating_sub(start));
// The final retained skill needs no cursor, even if later entries are oversized.
for (index, skill) in canonical_skills.iter().enumerate().skip(start).rev() {
let next_cursor = (!skills.is_empty()).then(|| cursor_at(index.saturating_add(1)));
if single_entry_response_is_bounded(skill, response_byte_budget, next_cursor) {
skills.push((index, skill));
} else {
omitted_oversized_entry = true;
}
}
skills.reverse();
let mut provider_warnings = if args.cursor.is_none() {
bounded_warnings(&catalog.warnings)
} else {
Vec::new()
};
let omission_warning = (omitted_oversized_entry
&& previous_byte_budget != Some(response_byte_budget))
.then_some(OVERSIZED_ENTRY_WARNING);
let mut end = MAX_SKILLS_PER_PAGE.min(skills.len());
loop {
let mut response = ListResponse {
skills: skills[..end]
.iter()
.map(|(_, skill)| (*skill).clone())
.collect(),
warnings: provider_warnings
.iter()
.cloned()
.chain(omission_warning.map(str::to_string))
.collect(),
next_cursor: (end < skills.len())
.then(|| cursor_at(skills[end.saturating_sub(1)].0.saturating_add(1))),
};
if serialized_len(&response)? <= response_byte_budget {
return skill_json_output(&response, args.authority);
}
if end > 1 {
end = end.saturating_sub(1);
} else if provider_warnings.len() > 1 {
provider_warnings.pop();
} else if !response.warnings.is_empty() {
response.skills.clear();
// Recording this budget acknowledges the omission warning, even when
// the next call resumes at the same canonical skill offset.
response.next_cursor = Some(cursor_at(start));
if serialized_len(&response)? <= response_byte_budget {
return skill_json_output(&response, args.authority);
}
if omission_warning.is_some() && !provider_warnings.is_empty() {
response.warnings = provider_warnings;
// Report discovery first without acknowledging an unshown omission.
// Reusing this offset lets the next call report it before advancing.
response.next_cursor = Some(format!("{cursor_fingerprint:016x}:{start}"));
if serialized_len(&response)? <= response_byte_budget {
return skill_json_output(&response, args.authority);
}
}
// FunctionCallError cannot carry external-context metadata, so do not
// expose provider warnings through this path.
return Err(FunctionCallError::RespondToModel(
"skills.list response budget leaves no room for discovery warnings"
.to_string(),
));
} else {
return Err(FunctionCallError::RespondToModel(
"skill metadata is too large to list".to_string(),
));
}
}
})
}
}
fn single_entry_response_is_bounded(
skill: &ListedSkill,
response_byte_budget: usize,
next_cursor: Option<String>,
) -> bool {
serialized_len(&ListResponse {
skills: vec![skill.clone()],
warnings: Vec::new(),
next_cursor,
})
.is_ok_and(|size| size <= response_byte_budget)
}
pub(super) fn listed_name(name: &str) -> &str {
take_bytes_at_char_boundary(name, MAX_SKILL_NAME_BYTES)
}
fn listed_skill(entry: SkillCatalogEntry) -> Option<ListedSkill> {
let authority = SkillToolAuthority::from_authority(&entry.authority)?;
if !is_bounded_handle(&entry.authority.id, MAX_HANDLE_BYTES)
|| !is_bounded_handle(&entry.id.0, MAX_HANDLE_BYTES)
|| !is_bounded_handle(entry.main_prompt.as_str(), MAX_HANDLE_BYTES)
{
return None;
}
Some(ListedSkill {
authority,
package: entry.id.0,
name: listed_name(&entry.name).to_owned(),
description: truncate_catalog_skill_description(&entry.description).into_owned(),
main_resource: entry.main_prompt.as_str().to_string(),
})
}

View File

@@ -0,0 +1,470 @@
use std::collections::hash_map::DefaultHasher;
use std::hash::Hash;
use std::hash::Hasher;
use std::sync::Arc;
use codex_analytics::AnalyticsEventsClient;
use codex_analytics::InvocationType;
use codex_analytics::build_track_events_context;
use codex_extension_api::ExtensionData;
use codex_extension_api::ExtensionMetrics;
use codex_extension_api::FunctionCallError;
use codex_extension_api::JsonToolOutput;
use codex_extension_api::ResponsesApiTool;
use codex_extension_api::ThreadOriginator;
use codex_extension_api::ToolCall;
use codex_extension_api::ToolExecutor;
use codex_extension_api::ToolName;
use codex_extension_api::ToolOutput;
use codex_extension_api::ToolSpec;
use codex_extension_api::parse_tool_input_schema;
use codex_mcp::CODEX_APPS_MCP_SERVER_NAME;
use codex_mcp::McpResourceClient;
use codex_otel::SessionTelemetry;
use codex_otel::SkillInvocationEvent;
use codex_otel::SkillInvocationType;
use codex_otel::sanitize_metric_tag_value;
use codex_tools::ResponsesApiNamespace;
use codex_tools::ResponsesApiNamespaceTool;
use codex_tools::default_namespace_description;
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use serde_json::Value;
use crate::aliases::SkillLocator;
use crate::catalog::SkillAuthority;
use crate::catalog::SkillCatalogEntry;
use crate::catalog::SkillSourceKind;
use crate::catalog::SkillSourceLocation;
use crate::sources::SkillProviders;
use crate::state::SkillsSessionState;
use crate::state::SkillsThreadState;
use crate::step_state::SkillToolAuthoritySelector;
use crate::step_state::SkillsStepState;
use crate::telemetry::ActiveSkillTurnMetrics;
use crate::telemetry::SkillTurnMetrics;
mod installations;
mod list;
mod read;
mod schema;
const SKILLS_NAMESPACE: &str = "skills";
const MAX_HANDLE_BYTES: usize = 2_048;
const MAX_SKILL_RESPONSE_BYTES: usize = 512 * 1024;
pub(crate) fn skill_tools(
providers: SkillProviders,
session_store: &ExtensionData,
thread_store: &ExtensionData,
step_store: &ExtensionData,
) -> Vec<Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>> {
let Some(thread_state) = thread_store.get::<SkillsThreadState>() else {
return Vec::new();
};
let Some(step_state) = step_store.get::<SkillsStepState>() else {
return Vec::new();
};
if !step_state.tools_enabled {
return Vec::new();
}
let mcp_resources = session_store
.get::<SkillsSessionState>()
.and_then(|state| state.mcp_resources.clone());
let analytics = SkillAnalytics::from_stores(session_store, thread_store);
let metrics = step_store
.get::<Arc<dyn ExtensionMetrics>>()
.map(|metrics| Arc::clone(metrics.as_ref()));
let context = SkillToolContext {
thread_id: thread_store.level_id().to_string(),
providers,
mcp_resources,
thread_state,
analytics,
step_state,
};
let mut tools: Vec<Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>> = vec![
Arc::new(list::ListTool {
context: context.clone(),
}),
Arc::new(read::ReadTool {
context: context.clone(),
metrics: metrics.clone(),
}),
];
if context.step_state.discovery_v2 {
tools.push(Arc::new(installations::InstallationsTool {
context,
metrics,
}));
}
tools
}
#[derive(Clone)]
pub(crate) struct SkillAnalytics {
client: AnalyticsEventsClient,
telemetry: Option<Arc<SessionTelemetry>>,
metrics: Option<Arc<dyn ExtensionMetrics>>,
turn_metrics: Option<Arc<SkillTurnMetrics>>,
thread_id: String,
product_client_id: String,
}
impl SkillAnalytics {
pub(crate) fn from_stores(
session_store: &ExtensionData,
thread_store: &ExtensionData,
) -> Option<Self> {
let client = session_store.get::<AnalyticsEventsClient>()?;
let originator = thread_store.get::<ThreadOriginator>()?;
Some(Self {
client: client.as_ref().clone(),
telemetry: session_store.get::<SessionTelemetry>(),
metrics: session_store
.get::<SkillsSessionState>()
.and_then(|state| state.extension_metrics.clone()),
// Code-mode callbacks retain these tools after another turn becomes active.
turn_metrics: thread_store
.get_or_init(ActiveSkillTurnMetrics::default)
.0
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.upgrade(),
thread_id: thread_store.level_id().to_string(),
product_client_id: originator.0.clone(),
})
}
pub(crate) fn track_skill_invocation(
&self,
skill: &SkillCatalogEntry,
source: &SkillSourceLocation,
model: String,
turn_id: String,
invocation_type: InvocationType,
) {
let invocation = skill.invocation(source, invocation_type);
if let Some(telemetry) = &self.telemetry {
telemetry
.as_ref()
.clone()
.with_model(&model, &model)
.skill_invocation(SkillInvocationEvent {
turn_id: &turn_id,
skill_name: &skill.name,
scope: skill.analytics_scope,
plugin_id: invocation.plugin_id.as_deref(),
invocation_type: match invocation_type {
InvocationType::Explicit => SkillInvocationType::Explicit,
InvocationType::Implicit => SkillInvocationType::Implicit,
},
});
}
let turn_metrics = self
.turn_metrics
.as_ref()
.filter(|turn| turn.turn_id == turn_id);
if let Some(turn_metrics) = &turn_metrics {
turn_metrics.record_plugin(invocation.plugin_id.as_deref());
}
if let Some(metrics) = &self.metrics {
let skill_name_tag = sanitize_metric_tag_value(skill.name.as_str());
let plugin_id_tag = sanitize_metric_tag_value(
invocation.plugin_id.as_deref().unwrap_or("unattributed"),
);
let model_slug_tag = sanitize_metric_tag_value(model.as_str());
let reasoning_effort = turn_metrics
.as_ref()
.map(|turn| turn.reasoning_effort.as_str())
.unwrap_or("unknown");
let invoke_type = match invocation_type {
InvocationType::Explicit => "explicit",
InvocationType::Implicit => "implicit",
};
metrics.counter(
"codex.skill.injected",
/*inc*/ 1,
&[
("status", "ok"),
("skill", skill_name_tag.as_str()),
("invoke_type", invoke_type),
("plugin_id", plugin_id_tag.as_str()),
("model_slug", model_slug_tag.as_str()),
("reasoning_effort", reasoning_effort),
],
);
}
self.client.track_skill_invocations(
build_track_events_context(
model,
self.thread_id.clone(),
turn_id,
self.product_client_id.clone(),
turn_metrics.and_then(|turn| turn.turn_metadata.clone()),
),
vec![invocation],
);
}
}
#[derive(Clone)]
struct SkillToolContext {
thread_id: String,
providers: SkillProviders,
mcp_resources: Option<Arc<McpResourceClient>>,
thread_state: Arc<SkillsThreadState>,
analytics: Option<SkillAnalytics>,
step_state: Arc<SkillsStepState>,
}
impl SkillToolContext {
fn matching_packages<'a>(
&'a self,
package: &SkillLocator,
) -> Result<Vec<(&'a SkillCatalogEntry, SkillSourceLocation)>, FunctionCallError> {
let catalog = &self.step_state.catalog.merged;
let matching_entries = |resolved_package: &str, alias_source: Option<&SkillSourceKind>| {
catalog
.entries
.iter()
.filter_map(|entry| {
entry.source_locations().find_map(|source| {
if source.package.0 != resolved_package
|| alias_source.is_some_and(|kind| *kind != source.authority.kind)
{
return None;
}
SkillToolAuthority::from_authority(&source.authority)?;
Some((entry, source))
})
})
.collect::<Vec<_>>()
};
let locator = package.as_str();
let exact = matching_entries(locator, /*alias_source*/ None);
if !exact.is_empty() || locator.starts_with("skill://") {
return Ok(exact);
}
if let Some(source) = package.alias_source() {
let resolved = self.step_state.catalog.aliases.resolve(package);
return Ok(resolved.map_or_else(Vec::new, |id| matching_entries(&id, Some(source))));
}
let named = catalog
.entries
.iter()
.filter(|entry| entry.is_model_visible())
.filter(|entry| entry.name == locator || list::listed_name(&entry.name) == locator)
.filter_map(|entry| {
entry.source_locations().find_map(|source| {
SkillToolAuthority::from_authority(&source.authority)?;
Some((entry, source))
})
})
.collect::<Vec<_>>();
// Separate environments can each have an installation of the same package.
if let Some(((_, first), rest)) = named.split_first()
&& rest.iter().any(|(_, source)| {
source.authority != first.authority || source.package != first.package
})
{
return Err(FunctionCallError::RespondToModel(
"skill name is ambiguous; use skills.list and pass the package for the intended skill"
.to_string(),
));
}
Ok(named)
}
}
#[derive(Deserialize, Hash, JsonSchema)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
enum InstallationSource {
Cloud,
Executor { environment_id: String },
}
impl InstallationSource {
fn validate(&self) -> Result<(), FunctionCallError> {
if let Self::Executor { environment_id } = self {
validate_handle("environment_id", environment_id, MAX_HANDLE_BYTES)?;
}
Ok(())
}
fn matches(&self, source: &SkillSourceLocation) -> bool {
source.enabled
&& match self {
Self::Cloud => source.authority.kind == SkillSourceKind::Cloud,
Self::Executor { environment_id } => {
source.authority.kind == SkillSourceKind::Executor
&& source
.main_prompt
.environment_path()
.is_some_and(|(id, _)| id == environment_id)
}
}
}
}
#[derive(Clone, Debug, Eq, Hash, JsonSchema, PartialEq, Serialize)]
#[serde(untagged)]
#[schemars(deny_unknown_fields)]
enum InstallationLocation {
Cloud {
package: String,
resource: String,
},
Executor {
environment_id: String,
skill_root: String,
},
}
impl InstallationLocation {
fn from_source(source: &SkillSourceLocation) -> Option<Self> {
if !source.enabled {
return None;
}
match &source.authority.kind {
SkillSourceKind::Cloud => Some(Self::Cloud {
package: source.package.0.clone(),
resource: source.main_prompt.as_str().to_string(),
}),
SkillSourceKind::Executor => {
let (environment_id, path) = source.main_prompt.environment_path()?;
Some(Self::Executor {
environment_id: environment_id.to_string(),
skill_root: path.parent()?.inferred_native_path_string(),
})
}
SkillSourceKind::Host | SkillSourceKind::Custom(_) => None,
}
}
}
#[derive(Clone, Debug, Deserialize, Eq, Hash, JsonSchema, PartialEq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub(crate) enum SkillToolAuthority {
Cloud,
Executor { id: String },
}
impl SkillToolAuthority {
fn selector(&self) -> SkillToolAuthoritySelector {
match self {
Self::Cloud => SkillToolAuthoritySelector::Cloud,
Self::Executor { .. } => SkillToolAuthoritySelector::Executor,
}
}
pub(crate) fn from_authority(authority: &SkillAuthority) -> Option<Self> {
match &authority.kind {
SkillSourceKind::Cloud if authority.id == CODEX_APPS_MCP_SERVER_NAME => {
Some(Self::Cloud)
}
SkillSourceKind::Executor => Some(Self::Executor {
id: authority.id.clone(),
}),
SkillSourceKind::Host | SkillSourceKind::Cloud | SkillSourceKind::Custom(_) => None,
}
}
}
fn skill_tool_name(name: &str) -> ToolName {
ToolName::namespaced(SKILLS_NAMESPACE, name)
}
fn skill_function_tool<I: JsonSchema, O: JsonSchema>(name: &str, description: &str) -> ToolSpec {
let tool = ResponsesApiTool {
name: name.to_string(),
description: description.to_string(),
strict: false,
defer_loading: None,
parameters: parse_tool_input_schema(&schema::input_schema_for::<I>())
.unwrap_or_else(|err| panic!("generated input schema for {name} should parse: {err}")),
output_schema: Some(schema::output_schema_for::<O>().into()),
};
ToolSpec::Namespace(ResponsesApiNamespace {
name: SKILLS_NAMESPACE.to_string(),
description: default_namespace_description(SKILLS_NAMESPACE),
tools: vec![ResponsesApiNamespaceTool::Function(tool)],
})
}
fn parse_args<T: for<'de> Deserialize<'de>>(call: &ToolCall<'_>) -> Result<T, FunctionCallError> {
let arguments = call.function_arguments()?;
let value = if arguments.trim().is_empty() {
Value::Object(serde_json::Map::new())
} else {
serde_json::from_str(arguments)
.map_err(|err| FunctionCallError::RespondToModel(err.to_string()))?
};
serde_json::from_value(value).map_err(|err| FunctionCallError::RespondToModel(err.to_string()))
}
fn validate_handle(name: &str, value: &str, max_bytes: usize) -> Result<(), FunctionCallError> {
if is_bounded_handle(value, max_bytes) {
return Ok(());
}
Err(FunctionCallError::RespondToModel(format!(
"{name} must be non-empty, contain no control characters, and be at most {max_bytes} bytes"
)))
}
fn is_bounded_handle(value: &str, max_bytes: usize) -> bool {
!value.is_empty() && value.len() <= max_bytes && !value.chars().any(char::is_control)
}
fn pagination_cursor(value: &(impl Hash + ?Sized), offset: usize) -> String {
format!("{:016x}:{offset}", value_fingerprint(value))
}
fn parse_pagination_cursor(
cursor: Option<&str>,
value: &(impl Hash + ?Sized),
tool: &str,
) -> Result<usize, FunctionCallError> {
let Some(cursor) = cursor else {
return Ok(0);
};
let invalid = || FunctionCallError::RespondToModel(format!("{tool} cursor is invalid"));
let (fingerprint, offset) = cursor.split_once(':').ok_or_else(invalid)?;
if u64::from_str_radix(fingerprint, 16).ok() != Some(value_fingerprint(value)) {
return Err(FunctionCallError::RespondToModel(format!(
"{tool} cursor is stale; restart from the first page"
)));
}
offset.parse::<usize>().map_err(|_| invalid())
}
fn value_fingerprint(value: &(impl Hash + ?Sized)) -> u64 {
let mut hasher = DefaultHasher::new();
value.hash(&mut hasher);
hasher.finish()
}
fn serialized_len(value: &impl Serialize) -> Result<usize, FunctionCallError> {
serde_json::to_vec(value)
.map(|value| value.len())
.map_err(|err| FunctionCallError::Fatal(err.to_string()))
}
fn skill_json_output<T: Serialize>(
value: &T,
authority: SkillToolAuthoritySelector,
) -> Result<Box<dyn ToolOutput>, FunctionCallError> {
let value = serde_json::to_value(value).map_err(|err| {
FunctionCallError::Fatal(format!("failed to serialize tool output: {err}"))
})?;
let output = JsonToolOutput::new(value);
Ok(match authority {
SkillToolAuthoritySelector::Cloud => Box::new(output.with_external_context()),
SkillToolAuthoritySelector::Executor => Box::new(output),
})
}

View File

@@ -0,0 +1,511 @@
use std::sync::Arc;
use codex_analytics::InvocationType;
use codex_extension_api::ExtensionMetrics;
use codex_extension_api::FunctionCallError;
use codex_extension_api::ToolCall;
use codex_extension_api::ToolExecutor;
use codex_extension_api::ToolExecutorFuture;
use codex_extension_api::ToolName;
use codex_extension_api::ToolSpec;
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use crate::aliases::SkillLocator;
use crate::catalog::SkillResourceId;
use crate::catalog::SkillSourceKind;
use crate::provider::MAX_SKILL_RESOURCE_CONTENT_BYTES;
use crate::provider::SkillReadContext;
use crate::provider::SkillReadRequest;
use crate::state::ExecutorReadSnapshot;
use super::InstallationLocation;
use super::InstallationSource;
use super::MAX_HANDLE_BYTES;
use super::MAX_SKILL_RESPONSE_BYTES;
use super::SKILLS_NAMESPACE;
use super::SkillToolAuthority;
use super::SkillToolAuthoritySelector;
use super::SkillToolContext;
use super::pagination_cursor;
use super::parse_args;
use super::parse_pagination_cursor;
use super::serialized_len;
use super::skill_function_tool;
use super::skill_json_output;
use super::skill_tool_name;
use super::validate_handle;
const TOOL_NAME: &str = "read";
const MAX_INSTALLATION_METADATA_BYTES: usize = 1024;
#[derive(Deserialize, JsonSchema)]
struct ReadArgs {
#[schemars(with = "String")]
package: SkillLocator,
resource: Option<String>,
cursor: Option<String>,
}
#[derive(Deserialize, JsonSchema)]
struct ReadInstallationArgs {
#[serde(flatten)]
read: ReadArgs,
source: Option<InstallationSource>,
}
#[derive(Debug, Eq, JsonSchema, PartialEq, Serialize)]
#[schemars(deny_unknown_fields)]
struct ReadResponse<M> {
resource: String,
contents: String,
#[serde(flatten)]
metadata: M,
next_cursor: Option<String>,
}
#[derive(Clone, Debug, Eq, JsonSchema, PartialEq, Serialize)]
struct LegacyReadMetadata {
#[serde(skip_serializing_if = "Option::is_none")]
skill_root: Option<String>,
}
#[derive(Clone, Debug, Eq, JsonSchema, PartialEq, Serialize)]
struct InstallationReadMetadata {
installations: Vec<InstallationLocation>,
#[serde(skip_serializing_if = "std::ops::Not::not")]
installations_truncated: bool,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(untagged)]
enum ReadMetadata {
Legacy(LegacyReadMetadata),
Installations(InstallationReadMetadata),
}
#[derive(Clone)]
pub(super) struct ReadTool {
pub(super) context: SkillToolContext,
pub(super) metrics: Option<Arc<dyn ExtensionMetrics>>,
}
impl<'call> ToolExecutor<ToolCall<'call>> for ReadTool {
fn tool_name(&self) -> ToolName {
skill_tool_name(TOOL_NAME)
}
fn supports_parallel_tool_calls(&self) -> bool {
true
}
fn spec(&self) -> ToolSpec {
if !self.context.step_state.discovery_v2 {
return skill_function_tool::<ReadArgs, ReadResponse<LegacyReadMetadata>>(
TOOL_NAME,
"Read one page from a skill. Pass its provided package directly; root aliases are resolved automatically. Omit resource to read SKILL.md; to read another file, use the same package and pass the file's complete skill:// identifier as resource. For executor-backed skills, skill_root is the skill's absolute directory in the executor filesystem and can be used to locate bundled scripts. If the package is not provided, use skills.list to find it. Pass next_cursor back as cursor to continue the same snapshot while it is cached; omit cursor to read again.",
);
}
skill_function_tool::<ReadInstallationArgs, ReadResponse<InstallationReadMetadata>>(
TOOL_NAME,
"Read one page from a skill. Pass its provided package directly; root aliases are resolved automatically. Omit resource to read SKILL.md; to read another file, use the same package and pass the file's complete skill:// identifier as resource. Use source {kind: cloud} for Cloud or {kind: executor, environment_id: ...} for one environment. Omit source to read the first matching location. The installations list contains Cloud locators (package and resource, passed directly to skills.read) or executor locations (environment_id and skill_root, the absolute directory containing instructions and supporting files such as scripts). If installations_truncated is true, use skills.installations with the same package to retrieve all locations. If the package is not provided, use skills.list to find it. Pass next_cursor back as cursor with the same package, source, and resource to continue the same snapshot while it is cached; omit cursor to read again.",
)
}
fn handle<'a>(&'a self, call: ToolCall<'call>) -> ToolExecutorFuture<'a>
where
'call: 'a,
{
Box::pin(async move {
let mut outcome = "internal_error";
let result = async {
let (args, source) = if self.context.step_state.discovery_v2 {
let args: ReadInstallationArgs =
parse_args(&call).inspect_err(|_| outcome = "invalid_arguments")?;
(args.read, args.source)
} else {
(
parse_args::<ReadArgs>(&call)
.inspect_err(|_| outcome = "invalid_arguments")?,
None,
)
};
if let Some(source) = &source {
source
.validate()
.inspect_err(|_| outcome = "invalid_arguments")?;
}
let response_byte_budget = call.response_byte_budget(MAX_SKILL_RESPONSE_BYTES);
validate_handle("package", args.package.as_str(), MAX_HANDLE_BYTES)
.inspect_err(|_| outcome = "invalid_arguments")?;
if let Some(resource) = args.resource.as_deref() {
validate_handle("resource", resource, MAX_HANDLE_BYTES)
.inspect_err(|_| outcome = "invalid_arguments")?;
}
let matches = self
.context
.matching_packages(&args.package)
.inspect_err(|_| outcome = "ambiguous_name")?;
let (skill_entry, selected_source, output_authority) = matches
.iter()
.find_map(|(entry, matched_source)| {
let selected_source = match &source {
None => matched_source.clone(),
Some(filter) => std::iter::once(matched_source.clone())
.chain(entry.source_locations())
.find(|candidate| filter.matches(candidate))?,
};
let authority =
SkillToolAuthority::from_authority(&selected_source.authority)?
.selector();
Some((*entry, selected_source, authority))
})
.ok_or_else(|| {
outcome = if !matches.is_empty() {
"source_unavailable"
} else if args.package.alias_source().is_some()
&& self
.context
.step_state
.catalog
.aliases
.resolve(&args.package)
.is_none()
{
"unresolved_alias"
} else {
"package_unavailable"
};
FunctionCallError::RespondToModel(if source.is_some() {
"skill package is not available from the requested source".to_string()
} else {
"skill package is not available".to_string()
})
})?;
let authority = selected_source.authority.clone();
let package = selected_source.package.clone();
let main_prompt = selected_source.main_prompt.clone();
let requested_resource = match args.resource {
None => main_prompt.clone(),
Some(resource) if resource == main_prompt.as_str() => main_prompt.clone(),
Some(resource) => main_prompt
.bind_environment_package_resource(&package, resource.clone())
.unwrap_or_else(|| SkillResourceId::new(resource)),
};
// Record the selected route before either cache or provider can serve the read.
// This is an attempted read, not a successful invocation or a backend RPC.
tracing::event!(
name: "codex.skill_read.source_selected",
target: "codex_otel.trace_safe",
tracing::Level::INFO,
event.name = "codex.skill_read.source_selected",
conversation.id = %self.context.thread_id,
turn_id = %call.turn_id,
call_id = %call.call_id,
tool_namespace = SKILLS_NAMESPACE,
tool_name = TOOL_NAME,
skill_source = match output_authority {
SkillToolAuthoritySelector::Cloud => "cloud",
SkillToolAuthoritySelector::Executor => "executor",
},
skill_name = %skill_entry.name,
skill_plugin_id = selected_source.plugin_id.as_deref(),
skill_resource_kind = if requested_resource == main_prompt {
"main_prompt"
} else {
"supporting_resource"
},
is_continuation = args.cursor.is_some(),
"Selected skill read source"
);
let (context, access_key) = match output_authority {
SkillToolAuthoritySelector::Cloud => (
SkillReadContext::Cloud {
mcp_resources: self.context.mcp_resources.clone(),
},
None,
),
SkillToolAuthoritySelector::Executor => {
let fs = requested_resource
.environment_path()
.and_then(|(id, _)| {
call.environments
.iter()
.find(|env| env.environment_id == id)
})
.map(codex_extension_api::ToolEnvironment::fs)
.ok_or_else(|| {
outcome = "environment_unavailable";
FunctionCallError::RespondToModel(
"skill environment is not available for this callback"
.to_string(),
)
})?;
(SkillReadContext::Executor { fs }, Some(fs.cache_key()))
}
};
let cursor_start = |contents: &str| {
if self.context.step_state.discovery_v2 {
parse_pagination_cursor(
args.cursor.as_deref(),
&(&source, &package, contents),
"skills.read",
)
} else {
parse_pagination_cursor(args.cursor.as_deref(), contents, "skills.read")
}
};
// Reuse the snapshot to avoid reading the whole file for each page. File edits
// are not detected on cache hits, so a continuation can return old contents.
// Snapshots have no expiry and are not cleared after the final page.
let cached = args.cursor.as_deref().and_then(|_| {
let access = access_key.as_ref()?;
let snapshot = self
.context
.thread_state
.executor_read_snapshot
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let snapshot = snapshot.as_ref().filter(|snapshot| {
snapshot.authority == authority
&& snapshot.package == package
&& snapshot.result.resource == requested_resource
&& snapshot.access == *access
})?;
let start = cursor_start(&snapshot.result.contents).ok()?;
Some((Arc::clone(&snapshot.result), start))
});
let (result, start) = match cached {
Some(cached) => cached,
None => {
let result = self
.context
.thread_state
.read_skill(
&self.context.providers,
SkillReadRequest {
authority: authority.clone(),
package: package.clone(),
resource: requested_resource.clone(),
context,
},
)
.await
.map_err(|err| {
outcome = "read_failed";
tracing::warn!(
error = %err,
turn_id = %call.turn_id,
call_id = %call.call_id,
resource = requested_resource.as_str(),
"skills.read provider request failed"
);
FunctionCallError::RespondToModel(
"failed to read skill resource".to_string(),
)
})?;
if result.resource != requested_resource {
return Err(FunctionCallError::Fatal(
"skill provider returned a different resource".to_string(),
));
}
let start = cursor_start(&result.contents)
.inspect_err(|_| outcome = "invalid_cursor")?;
(Arc::new(result), start)
}
};
if start > result.contents.len() || !result.contents.is_char_boundary(start) {
outcome = "invalid_cursor";
return Err(FunctionCallError::RespondToModel(
"skills.read cursor is invalid".to_string(),
));
}
// Shadow candidates use the merged identity, not the selected read route.
if skill_entry.authority.kind == SkillSourceKind::Cloud
&& let Some(state) = self
.context
.thread_state
.shadow_selection_turn(&call.turn_id)
{
state.record_invocation(skill_entry.main_prompt.as_str());
}
let metadata = if self.context.step_state.discovery_v2 {
let mut installations = Vec::new();
let mut installations_truncated = false;
let mut installation_bytes = 2; // JSON array brackets.
let installation_budget =
MAX_INSTALLATION_METADATA_BYTES.min(response_byte_budget / 4);
// Prefer the installation used by this read before other sources fill the budget.
for source in std::iter::once(selected_source.clone())
.chain(skill_entry.source_locations())
{
let Some(installation) = InstallationLocation::from_source(&source) else {
continue;
};
if installations.contains(&installation) {
continue;
}
let size =
serialized_len(&installation)? + usize::from(!installations.is_empty());
if installation_bytes + size > installation_budget {
installations_truncated = true;
continue;
}
installation_bytes += size;
installations.push(installation);
}
installations_truncated |= matches.iter().any(|(entry, _)| {
entry
.source_locations()
.filter_map(|source| InstallationLocation::from_source(&source))
.any(|location| !installations.contains(&location))
});
ReadMetadata::Installations(InstallationReadMetadata {
installations,
installations_truncated,
})
} else {
let skill_root = if output_authority == SkillToolAuthoritySelector::Executor {
main_prompt
.environment_path()
.and_then(|(_, path)| path.parent())
.map(|path| path.inferred_native_path_string())
} else {
None
};
ReadMetadata::Legacy(LegacyReadMetadata { skill_root })
};
let response = page_response(
result.resource.as_str(),
&result.contents,
&metadata,
start,
response_byte_budget,
|offset| {
if self.context.step_state.discovery_v2 {
pagination_cursor(
&(&source, &package, result.contents.as_str()),
offset,
)
} else {
pagination_cursor(result.contents.as_str(), offset)
}
},
)
.inspect_err(|error| {
outcome = match error {
FunctionCallError::RespondToModel(_) => "response_budget",
FunctionCallError::Fatal(_) => "internal_error",
};
})?;
let response_authority = if matches!(
&response.metadata,
ReadMetadata::Installations(metadata)
if metadata.installations.iter().any(|location| {
matches!(location, InstallationLocation::Cloud { .. })
})
) {
SkillToolAuthoritySelector::Cloud
} else {
output_authority
};
let output = skill_json_output(&response, response_authority)?;
if output_authority == super::SkillToolAuthoritySelector::Executor
&& response.next_cursor.is_some()
&& result.contents.len() <= MAX_SKILL_RESOURCE_CONTENT_BYTES
&& let Some(access) = access_key
{
*self
.context
.thread_state
.executor_read_snapshot
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) =
Some(ExecutorReadSnapshot {
authority,
package,
access,
result,
});
}
if requested_resource == main_prompt
&& args.cursor.is_none()
&& let Some(analytics) = self.context.analytics.as_ref()
{
analytics.track_skill_invocation(
skill_entry,
&selected_source,
call.model.clone(),
call.turn_id.clone(),
InvocationType::Implicit,
);
}
outcome = "success";
Ok(output)
}
.await;
if let Some(metrics) = &self.metrics {
metrics.counter(
"codex.skills.read.result",
/*inc*/ 1,
&[
("outcome", outcome),
(
"discovery_version",
if self.context.step_state.discovery_v2 {
"v2"
} else {
"v1"
},
),
],
);
}
result
})
}
}
fn page_response(
resource: &str,
contents: &str,
metadata: &ReadMetadata,
start: usize,
max_response_bytes: usize,
cursor_at: impl Fn(usize) -> String,
) -> Result<ReadResponse<ReadMetadata>, FunctionCallError> {
let response = |end, next_cursor| ReadResponse {
resource: resource.to_string(),
contents: contents[start..end].to_string(),
metadata: metadata.clone(),
next_cursor,
};
let complete = response(contents.len(), None);
if serialized_len(&complete)? <= max_response_bytes {
return Ok(complete);
}
let mut lower = start;
let mut upper = contents.len();
let mut best = None;
while lower < upper {
// Probe strictly above lower so a multibyte character cannot stall the search.
let end = contents.ceil_char_boundary(lower.midpoint(upper).saturating_add(1));
let candidate = response(end, Some(cursor_at(end)));
if serialized_len(&candidate)? <= max_response_bytes {
lower = end;
best = Some(candidate);
} else {
upper = contents.floor_char_boundary(end.saturating_sub(1));
}
}
best.ok_or_else(|| {
FunctionCallError::RespondToModel(
"skills.read response budget leaves no room for contents".to_string(),
)
})
}

View File

@@ -0,0 +1,42 @@
use schemars::JsonSchema;
use schemars::r#gen::SchemaSettings;
use serde_json::Map;
use serde_json::Value;
pub(super) fn input_schema_for<T: JsonSchema>() -> Value {
schema_for::<T>(/*option_add_null_type*/ false)
}
pub(super) fn output_schema_for<T: JsonSchema>() -> Value {
schema_for::<T>(/*option_add_null_type*/ true)
}
fn schema_for<T: JsonSchema>(option_add_null_type: bool) -> Value {
let schema = SchemaSettings::draft2019_09()
.with(|settings| {
settings.inline_subschemas = true;
settings.option_add_null_type = option_add_null_type;
})
.into_generator()
.into_root_schema_for::<T>();
let schema_value = serde_json::to_value(schema)
.unwrap_or_else(|err| panic!("generated skill tool schema should serialize: {err}"));
let Value::Object(mut schema_object) = schema_value else {
unreachable!("root tool schema must be an object");
};
let mut tool_schema = Map::new();
for key in [
"properties",
"required",
"type",
"additionalProperties",
"$defs",
"definitions",
] {
if let Some(value) = schema_object.remove(key) {
tool_schema.insert(key.to_string(), value);
}
}
Value::Object(tool_schema)
}

View File

@@ -0,0 +1,12 @@
use crate::render::truncate_utf8_to_bytes;
const MAX_WARNINGS: usize = 4;
const MAX_WARNING_BYTES: usize = 256;
pub(crate) fn bounded_warnings(warnings: &[String]) -> Vec<String> {
warnings
.iter()
.take(MAX_WARNINGS)
.map(|warning| truncate_utf8_to_bytes(warning, MAX_WARNING_BYTES).0)
.collect()
}

View File

@@ -0,0 +1,242 @@
use codex_extension_api::PreviousWorldStateSection;
use codex_extension_api::RenderedWorldStateFragment;
use codex_extension_api::WorldStateSectionContribution;
use codex_protocol::models::ContentItemMetadata;
use codex_protocol::models::input_text;
use codex_protocol::protocol::SKILLS_INSTRUCTIONS_CLOSE_TAG;
use codex_protocol::protocol::SKILLS_INSTRUCTIONS_OPEN_TAG;
use serde::Serialize;
use serde_json::json;
use crate::render::SkillRenderReport;
use crate::world_state_catalogs::CatalogBudgetAllocation;
pub(crate) const SKILLS_WORLD_STATE_ID: &str = "skills";
pub(crate) const CLOUD_SKILLS_WORLD_STATE_ID: &str = "cloud_skills";
pub(crate) const HOST_SKILLS_WORLD_STATE_ID: &str = "host_skills";
const NO_EXECUTOR_SKILLS_BODY: &str =
"\n## Skills update\nNo selected-environment skills are currently available.\n";
const HIDDEN_EXECUTOR_SKILLS_BODY: &str = "\n## Skills update\nSelected-environment skills are not listed automatically. Explicit skill mentions can still be resolved when available.\n";
const NO_CLOUD_SKILLS_BODY: &str =
"\n## Cloud skills update\nNo cloud skills are currently available.\n";
const HIDDEN_CLOUD_SKILLS_BODY: &str = "\n## Cloud skills update\nCloud skills are not listed automatically. Explicit skill mentions can still be resolved when available.\n";
const NO_HOST_SKILLS_BODY: &str =
"\n## Host skills update\nNo host skills are currently available.\n";
const HIDDEN_HOST_SKILLS_BODY: &str = "\n## Host skills update\nHost skills are not listed automatically. Explicit skill mentions can still be resolved when available.\n";
const OMITTED_HOST_SKILLS_BODY: &str = "\n## Host skills update\nHost skills are available but omitted from the model-visible skills list because the skills context budget was exceeded.\n";
pub(crate) type CatalogRenderCallback = Box<dyn Fn() + Send + Sync>;
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct CatalogSnapshot {
body: Option<String>,
include_instructions: bool,
#[serde(skip_serializing_if = "Option::is_none")]
enabled: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
allocation: Option<CatalogBudgetAllocation>,
}
pub(crate) fn executor_skills_world_state_section(
body: Option<String>,
include_instructions: bool,
previous_snapshot: Option<&serde_json::Value>,
on_render: CatalogRenderCallback,
) -> WorldStateSectionContribution {
// Remember display history, not execution authority. Discovery still determines `body`
// on every step, including when no selected-environment skills are available.
let last_available_fingerprint = previous_snapshot
.filter(|_| body.is_none() && include_instructions)
.and_then(|previous| {
previous
.get("body")
.and_then(serde_json::Value::as_str)
.map(|body| blake3::hash(body.as_bytes()).to_hex().to_string())
.or_else(|| {
previous
.get("lastAvailableFingerprint")
.and_then(serde_json::Value::as_str)
.map(str::to_string)
})
});
let snapshot = json!({
"body": body,
"includeInstructions": include_instructions,
"lastAvailableFingerprint": last_available_fingerprint,
});
let retained_body = body.clone();
let contribution = WorldStateSectionContribution::new(SKILLS_WORLD_STATE_ID, move |previous| {
if let PreviousWorldStateSection::Known(previous) = &previous
&& previous.get("includeInstructions").and_then(serde_json::Value::as_bool)
== Some(include_instructions)
{
if previous.get("body").and_then(serde_json::Value::as_str) == body.as_deref() {
return (Some(snapshot.clone()), None);
}
if let Some(body) = body.as_deref()
&& previous.get("lastAvailableFingerprint").and_then(serde_json::Value::as_str)
== Some(blake3::hash(body.as_bytes()).to_hex().as_str())
{
return (
Some(snapshot.clone()),
Some(RenderedWorldStateFragment::new(
"developer",
(SKILLS_INSTRUCTIONS_OPEN_TAG, SKILLS_INSTRUCTIONS_CLOSE_TAG),
input_text("\n## Skills update\nThe previously listed selected-environment skills are available again.\n".to_string()),
).with_metadata(ContentItemMetadata::skills())),
);
}
}
let body = match body.as_deref() {
Some(body) => body,
None if matches!(previous, PreviousWorldStateSection::Absent) => {
return (Some(snapshot.clone()), None);
}
None if !include_instructions => HIDDEN_EXECUTOR_SKILLS_BODY,
None => NO_EXECUTOR_SKILLS_BODY,
};
on_render();
(
Some(snapshot.clone()),
Some(RenderedWorldStateFragment::new(
"developer",
(SKILLS_INSTRUCTIONS_OPEN_TAG, SKILLS_INSTRUCTIONS_CLOSE_TAG),
input_text(body.to_string()),
).with_metadata(ContentItemMetadata::skills())),
)
})
.with_legacy_matcher(|role, text| {
role == "developer"
&& text.trim_start().starts_with(SKILLS_INSTRUCTIONS_OPEN_TAG)
&& text.trim_end().ends_with(SKILLS_INSTRUCTIONS_CLOSE_TAG)
});
// A short availability update is valid only while the actual catalog remains in history.
match retained_body {
Some(body) => contribution.with_retained_fragment_matcher(move |role, text| {
role == "developer" && text.contains(&body)
}),
None => contribution,
}
}
pub(crate) fn cloud_skills_world_state_section(
body: Option<String>,
include_instructions: bool,
enabled: bool,
allocation: CatalogBudgetAllocation,
on_render: CatalogRenderCallback,
) -> WorldStateSectionContribution {
skills_world_state_section(
CLOUD_SKILLS_WORLD_STATE_ID,
CatalogSnapshot {
body,
include_instructions,
enabled: Some(enabled),
allocation: Some(allocation),
},
NO_CLOUD_SKILLS_BODY,
if enabled {
HIDDEN_CLOUD_SKILLS_BODY
} else {
NO_CLOUD_SKILLS_BODY
},
on_render,
)
}
fn skills_world_state_section(
id: &'static str,
state: CatalogSnapshot,
no_skills_body: &'static str,
hidden_skills_body: &'static str,
on_render: CatalogRenderCallback,
) -> WorldStateSectionContribution {
let snapshot = json!(&state);
let CatalogSnapshot {
body,
include_instructions,
enabled,
..
} = state;
let retained_body = body.clone();
let contribution = WorldStateSectionContribution::new(id, move |previous| {
if let PreviousWorldStateSection::Known(previous) = &previous {
let previous_body = previous.get("body").and_then(serde_json::Value::as_str);
let previous_include_instructions = previous
.get("includeInstructions")
.and_then(serde_json::Value::as_bool);
let previous_enabled = previous.get("enabled").and_then(serde_json::Value::as_bool);
if previous_body == body.as_deref()
&& previous_include_instructions == Some(include_instructions)
&& previous_enabled == enabled
{
return (Some(snapshot.clone()), None);
}
}
let body = match body.as_deref() {
Some(body) => body,
None if matches!(previous, PreviousWorldStateSection::Absent) => {
return (Some(snapshot.clone()), None);
}
None if !include_instructions => hidden_skills_body,
None => no_skills_body,
};
on_render();
(
Some(snapshot.clone()),
Some(
RenderedWorldStateFragment::new(
"developer",
(SKILLS_INSTRUCTIONS_OPEN_TAG, SKILLS_INSTRUCTIONS_CLOSE_TAG),
input_text(body.to_string()),
)
.with_metadata(ContentItemMetadata::skills()),
),
)
});
match retained_body {
Some(body) => contribution.with_retained_fragment_matcher(move |role, text| {
role == "developer" && text.contains(&body)
}),
None => contribution,
}
}
pub(crate) fn host_skills_world_state_section(
body: Option<String>,
include_instructions: bool,
report: &SkillRenderReport,
on_render: CatalogRenderCallback,
) -> WorldStateSectionContribution {
let body = body.or_else(|| {
(report.included_count == 0 && report.omitted_count > 0)
.then(|| OMITTED_HOST_SKILLS_BODY.to_string())
});
let retained_fragment = body
.as_ref()
.map(|body| format!("{SKILLS_INSTRUCTIONS_OPEN_TAG}{body}{SKILLS_INSTRUCTIONS_CLOSE_TAG}"));
let contribution = skills_world_state_section(
HOST_SKILLS_WORLD_STATE_ID,
CatalogSnapshot {
body,
include_instructions,
enabled: None,
allocation: None,
},
NO_HOST_SKILLS_BODY,
HIDDEN_HOST_SKILLS_BODY,
on_render,
);
match retained_fragment {
Some(fragment) => contribution.with_retained_fragment_matcher(move |role, text| {
role == "developer" && text.contains(&fragment)
}),
None => contribution,
}
}

View File

@@ -0,0 +1,533 @@
//! Renders prepared step catalogs without performing discovery or changing tool readiness.
use std::sync::Arc;
use codex_extension_api::ContextualUserFragment;
use codex_extension_api::ExtensionEventSink;
use codex_extension_api::ExtensionWarning;
use codex_extension_api::WorldStateContributionInput;
use codex_extension_api::WorldStateSectionContribution;
use serde::Deserialize;
use serde::Serialize;
use crate::catalog::SkillCatalog;
use crate::catalog_delta::CatalogDelta;
use crate::catalog_delta::CatalogUsage;
use crate::catalog_delta::skills_delta_section;
use crate::render::AvailableSkillsRender;
use crate::render::PreparedSkillCatalog;
use crate::render::RenderedSkillCatalogs;
use crate::render::SkillCatalogRenderPolicy;
use crate::render::SkillMetadataBudget;
use crate::render::render_available_skills;
use crate::render::render_prepared_skill_catalogs;
use crate::render::skill_metadata_budget;
use crate::render_observability::CatalogSurface;
use crate::render_observability::record_catalog_render;
use crate::state::EmittedCatalogBudgetWarnings;
use crate::state::HostSkillsCatalogInWorldState;
use crate::step_state::CatalogStatus;
use crate::step_state::SkillToolAuthoritySelector;
use crate::step_state::SkillsStepState;
use crate::world_state::CatalogRenderCallback;
use crate::world_state::cloud_skills_world_state_section;
use crate::world_state::executor_skills_world_state_section;
use crate::world_state::host_skills_world_state_section;
// Start with one quarter reserved for filesystem skills, before their inventory is known.
const FILESYSTEM_BUDGET_DIVISOR: usize = 4;
/// A display allocation retained across executor readiness changes and thread resume.
/// A changed cloud catalog or total budget starts a new allocation. Within that
/// allocation, filesystem pressure can only shrink the cloud cap.
#[derive(Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct CatalogBudgetAllocation {
total_budget: SkillMetadataBudget,
cloud_limit: usize,
cloud_catalog_fingerprint: [u8; 32],
}
type CatalogWarningEmitter = Arc<dyn Fn(String) + Send + Sync>;
#[derive(Clone, Copy, Eq, PartialEq)]
enum CatalogKind {
Executor,
Cloud,
Host,
}
impl CatalogKind {
fn metrics_surface(self) -> CatalogSurface {
match self {
Self::Executor => CatalogSurface::ExecutorWorldState,
Self::Cloud => CatalogSurface::CloudWorldState,
Self::Host => CatalogSurface::HostWorldState,
}
}
}
struct CatalogContribution {
catalog: SkillCatalog,
status: CatalogStatus,
}
impl CatalogContribution {
fn unavailable() -> Self {
Self {
catalog: SkillCatalog::default(),
status: CatalogStatus::Unavailable,
}
}
}
struct CatalogContributions {
executor: CatalogContribution,
cloud: CatalogContribution,
host: CatalogContribution,
}
struct RenderedCatalogContribution {
kind: CatalogKind,
status: CatalogStatus,
budget: SkillMetadataBudget,
allocation: CatalogBudgetAllocation,
rendered: Option<AvailableSkillsRender>,
}
struct CatalogRenderingContext<'a> {
input: WorldStateContributionInput<'a>,
step_state: Arc<SkillsStepState>,
metadata_budget: SkillMetadataBudget,
render_policy: SkillCatalogRenderPolicy,
include_usage: bool,
warning_emitter: CatalogWarningEmitter,
}
impl<'a> CatalogRenderingContext<'a> {
fn new(
event_sink: Arc<dyn ExtensionEventSink>,
input: WorldStateContributionInput<'a>,
) -> Option<Self> {
let step_state = input.step_store.get::<SkillsStepState>()?;
let include_usage = input.model_info.include_skills_usage_instructions;
let context_window = input.model_info.resolved_context_window();
let metadata_budget =
skill_metadata_budget(context_window, step_state.config.max_context_tokens);
let emitted_warnings = input
.turn_store
.get_or_init(EmittedCatalogBudgetWarnings::default);
let thread_id = input.thread_store.level_id().to_string();
let turn_id = input.turn_id.to_string();
let warning_emitter: CatalogWarningEmitter = Arc::new(move |message| {
if emitted_warnings.insert(&message) {
event_sink.emit_warning(ExtensionWarning {
thread_id: thread_id.clone(),
turn_id: Some(turn_id.clone()),
message,
});
}
});
let render_policy = if step_state.discovery_v2 {
SkillCatalogRenderPolicy::DISCOVERY_V2
} else {
SkillCatalogRenderPolicy::EXTENSION_COMPATIBLE
}
.with_omitted_descriptions(step_state.config.omit_descriptions);
Some(Self {
input,
step_state,
metadata_budget,
render_policy,
include_usage,
warning_emitter,
})
}
fn render_world_state_catalogs(&self) -> [RenderedCatalogContribution; 3] {
let catalogs = CatalogContributions {
executor: CatalogContribution {
catalog: self
.step_state
.catalog
.select_from_catalog(SkillToolAuthoritySelector::Executor),
status: CatalogStatus::Enabled,
},
cloud: CatalogContribution {
catalog: self
.step_state
.catalog
.select_from_catalog(SkillToolAuthoritySelector::Cloud),
status: self.step_state.cloud_status,
},
host: self.step_state.host_catalog.as_ref().map_or_else(
CatalogContribution::unavailable,
|catalog| CatalogContribution {
catalog: catalog.clone(),
status: CatalogStatus::Enabled,
},
),
};
let total_limit = self.metadata_budget.limit();
let default_cloud_limit = total_limit - total_limit / FILESYSTEM_BUDGET_DIVISOR;
let executor_aliases = Some(
self.step_state
.catalog
.aliases
.for_authority(SkillToolAuthoritySelector::Executor),
);
let mut executor = PreparedSkillCatalog::with_alias_plan(
&catalogs.executor.catalog,
self.render_policy,
executor_aliases,
);
executor.prefer_cloud_skills(&catalogs.cloud.catalog);
// Identify the full visible cloud inventory before budgeting, including entries
// a previous cap omitted. Executor readiness and provider warnings are not inputs.
let cloud_metadata = catalogs
.cloud
.catalog
.entries
.iter()
.filter(|entry| entry.is_model_visible())
.map(|entry| {
(
&entry.id.0,
entry.authority.kind.to_string(),
&entry.name,
self.render_policy.description(entry),
entry.rendered_path(),
entry.alias_root(),
entry.alias_root_order(),
)
})
.collect::<Vec<_>>();
let cloud_catalog_fingerprint =
*blake3::hash(serde_json::json!(cloud_metadata).to_string().as_bytes()).as_bytes();
let mut allocation = self
.input
.previous_world_state
.and_then(|state| state.get(crate::world_state::CLOUD_SKILLS_WORLD_STATE_ID))
.and_then(|snapshot| snapshot.get("allocation"))
.and_then(|value| serde_json::from_value::<CatalogBudgetAllocation>(value.clone()).ok())
.filter(|previous| {
previous.total_budget == self.metadata_budget
&& previous.cloud_catalog_fingerprint == cloud_catalog_fingerprint
})
.unwrap_or(CatalogBudgetAllocation {
total_budget: self.metadata_budget,
cloud_limit: default_cloud_limit,
cloud_catalog_fingerprint,
});
allocation.cloud_limit = allocation.cloud_limit.min(default_cloud_limit);
let (mut rendered, mut filesystem_budget) =
self.render_with_cloud_limit(&catalogs, &executor, allocation.cloud_limit);
if let Some(cloud_limit) = self.rebalance_to_retain_all_skills(
&catalogs,
&executor,
&rendered,
allocation.cloud_limit,
) {
allocation.cloud_limit = cloud_limit;
(rendered, filesystem_budget) =
self.render_with_cloud_limit(&catalogs, &executor, allocation.cloud_limit);
}
if self.step_state.config.catalog_deltas_enabled {
let cloud = PreparedSkillCatalog::with_alias_plan(
&catalogs.cloud.catalog,
self.render_policy,
Some(
self.step_state
.catalog
.aliases
.for_authority(SkillToolAuthoritySelector::Cloud),
),
);
let host = PreparedSkillCatalog::new(
&catalogs.host.catalog,
SkillCatalogRenderPolicy::CORE_COMPATIBLE
.with_omitted_descriptions(self.step_state.config.omit_descriptions),
);
let grants = self
.input
.step_store
.get::<crate::TurnSkillFilesystemGrants>();
let primary_environment = self
.input
.environments
.first()
.map(|selection| selection.environment_id.as_str());
for (catalog, rendered) in [
(&executor, &mut rendered.executor),
(&cloud, &mut rendered.cloud),
(&host, &mut rendered.host),
] {
if let Some(rendered) = rendered {
rendered.entries = catalog.entries_for_render(
rendered,
grants.as_deref(),
primary_environment,
);
}
}
}
[
(CatalogKind::Executor, catalogs.executor, rendered.executor),
(CatalogKind::Cloud, catalogs.cloud, rendered.cloud),
(CatalogKind::Host, catalogs.host, rendered.host),
]
.map(|(kind, catalog, rendered)| RenderedCatalogContribution {
kind,
status: catalog.status,
budget: match kind {
CatalogKind::Cloud => self.metadata_budget.with_limit(allocation.cloud_limit),
CatalogKind::Executor | CatalogKind::Host => filesystem_budget,
},
allocation,
rendered,
})
}
/// Propose a smaller cloud cap only when omitted filesystem entries can fit without
/// losing any cloud entries. Description truncation alone never triggers rebalancing.
/// Within one cloud catalog and total budget, the cap can only shrink, so VM
/// disappearance does not expand the catalog.
fn rebalance_to_retain_all_skills(
&self,
catalogs: &CatalogContributions,
executor: &PreparedSkillCatalog<'_>,
rendered: &RenderedSkillCatalogs,
current_cloud_limit: usize,
) -> Option<usize> {
if ![&rendered.executor, &rendered.host]
.into_iter()
.flatten()
.any(|catalog| catalog.report.omitted_count > 0)
{
return None;
}
let cloud_aliases = Some(
self.step_state
.catalog
.aliases
.for_authority(SkillToolAuthoritySelector::Cloud),
);
let shared = render_prepared_skill_catalogs(
executor,
&PreparedSkillCatalog::with_alias_plan(
&catalogs.cloud.catalog,
self.render_policy,
cloud_aliases,
),
&PreparedSkillCatalog::new(
&catalogs.host.catalog,
SkillCatalogRenderPolicy::CORE_COMPATIBLE
.with_omitted_descriptions(self.step_state.config.omit_descriptions),
),
self.metadata_budget,
self.include_usage,
);
if [&shared.executor, &shared.cloud, &shared.host]
.into_iter()
.flatten()
.any(|catalog| catalog.report.omitted_count > 0)
{
return None;
}
let cloud_limit = shared.cloud.as_ref().map_or(0, |cloud| {
cloud.metadata_cost(self.metadata_budget, self.include_usage)
});
(cloud_limit < current_cloud_limit).then_some(cloud_limit)
}
/// Render the same buckets both before and after adjusting the allocation, so
/// the accepted cloud text is reproduced exactly on the next sampling step.
fn render_with_cloud_limit(
&self,
catalogs: &CatalogContributions,
executor: &PreparedSkillCatalog<'_>,
cloud_limit: usize,
) -> (RenderedSkillCatalogs, SkillMetadataBudget) {
if !self.step_state.config.include_instructions {
return (RenderedSkillCatalogs::default(), self.metadata_budget);
}
let cloud_aliases = Some(
self.step_state
.catalog
.aliases
.for_authority(SkillToolAuthoritySelector::Cloud),
);
let cloud_budget = self.metadata_budget.with_limit(cloud_limit);
let cloud = render_available_skills(
&catalogs.cloud.catalog,
self.render_policy,
cloud_budget,
self.include_usage,
cloud_aliases,
);
// Empty or disabled cloud catalogs leave the full allowance to filesystem skills.
let cloud_cost = cloud.as_ref().map_or(0, |rendered| {
rendered.metadata_cost(cloud_budget, self.include_usage)
});
let filesystem_budget = self
.metadata_budget
.with_limit(self.metadata_budget.limit().saturating_sub(cloud_cost));
let mut rendered = render_prepared_skill_catalogs(
executor,
&PreparedSkillCatalog::new(&SkillCatalog::default(), self.render_policy),
&PreparedSkillCatalog::new(
&catalogs.host.catalog,
SkillCatalogRenderPolicy::CORE_COMPATIBLE
.with_omitted_descriptions(self.step_state.config.omit_descriptions),
),
filesystem_budget,
self.include_usage,
);
rendered.cloud = cloud;
(rendered, filesystem_budget)
}
fn build_world_state_section(
&self,
catalog: RenderedCatalogContribution,
remaining: &mut SkillMetadataBudget,
) -> WorldStateSectionContribution {
let RenderedCatalogContribution {
kind,
status,
budget,
allocation,
rendered,
} = catalog;
let report = rendered
.as_ref()
.map(|rendered| rendered.report.clone())
.unwrap_or_default();
let include_instructions = self.step_state.config.include_instructions;
let catalog_deltas_enabled = self.step_state.config.catalog_deltas_enabled;
let metrics = self.input.extension_metrics.clone();
let warning_emitter = Arc::clone(&self.warning_emitter);
let on_render = move |render_report: &crate::render::SkillRenderReport| {
if !include_instructions || status != CatalogStatus::Enabled {
return;
}
record_catalog_render(
metrics.as_deref(),
kind.metrics_surface(),
budget,
render_report,
);
if let Some(message) = render_report.warning_message(catalog_deltas_enabled) {
warning_emitter(message);
}
};
if catalog_deltas_enabled {
let (id, source) = match kind {
CatalogKind::Executor => (
crate::world_state::SKILLS_WORLD_STATE_ID,
"Selected-environment",
),
CatalogKind::Cloud => (crate::world_state::CLOUD_SKILLS_WORLD_STATE_ID, "Cloud"),
CatalogKind::Host => {
if status != CatalogStatus::Unavailable {
self.input.turn_store.insert(HostSkillsCatalogInWorldState);
}
(crate::world_state::HOST_SKILLS_WORLD_STATE_ID, "Host")
}
};
return skills_delta_section(
id,
source,
CatalogDelta {
rendered,
include_usage: self.include_usage,
tracks_grants: kind != CatalogKind::Cloud,
allocation: (kind == CatalogKind::Cloud).then_some(allocation),
},
self.input
.previous_world_state
.and_then(|state| state.get(id)),
remaining,
on_render,
);
}
let body = rendered
.and_then(|rendered| rendered.into_fragment(self.include_usage))
.map(|fragment| fragment.body().into_text().unwrap_or_default());
let render_report = report.clone();
let on_render: CatalogRenderCallback = Box::new(move || on_render(&render_report));
match kind {
CatalogKind::Executor => executor_skills_world_state_section(
body,
include_instructions,
self.input
.previous_world_state
.and_then(|state| state.get(crate::world_state::SKILLS_WORLD_STATE_ID)),
on_render,
),
CatalogKind::Cloud => cloud_skills_world_state_section(
body,
include_instructions,
status == CatalogStatus::Enabled,
allocation,
on_render,
),
CatalogKind::Host => {
self.input.turn_store.insert(HostSkillsCatalogInWorldState);
host_skills_world_state_section(body, include_instructions, &report, on_render)
}
}
}
}
/// Renders catalog sections, retaining empty delta snapshots for shared budget accounting.
pub(crate) fn render_world_state_sections(
event_sink: Arc<dyn ExtensionEventSink>,
input: WorldStateContributionInput<'_>,
) -> Vec<WorldStateSectionContribution> {
let Some(context) = CatalogRenderingContext::new(event_sink, input) else {
return Vec::new();
};
let used = context
.input
.previous_world_state
.into_iter()
.flat_map(|state| {
[
crate::world_state::SKILLS_WORLD_STATE_ID,
crate::world_state::CLOUD_SKILLS_WORLD_STATE_ID,
crate::world_state::HOST_SKILLS_WORLD_STATE_ID,
]
.into_iter()
.filter_map(|id| state.get(id))
})
.filter_map(|snapshot| snapshot.get("usage"))
.filter_map(|usage| CatalogUsage::deserialize(usage).ok())
.map(|usage| usage.cost(context.metadata_budget))
.sum::<usize>();
let mut remaining = context
.metadata_budget
.with_limit(context.metadata_budget.limit().saturating_sub(used));
context
.render_world_state_catalogs()
.into_iter()
// Keep empty snapshots too: a source that becomes available later must use
// the same remaining budget instead of publishing another initial catalog.
.filter(|catalog| {
context.step_state.config.catalog_deltas_enabled
|| catalog.status != CatalogStatus::Unavailable
})
.map(|catalog| context.build_world_state_section(catalog, &mut remaining))
.collect()
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,347 @@
//! Multi-source budgeting and feature rollback through the skills extension.
use super::*;
use pretty_assertions::assert_eq;
#[tokio::test]
async fn skill_sources_spend_the_same_remaining_budget() -> TestResult {
let mut previous = serde_json::Map::new();
let enabled = TestConfig {
catalog_deltas_enabled: true,
..default_config()
};
render_catalogs(&[], &enabled, &mut previous).await?;
// One release-notes row fits the 100-token budget. The larger entry sorts first.
let large = "Detailed architectural guidance. ".repeat(40);
let small = "Draft release notes. ".repeat(9);
let entries = [
("architecture-review", large.as_str()),
("release-notes", small.as_str()),
];
let emitted = render_catalogs(&entries, &enabled, &mut previous).await?;
assert_eq!(
emitted
.lines()
.filter(|line| line.starts_with("- ") && line.contains("release-notes"))
.count(),
1
);
assert!(emitted.contains("- executor-release-notes:"), "{emitted}");
assert!(!emitted.contains("architecture-review"), "{emitted}");
let used = previous
.values()
.filter_map(|s| s["usage"]["tokens"].as_u64())
.sum::<u64>();
assert!((50..=100).contains(&used), "{used}");
let edited = [
("architecture-review", "Review architecture."),
("release-notes", small.as_str()),
];
assert_eq!(render_catalogs(&edited, &enabled, &mut previous).await?, "");
let disabled = default_config();
let empty = render_catalogs(&[], &disabled, &mut previous).await?;
assert!(empty.contains("skills are currently available"), "{empty}");
assert_eq!(render_catalogs(&[], &disabled, &mut previous).await?, "");
let omitted = TestConfig {
omit_descriptions: true,
..enabled
};
previous.clear();
let emitted =
render_catalogs(&[("notes", "Hidden description.")], &enabled, &mut previous).await?;
assert!(emitted.contains("description shown above"), "{emitted}");
assert!(
emitted.contains("- host-notes: Hidden description."),
"{emitted}"
);
// Resume a snapshot written before the description policy was persisted.
for snapshot in previous.values_mut() {
snapshot.as_object_mut().unwrap().remove("omitDescriptions");
}
let emitted =
render_catalogs(&[("notes", "Hidden description.")], &omitted, &mut previous).await?;
assert!(
emitted.contains("OR the task clearly matches a skill's name shown above, you must use that skill for that turn."),
"{emitted}"
);
assert!(emitted.contains("- executor-notes: "), "{emitted}");
assert!(!emitted.contains("Hidden description."), "{emitted}");
assert_eq!(
render_catalogs(&[("notes", "Edited description.")], &omitted, &mut previous).await?,
""
);
// A policy change still refreshes instructions when no more rows fit the budget.
let emitted =
render_catalogs(&[("notes", "Edited description.")], &enabled, &mut previous).await?;
assert!(emitted.contains("description shown above"), "{emitted}");
assert!(!emitted.contains("- executor-notes:"), "{emitted}");
assert!(!emitted.contains("- cloud-notes:"), "{emitted}");
assert!(!emitted.contains("- host-notes:"), "{emitted}");
assert_eq!(
render_catalogs(&[("notes", "Edited description.")], &enabled, &mut previous).await?,
""
);
Ok(())
}
#[tokio::test]
async fn grant_expiry_withdraws_only_missing_skills_when_metadata_budget_is_exhausted() -> TestResult
{
let enabled = TestConfig {
catalog_deltas_enabled: true,
..default_config()
};
let survivor = [("permanent", "Always available.")];
let original = [("unrelated", "Removed independently.")];
for grant_when_removed in [None, Some("granting-turn")] {
let mut previous = serde_json::Map::new();
let baseline = render_catalogs_for_step(
&original,
&enabled,
&mut previous,
/*granting_turn*/ None,
/*context_window*/ 60_000,
)
.await?;
assert!(baseline.contains("- executor-unrelated:"), "{baseline}");
let both = [
original[0],
survivor[0],
("temporary", "Turn only."),
("env-b/independent", "Available without the grant on env-1."),
];
let granted = render_catalogs_for_step(
&both,
&enabled,
&mut previous,
Some("granting-turn"),
/*context_window*/ 60_000,
)
.await?;
assert!(granted.contains("- executor-permanent:"), "{granted}");
assert!(granted.contains("- executor-independent:"), "{granted}");
assert!(granted.contains("- executor-temporary:"), "{granted}");
let expired = render_catalogs_for_step(
&survivor,
&enabled,
&mut previous,
grant_when_removed,
/*context_window*/ 1,
)
.await?;
assert_eq!(
expired,
format!("\n## Selected-environment skills update\n{REVALIDATION}")
);
assert_eq!(
render_catalogs_for_step(
&survivor,
&enabled,
&mut previous,
/*granting_turn*/ None,
/*context_window*/ 1
)
.await?,
""
);
let restored = [survivor[0], ("temporary", "Turn only.")];
for expected in [RESTORATION, ""] {
assert_eq!(
render_catalogs_for_step(
&restored,
&enabled,
&mut previous,
Some("reapproved"),
/*context_window*/ 1,
)
.await?,
expected
);
}
assert_eq!(
render_catalogs_for_step(
&survivor,
&enabled,
&mut previous,
/*granting_turn*/ None,
/*context_window*/ 1,
)
.await?,
format!("\n## Selected-environment skills update\n{REVALIDATION}")
);
assert_eq!(
render_catalogs_for_step(
&[],
&enabled,
&mut previous,
/*granting_turn*/ None,
/*context_window*/ 1
)
.await?,
""
);
}
Ok(())
}
const RESTORATION: &str = "\n## Selected-environment skills update\nSome previously unavailable skills are available again. Verify current access before relying on a skill from this source.\n";
const REVALIDATION: &str = "Some previously listed skills are no longer available. Verify current access before relying on a skill from this source.\n";
#[tokio::test]
async fn legacy_filesystem_catalog_revalidates_missing_rows_once() -> TestResult {
let config = TestConfig {
catalog_deltas_enabled: true,
..default_config()
};
let mut previous = serde_json::Map::new();
let survivor = [("stay", "Keep this skill.")];
let both = [survivor[0], ("gone", "Temporarily available.")];
render_catalogs_for_step(
&both,
&config,
&mut previous,
/*granting_turn*/ None,
/*context_window*/ 60_000,
)
.await?;
for snapshot in previous.values_mut() {
snapshot.as_object_mut().unwrap().remove("tracksGrants");
}
assert_eq!(
render_catalogs(&survivor, &config, &mut previous).await?,
format!(
"\n## Selected-environment skills update\n{REVALIDATION}\n## Host skills update\n{REVALIDATION}"
)
);
assert_eq!(
render_catalogs(&survivor, &config, &mut previous).await?,
""
);
assert_eq!(render_catalogs(&[], &config, &mut previous).await?, "");
Ok(())
}
async fn render_catalogs(
skills: &[(&str, &str)],
config: &TestConfig,
previous: &mut serde_json::Map<String, serde_json::Value>,
) -> Result<String, Box<dyn std::error::Error>> {
render_catalogs_for_step(
skills, config, previous, /*granting_turn*/ None, /*context_window*/ 5_000,
)
.await
}
async fn render_catalogs_for_step(
skills: &[(&str, &str)],
config: &TestConfig,
previous: &mut serde_json::Map<String, serde_json::Value>,
granting_turn: Option<&str>,
context_window: i64,
) -> Result<String, Box<dyn std::error::Error>> {
let turn_id = granting_turn.unwrap_or("turn");
let step_store = ExtensionData::new("step");
if granting_turn.is_some() {
step_store.insert(codex_skills_extension::TurnSkillFilesystemGrants {
environment_ids: ["env-1".to_string()].into(),
});
}
let provider = |kind: SkillSourceKind| -> Result<_, codex_utils_path_uri::PathUriParseError> {
let mut entries = Vec::new();
for &(name, description) in skills {
let (environment, name) = name.split_once('/').unwrap_or(("env-1", name));
let name = format!("{kind}-{name}");
let path = format!("/skills/{name}/SKILL.md");
let mut entry = test_entry(kind.clone(), "skills", &format!("{kind}/{name}"), &path);
if kind == SkillSourceKind::Executor {
entry.main_prompt = SkillResourceId::environment(
&path,
environment,
PathUri::parse(&format!("file://{path}"))?,
);
}
entry.description = description.to_string();
entries.push(entry.with_display_path(path));
}
Ok(Arc::new(StaticSkillProvider {
catalog: SkillCatalog {
entries,
..Default::default()
},
read_requests: Arc::new(Mutex::new(Vec::new())),
list_calls: None,
fail_first_list: false,
}))
};
let providers = SkillProviders::new()
.with_executor_provider(provider(SkillSourceKind::Executor)?)
.with_cloud_provider(provider(SkillSourceKind::Cloud)?)
.with_host_provider(provider(SkillSourceKind::Host)?);
let mut builder = ExtensionRegistryBuilder::new();
install_with_providers(&mut builder, providers, skills_extension_config);
let registry = builder.build();
let session_store = ExtensionData::new("session");
let thread_store = ExtensionData::new("thread");
registry.thread_lifecycle_contributors()[0]
.on_thread_start(ThreadStartInput {
config,
session_source: &SessionSource::Cli,
persistent_thread_state_available: true,
environments: &[],
mcp_resource_client: None,
extension_metrics: None,
session_store: &session_store,
thread_store: &thread_store,
})
.await;
start_registered_turn(&registry, &session_store, &thread_store, turn_id).await;
let roots = [SelectedCapabilityRoot {
id: "skills".to_string(),
location: CapabilityRootLocation::Environment {
environment_id: "env-1".to_string(),
path: PathUri::parse("file:///skills")?,
},
}];
let turn_store = ExtensionData::new(turn_id);
turn_store.insert(HostSkillsSnapshot::new(Arc::new(
SkillLoadOutcome::default(),
)));
let sections = prepared_world_state(
&registry,
&roots,
WorldStateContributionInput {
previous_world_state: Some(previous),
step_store: &step_store,
model_info: &ModelInfo {
context_window: Some(context_window),
include_skills_usage_instructions: true,
..catalog_model_info()
},
thread_id: codex_protocol::ThreadId::new(),
turn_id,
environments: &[],
extension_metrics: None,
session_store: &session_store,
thread_store: &thread_store,
turn_store: &turn_store,
},
)
.await;
let mut emitted = String::new();
for section in sections {
let prior = previous.get(section.id()).map_or(
PreviousWorldStateSection::Absent,
PreviousWorldStateSection::Known,
);
let (snapshot, fragment) = section.render_diff(prior);
if let Some(snapshot) = snapshot {
previous.insert(section.id().to_string(), snapshot);
}
if let Some(fragment) = fragment {
emitted.push_str(&fragment.body().clone().expect_text());
}
}
Ok(emitted)
}

View File

@@ -0,0 +1,339 @@
//! Verifies metadata-only V2 skill projection and refresh without legacy discovery.
use super::*;
use codex_exec_server::DiscoverV2CapabilitiesResponse;
use codex_exec_server::DiscoveredPluginFiles;
use codex_exec_server::ExecutorCapabilityDiscoveryV2Snapshot;
use codex_exec_server::ExecutorPlugin;
use codex_exec_server::ExecutorSkill;
use codex_skills::SkillDependencies;
use codex_skills::SkillPolicy;
use codex_skills::SkillToolDependency;
use codex_skills_extension::ExecutorSkillProvider;
use codex_skills_extension::merge_catalogs;
use pretty_assertions::assert_eq;
fn installation(
environment_id: &str,
) -> Result<ExecutorCapabilityDiscoveryV2Snapshot, Box<dyn std::error::Error>> {
Ok(ExecutorCapabilityDiscoveryV2Snapshot {
environment_id: environment_id.to_string(),
result: Ok(Arc::new(DiscoverV2CapabilitiesResponse {
plugins: vec![ExecutorPlugin {
id: "local-name@marketplace".to_string(),
display_name: "Local plugin".to_string(),
remote_plugin_id: Some("Plugin_123".to_string()),
version: "1".to_string(),
root: PathUri::parse("file:///plugins/local-name/1")?,
files: DiscoveredPluginFiles {
manifest: codex_exec_server::CapabilityTextFile {
path: PathUri::parse(
"file:///plugins/local-name/1/.codex-plugin/plugin.json",
)?,
contents: r#"{"name":"local-name"}"#.to_string(),
},
mcp_config: None,
apps_config: None,
},
skills: vec![ExecutorSkill {
name: "local-name:work".to_string(),
description: "Environment description".to_string(),
short_description: None,
path: PathUri::parse(
"file:///plugins/local-name/1/skills/other-directory/SKILL.md",
)?,
discovery_root: None,
dependencies: None,
policy: None,
}],
}],
..Default::default()
})),
})
}
#[tokio::test]
async fn v2_steps_refresh_metadata_and_preserve_separate_environments() -> TestResult {
let provider = Arc::new(ExecutorSkillProvider::new_with_restriction_product(
/*restriction_product*/ None,
));
let dependencies = Some(SkillDependencies {
tools: vec![SkillToolDependency {
r#type: "mcp".into(),
value: "deploy".into(),
description: None,
transport: Some("stdio".into()),
command: Some("deploy-mcp".into()),
url: None,
oauth_callback_port: None,
}],
});
let skill_path = PathUri::parse("file:///executor/skills/dashboard/SKILL.md")?;
let mut snapshots = vec![installation("remote-a")?, installation("remote-b")?];
for snapshot in &mut snapshots {
Arc::make_mut(snapshot.result.as_mut().unwrap())
.skills
.push(ExecutorSkill {
name: "dashboard".to_string(),
description: "Build a dashboard".to_string(),
short_description: None,
path: skill_path.clone(),
discovery_root: Some(SkillDiscoveryRoot {
id: "codex-home-skills".to_string(),
path: PathUri::parse("file:///executor/skills")?,
}),
dependencies: dependencies.clone(),
policy: Some(SkillPolicy {
allow_implicit_invocation: Some(false),
products: vec![],
}),
});
}
let query = SkillListQuery {
turn_id: "turn-1".to_string(),
executor_roots: Vec::new(),
host_snapshot: None,
include_host_skills: false,
include_bundled_skills: false,
include_cloud_skills: false,
mcp_resources: None,
executor_capability_discovery: None,
executor_capability_discovery_v2: Some(snapshots.clone()),
};
// Standalone skills without discovery-root metadata use the skills namespace.
let mut fallback_query = query.clone();
for snapshot in fallback_query
.executor_capability_discovery_v2
.as_mut()
.unwrap()
{
Arc::make_mut(snapshot.result.as_mut().unwrap()).skills[0].discovery_root = None;
}
let fallback = provider.list(fallback_query).await?;
assert_eq!(fallback.entries.len(), 4);
assert_eq!(
fallback.entries[1].id.0,
"skill://skills/executor/skills/dashboard"
);
assert_eq!(
fallback.entries[1].main_prompt.environment_id(),
Some("remote-a")
);
let catalog = provider.list(query).await?;
assert_eq!(catalog.entries.len(), 4);
let merged = merge_catalogs(/*cloud*/ None, catalog.clone());
assert_eq!(merged, catalog);
for entries in [
(&merged.entries[0], &merged.entries[2]),
(&merged.entries[1], &merged.entries[3]),
] {
let (first, second) = entries;
assert_eq!(first.main_prompt.environment_id(), Some("remote-a"));
assert_eq!(second.main_prompt.environment_id(), Some("remote-b"));
assert_eq!(first.authority, second.authority);
assert_eq!(first.id, second.id);
assert_ne!(first.main_prompt, second.main_prompt);
assert!(first.sources.is_empty());
assert!(second.sources.is_empty());
}
let mut rebound = merged.entries[0].clone();
rebound.main_prompt = merged.entries[2].main_prompt.clone();
let mut deduplicated = SkillCatalog::default();
deduplicated.push_entry(merged.entries[0].clone());
deduplicated.push_entry(rebound);
deduplicated.push_entry(merged.entries[2].clone());
assert_eq!(
deduplicated.entries,
vec![merged.entries[0].clone(), merged.entries[2].clone()]
);
let plugin = merged
.entries
.iter()
.find(|entry| entry.plugin_id.is_some())
.unwrap();
assert_eq!(plugin.authority.id, "local-name@marketplace");
assert_eq!(
plugin.id.0,
"skill://local-name@marketplace/plugins/local-name/1/skills/other-directory"
);
let entry = merged
.entries
.iter()
.find(|entry| entry.plugin_id.is_none())
.unwrap();
assert_eq!(entry.dependencies, dependencies);
assert!(entry.enabled);
assert!(!entry.prompt_visible);
assert_eq!(entry.authority.id, "codex-home-skills");
assert_eq!(
entry.id.0,
"skill://codex-home-skills/executor/skills/dashboard"
);
assert_eq!(
entry.main_prompt,
SkillResourceId::environment(entry.main_prompt.as_str(), "remote-a", skill_path.clone(),)
);
let providers = SkillProviders::new().with_executor_provider(provider);
let mut builder = ExtensionRegistryBuilder::new();
install_with_providers(&mut builder, providers, skills_extension_config);
let registry = builder.build();
let metrics = Arc::new(RecordingMetrics::default());
let session_store = ExtensionData::new("session");
let thread_store = ExtensionData::new("thread");
registry.thread_lifecycle_contributors()[0]
.on_thread_start(ThreadStartInput {
config: &default_config(),
session_source: &SessionSource::Cli,
persistent_thread_state_available: true,
environments: &[],
mcp_resource_client: None,
extension_metrics: Some(metrics.clone()),
session_store: &session_store,
thread_store: &thread_store,
})
.await;
let turn_store = ExtensionData::new("turn-1");
let mut expected_metrics = Vec::new();
for (description, failed_environment, count, status) in [
(Some("original"), None, 4, "complete"),
(Some("updated"), None, 4, "complete"),
// A replacement executor can return a fresh discovery with identical inventory.
(Some("updated"), None, 4, "complete"),
(Some("updated"), Some("remote-b"), 2, "partial"),
(None, None, 0, "complete"),
] {
if let Some(description) = description {
for snapshot in &mut snapshots {
if Some(snapshot.environment_id.as_str()) == failed_environment {
snapshot.result = Err("discovery unavailable".to_string());
} else {
let mut response = snapshot.result.as_ref().unwrap().as_ref().clone();
response.plugins[0].skills[0].description = description.to_string();
snapshot.result = Ok(Arc::new(response));
}
}
} else {
snapshots.clear();
}
expected_metrics.push(expected_catalog_entries("executor", status, count));
for _ in 0..2 {
let step_store = ExtensionData::new("step");
step_store.insert(snapshots.clone());
step_store.insert(SelectedPluginSnapshot {
plugins: snapshots
.iter()
.map(|snapshot| codex_extension_api::SelectedPluginIdentity {
selected_root_id: Some(format!(
"{}:local-name@marketplace",
snapshot.environment_id
)),
plugin_id: codex_core_plugin_common::PluginIdentity::Remote {
remote_plugin_id: "Plugin_123".into(),
},
})
.collect(),
..Default::default()
});
let sections = prepared_world_state(
&registry,
&[],
WorldStateContributionInput {
previous_world_state: None,
step_store: &step_store,
model_info: &catalog_model_info(),
thread_id: codex_protocol::ThreadId::new(),
turn_id: "turn-1",
environments: &[],
extension_metrics: None,
session_store: &session_store,
thread_store: &thread_store,
turn_store: &turn_store,
},
)
.await;
let rendered = sections
.iter()
.filter_map(|section| section.render_diff(PreviousWorldStateSection::Absent).1)
.map(|fragment| fragment.body().clone().expect_text())
.collect::<Vec<_>>()
.join("\n");
if let Some(description) = description {
assert!(
rendered.contains("skill://local-name@marketplace/"),
"{rendered}"
);
assert!(
rendered.contains(&format!("- local-name:work: {description}")),
"{rendered}"
);
assert!(!rendered.contains("- dashboard:"), "{rendered}");
} else {
assert!(!rendered.contains("- local-name:work:"), "{rendered}");
}
assert_eq!(metrics.samples(), expected_metrics);
}
}
Ok(())
}
#[tokio::test]
async fn v2_empty_failed_and_partial_results_never_load_legacy_roots() -> TestResult {
let provider =
ExecutorSkillProvider::new_with_restriction_product(/*restriction_product*/ None);
let successful = installation("executor-a")?;
let failed = ExecutorCapabilityDiscoveryV2Snapshot {
environment_id: "executor-b".to_string(),
result: Err("discovery unavailable".to_string()),
};
let root = SelectedCapabilityRoot {
id: "legacy".to_string(),
location: CapabilityRootLocation::Environment {
environment_id: "unavailable-legacy-executor".to_string(),
path: PathUri::parse("file:///legacy").unwrap(),
},
};
let access = FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS);
let query = |snapshots| SkillListQuery {
turn_id: "turn-1".to_string(),
// V2 must ignore this unavailable legacy root.
executor_roots: vec![AccessedSelectedCapabilityRoot {
root: &root,
fs: &access,
}],
host_snapshot: None,
include_host_skills: false,
include_bundled_skills: false,
include_cloud_skills: false,
mcp_resources: None,
executor_capability_discovery: None,
executor_capability_discovery_v2: Some(snapshots),
};
let successful_catalog = provider.list(query(vec![successful.clone()])).await?;
let failure_warning =
"Environment `executor-b` discovery failed: discovery unavailable".to_string();
for (snapshots, expected) in [
(Vec::new(), SkillCatalog::default()),
(
vec![failed.clone()],
SkillCatalog {
is_partial: true,
entries: Vec::new(),
warnings: vec![failure_warning.clone()],
},
),
(
vec![successful, failed],
SkillCatalog {
is_partial: true,
warnings: vec![failure_warning],
..successful_catalog
},
),
] {
assert_eq!(provider.list(query(snapshots)).await?, expected);
}
Ok(())
}

File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More