mirror of
https://github.com/openai/codex.git
synced 2026-12-04 00:51:02 +00:00
Support explicitly declared hooks in Agent Plugins (#65316)
## Why Codex skipped hooks in the Agent Plugin format even when the root `plugin.json` explicitly declared them. ## What changed - Discover hooks through the root manifest's `extensions.com.openai.hooks` declaration. File declarations must point to regular files inside the bundle without traversing symlinks. - Apply the existing hook approval flow and give Agent Plugin hooks the same isolated `PLUGIN_DATA` directory as the plugin's stdio MCP servers. - Include declared hooks in plugin details and capability detection without requiring a writable data directory. For remote catalog entries, `plugin/read` gets hook summaries from the matching installed bundle. ## Testing Cover invalid hook paths and runtime data directory failures, verify that an approved `PreToolUse` hook writes to isolated plugin data, and check remote plugin reads with matching, different, and absent local bundles. GitOrigin-RevId: 86311780865f7c598db22d873e88be2699750b75
This commit is contained in:
@@ -1226,10 +1226,7 @@ impl PluginRequestProcessor {
|
||||
.plugin
|
||||
.hooks
|
||||
.into_iter()
|
||||
.map(|hook| codex_app_server_protocol::PluginHookSummary {
|
||||
key: hook.key,
|
||||
event_name: hook.event_name.into(),
|
||||
})
|
||||
.map(plugin_hook_summary_to_info)
|
||||
.collect(),
|
||||
apps: app_summaries,
|
||||
app_templates: Vec::new(),
|
||||
@@ -2419,13 +2416,27 @@ fn remote_plugin_share_discoverability_to_info(
|
||||
}
|
||||
}
|
||||
|
||||
fn plugin_hook_summary_to_info(
|
||||
hook: codex_core_plugins::PluginHookSummary,
|
||||
) -> codex_app_server_protocol::PluginHookSummary {
|
||||
codex_app_server_protocol::PluginHookSummary {
|
||||
key: hook.key,
|
||||
event_name: hook.event_name.into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn remote_plugin_detail_to_info(
|
||||
detail: RemoteCatalogPluginDetail,
|
||||
apps: Vec<AppSummary>,
|
||||
plugin_policy: &PluginsConfigToml,
|
||||
manager: &codex_core_plugins::PluginsManager,
|
||||
) -> PluginDetail {
|
||||
let summary = installed_remote_plugin_summary_to_info(detail.summary, plugin_policy, manager);
|
||||
let (local_version, hooks) = if detail.summary.installed {
|
||||
manager.local_remote_plugin_details(&detail.summary.id, &detail.summary.remote_plugin_id)
|
||||
} else {
|
||||
(None, Vec::new())
|
||||
};
|
||||
let summary = remote_plugin_summary_to_info(detail.summary, plugin_policy, local_version);
|
||||
let app_templates = detail
|
||||
.app_templates
|
||||
.into_iter()
|
||||
@@ -2481,7 +2492,7 @@ fn remote_plugin_detail_to_info(
|
||||
description: detail.description,
|
||||
skills,
|
||||
onboarding_skill,
|
||||
hooks: Vec::new(),
|
||||
hooks: hooks.into_iter().map(plugin_hook_summary_to_info).collect(),
|
||||
apps,
|
||||
app_templates,
|
||||
mcp_servers: detail.mcp_servers,
|
||||
|
||||
@@ -567,8 +567,14 @@ apps = true
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test_case(None, false; "not installed")]
|
||||
#[test_case(Some("plugins~Plugin_11111111111111111111111111111111"), true; "matching installed bundle")]
|
||||
#[test_case(Some("plugins~Plugin_22222222222222222222222222222222"), false; "different installed bundle")]
|
||||
#[tokio::test]
|
||||
async fn plugin_read_returns_share_context_for_shared_remote_plugin() -> Result<()> {
|
||||
async fn plugin_read_returns_share_context_for_shared_remote_plugin(
|
||||
installed_bundle_id: Option<&str>,
|
||||
expect_hook: bool,
|
||||
) -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let server = MockServer::start().await;
|
||||
write_remote_plugin_catalog_config(
|
||||
@@ -618,13 +624,34 @@ async fn plugin_read_returns_share_context_for_shared_remote_plugin() -> Result<
|
||||
"skills": []
|
||||
}
|
||||
}"#;
|
||||
let installed_body = r#"{
|
||||
"plugins": [],
|
||||
"pagination": {
|
||||
"limit": 50,
|
||||
"next_page_token": null
|
||||
}
|
||||
}"#;
|
||||
let mut installed = Vec::new();
|
||||
if let Some(bundle_id) = installed_bundle_id {
|
||||
let mut plugin: serde_json::Value = serde_json::from_str(detail_body)?;
|
||||
plugin["enabled"] = json!(true);
|
||||
installed.push(plugin);
|
||||
let store = codex_core_plugins::store::PluginStore::new(codex_home.path().to_path_buf());
|
||||
let id = codex_plugin::PluginId::parse("shared-linear@workspace-shared-with-me")?;
|
||||
let root = store.plugin_root(&id, "2.3.4");
|
||||
std::fs::create_dir_all(&root)?;
|
||||
std::fs::write(
|
||||
root.join("plugin.json"),
|
||||
serde_json::to_vec(&json!({
|
||||
"$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
|
||||
"name": "shared-linear",
|
||||
"extensions": {"com.openai": {"hooks": "./check.json"}},
|
||||
}))?,
|
||||
)?;
|
||||
std::fs::write(
|
||||
root.join("check.json"),
|
||||
r#"{"hooks":{"PreToolUse":[{"hooks":[{"type":"command","command":"echo check"}]}]}}"#,
|
||||
)?;
|
||||
store.write_remote_plugin_id(&id, bundle_id)?;
|
||||
}
|
||||
let installed_body = json!({
|
||||
"plugins": installed,
|
||||
"pagination": {"limit": 50, "next_page_token": null}
|
||||
})
|
||||
.to_string();
|
||||
|
||||
Mock::given(method("GET"))
|
||||
.and(path(
|
||||
@@ -666,6 +693,16 @@ async fn plugin_read_returns_share_context_for_shared_remote_plugin() -> Result<
|
||||
timeout(DEFAULT_TIMEOUT, mcp.read_response(request_id)).await??;
|
||||
|
||||
assert_eq!(response.plugin.marketplace_name, "workspace-shared-with-me");
|
||||
let expected_hooks = if expect_hook {
|
||||
vec![codex_app_server_protocol::PluginHookSummary {
|
||||
key: "shared-linear@workspace-shared-with-me:check.json:pre_tool_use:0:0"
|
||||
.to_string(),
|
||||
event_name: HookEventName::PreToolUse,
|
||||
}]
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
assert_eq!(response.plugin.hooks, expected_hooks);
|
||||
assert_eq!(
|
||||
response.plugin.summary.id,
|
||||
"shared-linear@workspace-shared-with-me"
|
||||
|
||||
@@ -191,6 +191,8 @@ pub(super) fn parse_agent_plugin_manifest_uri(
|
||||
overlay_path,
|
||||
overlay_contents,
|
||||
)?;
|
||||
// A root manifest must opt in to hooks through its own OpenAI extension.
|
||||
resolved.paths.hooks = None;
|
||||
}
|
||||
Ok(resolved)
|
||||
}
|
||||
|
||||
@@ -90,6 +90,7 @@ pub use manager::EffectivePluginsChange;
|
||||
pub use manager::InstalledPluginSyncSource;
|
||||
pub use manager::PluginDetail;
|
||||
pub use manager::PluginDetailsUnavailableReason;
|
||||
pub use manager::PluginHookSummary;
|
||||
pub use manager::PluginInstallError;
|
||||
pub use manager::PluginInstallOutcome;
|
||||
pub use manager::PluginInstallRequest;
|
||||
|
||||
@@ -891,8 +891,8 @@ async fn load_plugin(
|
||||
let manifest = loaded_manifest.manifest;
|
||||
|
||||
let manifest_paths = &manifest.paths;
|
||||
let plugin_data_root = store.plugin_data_root(&loaded_plugin_id);
|
||||
let mcp_plugin_data_root = store.mcp_data_root(&loaded_plugin_id, loaded_manifest.format);
|
||||
let plugin_data_root =
|
||||
store.plugin_data_root_for_format(&loaded_plugin_id, loaded_manifest.format);
|
||||
loaded_plugin.plugin_namespace = Some(manifest.name.clone());
|
||||
match scope {
|
||||
PluginLoadScope::AllCapabilities {
|
||||
@@ -928,7 +928,7 @@ async fn load_plugin(
|
||||
plugin_root.as_path(),
|
||||
manifest_paths,
|
||||
Some(&plugin.mcp_servers),
|
||||
Some(mcp_plugin_data_root.as_path()),
|
||||
Some(plugin_data_root.as_path()),
|
||||
loaded_manifest.format,
|
||||
)
|
||||
.await;
|
||||
@@ -939,17 +939,24 @@ async fn load_plugin(
|
||||
}
|
||||
PluginLoadScope::HooksOnly => {}
|
||||
}
|
||||
let (hook_sources, hook_load_warnings) =
|
||||
if loaded_manifest.format == PluginManifestFormat::AgentPlugin {
|
||||
(Vec::new(), Vec::new())
|
||||
} else {
|
||||
load_plugin_hooks(
|
||||
&plugin_root,
|
||||
&loaded_plugin_id,
|
||||
&plugin_data_root,
|
||||
manifest_paths,
|
||||
)
|
||||
};
|
||||
let (mut hook_sources, mut hook_load_warnings) = load_plugin_hooks(
|
||||
&plugin_root,
|
||||
&loaded_plugin_id,
|
||||
&plugin_data_root,
|
||||
manifest_paths,
|
||||
loaded_manifest.format,
|
||||
);
|
||||
// Prepare runtime state here so inspecting a bundle never needs a writable data directory.
|
||||
if loaded_manifest.format == PluginManifestFormat::AgentPlugin
|
||||
&& !hook_sources.is_empty()
|
||||
&& let Err(err) = tokio::fs::create_dir_all(plugin_data_root.as_path()).await
|
||||
{
|
||||
hook_load_warnings.push(format!(
|
||||
"failed to create Agent Plugin data directory {}; disabling hooks: {err}",
|
||||
plugin_data_root.display()
|
||||
));
|
||||
hook_sources.clear();
|
||||
}
|
||||
loaded_plugin.hook_sources = hook_sources;
|
||||
loaded_plugin.hook_load_warnings = hook_load_warnings;
|
||||
loaded_plugin
|
||||
@@ -1176,19 +1183,29 @@ fn default_app_config_paths(plugin_root: &Path) -> Vec<AbsolutePathBuf> {
|
||||
}
|
||||
|
||||
// Discover plugin-bundled hooks from manifest `hooks` entries when present
|
||||
// (path, paths, inline object, or inline objects), otherwise from the default
|
||||
// `hooks/hooks.json` file.
|
||||
pub fn load_plugin_hooks(
|
||||
// (path, paths, inline object, or inline objects). Only legacy plugins discover
|
||||
// `hooks/hooks.json` without an explicit declaration.
|
||||
pub(crate) fn load_plugin_hooks(
|
||||
plugin_root: &AbsolutePathBuf,
|
||||
plugin_id: &PluginId,
|
||||
plugin_data_root: &AbsolutePathBuf,
|
||||
manifest_paths: &PluginManifestPaths,
|
||||
manifest_format: PluginManifestFormat,
|
||||
) -> (Vec<PluginHookSource>, Vec<String>) {
|
||||
let mut sources = Vec::new();
|
||||
let mut warnings = Vec::new();
|
||||
match &manifest_paths.hooks {
|
||||
Some(PluginManifestHooks::Paths(paths)) => {
|
||||
for path in paths {
|
||||
if manifest_format == PluginManifestFormat::AgentPlugin
|
||||
&& !is_installable_hook_file(plugin_root.as_path(), path.as_path())
|
||||
{
|
||||
warnings.push(format!(
|
||||
"expected a regular hooks file inside the plugin root: {}",
|
||||
path.display()
|
||||
));
|
||||
continue;
|
||||
}
|
||||
append_plugin_hook_file(
|
||||
plugin_root,
|
||||
plugin_id,
|
||||
@@ -1217,7 +1234,7 @@ pub fn load_plugin_hooks(
|
||||
});
|
||||
}
|
||||
}
|
||||
None => {
|
||||
None if manifest_format == PluginManifestFormat::Legacy => {
|
||||
let default_path = plugin_root.join(DEFAULT_HOOKS_CONFIG_FILE);
|
||||
if default_path.as_path().is_file() {
|
||||
append_plugin_hook_file(
|
||||
@@ -1230,10 +1247,36 @@ pub fn load_plugin_hooks(
|
||||
);
|
||||
}
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
(sources, warnings)
|
||||
}
|
||||
|
||||
// Installation copies only real directories and regular files. A symlink to another
|
||||
// directory inside the bundle passes canonical containment but disappears on install.
|
||||
fn is_installable_hook_file(root: &Path, path: &Path) -> bool {
|
||||
let Ok(relative) = path.strip_prefix(root) else {
|
||||
return false;
|
||||
};
|
||||
let mut current = root.to_path_buf();
|
||||
for component in relative.components() {
|
||||
current.push(component);
|
||||
let Ok(metadata) = current.symlink_metadata() else {
|
||||
return false;
|
||||
};
|
||||
if current == path {
|
||||
let (Ok(root), Ok(target)) = (root.canonicalize(), path.canonicalize()) else {
|
||||
return false;
|
||||
};
|
||||
return metadata.is_file() && target.starts_with(root);
|
||||
}
|
||||
if !metadata.is_dir() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
// Append one resolved plugin hook file, keeping source metadata for runtime
|
||||
// reporting and collecting load warnings for startup surfacing.
|
||||
fn append_plugin_hook_file(
|
||||
|
||||
@@ -396,12 +396,25 @@ async fn legacy_manifest_can_point_at_root_mcp_json() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn installed_agent_plugin_uses_isolated_data_root_for_stdio_mcp() {
|
||||
async fn installed_agent_plugin_shares_its_isolated_data_root_with_declared_hooks() {
|
||||
let temp_dir = TempDir::new().expect("tempdir");
|
||||
let plugin_root = temp_dir.path().join("plugins/cache/c/a-b/local");
|
||||
write_file(
|
||||
&plugin_root.join("plugin.json"),
|
||||
&format!(r#"{{"$schema":"{AGENT_PLUGIN_SCHEMA_URI}","name":"a-b"}}"#),
|
||||
&serde_json::json!({
|
||||
"$schema": AGENT_PLUGIN_SCHEMA_URI,
|
||||
"name": "a-b",
|
||||
"extensions": {"com.openai": {"hooks": "./.codex-plugin/hooks.json"}},
|
||||
})
|
||||
.to_string(),
|
||||
);
|
||||
write_file(
|
||||
&plugin_root.join(".codex-plugin/plugin.json"),
|
||||
r#"{"name":"a-b","hooks":"./hooks/legacy.json"}"#,
|
||||
);
|
||||
write_file(
|
||||
&plugin_root.join(".codex-plugin/hooks.json"),
|
||||
r#"{"hooks":{"PreToolUse":[{"hooks":[{"type":"command","command":"echo check"}]}]}}"#,
|
||||
);
|
||||
write_file(
|
||||
&plugin_root.join("mcp.json"),
|
||||
@@ -452,9 +465,18 @@ async fn installed_agent_plugin_uses_isolated_data_root_for_stdio_mcp() {
|
||||
.expect("absolute Agent Plugin data root")
|
||||
.canonicalize()
|
||||
.expect("canonical Agent Plugin data root");
|
||||
let server = plugins
|
||||
.first()
|
||||
.and_then(|plugin| plugin.mcp_servers.get("example"))
|
||||
let plugin = plugins.first().expect("loaded Agent plugin");
|
||||
let [hook] = plugin.hook_sources.as_slice() else {
|
||||
panic!("expected exactly one declared hook source");
|
||||
};
|
||||
assert_eq!(hook.source_relative_path, ".codex-plugin/hooks.json");
|
||||
assert_eq!(
|
||||
hook.plugin_data_root.canonicalize().unwrap(),
|
||||
expected_data_root
|
||||
);
|
||||
let server = plugin
|
||||
.mcp_servers
|
||||
.get("example")
|
||||
.expect("Agent plugin stdio MCP server");
|
||||
let McpServerTransportConfig::Stdio { env, .. } = &server.transport else {
|
||||
panic!("expected stdio MCP server");
|
||||
@@ -923,6 +945,7 @@ fn load_sources(plugin_root: &AbsolutePathBuf) -> (Vec<PluginHookSource>, Vec<St
|
||||
&plugin_id(),
|
||||
&plugin_data_root,
|
||||
&loaded_manifest.manifest.paths,
|
||||
loaded_manifest.format,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -950,6 +973,87 @@ fn assert_sources(sources: &[PluginHookSource], expected_relative_paths: &[&str]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agent_plugin_requires_a_regular_hook_file() {
|
||||
let (_tmp, root) = plugin_root();
|
||||
fs::write(
|
||||
root.join("plugin.json"),
|
||||
serde_json::json!({
|
||||
"$schema": AGENT_PLUGIN_SCHEMA_URI,
|
||||
"name": "demo-plugin",
|
||||
"extensions": {"com.openai": {"hooks": "./hooks"}},
|
||||
})
|
||||
.to_string(),
|
||||
)
|
||||
.expect("write root manifest");
|
||||
write_hook_file(&root, "hooks/hooks.json", "SessionStart", "echo default");
|
||||
|
||||
let (sources, warnings) = load_sources(&root);
|
||||
|
||||
assert_sources(&sources, &[]);
|
||||
assert_eq!(
|
||||
warnings,
|
||||
vec![format!(
|
||||
"expected a regular hooks file inside the plugin root: {}",
|
||||
root.join("hooks").display()
|
||||
)]
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn agent_plugin_skips_hook_paths_with_symlinked_components() {
|
||||
let (_tmp, root) = plugin_root();
|
||||
write_hook_file(&root, "hooks/check.json", "PreToolUse", "echo check");
|
||||
std::os::unix::fs::symlink("hooks", root.join("linked-dir")).unwrap();
|
||||
std::os::unix::fs::symlink("hooks/check.json", root.join("linked-file.json")).unwrap();
|
||||
write_file(
|
||||
root.join("plugin.json").as_path(),
|
||||
&serde_json::json!({
|
||||
"$schema": AGENT_PLUGIN_SCHEMA_URI,
|
||||
"name": "demo-plugin",
|
||||
"extensions": {"com.openai": {"hooks": [
|
||||
"./linked-dir/check.json", "./linked-file.json", "./hooks/check.json"
|
||||
]}},
|
||||
})
|
||||
.to_string(),
|
||||
);
|
||||
|
||||
let (sources, warnings) = load_sources(&root);
|
||||
|
||||
assert_sources(&sources, &["hooks/check.json"]);
|
||||
assert_eq!(warnings.len(), 2);
|
||||
assert!(warnings[0].contains("linked-dir"));
|
||||
assert!(warnings[1].contains("linked-file.json"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn hooks_only_load_warns_when_agent_plugin_data_directory_cannot_be_created() {
|
||||
let home = TempDir::new().unwrap();
|
||||
let store = PluginStore::new(home.path().to_path_buf());
|
||||
let id = PluginId::parse("example@test").unwrap();
|
||||
let root = store.plugin_root(&id, "local");
|
||||
write_file(
|
||||
root.join("plugin.json").as_path(),
|
||||
&serde_json::json!({
|
||||
"$schema": AGENT_PLUGIN_SCHEMA_URI,
|
||||
"name": "example",
|
||||
"extensions": {"com.openai": {"hooks": "./check.json"}},
|
||||
})
|
||||
.to_string(),
|
||||
);
|
||||
write_hook_file(&root, "check.json", "PreToolUse", "echo check");
|
||||
let data_root = store.agent_plugin_data_root(&id);
|
||||
write_file(data_root.as_path(), "not a directory");
|
||||
|
||||
let config = toml::from_str("enabled = true").unwrap();
|
||||
let plugin = load_plugin(id.as_key(), &config, &store, &PluginLoadScope::HooksOnly).await;
|
||||
|
||||
assert!(plugin.hook_sources.is_empty());
|
||||
assert_eq!(plugin.hook_load_warnings.len(), 1);
|
||||
assert!(plugin.hook_load_warnings[0].contains(&data_root.display().to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_plugin_hooks_discovers_default_hooks_file() {
|
||||
let (_tmp, plugin_root) = plugin_root();
|
||||
|
||||
@@ -46,6 +46,7 @@ use crate::loader::plugin_is_eligible_for_target_marketplace;
|
||||
use crate::loader::refresh_curated_plugin_cache;
|
||||
use crate::loader::refresh_non_curated_plugin_cache_with_mode;
|
||||
use crate::loader::remote_installed_plugins_to_config;
|
||||
use crate::manifest::LoadedPluginManifest;
|
||||
use crate::manifest::PluginManifestFormat;
|
||||
use crate::manifest::PluginManifestInterface;
|
||||
use crate::marketplace::MarketplaceError;
|
||||
@@ -859,17 +860,71 @@ impl PluginsManager {
|
||||
remote_plugin_id: &str,
|
||||
) -> Option<String> {
|
||||
let plugin_id = PluginId::parse(plugin_key).ok()?;
|
||||
let installation = self.store.active_plugin_installation(&plugin_id)?;
|
||||
let root = self.matching_remote_plugin_root(&plugin_id, remote_plugin_id)?;
|
||||
root.as_path().file_name()?.to_str().map(str::to_owned)
|
||||
}
|
||||
|
||||
fn matching_remote_plugin_root(
|
||||
&self,
|
||||
plugin_id: &PluginId,
|
||||
remote_plugin_id: &str,
|
||||
) -> Option<AbsolutePathBuf> {
|
||||
let installation = self.store.active_plugin_installation(plugin_id)?;
|
||||
if installation.persisted_remote_plugin_id().ok()?.as_deref() != Some(remote_plugin_id) {
|
||||
return None;
|
||||
}
|
||||
codex_utils_plugins::find_plugin_manifest_path(installation.root.as_path())?;
|
||||
installation
|
||||
.root
|
||||
Some(installation.root)
|
||||
}
|
||||
|
||||
/// Read the version and hook declarations from the same matching installed bundle.
|
||||
pub fn local_remote_plugin_details(
|
||||
&self,
|
||||
plugin_key: &str,
|
||||
remote_plugin_id: &str,
|
||||
) -> (Option<String>, Vec<PluginHookSummary>) {
|
||||
let Ok(plugin_id) = PluginId::parse(plugin_key) else {
|
||||
return (None, Vec::new());
|
||||
};
|
||||
let Some(root) = self.matching_remote_plugin_root(&plugin_id, remote_plugin_id) else {
|
||||
return (None, Vec::new());
|
||||
};
|
||||
let version = root
|
||||
.as_path()
|
||||
.file_name()?
|
||||
.to_str()
|
||||
.map(str::to_owned)
|
||||
.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.map(str::to_owned);
|
||||
let hooks = self
|
||||
.store
|
||||
.manifest_cache
|
||||
.load(root.as_path())
|
||||
.map(|manifest| self.plugin_hook_summaries(&root, &plugin_id, &manifest))
|
||||
.unwrap_or_default();
|
||||
(version, hooks)
|
||||
}
|
||||
|
||||
fn plugin_hook_summaries(
|
||||
&self,
|
||||
root: &AbsolutePathBuf,
|
||||
plugin_id: &PluginId,
|
||||
manifest: &LoadedPluginManifest,
|
||||
) -> Vec<PluginHookSummary> {
|
||||
let (sources, _) = load_plugin_hooks(
|
||||
root,
|
||||
plugin_id,
|
||||
&self
|
||||
.store
|
||||
.plugin_data_root_for_format(plugin_id, manifest.format),
|
||||
&manifest.manifest.paths,
|
||||
manifest.format,
|
||||
);
|
||||
plugin_hook_declarations(&sources)
|
||||
.into_iter()
|
||||
.map(|hook| PluginHookSummary {
|
||||
key: hook.key,
|
||||
event_name: hook.event_name,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn runtime_auth_slot(&self) -> RuntimeAuthSlot {
|
||||
@@ -3057,6 +3112,7 @@ impl PluginsManager {
|
||||
.ok_or_else(|| {
|
||||
MarketplaceError::InvalidPlugin("missing or invalid plugin.json".to_string())
|
||||
})?;
|
||||
let hooks = self.plugin_hook_summaries(&source_path, &plugin_id, &loaded_manifest);
|
||||
let manifest_format = loaded_manifest.format;
|
||||
let manifest = loaded_manifest.manifest;
|
||||
let description = manifest.description.clone();
|
||||
@@ -3097,20 +3153,9 @@ impl PluginsManager {
|
||||
.any(|skill| skill.path_to_skills_md == path_uri)
|
||||
.then_some(path)
|
||||
});
|
||||
let plugin_data_root = self.store.plugin_data_root(&plugin_id);
|
||||
let (hook_sources, _hook_load_warnings) = if manifest_format == PluginManifestFormat::Legacy
|
||||
{
|
||||
load_plugin_hooks(&source_path, &plugin_id, &plugin_data_root, &manifest.paths)
|
||||
} else {
|
||||
(Vec::new(), Vec::new())
|
||||
};
|
||||
let hooks = plugin_hook_declarations(&hook_sources)
|
||||
.into_iter()
|
||||
.map(|hook| PluginHookSummary {
|
||||
key: hook.key,
|
||||
event_name: hook.event_name,
|
||||
})
|
||||
.collect();
|
||||
let plugin_data_root = self
|
||||
.store
|
||||
.plugin_data_root_for_format(&plugin_id, manifest_format);
|
||||
let auth_mode = self.auth_mode();
|
||||
let mut app_declarations = if plugin_supports_apps(manifest_format, &plugin_id) {
|
||||
load_plugin_apps_from_manifest(source_path.as_path(), &manifest.paths).await
|
||||
@@ -3118,12 +3163,12 @@ impl PluginsManager {
|
||||
Vec::new()
|
||||
};
|
||||
let mcp_data_root = (manifest_format == PluginManifestFormat::AgentPlugin)
|
||||
.then(|| self.store.mcp_data_root(&plugin_id, manifest_format));
|
||||
.then_some(plugin_data_root.as_path());
|
||||
let mut mcp_servers = load_plugin_mcp_servers_from_manifest_with_format(
|
||||
source_path.as_path(),
|
||||
&manifest.paths,
|
||||
/*plugin_policy*/ None,
|
||||
mcp_data_root.as_deref(),
|
||||
mcp_data_root,
|
||||
manifest_format,
|
||||
)
|
||||
.await;
|
||||
|
||||
@@ -7,7 +7,6 @@ use crate::loader::load_plugin_apps_from_manifest;
|
||||
use crate::loader::load_plugin_hooks;
|
||||
use crate::loader::load_plugin_mcp_servers_from_manifest_with_format;
|
||||
use crate::loader::plugin_skill_roots;
|
||||
use crate::manifest::PluginManifestFormat;
|
||||
use crate::store::PluginStore;
|
||||
use codex_hooks::plugin_hook_declarations;
|
||||
use codex_plugin::PluginId;
|
||||
@@ -51,11 +50,14 @@ impl RemotePluginCapabilities {
|
||||
self.has_apps |= !load_plugin_apps_from_manifest(root.as_path(), paths)
|
||||
.await
|
||||
.is_empty();
|
||||
if loaded.format == PluginManifestFormat::Legacy {
|
||||
let (sources, _) =
|
||||
load_plugin_hooks(&root, plugin_id, &store.plugin_data_root(plugin_id), paths);
|
||||
self.has_hooks |= !plugin_hook_declarations(&sources).is_empty();
|
||||
}
|
||||
let (sources, _) = load_plugin_hooks(
|
||||
&root,
|
||||
plugin_id,
|
||||
&store.plugin_data_root_for_format(plugin_id, loaded.format),
|
||||
paths,
|
||||
loaded.format,
|
||||
);
|
||||
self.has_hooks |= !plugin_hook_declarations(&sources).is_empty();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Covers local capability accumulation and removal hints from the shared bundle sync.
|
||||
|
||||
use super::*;
|
||||
use crate::manifest::PluginManifestFormat;
|
||||
use crate::remote::RemoteInstalledPluginBundleSyncOutcome;
|
||||
use crate::remote::RemotePluginChange;
|
||||
use crate::remote::RemotePluginServiceConfig;
|
||||
@@ -29,7 +30,7 @@ async fn agent_plugin_capabilities_do_not_require_runtime_data_directory() {
|
||||
&json!({
|
||||
"$schema": AGENT_PLUGIN_SCHEMA_URI,
|
||||
"name": "example",
|
||||
"extensions": {"com.openai": {"apps": "./connectors.json"}},
|
||||
"extensions": {"com.openai": {"apps": "./connectors.json", "hooks": "./hooks.json"}},
|
||||
})
|
||||
.to_string(),
|
||||
);
|
||||
@@ -45,7 +46,12 @@ async fn agent_plugin_capabilities_do_not_require_runtime_data_directory() {
|
||||
root.join("connectors.json").as_path(),
|
||||
&json!({"apps": {"example": {"id": "connector_example"}}}).to_string(),
|
||||
);
|
||||
let data_root = store.mcp_data_root(&plugin_id, PluginManifestFormat::AgentPlugin);
|
||||
write_file(
|
||||
root.join("hooks.json").as_path(),
|
||||
r#"{"hooks":{"PreToolUse":[{"hooks":[{"type":"command","command":"echo example"}]}]}}"#,
|
||||
);
|
||||
let data_root =
|
||||
store.plugin_data_root_for_format(&plugin_id, PluginManifestFormat::AgentPlugin);
|
||||
|
||||
for block_data_root in [false, true] {
|
||||
if block_data_root {
|
||||
@@ -60,7 +66,7 @@ async fn agent_plugin_capabilities_do_not_require_runtime_data_directory() {
|
||||
has_apps: true,
|
||||
// Agent Plugins declare a conventional skills root even if it is absent.
|
||||
has_skills: true,
|
||||
..Default::default()
|
||||
has_hooks: true,
|
||||
}
|
||||
);
|
||||
assert_eq!(data_root.as_path().exists(), block_data_root);
|
||||
|
||||
@@ -136,7 +136,7 @@ impl PluginStore {
|
||||
.join(hex_prefix(&digest.finalize(), /*count*/ 32))
|
||||
}
|
||||
|
||||
pub(crate) fn mcp_data_root(
|
||||
pub(crate) fn plugin_data_root_for_format(
|
||||
&self,
|
||||
plugin_id: &PluginId,
|
||||
manifest_format: PluginManifestFormat,
|
||||
|
||||
@@ -160,10 +160,17 @@ pub fn trusted_config_layer_stack(
|
||||
let hook_state_table = hook_state
|
||||
.as_table_mut()
|
||||
.expect("hook state should be a table");
|
||||
hook_state_table.insert(
|
||||
"trusted_hash".to_string(),
|
||||
TomlValue::String(hook.current_hash),
|
||||
);
|
||||
// Match the config writer: plugin approvals pin both the declaration and the bundle.
|
||||
let declaration = if let Some((declaration, content)) = hook.current_hash.split_once('/') {
|
||||
hook_state_table.insert(
|
||||
"trusted_content_hash".to_string(),
|
||||
TomlValue::String(content.to_owned()),
|
||||
);
|
||||
declaration.to_owned()
|
||||
} else {
|
||||
hook.current_hash
|
||||
};
|
||||
hook_state_table.insert("trusted_hash".to_string(), TomlValue::String(declaration));
|
||||
state_table.insert(hook.key, hook_state);
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ use codex_config::McpServerConfig;
|
||||
use codex_config::test_support::CloudConfigBundleFixture;
|
||||
use codex_core::AgentRuntimeOwnership;
|
||||
use codex_core::AgentTurnAdmission;
|
||||
use codex_core::ConfigRefreshOutcome;
|
||||
use codex_core::ForkSnapshot;
|
||||
use codex_core::InheritedSessionId;
|
||||
use codex_core::RestrictRootCapabilities;
|
||||
@@ -39,6 +40,7 @@ use codex_protocol::protocol::AskForApproval;
|
||||
use codex_protocol::protocol::EventMsg;
|
||||
use codex_protocol::protocol::HookEventName;
|
||||
use codex_protocol::protocol::HookRunStatus;
|
||||
use codex_protocol::protocol::HookTrustStatus;
|
||||
use codex_protocol::protocol::InternalSessionSource;
|
||||
use codex_protocol::protocol::Op;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
@@ -58,6 +60,7 @@ use core_test_support::TestTargetOs;
|
||||
use core_test_support::fs_wait;
|
||||
use core_test_support::hooks::mount_hook_mcp;
|
||||
use core_test_support::hooks::trust_discovered_hooks;
|
||||
use core_test_support::hooks::trust_hooks;
|
||||
pub(super) use core_test_support::hooks::write_updating_pre_tool_use_hook;
|
||||
use core_test_support::responses;
|
||||
use core_test_support::responses::ev_apply_patch_custom_tool_call;
|
||||
@@ -4798,6 +4801,91 @@ async fn local_bundled_cleanup_hook_runs_without_saved_trust(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn agent_plugin_hook_requires_approval_and_writes_to_isolated_data() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
let server = start_mock_server().await;
|
||||
let mut turns = Vec::new();
|
||||
for id in ["before", "after"] {
|
||||
turns.push(sse(vec![
|
||||
ev_response_created(&format!("call-{id}")),
|
||||
ev_function_call(id, "exec_command", r#"{"cmd":"echo ok"}"#),
|
||||
ev_completed(&format!("call-{id}")),
|
||||
]));
|
||||
turns.push(sse(vec![
|
||||
ev_response_created(&format!("done-{id}")),
|
||||
ev_assistant_message(&format!("msg-{id}"), "done"),
|
||||
ev_completed(&format!("done-{id}")),
|
||||
]));
|
||||
}
|
||||
let _responses = mount_sse_sequence(&server, turns).await;
|
||||
let home = Arc::new(TempDir::new()?);
|
||||
let root = home.path().join("plugins/cache/test/sample/local");
|
||||
fs::create_dir_all(root.join(".codex-plugin"))?;
|
||||
fs::write(
|
||||
root.join("plugin.json"),
|
||||
serde_json::to_vec(&json!({
|
||||
"$schema": codex_utils_plugins::AGENT_PLUGIN_SCHEMA_URI,
|
||||
"name": "sample",
|
||||
"extensions": {"com.openai": {"hooks": "./.codex-plugin/hooks.json"}},
|
||||
}))?,
|
||||
)?;
|
||||
let python = if cfg!(windows) { "python" } else { "python3" };
|
||||
fs::write(
|
||||
root.join(".codex-plugin/hooks.json"),
|
||||
serde_json::to_vec(&json!({
|
||||
"hooks": {"PreToolUse": [{"matcher": "^Bash$", "hooks": [{
|
||||
"type": "command",
|
||||
"command": format!(r#"{python} -I -S "${{PLUGIN_ROOT}}/record.py""#),
|
||||
}]}]},
|
||||
}))?,
|
||||
)?;
|
||||
fs::write(
|
||||
root.join("record.py"),
|
||||
r#"import json, os, sys
|
||||
from pathlib import Path
|
||||
with (Path(os.environ["PLUGIN_DATA"]) / "calls").open("a", encoding="utf-8") as log:
|
||||
print(json.load(sys.stdin)["tool_use_id"], file=log)
|
||||
print("{}")
|
||||
"#,
|
||||
)?;
|
||||
fs::write(
|
||||
home.path().join("config.toml"),
|
||||
"[features]\nplugins = true\nhooks = true\n[plugins.\"sample@test\"]\nenabled = true\n",
|
||||
)?;
|
||||
let test = test_codex()
|
||||
.with_home(Arc::clone(&home))
|
||||
.build(&server)
|
||||
.await?;
|
||||
let hooks = test.codex.list_hooks().hooks;
|
||||
assert_eq!(hooks.len(), 1);
|
||||
assert_eq!(hooks[0].trust_status, HookTrustStatus::Untrusted);
|
||||
let data_root = fs::read_dir(home.path().join("plugins/data/agent-plugins"))?
|
||||
.next()
|
||||
.context("isolated data directory for hooks-only plugin")??
|
||||
.path();
|
||||
let log = data_root.join("calls");
|
||||
test.submit_turn_with_permission_profile("before approval", PermissionProfile::Disabled)
|
||||
.await?;
|
||||
assert!(!log.exists(), "the unapproved hook must not run");
|
||||
|
||||
let current = test.codex.config().await;
|
||||
let mut approved = (*current).clone();
|
||||
trust_hooks(&mut approved, hooks);
|
||||
assert_eq!(
|
||||
test.codex.refresh_runtime_config(current, approved).await,
|
||||
ConfigRefreshOutcome::Published
|
||||
);
|
||||
test.submit_turn_with_permission_profile("after approval", PermissionProfile::Disabled)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
fs::read_to_string(log)?.lines().collect::<Vec<_>>(),
|
||||
vec!["after"]
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn plugin_pre_tool_use_blocks_exec_command_before_execution() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
Reference in New Issue
Block a user