Files
codex/codex-rs/core/tests/common/hooks.rs
T
thomas f85a6e05eb 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
2026-12-02 19:09:13 +00:00

181 lines
6.2 KiB
Rust

use anyhow::Context;
use anyhow::Result;
use codex_config::CONFIG_TOML_FILE;
use codex_config::ConfigLayerStack;
use codex_config::TomlValue;
use codex_core::config::Config;
use codex_features::Feature;
use codex_hooks::HookListEntry;
use codex_utils_absolute_path::AbsolutePathBuf;
use serde_json::Value;
use serde_json::json;
use std::fs;
use std::path::Path;
pub fn write_updating_pre_tool_use_hook(
home: &Path,
matcher: &str,
updated_input: &Value,
) -> Result<()> {
let script_path = home.join("pre_tool_use_hook.py");
let log_path = home.join("pre_tool_use_hook_log.jsonl");
let updated_input_json =
serde_json::to_string(updated_input).context("serialize updated pre tool input")?;
let script = format!(
r#"import json
from pathlib import Path
import sys
payload = json.load(sys.stdin)
with Path(r"{log_path}").open("a", encoding="utf-8") as handle:
handle.write(json.dumps(payload) + "\n")
print(json.dumps({{
"hookSpecificOutput": {{
"hookEventName": "PreToolUse",
"permissionDecision": "allow",
"updatedInput": {updated_input_json}
}}
}}))
"#,
log_path = log_path.display(),
updated_input_json = updated_input_json,
);
let python = if cfg!(windows) { "python" } else { "python3" };
let hooks = serde_json::json!({
"hooks": {
"PreToolUse": [{
"matcher": matcher,
"hooks": [{
"type": "command",
"command": format!("{python} \"{}\"", script_path.display()),
"statusMessage": "rewriting pre tool input",
}]
}]
}
});
fs::write(&script_path, script).context("write updating pre tool use hook script")?;
fs::write(home.join("hooks.json"), hooks.to_string()).context("write hooks.json")?;
Ok(())
}
/// Build the MCP reply for a loopback hook fixture; notifications have no body.
pub fn hook_mcp_reply(
request: &serde_json::Value,
server: &str,
tools: &[&str],
call: impl FnOnce(&serde_json::Value) -> serde_json::Value,
) -> Option<serde_json::Value> {
let method = request["method"].as_str().expect("MCP method");
let Some(id) = request.get("id") else {
assert!(
method.starts_with("notifications/"),
"missing ID for {method}"
);
return None;
};
let result = match method {
"initialize" => json!({
"protocolVersion": request["params"]["protocolVersion"],
"capabilities": {"tools": {}},
"serverInfo": {"name": server, "version": "1.0.0"},
}),
"tools/list" => {
json!({"tools":tools.iter().map(|name| json!({"name":name,"inputSchema":{"type":"object"}})).collect::<Vec<_>>()})
}
"tools/call" => call(&request["params"]),
method => panic!("unexpected MCP request: {method}"),
};
Some(json!({"jsonrpc":"2.0", "id":id, "result":result}))
}
pub async fn mount_hook_mcp(
server: &wiremock::MockServer,
name: &'static str,
tools: &'static [&'static str],
respond: impl Fn(&serde_json::Value) -> serde_json::Value + Send + Sync + 'static,
) {
wiremock::Mock::given(wiremock::matchers::method("POST"))
.and(wiremock::matchers::path("/repl"))
.respond_with(move |req: &wiremock::Request| {
let request = serde_json::from_slice(&req.body).expect("MCP request");
match hook_mcp_reply(&request, name, tools, &respond) {
Some(reply) => wiremock::ResponseTemplate::new(200).set_body_json(reply),
None => wiremock::ResponseTemplate::new(202),
}
})
.mount(server)
.await;
}
pub fn trust_discovered_hooks(config: &mut Config) {
config
.features
.enable(Feature::CodexHooks)
.expect("test config should allow feature update");
let listed = codex_hooks::list_hooks(codex_hooks::HooksConfig {
feature_enabled: true,
config_layer_stack: Some(config.config_layer_stack.clone()),
..codex_hooks::HooksConfig::default()
});
assert!(
!listed.hooks.is_empty(),
"trusted hook fixture should discover at least one hook"
);
trust_hooks(config, listed.hooks);
}
pub fn trust_hooks(config: &mut Config, hooks: Vec<HookListEntry>) {
config.config_layer_stack =
trusted_config_layer_stack(&config.config_layer_stack, &config.codex_home, hooks);
}
pub fn trusted_config_layer_stack(
config_layer_stack: &ConfigLayerStack,
codex_home: &AbsolutePathBuf,
hooks: Vec<HookListEntry>,
) -> ConfigLayerStack {
let mut user_config = config_layer_stack
.get_active_user_layer()
.map(|layer| layer.config.clone())
.unwrap_or_else(|| TomlValue::Table(Default::default()));
let user_table = user_config
.as_table_mut()
.expect("user config should be a table");
let hooks_table = user_table
.entry("hooks")
.or_insert_with(|| TomlValue::Table(Default::default()))
.as_table_mut()
.expect("hooks config should be a table");
let state_table = hooks_table
.entry("state")
.or_insert_with(|| TomlValue::Table(Default::default()))
.as_table_mut()
.expect("hook state config should be a table");
for hook in hooks {
let mut hook_state = TomlValue::Table(Default::default());
let hook_state_table = hook_state
.as_table_mut()
.expect("hook state should be a table");
// 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);
}
config_layer_stack
.with_user_config(&codex_home.join(CONFIG_TOML_FILE), user_config)
.expect("hook user config should be valid")
}