Expose skill installations and stabilize package aliases (#55330)

## Why

A skill can be available from Cloud and multiple executor environments. Reading its instructions needs to expose where supporting files live and allow discovery of locations omitted by response limits. Package aliases also need to keep identifying the same roots as catalogs change.

## What changed

- With executor capability discovery V2, add `skills.installations` to list enabled locations with source filtering and pagination, without reading skill contents.
- Let `skills.read` select Cloud or a specific executor environment through `source`. Return bounded installation metadata and an `installations_truncated` flag so callers can retrieve omitted locations.
- Share bounded, append-only alias assignments between catalog rendering and tools within a live thread. Preserve each step's alias snapshot and render only root mappings used by its catalog entries.
- Use discovery-root metadata when constructing executor skill locators, with a fallback when it is absent. Preserve the legacy read response and tool set outside discovery V2.

## Testing

Add coverage for installation filtering and pagination, response budgets, source-specific reads and cursors, and alias stability across catalog and plugin changes. Add an end-to-end scenario that discovers an omitted installation and reads its instructions from the selected environment.

GitOrigin-RevId: a04e51e8242b21288d9d7b822780f9f1e093151d
This commit is contained in:
Anthony Tafoya
2026-10-19 17:37:49 +00:00
committed by copyberry
parent d70c2c2cdf
commit 03478b4b92
29 changed files with 1850 additions and 188 deletions
@@ -235,7 +235,8 @@ impl Executor {
"contents":"{\"inert-sentinel\":{\"command\":\"never-run\"}}"},
"appsConfig":null},"skills":[]}],
"skills":[{"name":"inert-sentinel","description":"Executor skill used by the acquisition test",
"shortDescription":null,"path":"file:///inert-sentinel/SKILL.md","metadata":null}],
"shortDescription":null,"path":"file:///inert-sentinel/SKILL.md",
"discoveryRoot":{"id":"codex-home-skills","path":"file:///"},"metadata":null}],
"warnings":[]
})),
Some("fs/open") if request["params"]["path"] == "file:///inert-sentinel/SKILL.md" => Some(json!({"handleId": request["params"]["handleId"]})),
+254
View File
@@ -54,6 +54,7 @@ use codex_protocol::protocol::EventMsg;
#[cfg(not(target_os = "windows"))]
use codex_protocol::protocol::MultiAgentVersion;
use codex_protocol::protocol::Op;
use codex_protocol::protocol::TurnEnvironmentSelection;
use codex_protocol::protocol::TurnSettingsUpdate;
use codex_protocol::protocol::TurnSettingsUpdateOutcome;
use codex_protocol::request_user_input::RequestUserInputAnswer;
@@ -1345,6 +1346,259 @@ async fn child_completion_wakes_parent_after_final_answer() -> Result<()> {
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn skill_read_recovers_omitted_installation_and_reads_selected_environment() -> Result<()> {
use codex_skills_extension::SkillProvider;
use codex_skills_extension::catalog::SkillAuthority;
use codex_skills_extension::catalog::SkillCatalog;
use codex_skills_extension::catalog::SkillCatalogEntry;
use codex_skills_extension::catalog::SkillPackageId;
use codex_skills_extension::catalog::SkillReadResult;
use codex_skills_extension::catalog::SkillResourceId;
use codex_skills_extension::catalog::SkillSearchResult;
use codex_skills_extension::catalog::SkillSourceKind;
use codex_skills_extension::catalog::SkillSourceLocation;
use codex_skills_extension::provider::SkillListQuery;
use codex_skills_extension::provider::SkillProviderFuture;
use codex_skills_extension::provider::SkillReadRequest;
use codex_skills_extension::provider::SkillSearchRequest;
skip_if_no_network!(Ok(()));
// Supply already-reconciled catalog fixtures; exercise production preparation and reads.
struct InstallationSkills(SkillCatalog);
impl SkillProvider for InstallationSkills {
fn list(&self, _query: SkillListQuery) -> SkillProviderFuture<'_, SkillCatalog> {
Box::pin(async { Ok(self.0.clone()) })
}
fn read<'a>(
&'a self,
request: SkillReadRequest<'a>,
) -> SkillProviderFuture<'a, SkillReadResult> {
Box::pin(async move {
assert!(
self.0
.entries
.iter()
.any(|entry| entry.id == request.package)
);
Ok(SkillReadResult {
resource: request.resource,
contents: "# Deployment\nRun scripts/check.py from an available installation."
.to_string(),
})
})
}
fn search(
&self,
_request: SkillSearchRequest,
) -> SkillProviderFuture<'_, SkillSearchResult> {
Box::pin(async { Ok(SkillSearchResult::default()) })
}
}
let executor = core_test_support::exec_server::ExecServerProcess::start().await?;
// Keep byte-budget decisions stable across host temporary-directory lengths.
let temp_root = fs::canonicalize(std::env::temp_dir())?;
let workspace = tempfile::Builder::new()
.rand_bytes(185_usize.saturating_sub(temp_root.to_string_lossy().len()))
.tempdir_in(temp_root)?;
let workspace_path = fs::canonicalize(workspace.path())?;
let deployment_root = workspace_path.join("skills/deploy");
fs::create_dir_all(&deployment_root)?;
let deployment_path = PathUri::from_host_native_path(&deployment_root)?;
let executor_contents = "# Deployment in env-04\nRun scripts/check.py from this installation.";
fs::write(deployment_root.join("SKILL.md"), executor_contents)?;
let mut catalog = SkillCatalog::default();
for (name, installation_count) in [("review", 2), ("deploy", 5)] {
let package = format!("skill://deployment/{name}");
let mut entry = SkillCatalogEntry::new(
SkillPackageId(package.clone()),
SkillAuthority::new(SkillSourceKind::Cloud, "codex_apps"),
name,
"Check an installed deployment before proceeding.",
SkillResourceId::new(format!("{package}/SKILL.md")),
);
for index in 0..installation_count {
let environment_id = format!("env-{index:02}");
let package = format!("skill://executor-{index:02}/{name}");
entry.sources.push(SkillSourceLocation {
authority: SkillAuthority::new(
SkillSourceKind::Executor,
format!("executor-{index:02}"),
),
package: SkillPackageId(package.clone()),
main_prompt: SkillResourceId::environment(
format!("{package}/SKILL.md"),
environment_id,
if name == "deploy" && index == 4 {
PathUri::from_host_native_path(deployment_root.join("SKILL.md"))?
} else {
PathUri::parse(&format!("file:///opt/skills/{name}/SKILL.md"))?
},
),
display_path: None,
plugin_id: None,
enabled: true,
alias_root: None,
prompt_visible: true,
});
}
catalog.entries.push(entry);
}
let mut extensions = ExtensionRegistryBuilder::<Config>::new();
install_with_providers(
&mut extensions,
SkillProviders::new()
.with_cloud_provider(Arc::new(InstallationSkills(catalog)))
.with_executor_provider(Arc::new(
ExecutorSkillProvider::new_with_restriction_product(
Arc::new(EnvironmentManager::default_for_tests()),
/*restriction_product*/ None,
),
)),
|config: &Config| SkillsExtensionConfig {
include_instructions: config.include_skill_instructions,
max_context_tokens: config.skill_max_context_tokens,
bundled_skills_enabled: false,
cloud_skill_enabled: true,
shadow_selection_enabled: false,
},
);
let server = start_mock_server().await;
let mock = mount_sse_sequence(
&server,
vec![
sse(vec![
ev_function_call_with_namespace(
"read-review",
"skills",
"read",
r#"{"package":"skill://executor-00/review","source":{"kind":"cloud"}}"#,
),
ev_completed("review-response"),
]),
sse(vec![
ev_function_call_with_namespace(
"read-deploy",
"skills",
"read",
r#"{"package":"skill://deployment/deploy"}"#,
),
ev_completed("deploy-response"),
]),
sse(vec![
ev_function_call_with_namespace(
"find-deploy",
"skills",
"installations",
r#"{"package":"skill://deployment/deploy"}"#,
),
ev_completed("installation-response"),
]),
sse(vec![
ev_function_call_with_namespace(
"read-env-04",
"skills",
"read",
r#"{"package":"skill://deployment/deploy","source":{"kind":"executor","environment_id":"env-04"}}"#,
),
ev_completed("executor-response"),
]),
sse(vec![
ev_assistant_message(
"done",
"I found the omitted env-04 installation and read its deployment instructions.",
),
ev_completed("done-response"),
]),
],
)
.await;
let test = test_codex()
.with_model("gpt-6-astra")
.with_auth(CodexAuth::create_dummy_chatgpt_auth_for_testing())
// Start without a local attachment so Cloud skills remain available.
.with_exec_server_url("none")
.with_extensions(Arc::new(extensions.build()))
.with_config(|config| {
configure_scenario_catalog(config);
config.cloud_skill_enabled = true;
config
.features
.enable(Feature::ExecutorCapabilityDiscoveryV2)
.expect("enable discovery V2");
})
.with_model_info_override("gpt-6-astra", |model| {
model.truncation_policy =
codex_protocol::openai_models::TruncationPolicyConfig::bytes(/*limit*/ 1200);
})
// The named executor runs on this host and reads the temporary workspace above.
.build(&server)
.await?;
test.thread_manager
.environment_manager()
.upsert_environment(
"env-04".to_string(),
executor.websocket_url.clone(),
/*connect_timeout*/ None,
)?;
let cwd = PathUri::from_host_native_path(&workspace_path)?;
test.submit_turn_with_environments(
"Read the review and deployment instructions, find all deployment installations, then read the instructions from env-04.",
Some(vec![TurnEnvironmentSelection {
selected_capability_roots: Default::default(),
environment_id: "env-04".to_string(),
cwd: cwd.clone(),
workspace_roots: vec![cwd],
config: EnvironmentConfigState::FromThread,
}]),
)
.await?;
let requests = mock.requests();
assert_eq!(requests.len(), 5);
let recovered: serde_json::Value = serde_json::from_str(
&mock
.function_call_output_text("read-env-04")
.expect("executor read output"),
)?;
assert_eq!(recovered["contents"], executor_contents);
assert_eq!(recovered["resource"], "skill://executor-04/deploy/SKILL.md");
// Canonicalize JSON only in snapshot copies (Cargo/Bazel differ in map ordering).
// Pretty printing keeps installation fields visible rather than hashing one long line.
let mut bodies = requests
.iter()
.map(core_test_support::responses::ResponsesRequest::body_json)
.collect::<Vec<_>>();
for body in &mut bodies {
for item in body["input"].as_array_mut().expect("request input") {
if item["type"] == "function_call_output" {
let mut output: serde_json::Value =
serde_json::from_str(item["output"].as_str().expect("tool output"))?;
for location in output["installations"].as_array_mut().into_iter().flatten() {
if location["skill_root"] == deployment_path.inferred_native_path_string() {
location["skill_root"] = json!("<ENV_04_SKILL_ROOT>");
}
}
output.sort_all_objects();
item["output"] = json!(serde_json::to_string_pretty(&output)?);
}
}
}
insta::assert_snapshot!(
"skill_read_installation_recovery_request_history",
context_snapshot::format_context_snapshot(
"Astra reads Cloud instructions, discovers an omitted deployment installation, and reads its instructions from env-04.",
&bodies.iter().map(SnapshotEntry::body).collect::<Vec<_>>(),
&ContextSnapshotOptions::default().rewrite_known_segments(),
)
);
Ok(())
}
#[test_case::test_case(false; "native_tools")]
#[test_case::test_case(true; "host_tools")]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
@@ -136,7 +136,10 @@ async fn cloud_preference_preserves_executor_aliases_and_description_budget() ->
assert!(!body.contains(&format!("(executor package: e0/s{index})")));
}
for (index, root) in roots.iter().enumerate() {
assert!(body.contains(&format!("- `e{index}` = `{root}`")));
assert_eq!(
body.contains(&format!("- `e{index}` = `{root}`")),
index == 1
);
}
assert_eq!(body.matches("UNIQUE_DESCRIPTION_END").count(), 3);
}
@@ -247,6 +247,12 @@ async fn cloud_skills_reuse_cache_and_invalidate_on_connection_or_auth_change()
}
// Empty catalogs must also reject reads of the previously cached skill.
let (plugin, _) = expected_skill.unwrap_or(last_available_skill);
// Auth changes revoke the old catalog, but never reuse its alias for a different root.
let alias = if plugin == "calendar" {
"c0/demo"
} else {
"c1/demo"
};
let package = format!("skill://{plugin}/demo");
let list_id = format!("list-{turn}");
let read_id = format!("read-{turn}");
@@ -265,7 +271,7 @@ async fn cloud_skills_reuse_cache_and_invalidate_on_connection_or_auth_change()
&read_id,
"skills",
"read",
&json!({"package": package}).to_string(),
&json!({"package": alias}).to_string(),
),
ev_completed("tools"),
]),
@@ -465,7 +465,7 @@ text({ names: result.skills.map(skill => skill.name), warnings: result.warnings,
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn production_turn_aliases_discovered_singleton_cloud_root() -> Result<()> {
async fn production_turn_aliases_discovered_singleton_cloud_locator() -> Result<()> {
skip_if_no_network!(Ok(()));
const SKILL_ROOT: &str = "skill://plugin_connector_1p_2330815c823c8191941e5dc465bb899f";
@@ -536,20 +536,13 @@ async fn production_turn_aliases_discovered_singleton_cloud_root() -> Result<()>
let request = response.single_request();
let developer_text = request.message_input_texts("developer").join("\n");
assert!(
developer_text.contains(&format!("- `c0` = `{SKILL_ROOT}`")),
"model request should include the discovered cloud root: {developer_text}"
);
assert!(
developer_text.lines().any(|line| {
line.starts_with("- demo:search:") && line.ends_with("(cloud package: c0/search)")
}),
"model request should include the aliased cloud skill: {developer_text}"
);
assert!(
developer_text.contains("- Root aliases: Pass short package locators directly"),
"model request should explain how to read aliased packages: {developer_text}"
"model request should include the aliased cloud package: {developer_text}"
);
assert!(developer_text.contains(&format!("- `c0` = `{SKILL_ROOT}`")));
let user_text = request.message_input_texts("user").join("\n");
assert!(
user_text.contains("<skill>\n<name>demo:search</name>") && user_text.contains(SKILL_BODY),
@@ -1,6 +1,6 @@
---
source: core/tests/suite/scenarios.rs
expression: "context_snapshot::format_context_snapshot(\"Astra keeps disabled skills hidden and uses each step's selected skills after the environment changes during preparation.\",\n&entries, &ContextSnapshotOptions::default().include_request_settings(),)"
expression: "context_snapshot::format_context_snapshot(description, &entries,\n&ContextSnapshotOptions::default().include_request_settings(),)"
---
Scenario: Astra keeps disabled skills hidden and uses each step's selected skills after the environment changes during preparation.
@@ -130,8 +130,8 @@ Settings:
## Skills
A skill is a set of instructions provided through a `SKILL.md` source. Below is the list of skills that ...locators can be expanded using the skill roots table. [hash=f00d6a4d3e192f06]
### Skill roots
- `e0` = `skill://other-skills/<SKILLS_ROOT>/other-skills`
- `e1` = `skill://other-skills/<SKILLS_ROOT>/other-skills`
Read a skill package directly with `skills.read({"package":"<package>"})` to read its `SKILL.md`; root a...ackage is not provided, use `skills.list` to find it. [hash=25bf84ea2123d647]
### Available skills
- next-helper: Use the next workflow (executor package: e0/next-helper)
- next-helper: Use the next workflow (executor package: e1/next-helper)
</skills_instructions>
@@ -132,8 +132,8 @@ Settings:
## Skills
A skill is a set of instructions provided through a `SKILL.md` source. Below is the list of skills that ...locators can be expanded using the skill roots table. [hash=f00d6a4d3e192f06]
### Skill roots
- `e0` = `skill://other-skills/<SKILLS_ROOT>/other-skills`
- `e2` = `skill://other-skills/<SKILLS_ROOT>/other-skills`
Read a skill package directly with `skills.read({"package":"<package>"})` to read its `SKILL.md`; root a...ackage is not provided, use `skills.list` to find it. [hash=25bf84ea2123d647]
### Available skills
- next-helper: Use the next workflow (executor package: e0/next-helper)
- next-helper: Use the next workflow (executor package: e2/next-helper)
</skills_instructions>
@@ -74,7 +74,6 @@ Settings:
## Skills
A skill is a set of instructions provided through a `SKILL.md` source. Below is the list of skills that ...locators can be expanded using the skill roots table. [hash=f00d6a4d3e192f06]
### Skill roots
- `e0` = `skill://executor-a/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa...aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa` [hash=89039f2551ec08fb]
- `e1` = `skill://executor-b/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb...bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb` [hash=aec7776011a3143f]
Read a skill package directly with `skills.read({"package":"<package>"})` to read its `SKILL.md`; root a...ackage is not provided, use `skills.list` to find it. [hash=25bf84ea2123d647]
### Available skills
@@ -0,0 +1,115 @@
---
source: core/tests/suite/scenarios.rs
assertion_line: 1456
expression: "context_snapshot::format_context_snapshot(\"Astra reads Cloud instructions, discovers an omitted deployment installation, and reads its instructions from env-04.\",\n&bodies.iter().map(SnapshotEntry::body).collect::<Vec<_>>(),\n&ContextSnapshotOptions::default().rewrite_known_segments(),)"
---
Scenario: Astra reads Cloud instructions, discovers an omitted deployment installation, and reads its instructions from env-04.
## Window 1
-- request 1 (request) --
00:additional_tools/developer (3; hash=e075a43448be3246):
- namespace/functions; hash=bbcd688349ca7e12
- custom/exec
- function/wait
- function/request_user_input
- function/request_user_input_async
- namespace/clock: Tools for reading and waiting on time.; hash=f402e8c5e9b5e317
- function/sleep
- namespace/collaboration: Tools for spawning and managing sub-agents.; hash=2c8d6295978dbe63
- function/followup_task
- function/interrupt_agent
- function/list_agents
- function/send_message
- function/spawn_agent
- function/wait_agent
01:message/developer:
<MODEL_INSTRUCTIONS>
02:message/developer[3]:
[01] <PERMISSIONS_INSTRUCTIONS>
[02] <COLLABORATION_MODE>
[03] <SKILLS_INSTRUCTIONS>
03:message/developer:
<MULTI_AGENT_ROLE>
04:message/developer:
<MULTI_AGENT_MODE>
05:message/user:
<ENVIRONMENT_CONTEXT>
06:message/user:
Read the review and deployment instructions, find all deployment installations, then read the instructions from env-04.
-- request 2 (request) --
07:function_call/skills.read:{"package":"skill://executor-00/review","source":{"kind":"cloud"}}
08:function_call_output:{
"contents": "# Deployment\\nRun scripts/check.py from an available installation.",
"installations": [
{
"package": "skill://deployment/review",
"resource": "skill://deployment/review/SKILL.md"
},
{
"environment_id": "env-00",
"skill_root": "/opt/skills/review"
},
{
"environment_id": "env-01",
"skill_root": "/opt/skills/review"
}
],
"next_cursor": null,
"resource": "skill://deployment/review/SKILL.md"
}
-- request 3 (request) --
09:function_call/skills.read:{"package":"skill://deployment/deploy"}
10:function_call_output:{
"contents": "# Deployment\\nRun scripts/check.py from an available installation.",
"installations": [
{
"package": "skill://deployment/deploy",
"resource": "skill://deployment/deploy/SKILL.md"
},
{
<OMITTED 12 LINES; ~65 TOKENS; hash=acd1e9324679b8e2>
"environment_id": "env-03",
"skill_root": "/opt/skills/deploy"
}
],
"installations_truncated": true,
"next_cursor": null,
"resource": "skill://deployment/deploy/SKILL.md"
}
-- request 4 (request) --
11:function_call/skills.installations:{"package":"skill://deployment/deploy"}
12:function_call_output:{
"installations": [
{
"package": "skill://deployment/deploy",
"resource": "skill://deployment/deploy/SKILL.md"
},
{
"environment_id": "env-00",
<OMITTED 13 LINES; ~76 TOKENS; hash=9220bf30c6cda548>
},
{
"environment_id": "env-04",
"skill_root": "<ENV_04_SKILL_ROOT>"
}
],
"next_cursor": null
}
-- request 5 (request) --
13:function_call/skills.read:{"package":"skill://deployment/deploy","source":{"environment_id":"env-04","kind":"executor"}}
14:function_call_output:{
"contents": "# Deployment in env-04\\nRun scripts/check.py from this installation.",
"installations": [
{
"environment_id": "env-04",
"skill_root": "<ENV_04_SKILL_ROOT>"
},
{
"package": "skill://deployment/deploy",
"resource": "skill://deployment/deploy/SKILL.md"
}
],
"installations_truncated": true,
"next_cursor": null,
"resource": "skill://executor-04/deploy/SKILL.md"
}
+135 -7
View File
@@ -1,9 +1,15 @@
//! Bounded, append-only aliases shared by rendering and reads within a live thread.
//! Step snapshots retain their assignments; aliases are not persisted across resume or fork.
use std::collections::HashSet;
use std::sync::Arc;
use std::sync::Mutex;
use serde::Deserialize;
use serde::Serialize;
use crate::catalog::SkillSourceKind;
use crate::skills_extension_state::SkillToolAuthoritySelector;
fn alias_prefix(source: &SkillSourceKind) -> Option<&'static str> {
match source {
@@ -66,34 +72,142 @@ impl SkillLocator {
}
}
struct AliasRoot {
name: String,
value: String,
/// Owns thread-wide alias allocation independently of provider caches.
#[derive(Default)]
pub(crate) struct SkillAliasState {
aliases: Mutex<SkillCatalogAliases>,
}
impl SkillAliasState {
pub(crate) fn capture(
&self,
roots: impl IntoIterator<Item = (SkillSourceKind, String)>,
) -> SkillCatalogAliases {
let mut aliases = self
.aliases
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
for (kind, root) in roots {
let selector = match kind {
SkillSourceKind::Cloud => SkillToolAuthoritySelector::Cloud,
SkillSourceKind::Executor => SkillToolAuthoritySelector::Executor,
SkillSourceKind::Host | SkillSourceKind::Custom(_) => continue,
};
aliases.extend(selector, [root.as_str()]);
}
aliases.clone()
}
}
/// Thread-wide assignments, captured alongside each step's catalog.
#[derive(Clone, Debug, Default)]
pub(crate) struct SkillCatalogAliases {
cloud: Arc<AliasPlan>,
executor: Arc<AliasPlan>,
budget: AliasBudget,
}
impl SkillCatalogAliases {
pub(crate) fn resolve(&self, locator: &SkillLocator) -> Option<String> {
let plan = match locator.alias_source() {
Some(SkillSourceKind::Cloud) => &self.cloud,
Some(SkillSourceKind::Executor) => &self.executor,
Some(SkillSourceKind::Host | SkillSourceKind::Custom(_)) | None => return None,
};
plan.expand(locator.as_str())
}
fn extend<'a>(
&mut self,
selector: SkillToolAuthoritySelector,
roots: impl IntoIterator<Item = &'a str>,
) {
let (plan, prefix) = match selector {
SkillToolAuthoritySelector::Cloud => (&mut self.cloud, "c"),
SkillToolAuthoritySelector::Executor => (&mut self.executor, "e"),
};
plan.extend_alias_plan(prefix, roots, &mut self.budget);
}
pub(crate) fn for_authority(&self, selector: SkillToolAuthoritySelector) -> &AliasPlan {
match selector {
SkillToolAuthoritySelector::Cloud => &self.cloud,
SkillToolAuthoritySelector::Executor => &self.executor,
}
}
}
const MAX_ALIAS_ROOTS: usize = 2_048;
const MAX_ALIAS_BYTES: usize = 16 * 1024;
/// Shared bound on thread-local Cloud/executor alias assignments and their rendered mappings.
#[derive(Clone, Debug, Default)]
struct AliasBudget {
roots: usize,
bytes: usize,
}
#[derive(Clone, Debug)]
struct AliasRoot {
name: String,
value: Arc<str>,
}
#[derive(Clone, Debug, Default)]
pub(crate) struct AliasPlan {
roots: Vec<AliasRoot>,
known_roots: HashSet<Arc<str>>,
}
impl AliasPlan {
pub(crate) fn build(source: &SkillSourceKind, candidates: &[&str]) -> Option<Self> {
let prefix = alias_prefix(source)?;
let mut roots = Vec::new();
let mut seen = HashSet::new();
let mut known_roots = HashSet::new();
for &root in candidates {
if !seen.insert(root) {
if known_roots.contains(root) {
continue;
}
let root: Arc<str> = root.into();
known_roots.insert(Arc::clone(&root));
let index = roots.len();
roots.push(AliasRoot {
name: format!("{prefix}{index}"),
value: root.to_string(),
value: root,
});
}
(!roots.is_empty()).then_some(Self { roots })
(!roots.is_empty()).then_some(Self { roots, known_roots })
}
/// Retains existing assignments and reserves new numbers for previously unseen roots.
fn extend_alias_plan<'a>(
self: &mut Arc<Self>,
prefix: &str,
roots: impl IntoIterator<Item = &'a str>,
budget: &mut AliasBudget,
) {
for root in roots {
if self.known_roots.contains(root) {
continue;
}
let name = format!("{prefix}{}", self.roots.len());
let bytes = name.len() + root.len() + "- `` = ``".len();
if budget.roots == MAX_ALIAS_ROOTS {
break;
}
if bytes > MAX_ALIAS_BYTES - budget.bytes {
continue;
}
budget.roots += 1;
budget.bytes += bytes;
let plan = Arc::make_mut(self);
let root: Arc<str> = root.into();
plan.known_roots.insert(Arc::clone(&root));
plan.roots.push(AliasRoot { name, value: root });
}
}
pub(crate) fn shorten(&self, locator: &str) -> Option<String> {
@@ -109,6 +223,20 @@ impl AliasPlan {
.map(|(root, suffix)| format!("{}/{suffix}", root.name))
}
fn expand(&self, alias: &str) -> Option<String> {
let (name, suffix) = alias.split_once('/')?;
let root = self.roots.iter().find(|root| root.name == name)?;
Some(format!("{}/{suffix}", root.value.trim_end_matches('/')))
}
pub(crate) fn root_lines_for(&self, used: &HashSet<String>) -> Vec<String> {
self.roots
.iter()
.filter(|root| used.contains(&root.name))
.map(|root| format!("- `{}` = `{}`", root.name, root.value))
.collect()
}
pub(crate) fn root_lines(&self) -> Vec<String> {
self.roots
.iter()
+49
View File
@@ -63,6 +63,7 @@ fn shortens_filesystem_and_skill_resource_locators() {
let shortened = plan.shorten(locator).expect("known root");
assert_eq!(shortened, expected);
assert_eq!(plan.expand(&shortened).as_deref(), Some(locator));
let json = serde_json::to_string(&shortened).unwrap();
let parsed: SkillLocator = serde_json::from_str(&json).unwrap();
assert_eq!(parsed.alias_source(), Some(&source));
@@ -127,3 +128,51 @@ fn locator_serde_recognizes_aliases_and_preserves_package_strings() {
assert_eq!(serde_json::to_string(&locator).unwrap(), json);
}
}
#[test]
fn appended_aliases_preserve_captured_steps_and_existing_locators() {
let mut aliases = std::sync::Arc::new(AliasPlan::default());
let mut budget = super::AliasBudget::default();
aliases.extend_alias_plan("e", ["skill://root"], &mut budget);
let previous = std::sync::Arc::clone(&aliases);
let locator = "skill://root/nested/demo";
let original = aliases.shorten(locator).unwrap();
aliases.extend_alias_plan("e", ["skill://root/nested", "skill://root"], &mut budget);
assert_eq!(previous.root_lines(), vec!["- `e0` = `skill://root`"]);
assert_eq!(previous.shorten(locator), Some(original.clone()));
assert_eq!(aliases.shorten(locator), Some("e1/demo".into()));
assert_eq!(aliases.expand(&original).as_deref(), Some(locator));
assert_eq!(aliases.expand("e1/demo").as_deref(), Some(locator));
assert_eq!(
aliases.root_lines_for(&std::collections::HashSet::from(["e1".to_string()])),
vec!["- `e1` = `skill://root/nested`"]
);
}
#[test]
fn alias_number_and_byte_budgets_are_shared_without_reassigning_existing_roots() {
let mut cloud = std::sync::Arc::new(AliasPlan::default());
let mut executor = std::sync::Arc::new(AliasPlan::default());
let mut budget = super::AliasBudget {
roots: super::MAX_ALIAS_ROOTS - 2,
..Default::default()
};
cloud.extend_alias_plan("c", ["skill://cloud"], &mut budget);
executor.extend_alias_plan("e", ["skill://first", "skill://second"], &mut budget);
assert_eq!(budget.roots, super::MAX_ALIAS_ROOTS);
assert_eq!(executor.root_lines(), vec!["- `e0` = `skill://first`"]);
assert_eq!(executor.shorten("skill://second/demo"), None);
assert_eq!(cloud.shorten("skill://cloud/demo"), Some("c0/demo".into()));
let mut budget = super::AliasBudget::default();
let mut aliases = std::sync::Arc::new(AliasPlan::default());
let oversized = "x".repeat(super::MAX_ALIAS_BYTES);
aliases.extend_alias_plan("e", ["skill://first", &oversized], &mut budget);
aliases.extend_alias_plan("e", ["skill://second"], &mut budget);
assert_eq!(
aliases.root_lines(),
vec!["- `e0` = `skill://first`", "- `e1` = `skill://second`"]
);
assert_eq!(aliases.shorten(&format!("{oversized}/demo")), None);
}
+4
View File
@@ -295,6 +295,8 @@ impl SkillCatalogEntry {
display_path: self.display_path.clone(),
plugin_id: self.plugin_id.clone(),
enabled: self.enabled,
alias_root: self.alias_root.clone(),
prompt_visible: self.prompt_visible,
}
}
@@ -331,6 +333,8 @@ pub struct SkillSourceLocation {
/// Installation attribution belongs to the route used, not the merged primary entry.
pub plugin_id: Option<String>,
pub enabled: bool,
pub alias_root: Option<String>,
pub prompt_visible: bool,
}
/// Merged catalog for one turn.
+9 -3
View File
@@ -44,6 +44,7 @@ pub(crate) enum SkillPromptKind {
Unaliased,
HostAliases,
ResourceAliases,
ResourceAliasesV2,
}
impl SkillPromptKind {
@@ -59,20 +60,22 @@ impl SkillPromptKind {
match self {
Self::Unaliased => SKILLS_INTRO_WITH_SOURCE_LOCATORS,
Self::HostAliases => SKILLS_INTRO_WITH_HOST_ALIASES,
Self::ResourceAliases => SKILLS_INTRO_WITH_RESOURCE_ALIASES,
Self::ResourceAliases | Self::ResourceAliasesV2 => SKILLS_INTRO_WITH_RESOURCE_ALIASES,
}
}
pub(crate) fn usage_instructions(self) -> &'static str {
match self {
Self::Unaliased | Self::ResourceAliases => SKILLS_HOW_TO_USE_WITH_SOURCE_LOCATORS,
Self::Unaliased | Self::ResourceAliases | Self::ResourceAliasesV2 => {
SKILLS_HOW_TO_USE_WITH_SOURCE_LOCATORS
}
Self::HostAliases => SKILLS_HOW_TO_USE_WITH_HOST_ALIASES,
}
}
pub(crate) fn alias_instructions(self) -> Option<&'static str> {
match self {
Self::ResourceAliases => Some(RESOURCE_ALIAS_INSTRUCTIONS),
Self::ResourceAliases | Self::ResourceAliasesV2 => Some(RESOURCE_ALIAS_INSTRUCTIONS),
Self::Unaliased | Self::HostAliases => None,
}
}
@@ -88,6 +91,9 @@ pub(crate) fn render_available_skills_body(
lines.push(prompt_kind.intro().to_string());
if !skill_root_lines.is_empty() {
lines.push("### Skill roots".to_string());
if prompt_kind == SkillPromptKind::ResourceAliasesV2 {
lines.push("For each alias listed below, this mapping replaces any earlier mapping for that alias. Use it for subsequent skill calls.".to_string());
}
lines.extend(skill_root_lines.iter().cloned());
}
if skill_lines
+7 -1
View File
@@ -102,7 +102,13 @@ fn render_catalog(
catalog_surface,
include_skills_usage_instructions,
budget,
render_available_skills(catalog, policy, budget, include_skills_usage_instructions),
render_available_skills(
catalog,
policy,
budget,
include_skills_usage_instructions,
/*alias_plan*/ None,
),
)
}
+4 -1
View File
@@ -32,7 +32,10 @@ fn detect_executor_skill(command: &str, environments: &[&str]) -> Option<SkillIn
};
let turn_store = ExtensionData::new("test-turn");
let step_catalog = Arc::new(crate::skills_extension_state::SkillStepCatalog::new(
/*cloud*/ None, catalog, /*discovery_v2*/ false,
/*cloud*/ None,
catalog,
/*discovery_v2*/ false,
Default::default(),
));
let step_store = ExtensionData::new("step");
step_store.insert(crate::skills_extension_state::SkillsStepState::new_with(
@@ -50,13 +50,21 @@ impl ExecutorSkillProvider {
}
}
for skill in &discovered.skills {
let Some(root) = skill.path.parent() else {
continue;
// Use the skills namespace when discovery-root metadata is absent.
let fallback_root;
let (root_id, root_path) = if let Some(root) = &skill.discovery_root {
(root.id.as_str(), &root.path)
} else {
let Some(parent) = skill.path.parent() else {
continue;
};
fallback_root = parent;
("skills", &fallback_root)
};
if let Some(entry) = self.catalog_entry_from_discovered_skill(
skill,
"skills",
&root,
root_id,
root_path,
&snapshot.environment_id,
) {
catalog.push_entry(entry);
+54 -20
View File
@@ -1,4 +1,5 @@
use std::borrow::Cow;
use std::collections::HashSet;
use std::num::NonZeroUsize;
use codex_protocol::protocol::SkillScope;
@@ -32,13 +33,14 @@ pub(crate) const MAX_SKILL_PATH_BYTES: usize = 1_024;
pub(crate) enum SkillCatalogRenderPolicy {
CoreCompatible,
ExtensionCompatible,
DiscoveryV2,
}
impl SkillCatalogRenderPolicy {
fn description(self, entry: &SkillCatalogEntry) -> &str {
match self {
Self::CoreCompatible => entry.description.as_str(),
Self::ExtensionCompatible => entry
Self::ExtensionCompatible | Self::DiscoveryV2 => entry
.short_description
.as_deref()
.unwrap_or(entry.description.as_str()),
@@ -62,14 +64,14 @@ impl SkillCatalogRenderPolicy {
.then_with(|| a.main_prompt.as_str().cmp(b.main_prompt.as_str()))
});
}
Self::ExtensionCompatible => {}
Self::ExtensionCompatible | Self::DiscoveryV2 => {}
}
}
fn includes_omission_notice(self) -> bool {
match self {
Self::CoreCompatible => false,
Self::ExtensionCompatible => true,
Self::ExtensionCompatible | Self::DiscoveryV2 => true,
}
}
}
@@ -525,8 +527,10 @@ pub(crate) fn render_available_skills(
policy: SkillCatalogRenderPolicy,
budget: SkillMetadataBudget,
include_skills_usage_instructions: bool,
alias_plan: Option<&AliasPlan>,
) -> Option<AvailableSkillsRender> {
PreparedSkillCatalog::new(catalog, policy).render(budget, include_skills_usage_instructions)
PreparedSkillCatalog::with_alias_plan(catalog, policy, alias_plan)
.render(budget, include_skills_usage_instructions)
}
pub(crate) fn render_prepared_skill_catalogs(
@@ -642,28 +646,42 @@ impl<'a> CatalogLines<'a> {
fn aliased(
entries: &[&'a SkillCatalogEntry],
policy: SkillCatalogRenderPolicy,
alias_plan: Option<&AliasPlan>,
alias_plan: Option<&Cow<'_, AliasPlan>>,
) -> Self {
let Some(plan) = alias_plan.filter(|_| !entries.is_empty()) else {
return Self::unaliased(entries, policy);
};
let mut used_roots = HashSet::new();
let skills = entries
.iter()
.map(|entry| {
SkillLine::with_locator(
entry,
policy,
render_skill_locator_with_aliases(entry, plan, &mut used_roots),
)
})
.collect();
Self {
prompt_kind: entries
.first()
.map(|entry| SkillPromptKind::for_aliased_source(&entry.authority.kind))
.unwrap_or(SkillPromptKind::Unaliased),
skills: entries
.iter()
.map(|entry| {
SkillLine::with_locator(
entry,
policy,
render_skill_locator_with_aliases(entry, plan),
)
let kind = SkillPromptKind::for_aliased_source(&entry.authority.kind);
if policy == SkillCatalogRenderPolicy::DiscoveryV2
&& kind == SkillPromptKind::ResourceAliases
{
SkillPromptKind::ResourceAliasesV2
} else {
kind
}
})
.collect(),
root_lines: plan.root_lines(),
.unwrap_or(SkillPromptKind::Unaliased),
skills,
root_lines: match plan {
Cow::Borrowed(plan) => plan.root_lines_for(&used_roots),
Cow::Owned(plan) => plan.root_lines(),
},
}
}
}
@@ -943,8 +961,14 @@ fn available_skills_fragment(
policy: SkillCatalogRenderPolicy,
budget: SkillMetadataBudget,
) -> Option<AvailableSkillsInstructions> {
render_available_skills(catalog, policy, budget, include_skills_usage_instructions)?
.into_fragment(include_skills_usage_instructions)
render_available_skills(
catalog,
policy,
budget,
include_skills_usage_instructions,
/*alias_plan*/ None,
)?
.into_fragment(include_skills_usage_instructions)
}
fn build_aliased_catalog(
@@ -1001,7 +1025,11 @@ pub(crate) fn build_alias_plan(entries: &[&SkillCatalogEntry]) -> Option<AliasPl
AliasPlan::build(source, &roots)
}
fn render_skill_locator_with_aliases(entry: &SkillCatalogEntry, plan: &AliasPlan) -> String {
fn render_skill_locator_with_aliases(
entry: &SkillCatalogEntry,
plan: &AliasPlan,
used_roots: &mut HashSet<String>,
) -> String {
let locator = match &entry.authority.kind {
SkillSourceKind::Executor | SkillSourceKind::Cloud => entry.id.0.as_str(),
SkillSourceKind::Host | SkillSourceKind::Custom(_) => entry.rendered_path(),
@@ -1009,7 +1037,13 @@ fn render_skill_locator_with_aliases(entry: &SkillCatalogEntry, plan: &AliasPlan
if entry.alias_root().is_none() {
return locator.to_string();
}
plan.shorten(locator).unwrap_or_else(|| locator.to_string())
let Some(alias) = plan.shorten(locator) else {
return locator.to_string();
};
if let Some((root, _)) = alias.split_once('/') {
used_roots.insert(root.to_string());
}
alias
}
fn aliased_metadata_overhead_cost(
+13 -2
View File
@@ -1,5 +1,6 @@
//! Prefers cloud skills before budgeting while retaining aliases from the full visible inventory.
use std::borrow::Cow;
use std::collections::HashSet;
use super::AvailableSkillsRender;
@@ -17,19 +18,29 @@ use crate::catalog_prompt::SkillPromptKind;
pub(crate) struct PreparedSkillCatalog<'a> {
pub(super) entries: Vec<&'a SkillCatalogEntry>,
alias_plan: Option<AliasPlan>,
alias_plan: Option<Cow<'a, AliasPlan>>,
policy: SkillCatalogRenderPolicy,
}
impl<'a> PreparedSkillCatalog<'a> {
pub(crate) fn new(catalog: &'a SkillCatalog, policy: SkillCatalogRenderPolicy) -> Self {
Self::with_alias_plan(catalog, policy, /*alias_plan*/ None)
}
pub(crate) fn with_alias_plan(
catalog: &'a SkillCatalog,
policy: SkillCatalogRenderPolicy,
alias_plan: Option<&'a AliasPlan>,
) -> Self {
let mut entries = catalog
.entries
.iter()
.filter(|entry| entry.is_model_visible())
.collect::<Vec<_>>();
policy.order_entries(&mut entries);
let alias_plan = build_alias_plan(&entries);
let alias_plan = alias_plan
.map(Cow::Borrowed)
.or_else(|| build_alias_plan(&entries).map(Cow::Owned));
Self {
entries,
alias_plan,
+11 -4
View File
@@ -467,7 +467,7 @@ fn path_aliases_retain_every_skill_under_budget_pressure() {
SkillLine::with_locator(
entry,
SkillCatalogRenderPolicy::ExtensionCompatible,
render_skill_locator_with_aliases(entry, &plan),
render_skill_locator_with_aliases(entry, &plan, &mut HashSet::new()),
)
.minimum_cost(SkillMetadataBudget::Characters(usize::MAX)),
)
@@ -510,7 +510,10 @@ fn executor_aliases_preserve_literal_backslashes_in_package_ids() {
.with_alias_root(root);
let plan = build_alias_plan(&[&entry]).expect("alias plan should build");
assert_eq!(render_skill_locator_with_aliases(&entry, &plan), "e0/demo");
assert_eq!(
render_skill_locator_with_aliases(&entry, &plan, &mut HashSet::new()),
"e0/demo"
);
}
#[tokio::test]
@@ -957,11 +960,11 @@ async fn singleton_plugin_versions_share_the_marketplace_alias_root()
vec![format!("- `r0` = `{marketplace_root}`")]
);
assert_eq!(
render_skill_locator_with_aliases(github, &plan),
render_skill_locator_with_aliases(github, &plan, &mut HashSet::new()),
"r0/github/hash123/skills/github/SKILL.md"
);
assert_eq!(
render_skill_locator_with_aliases(slack, &plan),
render_skill_locator_with_aliases(slack, &plan, &mut HashSet::new()),
"r0/slack/hash456/skills/slack/SKILL.md"
);
@@ -1081,6 +1084,7 @@ fn catalog_report_counts_partial_description_truncation() {
SkillCatalogRenderPolicy::ExtensionCompatible,
budget,
/*include_skills_usage_instructions*/ false,
/*alias_plan*/ None,
)
.expect("catalog should render");
assert_eq!(
@@ -1132,6 +1136,7 @@ fn catalog_emits_omission_marker_when_every_minimum_skill_line_exceeds_budget()
SkillCatalogRenderPolicy::CoreCompatible,
SkillMetadataBudget::Tokens(100),
/*include_skills_usage_instructions*/ false,
/*alias_plan*/ None,
)
.expect("core-compatible report should render");
assert_eq!(core_render.report, expected_report);
@@ -1145,6 +1150,7 @@ fn catalog_emits_omission_marker_when_every_minimum_skill_line_exceeds_budget()
SkillCatalogRenderPolicy::ExtensionCompatible,
SkillMetadataBudget::Tokens(100),
/*include_skills_usage_instructions*/ false,
/*alias_plan*/ None,
)
.expect("catalog should render");
assert_eq!(render.report, expected_report);
@@ -1180,6 +1186,7 @@ fn catalog_preserves_report_when_no_fragment_fits_budget() {
SkillCatalogRenderPolicy::ExtensionCompatible,
SkillMetadataBudget::Tokens(1),
/*include_skills_usage_instructions*/ false,
/*alias_plan*/ None,
)
.expect("catalog should produce a report");
assert_eq!(
@@ -11,6 +11,7 @@ use codex_mcp::McpResourceClientAuthKey;
use codex_mcp::McpResourceServerCacheKey;
use codex_protocol::capabilities::SelectedCapabilityRoot;
use crate::aliases::SkillCatalogAliases;
use crate::catalog::SkillAuthority;
use crate::catalog::SkillCatalog;
use crate::catalog::SkillPackageId;
@@ -249,6 +250,7 @@ pub(crate) type SkillsStepState = OnceCell<Arc<SkillStepCatalog>>;
#[derive(Debug)]
pub(crate) struct SkillStepCatalog {
pub(super) catalog: SkillCatalog,
pub(crate) aliases: SkillCatalogAliases,
/// None means no Cloud catalog was captured for this step.
pub(super) cloud_warnings: Option<Vec<String>>,
pub(super) executor_warnings: Vec<String>,
@@ -259,6 +261,7 @@ impl SkillStepCatalog {
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();
@@ -290,6 +293,7 @@ impl SkillStepCatalog {
);
Self {
catalog,
aliases,
cloud_warnings,
executor_warnings,
}
+22
View File
@@ -8,6 +8,7 @@ use codex_mcp::McpResourceClient;
use crate::SkillsExtensionConfig;
use crate::SkillsExtensionState;
use crate::aliases::SkillAliasState;
use crate::catalog::SkillAuthority;
use crate::catalog::SkillCatalog;
use crate::catalog::SkillPackageId;
@@ -28,6 +29,7 @@ use crate::skills_extension_state::CloudResourceCache;
use crate::skills_extension_state::CloudSkillGeneration;
use crate::skills_extension_state::ExecutorCatalogCacheKey;
use crate::skills_extension_state::SkillReadCacheKey;
use crate::skills_extension_state::SkillStepCatalog;
use crate::sources::SkillProviders;
#[cfg(test)]
@@ -44,6 +46,7 @@ pub struct SkillsThreadState {
config: Mutex<SkillsExtensionConfig>,
cloud_skills_available: bool,
skills_extension_state: Mutex<SkillsExtensionState>,
aliases: SkillAliasState,
shadow_selection_turn: Mutex<Option<ShadowSelectionTurn>>,
pub(crate) executor_read_snapshot: Mutex<Option<ExecutorReadSnapshot>>,
pub(crate) recent_skill_invocations: Arc<RecentSkillInvocations>,
@@ -56,6 +59,7 @@ impl SkillsThreadState {
config: Mutex::new(config),
cloud_skills_available,
skills_extension_state: Mutex::new(SkillsExtensionState::default()),
aliases: SkillAliasState::default(),
shadow_selection_turn: Mutex::new(None),
executor_read_snapshot: Mutex::new(None),
recent_skill_invocations: Arc::new(RecentSkillInvocations::default()),
@@ -116,6 +120,24 @@ impl SkillsThreadState {
.map(|turn| Arc::clone(&turn.state))
}
pub(crate) fn prepare_step_catalog(
&self,
cloud: Option<SkillCatalog>,
executor: SkillCatalog,
discovery_v2: bool,
) -> SkillStepCatalog {
let mut step = SkillStepCatalog::new(cloud, executor, discovery_v2, Default::default());
step.aliases = self.aliases.capture(
step.catalog
.entries
.iter()
.flat_map(super::catalog::SkillCatalogEntry::source_locations)
.filter(|source| source.enabled && source.prompt_visible)
.filter_map(|source| source.alias_root.map(|root| (source.authority.kind, root))),
);
step
}
/// Returns the executor catalog, reusing matching discovery caches.
#[tracing::instrument(
name = "skills.executor.refresh_executor_catalog",
@@ -0,0 +1,148 @@
//! Retrieves installation locations from the prepared catalog without reading skill contents.
use std::collections::HashSet;
use codex_extension_api::FunctionCallError;
use codex_extension_api::ToolCall;
use codex_extension_api::ToolExecutor;
use codex_extension_api::ToolExecutorFuture;
use codex_extension_api::ToolName;
use codex_extension_api::ToolSpec;
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use crate::aliases::SkillLocator;
use super::InstallationLocation;
use super::InstallationSource;
use super::MAX_HANDLE_BYTES;
use super::SkillToolAuthoritySelector;
use super::SkillToolContext;
use super::parse_args;
use super::parse_pagination_cursor;
use super::serialized_len;
use super::skill_function_tool;
use super::skill_json_output;
use super::skill_tool_name;
use super::validate_handle;
use super::value_fingerprint;
const TOOL_NAME: &str = "installations";
const MAX_INSTALLATIONS_RESPONSE_BYTES: usize = 8 * 1024;
#[derive(Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
struct InstallationsArgs {
#[schemars(with = "String")]
package: SkillLocator,
source: Option<InstallationSource>,
cursor: Option<String>,
}
#[derive(JsonSchema, Serialize)]
#[schemars(deny_unknown_fields)]
struct InstallationsResponse {
installations: Vec<InstallationLocation>,
next_cursor: Option<String>,
}
pub(super) struct InstallationsTool {
pub(super) context: SkillToolContext,
}
impl<'call> ToolExecutor<ToolCall<'call>> for InstallationsTool {
fn tool_name(&self) -> ToolName {
skill_tool_name(TOOL_NAME)
}
fn supports_parallel_tool_calls(&self) -> bool {
true
}
fn spec(&self) -> ToolSpec {
skill_function_tool::<InstallationsArgs, InstallationsResponse>(
TOOL_NAME,
"Find a skill's enabled Cloud and executor locations, including those omitted by skills.read. Pass its provided package directly; root aliases are resolved automatically. Use source {kind: cloud} for Cloud or {kind: executor, environment_id: ...} for one environment. Omit source for all locations. Cloud locations return package and resource: pass both directly to skills.read to read the main instruction file, usually SKILL.md. Executor locations return environment_id and skill_root, the absolute directory containing instructions and supporting files such as scripts. Pass next_cursor back as cursor with the same package and source to continue listing locations. Omit cursor to start again. An empty list without next_cursor means no enabled location matches.",
)
}
fn handle<'a>(&'a self, call: ToolCall<'call>) -> ToolExecutorFuture<'a>
where
'call: 'a,
{
Box::pin(async move {
let args: InstallationsArgs = parse_args(&call)?;
validate_handle("package", args.package.as_str(), MAX_HANDLE_BYTES)?;
if let Some(source) = &args.source {
source.validate()?;
}
let matches = self.context.matching_packages(&args.package)?;
let (entry, _) = matches.first().ok_or_else(|| {
FunctionCallError::RespondToModel("skill package is not available".to_string())
})?;
let mut installations = Vec::new();
let mut seen = HashSet::new();
for installation in matches
.iter()
.flat_map(|(entry, matched_source)| {
std::iter::once(matched_source.clone()).chain(entry.source_locations())
})
.filter(|source| {
args.source
.as_ref()
.is_none_or(|filter| filter.matches(source))
})
.filter_map(|source| InstallationLocation::from_source(&source))
{
if seen.insert(installation.clone()) {
installations.push(installation);
}
}
let identity = (&entry.id.0, &args.source, &installations);
let start =
parse_pagination_cursor(args.cursor.as_deref(), &identity, "skills.installations")?;
if start > installations.len() {
return Err(FunctionCallError::RespondToModel(
"skills.installations cursor is invalid".to_string(),
));
}
let fingerprint = value_fingerprint(&identity);
let cursor_at = |offset| format!("{fingerprint:016x}:{offset}");
let budget = call.response_byte_budget(MAX_INSTALLATIONS_RESPONSE_BYTES);
let mut response = InstallationsResponse {
installations: Vec::new(),
next_cursor: None,
};
let installation_count = installations.len();
for (index, installation) in installations.into_iter().enumerate().skip(start) {
response.installations.push(installation);
response.next_cursor =
(index + 1 < installation_count).then(|| cursor_at(index + 1));
if serialized_len(&response)? > budget {
response.installations.pop();
response.next_cursor = Some(cursor_at(index));
break;
}
}
if (start < installation_count && response.installations.is_empty())
|| serialized_len(&response)? > budget
{
return Err(FunctionCallError::RespondToModel(
"skills.installations response budget leaves no room for an installation"
.to_string(),
));
}
let authority = if response
.installations
.iter()
.any(|location| matches!(location, InstallationLocation::Cloud { .. }))
{
SkillToolAuthoritySelector::Cloud
} else {
SkillToolAuthoritySelector::Executor
};
skill_json_output(&response, authority)
})
}
}
+120 -6
View File
@@ -34,6 +34,7 @@ use serde::Deserialize;
use serde::Serialize;
use serde_json::Value;
use crate::aliases::SkillLocator;
use crate::catalog::SkillAuthority;
use crate::catalog::SkillCatalog;
use crate::catalog::SkillCatalogEntry;
@@ -47,6 +48,7 @@ use crate::state::SkillsThreadState;
use crate::telemetry::ActiveSkillTurnMetrics;
use crate::telemetry::SkillTurnMetrics;
mod installations;
mod list;
mod read;
mod schema;
@@ -64,12 +66,13 @@ pub(crate) fn skill_tools(
let Some(thread_state) = thread_store.get::<SkillsThreadState>() else {
return Vec::new();
};
let discovery_v2 = step_store
.get::<Vec<ExecutorCapabilityDiscoveryV2Snapshot>>()
.is_some();
let has_executor = step_store
.get::<Vec<ResolvedSelectedCapabilityRoot>>()
.is_some_and(|roots| !roots.is_empty())
|| step_store
.get::<Vec<ExecutorCapabilityDiscoveryV2Snapshot>>()
.is_some();
|| discovery_v2;
if !thread_state.cloud_skill_enabled() && !has_executor {
return Vec::new();
}
@@ -78,18 +81,25 @@ pub(crate) fn skill_tools(
.and_then(|state| state.mcp_resources.clone());
let analytics = SkillAnalytics::from_stores(session_store, thread_store);
let context = SkillToolContext {
discovery_v2,
providers,
mcp_resources,
thread_state,
analytics,
step_catalog: step_store.get_or_init(SkillsStepState::new),
};
vec![
let mut tools: Vec<Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>> = vec![
Arc::new(list::ListTool {
context: context.clone(),
}),
Arc::new(read::ReadTool { context }),
]
Arc::new(read::ReadTool {
context: context.clone(),
}),
];
if context.discovery_v2 {
tools.push(Arc::new(installations::InstallationsTool { context }));
}
tools
}
#[derive(Clone)]
@@ -202,6 +212,7 @@ impl SkillAnalytics {
#[derive(Clone)]
struct SkillToolContext {
discovery_v2: bool,
providers: SkillProviders,
mcp_resources: Option<Arc<McpResourceClient>>,
thread_state: Arc<SkillsThreadState>,
@@ -210,6 +221,43 @@ struct SkillToolContext {
}
impl SkillToolContext {
fn matching_packages<'a>(
&'a self,
package: &SkillLocator,
) -> Result<Vec<(&'a SkillCatalogEntry, SkillSourceLocation)>, FunctionCallError> {
let snapshot = self.step_catalog.get().ok_or_else(|| {
FunctionCallError::RespondToModel(
"skill catalog is not ready for this step".to_string(),
)
})?;
let catalog = &snapshot.catalog;
let matching_entries = |resolved_package: &str, alias_source: Option<&SkillSourceKind>| {
catalog
.entries
.iter()
.filter_map(|entry| {
entry.source_locations().find_map(|source| {
if source.package.0 != resolved_package
|| alias_source.is_some_and(|kind| *kind != source.authority.kind)
{
return None;
}
SkillToolAuthority::from_authority(&source.authority)?;
Some((entry, source))
})
})
.collect::<Vec<_>>()
};
let exact = matching_entries(package.as_str(), /*alias_source*/ None);
if !exact.is_empty() || package.alias_source().is_none() {
return Ok(exact);
}
let resolved_package = snapshot.aliases.resolve(package);
Ok(resolved_package.map_or_else(Vec::new, |resolved| {
matching_entries(&resolved, package.alias_source())
}))
}
fn catalog(
&self,
authorities: &[SkillToolAuthoritySelector],
@@ -223,6 +271,72 @@ 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(())
}
fn matches(&self, source: &SkillSourceLocation) -> bool {
source.enabled
&& match self {
Self::Cloud => source.authority.kind == SkillSourceKind::Cloud,
Self::Executor { environment_id } => {
source.authority.kind == SkillSourceKind::Executor
&& source
.main_prompt
.environment_path()
.is_some_and(|(id, _)| id == environment_id)
}
}
}
}
#[derive(Clone, Debug, Eq, Hash, JsonSchema, PartialEq, Serialize)]
#[serde(untagged)]
#[schemars(deny_unknown_fields)]
enum InstallationLocation {
Cloud {
package: String,
resource: String,
},
Executor {
environment_id: String,
skill_root: String,
},
}
impl InstallationLocation {
fn from_source(source: &SkillSourceLocation) -> Option<Self> {
if !source.enabled {
return None;
}
match &source.authority.kind {
SkillSourceKind::Cloud => Some(Self::Cloud {
package: source.package.0.clone(),
resource: source.main_prompt.as_str().to_string(),
}),
SkillSourceKind::Executor => {
let (environment_id, path) = source.main_prompt.environment_path()?;
Some(Self::Executor {
environment_id: environment_id.to_string(),
skill_root: path.parent()?.inferred_native_path_string(),
})
}
SkillSourceKind::Host | SkillSourceKind::Custom(_) => None,
}
}
}
#[derive(Clone, Debug, Deserialize, Eq, Hash, JsonSchema, PartialEq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub(crate) enum SkillToolAuthority {
+153 -82
View File
@@ -17,9 +17,10 @@ use crate::catalog::SkillSourceKind;
use crate::provider::MAX_SKILL_RESOURCE_CONTENT_BYTES;
use crate::provider::SkillReadContext;
use crate::provider::SkillReadRequest;
use crate::render::build_alias_plan;
use crate::state::ExecutorReadSnapshot;
use super::InstallationLocation;
use super::InstallationSource;
use super::MAX_HANDLE_BYTES;
use super::MAX_SKILL_RESPONSE_BYTES;
use super::SkillToolAuthority;
@@ -35,6 +36,7 @@ use super::skill_tool_name;
use super::validate_handle;
const TOOL_NAME: &str = "read";
const MAX_INSTALLATION_METADATA_BYTES: usize = 1024;
#[derive(Deserialize, JsonSchema)]
struct ReadArgs {
@@ -44,14 +46,41 @@ struct ReadArgs {
cursor: Option<String>,
}
#[derive(Deserialize, JsonSchema)]
struct ReadInstallationArgs {
#[serde(flatten)]
read: ReadArgs,
source: Option<InstallationSource>,
}
#[derive(Debug, Eq, JsonSchema, PartialEq, Serialize)]
#[schemars(deny_unknown_fields)]
struct ReadResponse {
struct ReadResponse<M> {
resource: String,
contents: String,
#[serde(flatten)]
metadata: M,
next_cursor: Option<String>,
}
#[derive(Clone, Debug, Eq, JsonSchema, PartialEq, Serialize)]
struct LegacyReadMetadata {
#[serde(skip_serializing_if = "Option::is_none")]
skill_root: Option<String>,
next_cursor: Option<String>,
}
#[derive(Clone, Debug, Eq, JsonSchema, PartialEq, Serialize)]
struct InstallationReadMetadata {
installations: Vec<InstallationLocation>,
#[serde(skip_serializing_if = "std::ops::Not::not")]
installations_truncated: bool,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(untagged)]
enum ReadMetadata {
Legacy(LegacyReadMetadata),
Installations(InstallationReadMetadata),
}
#[derive(Clone)]
@@ -69,9 +98,15 @@ impl<'call> ToolExecutor<ToolCall<'call>> for ReadTool {
}
fn spec(&self) -> ToolSpec {
skill_function_tool::<ReadArgs, ReadResponse>(
if !self.context.discovery_v2 {
return skill_function_tool::<ReadArgs, ReadResponse<LegacyReadMetadata>>(
TOOL_NAME,
"Read one page from a skill. Pass its provided package directly; root aliases are resolved automatically. Omit resource to read SKILL.md; to read another file, use the same package and pass the file's complete skill:// identifier as resource. For executor-backed skills, skill_root is the skill's absolute directory in the executor filesystem and can be used to locate bundled scripts. If the package is not provided, use skills.list to find it. Pass next_cursor back as cursor to continue the same snapshot while it is cached; omit cursor to read again.",
);
}
skill_function_tool::<ReadInstallationArgs, ReadResponse<InstallationReadMetadata>>(
TOOL_NAME,
"Read one page from a skill. Pass its provided package directly; root aliases are resolved automatically. Omit resource to read SKILL.md; to read another file, use the same package and pass the file's complete skill:// identifier as resource. For executor-backed skills, skill_root is the skill's absolute directory in the executor filesystem and can be used to locate bundled scripts. If the package is not provided, use skills.list to find it. Pass next_cursor back as cursor to continue the same snapshot while it is cached; omit cursor to read again.",
"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.",
)
}
@@ -80,65 +115,42 @@ impl<'call> ToolExecutor<ToolCall<'call>> for ReadTool {
'call: 'a,
{
Box::pin(async move {
let args: ReadArgs = parse_args(&call)?;
let (args, source) = if self.context.discovery_v2 {
let args: ReadInstallationArgs = parse_args(&call)?;
(args.read, args.source)
} else {
(parse_args::<ReadArgs>(&call)?, None)
};
if let Some(source) = &source {
source.validate()?;
}
let response_byte_budget = call.response_byte_budget(MAX_SKILL_RESPONSE_BYTES);
validate_handle("package", args.package.as_str(), MAX_HANDLE_BYTES)?;
if let Some(resource) = args.resource.as_deref() {
validate_handle("resource", resource, MAX_HANDLE_BYTES)?;
}
let catalog = self.context.catalog(&[
SkillToolAuthoritySelector::Cloud,
SkillToolAuthoritySelector::Executor,
])?;
let search_authorities: &[_] = match args.package.alias_source() {
Some(SkillSourceKind::Cloud) => &[SkillToolAuthoritySelector::Cloud],
Some(SkillSourceKind::Executor) => &[SkillToolAuthoritySelector::Executor],
Some(SkillSourceKind::Host | SkillSourceKind::Custom(_)) | None => &[
SkillToolAuthoritySelector::Cloud,
SkillToolAuthoritySelector::Executor,
],
};
let mut selected_skill = None;
for &selector in search_authorities {
// Resolve prompt aliases within their primary-authority partition.
let entries = catalog
.entries
.iter()
.filter(|entry| selector.matches(&entry.authority))
.collect::<Vec<_>>();
let alias_plan = build_alias_plan(
&entries
.iter()
.copied()
.filter(|entry| entry.is_model_visible())
.collect::<Vec<_>>(),
);
selected_skill = entries.into_iter().find_map(|entry| {
let matches_alias = alias_plan
.as_ref()
.and_then(|plan| plan.shorten(&entry.id.0))
.is_some_and(|alias| alias == args.package.as_str());
entry.source_locations().find_map(|source| {
if !(source.package.0 == args.package.as_str()
|| (source.package == entry.id && matches_alias))
{
return None;
}
let output_authority =
SkillToolAuthority::from_authority(&source.authority)?.selector();
Some((entry.clone(), source, output_authority))
let matches = self.context.matching_packages(&args.package)?;
let (skill_entry, selected_source, output_authority) = matches
.iter()
.find_map(|(entry, matched_source)| {
let selected_source = match &source {
None => matched_source.clone(),
Some(filter) => std::iter::once(matched_source.clone())
.chain(entry.source_locations())
.find(|candidate| filter.matches(candidate))?,
};
let authority =
SkillToolAuthority::from_authority(&selected_source.authority)?.selector();
Some((*entry, selected_source, authority))
})
.ok_or_else(|| {
FunctionCallError::RespondToModel(if source.is_some() {
"skill package is not available from the requested source".to_string()
} else {
"skill package is not available".to_string()
})
});
if selected_skill.is_some() {
break;
}
}
let Some((skill_entry, selected_source, output_authority)) = selected_skill else {
return Err(FunctionCallError::RespondToModel(
"skill package is not available".to_string(),
));
};
})?;
let authority = selected_source.authority.clone();
let package = selected_source.package.clone();
let main_prompt = selected_source.main_prompt.clone();
@@ -173,10 +185,21 @@ impl<'call> ToolExecutor<ToolCall<'call>> for ReadTool {
(SkillReadContext::Executor { fs }, Some(fs.cache_key()))
}
};
let cursor_start = |contents: &str| {
if self.context.discovery_v2 {
parse_pagination_cursor(
args.cursor.as_deref(),
&(&source, &package, contents),
"skills.read",
)
} else {
parse_pagination_cursor(args.cursor.as_deref(), contents, "skills.read")
}
};
// Reuse the snapshot to avoid reading the whole file for each page. File edits
// are not detected on cache hits, so a continuation can return old contents.
// Snapshots have no expiry and are not cleared after the final page.
let cached = args.cursor.as_deref().and_then(|cursor| {
let cached = args.cursor.as_deref().and_then(|_| {
let access = access_key.as_ref()?;
let snapshot = self
.context
@@ -190,12 +213,7 @@ impl<'call> ToolExecutor<ToolCall<'call>> for ReadTool {
&& snapshot.result.resource == requested_resource
&& snapshot.access == *access
})?;
let start = parse_pagination_cursor(
Some(cursor),
snapshot.result.contents.as_str(),
"skills.read",
)
.ok()?;
let start = cursor_start(&snapshot.result.contents).ok()?;
Some((Arc::clone(&snapshot.result), start))
});
let (result, start) = match cached {
@@ -231,11 +249,7 @@ impl<'call> ToolExecutor<ToolCall<'call>> for ReadTool {
"skill provider returned a different resource".to_string(),
));
}
let start = parse_pagination_cursor(
args.cursor.as_deref(),
result.contents.as_str(),
"skills.read",
)?;
let start = cursor_start(&result.contents)?;
(Arc::new(result), start)
}
};
@@ -253,22 +267,78 @@ impl<'call> ToolExecutor<ToolCall<'call>> for ReadTool {
{
state.record_invocation(skill_entry.main_prompt.as_str());
}
let skill_root = if output_authority == super::SkillToolAuthoritySelector::Executor {
main_prompt
.environment_path()
.and_then(|(_, path)| path.parent())
.map(|path| path.inferred_native_path_string())
let metadata = if self.context.discovery_v2 {
let mut installations = Vec::new();
let mut installations_truncated = false;
let mut installation_bytes = 2; // JSON array brackets.
let installation_budget =
MAX_INSTALLATION_METADATA_BYTES.min(response_byte_budget / 4);
// Prefer the installation used by this read before other sources fill the budget.
for source in
std::iter::once(selected_source.clone()).chain(skill_entry.source_locations())
{
let Some(installation) = InstallationLocation::from_source(&source) else {
continue;
};
if installations.contains(&installation) {
continue;
}
let size =
serialized_len(&installation)? + usize::from(!installations.is_empty());
if installation_bytes + size > installation_budget {
installations_truncated = true;
continue;
}
installation_bytes += size;
installations.push(installation);
}
installations_truncated |= matches.iter().any(|(entry, _)| {
entry
.source_locations()
.filter_map(|source| InstallationLocation::from_source(&source))
.any(|location| !installations.contains(&location))
});
ReadMetadata::Installations(InstallationReadMetadata {
installations,
installations_truncated,
})
} else {
None
let skill_root = if output_authority == SkillToolAuthoritySelector::Executor {
main_prompt
.environment_path()
.and_then(|(_, path)| path.parent())
.map(|path| path.inferred_native_path_string())
} else {
None
};
ReadMetadata::Legacy(LegacyReadMetadata { skill_root })
};
let response = page_response(
result.resource.as_str(),
&result.contents,
skill_root.as_deref(),
&metadata,
start,
response_byte_budget,
|offset| {
if self.context.discovery_v2 {
pagination_cursor(&(&source, &package, result.contents.as_str()), offset)
} else {
pagination_cursor(result.contents.as_str(), offset)
}
},
)?;
let output = skill_json_output(&response, output_authority)?;
let response_authority = if matches!(
&response.metadata,
ReadMetadata::Installations(metadata)
if metadata.installations.iter().any(|location| {
matches!(location, InstallationLocation::Cloud { .. })
})
) {
SkillToolAuthoritySelector::Cloud
} else {
output_authority
};
let output = skill_json_output(&response, response_authority)?;
if output_authority == super::SkillToolAuthoritySelector::Executor
&& response.next_cursor.is_some()
&& result.contents.len() <= MAX_SKILL_RESOURCE_CONTENT_BYTES
@@ -293,7 +363,7 @@ impl<'call> ToolExecutor<ToolCall<'call>> for ReadTool {
&& let Some(analytics) = self.context.analytics.as_ref()
{
analytics.track_skill_invocation(
&skill_entry,
skill_entry,
&selected_source,
call.model.clone(),
call.turn_id.clone(),
@@ -309,14 +379,15 @@ impl<'call> ToolExecutor<ToolCall<'call>> for ReadTool {
fn page_response(
resource: &str,
contents: &str,
skill_root: Option<&str>,
metadata: &ReadMetadata,
start: usize,
max_response_bytes: usize,
) -> Result<ReadResponse, FunctionCallError> {
cursor_at: impl Fn(usize) -> String,
) -> Result<ReadResponse<ReadMetadata>, FunctionCallError> {
let response = |end, next_cursor| ReadResponse {
resource: resource.to_string(),
contents: contents[start..end].to_string(),
skill_root: skill_root.map(str::to_string),
metadata: metadata.clone(),
next_cursor,
};
let complete = response(contents.len(), None);
@@ -330,7 +401,7 @@ fn page_response(
while lower < upper {
// Probe strictly above lower so a multibyte character cannot stall the search.
let end = contents.ceil_char_boundary(lower.midpoint(upper).saturating_add(1));
let candidate = response(end, Some(pagination_cursor(contents, end)));
let candidate = response(end, Some(cursor_at(end)));
if serialized_len(&candidate)? <= max_response_bytes {
lower = end;
best = Some(candidate);
+48 -11
View File
@@ -26,7 +26,6 @@ use crate::render::render_prepared_skill_catalogs;
use crate::render::skill_metadata_budget;
use crate::render_observability::CatalogSurface;
use crate::render_observability::record_catalog_render;
use crate::skills_extension_state::SkillStepCatalog;
use crate::skills_extension_state::SkillToolAuthoritySelector;
use crate::skills_extension_state::SkillsStepState;
use crate::sources::SkillProviders;
@@ -114,6 +113,7 @@ pub(crate) struct CatalogContext<'a> {
thread_state: Arc<SkillsThreadState>,
config: SkillsExtensionConfig,
metadata_budget: SkillMetadataBudget,
render_policy: SkillCatalogRenderPolicy,
include_usage: bool,
warning_emitter: CatalogWarningEmitter,
}
@@ -144,12 +144,18 @@ impl<'a> CatalogContext<'a> {
}
});
let render_policy = if input.executor_capability_discovery_v2.is_some() {
SkillCatalogRenderPolicy::DiscoveryV2
} else {
SkillCatalogRenderPolicy::ExtensionCompatible
};
Some(Self {
providers,
input,
thread_state,
config,
metadata_budget,
render_policy,
include_usage,
warning_emitter,
})
@@ -214,7 +220,11 @@ impl<'a> CatalogContext<'a> {
attribute_executor_plugins(&mut executor, selected_plugins);
}
}
Arc::new(SkillStepCatalog::new(cloud, executor, discovery_v2_enabled))
Arc::new(self.thread_state.prepare_step_catalog(
cloud,
executor,
discovery_v2_enabled,
))
}),
self.discover_host_catalog(),
);
@@ -286,9 +296,19 @@ impl<'a> CatalogContext<'a> {
) -> [RenderedCatalogContribution; 3] {
let total_limit = self.metadata_budget.limit();
let default_cloud_limit = total_limit - total_limit / FILESYSTEM_BUDGET_DIVISOR;
let mut executor = PreparedSkillCatalog::new(
let step_state = self.input.step_store.get::<SkillsStepState>();
let executor_aliases = step_state
.as_ref()
.and_then(|state| state.get())
.map(|catalog| {
catalog
.aliases
.for_authority(SkillToolAuthoritySelector::Executor)
});
let mut executor = PreparedSkillCatalog::with_alias_plan(
&catalogs.executor.catalog,
SkillCatalogRenderPolicy::ExtensionCompatible,
self.render_policy,
executor_aliases,
);
executor.prefer_cloud_skills(&catalogs.cloud.catalog);
// Identify the full visible cloud inventory before budgeting, including entries
@@ -382,11 +402,21 @@ impl<'a> CatalogContext<'a> {
return None;
}
let step_state = self.input.step_store.get::<SkillsStepState>();
let cloud_aliases = step_state
.as_ref()
.and_then(|state| state.get())
.map(|catalog| {
catalog
.aliases
.for_authority(SkillToolAuthoritySelector::Cloud)
});
let shared = render_prepared_skill_catalogs(
executor,
&PreparedSkillCatalog::new(
&PreparedSkillCatalog::with_alias_plan(
&catalogs.cloud.catalog,
SkillCatalogRenderPolicy::ExtensionCompatible,
self.render_policy,
cloud_aliases,
),
&PreparedSkillCatalog::new(
&catalogs.host.catalog,
@@ -421,12 +451,22 @@ impl<'a> CatalogContext<'a> {
return (RenderedSkillCatalogs::default(), self.metadata_budget);
}
let step_state = self.input.step_store.get::<SkillsStepState>();
let cloud_aliases = step_state
.as_ref()
.and_then(|state| state.get())
.map(|catalog| {
catalog
.aliases
.for_authority(SkillToolAuthoritySelector::Cloud)
});
let cloud_budget = self.metadata_budget.with_limit(cloud_limit);
let cloud = render_available_skills(
&catalogs.cloud.catalog,
SkillCatalogRenderPolicy::ExtensionCompatible,
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| {
@@ -437,10 +477,7 @@ impl<'a> CatalogContext<'a> {
.with_limit(self.metadata_budget.limit().saturating_sub(cloud_cost));
let mut rendered = render_prepared_skill_catalogs(
executor,
&PreparedSkillCatalog::new(
&SkillCatalog::default(),
SkillCatalogRenderPolicy::ExtensionCompatible,
),
&PreparedSkillCatalog::new(&SkillCatalog::default(), self.render_policy),
&PreparedSkillCatalog::new(
&catalogs.host.catalog,
SkillCatalogRenderPolicy::CoreCompatible,
+45 -15
View File
@@ -20,6 +20,7 @@ use codex_exec_server::ExecutorCapabilityDiscoveryV2Snapshot;
use codex_exec_server::ExecutorSkill;
use codex_exec_server::FileSystemEnvironmentAccessor;
use codex_exec_server::LOCAL_FS;
use codex_exec_server::SkillDiscoveryRoot;
use codex_extension_api::ConversationHistory;
use codex_extension_api::ExtensionData;
use codex_extension_api::ExtensionEventSink;
@@ -2542,9 +2543,11 @@ async fn cloud_discovery_is_gated_and_reports_failures() -> TestResult {
}
#[tokio::test]
async fn v2_read_cache_is_scoped_to_the_captured_environment() -> TestResult {
async fn v2_root_aliases_and_read_cache_use_the_captured_environment() -> TestResult {
let directory = tempfile::tempdir()?;
let path = directory.path().join("SKILL.md");
let root = directory.path().join("skills");
let path = root.join("nested/demo/SKILL.md");
std::fs::create_dir_all(path.parent().ok_or("skill directory")?)?;
std::fs::write(&path, "original\n".repeat(2_000))?;
let manager = Arc::new(EnvironmentManager::default_for_tests());
let environment = manager
@@ -2578,21 +2581,31 @@ async fn v2_read_cache_is_scoped_to_the_captured_environment() -> TestResult {
let snapshots = vec![ExecutorCapabilityDiscoveryV2Snapshot {
environment_id: "captured".to_string(),
result: Ok(Arc::new(DiscoverV2CapabilitiesResponse {
skills: vec![ExecutorSkill {
name: "demo".to_string(),
description: "Demo".to_string(),
short_description: None,
path: PathUri::from_host_native_path(&path)?,
discovery_root: None,
dependencies: None,
policy: None,
}],
skills: ["demo", "build", "check", "deploy", "review", "test"]
.into_iter()
.map(|name| {
Ok(ExecutorSkill {
name: name.to_string(),
description: "Demo".to_string(),
short_description: None,
path: PathUri::from_host_native_path(
root.join(format!("nested/{name}/SKILL.md")),
)?,
discovery_root: Some(SkillDiscoveryRoot {
id: "codex-home-skills".to_string(),
path: PathUri::from_host_native_path(&root)?,
}),
dependencies: None,
policy: None,
})
})
.collect::<Result<Vec<_>, Box<dyn std::error::Error>>>()?,
..Default::default()
})),
}];
let package = format!(
"skill://skills/{}",
PathUri::from_host_native_path(directory.path())?
"skill://codex-home-skills/{}",
PathUri::from_host_native_path(path.parent().ok_or("skill directory")?)?
.inferred_native_path_string()
.replace('\\', "/")
.trim_start_matches('/')
@@ -2623,7 +2636,7 @@ async fn v2_read_cache_is_scoped_to_the_captured_environment() -> TestResult {
.into_iter()
.collect::<HashMap<_, _>>(),
);
registry.context_contributors()[0]
let sections = registry.context_contributors()[0]
.contribute_world_state(WorldStateContributionInput {
previous_world_state: None,
step_store: &step_store,
@@ -2640,6 +2653,13 @@ async fn v2_read_cache_is_scoped_to_the_captured_environment() -> TestResult {
turn_store: &turn_store,
})
.await;
let rendered = sections
.iter()
.filter_map(|section| section.render_diff(PreviousWorldStateSection::Absent).1)
.map(|fragment| fragment.body().clone().expect_text())
.collect::<Vec<_>>()
.join("\n");
assert!(rendered.contains("e0/nested/demo"), "{rendered}");
let tools = registry.tool_contributors()[0].tools_for_step(
&session_store,
&thread_store,
@@ -2650,7 +2670,8 @@ async fn v2_read_cache_is_scoped_to_the_captured_environment() -> TestResult {
.find(|tool| tool.tool_name().name == "read")
.ok_or("skills.read")?;
let payload = ToolPayload::Function {
arguments: serde_json::json!({"package": package, "cursor": cursor}).to_string(),
arguments: serde_json::json!({"package": "e0/nested/demo", "cursor": cursor})
.to_string(),
};
let result = read
.handle(ToolCall {
@@ -2686,6 +2707,15 @@ async fn v2_read_cache_is_scoped_to_the_captured_environment() -> TestResult {
let response = result?
.post_tool_use_response("read", &payload)
.ok_or("read output")?;
assert_eq!(response["resource"], format!("{package}/SKILL.md"));
assert_eq!(
response["installations"],
serde_json::json!([{
"environment_id": "captured",
"skill_root": PathUri::from_host_native_path(path.parent().ok_or("skill directory")?)?
.inferred_native_path_string(),
}])
);
assert!(
response["contents"]
.as_str()
@@ -80,7 +80,10 @@ async fn v2_steps_refresh_metadata_and_preserve_separate_environments() -> TestR
description: "Build a dashboard".to_string(),
short_description: None,
path: skill_path.clone(),
discovery_root: None,
discovery_root: Some(SkillDiscoveryRoot {
id: "codex-home-skills".to_string(),
path: PathUri::parse("file:///executor/skills")?,
}),
dependencies: dependencies.clone(),
policy: Some(SkillPolicy {
allow_implicit_invocation: Some(false),
@@ -100,6 +103,25 @@ async fn v2_steps_refresh_metadata_and_preserve_separate_environments() -> TestR
executor_capability_discovery: None,
executor_capability_discovery_v2: Some(snapshots.clone()),
};
// Standalone skills without discovery-root metadata use the skills namespace.
let mut fallback_query = query.clone();
for snapshot in fallback_query
.executor_capability_discovery_v2
.as_mut()
.unwrap()
{
Arc::make_mut(snapshot.result.as_mut().unwrap()).skills[0].discovery_root = None;
}
let fallback = provider.list(fallback_query).await?;
assert_eq!(fallback.entries.len(), 4);
assert_eq!(
fallback.entries[1].id.0,
"skill://skills/executor/skills/dashboard"
);
assert_eq!(
fallback.entries[1].main_prompt.environment_id(),
Some("remote-a")
);
let catalog = provider.list(query).await?;
assert_eq!(catalog.entries.len(), 4);
let merged = merge_catalogs(/*cloud*/ None, catalog.clone());
@@ -148,8 +170,11 @@ async fn v2_steps_refresh_metadata_and_preserve_separate_environments() -> TestR
assert_eq!(entry.dependencies, dependencies);
assert!(entry.enabled);
assert!(!entry.prompt_visible);
assert_eq!(entry.authority.id, "skills");
assert_eq!(entry.id.0, "skill://skills/executor/skills/dashboard");
assert_eq!(entry.authority.id, "codex-home-skills");
assert_eq!(
entry.id.0,
"skill://codex-home-skills/executor/skills/dashboard"
);
assert_eq!(
entry.main_prompt,
SkillResourceId::environment(entry.main_prompt.as_str(), "remote-a", skill_path.clone(),)
@@ -194,6 +194,15 @@ async fn call_tool(
tools: &[Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>],
name: &str,
arguments: Value,
) -> Result<Value, FunctionCallError> {
call_tool_with_budget(tools, name, arguments, TruncationPolicy::Bytes(10_000)).await
}
async fn call_tool_with_budget(
tools: &[Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>],
name: &str,
arguments: Value,
truncation_policy: TruncationPolicy,
) -> Result<Value, FunctionCallError> {
let tool = tools
.iter()
@@ -203,6 +212,8 @@ async fn call_tool(
arguments: arguments.to_string(),
};
let access = FileSystemEnvironmentAccessor::unrestricted(&LOCAL_FS);
let cwd = PathUri::parse("file:///installed")
.map_err(|error| FunctionCallError::RespondToModel(error.to_string()))?;
let result = tool
.handle(ToolCall {
turn_id: "turn-1".to_string(),
@@ -210,18 +221,16 @@ async fn call_tool(
tool_name: tool.tool_name(),
model: "test".to_string(),
codex_turn_metadata: None,
truncation_policy: TruncationPolicy::Bytes(10_000),
truncation_policy,
source: ToolCallSource::Direct,
conversation_history: ConversationHistory::default(),
turn_item_emitter: Arc::new(NoopTurnItemEmitter),
attachment_store: Arc::new(InlineAttachmentStore),
ephemeral: false,
environments: vec![ToolEnvironment::new(
"env-1".to_string(),
PathUri::parse("file:///installed")
.map_err(|error| FunctionCallError::RespondToModel(error.to_string()))?,
&access,
)],
environments: ["env-1", "env-2", "env-3"]
.into_iter()
.map(|id| ToolEnvironment::new(id.to_string(), cwd.clone(), &access))
.collect(),
payload: payload.clone(),
})
.await?;
@@ -231,9 +240,22 @@ async fn call_tool(
arguments["authority"]["kind"] == "cloud"
);
}
result
let response = result
.post_tool_use_response("skill-test", &payload)
.ok_or_else(|| FunctionCallError::RespondToModel("missing skill response".to_string()))
.ok_or_else(|| FunctionCallError::RespondToModel("missing skill response".to_string()))?;
let includes_cloud_location = response["installations"]
.as_array()
.is_some_and(|locations| {
locations
.iter()
.any(|location| location.get("resource").is_some())
});
if name == "installations" {
assert_eq!(result.contains_external_context(), includes_cloud_location);
} else if name == "read" && includes_cloud_location {
assert!(result.contains_external_context());
}
Ok(response)
}
fn selected_plugins(roots: &[Option<&str>], disabled: &[&str]) -> SelectedPluginSnapshot {
@@ -356,6 +378,209 @@ async fn v2_merged_skills_preserve_cloud_metadata_and_accepted_plugin_routes() -
Ok(())
}
#[tokio::test]
async fn executor_aliases_survive_cloud_promotion_without_reassigning_remaining_roots() -> TestResult
{
let promoted_root = format!("installed-{}", "a".repeat(120));
let local_root = format!("local-{}", "b".repeat(120));
let names = ["work", "build", "check", "deploy", "review", "test"];
let mut installed = Vec::new();
for root in [&promoted_root, &local_root] {
for name in names {
let mut entry = installed_skill(root, name)?.with_alias_root(format!("skill://{root}"));
if root == &local_root {
entry = entry.with_remote_plugin_id(/*remote_plugin_id*/ None);
entry.name = format!("local:{name}");
}
installed.push(entry);
}
}
let config = TestConfig {
cloud_skill_enabled: false,
..default_config()
};
let mut harness = MergeHarness::new(
provider(installed.clone()),
provider(names.into_iter().map(cloud_skill).collect()),
config.clone(),
)
.await?;
for cloud_skill_enabled in [false, true] {
if cloud_skill_enabled {
harness.registry.config_contributors()[0].on_config_changed(
&harness.session_store,
&harness.thread_store,
&config,
&TestConfig {
cloud_skill_enabled: true,
..config.clone()
},
);
harness.turn_store = ExtensionData::new("turn-2");
harness.step_store = ExtensionData::new("step-2");
start_registered_turn(
&harness.registry,
&harness.session_store,
&harness.thread_store,
harness.turn_store.level_id(),
)
.await;
}
let tools = harness.tools(&harness.step_store);
let rendered = harness.render().await?;
assert!(rendered.contains("e1/work"), "{rendered}");
assert!(
rendered.contains(&format!("- `e1` = `skill://{local_root}`")),
"{rendered}"
);
assert_eq!(
rendered.contains(&format!("- `e0` = `skill://{promoted_root}`")),
!cloud_skill_enabled,
"{rendered}"
);
assert_eq!(
rendered.contains("e0/work"),
!cloud_skill_enabled,
"{rendered}"
);
for (alias, entry) in [
("e0/work", &installed[0]),
("e1/work", &installed[names.len()]),
] {
let output = call_tool(&tools, "read", json!({"package": alias})).await?;
assert_eq!(output["resource"], json!(entry.main_prompt.as_str()));
let full = call_tool(&tools, "read", json!({"package": entry.id.0})).await?;
assert_eq!(output, full);
}
if cloud_skill_enabled {
for tool in ["read", "installations"] {
let aliased = call_tool(
&tools,
tool,
json!({"package": "e0/work", "source": {"kind": "cloud"}}),
)
.await?;
let full = call_tool(
&tools,
tool,
json!({"package": installed[0].id.0, "source": {"kind": "cloud"}}),
)
.await?;
assert_eq!(aliased, full);
}
}
let output = call_tool(&tools, "list", json!({"authority": {"kind": "executor"}})).await?;
assert_eq!(
output["skills"].as_array().unwrap().len(),
if cloud_skill_enabled {
names.len()
} else {
installed.len()
}
);
}
Ok(())
}
#[tokio::test]
async fn rejected_roots_do_not_starve_accepted_alternate_and_standalone_aliases() -> TestResult {
let mut entries = Vec::new();
// Together these individually allocatable roots exceed the shared 16 KiB allowance.
for index in 0..180 {
let root = format!("a-rejected-{index:03}-{}", "x".repeat(120));
let entry = installed_skill(&root, "work")?
.with_alias_root(format!("skill://{root}"))
.with_remote_plugin_id(Some(format!("Rejected_{index}")));
entries.push(entry);
}
let promoted = installed_skill("b-promoted", "work")?.with_alias_root("skill://b-promoted");
let mut standalone = installed_skill("c-local", "work")?
.with_alias_root("skill://c-local")
.with_remote_plugin_id(/*remote_plugin_id*/ None)
.with_plugin_id(/*plugin_id*/ None);
standalone.name = "local:work".to_string();
entries.extend([promoted.clone(), standalone.clone()]);
let harness = MergeHarness::new(
provider(entries),
provider(vec![cloud_skill("work")]),
default_config(),
)
.await?;
let tools = harness.tools(&harness.step_store);
harness.render().await?;
for (alias, entry) in [("e0/work", promoted), ("e1/work", standalone)] {
let output = call_tool(&tools, "read", json!({"package": alias})).await?;
assert_eq!(output["resource"], json!(entry.main_prompt.as_str()));
}
Ok(())
}
#[tokio::test]
async fn cloud_rendering_and_reads_share_aliases_after_a_plugin_is_disabled() -> TestResult {
let roots = [
format!("Plugin_{}", "a".repeat(120)),
format!("Plugin_{}", "b".repeat(120)),
];
let names = ["work", "build", "check", "deploy", "review", "test"];
let entries = roots
.iter()
.flat_map(|root| {
names.map(|name| {
let package = format!("skill://{root}/{name}");
SkillCatalogEntry::new(
SkillPackageId(package.clone()),
SkillAuthority::new(SkillSourceKind::Cloud, "codex_apps"),
format!("{root}:{name}"),
"Cloud skill",
SkillResourceId::new(format!("{package}/SKILL.md")),
)
.with_alias_root(format!("skill://{root}"))
.with_remote_plugin_id(Some(root.clone()))
})
})
.collect();
let harness =
MergeHarness::new(provider(Vec::new()), provider(entries), default_config()).await?;
let rendered = harness.render().await?;
assert!(rendered.contains(
"For each alias listed below, this mapping replaces any earlier mapping for that alias."
));
assert!(
rendered.contains("c0/work") && rendered.contains("c1/work"),
"{rendered}"
);
let step = ExtensionData::new("step-2");
step.insert(SelectedPluginSnapshot {
plugins: vec![SelectedPluginIdentity {
selected_root_id: None,
plugin_id: PluginIdentity::Remote {
remote_plugin_id: roots[1].clone(),
},
}],
disabled_plugin_ids: vec![roots[0].clone()],
..Default::default()
});
let rendered = harness.render_step(&step).await?;
assert!(rendered.contains("c1/work"), "{rendered}");
assert!(!rendered.contains(&roots[0]), "{rendered}");
let tools = harness.tools(&step);
let aliased = call_tool(&tools, "read", json!({"package": "c1/work"})).await?;
let full = call_tool(
&tools,
"read",
json!({"package": format!("skill://{}/work", roots[1])}),
)
.await?;
assert_eq!(aliased, full);
assert!(
call_tool(&tools, "read", json!({"package": "c0/work"}))
.await
.is_err()
);
Ok(())
}
#[tokio::test]
async fn v2_only_complete_cloud_catalog_excludes_unmatched_remote_skills() -> TestResult {
let mut unavailable = provider(vec![cloud_skill("work")]);
@@ -420,6 +645,362 @@ async fn v2_disabled_remote_plugin_blocks_both_read_routes() -> TestResult {
Ok(())
}
#[tokio::test]
async fn v1_reads_preserve_response_shape_without_installations_tool() -> TestResult {
let cloud = cloud_skill("work");
let executor = installed_skill("first", "work")?;
let mut disabled = MergeHarness::new(
provider(vec![executor.clone()]),
provider(vec![cloud.clone()]),
default_config(),
)
.await?;
disabled.snapshots = None;
assert_eq!(
disabled
.tools(&disabled.step_store)
.iter()
.map(|tool| tool.tool_name().name)
.collect::<Vec<_>>(),
["list", "read"],
);
disabled.render().await?;
let tools = disabled.tools(&disabled.step_store);
for entry in [&cloud, &executor] {
let mut expected = json!({
"resource": entry.main_prompt.as_str(),
"contents": "# Lint Fix\n\nRun the formatter.",
"next_cursor": null,
});
if entry.authority.kind == SkillSourceKind::Executor {
expected["skill_root"] =
json!(PathUri::parse("file:///skills/first")?.inferred_native_path_string());
}
assert_eq!(
call_tool(&tools, "read", json!({"package": entry.id.0})).await?,
expected
);
}
Ok(())
}
#[tokio::test]
async fn v2_reads_preserve_content_routes_with_bounded_installations() -> TestResult {
let cloud = cloud_skill("work").with_alias_root("skill://Plugin_123");
let selected = installed_skill("selected", "work")?;
let mut entries = vec![installed_skill(&"long".repeat(600), "work")?];
let mut locations =
vec![json!({"package": cloud.id.0, "resource": cloud.main_prompt.as_str()})];
for index in 0..20 {
entries.push(installed_skill(&format!("root-{index}"), "work")?);
locations.push(json!({
"environment_id": "env-1",
"skill_root": PathUri::parse(&format!("file:///skills/root-{index}"))?.inferred_native_path_string(),
}));
}
entries.push(selected.clone());
let mut opaque =
installed_skill("opaque", "work")?.with_remote_plugin_id(/*remote_plugin_id*/ None);
opaque.id = SkillPackageId("c0/opaque".to_string());
entries.push(opaque.clone());
locations.push(json!({
"environment_id": "env-1",
"skill_root": PathUri::parse("file:///skills/selected")?.inferred_native_path_string(),
}));
let executor = provider(entries);
let executor_reads = executor.read_requests.clone();
let cloud_provider = provider(vec![cloud.clone()]);
let cloud_reads = cloud_provider.read_requests.clone();
let harness = MergeHarness::new(executor, cloud_provider, default_config()).await?;
let tools = harness.tools(&harness.step_store);
harness.render().await?;
for (package, source, requested, limit) in [
("c0/work", Value::Null, &cloud, 10_000),
(selected.id.0.as_str(), Value::Null, &selected, 1000),
(
selected.id.0.as_str(),
json!({"kind": "cloud"}),
&cloud,
10_000,
),
] {
let mut ordered = locations.clone();
if requested.authority.kind == SkillSourceKind::Executor {
// The selected location must fit even when it is last in catalog order.
let location = ordered.pop().unwrap();
ordered.insert(0, location);
}
let output = call_tool_with_budget(
&tools,
"read",
json!({"package": package, "source": source}),
TruncationPolicy::Bytes(limit),
)
.await?;
let installations = output["installations"].as_array().unwrap();
assert!(installations.len() >= 2);
assert!(installations.len() < locations.len());
assert!(serde_json::to_vec(installations)?.len() <= 1024.min(limit * 6 / 5 / 4));
assert!(serde_json::to_vec(&output)?.len() <= limit * 6 / 5);
let expected = json!({
"resource": requested.main_prompt.as_str(),
"contents": "# Lint Fix\n\nRun the formatter.",
"installations": &ordered[..installations.len()],
"installations_truncated": true,
"next_cursor": null,
});
assert_eq!(output, expected);
}
for (reads, entry) in [(cloud_reads, cloud), (executor_reads, selected)] {
assert_eq!(
read_request_keys(&reads),
vec![(entry.authority, entry.id, entry.main_prompt)]
);
}
for tool in ["read", "installations"] {
let output = call_tool(&tools, tool, json!({"package": opaque.id.0})).await?;
assert_eq!(
output["installations"],
json!([{
"environment_id": "env-1",
"skill_root": PathUri::parse("file:///skills/opaque")?.inferred_native_path_string(),
}])
);
}
let first = installed_skill("shared", "work")?
.with_remote_plugin_id(/*remote_plugin_id*/ None)
.with_alias_root("skill://shared");
let mut second = first.clone();
second.main_prompt = SkillResourceId::environment(
first.main_prompt.as_str(),
"env-2",
PathUri::parse("file:///skills/shared/SKILL.md")?,
);
let executor = provider(vec![first.clone(), second.clone()]);
let reads = executor.read_requests.clone();
let harness = MergeHarness::new(executor, provider(Vec::new()), default_config()).await?;
let tools = harness.tools(&harness.step_store);
harness.render().await?;
let locations = ["env-1", "env-2"].map(|environment_id| {
json!({
"environment_id": environment_id,
"skill_root": PathUri::parse("file:///skills/shared").unwrap().inferred_native_path_string(),
})
});
let read = call_tool(&tools, "read", json!({"package": first.id.0})).await?;
assert_eq!(
read,
json!({
"resource": first.main_prompt.as_str(),
"contents": "# Lint Fix\n\nRun the formatter.",
"installations": [locations[0]],
"installations_truncated": true,
"next_cursor": null,
}),
);
assert_eq!(
call_tool(&tools, "installations", json!({"package": "e0/work"})).await?,
json!({"installations": locations, "next_cursor": null}),
);
assert_eq!(
call_tool(
&tools,
"installations",
json!({"package": "e0/work", "source": {"kind": "executor", "environment_id": "env-2"}}),
)
.await?,
json!({"installations": [locations[1]], "next_cursor": null}),
);
let source = json!({"kind": "executor", "environment_id": "env-2"});
let selected = call_tool(
&tools,
"read",
json!({"package": "e0/work", "source": source}),
)
.await?;
assert_eq!(
selected,
json!({
"resource": second.main_prompt.as_str(),
"contents": "# Lint Fix\n\nRun the formatter.",
"installations": [locations[1]],
"installations_truncated": true,
"next_cursor": null,
})
);
assert_eq!(
read_request_keys(&reads),
vec![
(
first.authority.clone(),
first.id.clone(),
first.main_prompt.clone()
),
(
second.authority.clone(),
second.id.clone(),
second.main_prompt.clone()
),
]
);
assert_eq!(
call_tool(&tools, "read", json!({"package": "e0/work"})).await?,
read,
);
assert_eq!(
call_tool(
&tools,
"read",
json!({"package": first.id.0, "source": source})
)
.await?,
selected,
);
for source in [
json!({"kind": "cloud"}),
json!({"kind": "executor", "environment_id": "missing"}),
] {
assert_matches!(
call_tool(&tools, "read", json!({"package": "e0/work", "source": source})).await,
Err(FunctionCallError::RespondToModel(message)) if message == "skill package is not available from the requested source"
);
}
let page = call_tool_with_budget(
&tools,
"read",
json!({"package": "e0/work", "source": source}),
TruncationPolicy::Bytes(120),
)
.await?;
let cursor = &page["next_cursor"];
assert!(!cursor.is_null());
let next = call_tool(
&tools,
"read",
json!({"package": "e0/work", "source": source, "cursor": cursor}),
)
.await?;
assert_eq!(
format!(
"{}{}",
page["contents"].as_str().unwrap(),
next["contents"].as_str().unwrap()
),
"# Lint Fix\n\nRun the formatter."
);
assert!(call_tool(&tools, "read", json!({
"package": "e0/work", "source": {"kind": "executor", "environment_id": "env-1"}, "cursor": cursor,
})).await.is_err());
Ok(())
}
#[tokio::test]
async fn v2_installations_filter_all_matching_locations_and_paginate_within_budget() -> TestResult {
let cloud = cloud_skill("work").with_alias_root("skill://Plugin_123");
let cloud_location = json!({"package": cloud.id.0, "resource": cloud.main_prompt.as_str()});
let mut entries = vec![
installed_skill("disabled", "work")?.disabled(),
installed_skill("unrelated", "other")?,
];
let mut expected = vec![cloud_location.clone()];
for index in 0..140 {
entries.push(installed_skill(&format!("root-{index}"), "work")?);
expected.push(json!({
"environment_id": "env-1",
"skill_root": PathUri::parse(&format!("file:///skills/root-{index}"))?.inferred_native_path_string(),
}));
}
entries.push(entries[2].clone());
let executor = provider(entries);
let executor_reads = executor.read_requests.clone();
let cloud_provider = provider(vec![cloud]);
let cloud_reads = cloud_provider.read_requests.clone();
let harness = MergeHarness::new(executor, cloud_provider, default_config()).await?;
let tools = harness.tools(&harness.step_store);
harness.render().await?;
assert_eq!(
call_tool(
&tools,
"installations",
json!({
"package": "skill://root-0/work", "source": {"kind": "cloud"},
})
)
.await?,
json!({"installations": [cloud_location], "next_cursor": null}),
);
assert_eq!(
call_tool(
&tools,
"installations",
json!({
"package": "c0/work", "source": {"kind": "executor", "environment_id": "missing"},
})
)
.await?,
json!({"installations": [], "next_cursor": null}),
);
let mut locations = Vec::new();
let mut cursor = Value::Null;
let mut first_cursor = Value::Null;
for _ in 0..=expected.len() {
let page = call_tool(
&tools,
"installations",
json!({"package": "c0/work", "cursor": cursor}),
)
.await?;
assert!(serde_json::to_vec(&page)?.len() <= 8 * 1024);
locations.extend(page["installations"].as_array().unwrap().iter().cloned());
cursor = page["next_cursor"].clone();
if first_cursor.is_null() {
first_cursor = cursor.clone();
}
if cursor.is_null() {
break;
}
}
assert!(!first_cursor.is_null());
assert_eq!(cursor, Value::Null);
assert_eq!(locations, expected);
assert!(
call_tool(
&tools,
"installations",
json!({
"package": "c0/work", "source": {"kind": "cloud"}, "cursor": first_cursor,
})
)
.await
.is_err()
);
let small_page = call_tool_with_budget(
&tools,
"installations",
json!({"package": "c0/work"}),
TruncationPolicy::Bytes(300),
)
.await?;
assert!(serde_json::to_vec(&small_page)?.len() <= 360);
assert!(!small_page["next_cursor"].is_null());
assert!(
call_tool_with_budget(
&tools,
"installations",
json!({"package": "c0/work"}),
TruncationPolicy::Bytes(1),
)
.await
.is_err()
);
assert!(read_request_keys(&cloud_reads).is_empty());
assert!(read_request_keys(&executor_reads).is_empty());
Ok(())
}
#[tokio::test]
async fn v2_rendering_and_tools_retain_their_step_catalog() -> TestResult {
let installed =
@@ -174,7 +174,10 @@ async fn cloud_preference_preserves_aliases_reads_and_executor_fallback() -> Tes
} else {
assert!(executor_body.contains("(executor package: e1/s0)"));
for (index, root) in executor_roots.iter().enumerate() {
assert!(executor_body.contains(&format!("- `e{index}` = `{root}`")));
assert_eq!(
executor_body.contains(&format!("- `e{index}` = `{root}`")),
index == 1 || !cloud_enabled,
);
}
}
previous = snapshots;