Base: codex-main originale (prima del fork aKode)
This commit is contained in:
@@ -0,0 +1,369 @@
|
||||
//! Cloud catalog reuse, refresh retries, and auth-scoped retention through real Core turns.
|
||||
|
||||
use super::*;
|
||||
use codex_extension_api::ThreadLifecycleContributor;
|
||||
use codex_extension_api::ThreadStartInput;
|
||||
use codex_mcp::McpResourceClient;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
|
||||
struct CloudTurnProvider {
|
||||
reply: Mutex<Result<Option<(&'static str, u32)>, ()>>,
|
||||
lists: AtomicUsize,
|
||||
reads: AtomicUsize,
|
||||
resource_key: Mutex<Option<codex_mcp::McpResourceServerCacheKey>>,
|
||||
}
|
||||
|
||||
impl SkillProvider for CloudTurnProvider {
|
||||
fn list<'a>(&'a self, query: SkillListQuery<'a>) -> SkillProviderFuture<'a, SkillCatalog> {
|
||||
Box::pin(async move {
|
||||
self.lists.fetch_add(1, Ordering::SeqCst);
|
||||
*self.resource_key.lock().expect("resource key lock") = query
|
||||
.mcp_resources
|
||||
.as_ref()
|
||||
.and_then(|client| client.server_cache_key(CODEX_APPS_MCP_SERVER_NAME));
|
||||
let reply = *self.reply.lock().expect("cloud reply lock");
|
||||
let selected =
|
||||
reply.map_err(|()| SkillProviderError::new("cloud skill unavailable"))?;
|
||||
let entries = selected
|
||||
.into_iter()
|
||||
.map(|(plugin, revision)| {
|
||||
let package = format!("skill://{plugin}/demo");
|
||||
SkillCatalogEntry::new(
|
||||
SkillPackageId(package.clone()),
|
||||
SkillAuthority::new(SkillSourceKind::Cloud, CODEX_APPS_MCP_SERVER_NAME),
|
||||
format!("{plugin}:demo"),
|
||||
format!("Cloud {plugin} revision {revision}"),
|
||||
SkillResourceId::new(format!("{package}/SKILL.md")),
|
||||
)
|
||||
.with_display_path(&package)
|
||||
.with_alias_root(format!("skill://{plugin}"))
|
||||
})
|
||||
.collect();
|
||||
Ok(SkillCatalog {
|
||||
is_partial: false,
|
||||
entries,
|
||||
warnings: Vec::new(),
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn read<'a>(
|
||||
&'a self,
|
||||
request: SkillReadRequest<'a>,
|
||||
) -> SkillProviderFuture<'a, SkillReadResult> {
|
||||
Box::pin(async move {
|
||||
self.reads.fetch_add(1, Ordering::SeqCst);
|
||||
let selected = *self.reply.lock().expect("cloud reply lock");
|
||||
let (plugin, revision) = selected
|
||||
.ok()
|
||||
.flatten()
|
||||
.ok_or_else(|| SkillProviderError::new("cloud skill unavailable"))?;
|
||||
assert_eq!(
|
||||
request.resource.as_str(),
|
||||
format!("skill://{plugin}/demo/SKILL.md")
|
||||
);
|
||||
Ok(SkillReadResult {
|
||||
resource: request.resource,
|
||||
contents: format!("{plugin} instructions {revision}"),
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn search(&self, _request: SkillSearchRequest) -> SkillProviderFuture<'_, SkillSearchResult> {
|
||||
Box::pin(async { Ok(SkillSearchResult::default()) })
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct SessionResources(Mutex<Option<Arc<McpResourceClient>>>);
|
||||
|
||||
impl ThreadLifecycleContributor<Config> for SessionResources {
|
||||
fn on_thread_start<'a>(
|
||||
&'a self,
|
||||
input: ThreadStartInput<'a, Config>,
|
||||
) -> ExtensionFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
*self.0.lock().expect("session resources lock") = input.mcp_resource_client.clone();
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn cloud_skills_reuse_cache_and_invalidate_on_connection_or_auth_change() -> Result<()> {
|
||||
core_test_support::skip_if_no_network!(Ok(()));
|
||||
|
||||
let server = responses::start_mock_server().await;
|
||||
let apps = AppsTestServer::mount(&server).await?;
|
||||
let calendar = ("calendar", 1);
|
||||
let updated_calendar = ("calendar", 2);
|
||||
let gmail = ("gmail", 1);
|
||||
let provider = Arc::new(CloudTurnProvider {
|
||||
reply: Mutex::new(Ok(Some(calendar))),
|
||||
lists: AtomicUsize::new(0),
|
||||
reads: AtomicUsize::new(0),
|
||||
resource_key: Mutex::new(None),
|
||||
});
|
||||
let resources = Arc::new(SessionResources::default());
|
||||
let mut extensions = ExtensionRegistryBuilder::new();
|
||||
extensions.thread_lifecycle_contributor(resources.clone());
|
||||
install_with_providers(
|
||||
&mut extensions,
|
||||
SkillProviders::new().with_cloud_provider(provider.clone()),
|
||||
|_config: &Config| SkillsExtensionConfig {
|
||||
include_instructions: true,
|
||||
catalog_deltas_enabled: false,
|
||||
omit_descriptions: false,
|
||||
max_context_tokens: None,
|
||||
bundled_skills_enabled: false,
|
||||
cloud_skill_enabled: true,
|
||||
shadow_selection_enabled: false,
|
||||
},
|
||||
);
|
||||
let mut builder = apps_enabled_builder(apps.chatgpt_base_url)
|
||||
.with_exec_server_url("none")
|
||||
.with_extensions(Arc::new(extensions.build()))
|
||||
.with_auth(CodexAuth::from_external_chatgpt_tokens(
|
||||
"header.e30.initial",
|
||||
"account-a",
|
||||
/*chatgpt_plan_type*/ None,
|
||||
)?)
|
||||
.with_config(move |config| {
|
||||
config.include_skill_instructions = true;
|
||||
config.cloud_skill_enabled = true;
|
||||
});
|
||||
let test = builder.build_with_auto_env(&server).await?;
|
||||
let mut last_available_skill = calendar;
|
||||
// Back off failures across steps and turns; reconnects allow immediate recovery.
|
||||
for (turn, next_reply, expected_skill, new_account, expected_lists, expected_reads) in [
|
||||
("discovered", Ok(Some(calendar)), Some(calendar), None, 1, 1),
|
||||
(
|
||||
"cached",
|
||||
Ok(Some(updated_calendar)),
|
||||
Some(calendar),
|
||||
None,
|
||||
0,
|
||||
0,
|
||||
),
|
||||
(
|
||||
"refreshed",
|
||||
Ok(Some(updated_calendar)),
|
||||
Some(updated_calendar),
|
||||
None,
|
||||
1,
|
||||
1,
|
||||
),
|
||||
(
|
||||
"same-account-failure",
|
||||
Err(()),
|
||||
Some(updated_calendar),
|
||||
None,
|
||||
1,
|
||||
0,
|
||||
),
|
||||
("removed", Ok(None), None, None, 1, 0),
|
||||
("empty-cached", Ok(Some(updated_calendar)), None, None, 0, 0),
|
||||
(
|
||||
"restored",
|
||||
Ok(Some(updated_calendar)),
|
||||
Some(updated_calendar),
|
||||
None,
|
||||
1,
|
||||
1,
|
||||
),
|
||||
(
|
||||
"auth-changed-failure",
|
||||
Err(()),
|
||||
None,
|
||||
Some("account-b"),
|
||||
1,
|
||||
0,
|
||||
),
|
||||
("new-account-cooldown", Ok(Some(gmail)), None, None, 0, 0),
|
||||
(
|
||||
"new-account-discovered",
|
||||
Ok(Some(gmail)),
|
||||
Some(gmail),
|
||||
None,
|
||||
1,
|
||||
1,
|
||||
),
|
||||
(
|
||||
"connection-replaced-failure",
|
||||
Err(()),
|
||||
Some(gmail),
|
||||
None,
|
||||
1,
|
||||
0,
|
||||
),
|
||||
(
|
||||
"replacement-connection-discovered",
|
||||
Ok(Some(gmail)),
|
||||
Some(gmail),
|
||||
None,
|
||||
1,
|
||||
1,
|
||||
),
|
||||
] {
|
||||
let previous_lists = provider.lists.load(Ordering::SeqCst);
|
||||
let previous_reads = provider.reads.load(Ordering::SeqCst);
|
||||
*provider.reply.lock().expect("cloud reply lock") = next_reply;
|
||||
let previous_connection_scope = if matches!(
|
||||
turn,
|
||||
"refreshed"
|
||||
| "same-account-failure"
|
||||
| "removed"
|
||||
| "restored"
|
||||
| "new-account-discovered"
|
||||
| "connection-replaced-failure"
|
||||
| "replacement-connection-discovered"
|
||||
) {
|
||||
let client = resources
|
||||
.0
|
||||
.lock()
|
||||
.expect("session resources lock")
|
||||
.clone()
|
||||
.expect("thread MCP resource client");
|
||||
let auth = client.auth_cache_key_for_server(CODEX_APPS_MCP_SERVER_NAME);
|
||||
let connection = client.server_cache_key(CODEX_APPS_MCP_SERVER_NAME);
|
||||
// Turn-start preparation must consume the pending reconnect before discovery.
|
||||
test.codex.submit(Op::RefreshMcpServers).await?;
|
||||
Some((client, auth, connection))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(account) = new_account {
|
||||
let client = resources
|
||||
.0
|
||||
.lock()
|
||||
.expect("session resources lock")
|
||||
.clone()
|
||||
.expect("thread MCP resource client");
|
||||
let previous_auth = client.auth_cache_key_for_server(CODEX_APPS_MCP_SERVER_NAME);
|
||||
codex_login::auth::login_with_chatgpt_auth_tokens(
|
||||
test.codex_home_path(),
|
||||
"header.e30.changed",
|
||||
account,
|
||||
/*chatgpt_plan_type*/ None,
|
||||
)?;
|
||||
test.thread_manager.auth_manager().reload().await;
|
||||
// Wait for the real auth transition, without manually refreshing MCP.
|
||||
tokio::time::timeout(Duration::from_secs(10), async {
|
||||
while client.auth_cache_key_for_server(CODEX_APPS_MCP_SERVER_NAME) == previous_auth
|
||||
{
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await?;
|
||||
assert_eq!(provider.lists.load(Ordering::SeqCst), previous_lists);
|
||||
}
|
||||
// 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}");
|
||||
let response = responses::mount_sse_sequence(
|
||||
&server,
|
||||
vec![
|
||||
sse(vec![
|
||||
ev_response_created("tools"),
|
||||
responses::ev_function_call_with_namespace(
|
||||
&list_id,
|
||||
"skills",
|
||||
"list",
|
||||
&json!({"authority":{"kind":"cloud"}}).to_string(),
|
||||
),
|
||||
responses::ev_function_call_with_namespace(
|
||||
&read_id,
|
||||
"skills",
|
||||
"read",
|
||||
&json!({"package": alias}).to_string(),
|
||||
),
|
||||
ev_completed("tools"),
|
||||
]),
|
||||
sse(vec![ev_response_created("done"), ev_completed("done")]),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
test.submit_turn("Inspect the cloud skill and read its instructions.")
|
||||
.await?;
|
||||
let client = resources
|
||||
.0
|
||||
.lock()
|
||||
.expect("session resources lock")
|
||||
.clone()
|
||||
.expect("thread MCP resource client");
|
||||
assert!(
|
||||
client.server_cache_key(CODEX_APPS_MCP_SERVER_NAME)
|
||||
== *provider.resource_key.lock().expect("resource key lock"),
|
||||
"turn-start reprojection must not invalidate resource caches: {turn}"
|
||||
);
|
||||
if let Some((client, scope, connection)) = previous_connection_scope {
|
||||
assert!(client.server_cache_key(CODEX_APPS_MCP_SERVER_NAME) != connection);
|
||||
assert!(
|
||||
client.auth_cache_key_for_server(CODEX_APPS_MCP_SERVER_NAME) == scope,
|
||||
"same-auth reconnect must preserve the cloud cache scope"
|
||||
);
|
||||
}
|
||||
let requests = response.requests();
|
||||
assert_eq!(requests.len(), 2, "turn {turn}");
|
||||
assert_eq!(
|
||||
provider.lists.load(Ordering::SeqCst),
|
||||
previous_lists + expected_lists,
|
||||
"turn {turn}"
|
||||
);
|
||||
assert_eq!(
|
||||
provider.reads.load(Ordering::SeqCst),
|
||||
previous_reads + expected_reads,
|
||||
"turn {turn}"
|
||||
);
|
||||
let listed: Value = serde_json::from_str(
|
||||
&requests[1]
|
||||
.function_call_output_text(&list_id)
|
||||
.expect("skills.list result"),
|
||||
)?;
|
||||
let read = requests[1]
|
||||
.function_call_output_text(&read_id)
|
||||
.expect("skills.read result");
|
||||
if let Some((plugin, revision)) = expected_skill {
|
||||
last_available_skill = (plugin, revision);
|
||||
let description = format!("Cloud {plugin} revision {revision}");
|
||||
assert_eq!(
|
||||
listed["skills"].as_array().expect("listed skills").len(),
|
||||
1,
|
||||
"turn {turn}"
|
||||
);
|
||||
assert_eq!(listed["skills"][0]["package"], package, "turn {turn}");
|
||||
assert_eq!(
|
||||
listed["skills"][0]["description"], description,
|
||||
"turn {turn}"
|
||||
);
|
||||
assert!(
|
||||
requests[0]
|
||||
.message_input_texts("developer")
|
||||
.join("\n")
|
||||
.contains(&description),
|
||||
"turn {turn}"
|
||||
);
|
||||
let read: Value = serde_json::from_str(&read)?;
|
||||
assert_eq!(
|
||||
read["contents"],
|
||||
format!("{plugin} instructions {revision}"),
|
||||
"turn {turn}"
|
||||
);
|
||||
} else {
|
||||
assert_eq!(listed["skills"], json!([]), "turn {turn}");
|
||||
assert!(
|
||||
read.contains("skill package is not available"),
|
||||
"turn {turn}: {read}"
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
945
codex-rs/core/tests/suite/skills_extension/cloud_skill_tests.rs
Normal file
945
codex-rs/core/tests/suite/skills_extension/cloud_skill_tests.rs
Normal file
@@ -0,0 +1,945 @@
|
||||
//! Core cloud-skill behavior exercised without the concrete MCP-backed provider.
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
#[path = "yielded_skill_tests.rs"]
|
||||
mod yielded_skill_tests;
|
||||
|
||||
struct FakeCloudSkillProvider {
|
||||
catalog: SkillCatalog,
|
||||
resources: std::collections::HashMap<String, String>,
|
||||
reads: Mutex<Vec<String>>,
|
||||
read_barrier: Option<tokio::sync::Barrier>,
|
||||
}
|
||||
|
||||
impl SkillProvider for FakeCloudSkillProvider {
|
||||
fn list<'a>(&'a self, _query: SkillListQuery<'a>) -> SkillProviderFuture<'a, SkillCatalog> {
|
||||
Box::pin(async { Ok(self.catalog.clone()) })
|
||||
}
|
||||
|
||||
fn read<'a>(
|
||||
&'a self,
|
||||
request: SkillReadRequest<'a>,
|
||||
) -> SkillProviderFuture<'a, SkillReadResult> {
|
||||
Box::pin(async move {
|
||||
assert_eq!(
|
||||
request.authority,
|
||||
SkillAuthority::new(SkillSourceKind::Cloud, CODEX_APPS_MCP_SERVER_NAME)
|
||||
);
|
||||
assert!(
|
||||
self.catalog
|
||||
.entries
|
||||
.iter()
|
||||
.any(|entry| entry.id == request.package)
|
||||
);
|
||||
self.reads
|
||||
.lock()
|
||||
.await
|
||||
.push(request.resource.as_str().to_string());
|
||||
let contents = self
|
||||
.resources
|
||||
.get(request.resource.as_str())
|
||||
.cloned()
|
||||
.ok_or_else(|| SkillProviderError::new("unknown fake skill resource"))?;
|
||||
if let Some(barrier) = &self.read_barrier {
|
||||
tokio::time::timeout(Duration::from_secs(/*secs*/ 10), barrier.wait())
|
||||
.await
|
||||
.map_err(|_| SkillProviderError::new("skill reads did not overlap"))?;
|
||||
}
|
||||
Ok(SkillReadResult {
|
||||
resource: request.resource,
|
||||
contents,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn search(&self, _request: SkillSearchRequest) -> SkillProviderFuture<'_, SkillSearchResult> {
|
||||
Box::pin(async { Ok(SkillSearchResult::default()) })
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn explicit_only_cloud_skill_is_hidden_but_can_be_invoked() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
const SKILL_PACKAGE: &str = "skill://demo/explicit-only";
|
||||
const MAIN_RESOURCE: &str = "skill://demo/explicit-only/SKILL.md";
|
||||
const REFERENCED_RESOURCE: &str = "skill://demo/explicit-only/references/guide.md";
|
||||
const READ_CALL_ID: &str = "read-explicit-only-resource";
|
||||
const LIST_CALL_ID: &str = "list-model-visible-skills";
|
||||
const CODE_MODE_LIST_CALL_ID: &str = "list-skills-through-code-mode";
|
||||
const CONTINUATION_CALL_ID: &str = "read-explicit-only-resource-continuation";
|
||||
const MAIN_READ_CALL_ID: &str = "read-explicit-only-main";
|
||||
const REPEATED_MAIN_READ_CALL_ID: &str = "read-explicit-only-main-again";
|
||||
const INVALID_CURSOR_CALL_ID: &str = "read-explicit-only-invalid-cursor";
|
||||
const MISSING_PACKAGE_CALL_ID: &str = "read-missing-package";
|
||||
const CODE_MODE_CALL_ID: &str = "code-mode-skill-read";
|
||||
|
||||
// Fill the shared 300-byte page through the emoji; ignoring escaping would fit everything.
|
||||
let read_prefix = "a".repeat(184);
|
||||
let referenced_contents = format!("{read_prefix}😀\"\\\nabcdefghijklm");
|
||||
let server = responses::start_mock_server().await;
|
||||
let response = responses::mount_sse_sequence(
|
||||
&server,
|
||||
vec![
|
||||
sse(vec![
|
||||
ev_response_created("resp-1"),
|
||||
responses::ev_function_call_with_namespace(
|
||||
READ_CALL_ID,
|
||||
"skills",
|
||||
"read",
|
||||
&json!({
|
||||
"package": SKILL_PACKAGE,
|
||||
"authority": {
|
||||
"kind": "cloud",
|
||||
},
|
||||
"resource": REFERENCED_RESOURCE,
|
||||
})
|
||||
.to_string(),
|
||||
),
|
||||
responses::ev_function_call_with_namespace(
|
||||
LIST_CALL_ID,
|
||||
"skills",
|
||||
"list",
|
||||
&json!({ "authority": { "kind": "cloud" } }).to_string(),
|
||||
),
|
||||
responses::ev_custom_tool_call(
|
||||
CODE_MODE_LIST_CALL_ID,
|
||||
"exec",
|
||||
r#"const result = await tools.skills__list({ authority: { kind: "cloud" } });
|
||||
text({ names: result.skills.map(skill => skill.name), warnings: result.warnings, next_cursor: result.next_cursor });"#,
|
||||
),
|
||||
ev_completed("resp-1"),
|
||||
]),
|
||||
sse(vec![ev_response_created("resp-2"), ev_completed("resp-2")]),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
|
||||
let mut extensions = ExtensionRegistryBuilder::new();
|
||||
install_with_providers(
|
||||
&mut extensions,
|
||||
SkillProviders::new().with_cloud_provider(Arc::new(FakeCloudSkillProvider {
|
||||
catalog: SkillCatalog {
|
||||
is_partial: false,
|
||||
entries: [
|
||||
"alpha-visible",
|
||||
"bravo-visible-skill",
|
||||
"explicit-only",
|
||||
"visible",
|
||||
]
|
||||
.into_iter()
|
||||
.map(|name| {
|
||||
let package = format!("skill://demo/{name}");
|
||||
let entry = SkillCatalogEntry::new(
|
||||
SkillPackageId(package.clone()),
|
||||
SkillAuthority::new(SkillSourceKind::Cloud, CODEX_APPS_MCP_SERVER_NAME),
|
||||
format!("demo:{name}"),
|
||||
"",
|
||||
SkillResourceId::new(format!("{package}/SKILL.md")),
|
||||
)
|
||||
.with_display_path(&package)
|
||||
.with_alias_root("skill://demo");
|
||||
if name == "explicit-only" {
|
||||
entry.hidden_from_prompt()
|
||||
} else {
|
||||
entry
|
||||
}
|
||||
})
|
||||
.collect(),
|
||||
warnings: Vec::new(),
|
||||
},
|
||||
reads: Mutex::default(),
|
||||
read_barrier: None,
|
||||
resources: std::collections::HashMap::from([
|
||||
(
|
||||
MAIN_RESOURCE.to_string(),
|
||||
format!("# Explicit-only instructions\nRead {REFERENCED_RESOURCE}."),
|
||||
),
|
||||
(REFERENCED_RESOURCE.to_string(), referenced_contents.clone()),
|
||||
]),
|
||||
})),
|
||||
|config: &Config| SkillsExtensionConfig {
|
||||
include_instructions: config.include_skill_instructions,
|
||||
catalog_deltas_enabled: config.features.enabled(Feature::SkillCatalogDeltas),
|
||||
omit_descriptions: false,
|
||||
max_context_tokens: config.skill_max_context_tokens,
|
||||
bundled_skills_enabled: false,
|
||||
cloud_skill_enabled: true,
|
||||
shadow_selection_enabled: false,
|
||||
},
|
||||
);
|
||||
let chatgpt_base_url = server.uri();
|
||||
let mut builder = test_codex()
|
||||
.with_auth(CodexAuth::create_dummy_chatgpt_auth_for_testing())
|
||||
.with_config(move |config| config.chatgpt_base_url = chatgpt_base_url)
|
||||
// Local executors disable cloud skill discovery.
|
||||
.with_exec_server_url("none")
|
||||
.with_extensions(Arc::new(extensions.build()))
|
||||
.with_model_info_override("gpt-5.5", |model_info| {
|
||||
model_info.truncation_policy = TruncationPolicyConfig::bytes(/*limit*/ 250);
|
||||
})
|
||||
.with_config(|config| {
|
||||
config.include_skill_instructions = true;
|
||||
config.cloud_skill_enabled = true;
|
||||
config
|
||||
.features
|
||||
.enable(Feature::CodeMode)
|
||||
.expect("code mode should be configurable in tests");
|
||||
config
|
||||
.features
|
||||
.enable(Feature::CodeModeHost)
|
||||
.expect("code mode host should be configurable in tests");
|
||||
})
|
||||
.with_code_mode_host_program(codex_utils_cargo_bin::cargo_bin("codex-code-mode-host")?);
|
||||
let test = builder.build_with_auto_env(&server).await?;
|
||||
|
||||
test.submit_turn("Use $demo:explicit-only.").await?;
|
||||
|
||||
let requests = response.requests();
|
||||
assert_eq!(requests.len(), 2);
|
||||
let request = &requests[0];
|
||||
let developer_messages = request.message_input_texts("developer");
|
||||
for name in ["visible", "alpha-visible", "bravo-visible-skill"] {
|
||||
let catalog_entry = format!("- demo:{name}:");
|
||||
assert!(
|
||||
developer_messages
|
||||
.iter()
|
||||
.any(|message| message.contains(&catalog_entry)),
|
||||
"model-visible skills should include `{name}`: {developer_messages:?}"
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
developer_messages
|
||||
.iter()
|
||||
.all(|message| !message.contains("- demo:explicit-only:")),
|
||||
"model-visible skills should omit the explicit-only skill: {developer_messages:?}"
|
||||
);
|
||||
let user_messages = request.message_input_texts("user");
|
||||
let skill_instructions = user_messages
|
||||
.iter()
|
||||
.find(|message| {
|
||||
message.contains("<name>demo:explicit-only</name>")
|
||||
&& message.contains("# Explicit-only instructions")
|
||||
&& message.contains(REFERENCED_RESOURCE)
|
||||
})
|
||||
.expect("explicit invocation should inject the hidden skill instructions and reference");
|
||||
let resource_access = skill_instructions
|
||||
.split_once("<resource_access>")
|
||||
.and_then(|(_, remainder)| remainder.split_once("</resource_access>"))
|
||||
.map(|(metadata, _)| metadata)
|
||||
.expect("hidden cloud skills should include resource-access metadata");
|
||||
assert_eq!(
|
||||
serde_json::from_str::<Value>(resource_access)?,
|
||||
json!({
|
||||
"authority": { "kind": "cloud" },
|
||||
"package": SKILL_PACKAGE,
|
||||
"main_resource": MAIN_RESOURCE,
|
||||
})
|
||||
);
|
||||
let first_output = requests[1]
|
||||
.function_call_output_text(READ_CALL_ID)
|
||||
.expect("skills.read should return the referenced resource");
|
||||
assert!(first_output.len() <= 300);
|
||||
let first_page = serde_json::from_str::<Value>(&first_output)?;
|
||||
let cursor = first_page["next_cursor"]
|
||||
.as_str()
|
||||
.ok_or_else(|| anyhow::anyhow!("skills.read should return a continuation cursor"))?
|
||||
.to_string();
|
||||
assert_eq!(
|
||||
first_page,
|
||||
json!({
|
||||
"resource": REFERENCED_RESOURCE,
|
||||
"contents": format!("{read_prefix}😀"),
|
||||
"next_cursor": cursor,
|
||||
})
|
||||
);
|
||||
let mut list_output = requests[1]
|
||||
.function_call_output_text(LIST_CALL_ID)
|
||||
.expect("skills.list should return the model-visible catalog");
|
||||
let code_mode_output = requests[1].custom_tool_call_output(CODE_MODE_LIST_CALL_ID);
|
||||
let code_mode_text = code_mode_output["output"]
|
||||
.as_array()
|
||||
.and_then(|items| items.last())
|
||||
.and_then(|item| item["text"].as_str())
|
||||
.ok_or_else(|| {
|
||||
anyhow::anyhow!("Code Mode should return its skills.list result: {code_mode_output}")
|
||||
})?;
|
||||
assert_eq!(
|
||||
serde_json::from_str::<Value>(code_mode_text)?,
|
||||
json!({
|
||||
"names": ["demo:alpha-visible", "demo:bravo-visible-skill", "demo:visible"],
|
||||
"warnings": [],
|
||||
"next_cursor": null,
|
||||
})
|
||||
);
|
||||
let events = wait_for_analytics_events(&server, "skill_invocation", /*expected_count*/ 1).await;
|
||||
assert_eq!(events.len(), 1);
|
||||
assert_eq!(events[0]["skill_name"], "demo:explicit-only");
|
||||
assert_eq!(events[0]["event_params"]["invoke_type"], "explicit");
|
||||
|
||||
let response = responses::mount_sse_sequence(
|
||||
&server,
|
||||
vec![
|
||||
sse(vec![
|
||||
ev_response_created("resp-3"),
|
||||
responses::ev_function_call_with_namespace(
|
||||
CONTINUATION_CALL_ID,
|
||||
"skills",
|
||||
"read",
|
||||
&json!({
|
||||
"package": SKILL_PACKAGE,
|
||||
"resource": REFERENCED_RESOURCE,
|
||||
"cursor": cursor,
|
||||
})
|
||||
.to_string(),
|
||||
),
|
||||
responses::ev_function_call_with_namespace(
|
||||
MAIN_READ_CALL_ID,
|
||||
"skills",
|
||||
"read",
|
||||
&json!({ "package": SKILL_PACKAGE }).to_string(),
|
||||
),
|
||||
responses::ev_function_call_with_namespace(
|
||||
REPEATED_MAIN_READ_CALL_ID,
|
||||
"skills",
|
||||
"read",
|
||||
&json!({ "package": SKILL_PACKAGE, "resource": MAIN_RESOURCE }).to_string(),
|
||||
),
|
||||
responses::ev_function_call_with_namespace(
|
||||
INVALID_CURSOR_CALL_ID,
|
||||
"skills",
|
||||
"read",
|
||||
&json!({ "package": SKILL_PACKAGE, "cursor": "invalid" }).to_string(),
|
||||
),
|
||||
responses::ev_function_call_with_namespace(
|
||||
MISSING_PACKAGE_CALL_ID,
|
||||
"skills",
|
||||
"read",
|
||||
&json!({ "package": "skill://demo/missing" }).to_string(),
|
||||
),
|
||||
ev_completed("resp-3"),
|
||||
]),
|
||||
sse(vec![ev_response_created("resp-4"), ev_completed("resp-4")]),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
|
||||
test.submit_turn("Continue without explicitly selecting a skill.")
|
||||
.await?;
|
||||
let requests = response.requests();
|
||||
assert_eq!(requests.len(), 2);
|
||||
let continuation_output = requests[1]
|
||||
.function_call_output_text(CONTINUATION_CALL_ID)
|
||||
.expect("skills.read should return the next referenced-resource page");
|
||||
assert!(continuation_output.len() <= 300);
|
||||
let continuation_page = serde_json::from_str::<Value>(&continuation_output)?;
|
||||
assert_eq!(
|
||||
continuation_page,
|
||||
json!({
|
||||
"resource": REFERENCED_RESOURCE,
|
||||
"contents": "\"\\\nabcdefghijklm",
|
||||
"next_cursor": null,
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
format!(
|
||||
"{}{}",
|
||||
first_page["contents"].as_str().unwrap_or_default(),
|
||||
continuation_page["contents"].as_str().unwrap_or_default()
|
||||
),
|
||||
referenced_contents
|
||||
);
|
||||
for call_id in [MAIN_READ_CALL_ID, REPEATED_MAIN_READ_CALL_ID] {
|
||||
let output = requests[1]
|
||||
.function_call_output_text(call_id)
|
||||
.expect("skills.read should return the main resource");
|
||||
assert_eq!(
|
||||
serde_json::from_str::<Value>(&output)?["resource"],
|
||||
MAIN_RESOURCE
|
||||
);
|
||||
}
|
||||
for call_id in [INVALID_CURSOR_CALL_ID, MISSING_PACKAGE_CALL_ID] {
|
||||
assert!(
|
||||
requests[1].function_call_output_text(call_id).is_some(),
|
||||
"failed skills.read should return a tool error for {call_id}"
|
||||
);
|
||||
}
|
||||
|
||||
let events = wait_for_analytics_events(&server, "skill_invocation", /*expected_count*/ 2).await;
|
||||
assert_eq!(events.len(), 2, "repeated main reads must be deduplicated");
|
||||
assert_eq!(events[1]["skill_name"], "demo:explicit-only");
|
||||
assert_eq!(
|
||||
events[1]["skill_id"],
|
||||
format!("{:x}", sha1::Sha1::digest(MAIN_RESOURCE.as_bytes()))
|
||||
);
|
||||
assert_eq!(events[1]["event_params"]["invoke_type"], "implicit");
|
||||
|
||||
for (name, has_more) in [
|
||||
("alpha-visible", true),
|
||||
("bravo-visible-skill", true),
|
||||
("visible", false),
|
||||
] {
|
||||
assert!(list_output.len() <= 300);
|
||||
let list_response = serde_json::from_str::<Value>(&list_output)?;
|
||||
let next_cursor = list_response["next_cursor"].as_str();
|
||||
assert_eq!(next_cursor.is_some(), has_more);
|
||||
assert_eq!(
|
||||
list_response,
|
||||
json!({
|
||||
"skills": [{
|
||||
"authority": {"kind": "cloud"},
|
||||
"package": format!("skill://demo/{name}"),
|
||||
"name": format!("demo:{name}"),
|
||||
"description": "",
|
||||
"main_resource": format!("skill://demo/{name}/SKILL.md"),
|
||||
}],
|
||||
"warnings": [],
|
||||
"next_cursor": next_cursor,
|
||||
})
|
||||
);
|
||||
if let Some(cursor) = next_cursor {
|
||||
let call_id = format!("list-after-{name}");
|
||||
let page = responses::mount_sse_sequence(
|
||||
&server,
|
||||
vec![
|
||||
sse(vec![
|
||||
ev_response_created(&call_id),
|
||||
responses::ev_function_call_with_namespace(
|
||||
&call_id,
|
||||
"skills",
|
||||
"list",
|
||||
&json!({
|
||||
"authority": { "kind": "cloud" },
|
||||
"cursor": cursor,
|
||||
})
|
||||
.to_string(),
|
||||
),
|
||||
ev_completed(&call_id),
|
||||
]),
|
||||
sse(vec![ev_response_created("listed"), ev_completed("listed")]),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
test.submit_turn("Continue listing skills.").await?;
|
||||
list_output = page.requests()[1]
|
||||
.function_call_output_text(&call_id)
|
||||
.expect("skills.list should return the next page");
|
||||
}
|
||||
}
|
||||
|
||||
let response = responses::mount_sse_sequence(
|
||||
&server,
|
||||
vec![
|
||||
sse(vec![
|
||||
ev_response_created("resp-5"),
|
||||
responses::ev_custom_tool_call(
|
||||
CODE_MODE_CALL_ID,
|
||||
"exec",
|
||||
&format!(
|
||||
"const result = await tools.skills__read({{package: {SKILL_PACKAGE:?}, resource: {REFERENCED_RESOURCE:?}}}); text(JSON.stringify({{contents: result.contents, next_cursor: result.next_cursor}}));"
|
||||
),
|
||||
),
|
||||
ev_completed("resp-5"),
|
||||
]),
|
||||
sse(vec![ev_response_created("resp-6"), ev_completed("resp-6")]),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
test.submit_turn("Read the complete skill resource using code mode.")
|
||||
.await?;
|
||||
let requests = response.requests();
|
||||
assert_eq!(requests.len(), 2);
|
||||
let output = requests[1].custom_tool_call_output(CODE_MODE_CALL_ID);
|
||||
let nested_result = output["output"]
|
||||
.as_array()
|
||||
.and_then(|items| items.last())
|
||||
.and_then(|item| item["text"].as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("code mode should return the nested skill result"))?;
|
||||
assert_eq!(
|
||||
serde_json::from_str::<Value>(nested_result)?,
|
||||
json!({"contents": referenced_contents, "next_cursor": null})
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn production_turn_aliases_discovered_singleton_cloud_locator() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
const SKILL_ROOT: &str = "skill://plugin_connector_1p_2330815c823c8191941e5dc465bb899f";
|
||||
const SKILL_BODY: &str = "CLOUD_SKILL_REMAINS_AVAILABLE_WITHOUT_HOST_DISCOVERY";
|
||||
|
||||
let server = responses::start_mock_server().await;
|
||||
let response = mount_sse_once(
|
||||
&server,
|
||||
sse(vec![ev_response_created("resp-1"), ev_completed("resp-1")]),
|
||||
)
|
||||
.await;
|
||||
|
||||
let mut extensions = ExtensionRegistryBuilder::new();
|
||||
install_with_providers(
|
||||
&mut extensions,
|
||||
SkillProviders::new().with_cloud_provider(Arc::new(FakeCloudSkillProvider {
|
||||
catalog: SkillCatalog {
|
||||
is_partial: false,
|
||||
entries: vec![
|
||||
SkillCatalogEntry::new(
|
||||
SkillPackageId(format!("{SKILL_ROOT}/search")),
|
||||
SkillAuthority::new(SkillSourceKind::Cloud, CODEX_APPS_MCP_SERVER_NAME),
|
||||
"demo:search",
|
||||
"Search company knowledge.",
|
||||
SkillResourceId::new(format!("{SKILL_ROOT}/search/SKILL.md")),
|
||||
)
|
||||
.with_display_path(format!("{SKILL_ROOT}/search"))
|
||||
.with_alias_root(SKILL_ROOT),
|
||||
],
|
||||
warnings: Vec::new(),
|
||||
},
|
||||
resources: std::collections::HashMap::from([(
|
||||
format!("{SKILL_ROOT}/search/SKILL.md"),
|
||||
SKILL_BODY.to_string(),
|
||||
)]),
|
||||
reads: Mutex::default(),
|
||||
read_barrier: None,
|
||||
})),
|
||||
|config: &Config| SkillsExtensionConfig {
|
||||
include_instructions: config.include_skill_instructions,
|
||||
catalog_deltas_enabled: config.features.enabled(Feature::SkillCatalogDeltas),
|
||||
omit_descriptions: false,
|
||||
max_context_tokens: config.skill_max_context_tokens,
|
||||
bundled_skills_enabled: false,
|
||||
cloud_skill_enabled: true,
|
||||
shadow_selection_enabled: false,
|
||||
},
|
||||
);
|
||||
let chatgpt_base_url = server.uri();
|
||||
let mut builder = test_codex()
|
||||
.with_auth(CodexAuth::create_dummy_chatgpt_auth_for_testing())
|
||||
.with_config(move |config| config.chatgpt_base_url = chatgpt_base_url)
|
||||
.with_exec_server_url("none")
|
||||
.with_extensions(Arc::new(extensions.build()))
|
||||
.with_model_info_override("gpt-5.5", |model_info| {
|
||||
model_info.context_window = Some(2_000);
|
||||
model_info.max_context_window = None;
|
||||
})
|
||||
.with_config(|config| {
|
||||
config.include_skill_instructions = true;
|
||||
config.cloud_skill_enabled = true;
|
||||
config
|
||||
.features
|
||||
.enable(Feature::SkipHostSkillDiscovery)
|
||||
.expect("cloud skills must not depend on host discovery");
|
||||
});
|
||||
let test = builder.build_with_auto_env(&server).await?;
|
||||
|
||||
test.submit_turn("Use $demo:search.").await?;
|
||||
|
||||
let request = response.single_request();
|
||||
let developer_text = request.message_input_texts("developer").join("\n");
|
||||
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 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),
|
||||
"cloud instruction reads must remain available without host discovery: {user_text}"
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn cloud_skill_reads_run_in_parallel() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
const PACKAGE: &str = "skill://demo/parallel";
|
||||
const READS: [(&str, &str, &str); 2] = [
|
||||
(
|
||||
"read-main",
|
||||
"skill://demo/parallel/SKILL.md",
|
||||
"Main instructions.",
|
||||
),
|
||||
(
|
||||
"read-reference",
|
||||
"skill://demo/parallel/references/guide.md",
|
||||
"Reference instructions.",
|
||||
),
|
||||
];
|
||||
let server = responses::start_mock_server().await;
|
||||
let mut extensions = ExtensionRegistryBuilder::new();
|
||||
install_with_providers(
|
||||
&mut extensions,
|
||||
SkillProviders::new().with_cloud_provider(Arc::new(FakeCloudSkillProvider {
|
||||
catalog: SkillCatalog {
|
||||
is_partial: false,
|
||||
entries: vec![SkillCatalogEntry::new(
|
||||
SkillPackageId(PACKAGE.to_string()),
|
||||
SkillAuthority::new(SkillSourceKind::Cloud, CODEX_APPS_MCP_SERVER_NAME),
|
||||
"demo:parallel",
|
||||
"Instructions and a reference.",
|
||||
SkillResourceId::new(READS[0].1),
|
||||
)],
|
||||
warnings: Vec::new(),
|
||||
},
|
||||
resources: READS
|
||||
.iter()
|
||||
.map(|(_, resource, contents)| (resource.to_string(), contents.to_string()))
|
||||
.collect(),
|
||||
reads: Mutex::default(),
|
||||
// An exclusive scheduler lock prevents the second read from reaching this barrier.
|
||||
read_barrier: Some(tokio::sync::Barrier::new(/*n*/ 2)),
|
||||
})),
|
||||
|config: &Config| SkillsExtensionConfig {
|
||||
include_instructions: config.include_skill_instructions,
|
||||
catalog_deltas_enabled: config.features.enabled(Feature::SkillCatalogDeltas),
|
||||
omit_descriptions: false,
|
||||
max_context_tokens: config.skill_max_context_tokens,
|
||||
bundled_skills_enabled: false,
|
||||
cloud_skill_enabled: true,
|
||||
shadow_selection_enabled: false,
|
||||
},
|
||||
);
|
||||
let chatgpt_base_url = server.uri();
|
||||
let mut builder = test_codex()
|
||||
.with_auth(CodexAuth::create_dummy_chatgpt_auth_for_testing())
|
||||
.with_exec_server_url("none")
|
||||
.with_extensions(Arc::new(extensions.build()))
|
||||
.with_config(move |config| {
|
||||
config.chatgpt_base_url = chatgpt_base_url;
|
||||
config.include_skill_instructions = true;
|
||||
config.cloud_skill_enabled = true;
|
||||
});
|
||||
let test = builder.build_with_auto_env(&server).await?;
|
||||
let mut calls = vec![ev_response_created("read-both")];
|
||||
calls.extend(READS.map(|(call_id, resource, _)| {
|
||||
responses::ev_function_call_with_namespace(
|
||||
call_id,
|
||||
"skills",
|
||||
"read",
|
||||
&json!({"package": PACKAGE, "resource": resource}).to_string(),
|
||||
)
|
||||
}));
|
||||
calls.push(ev_completed("read-both"));
|
||||
let response = responses::mount_sse_sequence(
|
||||
&server,
|
||||
vec![
|
||||
sse(calls),
|
||||
sse(vec![ev_response_created("done"), ev_completed("done")]),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
test.submit_turn("Read both resources.").await?;
|
||||
|
||||
let requests = response.requests();
|
||||
assert_eq!(requests.len(), 2);
|
||||
for (call_id, resource, contents) in READS {
|
||||
let output = requests[1]
|
||||
.function_call_output_text(call_id)
|
||||
.expect("each concurrent skill read should return its resource");
|
||||
assert_eq!(
|
||||
serde_json::from_str::<Value>(&output)?,
|
||||
json!({"resource": resource, "contents": contents, "next_cursor": null})
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn cloud_skill_can_read_referenced_resource_without_an_executor() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
const SKILL_NAME: &str = "demo-plugin:deploy";
|
||||
|
||||
const SKILL_DESCRIPTION: &str = "Deploy through the <hosted> orchestrator.";
|
||||
|
||||
const SKILL_RESOURCE_URI: &str = "skill://plugin_demo/deploy";
|
||||
|
||||
const SKILL_MAIN_PROMPT_URI: &str = "skill://plugin_demo/deploy/SKILL.md";
|
||||
|
||||
const SKILL_REFERENCE_URI: &str = "skill://plugin_demo/deploy/references/deploy.md";
|
||||
|
||||
const SKILL_MARKER: &str = "ORCHESTRATOR_SKILL_BODY_MARKER";
|
||||
|
||||
const SKILL_CONTENTS: &str = concat!(
|
||||
"---\n",
|
||||
"name: deploy\n",
|
||||
"description: Deploy through the orchestrator.\n",
|
||||
"---\n\n",
|
||||
"# Deploy\n\n",
|
||||
"ORCHESTRATOR_SKILL_BODY_MARKER\n\n",
|
||||
"Read the [deployment reference](skill://plugin_demo/deploy/references/deploy.md).\n",
|
||||
);
|
||||
|
||||
const SKILL_REFERENCE_CONTENTS: &str =
|
||||
"# Deploy reference\n\nUse the orchestrator deployment API.\n";
|
||||
|
||||
const SKILLS_LIST_CALL_ID: &str = "skills-list";
|
||||
|
||||
const SKILLS_READ_MAIN_CALL_ID: &str = "skills-read-main";
|
||||
|
||||
const SKILLS_READ_CALL_ID: &str = "skills-read";
|
||||
|
||||
const SKILLS_READ_AGAIN_CALL_ID: &str = "skills-read-again";
|
||||
|
||||
let responses_server = responses::start_mock_server().await;
|
||||
let provider = Arc::new(FakeCloudSkillProvider {
|
||||
catalog: SkillCatalog {
|
||||
is_partial: false,
|
||||
entries: vec![
|
||||
SkillCatalogEntry::new(
|
||||
SkillPackageId(SKILL_RESOURCE_URI.to_string()),
|
||||
SkillAuthority::new(SkillSourceKind::Cloud, CODEX_APPS_MCP_SERVER_NAME),
|
||||
SKILL_NAME,
|
||||
SKILL_DESCRIPTION,
|
||||
SkillResourceId::new(SKILL_MAIN_PROMPT_URI),
|
||||
)
|
||||
.with_display_path(SKILL_RESOURCE_URI)
|
||||
.with_alias_root("skill://plugin_demo"),
|
||||
],
|
||||
warnings: vec!["Cloud discovery returned a partial catalog.".to_string()],
|
||||
},
|
||||
resources: std::collections::HashMap::from([
|
||||
(
|
||||
SKILL_MAIN_PROMPT_URI.to_string(),
|
||||
SKILL_CONTENTS.to_string(),
|
||||
),
|
||||
(
|
||||
SKILL_REFERENCE_URI.to_string(),
|
||||
SKILL_REFERENCE_CONTENTS.to_string(),
|
||||
),
|
||||
]),
|
||||
reads: Mutex::default(),
|
||||
read_barrier: None,
|
||||
});
|
||||
let mut extensions = ExtensionRegistryBuilder::new();
|
||||
install_with_providers(
|
||||
&mut extensions,
|
||||
SkillProviders::new().with_cloud_provider(provider.clone()),
|
||||
|config: &Config| SkillsExtensionConfig {
|
||||
include_instructions: config.include_skill_instructions,
|
||||
catalog_deltas_enabled: config.features.enabled(Feature::SkillCatalogDeltas),
|
||||
omit_descriptions: false,
|
||||
max_context_tokens: config.skill_max_context_tokens,
|
||||
bundled_skills_enabled: false,
|
||||
cloud_skill_enabled: true,
|
||||
shadow_selection_enabled: false,
|
||||
},
|
||||
);
|
||||
let chatgpt_base_url = responses_server.uri();
|
||||
let mut builder = test_codex()
|
||||
.with_auth(CodexAuth::create_dummy_chatgpt_auth_for_testing())
|
||||
.with_config(move |config| config.chatgpt_base_url = chatgpt_base_url)
|
||||
.with_exec_server_url("none")
|
||||
.with_extensions(Arc::new(extensions.build()))
|
||||
.with_config(|config| {
|
||||
config.include_skill_instructions = true;
|
||||
config.cloud_skill_enabled = true;
|
||||
});
|
||||
let test = builder.build_with_auto_env(&responses_server).await?;
|
||||
let response_mock = responses::mount_sse_sequence(
|
||||
&responses_server,
|
||||
vec![
|
||||
responses::sse(vec![
|
||||
responses::ev_response_created("resp-skills-read-main"),
|
||||
responses::ev_function_call_with_namespace(
|
||||
SKILLS_READ_MAIN_CALL_ID,
|
||||
"skills",
|
||||
"read",
|
||||
&json!({
|
||||
"package": SKILL_RESOURCE_URI,
|
||||
})
|
||||
.to_string(),
|
||||
),
|
||||
responses::ev_completed("resp-skills-read-main"),
|
||||
]),
|
||||
responses::sse(vec![
|
||||
responses::ev_response_created("resp-skills-list"),
|
||||
responses::ev_function_call_with_namespace(
|
||||
SKILLS_LIST_CALL_ID,
|
||||
"skills",
|
||||
"list",
|
||||
&json!({
|
||||
"authority": {
|
||||
"kind": "cloud",
|
||||
},
|
||||
})
|
||||
.to_string(),
|
||||
),
|
||||
responses::ev_completed("resp-skills-list"),
|
||||
]),
|
||||
responses::sse(vec![
|
||||
responses::ev_response_created("resp-skills-read"),
|
||||
responses::ev_function_call_with_namespace(
|
||||
SKILLS_READ_CALL_ID,
|
||||
"skills",
|
||||
"read",
|
||||
&json!({
|
||||
"package": SKILL_RESOURCE_URI,
|
||||
"authority": {
|
||||
"kind": "cloud",
|
||||
},
|
||||
"resource": SKILL_REFERENCE_URI,
|
||||
})
|
||||
.to_string(),
|
||||
),
|
||||
responses::ev_completed("resp-skills-read"),
|
||||
]),
|
||||
responses::sse(vec![
|
||||
responses::ev_response_created("resp-skills-read-again"),
|
||||
responses::ev_function_call_with_namespace(
|
||||
SKILLS_READ_AGAIN_CALL_ID,
|
||||
"skills",
|
||||
"read",
|
||||
&json!({
|
||||
"package": SKILL_RESOURCE_URI,
|
||||
"resource": SKILL_REFERENCE_URI,
|
||||
})
|
||||
.to_string(),
|
||||
),
|
||||
responses::ev_completed("resp-skills-read-again"),
|
||||
]),
|
||||
responses::sse(vec![
|
||||
responses::ev_response_created("resp-orchestrator-skill"),
|
||||
responses::ev_assistant_message("msg-orchestrator-skill", "Done"),
|
||||
responses::ev_completed("resp-orchestrator-skill"),
|
||||
]),
|
||||
responses::sse(vec![
|
||||
responses::ev_response_created("resp-orchestrator-skill-next-turn"),
|
||||
responses::ev_assistant_message("msg-orchestrator-skill-next-turn", "Done"),
|
||||
responses::ev_completed("resp-orchestrator-skill-next-turn"),
|
||||
]),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
test.submit_turn("Use the deployment capability.").await?;
|
||||
let requests = response_mock.requests();
|
||||
assert_eq!(requests.len(), 5);
|
||||
let first_request = &requests[0];
|
||||
assert!(first_request.tool_by_name("skills", "list").is_some());
|
||||
let read_tool = first_request
|
||||
.tool_by_name("skills", "read")
|
||||
.ok_or_else(|| anyhow::anyhow!("skills.read should be available"))?;
|
||||
assert_eq!(read_tool["parameters"]["required"], json!(["package"]));
|
||||
assert!(
|
||||
read_tool["parameters"]["properties"]
|
||||
.get("authority")
|
||||
.is_none()
|
||||
);
|
||||
assert!(first_request.tool_by_name("skills", "search").is_none());
|
||||
|
||||
let developer_messages = first_request.message_input_texts("developer");
|
||||
let catalog_line = format!("- {SKILL_NAME}: {SKILL_DESCRIPTION} (cloud package: c0/deploy)");
|
||||
assert!(
|
||||
developer_messages
|
||||
.iter()
|
||||
.any(|text| text.contains("- `c0` = `skill://plugin_demo`"))
|
||||
);
|
||||
assert_eq!(
|
||||
1,
|
||||
developer_messages
|
||||
.iter()
|
||||
.filter(|text| text.contains(&catalog_line))
|
||||
.count()
|
||||
);
|
||||
assert!(
|
||||
developer_messages
|
||||
.iter()
|
||||
.all(|text| !text.contains("ignored-plugin:ignored"))
|
||||
);
|
||||
assert!(
|
||||
developer_messages
|
||||
.iter()
|
||||
.any(|text| text.contains("do not treat `skill://` identifiers as filesystem paths"))
|
||||
);
|
||||
assert!(
|
||||
first_request
|
||||
.message_input_texts("user")
|
||||
.into_iter()
|
||||
.all(|text| !text.starts_with("<skill>"))
|
||||
);
|
||||
|
||||
let main_read_output = requests[1]
|
||||
.function_call_output_text(SKILLS_READ_MAIN_CALL_ID)
|
||||
.ok_or_else(|| anyhow::anyhow!("skills.read output should be sent to the model"))?;
|
||||
assert_eq!(
|
||||
serde_json::from_str::<serde_json::Value>(&main_read_output)?,
|
||||
json!({
|
||||
"resource": SKILL_MAIN_PROMPT_URI,
|
||||
"contents": SKILL_CONTENTS,
|
||||
"next_cursor": null,
|
||||
})
|
||||
);
|
||||
|
||||
let list_output = requests[2]
|
||||
.function_call_output_text(SKILLS_LIST_CALL_ID)
|
||||
.ok_or_else(|| anyhow::anyhow!("skills.list output should be sent to the model"))?;
|
||||
assert_eq!(
|
||||
serde_json::from_str::<serde_json::Value>(&list_output)?,
|
||||
json!({
|
||||
"skills": [{
|
||||
"authority": {
|
||||
"kind": "cloud",
|
||||
},
|
||||
"package": SKILL_RESOURCE_URI,
|
||||
"name": SKILL_NAME,
|
||||
"description": SKILL_DESCRIPTION,
|
||||
"main_resource": SKILL_MAIN_PROMPT_URI,
|
||||
}],
|
||||
"warnings": ["Cloud discovery returned a partial catalog."],
|
||||
"next_cursor": null,
|
||||
})
|
||||
);
|
||||
|
||||
let read_output = requests[3]
|
||||
.function_call_output_text(SKILLS_READ_CALL_ID)
|
||||
.ok_or_else(|| anyhow::anyhow!("skills.read output should be sent to the model"))?;
|
||||
assert_eq!(
|
||||
serde_json::from_str::<serde_json::Value>(&read_output)?,
|
||||
json!({
|
||||
"resource": SKILL_REFERENCE_URI,
|
||||
"contents": SKILL_REFERENCE_CONTENTS,
|
||||
"next_cursor": null,
|
||||
})
|
||||
);
|
||||
let repeated_read_output = requests[4]
|
||||
.function_call_output_text(SKILLS_READ_AGAIN_CALL_ID)
|
||||
.ok_or_else(|| {
|
||||
anyhow::anyhow!("repeated skills.read output should be sent to the model")
|
||||
})?;
|
||||
assert_eq!(read_output, repeated_read_output);
|
||||
assert_eq!(
|
||||
*provider.reads.lock().await,
|
||||
vec![SKILL_MAIN_PROMPT_URI, SKILL_REFERENCE_URI]
|
||||
);
|
||||
|
||||
test.submit_turn(&format!("Use ${SKILL_NAME} on the next turn"))
|
||||
.await?;
|
||||
let requests = response_mock.requests();
|
||||
assert_eq!(requests.len(), 6);
|
||||
let skill_fragments = requests[5]
|
||||
.message_input_texts("user")
|
||||
.into_iter()
|
||||
.filter(|text| text.starts_with("<skill>"))
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(1, skill_fragments.len());
|
||||
assert!(skill_fragments[0].contains(&format!("<name>{SKILL_NAME}</name>")));
|
||||
assert!(skill_fragments[0].contains(SKILL_MARKER));
|
||||
assert!(skill_fragments[0].contains(SKILL_REFERENCE_URI));
|
||||
// Partial discovery retries on the next turn without an MCP or auth invalidation.
|
||||
assert_eq!(
|
||||
*provider.reads.lock().await,
|
||||
vec![
|
||||
SKILL_MAIN_PROMPT_URI,
|
||||
SKILL_REFERENCE_URI,
|
||||
SKILL_MAIN_PROMPT_URI
|
||||
]
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
//! Skill analytics retain the originating turn when Code Mode resumes a yielded cell.
|
||||
|
||||
use super::*;
|
||||
use codex_core::TurnInputSubmission;
|
||||
use codex_protocol::openai_models::ToolMode;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn yielded_skill_read_keeps_originating_turn_metadata() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
const PACKAGE: &str = "skill://demo/yielded";
|
||||
const RESOURCE: &str = "skill://demo/yielded/SKILL.md";
|
||||
let server = responses::start_mock_server().await;
|
||||
let mut extensions = ExtensionRegistryBuilder::new();
|
||||
install_with_providers(
|
||||
&mut extensions,
|
||||
SkillProviders::new().with_cloud_provider(Arc::new(FakeCloudSkillProvider {
|
||||
catalog: SkillCatalog {
|
||||
is_partial: false,
|
||||
entries: vec![SkillCatalogEntry::new(
|
||||
SkillPackageId(PACKAGE.to_string()),
|
||||
SkillAuthority::new(SkillSourceKind::Cloud, CODEX_APPS_MCP_SERVER_NAME),
|
||||
"demo:yielded",
|
||||
"Instructions for the yielded skill.",
|
||||
SkillResourceId::new(RESOURCE),
|
||||
)],
|
||||
warnings: Vec::new(),
|
||||
},
|
||||
resources: std::collections::HashMap::from([(
|
||||
RESOURCE.to_string(),
|
||||
"Yielded skill instructions.".to_string(),
|
||||
)]),
|
||||
reads: Mutex::default(),
|
||||
read_barrier: None,
|
||||
})),
|
||||
|config: &Config| SkillsExtensionConfig {
|
||||
include_instructions: config.include_skill_instructions,
|
||||
catalog_deltas_enabled: config.features.enabled(Feature::SkillCatalogDeltas),
|
||||
omit_descriptions: false,
|
||||
max_context_tokens: config.skill_max_context_tokens,
|
||||
bundled_skills_enabled: false,
|
||||
cloud_skill_enabled: true,
|
||||
shadow_selection_enabled: false,
|
||||
},
|
||||
);
|
||||
let chatgpt_base_url = server.uri();
|
||||
let mut builder = test_codex()
|
||||
.with_auth(CodexAuth::create_dummy_chatgpt_auth_for_testing())
|
||||
.with_exec_server_url("none")
|
||||
.with_extensions(Arc::new(extensions.build()))
|
||||
.with_model_info_override("gpt-5.5", |model| {
|
||||
model.tool_mode = Some(ToolMode::CodeMode);
|
||||
model.experimental_supported_tools = vec!["test_sync_tool".to_string()];
|
||||
})
|
||||
.with_config(move |config| {
|
||||
config.chatgpt_base_url = chatgpt_base_url;
|
||||
config.cloud_skill_enabled = true;
|
||||
config.features.enable(Feature::CodeMode).unwrap();
|
||||
config.features.enable(Feature::CodeModeHost).unwrap();
|
||||
})
|
||||
.with_code_mode_host_program(codex_utils_cargo_bin::cargo_bin("codex-code-mode-host")?);
|
||||
let test = builder.build_with_auto_env(&server).await?;
|
||||
// A cannot read its skill until B has become the active turn.
|
||||
let read_after_barrier = format!(
|
||||
r#"await tools.test_sync_tool({{barrier: {{
|
||||
id: "yielded-skill-turns", participants: 2, timeout_ms: 60000
|
||||
}}}});
|
||||
text(await tools.skills__read({{package: "{PACKAGE}"}}));"#
|
||||
);
|
||||
mount_sse_once(
|
||||
&server,
|
||||
sse(vec![
|
||||
ev_response_created("resp-a"),
|
||||
responses::ev_custom_tool_call(
|
||||
"call-a",
|
||||
"exec",
|
||||
&format!("// @exec: {{\"yield_time_ms\": 1}}\n{read_after_barrier}"),
|
||||
),
|
||||
ev_completed("resp-a"),
|
||||
]),
|
||||
)
|
||||
.await;
|
||||
let yielded = mount_sse_once(
|
||||
&server,
|
||||
sse(vec![
|
||||
ev_response_created("resp-a-done"),
|
||||
ev_completed("resp-a-done"),
|
||||
]),
|
||||
)
|
||||
.await;
|
||||
let request = TurnInputRequest::user_input(vec![UserInput::Text {
|
||||
text: "Start a skill read and leave it running.".to_string(),
|
||||
text_elements: Vec::new(),
|
||||
}]);
|
||||
let submitted = test.codex.start_or_steer_turn(request).await?;
|
||||
let TurnInputSubmission::Started {
|
||||
turn_id: turn_a, ..
|
||||
} = submitted
|
||||
else {
|
||||
anyhow::bail!("expected turn A to start, got {submitted:?}");
|
||||
};
|
||||
wait_for_event(&test.codex, |event| {
|
||||
matches!(event, EventMsg::TurnComplete(_))
|
||||
})
|
||||
.await;
|
||||
let (output, _) = yielded
|
||||
.single_request()
|
||||
.custom_tool_call_output_content_and_success("call-a")
|
||||
.expect("yielded cell output");
|
||||
assert!(
|
||||
output
|
||||
.expect("yielded cell status")
|
||||
.starts_with("Script running with cell ID ")
|
||||
);
|
||||
|
||||
mount_sse_once(
|
||||
&server,
|
||||
sse(vec![
|
||||
ev_response_created("resp-b"),
|
||||
responses::ev_custom_tool_call(
|
||||
"call-b",
|
||||
"exec",
|
||||
&format!("// @exec: {{\"yield_time_ms\": 60000}}\n{read_after_barrier}"),
|
||||
),
|
||||
ev_completed("resp-b"),
|
||||
]),
|
||||
)
|
||||
.await;
|
||||
mount_sse_once(
|
||||
&server,
|
||||
sse(vec![
|
||||
ev_response_created("resp-b-done"),
|
||||
ev_completed("resp-b-done"),
|
||||
]),
|
||||
)
|
||||
.await;
|
||||
let submitted = test
|
||||
.codex
|
||||
.start_or_steer_turn(TurnInputRequest::user_input(vec![UserInput::Text {
|
||||
text: "Read the skill in this turn and release the previous read.".to_string(),
|
||||
text_elements: Vec::new(),
|
||||
}]))
|
||||
.await?;
|
||||
let TurnInputSubmission::Started {
|
||||
turn_id: turn_b, ..
|
||||
} = submitted
|
||||
else {
|
||||
anyhow::bail!("expected turn B to start, got {submitted:?}");
|
||||
};
|
||||
wait_for_event(&test.codex, |event| {
|
||||
matches!(event, EventMsg::TurnComplete(_))
|
||||
})
|
||||
.await;
|
||||
|
||||
let events = wait_for_analytics_events(&server, "skill_invocation", /*expected_count*/ 2).await;
|
||||
assert_eq!(events.len(), 2);
|
||||
for turn_id in [&turn_a, &turn_b] {
|
||||
let event = events
|
||||
.iter()
|
||||
.find(|event| event["event_params"]["turn_id"] == *turn_id)
|
||||
.expect("each skill read should retain its originating turn");
|
||||
assert_eq!(event["skill_name"], "demo:yielded");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Reference in New Issue
Block a user