aKode fase 2b-2: rimosso login ChatGPT e tutti i sottosistemi solo-ChatGPT

- Login: resta solo chiave API (+ header, Bedrock). Rimossi OAuth/browser,
  device code, refresh/revoke su auth.openai.com, PAT, agent/workload identity,
  runtime agent instance, backend-client e openapi-models, workspace routing.
- Rimossi: generazione immagini (ext + skill imagegen), history notes, plugin
  remoti (catalogo, sync, share), cyber access program, daybreak, cloud config
  e requirements (config_server ora fail-closed), attestation, frozen cloud
  skills, EMA MCP auth, Codex Apps/connettori, ricerca ospitata, header/zstd/
  routing/cookie del backend Codex, fallback OPENAI_API_KEY del realtime.
- Messaggi d'errore senza link a chatgpt.com.
- Chiavi di config legacy accettate e ignorate; feature rimosse = Stage::Removed.
- Test: cancellati solo quelli del codice rimosso; test di sicurezza
  (sandbox estensioni, permessi, redazione, auth storage, requirements)
  adattati. Restano solo fallimenti d'ambiente (code-mode-host/V8, ~/.agents).
- Istruzioni di sistema invariate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-10 16:20:15 +01:00
parent 82347a58ed
commit 6089fbde91
1573 changed files with 10289 additions and 177679 deletions

View File

@@ -13,7 +13,6 @@ 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,
@@ -42,7 +41,6 @@ impl From<String> for SkillLocator {
}
index.parse::<usize>().ok()?;
[
SkillSourceKind::Cloud,
SkillSourceKind::Executor,
SkillSourceKind::Host,
]
@@ -89,7 +87,6 @@ impl SkillAliasState {
.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,
};
@@ -102,7 +99,6 @@ impl SkillAliasState {
/// 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,
}
@@ -110,7 +106,6 @@ pub(crate) struct SkillCatalogAliases {
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,
};
@@ -123,7 +118,6 @@ impl SkillCatalogAliases {
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);
@@ -131,7 +125,6 @@ impl SkillCatalogAliases {
pub(crate) fn for_authority(&self, selector: SkillToolAuthoritySelector) -> &AliasPlan {
match selector {
SkillToolAuthoritySelector::Cloud => &self.cloud,
SkillToolAuthoritySelector::Executor => &self.executor,
}
}
@@ -140,7 +133,7 @@ impl SkillCatalogAliases {
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.
/// Shared bound on thread-local executor alias assignments and their rendered mappings.
#[derive(Clone, Debug, Default)]
struct AliasBudget {
roots: usize,

View File

@@ -52,12 +52,6 @@ fn shortens_filesystem_and_skill_resource_locators() {
"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");
@@ -104,7 +98,7 @@ fn aliases_roots_used_by_only_one_skill() {
#[test]
fn locator_serde_recognizes_aliases_and_preserves_package_strings() {
for (value, expected_source) in [
("c0/release", Some(SkillSourceKind::Cloud)),
("c0/release", None),
("e12/references/details.md", Some(SkillSourceKind::Executor)),
("r1/release/SKILL.md", Some(SkillSourceKind::Host)),
("skill://Plugin_123/release", None),
@@ -152,18 +146,18 @@ fn appended_aliases_preserve_captured_steps_and_existing_locators() {
#[test]
fn alias_number_and_byte_budgets_are_shared_without_reassigning_existing_roots() {
let mut cloud = std::sync::Arc::new(AliasPlan::default());
let mut other = 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);
other.extend_alias_plan("r", ["skill://other"], &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()));
assert_eq!(other.shorten("skill://other/demo"), Some("r0/demo".into()));
let mut budget = super::AliasBudget::default();
let mut aliases = std::sync::Arc::new(AliasPlan::default());

View File

@@ -14,8 +14,6 @@ pub enum SkillSourceKind {
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),
@@ -30,7 +28,6 @@ impl SkillSourceKind {
match self {
Self::Host => "host",
Self::Executor => "executor",
Self::Cloud => "cloud",
Self::Custom(kind) => kind,
}
}
@@ -306,7 +303,7 @@ impl SkillCatalogEntry {
pub(crate) fn unaliased_locator(&self) -> &str {
match &self.authority.kind {
SkillSourceKind::Executor | SkillSourceKind::Cloud => self.id.0.as_str(),
SkillSourceKind::Executor => self.id.0.as_str(),
SkillSourceKind::Host | SkillSourceKind::Custom(_) => self.rendered_path(),
}
}
@@ -374,40 +371,27 @@ impl SkillCatalog {
}
}
/// Applies plugin denials and requires accepted Cloud or executor roots before merging skills.
/// Applies plugin denials and requires accepted 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
) {
if skill.authority.kind != 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
})
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}");
let accepted = snapshot
.plugins
.iter()
.any(|plugin| plugin.selected_root_id.as_deref() == Some(root_id.as_str()));
skill.enabled &= skill
.remote_plugin_id
.as_ref()
@@ -420,54 +404,6 @@ pub(crate) fn apply_plugin_denials(catalog: &mut SkillCatalog, snapshot: &Select
}
}
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 {
@@ -511,7 +447,3 @@ impl std::fmt::Display for SkillProviderError {
impl std::error::Error for SkillProviderError {}
pub type SkillProviderResult<T> = Result<T, SkillProviderError>;
#[cfg(test)]
#[path = "catalog_tests.rs"]
mod tests;

View File

@@ -26,7 +26,6 @@ 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 =
@@ -92,14 +91,12 @@ struct CatalogSnapshot {
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 {
@@ -151,7 +148,6 @@ pub(crate) fn skills_delta_section(
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()
};
@@ -277,7 +273,6 @@ fn build_catalog_update(
}
previous.entries = entries;
previous.instructions_sent |= body.is_some();
previous.allocation = catalog.allocation;
CatalogResult {
snapshot: previous,
report,

View File

@@ -5,7 +5,7 @@ use pretty_assertions::assert_eq;
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(),
heading: "\n## Selected-environment skills update\n".to_string(),
},
skill_lines: Vec::new(),
root_lines: Vec::new(),
@@ -23,12 +23,12 @@ fn update_spends_budget_only_on_accepted_rows_and_their_new_roots() {
}),
};
let notes = skill(
"- release-notes: (cloud package: c0/notes)",
"c0",
"- release-notes: (executor package: e0/notes)",
"e0",
"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 docs = skill("- docs: (executor package: e0/docs)", "e0", "skill://writing");
let expected = "\n## Selected-environment skills update\n### Skill roots\nThese mappings replace earlier mappings for the same aliases.\n- `e0` = `skill://writing`\n### Added or updated skills:\n- release-notes: (executor package: e0/notes)\n- docs: (executor package: e0/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");
@@ -37,10 +37,10 @@ fn update_spends_budget_only_on_accepted_rows_and_their_new_roots() {
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!(draft.into_body("Selected-environment").as_deref(), Some(expected));
assert_eq!(
snapshot.roots,
BTreeMap::from([("c0".into(), "skill://writing".into())])
BTreeMap::from([("e0".into(), "skill://writing".into())])
);
assert_eq!(snapshot.usage.characters, expected.chars().count());
assert_eq!(remaining, SkillMetadataBudget::Characters(0));

View File

@@ -51,7 +51,7 @@ impl SkillPromptKind {
pub(crate) fn for_aliased_source(source: &SkillSourceKind) -> Self {
match source {
SkillSourceKind::Host => Self::HostAliases,
SkillSourceKind::Executor | SkillSourceKind::Cloud => Self::ResourceAliases,
SkillSourceKind::Executor => Self::ResourceAliases,
SkillSourceKind::Custom(_) => Self::Unaliased,
}
}
@@ -119,7 +119,7 @@ pub(crate) fn render_available_skills_body(
}
if skill_lines
.iter()
.any(|line| line.contains("(executor package: ") || line.contains("(cloud package: "))
.any(|line| line.contains("(executor 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."

View File

@@ -1,27 +1,13 @@
//! Reusable provider catalog caches and Cloud resource contents.
//! Reusable provider catalog caches.
//! 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)]
@@ -32,72 +18,6 @@ pub(crate) struct SkillCatalogState {
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.
@@ -180,66 +100,3 @@ impl CachedExecutorDiscoveryCatalog {
})
}
}
#[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

@@ -1,77 +0,0 @@
//! 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

@@ -1,620 +0,0 @@
//! 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

@@ -1,98 +0,0 @@
//! 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

@@ -13,8 +13,6 @@ pub struct SkillsExtensionConfig {
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

@@ -38,7 +38,6 @@ fn host_interface_metadata_makes_unlisted_workflow_discoverable() {
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 {

View File

@@ -2,7 +2,6 @@ use std::sync::Arc;
use crate::HostSkillsSnapshot;
use crate::InjectedHostSkillPrompts;
use codex_exec_server::LOCAL_ENVIRONMENT_ID;
use codex_extension_api::ConfigContributor;
use codex_extension_api::ContextContributor;
use codex_extension_api::ContextualUserFragment;
@@ -70,9 +69,6 @@ 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>,
@@ -150,14 +146,8 @@ where
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,
));
})
@@ -179,10 +169,8 @@ where
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()),
@@ -216,7 +204,6 @@ where
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()),
@@ -360,8 +347,7 @@ where
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,
// Executor catalogs come from the prepared step snapshot.
mcp_resources: mcp_resources.clone(),
executor_capability_discovery: None,
executor_capability_discovery_v2: None,
@@ -401,7 +387,6 @@ where
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
@@ -537,7 +522,6 @@ impl<C> SkillsExtension<C> {
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,
@@ -631,7 +615,6 @@ pub fn install_with_providers_and_metrics<C>(
});
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());

View File

@@ -12,7 +12,7 @@ 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.
/// prompts and retaining executor skill precedence.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct InjectedHostSkillPrompts {
paths: HashSet<String>,

View File

@@ -179,7 +179,6 @@ fn roots_from_layer_stack<'a>(
}
ConfigLayerSource::PackagedDefaults { .. }
| ConfigLayerSource::Mdm { .. }
| ConfigLayerSource::EnterpriseManaged { .. }
| ConfigLayerSource::SessionFlags
| ConfigLayerSource::LegacyManagedConfigTomlFromFile { .. }
| ConfigLayerSource::LegacyManagedConfigTomlFromMdm => {}

View File

@@ -298,7 +298,6 @@ fn expected_skill(path: AbsolutePathBuf, name: &str, scope: SkillScope) -> Skill
path_to_skills_md: PathUri::from_abs_path(&path),
scope,
plugin_id: None,
remote_plugin_id: None,
}
}
@@ -356,7 +355,6 @@ async fn plugin_roots_preserve_plugin_resolution_metadata() {
let skills_root = plugin_root.join("skills");
let plugin_identity = PluginIdentity {
plugin_id: "example@test".to_string(),
remote_plugin_id: Some("plugins~Plugin_example".to_string()),
};
let plugin_namespace = "example".to_string();

View File

@@ -97,7 +97,6 @@ fn plugin_skill_root_for_skill_path(
path: skills_root.abs(),
plugin_identity: PluginIdentity {
plugin_id: plugin_id.to_string(),
remote_plugin_id: None,
},
plugin_namespace: plugin_namespace.to_string(),
plugin_root: plugin_root.abs(),
@@ -432,7 +431,6 @@ async fn snapshot_for_config_preserves_host_precedence_for_symlinked_plugin_root
),
scope: SkillScope::User,
plugin_id: None,
remote_plugin_id: None,
}]
);
}
@@ -502,91 +500,6 @@ async fn skills_list_snapshots_share_host_roots_only_within_one_request() {
);
}
#[tokio::test]
async fn skills_for_config_refreshes_cache_when_remote_plugin_id_changes() {
let codex_home = tempfile::tempdir().expect("tempdir");
let cwd = tempfile::tempdir().expect("tempdir");
let skill_path = write_plugin_skill(
&codex_home,
"test",
"sample",
"sample-search",
"sample-search",
"search sample data",
);
let config_layer_stack = config_stack(&codex_home, "");
let mut plugin_skill_root =
plugin_skill_root_for_skill_path(&skill_path, "sample@test", "sample");
let skills_service = HostSkillsService::new(
codex_home.path().abs(),
/*bundled_skills_enabled*/ true,
);
let plugin_input = HostSkillsLoadInput::new(
cwd.path().abs(),
vec![plugin_skill_root.clone()],
config_layer_stack.clone(),
)
.with_plugin_skill_snapshots(Some(test_plugin_skill_snapshots()));
let plugin_snapshot = skills_service
.snapshot_for_config(
&plugin_input,
Some(&codex_exec_server::FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS)),
)
.await;
fs::write(
&skill_path,
"---\nname: sample-search\ndescription: updated sample data\n---\n\n# Body\n",
)
.expect("update plugin skill");
let listing_input = plugin_input
.clone()
.with_plugin_skill_snapshots(/*plugin_skill_snapshots*/ None);
let listing_snapshot = skills_service
.for_request()
.snapshot_for_cwd(
&listing_input,
/*force_reload*/ false,
Some(Arc::clone(&LOCAL_FS)),
)
.await;
assert_eq!(
(
plugin_snapshot
.outcome()
.skills
.iter()
.find(|skill| skill.name == "sample:sample-search")
.map(|skill| skill.description.as_str()),
listing_snapshot
.outcome()
.skills
.iter()
.find(|skill| skill.name == "sample:sample-search")
.map(|skill| skill.description.as_str()),
),
(Some("search sample data"), Some("updated sample data"))
);
plugin_skill_root.plugin_identity.remote_plugin_id = Some("plugins~Plugin_sample".to_string());
let refreshed = skills_for_config_with_stack(
&skills_service,
&cwd,
&config_layer_stack,
&[plugin_skill_root],
)
.await;
assert_eq!(
refreshed
.skills
.iter()
.find(|skill| skill.name == "sample:sample-search")
.and_then(|skill| skill.remote_plugin_id.as_deref()),
Some("plugins~Plugin_sample")
);
}
#[tokio::test]
async fn set_extra_roots_replaces_runtime_roots_and_clears_cache() {
let codex_home = tempfile::tempdir().expect("tempdir");

View File

@@ -85,7 +85,7 @@ pub fn detect_implicit_skill_invocation(
scope: skill.scope,
},
plugin_id: skill.plugin_id,
remote_plugin_id: skill.remote_plugin_id,
remote_plugin_id: None,
invocation_type: InvocationType::Implicit,
});
}
@@ -114,12 +114,12 @@ pub fn detect_implicit_skill_invocation(
.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
)
}) {
for entry in step_catalog
.merged
.entries
.iter()
.filter(|entry| entry.authority.kind == SkillSourceKind::Executor)
{
if entry.enabled && matches_route(&entry.authority, &entry.main_prompt) {
return Some(entry.invocation(&entry.primary_source(), InvocationType::Implicit));
}

View File

@@ -31,7 +31,6 @@ fn detect_executor_skill(command: &str, environments: &[&str]) -> Option<SkillIn
};
let turn_store = ExtensionData::new("test-turn");
let step_catalog = crate::step_state::SkillStepCatalog::new(
/*cloud*/ None,
catalog,
/*discovery_v2*/ false,
Default::default(),
@@ -42,14 +41,12 @@ fn detect_executor_skill(command: &str, environments: &[&str]) -> Option<SkillIn
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,
},
});

View File

@@ -32,7 +32,6 @@ 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;
@@ -48,7 +47,6 @@ pub use invocation::SkillInvocation;
pub use invocation::SkillInvocationLocation;
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;

View File

@@ -390,7 +390,6 @@ async fn parse_skill_file(
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()),
})
}

View File

@@ -95,7 +95,6 @@ async fn host_loading_reuses_walk_inventory_for_symlinked_skill_pack() {
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(),
@@ -107,7 +106,6 @@ async fn host_loading_reuses_walk_inventory_for_symlinked_skill_pack() {
path_to_skills_md: PathUri::from_abs_path(&second_skill_path),
scope: SkillScope::User,
plugin_id: None,
remote_plugin_id: None,
},
]
);

View File

@@ -93,7 +93,6 @@ impl PluginSkillsFixture {
access: FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS),
identity: PluginIdentity {
plugin_id: "sample@test".to_string(),
remote_plugin_id: Some("remote-sample".to_string()),
},
}
}
@@ -267,8 +266,8 @@ async fn reuses_owner_managed_plugin_root_snapshots() {
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")
cached_outcome.skills[0].plugin_id.as_deref(),
Some("sample@test")
);
}

View File

@@ -98,7 +98,6 @@ impl PluginSkillFixture {
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(),
@@ -162,7 +161,6 @@ policy:
path_to_skills_md: PathUri::from_abs_path(&skill_path),
scope: SkillScope::User,
plugin_id: None,
remote_plugin_id: None,
}]
);
}
@@ -189,7 +187,6 @@ async fn invalid_optional_metadata_fails_open() {
path_to_skills_md: PathUri::from_abs_path(&skill_path),
scope: SkillScope::Repo,
plugin_id: None,
remote_plugin_id: None,
}]
);
}
@@ -236,7 +233,6 @@ async fn loads_host_interface_metadata_and_local_asset_paths() {
path_to_skills_md: PathUri::from_abs_path(&skill_path),
scope: SkillScope::User,
plugin_id: None,
remote_plugin_id: None,
}]
);
}
@@ -279,7 +275,6 @@ async fn loads_plugin_skill_interface_icons_from_local_and_shared_assets() {
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,
}]
);
}
@@ -317,7 +312,6 @@ async fn rejects_plugin_skill_interface_icons_outside_shared_assets() {
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,
}]
);
}
@@ -348,7 +342,6 @@ async fn rejects_interface_fields_that_escape_or_fail_validation() {
path_to_skills_md: PathUri::from_abs_path(&skill_path),
scope: SkillScope::User,
plugin_id: None,
remote_plugin_id: None,
}]
);
}
@@ -403,7 +396,6 @@ async fn discovers_nested_plugin_namespace_without_plugin_identity() {
path_to_skills_md: PathUri::from_abs_path(&skill_path),
scope: SkillScope::User,
plugin_id: None,
remote_plugin_id: None,
}]
);
}
@@ -426,7 +418,6 @@ async fn plugin_root_accepts_maximum_length_qualified_skill_name() {
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,
@@ -449,7 +440,6 @@ async fn plugin_root_accepts_maximum_length_qualified_skill_name() {
path_to_skills_md: PathUri::from_abs_path(&skill_path),
scope: SkillScope::User,
plugin_id: Some("demo@test".to_string()),
remote_plugin_id: None,
}]
);
}
@@ -471,7 +461,6 @@ async fn plugin_root_rejects_overlong_qualified_skill_name() {
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,
@@ -522,7 +511,6 @@ async fn recursive_plugin_root_preserves_owner_namespace_and_shared_asset_policy
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,
@@ -552,7 +540,6 @@ async fn recursive_plugin_root_preserves_owner_namespace_and_shared_asset_policy
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!(
@@ -584,7 +571,6 @@ async fn direct_child_plugin_root_ignores_nested_skills() {
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,
@@ -607,7 +593,6 @@ async fn direct_child_plugin_root_ignores_nested_skills() {
path_to_skills_md: PathUri::from_abs_path(&direct_path),
scope: SkillScope::User,
plugin_id: Some("demo@test".to_string()),
remote_plugin_id: None,
}]
);
}
@@ -636,7 +621,6 @@ async fn direct_child_plugin_root_skips_skills_resolving_outside_plugin_root() {
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,
@@ -667,7 +651,6 @@ async fn recursive_plugin_root_preserves_symlinked_skill_discovery_path() {
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,
@@ -690,7 +673,6 @@ async fn recursive_plugin_root_preserves_symlinked_skill_discovery_path() {
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!(

View File

@@ -10,7 +10,6 @@ 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;
@@ -20,38 +19,21 @@ pub(crate) async fn prepare_catalogs(
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_executor_catalog(thread_state, providers, input, &config),
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),
tools_enabled: !input.ready_selected_capability_roots.is_empty() || discovery_v2,
catalog: thread_state.prepare_step_catalog(executor, discovery_v2),
host_catalog,
cloud_status,
config,
}
}
@@ -61,7 +43,6 @@ async fn discover_executor_catalog(
providers: &SkillProviders,
input: &StepPreparationInput<'_>,
config: &SkillsExtensionConfig,
cloud_enabled: bool,
) -> SkillCatalog {
let query = SkillListQuery {
turn_id: input.turn_id.to_string(),
@@ -69,7 +50,6 @@ async fn discover_executor_catalog(
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>()
@@ -100,7 +80,6 @@ async fn discover_host_catalog(
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,

View File

@@ -3,7 +3,6 @@ use std::pin::Pin;
use std::sync::Arc;
mod executor;
mod frozen_cloud;
mod host;
use crate::HostSkillsSnapshot;
@@ -23,7 +22,6 @@ 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;
@@ -36,7 +34,6 @@ pub struct SkillListQuery<'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>,
@@ -63,9 +60,6 @@ pub enum SkillReadContext<'a> {
Executor {
fs: &'a dyn EnvironmentAccess,
},
Cloud {
mcp_resources: Option<Arc<McpResourceClient>>,
},
Custom {
mcp_resources: Option<Arc<McpResourceClient>>,
},
@@ -87,12 +81,6 @@ pub type SkillProviderFuture<'a, T> =
/// 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>;

View File

@@ -43,7 +43,6 @@ impl ExecutorSkillProvider {
) else {
continue;
};
entry.remote_plugin_id = plugin.remote_plugin_id.clone();
entry.plugin_id = Some(plugin.id.clone());
entry.invocation_scope = Some(SkillScope::User);
catalog.push_entry(entry);

View File

@@ -1,164 +0,0 @@
//! 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

@@ -1,92 +0,0 @@
//! 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

@@ -262,7 +262,6 @@ impl<'a> SkillLine<'a> {
locator_kind: match &entry.authority.kind {
SkillSourceKind::Host => "file",
SkillSourceKind::Executor => "executor package",
SkillSourceKind::Cloud => "cloud package",
SkillSourceKind::Custom(_) => "custom resource",
},
}
@@ -530,7 +529,6 @@ pub(crate) struct AvailableSkillsRender {
#[derive(Default)]
pub(crate) struct RenderedSkillCatalogs {
pub(crate) executor: Option<AvailableSkillsRender>,
pub(crate) cloud: Option<AvailableSkillsRender>,
pub(crate) host: Option<AvailableSkillsRender>,
}
@@ -593,70 +591,40 @@ pub(crate) fn render_available_skills(
pub(crate) fn render_prepared_skill_catalogs(
executor: &PreparedSkillCatalog<'_>,
cloud: &PreparedSkillCatalog<'_>,
host: &PreparedSkillCatalog<'_>,
budget: SkillMetadataBudget,
include_skills_usage_instructions: bool,
) -> RenderedSkillCatalogs {
let nonempty_catalog_count = [
!executor.entries.is_empty(),
!cloud.entries.is_empty(),
!host.entries.is_empty(),
]
.into_iter()
.filter(|nonempty| *nonempty)
.count();
if nonempty_catalog_count <= 1 {
if executor.entries.is_empty() || host.entries.is_empty() {
return RenderedSkillCatalogs {
executor: executor.render(budget, include_skills_usage_instructions),
cloud: cloud.render(budget, include_skills_usage_instructions),
host: host.render(budget, include_skills_usage_instructions),
};
}
let absolute = render_combined_lines(
executor.unaliased(),
cloud.unaliased(),
host.unaliased(),
budget,
);
let absolute = render_combined_lines(executor.unaliased(), host.unaliased(), budget);
let mut selected = absolute;
let host_only_aliases = build_aliased_combined_catalog(
executor.unaliased(),
cloud.unaliased(),
host.aliased(),
budget,
include_skills_usage_instructions,
);
let executor_only_aliases = build_aliased_combined_catalog(
executor.aliased(),
cloud.unaliased(),
host.unaliased(),
budget,
include_skills_usage_instructions,
);
let cloud_only_aliases = build_aliased_combined_catalog(
executor.unaliased(),
cloud.aliased(),
host.unaliased(),
budget,
include_skills_usage_instructions,
);
let all_source_aliases = build_aliased_combined_catalog(
executor.aliased(),
cloud.aliased(),
host.aliased(),
budget,
include_skills_usage_instructions,
);
for candidate in [
host_only_aliases,
executor_only_aliases,
cloud_only_aliases,
all_source_aliases,
]
for candidate in [host_only_aliases, executor_only_aliases, all_source_aliases]
.into_iter()
.flatten()
{
@@ -672,14 +640,12 @@ pub(crate) fn render_prepared_skill_catalogs(
RenderedSkillCatalogs {
executor: Some(selected.executor),
cloud: Some(selected.cloud),
host: Some(selected.host),
}
}
struct CombinedAvailableSkillsRender {
executor: AvailableSkillsRender,
cloud: AvailableSkillsRender,
host: AvailableSkillsRender,
}
@@ -748,23 +714,15 @@ impl<'a> CatalogLines<'a> {
fn render_combined_lines(
executor: CatalogLines<'_>,
cloud: CatalogLines<'_>,
host: CatalogLines<'_>,
budget: SkillMetadataBudget,
) -> CombinedAvailableSkillsRender {
let executor_end = executor.skills.len();
let cloud_end = executor_end.saturating_add(cloud.skills.len());
let mut lines = executor.skills;
lines.extend(cloud.skills);
lines.extend(host.skills);
let mut allocations = allocate_skill_lines(&lines, budget);
let omission_marker =
reserve_non_host_omission_marker(&lines, executor_end, cloud_end, budget, &mut allocations);
let (executor_omission_marker, cloud_omission_marker) = if executor_end == cloud_end {
(omission_marker, None)
} else {
(None, omission_marker)
};
reserve_non_host_omission_marker(&lines, executor_end, budget, &mut allocations);
CombinedAvailableSkillsRender {
executor: render_combined_group(
@@ -772,18 +730,11 @@ fn render_combined_lines(
&allocations[..executor_end],
executor.prompt,
executor.root_lines,
executor_omission_marker,
),
cloud: render_combined_group(
&lines[executor_end..cloud_end],
&allocations[executor_end..cloud_end],
cloud.prompt,
cloud.root_lines,
cloud_omission_marker,
omission_marker,
),
host: render_combined_group(
&lines[cloud_end..],
&allocations[cloud_end..],
&lines[executor_end..],
&allocations[executor_end..],
host.prompt,
host.root_lines,
/*omission_marker*/ None,
@@ -827,19 +778,18 @@ fn render_combined_group(
fn build_aliased_combined_catalog(
executor: CatalogLines<'_>,
cloud: CatalogLines<'_>,
host: CatalogLines<'_>,
budget: SkillMetadataBudget,
include_skills_usage_instructions: bool,
) -> Option<CombinedAvailableSkillsRender> {
if [&executor.root_lines, &cloud.root_lines, &host.root_lines]
if [&executor.root_lines, &host.root_lines]
.into_iter()
.all(Vec::is_empty)
{
return None;
}
let table_cost = [&executor, &cloud, &host]
let table_cost = [&executor, &host]
.into_iter()
.filter(|catalog| !catalog.root_lines.is_empty())
.map(|catalog| {
@@ -860,12 +810,7 @@ fn build_aliased_combined_catalog(
SkillMetadataBudget::Tokens(_) => SkillMetadataBudget::Tokens(adjusted_limit),
SkillMetadataBudget::Characters(_) => SkillMetadataBudget::Characters(adjusted_limit),
};
Some(render_combined_lines(
executor,
cloud,
host,
adjusted_budget,
))
Some(render_combined_lines(executor, host, adjusted_budget))
}
fn combined_render_is_better(
@@ -877,7 +822,6 @@ fn combined_render_is_better(
let priority = |rendered: &CombinedAvailableSkillsRender| {
(
rendered.executor.report.included_count,
rendered.cloud.report.included_count,
rendered.host.report.included_count,
)
};
@@ -886,7 +830,7 @@ fn combined_render_is_better(
}
let truncated_chars = |rendered: &CombinedAvailableSkillsRender| {
[&rendered.executor, &rendered.cloud, &rendered.host]
[&rendered.executor, &rendered.host]
.into_iter()
.fold(0usize, |total, catalog| {
total.saturating_add(catalog.report.truncated_description_chars)
@@ -905,7 +849,7 @@ fn combined_available_skills_cost(
rendered: &CombinedAvailableSkillsRender,
include_skills_usage_instructions: bool,
) -> usize {
[&rendered.executor, &rendered.cloud, &rendered.host]
[&rendered.executor, &rendered.host]
.into_iter()
.fold(0usize, |used, catalog| {
used.saturating_add(catalog.metadata_cost(budget, include_skills_usage_instructions))
@@ -915,12 +859,11 @@ fn combined_available_skills_cost(
fn reserve_non_host_omission_marker(
skill_lines: &[SkillLine<'_>],
executor_end: usize,
cloud_end: usize,
budget: SkillMetadataBudget,
allocations: &mut [SkillLineAllocation],
) -> Option<String> {
loop {
let omitted_count = allocations[..cloud_end]
let omitted_count = allocations[..executor_end]
.iter()
.filter(|allocation| matches!(allocation, SkillLineAllocation::Omitted))
.count();
@@ -934,9 +877,8 @@ fn reserve_non_host_omission_marker(
return Some(marker);
}
let index = (cloud_end..allocations.len())
let index = (executor_end..allocations.len())
.rev()
.chain((executor_end..cloud_end).rev())
.chain((0..executor_end).rev())
.find(|index| {
matches!(
@@ -1078,7 +1020,7 @@ pub(crate) fn build_alias_plan(entries: &[&SkillCatalogEntry]) -> Option<AliasPl
alias_ordered_entries.sort_by_key(|entry| entry.alias_root_order().unwrap_or(usize::MAX));
let roots = match source {
SkillSourceKind::Host => shared_host_alias_roots(&alias_ordered_entries),
SkillSourceKind::Executor | SkillSourceKind::Cloud => alias_ordered_entries
SkillSourceKind::Executor => alias_ordered_entries
.iter()
.filter_map(|entry| entry.alias_root())
.map(str::to_string)

View File

@@ -1,4 +1,4 @@
//! Prefers cloud skills before budgeting while retaining aliases from the full visible inventory.
//! Prepares visible catalog entries and aliases from the full visible inventory.
//! Collects comparison metadata after the final rendering has been selected.
use std::borrow::Cow;
@@ -57,22 +57,6 @@ impl<'a> PreparedSkillCatalog<'a> {
}
}
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)
}
@@ -129,9 +113,7 @@ impl<'a> PreparedSkillCatalog<'a> {
SkillSourceKind::Host if entry.prompt_scope() == Some(SkillScope::Repo) => {
primary_environment
}
SkillSourceKind::Host | SkillSourceKind::Cloud | SkillSourceKind::Custom(_) => {
None
}
SkillSourceKind::Host | SkillSourceKind::Custom(_) => None,
};
let granted = environment.is_some_and(|id| {
grants.is_some_and(|grants| grants.environment_ids.contains(id))

View File

@@ -14,7 +14,6 @@ use crate::render::SkillRenderReport;
pub(crate) enum CatalogSurface {
ThreadContext,
ExecutorWorldState,
CloudWorldState,
HostWorldState,
TurnInput,
}
@@ -24,7 +23,6 @@ impl CatalogSurface {
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",
}

View File

@@ -24,7 +24,6 @@ use crate::loader::load_and_merge_host_skill_roots;
fn render_combined_available_skills(
executor_catalog: &SkillCatalog,
cloud_catalog: &SkillCatalog,
host_catalog: &SkillCatalog,
budget: SkillMetadataBudget,
include_skills_usage_instructions: bool,
@@ -34,10 +33,6 @@ fn render_combined_available_skills(
executor_catalog,
SkillCatalogRenderPolicy::EXTENSION_COMPATIBLE,
),
&PreparedSkillCatalog::new(
cloud_catalog,
SkillCatalogRenderPolicy::EXTENSION_COMPATIBLE,
),
&PreparedSkillCatalog::new(host_catalog, SkillCatalogRenderPolicy::CORE_COMPATIBLE),
budget,
include_skills_usage_instructions,
@@ -87,63 +82,6 @@ fn skill_prompt_contents_are_bounded_at_utf8_boundaries() {
assert_eq!(truncated, true);
}
#[test]
fn prebudget_dedup_can_choose_full_locators_over_preserved_aliases() {
let hidden_root = format!("skill://executor/{}", "long-package-root/".repeat(40));
let mut hidden = entry(
"demo:hidden",
"Hidden duplicate.",
/*short_description*/ None,
)
.with_alias_root(hidden_root.clone());
hidden.authority.kind = SkillSourceKind::Executor;
hidden.id = SkillPackageId(format!("{hidden_root}/hidden"));
let mut visible = entry(
"other:visible",
"Keep this description.",
/*short_description*/ None,
)
.with_alias_root("skill://short");
visible.authority.kind = SkillSourceKind::Executor;
visible.id = SkillPackageId("skill://short/visible".to_string());
let executor = SkillCatalog {
is_partial: false,
entries: vec![hidden.clone(), visible],
warnings: Vec::new(),
};
hidden.authority.kind = SkillSourceKind::Cloud;
let cloud = SkillCatalog {
is_partial: false,
entries: vec![hidden],
warnings: Vec::new(),
};
let mut prepared =
PreparedSkillCatalog::new(&executor, SkillCatalogRenderPolicy::EXTENSION_COMPATIBLE);
prepared.prefer_cloud_skills(&cloud);
let rendered = prepared
.render(
SkillMetadataBudget::Characters(300),
/*include_skills_usage_instructions*/ false,
)
.expect("remaining executor skill should render");
assert!(rendered.skill_root_lines.is_empty());
assert_eq!(
rendered.skill_lines,
vec![
"- other:visible: Keep this description. (executor package: skill://short/visible)"
.to_string(),
]
);
assert_eq!(
rendered.report,
SkillRenderReport {
total_count: 1,
included_count: 1,
..Default::default()
}
);
}
fn entry(name: &str, description: &str, short_description: Option<&str>) -> SkillCatalogEntry {
entry_with_path(
name,
@@ -643,7 +581,6 @@ async fn host_alias_roots_follow_core_discovery_order() -> Result<(), Box<dyn st
host_snapshot: Some(Arc::new(HostSkillsSnapshot::new(Arc::new(outcome)))),
include_host_skills: true,
include_bundled_skills: false,
include_cloud_skills: false,
mcp_resources: None,
executor_capability_discovery: None,
executor_capability_discovery_v2: None,
@@ -755,9 +692,8 @@ fn mixed_catalog_reserves_executor_omission_marker_by_omitting_host_first() {
warnings: Vec::new(),
};
let RenderedSkillCatalogs { host, executor, .. } = render_combined_available_skills(
let RenderedSkillCatalogs { host, executor } = render_combined_available_skills(
&executor_catalog,
&SkillCatalog::default(),
&host_catalog,
SkillMetadataBudget::Tokens(28),
/*include_skills_usage_instructions*/ false,
@@ -802,7 +738,6 @@ fn mixed_catalog_reserves_executor_omission_marker_by_omitting_host_first() {
fn mixed_catalogs_alias_all_skill_sources_under_budget_pressure() {
let executor_root =
"skill://executor-environment-with-a-long-shared-root/workspaces/project/.agents/skills";
let cloud_root = "skill://plugin_connector_1p_2330815c823c8191941e5dc465bb899f";
let host_root = "/Users/test/.codex/plugins/cache/openai-curated/example/hash1234567890/skills";
let catalog =
|source: SkillSourceKind, authority: &str, root: &str, prefix: &str| SkillCatalog {
@@ -811,12 +746,7 @@ fn mixed_catalogs_alias_all_skill_sources_under_budget_pressure() {
.map(|index| {
let name = format!("{prefix}-{index}");
let package = format!("{root}/{name}");
let locator = match source {
SkillSourceKind::Cloud => package.clone(),
SkillSourceKind::Host
| SkillSourceKind::Executor
| SkillSourceKind::Custom(_) => format!("{package}/SKILL.md"),
};
let locator = format!("{package}/SKILL.md");
SkillCatalogEntry::new(
SkillPackageId(package),
SkillAuthority::new(source.clone(), authority),
@@ -836,28 +766,21 @@ fn mixed_catalogs_alias_all_skill_sources_under_budget_pressure() {
executor_root,
"executor",
);
let cloud_catalog = catalog(SkillSourceKind::Cloud, "codex_apps", cloud_root, "cloud");
let host_catalog = catalog(SkillSourceKind::Host, "host", host_root, "host");
let rendered = render_combined_available_skills(
&executor_catalog,
&cloud_catalog,
&host_catalog,
SkillMetadataBudget::Characters(900),
/*include_skills_usage_instructions*/ true,
);
let executor = rendered.executor.expect("executor catalog should render");
let cloud = rendered.cloud.expect("cloud catalog should render");
let host = rendered.host.expect("host catalog should render");
assert_eq!(
executor.skill_root_lines,
vec![format!("- `e0` = `{executor_root}`")]
);
assert_eq!(
cloud.skill_root_lines,
vec![format!("- `c0` = `{cloud_root}`")]
);
assert_eq!(
host.skill_root_lines,
vec![format!("- `r0` = `{host_root}`")]
@@ -868,12 +791,6 @@ fn mixed_catalogs_alias_all_skill_sources_under_budget_pressure() {
.iter()
.any(|line| line.contains("(executor package: e0/executor-0)"))
);
assert!(
cloud
.skill_lines
.iter()
.any(|line| line.contains("(cloud package: c0/cloud-0)"))
);
assert!(
host.skill_lines
.iter()
@@ -882,10 +799,9 @@ fn mixed_catalogs_alias_all_skill_sources_under_budget_pressure() {
assert_eq!(
(
executor.report.included_count,
cloud.report.included_count,
host.report.included_count,
),
(3, 3, 3)
(3, 3)
);
}
@@ -922,36 +838,15 @@ fn mixed_catalog_prefers_executor_inclusion_over_total_aliased_inclusion() {
],
warnings: Vec::new(),
};
let cloud_resource = "skill://cloud/one";
let cloud_catalog = SkillCatalog {
is_partial: false,
entries: vec![
SkillCatalogEntry::new(
SkillPackageId("c1".to_string()),
SkillAuthority::new(SkillSourceKind::Cloud, "codex_apps"),
"c1",
"",
SkillResourceId::new(cloud_resource),
)
.with_display_path(cloud_resource),
],
warnings: Vec::new(),
};
let RenderedSkillCatalogs {
host,
executor,
cloud,
} = render_combined_available_skills(
let RenderedSkillCatalogs { host, executor } = render_combined_available_skills(
&executor_catalog,
&cloud_catalog,
&host_catalog,
SkillMetadataBudget::Tokens(74),
/*include_skills_usage_instructions*/ false,
);
let host = host.expect("host catalog should render");
let executor = executor.expect("executor catalog should render");
let cloud = cloud.expect("cloud catalog should render");
assert_eq!(
executor.report,
@@ -973,7 +868,6 @@ fn mixed_catalog_prefers_executor_inclusion_over_total_aliased_inclusion() {
truncated_description_count: 0,
}
);
assert_eq!(cloud.report.total_count, 1);
assert_eq!(host.skill_root_lines, Vec::<String>::new());
}
@@ -1019,7 +913,6 @@ async fn singleton_plugin_versions_share_the_marketplace_alias_root()
host_snapshot: Some(Arc::new(HostSkillsSnapshot::new(Arc::new(outcome)))),
include_host_skills: true,
include_bundled_skills: false,
include_cloud_skills: false,
mcp_resources: None,
executor_capability_discovery: None,
executor_capability_discovery_v2: None,

View File

@@ -54,7 +54,6 @@ async fn turn_input_and_history_advance_while_ranking_is_blocked()
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();
@@ -82,7 +81,6 @@ async fn turn_input_and_history_advance_while_ranking_is_blocked()
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");
@@ -127,12 +125,10 @@ async fn turn_input_and_history_advance_while_ranking_is_blocked()
.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(

View File

@@ -95,13 +95,8 @@ impl ShadowSelectionExperiment {
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
)
{
// Invocation observation covers host shell use.
if !entry.is_model_visible() || entry.authority.kind != SkillSourceKind::Host {
continue;
}
let resource = normalize_skill_resource(entry.main_prompt.as_str());
@@ -123,11 +118,7 @@ impl ShadowSelectionExperiment {
// 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
)
entry.is_model_visible() && entry.authority.kind == SkillSourceKind::Host
}) {
task_context.record(
&input.turn_id,

View File

@@ -3,7 +3,6 @@ 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;
@@ -40,17 +39,12 @@ impl SkillProviderSource {
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,
}
}
@@ -97,29 +91,6 @@ impl SkillProviders {
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()
@@ -131,29 +102,6 @@ impl SkillProviders {
.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

View File

@@ -4,35 +4,25 @@
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;
@@ -40,24 +30,14 @@ 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,
@@ -70,13 +50,10 @@ pub struct SkillsThreadState {
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(),
@@ -95,37 +72,18 @@ impl SkillsThreadState {
}
pub(crate) fn set_config(&self, config: SkillsExtensionConfig) {
let mut previous = self
*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
.unwrap_or_else(std::sync::PoisonError::into_inner) = config;
}
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());
let mut step = SkillStepCatalog::new(executor, discovery_v2, Default::default());
step.aliases = self.aliases.capture(
step.merged
.entries
@@ -277,194 +235,12 @@ impl SkillsThreadState {
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))
providers.read(request).await
}
pub(crate) fn replace_shadow_selection_turn(

View File

@@ -4,7 +4,6 @@ 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;
@@ -16,7 +15,6 @@ pub(crate) struct SkillsStepState {
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,
}
@@ -25,31 +23,18 @@ pub(crate) struct SkillsStepState {
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
};
let mut catalog = executor;
catalog.entries.retain_mut(|entry| {
if !entry.enabled {
return false;
@@ -59,7 +44,6 @@ impl SkillStepCatalog {
});
tracing::debug!(
discovery_v2,
?cloud_skill_count,
executor_skill_count,
enabled_skill_count = catalog.entries.len(),
warning_count = catalog.warnings.len(),
@@ -68,7 +52,6 @@ impl SkillStepCatalog {
Self {
merged: catalog,
aliases,
cloud_warnings,
executor_warnings,
}
}
@@ -86,7 +69,6 @@ impl SkillStepCatalog {
.cloned()
.collect();
let warnings = match authority {
SkillToolAuthoritySelector::Cloud => self.cloud_warnings.clone().unwrap_or_default(),
SkillToolAuthoritySelector::Executor => self.executor_warnings.clone(),
};
SkillCatalog {
@@ -100,14 +82,12 @@ impl SkillStepCatalog {
#[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,
}
}
@@ -116,6 +96,5 @@ impl SkillToolAuthoritySelector {
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum CatalogStatus {
Unavailable,
Disabled,
Enabled,
}

View File

@@ -66,7 +66,7 @@ impl<'call> ToolExecutor<ToolCall<'call>> for InstallationsTool {
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.",
"Find a skill's enabled executor locations, including those omitted by skills.read. Pass its provided package directly; root aliases are resolved automatically. Use source {kind: executor, environment_id: ...} for one environment. Omit source for all locations. 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.",
)
}
@@ -82,7 +82,6 @@ impl<'call> ToolExecutor<ToolCall<'call>> for InstallationsTool {
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)
@@ -170,16 +169,7 @@ impl<'call> ToolExecutor<ToolCall<'call>> for InstallationsTool {
.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)?;
let output = skill_json_output(&response, SkillToolAuthoritySelector::Executor)?;
outcome = if response.installations.is_empty() {
"empty"
} else {

View File

@@ -14,8 +14,6 @@ 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 as InvocationType;
@@ -65,9 +63,6 @@ pub(crate) fn skill_tools(
if !step_state.tools_enabled {
return Vec::new();
}
let mcp_resources = session_store
.get::<SkillsSessionState>()
.and_then(|state| state.mcp_resources.clone());
let invocations = SkillInvocationRecorder::from_stores(session_store, thread_store);
let metrics = step_store
.get::<Arc<dyn ExtensionMetrics>>()
@@ -75,7 +70,6 @@ pub(crate) fn skill_tools(
let context = SkillToolContext {
thread_id: thread_store.level_id().to_string(),
providers,
mcp_resources,
thread_state,
invocations,
step_state,
@@ -189,7 +183,6 @@ impl SkillInvocationRecorder {
struct SkillToolContext {
thread_id: String,
providers: SkillProviders,
mcp_resources: Option<Arc<McpResourceClient>>,
thread_state: Arc<SkillsThreadState>,
invocations: Option<SkillInvocationRecorder>,
step_state: Arc<SkillsStepState>,
@@ -258,22 +251,18 @@ impl SkillToolContext {
#[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(())
let Self::Executor { environment_id } = self;
validate_handle("environment_id", environment_id, MAX_HANDLE_BYTES)
}
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
@@ -289,10 +278,6 @@ impl InstallationSource {
#[serde(untagged)]
#[schemars(deny_unknown_fields)]
enum InstallationLocation {
Cloud {
package: String,
resource: String,
},
Executor {
environment_id: String,
skill_root: String,
@@ -305,10 +290,6 @@ impl InstallationLocation {
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 {
@@ -324,27 +305,22 @@ impl InstallationLocation {
#[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,
SkillSourceKind::Host | SkillSourceKind::Custom(_) => None,
}
}
}
@@ -439,7 +415,6 @@ fn skill_json_output<T: Serialize>(
})?;
let output = JsonToolOutput::new(value);
Ok(match authority {
SkillToolAuthoritySelector::Cloud => Box::new(output.with_external_context()),
SkillToolAuthoritySelector::Executor => Box::new(output),
})
}

View File

@@ -14,7 +14,6 @@ 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;
@@ -109,7 +108,7 @@ impl<'call> ToolExecutor<ToolCall<'call>> for ReadTool {
}
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.",
"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: executor, environment_id: ...} for one environment. Omit source to read the first matching location. The installations list contains 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.",
)
}
@@ -207,7 +206,6 @@ impl<'call> ToolExecutor<ToolCall<'call>> for ReadTool {
tool_namespace = SKILLS_NAMESPACE,
tool_name = TOOL_NAME,
skill_source = match output_authority {
SkillToolAuthoritySelector::Cloud => "cloud",
SkillToolAuthoritySelector::Executor => "executor",
},
skill_name = %skill_entry.name,
@@ -221,12 +219,6 @@ impl<'call> ToolExecutor<ToolCall<'call>> for ReadTool {
"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()
@@ -322,15 +314,6 @@ impl<'call> ToolExecutor<ToolCall<'call>> for ReadTool {
"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;
@@ -400,18 +383,7 @@ impl<'call> ToolExecutor<ToolCall<'call>> for ReadTool {
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)?;
let output = skill_json_output(&response, output_authority)?;
if output_authority == super::SkillToolAuthoritySelector::Executor
&& response.next_cursor.is_some()
&& result.contents.len() <= MAX_SKILL_RESOURCE_CONTENT_BYTES

View File

@@ -9,17 +9,12 @@ 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";
@@ -32,10 +27,6 @@ pub(crate) type CatalogRenderCallback = Box<dyn Fn() + Send + Sync>;
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(
@@ -121,31 +112,6 @@ pub(crate) fn executor_skills_world_state_section(
}
}
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,
@@ -157,8 +123,6 @@ fn skills_world_state_section(
let CatalogSnapshot {
body,
include_instructions,
enabled,
..
} = state;
let retained_body = body.clone();
@@ -168,10 +132,8 @@ fn skills_world_state_section(
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);
}
@@ -226,8 +188,6 @@ pub(crate) fn host_skills_world_state_section(
CatalogSnapshot {
body,
include_instructions,
enabled: None,
allocation: None,
},
NO_HOST_SKILLS_BODY,
HIDDEN_HOST_SKILLS_BODY,

View File

@@ -8,7 +8,6 @@ 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;
@@ -16,10 +15,8 @@ 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;
@@ -30,30 +27,14 @@ 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,
}
@@ -61,7 +42,6 @@ impl CatalogKind {
fn metrics_surface(self) -> CatalogSurface {
match self {
Self::Executor => CatalogSurface::ExecutorWorldState,
Self::Cloud => CatalogSurface::CloudWorldState,
Self::Host => CatalogSurface::HostWorldState,
}
}
@@ -81,17 +61,10 @@ impl CatalogContribution {
}
}
struct CatalogContributions {
executor: CatalogContribution,
cloud: CatalogContribution,
host: CatalogContribution,
}
struct RenderedCatalogContribution {
kind: CatalogKind,
status: CatalogStatus,
budget: SkillMetadataBudget,
allocation: CatalogBudgetAllocation,
rendered: Option<AvailableSkillsRender>,
}
@@ -145,112 +118,49 @@ impl<'a> CatalogRenderingContext<'a> {
})
}
fn render_world_state_catalogs(&self) -> [RenderedCatalogContribution; 3] {
let catalogs = CatalogContributions {
executor: CatalogContribution {
catalog: self
.step_state
.catalog
.select_from_catalog(SkillToolAuthoritySelector::Executor),
fn render_world_state_catalogs(&self) -> [RenderedCatalogContribution; 2] {
let executor_catalog = CatalogContribution {
catalog: self
.step_state
.catalog
.select_from_catalog(SkillToolAuthoritySelector::Executor),
status: CatalogStatus::Enabled,
};
let host_catalog = self.step_state.host_catalog.as_ref().map_or_else(
CatalogContribution::unavailable,
|catalog| CatalogContribution {
catalog: catalog.clone(),
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,
let executor = PreparedSkillCatalog::with_alias_plan(
&executor_catalog.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);
}
let host = PreparedSkillCatalog::new(
&host_catalog.catalog,
SkillCatalogRenderPolicy::CORE_COMPATIBLE
.with_omitted_descriptions(self.step_state.config.omit_descriptions),
);
let mut rendered = if self.step_state.config.include_instructions {
render_prepared_skill_catalogs(
&executor,
&host,
self.metadata_budget,
self.include_usage,
)
} else {
Default::default()
};
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
@@ -262,7 +172,6 @@ impl<'a> CatalogRenderingContext<'a> {
.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 {
@@ -276,125 +185,17 @@ impl<'a> CatalogRenderingContext<'a> {
}
[
(CatalogKind::Executor, catalogs.executor, rendered.executor),
(CatalogKind::Cloud, catalogs.cloud, rendered.cloud),
(CatalogKind::Host, catalogs.host, rendered.host),
(CatalogKind::Executor, executor_catalog, rendered.executor),
(CatalogKind::Host, host_catalog, 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,
budget: self.metadata_budget,
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,
@@ -404,7 +205,6 @@ impl<'a> CatalogRenderingContext<'a> {
kind,
status,
budget,
allocation,
rendered,
} = catalog;
let report = rendered
@@ -437,7 +237,6 @@ impl<'a> CatalogRenderingContext<'a> {
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);
@@ -451,8 +250,7 @@ impl<'a> CatalogRenderingContext<'a> {
CatalogDelta {
rendered,
include_usage: self.include_usage,
tracks_grants: kind != CatalogKind::Cloud,
allocation: (kind == CatalogKind::Cloud).then_some(allocation),
tracks_grants: true,
},
self.input
.previous_world_state
@@ -476,13 +274,6 @@ impl<'a> CatalogRenderingContext<'a> {
.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)
@@ -506,7 +297,6 @@ pub(crate) fn render_world_state_sections(
.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()

View File

@@ -531,7 +531,6 @@ async fn selected_root_id_distinguishes_identical_executor_paths() {
host_snapshot: None,
include_host_skills: false,
include_bundled_skills: true,
include_cloud_skills: false,
mcp_resources: None,
executor_capability_discovery: None,
executor_capability_discovery_v2: None,
@@ -619,7 +618,6 @@ async fn executor_discovery_preserves_posix_and_windows_locator_alias_roots() {
host_snapshot: None,
include_host_skills: false,
include_bundled_skills: true,
include_cloud_skills: false,
mcp_resources: None,
executor_capability_discovery: Some(discovery),
executor_capability_discovery_v2: None,
@@ -744,7 +742,6 @@ async fn executor_discovery_routes_produce_equivalent_catalog_metadata() {
host_snapshot: None,
include_host_skills: false,
include_bundled_skills: true,
include_cloud_skills: false,
mcp_resources: None,
executor_capability_discovery,
executor_capability_discovery_v2: None,
@@ -932,7 +929,6 @@ async fn pre_discovered_executor_catalog_snapshot() {
host_snapshot: None,
include_host_skills: false,
include_bundled_skills: true,
include_cloud_skills: false,
mcp_resources: None,
executor_capability_discovery: Some(executor_capability_discovery),
executor_capability_discovery_v2: None,
@@ -1054,7 +1050,6 @@ async fn direct_executor_discovery_preserves_hidden_nested_and_probed_metadata()
host_snapshot: None,
include_host_skills: false,
include_bundled_skills: true,
include_cloud_skills: false,
mcp_resources: None,
executor_capability_discovery: None,
executor_capability_discovery_v2: None,
@@ -1118,7 +1113,6 @@ async fn high_level_discovery_reuses_materialized_skill_contents_for_reads() {
host_snapshot: None,
include_host_skills: false,
include_bundled_skills: true,
include_cloud_skills: false,
mcp_resources: None,
executor_capability_discovery: Some(executor_capability_discovery),
executor_capability_discovery_v2: None,

View File

@@ -101,9 +101,6 @@ type TestResult = Result<(), Box<dyn std::error::Error>>;
#[path = "skills_extension/shadow_task_context_tests.rs"]
mod shadow_task_context_tests;
#[path = "skills_extension/presentation_dedup_tests.rs"]
mod presentation_dedup_tests;
#[path = "skills_extension/catalog_delta_tests.rs"]
mod catalog_delta_tests;
@@ -274,7 +271,7 @@ async fn skill_world_state_fragments(
session_store: &ExtensionData,
thread_store: &ExtensionData,
turn_id: &str,
) -> Result<(RenderedWorldStateFragment, RenderedWorldStateFragment), Box<dyn std::error::Error>> {
) -> Result<RenderedWorldStateFragment, Box<dyn std::error::Error>> {
let turn_store = ExtensionData::new(turn_id);
let selected_roots = [SelectedCapabilityRoot {
id: "skills".to_string(),
@@ -305,11 +302,7 @@ async fn skill_world_state_fragments(
.render_diff(PreviousWorldStateSection::Absent)
.1
.ok_or("executor skills should render through world state")?;
let cloud = world_state_section(&sections, "cloud_skills")
.render_diff(PreviousWorldStateSection::Absent)
.1
.ok_or("cloud skills should render through world state")?;
Ok((executor, cloud))
Ok(executor)
}
async fn start_registered_turn(
@@ -386,7 +379,6 @@ async fn installed_extension_uses_host_service_snapshot() -> TestResult {
path_to_skills_md: PathUri::from_abs_path(&skill_path),
scope: SkillScope::User,
plugin_id: None,
remote_plugin_id: None,
});
let loaded_skills = Arc::new(outcome);
let skill_prompt_path = skill_path_string.replace('\\', "/");
@@ -468,7 +460,6 @@ async fn host_world_state_records_catalog_metrics_on_publish_and_change() -> Tes
path_to_skills_md: PathUri::from_abs_path(&skill_path),
scope: SkillScope::User,
plugin_id: None,
remote_plugin_id: None,
});
let turn_store = ExtensionData::new("turn-1");
turn_store.insert(HostSkillsSnapshot::new(Arc::new(outcome.clone())));
@@ -542,7 +533,6 @@ async fn host_world_state_records_catalog_metrics_on_publish_and_change() -> Tes
path_to_skills_md: PathUri::from_abs_path(&second_skill_path),
scope: SkillScope::User,
plugin_id: None,
remote_plugin_id: None,
});
turn_store.insert(HostSkillsSnapshot::new(Arc::new(outcome)));
let sections = prepared_world_state(
@@ -599,7 +589,6 @@ async fn persisted_host_snapshot_deduplicates_warning_after_reinitialization() -
path_to_skills_md: PathUri::from_abs_path(&skill_path),
scope: SkillScope::User,
plugin_id: None,
remote_plugin_id: None,
});
let host_snapshot = HostSkillsSnapshot::new(Arc::new(outcome));
@@ -691,12 +680,9 @@ async fn persisted_host_snapshot_deduplicates_warning_after_reinitialization() -
}
#[tokio::test]
async fn executor_cloud_and_host_share_catalog_world_state_flow() -> TestResult {
async fn executor_and_host_share_catalog_world_state_flow() -> TestResult {
let provider = |mut entry: SkillCatalogEntry| {
if matches!(
entry.authority.kind,
SkillSourceKind::Cloud | SkillSourceKind::Host
) {
if entry.authority.kind == SkillSourceKind::Host {
entry.name = "shared-skill".to_string();
}
Arc::new(StaticSkillProvider {
@@ -717,15 +703,6 @@ async fn executor_cloud_and_host_share_catalog_world_state_flow() -> TestResult
"executor/executor-skill",
"skill://executor/executor-skill/SKILL.md",
)))
.with_cloud_provider(provider(
test_entry(
SkillSourceKind::Cloud,
"codex_apps",
"cloud/cloud-skill",
"skill://cloud/cloud-skill/SKILL.md",
)
.with_remote_plugin_id(Some("shared-plugin".to_string())),
))
.with_host_provider(provider(
test_entry(
SkillSourceKind::Host,
@@ -753,7 +730,6 @@ async fn executor_cloud_and_host_share_catalog_world_state_flow() -> TestResult
thread_store: &thread_store,
})
.await;
// Host rendering stays separate even when its identity matches a Cloud skill.
start_registered_turn(&registry, &session_store, &thread_store, "turn-1").await;
let selected_roots = [SelectedCapabilityRoot {
@@ -791,7 +767,7 @@ async fn executor_cloud_and_host_share_catalog_world_state_flow() -> TestResult
.iter()
.map(WorldStateSectionContribution::id)
.collect::<Vec<_>>(),
vec!["skills", "cloud_skills", "host_skills"]
vec!["skills", "host_skills"]
);
assert!(metrics.samples().is_empty());
@@ -800,10 +776,6 @@ async fn executor_cloud_and_host_share_catalog_world_state_flow() -> TestResult
"skills",
"- executor-skill: Fix lint errors. (executor package: executor/executor-skill)",
),
(
"cloud_skills",
"- shared-skill: Fix lint errors. (cloud package: cloud/cloud-skill)",
),
(
"host_skills",
"- shared-skill: Fix lint errors. (file: /skills/host-skill/SKILL.md)",
@@ -817,12 +789,8 @@ async fn executor_cloud_and_host_share_catalog_world_state_flow() -> TestResult
assert!(body.contains(expected_line));
}
let expected_metrics = [
"executor_world_state",
"cloud_world_state",
"host_world_state",
]
.into_iter()
let expected_metrics = ["executor_world_state", "host_world_state"]
.into_iter()
.flat_map(|surface| expected_catalog_metric_samples(surface, /*count*/ 1))
.collect::<Vec<_>>();
assert_eq!(metrics.samples(), expected_metrics);
@@ -1859,7 +1827,6 @@ async fn overlapping_executor_catalogs_render_their_own_roots() -> TestResult {
#[tokio::test]
async fn default_context_truncates_catalog_descriptions() -> TestResult {
let description = "x".repeat(1_025);
// A small cloud catalog leaves its unused allowance to filesystem descriptions.
let executor_entries = (0..5)
.map(|index| {
let package_id = format!("executor/executor-long-description-{index}");
@@ -1873,13 +1840,6 @@ async fn default_context_truncates_catalog_descriptions() -> TestResult {
entry
})
.collect();
let mut cloud_entry = test_entry(
SkillSourceKind::Cloud,
"codex_apps",
"cloud/cloud-long-description",
"skill://cloud/cloud-long-description/SKILL.md",
);
cloud_entry.description = description.clone();
let providers = SkillProviders::new()
.with_executor_provider(Arc::new(StaticSkillProvider {
catalog: SkillCatalog {
@@ -1890,16 +1850,6 @@ async fn default_context_truncates_catalog_descriptions() -> TestResult {
read_requests: Arc::new(Mutex::new(Vec::new())),
list_calls: None,
fail_first_list: false,
}))
.with_cloud_provider(Arc::new(StaticSkillProvider {
catalog: SkillCatalog {
is_partial: false,
entries: vec![cloud_entry],
warnings: Vec::new(),
},
read_requests: Arc::new(Mutex::new(Vec::new())),
list_calls: None,
fail_first_list: false,
}));
let mut builder = ExtensionRegistryBuilder::new();
install_with_providers(&mut builder, providers, skills_extension_config);
@@ -1922,287 +1872,24 @@ async fn default_context_truncates_catalog_descriptions() -> TestResult {
.await;
start_registered_turn(&registry, &session_store, &thread_store, "turn-1").await;
let (executor, cloud) =
let executor =
skill_world_state_fragments(&registry, &session_store, &thread_store, "turn-1").await?;
let executor = executor.body().clone().expect_text();
let cloud = cloud.body().clone().expect_text();
let expected_description = "x".repeat(1_021) + "...";
for index in 0..5 {
assert!(executor.contains(&format!(
"- executor-long-description-{index}: {expected_description} (executor package:"
)));
}
assert!(cloud.contains("- cloud-long-description:"));
for rendered in [executor, cloud] {
assert!(rendered.contains(&expected_description));
assert!(!rendered.contains(&"x".repeat(1_024)));
assert!(!rendered.contains(&description));
}
assert!(!executor.contains(&"x".repeat(1_024)));
assert!(!executor.contains(&description));
Ok(())
}
#[tokio::test]
async fn catalog_rebalances_only_to_avoid_omissions_and_retains_the_allocation() -> TestResult {
enum Phase {
Initial,
FirstReady,
Disconnected,
Reconnected,
Resumed,
CloudCatalogGrew,
BudgetChanged,
}
// Description-only pressure, filesystem omissions that can be rescued, and
// unavoidable omissions. Check both token and fallback character accounting.
for (executor_count, cloud_count, rebalance, all_fit) in [
(17, 82, false, true),
(40, 5, true, true),
(40, 160, false, false),
] {
for context_window in [None, Some(100_000)] {
let description = "x".repeat(1_025);
let executor_entries: Vec<_> = (0..executor_count)
.map(|index| {
let package_id = format!("executor/executor-skill-{index:02}");
let mut entry = test_entry(
SkillSourceKind::Executor,
"env-1",
&package_id,
&format!("skill://{package_id}/SKILL.md"),
);
entry.description = description.clone();
entry
})
.collect();
let registry_for_cloud_count = |cloud_count| {
let cloud_entries = (0..cloud_count)
.map(|index| {
let package_id = format!("cloud/cloud-skill-{index:02}");
let mut entry = test_entry(
SkillSourceKind::Cloud,
"codex_apps",
&package_id,
&format!("skill://{package_id}/SKILL.md"),
);
entry.description = description.clone();
entry
})
.collect();
let providers = SkillProviders::new()
.with_executor_provider(Arc::new(StaticSkillProvider {
catalog: SkillCatalog {
is_partial: false,
entries: executor_entries.clone(),
warnings: Vec::new(),
},
read_requests: Arc::new(Mutex::new(Vec::new())),
list_calls: None,
fail_first_list: false,
}))
.with_cloud_provider(Arc::new(StaticSkillProvider {
catalog: SkillCatalog {
is_partial: false,
entries: cloud_entries,
warnings: Vec::new(),
},
read_requests: Arc::new(Mutex::new(Vec::new())),
list_calls: None,
fail_first_list: false,
}));
let mut builder = ExtensionRegistryBuilder::new();
install_with_providers(&mut builder, providers, skills_extension_config);
builder.build()
};
let mut registry = registry_for_cloud_count(cloud_count);
let selected_roots = [SelectedCapabilityRoot {
id: "skills".to_string(),
location: CapabilityRootLocation::Environment {
environment_id: "env-1".to_string(),
path: PathUri::parse("file:///skills")?,
},
}];
let mut model = ModelInfo {
context_window,
..catalog_model_info()
};
let session_store = ExtensionData::new("session");
let mut thread_store = ExtensionData::new("thread");
let mut previous = serde_json::Map::new();
let mut initial_cloud = None;
let mut accepted_cloud = None;
let mut phases = vec![
Phase::Initial,
Phase::FirstReady,
Phase::Disconnected,
Phase::Reconnected,
Phase::Disconnected,
Phase::Reconnected,
Phase::Resumed,
];
if rebalance {
phases.extend([
Phase::CloudCatalogGrew,
Phase::Disconnected,
Phase::Reconnected,
Phase::Resumed,
]);
}
phases.push(Phase::BudgetChanged);
for (step, phase) in phases.into_iter().enumerate() {
if matches!(phase, Phase::CloudCatalogGrew) {
// Refresh the cloud inventory on resume while retaining the saved allocation.
registry = registry_for_cloud_count(/*cloud_count*/ 15);
}
if matches!(
phase,
Phase::Initial | Phase::Resumed | Phase::CloudCatalogGrew
) {
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: None,
session_store: &session_store,
thread_store: &thread_store,
})
.await;
}
if matches!(phase, Phase::BudgetChanged) {
model.context_window = Some(200_000);
}
let ready = matches!(
phase,
Phase::FirstReady
| Phase::Reconnected
| Phase::Resumed
| Phase::CloudCatalogGrew
);
let turn_id = format!("turn-{step}");
let turn_store = ExtensionData::new(&turn_id);
start_registered_turn(&registry, &session_store, &thread_store, &turn_id).await;
let sections = prepared_world_state(
&registry,
if ready { &selected_roots } else { &[] },
WorldStateContributionInput {
previous_world_state: Some(&previous),
model_info: &model,
thread_id: codex_protocol::ThreadId::new(),
turn_id: &turn_id,
environments: &[],
extension_metrics: None,
session_store: &session_store,
thread_store: &thread_store,
turn_store: &turn_store,
step_store: &turn_store,
},
)
.await;
let rendered = sections
.iter()
.map(|section| {
let prior = previous.get(section.id()).map_or(
PreviousWorldStateSection::Absent,
PreviousWorldStateSection::Known,
);
(section.id().to_string(), section.render_diff(prior))
})
.collect::<std::collections::BTreeMap<_, _>>();
let cloud = &rendered["cloud_skills"];
let cloud_snapshot = cloud.0.as_ref().expect("cloud snapshot");
let cloud_body = cloud_snapshot["body"].as_str().ok_or("cloud catalog")?;
match phase {
Phase::Initial => initial_cloud = Some(cloud_body.to_string()),
Phase::FirstReady => {
assert_eq!(initial_cloud.as_deref() != Some(cloud_body), rebalance);
accepted_cloud = Some(cloud_snapshot.clone());
let executor = rendered["skills"].0.as_ref().expect("executor snapshot");
let executor_body = executor["body"].as_str().ok_or("executor catalog")?;
assert_eq!(
executor_body
.lines()
.filter(|line| line.starts_with("- executor-skill-"))
.count()
== executor_count,
all_fit
);
if all_fit {
assert_eq!(
cloud_body
.lines()
.filter(|line| line.starts_with("- cloud-skill-"))
.count(),
cloud_count
);
}
}
Phase::CloudCatalogGrew => {
let allocation = &cloud_snapshot["allocation"];
let previous_limit = previous["cloud_skills"]["allocation"]["cloudLimit"]
.as_u64()
.ok_or("previous cloud limit")?;
assert!(
allocation["cloudLimit"].as_u64().ok_or("cloud limit")?
> previous_limit
);
assert_ne!(
allocation["cloudCatalogFingerprint"],
previous["cloud_skills"]["allocation"]["cloudCatalogFingerprint"]
);
assert_eq!(
cloud_body
.lines()
.filter(|line| line.starts_with("- cloud-skill-"))
.count(),
15
);
let executor = rendered["skills"].0.as_ref().expect("executor snapshot");
assert_eq!(
executor["body"]
.as_str()
.ok_or("executor catalog")?
.lines()
.filter(|line| line.starts_with("- executor-skill-"))
.count(),
executor_count
);
accepted_cloud = Some(cloud_snapshot.clone());
}
Phase::Disconnected | Phase::Reconnected | Phase::Resumed => {
assert_eq!(Some(cloud_snapshot), accepted_cloud.as_ref());
assert!(cloud.1.is_none());
}
Phase::BudgetChanged => {
// A genuinely different total budget starts a new allocation.
assert_eq!(
cloud_snapshot["allocation"],
serde_json::json!({
"totalBudget": {"tokens": 4_000}, "cloudLimit": 3_000,
"cloudCatalogFingerprint": previous["cloud_skills"]["allocation"]["cloudCatalogFingerprint"],
})
);
}
}
previous = rendered
.into_iter()
.map(|(id, (snapshot, _))| (id, snapshot.expect("skills snapshot")))
.collect();
}
}
}
Ok(())
}
#[tokio::test]
async fn extreme_budget_pressure_removes_descriptions_before_omitting_entries() -> TestResult {
let executor_entries = (0..40)
let executor_entries = (0..200)
.map(|index| {
let package_id = format!("executor/executor-skill-{index:03}");
let mut entry = test_entry(
@@ -2215,19 +1902,6 @@ async fn extreme_budget_pressure_removes_descriptions_before_omitting_entries()
entry
})
.collect();
let cloud_entries = (0..160)
.map(|index| {
let package_id = format!("cloud/cloud-skill-{index:03}");
let mut entry = test_entry(
SkillSourceKind::Cloud,
"codex_apps",
&package_id,
&format!("skill://{package_id}/SKILL.md"),
);
entry.description = format!("cloud-description-{index:03}");
entry
})
.collect();
let providers = SkillProviders::new()
.with_executor_provider(Arc::new(StaticSkillProvider {
catalog: SkillCatalog {
@@ -2238,16 +1912,6 @@ async fn extreme_budget_pressure_removes_descriptions_before_omitting_entries()
read_requests: Arc::new(Mutex::new(Vec::new())),
list_calls: None,
fail_first_list: false,
}))
.with_cloud_provider(Arc::new(StaticSkillProvider {
catalog: SkillCatalog {
is_partial: false,
entries: cloud_entries,
warnings: Vec::new(),
},
read_requests: Arc::new(Mutex::new(Vec::new())),
list_calls: None,
fail_first_list: false,
}));
let (event_tx, event_rx) = std::sync::mpsc::channel();
let mut builder =
@@ -2272,29 +1936,19 @@ async fn extreme_budget_pressure_removes_descriptions_before_omitting_entries()
.await;
start_registered_turn(&registry, &session_store, &thread_store, "turn-1").await;
let (executor, cloud) =
let executor =
skill_world_state_fragments(&registry, &session_store, &thread_store, "turn-1").await?;
let executor = executor.body().clone().expect_text();
let cloud = cloud.body().clone().expect_text();
let included_executor_count = executor
.lines()
.filter(|line| line.starts_with("- executor-skill-"))
.count();
let included_cloud_count = cloud
.lines()
.filter(|line| line.starts_with("- cloud-skill-"))
.count();
assert!(included_executor_count > 0);
assert!(included_executor_count < 40);
assert!(included_cloud_count > 0);
assert!(included_cloud_count < 160);
assert!(included_executor_count < 200);
assert!(executor.contains("- executor-skill-000: (executor package:"));
assert!(cloud.contains("- cloud-skill-000: (cloud package:"));
assert!(!cloud.contains("- cloud-skill-159:"));
for (total, included, rendered) in [
(40, included_executor_count, executor),
(160, included_cloud_count, cloud),
] {
assert!(!executor.contains("- executor-skill-199:"));
{
let (total, included, rendered) = (200, included_executor_count, executor);
assert!(!rendered.contains("description-"));
assert!(rendered.contains("additional skills omitted from this bounded skills list"));
let omitted_count = total - included;
@@ -2316,28 +1970,37 @@ async fn extreme_budget_pressure_removes_descriptions_before_omitting_entries()
#[tokio::test]
async fn skills_list_only_returns_model_visible_bounded_metadata() -> TestResult {
const OVERSIZED_WARNING: &str = "Some skills were omitted because their metadata is too large.";
const PROVIDER_WARNING: &str = "Some cloud skills could not be discovered because the provider disconnected before returning the complete catalog.";
const PROVIDER_WARNING: &str = "Some local skills could not be discovered because the provider disconnected before returning the complete catalog.";
let supplementary_warning = "w".repeat(256);
let opaque_suffix = "\\".repeat(1_500);
// Executor listings carry a 12-byte longer authority (`{"kind":"executor","id":"e"}`)
// than the original single-source fixture, so descriptions are 12 bytes shorter to keep
// the same page boundaries.
let mut entry = test_entry(
SkillSourceKind::Cloud,
"codex_apps",
&format!("cloud/{opaque_suffix}"),
&format!("skill://cloud/{opaque_suffix}/SKILL.md"),
SkillSourceKind::Executor,
"e",
&format!("local/{opaque_suffix}"),
&format!("skill://local/{opaque_suffix}/SKILL.md"),
);
entry.description = "x".repeat(1_025);
let [first_entry, mut middle_entry, mut final_entry] = ["p0", "p1", "p2"].map(|name| {
entry.main_prompt = SkillResourceId::environment(
format!("skill://local/{opaque_suffix}/SKILL.md"),
"env-1",
PathUri::parse("file:///skills/opaque/SKILL.md")?,
);
entry.description = "x".repeat(1_012);
let [mut first_entry, mut middle_entry, mut final_entry] = ["p0", "p1", "p2"].map(|name| {
test_entry(
SkillSourceKind::Cloud,
"codex_apps",
SkillSourceKind::Executor,
"e",
name,
&format!("skill://{name}/SKILL.md"),
)
});
middle_entry.description = "d".repeat(110);
final_entry.description = "d".repeat(50);
let providers = SkillProviders::new().with_cloud_provider(Arc::new(StaticSkillProvider {
first_entry.description = "Fix.".to_string();
middle_entry.description = "d".repeat(98);
final_entry.description = "d".repeat(38);
let providers = SkillProviders::new().with_executor_provider(Arc::new(StaticSkillProvider {
catalog: SkillCatalog {
is_partial: false,
entries: vec![
@@ -2346,10 +2009,10 @@ async fn skills_list_only_returns_model_visible_bounded_metadata() -> TestResult
middle_entry,
final_entry,
test_entry(
SkillSourceKind::Cloud,
"codex_apps",
"cloud/hidden",
"skill://cloud/hidden/SKILL.md",
SkillSourceKind::Executor,
"e",
"local/hidden",
"skill://local/hidden/SKILL.md",
)
.hidden_from_prompt(),
],
@@ -2386,9 +2049,16 @@ async fn skills_list_only_returns_model_visible_bounded_metadata() -> TestResult
start_registered_turn(&registry, &session_store, &thread_store, "turn-1").await;
let step_store = ExtensionData::new("step");
let selected_roots = [SelectedCapabilityRoot {
id: "skills".to_string(),
location: CapabilityRootLocation::Environment {
environment_id: "env-1".to_string(),
path: PathUri::parse("file:///skills")?,
},
}];
prepared_world_state(
&registry,
&[],
&selected_roots,
WorldStateContributionInput {
previous_world_state: None,
step_store: &step_store,
@@ -2410,7 +2080,7 @@ async fn skills_list_only_returns_model_visible_bounded_metadata() -> TestResult
.find(|tool| tool.tool_name().name == "list")
.ok_or("skills.list tool should be registered")?;
let payload = ToolPayload::Function {
arguments: serde_json::json!({"authority": {"kind": "cloud"}}).to_string(),
arguments: serde_json::json!({"authority": {"kind": "executor"}}).to_string(),
};
let call = ToolCall {
turn_id: "turn-1".to_string(),
@@ -2435,7 +2105,7 @@ async fn skills_list_only_returns_model_visible_bounded_metadata() -> TestResult
.as_array()
.ok_or("skills.list should return skills")?;
assert_eq!(complete_skills.len(), 4);
assert_eq!(complete_skills[0]["description"], "x".repeat(1_021) + "...");
assert_eq!(complete_skills[0]["description"], "x".repeat(1_012));
assert_eq!(
complete_response["warnings"].as_array().map(Vec::len),
Some(4)
@@ -2480,7 +2150,7 @@ async fn skills_list_only_returns_model_visible_bounded_metadata() -> TestResult
{
let payload = ToolPayload::Function {
arguments: serde_json::json!({
"authority": {"kind": "cloud"},
"authority": {"kind": "executor"},
"cursor": cursor,
})
.to_string(),
@@ -2494,7 +2164,7 @@ async fn skills_list_only_returns_model_visible_bounded_metadata() -> TestResult
..call.clone()
})
.await?;
assert!(output.contains_external_context());
assert!(!output.contains_external_context());
let response = output
.post_tool_use_response(&call_id, &payload)
.ok_or("skills.list should expose structured output")?;
@@ -2525,7 +2195,7 @@ async fn skills_list_only_returns_model_visible_bounded_metadata() -> TestResult
.ok_or("cursor should include its budget")?;
let legacy_payload = ToolPayload::Function {
arguments: serde_json::json!({
"authority": {"kind": "cloud"},
"authority": {"kind": "executor"},
"cursor": legacy_cursor,
})
.to_string(),
@@ -2569,7 +2239,7 @@ async fn skills_list_only_returns_model_visible_bounded_metadata() -> TestResult
// The resource fits the 2400-byte budget before escaping, but not after.
let insufficient_budget_payload = ToolPayload::Function {
arguments: serde_json::json!({
"package": format!("cloud/{opaque_suffix}"),
"package": format!("local/{opaque_suffix}"),
})
.to_string(),
};
@@ -2586,7 +2256,11 @@ async fn skills_list_only_returns_model_visible_bounded_metadata() -> TestResult
turn_item_emitter: Arc::new(NoopTurnItemEmitter),
attachment_store: Arc::new(InlineAttachmentStore),
ephemeral: false,
environments: Vec::new(),
environments: vec![codex_extension_api::ToolEnvironment::new(
"env-1".to_string(),
PathUri::parse("file:///skills")?,
&FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS),
)],
payload: insufficient_budget_payload,
})
.await
@@ -2601,138 +2275,6 @@ async fn skills_list_only_returns_model_visible_bounded_metadata() -> TestResult
Ok(())
}
#[tokio::test]
async fn cloud_discovery_is_gated_and_reports_failures() -> TestResult {
for (cloud_skill_enabled, has_cloud_provider) in [(false, true), (true, true), (true, false)] {
let list_calls = Arc::new(AtomicUsize::new(0));
let mut providers = SkillProviders::new();
if has_cloud_provider {
providers = providers.with_cloud_provider(Arc::new(StaticSkillProvider {
catalog: SkillCatalog::default(),
read_requests: Arc::new(Mutex::new(Vec::new())),
list_calls: Some(Arc::clone(&list_calls)),
fail_first_list: true,
}));
}
let cloud_available = cloud_skill_enabled && has_cloud_provider;
let (event_tx, event_rx) = std::sync::mpsc::channel();
let mut builder =
ExtensionRegistryBuilder::with_event_sink(Arc::new(ChannelEventSink(event_tx)));
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");
let session_source = SessionSource::Cli;
let config = TestConfig {
cloud_skill_enabled,
..default_config()
};
registry.thread_lifecycle_contributors()[0]
.on_thread_start(ThreadStartInput {
config: &config,
session_source: &session_source,
persistent_thread_state_available: true,
environments: &[],
mcp_resource_client: None,
extension_metrics: None,
session_store: &session_store,
thread_store: &thread_store,
})
.await;
assert_eq!(
registry
.turn_lifecycle_contributors()
.iter()
.map(|contributor| contributor.turn_start_phase(&thread_store))
.collect::<Vec<_>>(),
vec![
codex_extension_api::TurnStartPhase::BeforeTaskRegistration,
if cloud_available {
codex_extension_api::TurnStartPhase::RegularTaskStart
} else {
codex_extension_api::TurnStartPhase::BeforeTaskRegistration
},
]
);
assert_eq!(
registry
.turn_lifecycle_contributors()
.iter()
.map(|contributor| contributor.requires_mcp_runtime(&thread_store))
.collect::<Vec<_>>(),
vec![false, cloud_available]
);
start_registered_turn(&registry, &session_store, &thread_store, "turn-1").await;
assert_eq!(
list_calls.load(Ordering::Relaxed),
usize::from(cloud_available)
);
for discovery_v2 in [None, Some([].as_slice())] {
let step_store = ExtensionData::new("step");
if let Some(snapshots) = discovery_v2 {
step_store.insert(Vec::<
codex_exec_server::ExecutorCapabilityDiscoveryV2Snapshot,
>::from(snapshots));
}
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: &ExtensionData::new("turn-1"),
},
)
.await;
if has_cloud_provider {
// Resume may retain a catalog even when the new Cloud discovery fails.
let previous = serde_json::json!({
"body": "Previously advertised Cloud skills",
"includeInstructions": true,
"enabled": true,
});
let update = world_state_section(&sections, "cloud_skills")
.render_diff(PreviousWorldStateSection::Known(&previous))
.1
.ok_or("unavailable Cloud skills should withdraw the previous catalog")?;
assert_eq!(
update.body().clone().expect_text(),
"\n## Cloud skills update\nNo cloud skills are currently available.\n"
);
} else {
assert!(
sections
.iter()
.all(|section| section.id() != "cloud_skills")
);
}
}
if !cloud_available {
assert!(event_rx.try_recv().is_err());
let tools = registry.tool_contributors()[0].tools_for_step(
&session_store,
&thread_store,
&ExtensionData::new("step"),
);
assert!(tools.iter().all(|tool| tool.tool_name().name != "list"));
continue;
}
let warning = event_rx.try_recv()?.into_warning();
assert_eq!(warning.thread_id, thread_store.level_id());
assert_eq!(warning.turn_id.as_deref(), Some("turn-1"));
assert!(warning.message.contains("temporary cloud failure"));
}
Ok(())
}
#[tokio::test]
async fn v2_root_aliases_and_read_cache_use_the_captured_environment() -> TestResult {
let directory = tempfile::tempdir()?;
@@ -3046,17 +2588,7 @@ async fn root_qualified_locator_selects_only_the_matching_executor_skill() -> Te
}
#[tokio::test]
async fn model_context_window_scales_executor_and_cloud_catalogs() -> TestResult {
let cloud_entries = (0..40)
.map(|index| {
test_entry(
SkillSourceKind::Cloud,
"cloud",
&format!("cloud/skill-{index:02}"),
&format!("skill-{index:02}/SKILL.md"),
)
})
.collect();
async fn model_context_window_scales_executor_catalog() -> TestResult {
let executor_entries = (0..200)
.map(|index| {
test_entry(
@@ -3067,18 +2599,8 @@ async fn model_context_window_scales_executor_and_cloud_catalogs() -> TestResult
)
})
.collect();
let providers = SkillProviders::new()
.with_cloud_provider(Arc::new(StaticSkillProvider {
catalog: SkillCatalog {
is_partial: false,
entries: cloud_entries,
warnings: Vec::new(),
},
read_requests: Arc::new(Mutex::new(Vec::new())),
list_calls: None,
fail_first_list: false,
}))
.with_executor_provider(Arc::new(StaticSkillProvider {
let providers =
SkillProviders::new().with_executor_provider(Arc::new(StaticSkillProvider {
catalog: SkillCatalog {
is_partial: false,
entries: executor_entries,
@@ -3167,29 +2689,14 @@ async fn model_context_window_scales_executor_and_cloud_catalogs() -> TestResult
executor_section.render_diff(PreviousWorldStateSection::Absent);
let snapshot = snapshot.unwrap();
let executor_fragment = executor_fragment.ok_or("bounded executor catalog should render")?;
assert!(
!executor_fragment
.body()
.clone()
.expect_text()
.contains("skill-39")
);
let cloud_fragment = world_state_section(&sections, "cloud_skills")
.render_diff(PreviousWorldStateSection::Absent)
.1
.ok_or("bounded cloud catalog should render")?;
assert!(
cloud_fragment
.body()
.clone()
.expect_text()
.contains("additional skills omitted")
);
let executor_body = executor_fragment.body().clone().expect_text();
assert!(!executor_body.contains("skill-199"));
assert!(executor_body.contains("additional skills omitted"));
let warnings = event_rx
.try_iter()
.map(CapturedExtensionEvent::into_warning)
.collect::<Vec<_>>();
assert_eq!(warnings.len(), 2);
assert_eq!(warnings.len(), 1);
for warning in warnings {
assert_eq!(warning.thread_id, thread_store.level_id());
assert_eq!(warning.turn_id.as_deref(), Some("turn-1"));
@@ -3663,7 +3170,7 @@ impl SkillProvider for StaticSkillProvider {
let catalog = self.catalog.clone();
Box::pin(async move {
if fail {
Err(SkillProviderError::new("temporary cloud failure"))
Err(SkillProviderError::new("temporary provider failure"))
} else {
Ok(catalog)
}
@@ -3719,7 +3226,6 @@ struct TestConfig {
catalog_deltas_enabled: bool,
omit_descriptions: bool,
bundled_skills_enabled: bool,
cloud_skill_enabled: bool,
shadow_selection_enabled: bool,
}
@@ -3729,7 +3235,6 @@ fn default_config() -> TestConfig {
catalog_deltas_enabled: false,
omit_descriptions: false,
bundled_skills_enabled: true,
cloud_skill_enabled: true,
shadow_selection_enabled: false,
}
}
@@ -3741,7 +3246,6 @@ fn skills_extension_config(config: &TestConfig) -> SkillsExtensionConfig {
omit_descriptions: config.omit_descriptions,
max_context_tokens: None,
bundled_skills_enabled: config.bundled_skills_enabled,
cloud_skill_enabled: config.cloud_skill_enabled,
shadow_selection_enabled: config.shadow_selection_enabled,
}
}

View File

@@ -77,7 +77,6 @@ async fn skill_sources_spend_the_same_remaining_budget() -> TestResult {
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?,
@@ -277,7 +276,6 @@ async fn render_catalogs_for_step(
};
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);

View File

@@ -10,7 +10,6 @@ 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(
@@ -22,7 +21,6 @@ fn installation(
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 {
@@ -95,7 +93,6 @@ async fn v2_steps_refresh_metadata_and_preserve_separate_environments() -> TestR
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()),
@@ -121,8 +118,7 @@ async fn v2_steps_refresh_metadata_and_preserve_separate_environments() -> TestR
);
let catalog = provider.list(query).await?;
assert_eq!(catalog.entries.len(), 4);
let merged = merge_catalogs(/*cloud*/ None, catalog.clone());
assert_eq!(merged, catalog);
let merged = catalog;
for entries in [
(&merged.entries[0], &merged.entries[2]),
(&merged.entries[1], &merged.entries[3]),
@@ -306,7 +302,6 @@ async fn v2_empty_failed_and_partial_results_never_load_legacy_roots() -> TestRe
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),

View File

@@ -6,25 +6,24 @@ use pretty_assertions::assert_eq;
#[tokio::test]
async fn skill_names_preserve_package_and_alias_precedence_in_both_versions() -> TestResult {
for discovery_v2 in [false, true] {
let cloud = cloud_skill("work").with_alias_root("skill://Plugin_123");
let mut hidden = cloud_skill("hidden").hidden_from_prompt();
hidden.name = cloud.name.clone();
let mut disabled = cloud_skill("disabled").disabled();
disabled.name = cloud.name.clone();
let skill = executor_skill("work").with_alias_root("skill://Plugin_123");
let mut hidden = executor_skill("hidden").hidden_from_prompt();
hidden.name = skill.name.clone();
let mut disabled = executor_skill("disabled").disabled();
disabled.name = skill.name.clone();
let disabled_package = disabled.id.0.clone();
let mut entries = vec![cloud.clone(), hidden, disabled];
let mut entries = vec![skill.clone(), hidden, disabled];
for (id, name) in [
("package-shadow", cloud.id.0.as_str()),
("alias-shadow", "c0/work"),
("package-shadow", skill.id.0.as_str()),
("alias-shadow", "e0/work"),
("disabled-package-shadow", disabled_package.as_str()),
("disabled-alias-shadow", "c0/disabled"),
("disabled-alias-shadow", "e0/disabled"),
] {
let mut shadow = cloud_skill(id);
let mut shadow = executor_skill(id);
shadow.name = name.to_string();
entries.push(shadow);
}
let mut harness =
MergeHarness::new(provider(vec![]), provider(entries), default_config()).await?;
let mut harness = MergeHarness::new(provider(entries), default_config()).await?;
if !discovery_v2 {
harness.snapshots = None;
}
@@ -35,8 +34,8 @@ async fn skill_names_preserve_package_and_alias_precedence_in_both_versions() ->
} else {
vec!["read"]
} {
let expected = call_tool(&tools, tool, json!({"package": cloud.id.0})).await?;
for package in [cloud.name.as_str(), "c0/work"] {
let expected = call_tool(&tools, tool, json!({"package": skill.id.0})).await?;
for package in [skill.name.as_str(), "e0/work"] {
assert_eq!(
call_tool(&tools, tool, json!({"package": package})).await?,
expected,
@@ -44,9 +43,9 @@ async fn skill_names_preserve_package_and_alias_precedence_in_both_versions() ->
);
}
if tool == "read" {
assert_eq!(expected["resource"], cloud.main_prompt.as_str());
assert_eq!(expected["resource"], skill.main_prompt.as_str());
}
for package in [disabled_package.as_str(), "c0/disabled"] {
for package in [disabled_package.as_str(), "e0/disabled"] {
assert_eq!(
call_tool(&tools, tool, json!({"package": package})).await,
Err(FunctionCallError::RespondToModel(
@@ -59,63 +58,18 @@ async fn skill_names_preserve_package_and_alias_precedence_in_both_versions() ->
Ok(())
}
#[tokio::test]
async fn listed_skill_names_preserve_merged_locations_and_source_filters() -> TestResult {
let mut cloud = cloud_skill("work");
let mut executor = installed_skill("first", "work")?;
// A valid qualified name can exceed the byte limit in skills.list.
cloud.name = format!("x:{}", "🦀".repeat(64));
executor.name.clone_from(&cloud.name);
let harness = MergeHarness::new(
provider(vec![executor]),
provider(vec![cloud.clone()]),
default_config(),
)
.await?;
harness
.turn_store
.insert(selected_plugins(&[None, Some("env-1:first")], &[]));
let tools = harness.tools(&harness.step_store).await;
let listed = call_tool(&tools, "list", json!({"authority": {"kind": "cloud"}})).await?;
for tool in ["read", "installations"] {
for source in [
Value::Null,
json!({"kind": "cloud"}),
json!({"kind": "executor", "environment_id": "env-1"}),
] {
assert_eq!(
call_tool(
&tools,
tool,
json!({"package": listed["skills"][0]["name"], "source": source})
)
.await?,
call_tool(
&tools,
tool,
json!({"package": cloud.id.0, "source": source})
)
.await?,
"{tool}: {source}",
);
}
}
Ok(())
}
#[tokio::test]
async fn ambiguous_skill_names_require_a_package_locator() -> TestResult {
let prefix = format!("x:{}", "🦀".repeat(63));
let mut first = cloud_skill("work");
let mut first = executor_skill("work");
first.name = format!("{prefix}🦀");
let mut second = cloud_skill("another");
let mut second = executor_skill("another");
second.name = first.name.clone();
let mut shorter = cloud_skill("shorter");
let mut shorter = executor_skill("shorter");
shorter.name = prefix.clone();
let hidden = cloud_skill("hidden").hidden_from_prompt();
let disabled = cloud_skill("disabled").disabled();
let hidden = executor_skill("hidden").hidden_from_prompt();
let disabled = executor_skill("disabled").disabled();
let harness = MergeHarness::new(
provider(vec![]),
provider(vec![first.clone(), second, shorter, hidden, disabled]),
default_config(),
)

View File

@@ -7,7 +7,7 @@ use tokio::sync::Notify;
struct PausedExecutor {
entered: Notify,
resume: Notify,
queries: Mutex<Vec<(bool, bool)>>,
queries: Mutex<Vec<bool>>,
}
impl SkillProvider for PausedExecutor {
@@ -16,7 +16,7 @@ impl SkillProvider for PausedExecutor {
self.queries
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.push((query.include_bundled_skills, query.include_cloud_skills));
.push(query.include_bundled_skills);
self.entered.notify_one();
self.resume.notified().await;
Ok(SkillCatalog::default())
@@ -36,31 +36,13 @@ impl SkillProvider for PausedExecutor {
}
#[tokio::test]
async fn config_reload_during_preparation_applies_to_next_step_but_reads_still_check_live_policy()
-> TestResult {
async fn config_reload_during_preparation_applies_to_next_step() -> TestResult {
let executor = Arc::new(PausedExecutor {
entered: Notify::new(),
resume: Notify::new(),
queries: Mutex::default(),
});
let cloud = test_entry(
SkillSourceKind::Cloud,
"codex_apps",
"cloud/demo",
"skill://cloud/demo/SKILL.md",
);
let cloud_reads = Arc::default();
let providers = SkillProviders::new()
.with_executor_provider(executor.clone())
.with_cloud_provider(Arc::new(StaticSkillProvider {
catalog: SkillCatalog {
entries: vec![cloud],
..Default::default()
},
read_requests: Arc::clone(&cloud_reads),
list_calls: None,
fail_first_list: false,
}));
let providers = SkillProviders::new().with_executor_provider(executor.clone());
let mut builder = ExtensionRegistryBuilder::new();
install_with_providers(&mut builder, providers, skills_extension_config);
let registry = builder.build();
@@ -69,7 +51,6 @@ async fn config_reload_during_preparation_applies_to_next_step_but_reads_still_c
let turn = ExtensionData::new("turn");
let config = default_config();
let updated = TestConfig {
cloud_skill_enabled: false,
bundled_skills_enabled: false,
..config.clone()
};
@@ -96,8 +77,8 @@ async fn config_reload_during_preparation_applies_to_next_step_but_reads_still_c
let step = ExtensionData::new("step");
let next_step = ExtensionData::new("next-step");
let model_info = catalog_model_info();
for (store, expected_enabled) in [(&step, true), (&next_step, false)] {
let (sections, ()) = tokio::join!(
for store in [&step, &next_step] {
let (_sections, ()) = tokio::join!(
prepared_world_state(
&registry,
&roots,
@@ -121,30 +102,10 @@ async fn config_reload_during_preparation_applies_to_next_step_but_reads_still_c
executor.resume.notify_one();
}
);
let rendered = sections
.iter()
.filter_map(|section| section.render_diff(PreviousWorldStateSection::Absent).1)
.map(|fragment| fragment.body().clone().expect_text())
.collect::<Vec<_>>()
.join("\n");
assert_eq!(
rendered.contains("cloud/demo"),
expected_enabled,
"{rendered}"
);
}
assert_eq!(
*executor.queries.lock().unwrap(),
vec![(true, true), (false, false)]
vec![true, false]
);
let tools = registry.tool_contributors()[0].tools_for_step(&session, &thread, &step);
let result = merge_catalog_tests::call_tool(
&tools,
"read",
serde_json::json!({"package": "cloud/demo"}),
)
.await;
assert_matches!(result, Err(FunctionCallError::RespondToModel(message)) if message == "failed to read skill resource");
assert!(read_request_keys(&cloud_reads).is_empty());
Ok(())
}

View File

@@ -1,267 +0,0 @@
//! Pre-budget deduplication preserves source packages and aliases across executor readiness changes.
use super::*;
use codex_exec_server::EnvironmentManager;
use codex_extension_api::ToolEnvironment;
use pretty_assertions::assert_eq;
#[tokio::test]
async fn cloud_preference_preserves_aliases_reads_and_executor_fallback() -> TestResult {
for (cloud_enabled, all_overlap) in [(true, false), (false, false), (true, true)] {
let description = format!("{} UNIQUE_DESCRIPTION_END", "Skill guidance. ".repeat(60));
let executor_roots = [
format!("skill://executor-a/{}", "a".repeat(180)),
format!("skill://executor-b/{}", "b".repeat(180)),
];
let mut executor_entries = Vec::new();
for (plugin, root) in ["demo", "other"].into_iter().zip(&executor_roots) {
for index in 0..3 {
let package = format!("{root}/s{index}");
let mut entry = test_entry(
SkillSourceKind::Executor,
"skills",
&package,
&format!("{package}/SKILL.md"),
);
entry.name = format!("{plugin}:s{index}");
entry.description = description.clone();
entry.main_prompt = SkillResourceId::environment(
format!("{package}/SKILL.md"),
"local",
PathUri::parse(&format!("file:///skills/{plugin}/s{index}/SKILL.md"))?,
);
executor_entries.push(entry.with_alias_root(root));
}
}
let mut cloud_entries = Vec::new();
for plugin in if all_overlap {
vec!["demo", "other"]
} else {
vec!["demo"]
} {
for index in 0..3 {
let mut entry = test_entry(
SkillSourceKind::Cloud,
"codex_apps",
&format!("cloud/{plugin}/s{index}"),
&format!("cloud/{plugin}/s{index}/SKILL.md"),
);
entry.name = format!("{plugin}:s{index}");
cloud_entries.push(entry);
}
}
let provider = |entries| {
Arc::new(StaticSkillProvider {
catalog: SkillCatalog {
is_partial: false,
entries,
warnings: Vec::new(),
},
read_requests: Arc::new(Mutex::new(Vec::new())),
list_calls: None,
fail_first_list: false,
})
};
let providers = SkillProviders::new()
.with_executor_provider(provider(executor_entries.clone()))
.with_cloud_provider(provider(cloud_entries));
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");
let config = TestConfig {
cloud_skill_enabled: cloud_enabled,
..default_config()
};
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;
let roots = [SelectedCapabilityRoot {
id: "skills".to_string(),
location: CapabilityRootLocation::Environment {
environment_id: "local".to_string(),
path: PathUri::parse("file:///skills")?,
},
}];
let resolved_roots = EnvironmentManager::default_for_tests()
.resolve_selected_capability_roots(&roots, &Default::default())
.await;
assert_eq!(resolved_roots.len(), 1);
let access = FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS);
let mut previous = serde_json::Map::new();
let mut initial_cloud_body = None;
let model_info = ModelInfo {
context_window: Some(70_000),
..catalog_model_info()
};
for (stage, ready) in [
("before", false),
("connected", true),
("disconnected", false),
] {
start_registered_turn(&registry, &session_store, &thread_store, stage).await;
let turn_store = ExtensionData::new(stage);
let sections = prepared_world_state(
&registry,
if ready { &roots } else { &[] },
WorldStateContributionInput {
previous_world_state: Some(&previous),
model_info: &model_info,
thread_id: codex_protocol::ThreadId::new(),
turn_id: stage,
environments: &[],
extension_metrics: None,
session_store: &session_store,
thread_store: &thread_store,
turn_store: &turn_store,
step_store: &turn_store,
},
)
.await;
let snapshots: serde_json::Map<String, serde_json::Value> = sections
.iter()
.map(|section| {
let previous = previous.get(section.id()).map_or(
PreviousWorldStateSection::Absent,
PreviousWorldStateSection::Known,
);
let snapshot = section.render_diff(previous).0.expect("skills snapshot");
(section.id().to_string(), snapshot)
})
.collect();
let executor_body = snapshots["skills"]["body"]
.as_str()
.unwrap_or_default()
.to_string();
let cloud_body = snapshots["cloud_skills"]["body"]
.as_str()
.unwrap_or_default()
.to_string();
for index in 0..3 {
let listing = format!("- demo:s{index}:");
assert_eq!(executor_body.contains(&listing), ready && !cloud_enabled);
assert_eq!(cloud_body.contains(&listing), cloud_enabled);
assert_eq!(
executor_body.contains(&format!("- other:s{index}:")),
ready && !all_overlap
);
}
assert_eq!(
executor_body.matches("UNIQUE_DESCRIPTION_END").count(),
if ready && cloud_enabled && !all_overlap {
3
} else {
0
}
);
if stage == "before" {
initial_cloud_body = Some(cloud_body.clone());
} else {
assert_eq!(Some(&cloud_body), initial_cloud_body.as_ref());
}
if !ready || all_overlap {
assert!(executor_body.is_empty());
} else {
assert!(executor_body.contains("(executor package: e1/s0)"));
for (index, root) in executor_roots.iter().enumerate() {
assert_eq!(
executor_body.contains(&format!("- `e{index}` = `{root}`")),
index == 1 || !cloud_enabled,
);
}
}
previous = snapshots;
if !ready {
continue;
}
turn_store.insert(resolved_roots.clone());
let tools = registry.tool_contributors()[0].tools_for_step(
&session_store,
&thread_store,
&turn_store,
);
for (name, arguments, expected_resource) in [
(
"list",
serde_json::json!({"authority": {"kind": "executor"}}),
None,
),
(
"read",
serde_json::json!({"package": "e0/s0"}),
Some(executor_entries[0].main_prompt.as_str()),
),
(
"read",
serde_json::json!({"package": "e1/s0"}),
Some(executor_entries[3].main_prompt.as_str()),
),
(
"read",
serde_json::json!({"package": executor_entries[0].id.0}),
Some(executor_entries[0].main_prompt.as_str()),
),
] {
let tool = tools
.iter()
.find(|tool| tool.tool_name().name == name)
.ok_or("missing tool")?;
let payload = ToolPayload::Function {
arguments: arguments.to_string(),
};
let output = tool
.handle(ToolCall {
turn_id: stage.to_string(),
call_id: "call".to_string(),
tool_name: tool.tool_name(),
model: "test".to_string(),
codex_turn_metadata: None,
truncation_policy: TruncationPolicy::Bytes(20_000),
source: ToolCallSource::Direct,
conversation_history: ConversationHistory::default(),
turn_item_emitter: Arc::new(NoopTurnItemEmitter),
attachment_store: Arc::new(InlineAttachmentStore),
ephemeral: false,
environments: vec![ToolEnvironment::new(
"local".to_string(),
PathUri::parse("file:///skills")?,
&access,
)],
payload: payload.clone(),
})
.await?;
let response = output
.post_tool_use_response("call", &payload)
.ok_or("missing response")?;
if let Some(resource) = expected_resource {
assert_eq!(response["resource"], resource);
} else {
assert_eq!(
response["skills"]
.as_array()
.ok_or("missing skills")?
.iter()
.map(|skill| skill["package"].as_str())
.collect::<Vec<_>>(),
executor_entries
.iter()
.map(|entry| Some(entry.id.0.as_str()))
.collect::<Vec<_>>()
);
}
}
}
}
Ok(())
}

View File

@@ -43,14 +43,11 @@ impl<S: tracing::Subscriber> Layer<S> for ReadEvents {
}
#[tokio::test]
async fn source_events_cover_cached_cloud_and_explicit_executor_reads() -> TestResult {
let cloud = cloud_skill("work").with_plugin_id(Some("cloud-plugin".into()));
async fn source_events_cover_default_and_explicit_executor_reads() -> TestResult {
let installed = installed_skill("matching", "work")?;
let cloud_provider = provider(vec![cloud.clone()]);
let cloud_reads = cloud_provider.read_requests.clone();
let executor = provider(vec![installed]);
let executor = provider(vec![installed.clone()]);
let executor_reads = executor.read_requests.clone();
let harness = MergeHarness::new(executor, cloud_provider, default_config()).await?;
let harness = MergeHarness::new(executor, default_config()).await?;
harness
.turn_store
.insert(selected_plugins(&[None, Some("env-1:matching")], &[]));
@@ -64,16 +61,14 @@ async fn source_events_cover_cached_cloud_and_explicit_executor_reads() -> TestR
let _interest_cache_guard =
tracing::Dispatch::new(tracing::subscriber::NoSubscriber::default());
async {
for source in ["cloud", "cloud", "executor", "executor"] {
let selector = if source == "executor" {
json!({"kind": source, "environment_id": "env-1"})
} else {
json!({"kind": source})
};
for selector in [
Value::Null,
json!({"kind": "executor", "environment_id": "env-1"}),
] {
call_tool(
&tools,
"read",
json!({"package": cloud.id.0, "source": selector}),
json!({"package": installed.id.0, "source": selector}),
)
.await?;
}
@@ -87,7 +82,7 @@ async fn source_events_cover_cached_cloud_and_explicit_executor_reads() -> TestR
.with_subscriber(subscriber)
.await?;
let expected = ["cloud", "cloud", "executor", "executor"].map(|source| {
let expected = [(); 2].map(|()| {
json!({
"message": "Selected skill read source",
"event.name": "codex.skill_read.source_selected",
@@ -96,21 +91,14 @@ async fn source_events_cover_cached_cloud_and_explicit_executor_reads() -> TestR
"call_id": "skill-test",
"tool_namespace": "skills",
"tool_name": "read",
"skill_source": source,
"skill_source": "executor",
"skill_name": "deploy:work",
"skill_plugin_id": if source == "cloud" { "cloud-plugin" } else { "matching" },
"skill_plugin_id": "matching",
"skill_resource_kind": "main_prompt",
"is_continuation": false,
})
});
assert_eq!(*events.0.lock().unwrap(), expected);
// Both cloud reads are attributable even though the second needs no provider call.
assert_eq!(
(
read_request_keys(&cloud_reads).len(),
read_request_keys(&executor_reads).len()
),
(1, 2),
);
assert_eq!(read_request_keys(&executor_reads).len(), 2);
Ok(())
}

View File

@@ -38,9 +38,9 @@ async fn reads_report_outcomes_for_each_discovery_version() -> TestResult {
PathUri::parse("file:///skills/local/SKILL.md")?,
);
let mut harness = MergeHarness::new(
provider(vec![executor]),
provider(vec![
cloud_skill("work").with_alias_root("skill://Plugin_123"),
executor,
executor_skill("work").with_alias_root("skill://Plugin_123"),
]),
default_config(),
)
@@ -59,7 +59,7 @@ async fn reads_report_outcomes_for_each_discovery_version() -> TestResult {
),
(json!({}), 10_000, "invalid_arguments"),
(json!({"package": "missing"}), 10_000, "package_unavailable"),
(json!({"package": "c99/work"}), 10_000, "unresolved_alias"),
(json!({"package": "e99/work"}), 10_000, "unresolved_alias"),
(
json!({"package": "skill://executor/local"}),
10_000,
@@ -80,27 +80,10 @@ async fn reads_report_outcomes_for_each_discovery_version() -> TestResult {
1,
"response_budget",
),
(
json!({"package": "skill://Plugin_123/work"}),
10_000,
"read_failed",
),
] {
if discovery_version == "v1" && outcome != "success" {
continue;
}
if outcome == "read_failed" {
let config = default_config();
harness.registry.config_contributors()[0].on_config_changed(
&harness.session_store,
&harness.thread_store,
&config,
&TestConfig {
cloud_skill_enabled: false,
..config.clone()
},
);
}
let result =
call_tool_with_budget(&tools, "read", arguments, TruncationPolicy::Bytes(budget))
.await;
@@ -110,7 +93,14 @@ async fn reads_report_outcomes_for_each_discovery_version() -> TestResult {
"{outcome}: {result:?}"
);
expected.push(read_result(outcome, discovery_version));
assert_eq!(harness.catalog_metrics.counters(), expected);
// Successful executor reads also record skill invocations; compare read outcomes only.
let read_counters = harness
.catalog_metrics
.counters()
.into_iter()
.filter(|counter| counter.name == "codex.skills.read.result")
.collect::<Vec<_>>();
assert_eq!(read_counters, expected);
}
}
Ok(())
@@ -119,9 +109,8 @@ async fn reads_report_outcomes_for_each_discovery_version() -> TestResult {
#[tokio::test]
async fn installations_report_outcomes_for_each_discovery_version() -> TestResult {
let harness = MergeHarness::new(
provider(Vec::new()),
provider(vec![
cloud_skill("work").with_alias_root("skill://Plugin_123"),
executor_skill("work").with_alias_root("skill://Plugin_123"),
]),
default_config(),
)
@@ -137,13 +126,13 @@ async fn installations_report_outcomes_for_each_discovery_version() -> TestResul
"all",
),
(
json!({"package": "c0/work", "source": {"kind": "cloud"}}),
json!({"package": "e0/work", "source": {"kind": "executor", "environment_id": "env-1"}}),
10_000,
"success",
"cloud",
"executor",
),
(
json!({"package": "c0/work", "source": {"kind": "executor", "environment_id": "missing"}}),
json!({"package": "e0/work", "source": {"kind": "executor", "environment_id": "missing"}}),
10_000,
"empty",
"executor",
@@ -151,30 +140,30 @@ async fn installations_report_outcomes_for_each_discovery_version() -> TestResul
(json!({}), 10_000, "invalid_arguments", "unparsed"),
(json!({"package": ""}), 10_000, "invalid_package", "all"),
(
json!({"package": "c0/work", "source": {"kind": "executor", "environment_id": ""}}),
json!({"package": "e0/work", "source": {"kind": "executor", "environment_id": ""}}),
10_000,
"invalid_source",
"executor",
),
(
json!({"package": "c0/missing"}),
json!({"package": "e0/missing"}),
10_000,
"package_unavailable",
"all",
),
(
json!({"package": "c99/work"}),
json!({"package": "e99/work"}),
10_000,
"unresolved_alias",
"all",
),
(
json!({"package": "c0/work", "cursor": "invalid"}),
json!({"package": "e0/work", "cursor": "invalid"}),
10_000,
"invalid_cursor",
"all",
),
(json!({"package": "c0/work"}), 1, "response_budget", "all"),
(json!({"package": "e0/work"}), 1, "response_budget", "all"),
] {
let result = call_tool_with_budget(
&tools,