Base: codex-main originale (prima del fork aKode)
This commit is contained in:
526
codex-rs/hooks/src/engine/command_runner.rs
Normal file
526
codex-rs/hooks/src/engine/command_runner.rs
Normal file
@@ -0,0 +1,526 @@
|
||||
use std::collections::HashMap;
|
||||
use std::ffi::OsStr;
|
||||
use std::ffi::OsString;
|
||||
use std::future::Future;
|
||||
use std::io::ErrorKind;
|
||||
#[cfg(windows)]
|
||||
use std::os::windows::process::CommandExt;
|
||||
use std::path::Path;
|
||||
#[cfg(not(unix))]
|
||||
use std::process::Stdio;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::MutexGuard;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
use async_channel::Sender;
|
||||
use codex_protocol::shell_environment::is_non_inheritable_env_var;
|
||||
#[cfg(unix)]
|
||||
use codex_utils_pty::Command;
|
||||
#[cfg(windows)]
|
||||
use codex_utils_pty::JobObject;
|
||||
use futures::future::try_join;
|
||||
use serde_json::Value;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
#[cfg(not(unix))]
|
||||
use tokio::process::Command;
|
||||
use tokio::sync::Semaphore;
|
||||
use tokio::task::JoinSet;
|
||||
use tokio::time::timeout;
|
||||
use tracing::Span;
|
||||
|
||||
#[cfg(windows)]
|
||||
const CREATE_NO_WINDOW: u32 = 0x08000000;
|
||||
|
||||
use super::ClaudeHooksEngine;
|
||||
use super::CommandShell;
|
||||
use super::ConfiguredHandler;
|
||||
use super::HandlerRunResult;
|
||||
use super::dispatcher::ParsedHandler;
|
||||
use super::dispatcher::hook_event_name_label;
|
||||
use super::dispatcher::hook_execution_mode_label;
|
||||
use super::dispatcher::hook_handler_type_label;
|
||||
use super::dispatcher::hook_scope_label;
|
||||
use super::dispatcher::hook_source_label;
|
||||
use super::dispatcher::scope_for_event;
|
||||
use crate::output_spill::HookOutputSpiller;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::HookCompletedEvent;
|
||||
use codex_protocol::protocol::HookHandlerType;
|
||||
use codex_protocol::protocol::HookOutputEntry;
|
||||
use codex_protocol::protocol::HookOutputEntryKind;
|
||||
|
||||
const MAX_CONCURRENT_ASYNC_HOOKS: usize = 8;
|
||||
|
||||
/// Owns command execution and bounded asynchronous work for one session.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct CommandHookRuntime {
|
||||
pub(crate) environment_executor: Option<Arc<dyn crate::HookEnvironmentExecutor>>,
|
||||
shell: CommandShell,
|
||||
environment: Arc<Vec<(OsString, OsString)>>,
|
||||
result_sender: Sender<HookCompletedEvent>,
|
||||
state: Arc<Mutex<CommandHookRuntimeState>>,
|
||||
output_spiller: HookOutputSpiller,
|
||||
}
|
||||
|
||||
struct CommandHookRuntimeState {
|
||||
concurrency_limit: Arc<Semaphore>,
|
||||
tasks: JoinSet<()>,
|
||||
}
|
||||
|
||||
impl Default for CommandHookRuntimeState {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
concurrency_limit: Arc::new(Semaphore::new(MAX_CONCURRENT_ASYNC_HOOKS)),
|
||||
tasks: JoinSet::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CommandHookRuntime {
|
||||
pub(crate) fn new(
|
||||
shell: CommandShell,
|
||||
environment: Arc<Vec<(OsString, OsString)>>,
|
||||
thread_id: ThreadId,
|
||||
result_sender: Sender<HookCompletedEvent>,
|
||||
) -> Self {
|
||||
Self {
|
||||
environment_executor: None,
|
||||
shell,
|
||||
environment,
|
||||
result_sender,
|
||||
state: Arc::new(Mutex::new(CommandHookRuntimeState::default())),
|
||||
output_spiller: HookOutputSpiller::new(thread_id),
|
||||
}
|
||||
}
|
||||
|
||||
fn lock_state(&self) -> MutexGuard<'_, CommandHookRuntimeState> {
|
||||
self.state
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
|
||||
pub(crate) fn reconfigured(&self, shell: CommandShell) -> Self {
|
||||
Self {
|
||||
environment_executor: self.environment_executor.clone(),
|
||||
shell,
|
||||
environment: Arc::clone(&self.environment),
|
||||
result_sender: self.result_sender.clone(),
|
||||
state: Arc::clone(&self.state),
|
||||
output_spiller: self.output_spiller.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn output_spiller(&self) -> &HookOutputSpiller {
|
||||
&self.output_spiller
|
||||
}
|
||||
|
||||
pub(crate) fn schedule_async_hook<T: 'static>(
|
||||
&self,
|
||||
engine: ClaudeHooksEngine,
|
||||
handler: ConfiguredHandler,
|
||||
event_input: Value,
|
||||
cwd: std::path::PathBuf,
|
||||
turn_id: Option<String>,
|
||||
parse: fn(&ConfiguredHandler, HandlerRunResult, Option<String>) -> ParsedHandler<T>,
|
||||
) {
|
||||
if self.result_sender.is_closed() {
|
||||
return;
|
||||
}
|
||||
|
||||
let result_sender = self.result_sender.clone();
|
||||
let runtime = self.clone();
|
||||
self.schedule_async_task(async move {
|
||||
let result = super::dispatcher::execute_handler(
|
||||
&engine,
|
||||
&handler,
|
||||
&event_input,
|
||||
&cwd,
|
||||
/*metadata*/ None,
|
||||
)
|
||||
.await;
|
||||
let mut hook_result = parse(&handler, result, turn_id).completed;
|
||||
let mut entries = Vec::new();
|
||||
let mut warnings = Vec::new();
|
||||
|
||||
for entry in std::mem::take(&mut hook_result.run.entries) {
|
||||
match entry.kind {
|
||||
HookOutputEntryKind::Context => {
|
||||
let text = runtime
|
||||
.output_spiller
|
||||
.maybe_spill_text_with_limit(
|
||||
entry.text,
|
||||
handler.additional_context_limit,
|
||||
)
|
||||
.await;
|
||||
entries.push(HookOutputEntry {
|
||||
kind: HookOutputEntryKind::Context,
|
||||
text,
|
||||
});
|
||||
}
|
||||
HookOutputEntryKind::Warning => warnings.push(entry),
|
||||
HookOutputEntryKind::Error => entries.push(entry),
|
||||
HookOutputEntryKind::Stop | HookOutputEntryKind::Feedback => {}
|
||||
}
|
||||
}
|
||||
|
||||
entries.extend(warnings);
|
||||
hook_result.run.entries = entries;
|
||||
let _ = result_sender.try_send(hook_result);
|
||||
});
|
||||
}
|
||||
|
||||
pub(crate) fn schedule_async_task(&self, task: impl Future<Output = ()> + Send + 'static) {
|
||||
let mut state = self.lock_state();
|
||||
if state.concurrency_limit.is_closed() {
|
||||
return;
|
||||
}
|
||||
|
||||
while state.tasks.try_join_next().is_some() {}
|
||||
let concurrency_limit = Arc::clone(&state.concurrency_limit);
|
||||
state.tasks.spawn(async move {
|
||||
let Ok(_permit) = concurrency_limit.acquire_owned().await else {
|
||||
return;
|
||||
};
|
||||
task.await;
|
||||
});
|
||||
}
|
||||
|
||||
pub(crate) async fn shutdown(&self) {
|
||||
let mut tasks = {
|
||||
let mut state = self.lock_state();
|
||||
state.concurrency_limit.close();
|
||||
std::mem::take(&mut state.tasks)
|
||||
};
|
||||
tasks.abort_all();
|
||||
while tasks.join_next().await.is_some() {}
|
||||
}
|
||||
}
|
||||
|
||||
#[tracing::instrument(
|
||||
name = "codex.hooks.command",
|
||||
level = "trace",
|
||||
skip_all,
|
||||
fields(
|
||||
hook.event_name = hook_event_name_label(handler.event_name),
|
||||
hook.handler_type = hook_handler_type_label(HookHandlerType::Command),
|
||||
hook.execution_mode = hook_execution_mode_label(handler.execution_mode()),
|
||||
hook.scope = hook_scope_label(scope_for_event(handler.event_name)),
|
||||
hook.source = hook_source_label(handler.source),
|
||||
hook.display_order = handler.display_order,
|
||||
hook.timeout_sec = handler.timeout_sec,
|
||||
hook.command_outcome = tracing::field::Empty,
|
||||
)
|
||||
)]
|
||||
pub(crate) async fn run_command(
|
||||
runtime: &CommandHookRuntime,
|
||||
handler: &ConfiguredHandler,
|
||||
command_line: &str,
|
||||
env: &HashMap<String, String>,
|
||||
input_json: &str,
|
||||
cwd: &Path,
|
||||
) -> HandlerRunResult {
|
||||
let started_at = chrono::Utc::now().timestamp();
|
||||
let started = Instant::now();
|
||||
let timeout_started = tokio::time::Instant::now();
|
||||
let duration = Duration::from_secs(handler.timeout_sec);
|
||||
if let Some(trust) = &handler.plugin_trust {
|
||||
let error = match timeout(duration, trust.verify()).await {
|
||||
Ok(Ok(())) => None,
|
||||
Ok(Err(err)) => Some(err.to_string()),
|
||||
Err(_) => Some(format!("hook timed out after {}s", handler.timeout_sec)),
|
||||
};
|
||||
if let Some(error) = error {
|
||||
return finish_command_run(
|
||||
started_at,
|
||||
started,
|
||||
CommandRunCompletion {
|
||||
exit_code: None,
|
||||
stdout: String::new(),
|
||||
stderr: String::new(),
|
||||
error: Some(error),
|
||||
outcome: "trust_error",
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if let super::HandlerSourcePath::Environment { environment_id, .. } = &handler.source_path {
|
||||
let result = match &runtime.environment_executor {
|
||||
Some(executor) => {
|
||||
executor
|
||||
.execute(
|
||||
environment_id,
|
||||
command_line,
|
||||
env,
|
||||
input_json,
|
||||
Duration::from_secs(handler.timeout_sec),
|
||||
)
|
||||
.await
|
||||
}
|
||||
None => Err(anyhow::anyhow!("environment hook executor is unavailable")),
|
||||
};
|
||||
let (exit_code, stdout, stderr, error) = match result {
|
||||
Ok(output) => (Some(output.exit_code), output.stdout, output.stderr, None),
|
||||
Err(error) => (None, String::new(), String::new(), Some(error.to_string())),
|
||||
};
|
||||
return HandlerRunResult {
|
||||
context_metadata: codex_protocol::models::ContentItemMetadata::command_hook(),
|
||||
started_at,
|
||||
completed_at: chrono::Utc::now().timestamp(),
|
||||
duration_ms: started.elapsed().as_millis().try_into().unwrap_or(i64::MAX),
|
||||
exit_code,
|
||||
stdout,
|
||||
stderr,
|
||||
error,
|
||||
};
|
||||
}
|
||||
|
||||
let mut command = build_command(&runtime.shell, command_line, &runtime.environment, env);
|
||||
command.current_dir(cwd);
|
||||
|
||||
#[cfg(windows)]
|
||||
let (child, process_tree_job) = match JobObject::spawn_background(&mut command) {
|
||||
Ok((child, job)) => (Ok(child), job),
|
||||
Err(error) => (Err(error), None),
|
||||
};
|
||||
#[cfg(not(windows))]
|
||||
let child = command.spawn();
|
||||
|
||||
let mut child = match child {
|
||||
Ok(child) => child,
|
||||
Err(err) => {
|
||||
return finish_command_run(
|
||||
started_at,
|
||||
started,
|
||||
CommandRunCompletion {
|
||||
exit_code: None,
|
||||
stdout: String::new(),
|
||||
stderr: String::new(),
|
||||
error: Some(err.to_string()),
|
||||
outcome: "spawn_error",
|
||||
},
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
let mut process_tree_guard = ProcessTreeGuard {
|
||||
process_id: child.id(),
|
||||
#[cfg(windows)]
|
||||
job: process_tree_job,
|
||||
};
|
||||
|
||||
let stdin = child.stdin.take();
|
||||
let write_stdin = async {
|
||||
if let Some(mut stdin) = stdin
|
||||
&& let Err(err) = stdin.write_all(input_json.as_bytes()).await
|
||||
&& err.kind() != ErrorKind::BrokenPipe
|
||||
{
|
||||
return Err(("stdin_error", format!("failed to write hook stdin: {err}")));
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
let wait_with_output = async {
|
||||
child
|
||||
.wait_with_output()
|
||||
.await
|
||||
.map_err(|err| ("wait_error", err.to_string()))
|
||||
};
|
||||
|
||||
// Drain output while sending input so neither pipe can block the other, and
|
||||
// include stdin writes in the deadline even when the hook never reads them.
|
||||
match timeout(
|
||||
duration.saturating_sub(timeout_started.elapsed()),
|
||||
try_join(write_stdin, wait_with_output),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Ok(((), output))) => {
|
||||
// Successfully completed hooks may intentionally leave detached helpers running.
|
||||
#[cfg(windows)]
|
||||
if let Some(job) = process_tree_guard.job.as_ref() {
|
||||
let _ = job.preserve_descendants();
|
||||
}
|
||||
process_tree_guard.process_id = None;
|
||||
finish_command_run(
|
||||
started_at,
|
||||
started,
|
||||
CommandRunCompletion {
|
||||
exit_code: output.status.code(),
|
||||
stdout: String::from_utf8_lossy(&output.stdout).to_string(),
|
||||
stderr: String::from_utf8_lossy(&output.stderr).to_string(),
|
||||
error: None,
|
||||
outcome: "completed",
|
||||
},
|
||||
)
|
||||
}
|
||||
Ok(Err((outcome, error))) => finish_command_run(
|
||||
started_at,
|
||||
started,
|
||||
CommandRunCompletion {
|
||||
exit_code: None,
|
||||
stdout: String::new(),
|
||||
stderr: String::new(),
|
||||
error: Some(error),
|
||||
outcome,
|
||||
},
|
||||
),
|
||||
Err(_) => finish_command_run(
|
||||
started_at,
|
||||
started,
|
||||
CommandRunCompletion {
|
||||
exit_code: None,
|
||||
stdout: String::new(),
|
||||
stderr: String::new(),
|
||||
error: Some(format!("hook timed out after {}s", handler.timeout_sec)),
|
||||
outcome: "timeout",
|
||||
},
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
// Needed only until command hooks move to the exec server, which owns process-tree cleanup.
|
||||
struct ProcessTreeGuard {
|
||||
process_id: Option<u32>,
|
||||
#[cfg(windows)]
|
||||
job: Option<JobObject>,
|
||||
}
|
||||
|
||||
impl Drop for ProcessTreeGuard {
|
||||
fn drop(&mut self) {
|
||||
let Some(process_id) = self.process_id else {
|
||||
return;
|
||||
};
|
||||
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let _ = codex_utils_pty::process_group::kill_process_group(process_id);
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
{
|
||||
if let Some(job) = self.job.as_ref() {
|
||||
let _ = job.terminate();
|
||||
} else {
|
||||
let _ = std::process::Command::new("taskkill")
|
||||
.args(["/PID", &process_id.to_string(), "/T", "/F"])
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.creation_flags(CREATE_NO_WINDOW)
|
||||
.spawn();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct CommandRunCompletion {
|
||||
exit_code: Option<i32>,
|
||||
stdout: String,
|
||||
stderr: String,
|
||||
error: Option<String>,
|
||||
outcome: &'static str,
|
||||
}
|
||||
|
||||
fn finish_command_run(
|
||||
started_at: i64,
|
||||
started: Instant,
|
||||
completion: CommandRunCompletion,
|
||||
) -> HandlerRunResult {
|
||||
Span::current().record("hook.command_outcome", completion.outcome);
|
||||
HandlerRunResult {
|
||||
context_metadata: codex_protocol::models::ContentItemMetadata::command_hook(),
|
||||
started_at,
|
||||
completed_at: chrono::Utc::now().timestamp(),
|
||||
duration_ms: started.elapsed().as_millis().try_into().unwrap_or(i64::MAX),
|
||||
exit_code: completion.exit_code,
|
||||
stdout: completion.stdout,
|
||||
stderr: completion.stderr,
|
||||
error: completion.error,
|
||||
}
|
||||
}
|
||||
|
||||
fn build_command(
|
||||
shell: &CommandShell,
|
||||
command_line: &str,
|
||||
environment: &[(OsString, OsString)],
|
||||
env: &HashMap<String, String>,
|
||||
) -> Command {
|
||||
let mut command = if shell.program.is_empty() {
|
||||
Command::new(default_shell_program(environment))
|
||||
} else {
|
||||
Command::new(&shell.program)
|
||||
};
|
||||
if shell.program.is_empty() {
|
||||
#[cfg(windows)]
|
||||
command.arg("/C");
|
||||
#[cfg(not(windows))]
|
||||
command.arg("-lc");
|
||||
} else {
|
||||
command.args(&shell.args);
|
||||
}
|
||||
#[cfg(windows)]
|
||||
if shell.program.is_empty() || shell.args.iter().any(|arg| arg.eq_ignore_ascii_case("/c")) {
|
||||
command.raw_arg(format!(r#""{command_line}""#));
|
||||
} else {
|
||||
command.arg(command_line);
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
command.arg(command_line);
|
||||
|
||||
#[cfg(unix)]
|
||||
command.process_mode(codex_utils_pty::ProcessMode::NewSession);
|
||||
#[cfg(windows)]
|
||||
command.creation_flags(CREATE_NO_WINDOW);
|
||||
#[cfg(not(unix))]
|
||||
command
|
||||
.env_clear()
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.kill_on_drop(true);
|
||||
|
||||
// Both launchers start with an empty environment. Replay the session snapshot
|
||||
// before hook overrides, filtering restricted names from both sources.
|
||||
command.envs(
|
||||
environment
|
||||
.iter()
|
||||
.map(|(key, value)| (key.as_os_str(), value.as_os_str()))
|
||||
.chain(
|
||||
env.iter()
|
||||
.map(|(key, value)| (OsStr::new(key), OsStr::new(value))),
|
||||
)
|
||||
.filter(|(key, _)| !key.to_str().is_some_and(is_non_inheritable_env_var)),
|
||||
);
|
||||
command
|
||||
}
|
||||
|
||||
fn default_shell_program(environment: &[(OsString, OsString)]) -> OsString {
|
||||
#[cfg(windows)]
|
||||
let (environment_variable, fallback_program) = ("COMSPEC", "cmd.exe");
|
||||
|
||||
#[cfg(not(windows))]
|
||||
let (environment_variable, fallback_program) = ("SHELL", "/bin/sh");
|
||||
|
||||
environment
|
||||
.iter()
|
||||
.find(|(key, _)| {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
key.to_str()
|
||||
.is_some_and(|key| key.eq_ignore_ascii_case(environment_variable))
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
key == OsStr::new(environment_variable)
|
||||
}
|
||||
})
|
||||
.map(|(_, value)| value.clone())
|
||||
.unwrap_or_else(|| OsString::from(fallback_program))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "command_runner_tests.rs"]
|
||||
mod tests;
|
||||
959
codex-rs/hooks/src/engine/command_runner_tests.rs
Normal file
959
codex-rs/hooks/src/engine/command_runner_tests.rs
Normal file
@@ -0,0 +1,959 @@
|
||||
use std::collections::HashMap;
|
||||
use std::ffi::OsString;
|
||||
#[cfg(windows)]
|
||||
use std::fs;
|
||||
#[cfg(unix)]
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use async_channel::Receiver;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::HookCompletedEvent;
|
||||
use codex_protocol::protocol::HookEventName;
|
||||
use codex_protocol::protocol::HookOutputEntry;
|
||||
use codex_protocol::protocol::HookOutputEntryKind;
|
||||
use codex_protocol::protocol::HookRunStatus;
|
||||
use codex_protocol::protocol::HookSource;
|
||||
use codex_protocol::shell_environment::CODEX_EXEC_SERVER_NOISE_AUTH_TOKEN_ENV_VAR;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
use tempfile::tempdir;
|
||||
use tokio::time::sleep;
|
||||
use tokio::time::timeout;
|
||||
|
||||
use super::super::ClaudeHooksEngine;
|
||||
use super::super::ConfiguredHandlerKind;
|
||||
use super::super::tests::mcp_executor;
|
||||
use super::CommandHookRuntime;
|
||||
use super::CommandShell;
|
||||
use super::ConfiguredHandler;
|
||||
use super::MAX_CONCURRENT_ASYNC_HOOKS;
|
||||
use super::build_command;
|
||||
use super::default_shell_program;
|
||||
use super::run_command;
|
||||
use crate::events::user_prompt_submit::UserPromptSubmitRequest;
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn hook_shell_startup_does_not_stop_on_controlling_terminal() {
|
||||
const CHILD_ENV: &str = "CODEX_HOOK_TERMINAL_TEST_CHILD";
|
||||
const TEST_NAME: &str =
|
||||
"engine::command_runner::tests::hook_shell_startup_does_not_stop_on_controlling_terminal";
|
||||
|
||||
if std::env::var_os(CHILD_ENV).is_none() {
|
||||
// Re-exec under a controlling terminal even when the test runner has none.
|
||||
let executable = std::env::current_exe().expect("current test executable");
|
||||
let mut env = std::env::vars().collect::<HashMap<_, _>>();
|
||||
env.insert(CHILD_ENV.to_string(), "1".to_string());
|
||||
let codex_utils_pty::SpawnedProcess {
|
||||
session: _session,
|
||||
mut stdout_rx,
|
||||
exit_rx,
|
||||
..
|
||||
} = codex_utils_pty::spawn_pty_process(
|
||||
executable.to_str().expect("UTF-8 test executable path"),
|
||||
&[
|
||||
TEST_NAME.to_string(),
|
||||
"--exact".to_string(),
|
||||
"--nocapture".to_string(),
|
||||
],
|
||||
&std::env::current_dir().expect("current test directory"),
|
||||
&env,
|
||||
/*arg0*/ &None,
|
||||
codex_utils_pty::TerminalSize::default(),
|
||||
codex_utils_pty::ChildFds::Inherited(&[]),
|
||||
)
|
||||
.await
|
||||
.expect("spawn test with a controlling terminal");
|
||||
|
||||
let (exit_code, output) = timeout(Duration::from_secs(10), async {
|
||||
let output = async {
|
||||
let mut output = Vec::new();
|
||||
while let Some(chunk) = stdout_rx.recv().await {
|
||||
output.extend_from_slice(&chunk);
|
||||
}
|
||||
output
|
||||
};
|
||||
tokio::join!(exit_rx, output)
|
||||
})
|
||||
.await
|
||||
.expect("terminal hook test should finish");
|
||||
let output = String::from_utf8_lossy(&output);
|
||||
assert_eq!(
|
||||
exit_code.expect("terminal hook test exit status"),
|
||||
0,
|
||||
"{output}"
|
||||
);
|
||||
assert!(
|
||||
output.contains(TEST_NAME),
|
||||
"child did not run test: {output}"
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
std::fs::File::open("/dev/tty").expect("test process must have a controlling terminal");
|
||||
let temp = tempdir().expect("create temp dir");
|
||||
let startup_path = temp.path().join("bashenv");
|
||||
std::fs::write(
|
||||
&startup_path,
|
||||
"command -v stty >/dev/null || exit 1\nstty sane < /dev/tty\n",
|
||||
)
|
||||
.expect("write shell startup fixture");
|
||||
let command = "printf hook-ran";
|
||||
let env = HashMap::from([(
|
||||
"BASH_ENV".to_string(),
|
||||
startup_path
|
||||
.to_str()
|
||||
.expect("UTF-8 startup path")
|
||||
.to_string(),
|
||||
)]);
|
||||
let handler = ConfiguredHandler {
|
||||
builtin: false,
|
||||
plugin_trust: None,
|
||||
event_name: HookEventName::SessionStart,
|
||||
matcher: None,
|
||||
timeout_sec: 2,
|
||||
status_message: None,
|
||||
additional_context_limit: Default::default(),
|
||||
source_path: AbsolutePathBuf::try_from(temp.path().join("hooks.json"))
|
||||
.expect("absolute hook configuration path")
|
||||
.into(),
|
||||
source: HookSource::User,
|
||||
display_order: 0,
|
||||
kind: ConfiguredHandlerKind::Command {
|
||||
command: command.to_string(),
|
||||
r#async: false,
|
||||
env: env.clone(),
|
||||
},
|
||||
};
|
||||
let (result_sender, _result_receiver) = async_channel::unbounded();
|
||||
let runtime = CommandHookRuntime::new(
|
||||
CommandShell {
|
||||
program: "/bin/bash".to_string(),
|
||||
args: vec!["-c".to_string()],
|
||||
},
|
||||
Arc::new(std::env::vars_os().collect()),
|
||||
ThreadId::new(),
|
||||
result_sender,
|
||||
);
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "macos"))]
|
||||
static FORKS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
|
||||
#[cfg(any(target_os = "linux", target_os = "macos"))]
|
||||
{
|
||||
use std::sync::atomic::Ordering;
|
||||
extern "C" fn record_parent_fork() {
|
||||
FORKS.fetch_add(1, Ordering::SeqCst);
|
||||
}
|
||||
// Registration cannot be undone, so keep it in this isolated TTY child.
|
||||
// SAFETY: The callback only updates a lock-free atomic in the parent.
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
libc::pthread_atfork(
|
||||
/*prepare*/ None,
|
||||
Some(record_parent_fork),
|
||||
/*child*/ None,
|
||||
)
|
||||
},
|
||||
0
|
||||
);
|
||||
let mut baseline = tokio::process::Command::new("/bin/sh");
|
||||
baseline.args(["-c", "exit 0"]);
|
||||
// SAFETY: A no-op callback forces fork for the positive control.
|
||||
unsafe {
|
||||
baseline.pre_exec(|| Ok(()));
|
||||
}
|
||||
assert!(baseline.status().await.expect("fork control").success());
|
||||
assert_eq!(FORKS.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
let result = run_command(&runtime, &handler, command, &env, "{}", temp.path()).await;
|
||||
#[cfg(any(target_os = "linux", target_os = "macos"))]
|
||||
{
|
||||
#[cfg(all(target_os = "linux", target_env = "gnu"))]
|
||||
let native_chdir_supported = {
|
||||
// SAFETY: Only inspect symbol availability, matching the launcher.
|
||||
!unsafe {
|
||||
libc::dlsym(
|
||||
libc::RTLD_DEFAULT,
|
||||
c"posix_spawn_file_actions_addchdir_np".as_ptr(),
|
||||
)
|
||||
}
|
||||
.is_null()
|
||||
};
|
||||
#[cfg(not(all(target_os = "linux", target_env = "gnu")))]
|
||||
let native_chdir_supported = true;
|
||||
if native_chdir_supported {
|
||||
assert_eq!(
|
||||
FORKS.load(std::sync::atomic::Ordering::SeqCst),
|
||||
1,
|
||||
"hook must avoid forking its parent"
|
||||
);
|
||||
}
|
||||
}
|
||||
assert_eq!(result.exit_code, Some(0), "stderr: {}", result.stderr);
|
||||
assert_eq!(result.stdout, "hook-ran");
|
||||
assert_eq!(result.error, None);
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[tokio::test]
|
||||
async fn cmd_shell_runs_quoted_hook_command_path() {
|
||||
let temp = tempdir().expect("create temp dir");
|
||||
let hook_dir = temp.path().join("hook with spaces");
|
||||
fs::create_dir(&hook_dir).expect("create hook dir");
|
||||
let hook_path = hook_dir.join("hook.cmd");
|
||||
fs::write(
|
||||
&hook_path,
|
||||
"@echo off\r\nif not \"%~1\"==\"notify\" exit /B 7\r\necho hook-ran\r\n",
|
||||
)
|
||||
.expect("write hook command");
|
||||
let source_path =
|
||||
AbsolutePathBuf::try_from(hook_path.clone()).expect("absolute hook command path");
|
||||
let command = format!(r#""{}" notify"#, hook_path.display());
|
||||
let env = HashMap::new();
|
||||
let handler = ConfiguredHandler {
|
||||
builtin: false,
|
||||
plugin_trust: None,
|
||||
event_name: HookEventName::SessionStart,
|
||||
matcher: None,
|
||||
timeout_sec: 10,
|
||||
status_message: None,
|
||||
additional_context_limit: Default::default(),
|
||||
source_path: source_path.into(),
|
||||
source: HookSource::User,
|
||||
display_order: 0,
|
||||
kind: ConfiguredHandlerKind::Command {
|
||||
command: command.clone(),
|
||||
r#async: false,
|
||||
env: env.clone(),
|
||||
},
|
||||
};
|
||||
let shells = [
|
||||
CommandShell {
|
||||
program: String::new(),
|
||||
args: Vec::new(),
|
||||
},
|
||||
CommandShell {
|
||||
program: std::env::var("COMSPEC").unwrap_or_else(|_| "cmd.exe".to_string()),
|
||||
args: vec!["/c".to_string()],
|
||||
},
|
||||
];
|
||||
|
||||
for shell in shells {
|
||||
let (result_sender, _result_receiver) = async_channel::unbounded();
|
||||
let runtime = CommandHookRuntime::new(
|
||||
shell,
|
||||
Arc::new(std::env::vars_os().collect()),
|
||||
ThreadId::new(),
|
||||
result_sender,
|
||||
);
|
||||
let result = run_command(&runtime, &handler, &command, &env, "{}", temp.path()).await;
|
||||
|
||||
assert_eq!(result.exit_code, Some(0), "stderr: {}", result.stderr);
|
||||
assert_eq!(result.stdout.trim(), "hook-ran");
|
||||
assert!(result.error.is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn fast_exiting_hook_preserves_stdout_when_stdin_is_not_consumed() {
|
||||
let temp = tempdir().expect("create temp dir");
|
||||
let source_path = AbsolutePathBuf::try_from(temp.path().join("hooks.json"))
|
||||
.expect("absolute hook configuration path");
|
||||
let command = "echo hook-ran";
|
||||
let env = HashMap::new();
|
||||
let handler = ConfiguredHandler {
|
||||
builtin: false,
|
||||
plugin_trust: None,
|
||||
event_name: HookEventName::SessionStart,
|
||||
matcher: None,
|
||||
timeout_sec: 10,
|
||||
status_message: None,
|
||||
additional_context_limit: Default::default(),
|
||||
source_path: source_path.into(),
|
||||
source: HookSource::User,
|
||||
display_order: 0,
|
||||
kind: ConfiguredHandlerKind::Command {
|
||||
command: command.to_string(),
|
||||
r#async: false,
|
||||
env: env.clone(),
|
||||
},
|
||||
};
|
||||
let input_json = format!(r#"{{"padding":"{}"}}"#, "x".repeat(1024 * 1024));
|
||||
let (runtime, _result_receiver) = runtime();
|
||||
|
||||
let result = run_command(&runtime, &handler, command, &env, &input_json, temp.path()).await;
|
||||
|
||||
assert_eq!(result.exit_code, Some(0), "stderr: {}", result.stderr);
|
||||
assert_eq!(result.stdout.trim(), "hook-ran");
|
||||
assert_eq!(result.error, None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn hook_drains_output_and_times_out_while_stdin_is_blocked() {
|
||||
let temp = tempdir().expect("create temp dir");
|
||||
let mut handler = write_handler(
|
||||
&temp,
|
||||
r#"from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
|
||||
sys.stdout.write("x" * 1024 * 1024)
|
||||
sys.stdout.flush()
|
||||
sys.stderr.write("x" * 1024 * 1024)
|
||||
sys.stderr.flush()
|
||||
Path("output-drained").touch()
|
||||
time.sleep(30)
|
||||
"#,
|
||||
);
|
||||
handler.timeout_sec = 2;
|
||||
let ConfiguredHandlerKind::Command { command, env, .. } = &handler.kind else {
|
||||
panic!("expected command hook");
|
||||
};
|
||||
let input_json = format!(r#"{{"padding":"{}"}}"#, "x".repeat(1024 * 1024));
|
||||
let (runtime, _result_receiver) = runtime();
|
||||
|
||||
// Keep user shell startup files out of the pipe I/O timeout test.
|
||||
let runtime = runtime.reconfigured(if cfg!(windows) {
|
||||
CommandShell {
|
||||
program: "cmd.exe".to_string(),
|
||||
args: vec!["/D".to_string(), "/C".to_string()],
|
||||
}
|
||||
} else {
|
||||
CommandShell {
|
||||
program: "/bin/sh".to_string(),
|
||||
args: vec!["-c".to_string()],
|
||||
}
|
||||
});
|
||||
|
||||
let result = timeout(
|
||||
Duration::from_secs(10),
|
||||
run_command(&runtime, &handler, command, env, &input_json, temp.path()),
|
||||
)
|
||||
.await
|
||||
.expect("the hook timeout must also cover blocked stdin writes");
|
||||
|
||||
assert!(temp.path().join("output-drained").exists());
|
||||
assert_eq!(result.exit_code, None);
|
||||
assert_eq!(result.error, Some("hook timed out after 2s".to_string()));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn command_hook_does_not_expose_configured_noise_auth_token() {
|
||||
let temp = tempdir().expect("create temp dir");
|
||||
let source_path = AbsolutePathBuf::try_from(temp.path().join("hooks.json"))
|
||||
.expect("absolute hook configuration path");
|
||||
let command = if cfg!(windows) { "set" } else { "env" };
|
||||
let env = HashMap::from([
|
||||
(
|
||||
CODEX_EXEC_SERVER_NOISE_AUTH_TOKEN_ENV_VAR.to_ascii_lowercase(),
|
||||
"configured-noise-token".to_string(),
|
||||
),
|
||||
("CODEX_HOOK_SAFE_ENV".to_string(), "visible".to_string()),
|
||||
]);
|
||||
let handler = ConfiguredHandler {
|
||||
builtin: false,
|
||||
plugin_trust: None,
|
||||
event_name: HookEventName::SessionStart,
|
||||
matcher: None,
|
||||
timeout_sec: 10,
|
||||
status_message: None,
|
||||
additional_context_limit: Default::default(),
|
||||
source_path: source_path.into(),
|
||||
source: HookSource::User,
|
||||
display_order: 0,
|
||||
kind: ConfiguredHandlerKind::Command {
|
||||
command: command.to_string(),
|
||||
r#async: false,
|
||||
env: env.clone(),
|
||||
},
|
||||
};
|
||||
let (runtime, _result_receiver) = runtime();
|
||||
|
||||
let result = run_command(&runtime, &handler, command, &env, "{}", temp.path()).await;
|
||||
|
||||
assert_eq!(result.exit_code, Some(0), "stderr: {}", result.stderr);
|
||||
assert!(result.stdout.contains("CODEX_HOOK_SAFE_ENV=visible"));
|
||||
assert!(!result.stdout.lines().any(|line| {
|
||||
line.split_once('=').is_some_and(|(name, _)| {
|
||||
name.eq_ignore_ascii_case(CODEX_EXEC_SERVER_NOISE_AUTH_TOKEN_ENV_VAR)
|
||||
})
|
||||
}));
|
||||
assert_eq!(result.error, None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn build_command_replays_snapshot_before_hook_overrides_and_scrubbing() {
|
||||
#[cfg(unix)]
|
||||
let non_unicode_value = OsString::from_vec(vec![b'v', 0xff]);
|
||||
let environment = vec![
|
||||
(
|
||||
OsString::from("CODEX_HOOK_SNAPSHOT"),
|
||||
OsString::from("captured"),
|
||||
),
|
||||
(
|
||||
OsString::from("CODEX_HOOK_OVERRIDE"),
|
||||
OsString::from("captured"),
|
||||
),
|
||||
(
|
||||
OsString::from(CODEX_EXEC_SERVER_NOISE_AUTH_TOKEN_ENV_VAR),
|
||||
OsString::from("captured-noise-token"),
|
||||
),
|
||||
#[cfg(unix)]
|
||||
(OsString::from("CODEX_HOOK_NON_UNICODE"), non_unicode_value),
|
||||
];
|
||||
let env = HashMap::from([
|
||||
("CODEX_HOOK_OVERRIDE".to_string(), "configured".to_string()),
|
||||
("CODEX_HOOK_SAFE_ENV".to_string(), "visible".to_string()),
|
||||
(
|
||||
CODEX_EXEC_SERVER_NOISE_AUTH_TOKEN_ENV_VAR.to_string(),
|
||||
"configured-noise-token".to_string(),
|
||||
),
|
||||
]);
|
||||
#[cfg(not(windows))]
|
||||
let (program, args, command_line) = (
|
||||
"/bin/sh",
|
||||
vec!["-c".to_string()],
|
||||
"printf '%s\\n' \"$CODEX_HOOK_SNAPSHOT\" \"$CODEX_HOOK_OVERRIDE\" \"$CODEX_HOOK_SAFE_ENV\" \"${CODEX_EXEC_SERVER_NOISE_AUTH_TOKEN-absent}\" \"$CODEX_HOOK_NON_UNICODE\"",
|
||||
);
|
||||
#[cfg(windows)]
|
||||
let (program, args, command_line) = (
|
||||
"cmd.exe",
|
||||
vec!["/D".to_string(), "/C".to_string()],
|
||||
"echo %CODEX_HOOK_SNAPSHOT%&echo %CODEX_HOOK_OVERRIDE%&echo %CODEX_HOOK_SAFE_ENV%&if defined CODEX_EXEC_SERVER_NOISE_AUTH_TOKEN (echo leaked) else (echo absent)",
|
||||
);
|
||||
let command = build_command(
|
||||
&CommandShell {
|
||||
program: program.to_string(),
|
||||
args,
|
||||
},
|
||||
command_line,
|
||||
&environment,
|
||||
&env,
|
||||
);
|
||||
#[cfg(not(unix))]
|
||||
let mut command = command;
|
||||
let output = command
|
||||
.spawn()
|
||||
.expect("spawn hook")
|
||||
.wait_with_output()
|
||||
.await
|
||||
.expect("hook output");
|
||||
assert!(output.status.success(), "{output:?}");
|
||||
#[cfg(unix)]
|
||||
assert_eq!(
|
||||
output.stdout,
|
||||
b"captured\nconfigured\nvisible\nabsent\nv\xff\n"
|
||||
);
|
||||
#[cfg(windows)]
|
||||
assert_eq!(
|
||||
output.stdout,
|
||||
b"captured\r\nconfigured\r\nvisible\r\nabsent\r\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fallback_shell_uses_snapshot() {
|
||||
#[cfg(windows)]
|
||||
let (name, program) = ("comspec", r"C:\captured\cmd.exe");
|
||||
#[cfg(not(windows))]
|
||||
let (name, program) = ("SHELL", "/captured/shell");
|
||||
assert_eq!(
|
||||
default_shell_program(&[(OsString::from(name), OsString::from(program))]),
|
||||
OsString::from(program),
|
||||
);
|
||||
}
|
||||
|
||||
const ASYNC_HOOK_TEST_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
|
||||
fn runtime() -> (CommandHookRuntime, Receiver<HookCompletedEvent>) {
|
||||
runtime_with_environment(Arc::new(std::env::vars_os().collect()))
|
||||
}
|
||||
|
||||
fn runtime_with_environment(
|
||||
environment: Arc<Vec<(OsString, OsString)>>,
|
||||
) -> (CommandHookRuntime, Receiver<HookCompletedEvent>) {
|
||||
let thread_id = ThreadId::new();
|
||||
let (result_sender, result_receiver) = async_channel::unbounded();
|
||||
let runtime = CommandHookRuntime::new(
|
||||
CommandShell {
|
||||
program: String::new(),
|
||||
args: Vec::new(),
|
||||
},
|
||||
environment,
|
||||
thread_id,
|
||||
result_sender,
|
||||
);
|
||||
(runtime, result_receiver)
|
||||
}
|
||||
|
||||
fn write_handler(temp: &TempDir, source: &str) -> ConfiguredHandler {
|
||||
let script_path = temp.path().join("async_hook.py");
|
||||
std::fs::write(&script_path, source).expect("write async test hook");
|
||||
ConfiguredHandler {
|
||||
builtin: false,
|
||||
plugin_trust: None,
|
||||
event_name: HookEventName::UserPromptSubmit,
|
||||
matcher: None,
|
||||
timeout_sec: 10,
|
||||
status_message: None,
|
||||
additional_context_limit: Default::default(),
|
||||
source_path: AbsolutePathBuf::try_from(temp.path().join("hooks.json"))
|
||||
.expect("absolute test hook path")
|
||||
.into(),
|
||||
source: HookSource::User,
|
||||
display_order: 0,
|
||||
kind: ConfiguredHandlerKind::Command {
|
||||
command: format!("python3 {}", script_path.display()),
|
||||
r#async: true,
|
||||
env: HashMap::new(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
async fn schedule(runtime: &CommandHookRuntime, handler: ConfiguredHandler, cwd: &Path) {
|
||||
let engine = ClaudeHooksEngine {
|
||||
enabled: true,
|
||||
handlers: Arc::new(vec![handler]),
|
||||
hook_entries: Default::default(),
|
||||
warnings: Arc::default(),
|
||||
required_load_errors: Arc::default(),
|
||||
command_runtime: runtime.clone(),
|
||||
mcp_executor: mcp_executor(),
|
||||
};
|
||||
engine
|
||||
.run_user_prompt_submit(UserPromptSubmitRequest {
|
||||
session_id: ThreadId::new(),
|
||||
turn_id: "async-test-turn".to_string(),
|
||||
subagent: None,
|
||||
cwd: AbsolutePathBuf::try_from(cwd.to_path_buf()).expect("absolute test hook cwd"),
|
||||
transcript_path: None,
|
||||
model: "test-model".to_string(),
|
||||
permission_mode: "default".to_string(),
|
||||
prompt: "test prompt".to_string(),
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn async_hook_marks_invalid_structured_output_as_failed() {
|
||||
let temp = TempDir::new().expect("async test directory");
|
||||
let (runtime, results) = runtime();
|
||||
let handler = write_handler(
|
||||
&temp,
|
||||
r#"import sys
|
||||
|
||||
sys.stdin.read()
|
||||
print('{"systemMessage": 123}')
|
||||
"#,
|
||||
);
|
||||
|
||||
schedule(&runtime, handler, temp.path()).await;
|
||||
let hook_result = timeout(ASYNC_HOOK_TEST_TIMEOUT, results.recv())
|
||||
.await
|
||||
.expect("invalid async output should still finish its background task")
|
||||
.expect("result receiver should remain open");
|
||||
|
||||
assert_eq!(hook_result.run.status, HookRunStatus::Failed);
|
||||
assert_eq!(
|
||||
hook_result.run.entries,
|
||||
vec![HookOutputEntry {
|
||||
kind: HookOutputEntryKind::Error,
|
||||
text: "hook returned invalid user prompt submit JSON output".to_string(),
|
||||
}]
|
||||
);
|
||||
|
||||
runtime.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn async_hook_result_survives_runtime_reconfiguration() {
|
||||
let temp = TempDir::new().expect("async test directory");
|
||||
let mut environment = std::env::vars_os().collect::<Vec<_>>();
|
||||
environment.push((
|
||||
OsString::from("CODEX_HOOK_CAPTURED_ENV"),
|
||||
OsString::from("captured"),
|
||||
));
|
||||
let (previous, results) = runtime_with_environment(Arc::new(environment));
|
||||
let release_path = temp.path().join("release");
|
||||
let handler = write_handler(
|
||||
&temp,
|
||||
&format!(
|
||||
r#"import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
|
||||
json.load(sys.stdin)
|
||||
while not Path(r"{}").exists():
|
||||
time.sleep(0.01)
|
||||
print(os.environ["CODEX_HOOK_CAPTURED_ENV"])
|
||||
"#,
|
||||
release_path.display()
|
||||
),
|
||||
);
|
||||
schedule(&previous, handler, temp.path()).await;
|
||||
|
||||
let reconfigured = previous.reconfigured(CommandShell {
|
||||
program: String::new(),
|
||||
args: Vec::new(),
|
||||
});
|
||||
assert!(Arc::ptr_eq(
|
||||
&previous.environment,
|
||||
&reconfigured.environment
|
||||
));
|
||||
std::fs::write(release_path, "ready").expect("release async hook");
|
||||
|
||||
let hook_result = timeout(ASYNC_HOOK_TEST_TIMEOUT, results.recv())
|
||||
.await
|
||||
.expect("in-flight hook should survive runtime reconfiguration")
|
||||
.expect("result receiver should remain open");
|
||||
assert_eq!(
|
||||
hook_result.run.entries,
|
||||
vec![HookOutputEntry {
|
||||
kind: HookOutputEntryKind::Context,
|
||||
text: "captured".to_string(),
|
||||
}]
|
||||
);
|
||||
|
||||
reconfigured.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn async_hooks_limit_concurrent_processes_without_dropping_waiting_jobs() {
|
||||
let temp = TempDir::new().expect("async test directory");
|
||||
let (runtime, results) = runtime();
|
||||
let started_dir = temp.path().join("started");
|
||||
let release_path = temp.path().join("release");
|
||||
std::fs::create_dir(&started_dir).expect("create hook marker directory");
|
||||
let mut handler = write_handler(
|
||||
&temp,
|
||||
&format!(
|
||||
r#"import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
|
||||
sys.stdin.read()
|
||||
Path(r"{started}", str(os.getpid())).touch()
|
||||
while not Path(r"{release}").exists():
|
||||
time.sleep(0.01)
|
||||
print("{{}}")
|
||||
"#,
|
||||
started = started_dir.display(),
|
||||
release = release_path.display(),
|
||||
),
|
||||
);
|
||||
handler.timeout_sec = ASYNC_HOOK_TEST_TIMEOUT.as_secs();
|
||||
|
||||
for _ in 0..=MAX_CONCURRENT_ASYNC_HOOKS {
|
||||
schedule(&runtime, handler.clone(), temp.path()).await;
|
||||
}
|
||||
|
||||
let started_count = || {
|
||||
std::fs::read_dir(&started_dir)
|
||||
.expect("read hook marker directory")
|
||||
.count()
|
||||
};
|
||||
timeout(ASYNC_HOOK_TEST_TIMEOUT, async {
|
||||
while started_count() < MAX_CONCURRENT_ASYNC_HOOKS {
|
||||
sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("all available async hook slots should start");
|
||||
assert_eq!(started_count(), MAX_CONCURRENT_ASYNC_HOOKS);
|
||||
|
||||
std::fs::write(release_path, "ready").expect("release running async hooks");
|
||||
for _ in 0..=MAX_CONCURRENT_ASYNC_HOOKS {
|
||||
timeout(ASYNC_HOOK_TEST_TIMEOUT, results.recv())
|
||||
.await
|
||||
.expect("waiting async hook should eventually finish")
|
||||
.expect("result receiver should remain open");
|
||||
}
|
||||
assert_eq!(started_count(), MAX_CONCURRENT_ASYNC_HOOKS + 1);
|
||||
|
||||
runtime.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn shutdown_aborts_in_flight_async_hooks_without_delivering_context() {
|
||||
let temp = TempDir::new().expect("async test directory");
|
||||
let (runtime, results) = runtime();
|
||||
let started_path = temp.path().join("started");
|
||||
let release_path = temp.path().join("release");
|
||||
let handler = write_handler(
|
||||
&temp,
|
||||
&format!(
|
||||
r#"import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
|
||||
json.load(sys.stdin)
|
||||
Path(r"{started}").write_text("started", encoding="utf-8")
|
||||
while not Path(r"{release}").exists():
|
||||
time.sleep(0.01)
|
||||
print(json.dumps({{
|
||||
"hookSpecificOutput": {{
|
||||
"hookEventName": "UserPromptSubmit",
|
||||
"additionalContext": "must not be delivered after shutdown"
|
||||
}}
|
||||
}}))
|
||||
"#,
|
||||
started = started_path.display(),
|
||||
release = release_path.display(),
|
||||
),
|
||||
);
|
||||
schedule(&runtime, handler, temp.path()).await;
|
||||
|
||||
timeout(ASYNC_HOOK_TEST_TIMEOUT, async {
|
||||
while !started_path.exists() {
|
||||
sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("async hook should start before runtime shutdown");
|
||||
|
||||
runtime.shutdown().await;
|
||||
drop(runtime);
|
||||
std::fs::write(release_path, "ready").expect("release shutdown hook");
|
||||
assert!(
|
||||
timeout(Duration::from_millis(150), results.recv())
|
||||
.await
|
||||
.expect("shutdown should close the result channel")
|
||||
.is_err(),
|
||||
"shutdown must not deliver a late async result"
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
async fn process_is_running(pid: &str) -> bool {
|
||||
let output = tokio::process::Command::new("ps")
|
||||
.args(["-p", pid, "-o", "stat="])
|
||||
.output()
|
||||
.await
|
||||
.expect("inspect hook process state");
|
||||
assert!(output.stderr.is_empty(), "{output:?}");
|
||||
assert!(output.status.success() || output.status.code() == Some(1));
|
||||
String::from_utf8_lossy(&output.stdout)
|
||||
.split_whitespace()
|
||||
.any(|state| !state.starts_with('Z'))
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn cancelled_and_timed_out_hooks_kill_their_process_group() {
|
||||
enum Termination {
|
||||
Cancellation,
|
||||
Timeout,
|
||||
}
|
||||
|
||||
for termination in [Termination::Cancellation, Termination::Timeout] {
|
||||
let temp = tempdir().expect("create temp dir");
|
||||
let mut handler = write_handler(
|
||||
&temp,
|
||||
r#"import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
child = subprocess.Popen(['sleep', '60'])
|
||||
Path('hook-pids.tmp').write_text(f'{os.getpid()} {child.pid}')
|
||||
Path('hook-pids.tmp').rename('hook-pids')
|
||||
time.sleep(60)
|
||||
"#,
|
||||
);
|
||||
handler.timeout_sec = 2;
|
||||
let ConfiguredHandlerKind::Command { command, env, .. } = &handler.kind else {
|
||||
panic!("expected command hook");
|
||||
};
|
||||
let (mut runtime, _result_receiver) = runtime();
|
||||
runtime.shell.program = "/bin/sh".into();
|
||||
runtime.shell.args = vec!["-c".into()];
|
||||
let mut run = Box::pin(run_command(
|
||||
&runtime,
|
||||
&handler,
|
||||
command,
|
||||
env,
|
||||
"{}",
|
||||
temp.path(),
|
||||
));
|
||||
let pids = timeout(Duration::from_secs(10), async {
|
||||
loop {
|
||||
if let Ok(pids) = std::fs::read_to_string(temp.path().join("hook-pids")) {
|
||||
break pids;
|
||||
}
|
||||
tokio::select! {
|
||||
result = &mut run => panic!("hook exited before cancellation: {result:?}"),
|
||||
_ = sleep(Duration::from_millis(10)) => {}
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("hook and descendant must start");
|
||||
match termination {
|
||||
Termination::Cancellation => drop(run),
|
||||
Termination::Timeout => {
|
||||
let result = timeout(Duration::from_secs(10), run)
|
||||
.await
|
||||
.expect("hook timeout completes");
|
||||
assert_eq!(result.error, Some("hook timed out after 2s".to_string()));
|
||||
}
|
||||
}
|
||||
timeout(Duration::from_secs(10), async {
|
||||
loop {
|
||||
let mut all_stopped = true;
|
||||
for pid in pids.split_whitespace() {
|
||||
all_stopped &= !process_is_running(pid).await;
|
||||
}
|
||||
if all_stopped {
|
||||
break;
|
||||
}
|
||||
sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("cancellation and timeout must stop both hook and descendant");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn completed_hook_preserves_background_descendant() {
|
||||
for exit_code in [0, 23] {
|
||||
let temp = tempdir().expect("create temp dir");
|
||||
let handler = write_handler(
|
||||
&temp,
|
||||
&format!(
|
||||
r#"import subprocess
|
||||
|
||||
subprocess.Popen(
|
||||
['sh', '-c', 'i=0; while [ ! -f release-descendant ] && [ "$i" -lt 500 ]; do sleep 0.01; i=$((i + 1)); done; printf survived > descendant-result.tmp; mv descendant-result.tmp descendant-result'],
|
||||
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
raise SystemExit({exit_code})
|
||||
"#
|
||||
),
|
||||
);
|
||||
let ConfiguredHandlerKind::Command { command, env, .. } = &handler.kind else {
|
||||
panic!("expected command hook");
|
||||
};
|
||||
let (mut runtime, _result_receiver) = runtime();
|
||||
runtime.shell.program = "/bin/sh".into();
|
||||
runtime.shell.args = vec!["-c".into()];
|
||||
let result = run_command(&runtime, &handler, command, env, "{}", temp.path()).await;
|
||||
// Release even on a failed assertion so a failed test does not leak a waiter.
|
||||
std::fs::write(temp.path().join("release-descendant"), "").expect("release descendant");
|
||||
assert_eq!((result.exit_code, result.error), (Some(exit_code), None));
|
||||
let result_path = temp.path().join("descendant-result");
|
||||
timeout(Duration::from_secs(10), async {
|
||||
while !result_path.exists() {
|
||||
sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("completed hook must leave its descendant running");
|
||||
assert_eq!(std::fs::read_to_string(result_path).unwrap(), "survived");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn exited_hook_leader_with_open_descendant_output_still_times_out() {
|
||||
let temp = tempdir().expect("create temp dir");
|
||||
let mut handler = write_handler(
|
||||
&temp,
|
||||
r#"from pathlib import Path
|
||||
import subprocess
|
||||
|
||||
child = subprocess.Popen(['sleep', '60'])
|
||||
Path('descendant-pid').write_text(str(child.pid))
|
||||
"#,
|
||||
);
|
||||
handler.timeout_sec = 2;
|
||||
let ConfiguredHandlerKind::Command { command, env, .. } = &handler.kind else {
|
||||
panic!("expected command hook");
|
||||
};
|
||||
let (mut runtime, _result_receiver) = runtime();
|
||||
runtime.shell.program = "/bin/sh".into();
|
||||
runtime.shell.args = vec!["-c".into()];
|
||||
let result = run_command(&runtime, &handler, command, env, "{}", temp.path()).await;
|
||||
assert_eq!(result.error, Some("hook timed out after 2s".to_string()));
|
||||
let pid = std::fs::read_to_string(temp.path().join("descendant-pid"))
|
||||
.expect("descendant started before its parent exited");
|
||||
timeout(Duration::from_secs(10), async {
|
||||
while process_is_running(pid.trim()).await {
|
||||
sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("hook timeout must stop the descendant after the leader exits");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn hook_rejects_nul_arguments_before_execution() {
|
||||
for nul_in_shell_args in [false, true] {
|
||||
let root = tempdir().expect("tempdir");
|
||||
let (mut runtime, _receiver) = runtime();
|
||||
runtime.shell = CommandShell {
|
||||
program: "/usr/bin/touch".to_string(),
|
||||
args: if nul_in_shell_args {
|
||||
vec!["bad\0arg".to_string()]
|
||||
} else {
|
||||
Vec::new()
|
||||
},
|
||||
};
|
||||
let command = if nul_in_shell_args { "ran" } else { "bad\0arg" };
|
||||
let handler = write_handler(&root, "");
|
||||
let result = run_command(
|
||||
&runtime,
|
||||
&handler,
|
||||
command,
|
||||
&HashMap::new(),
|
||||
"",
|
||||
root.path(),
|
||||
)
|
||||
.await;
|
||||
assert!(result.error.is_some(), "invalid hook ran: {result:?}");
|
||||
assert_eq!(result.exit_code, None);
|
||||
assert!(!root.path().join("ran").exists());
|
||||
assert!(!root.path().join("<string-with-nul>").exists());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn hook_rejects_nul_in_configured_and_default_shell_program() {
|
||||
for configured in [false, true] {
|
||||
let root = tempdir().expect("tempdir");
|
||||
let (mut runtime, _receiver) = runtime_with_environment(Arc::new(vec![(
|
||||
OsString::from("SHELL"),
|
||||
OsString::from("/bin/sh\0"),
|
||||
)]));
|
||||
if configured {
|
||||
runtime.shell.program = "/bin/sh\0".to_string();
|
||||
}
|
||||
let handler = write_handler(&root, "");
|
||||
let result = run_command(
|
||||
&runtime,
|
||||
&handler,
|
||||
"printf ran > ran",
|
||||
&HashMap::new(),
|
||||
"",
|
||||
root.path(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
result.error.as_deref(),
|
||||
Some("nul byte found in provided data")
|
||||
);
|
||||
assert_eq!(result.exit_code, None);
|
||||
assert!(!root.path().join("ran").exists());
|
||||
}
|
||||
}
|
||||
1963
codex-rs/hooks/src/engine/discovery.rs
Normal file
1963
codex-rs/hooks/src/engine/discovery.rs
Normal file
File diff suppressed because it is too large
Load Diff
683
codex-rs/hooks/src/engine/dispatcher.rs
Normal file
683
codex-rs/hooks/src/engine/dispatcher.rs
Normal file
@@ -0,0 +1,683 @@
|
||||
use std::path::Path;
|
||||
|
||||
use futures::StreamExt;
|
||||
use futures::stream::FuturesUnordered;
|
||||
use serde_json::Map;
|
||||
use serde_json::Value;
|
||||
|
||||
use codex_protocol::protocol::HookCompletedEvent;
|
||||
use codex_protocol::protocol::HookEventName;
|
||||
use codex_protocol::protocol::HookExecutionMode;
|
||||
use codex_protocol::protocol::HookHandlerType;
|
||||
use codex_protocol::protocol::HookRunStatus;
|
||||
use codex_protocol::protocol::HookRunSummary;
|
||||
use codex_protocol::protocol::HookScope;
|
||||
|
||||
use super::ClaudeHooksEngine;
|
||||
use super::ConfiguredHandler;
|
||||
use super::ConfiguredHandlerKind;
|
||||
use super::HandlerRunResult;
|
||||
use super::HandlerSourcePath;
|
||||
use super::command_runner::run_command;
|
||||
use super::mcp_runner::run_mcp_tool;
|
||||
use crate::events::common::matches_matcher;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct ParsedHandler<T> {
|
||||
pub completed: HookCompletedEvent,
|
||||
pub data: T,
|
||||
pub completion_order: usize,
|
||||
}
|
||||
|
||||
pub(crate) fn select_handlers(
|
||||
handlers: &[ConfiguredHandler],
|
||||
event_name: HookEventName,
|
||||
matcher_input: Option<&str>,
|
||||
) -> Vec<ConfiguredHandler> {
|
||||
let matcher_inputs = matcher_input.into_iter().collect::<Vec<_>>();
|
||||
select_handlers_for_matcher_inputs(handlers, event_name, &matcher_inputs)
|
||||
}
|
||||
|
||||
pub(crate) fn select_handlers_for_matcher_inputs(
|
||||
handlers: &[ConfiguredHandler],
|
||||
event_name: HookEventName,
|
||||
matcher_inputs: &[&str],
|
||||
) -> Vec<ConfiguredHandler> {
|
||||
// Check each configured handler once, even when several compatibility names
|
||||
// match the same regex. A hook like `apply_patch|Write|Edit` should run a
|
||||
// single time for one tool call, not once per matching alias.
|
||||
handlers
|
||||
.iter()
|
||||
.filter(|handler| handler.event_name == event_name)
|
||||
.filter(|handler| match event_name {
|
||||
HookEventName::PreToolUse
|
||||
| HookEventName::PermissionRequest
|
||||
| HookEventName::PostToolUse
|
||||
| HookEventName::SessionStart
|
||||
| HookEventName::SessionEnd
|
||||
| HookEventName::SubagentStart
|
||||
| HookEventName::SubagentStop
|
||||
| HookEventName::PreCompact
|
||||
| HookEventName::PostCompact => {
|
||||
if matcher_inputs.is_empty() {
|
||||
matches_matcher(handler.matcher.as_ref(), /*input*/ None)
|
||||
} else {
|
||||
matcher_inputs
|
||||
.iter()
|
||||
.any(|input| matches_matcher(handler.matcher.as_ref(), Some(input)))
|
||||
}
|
||||
}
|
||||
HookEventName::PreModelRequest
|
||||
| HookEventName::PostModelRequest
|
||||
| HookEventName::UserPromptSubmit
|
||||
| HookEventName::Stop
|
||||
| HookEventName::Interrupt => true,
|
||||
})
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(crate) fn running_summary(handler: &ConfiguredHandler) -> HookRunSummary {
|
||||
let source_path = match &handler.source_path {
|
||||
HandlerSourcePath::Local(path) => path.clone().into(),
|
||||
HandlerSourcePath::Environment {
|
||||
source_path: path, ..
|
||||
} => path.clone().into(),
|
||||
HandlerSourcePath::ExecutorScoped { .. } => {
|
||||
unreachable!("executor-scoped hooks do not produce public hook summaries")
|
||||
}
|
||||
};
|
||||
HookRunSummary {
|
||||
builtin: handler.builtin,
|
||||
id: handler.run_id(),
|
||||
event_name: handler.event_name,
|
||||
handler_type: handler.handler_type(),
|
||||
execution_mode: handler.execution_mode(),
|
||||
scope: scope_for_event(handler.event_name),
|
||||
source_path,
|
||||
source: handler.source,
|
||||
display_order: handler.display_order,
|
||||
status: HookRunStatus::Running,
|
||||
status_message: handler.status_message.clone(),
|
||||
started_at: chrono::Utc::now().timestamp(),
|
||||
completed_at: None,
|
||||
duration_ms: None,
|
||||
entries: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn execute_handlers<T: 'static>(
|
||||
engine: &ClaudeHooksEngine,
|
||||
handlers: Vec<ConfiguredHandler>,
|
||||
input: &Value,
|
||||
cwd: &Path,
|
||||
turn_id: Option<String>,
|
||||
parse: fn(&ConfiguredHandler, HandlerRunResult, Option<String>) -> ParsedHandler<T>,
|
||||
) -> Vec<ParsedHandler<T>> {
|
||||
execute_handlers_with_metadata(
|
||||
engine, handlers, input, cwd, turn_id, /*metadata*/ None, parse,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(crate) async fn execute_handlers_with_metadata<T: 'static>(
|
||||
engine: &ClaudeHooksEngine,
|
||||
handlers: Vec<ConfiguredHandler>,
|
||||
input: &Value,
|
||||
cwd: &Path,
|
||||
turn_id: Option<String>,
|
||||
metadata: Option<&Map<String, Value>>,
|
||||
parse: fn(&ConfiguredHandler, HandlerRunResult, Option<String>) -> ParsedHandler<T>,
|
||||
) -> Vec<ParsedHandler<T>> {
|
||||
let mut executor_handlers = Vec::new();
|
||||
let mut pending = FuturesUnordered::new();
|
||||
for (configured_order, handler) in handlers.into_iter().enumerate() {
|
||||
if matches!(
|
||||
handler.source_path,
|
||||
HandlerSourcePath::ExecutorScoped { .. }
|
||||
) {
|
||||
executor_handlers.push(handler);
|
||||
continue;
|
||||
}
|
||||
let event_input = handler.source_path.event_input(input);
|
||||
if handler.execution_mode() == HookExecutionMode::Async {
|
||||
engine.command_runtime.schedule_async_hook(
|
||||
engine.clone(),
|
||||
handler,
|
||||
event_input.into_owned(),
|
||||
cwd.to_path_buf(),
|
||||
turn_id.clone(),
|
||||
parse,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
let turn_id = turn_id.clone();
|
||||
pending.push(async move {
|
||||
let result =
|
||||
execute_handler(engine, &handler, &event_input, cwd, /*metadata*/ None).await;
|
||||
let parsed = parse(&handler, result, turn_id);
|
||||
(configured_order, parsed)
|
||||
});
|
||||
}
|
||||
|
||||
let mut completed = Vec::new();
|
||||
let mut completion_order = 0;
|
||||
let mut should_stop = false;
|
||||
let mut should_block = false;
|
||||
while let Some((configured_order, mut parsed)) = pending.next().await {
|
||||
should_stop |= parsed.completed.run.status == HookRunStatus::Stopped;
|
||||
should_block |= parsed.completed.run.status == HookRunStatus::Blocked;
|
||||
parsed.completion_order = completion_order;
|
||||
completion_order += 1;
|
||||
completed.push((configured_order, parsed));
|
||||
}
|
||||
completed.sort_by_key(|(configured_order, _)| *configured_order);
|
||||
|
||||
if should_stop || !should_block {
|
||||
for handler in executor_handlers {
|
||||
let task_engine = engine.clone();
|
||||
let event_input = input.clone();
|
||||
let cwd = cwd.to_path_buf();
|
||||
let metadata = metadata.cloned();
|
||||
engine.command_runtime.schedule_async_task(async move {
|
||||
let result = execute_handler(
|
||||
&task_engine,
|
||||
&handler,
|
||||
&event_input,
|
||||
&cwd,
|
||||
metadata.as_ref(),
|
||||
)
|
||||
.await;
|
||||
if let Some(error) = result.error {
|
||||
tracing::warn!(
|
||||
source_path = %handler.source_path,
|
||||
%error,
|
||||
"executor-scoped hook failed"
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
completed.into_iter().map(|(_, parsed)| parsed).collect()
|
||||
}
|
||||
|
||||
pub(super) async fn execute_handler(
|
||||
engine: &ClaudeHooksEngine,
|
||||
handler: &ConfiguredHandler,
|
||||
event_input: &Value,
|
||||
cwd: &Path,
|
||||
metadata: Option<&Map<String, Value>>,
|
||||
) -> HandlerRunResult {
|
||||
match &handler.kind {
|
||||
ConfiguredHandlerKind::Command { command, env, .. } => {
|
||||
run_command(
|
||||
&engine.command_runtime,
|
||||
handler,
|
||||
command,
|
||||
env,
|
||||
&event_input.to_string(),
|
||||
cwd,
|
||||
)
|
||||
.await
|
||||
}
|
||||
ConfiguredHandlerKind::McpTool {
|
||||
server,
|
||||
tool,
|
||||
input,
|
||||
} => {
|
||||
run_mcp_tool(
|
||||
engine.mcp_executor.as_ref(),
|
||||
handler,
|
||||
server,
|
||||
tool,
|
||||
input,
|
||||
event_input,
|
||||
metadata,
|
||||
)
|
||||
.await
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn completed_summary(
|
||||
handler: &ConfiguredHandler,
|
||||
run_result: &HandlerRunResult,
|
||||
status: HookRunStatus,
|
||||
entries: Vec<codex_protocol::protocol::HookOutputEntry>,
|
||||
) -> HookRunSummary {
|
||||
let source_path = match &handler.source_path {
|
||||
HandlerSourcePath::Local(path) => path.clone().into(),
|
||||
HandlerSourcePath::Environment {
|
||||
source_path: path, ..
|
||||
} => path.clone().into(),
|
||||
HandlerSourcePath::ExecutorScoped { .. } => {
|
||||
unreachable!("executor-scoped hooks do not produce public hook summaries")
|
||||
}
|
||||
};
|
||||
HookRunSummary {
|
||||
builtin: handler.builtin,
|
||||
id: handler.run_id(),
|
||||
event_name: handler.event_name,
|
||||
handler_type: handler.handler_type(),
|
||||
execution_mode: handler.execution_mode(),
|
||||
scope: scope_for_event(handler.event_name),
|
||||
source_path,
|
||||
source: handler.source,
|
||||
display_order: handler.display_order,
|
||||
status,
|
||||
status_message: handler.status_message.clone(),
|
||||
started_at: run_result.started_at,
|
||||
completed_at: Some(run_result.completed_at),
|
||||
duration_ms: Some(run_result.duration_ms),
|
||||
entries,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn scope_for_event(event_name: HookEventName) -> HookScope {
|
||||
match event_name {
|
||||
HookEventName::SessionStart | HookEventName::SessionEnd | HookEventName::SubagentStart => {
|
||||
HookScope::Thread
|
||||
}
|
||||
HookEventName::PreToolUse
|
||||
| HookEventName::PermissionRequest
|
||||
| HookEventName::PostToolUse
|
||||
| HookEventName::PreCompact
|
||||
| HookEventName::PostCompact
|
||||
| HookEventName::UserPromptSubmit
|
||||
| HookEventName::SubagentStop
|
||||
| HookEventName::Stop
|
||||
| HookEventName::PreModelRequest
|
||||
| HookEventName::PostModelRequest
|
||||
| HookEventName::Interrupt => HookScope::Turn,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn hook_event_name_label(event_name: HookEventName) -> &'static str {
|
||||
match event_name {
|
||||
HookEventName::PreToolUse => "PreToolUse",
|
||||
HookEventName::PermissionRequest => "PermissionRequest",
|
||||
HookEventName::PostToolUse => "PostToolUse",
|
||||
HookEventName::PreCompact => "PreCompact",
|
||||
HookEventName::PostCompact => "PostCompact",
|
||||
HookEventName::PreModelRequest => "PreModelRequest",
|
||||
HookEventName::PostModelRequest => "PostModelRequest",
|
||||
HookEventName::SessionStart => "SessionStart",
|
||||
HookEventName::SessionEnd => "SessionEnd",
|
||||
HookEventName::UserPromptSubmit => "UserPromptSubmit",
|
||||
HookEventName::SubagentStart => "SubagentStart",
|
||||
HookEventName::SubagentStop => "SubagentStop",
|
||||
HookEventName::Stop => "Stop",
|
||||
HookEventName::Interrupt => "Interrupt",
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the canonical label for a hook execution mode.
|
||||
pub fn hook_execution_mode_label(mode: HookExecutionMode) -> &'static str {
|
||||
match mode {
|
||||
HookExecutionMode::Sync => "sync",
|
||||
HookExecutionMode::Async => "async",
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the canonical label for a hook handler type.
|
||||
pub fn hook_handler_type_label(handler_type: HookHandlerType) -> &'static str {
|
||||
match handler_type {
|
||||
HookHandlerType::Command => "command",
|
||||
HookHandlerType::McpTool => "mcp_tool",
|
||||
HookHandlerType::Prompt => "prompt",
|
||||
HookHandlerType::Agent => "agent",
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn hook_scope_label(scope: HookScope) -> &'static str {
|
||||
match scope {
|
||||
HookScope::Thread => "thread",
|
||||
HookScope::Turn => "turn",
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn hook_source_label(source: codex_protocol::protocol::HookSource) -> &'static str {
|
||||
match source {
|
||||
codex_protocol::protocol::HookSource::System => "system",
|
||||
codex_protocol::protocol::HookSource::User => "user",
|
||||
codex_protocol::protocol::HookSource::Project => "project",
|
||||
codex_protocol::protocol::HookSource::Mdm => "mdm",
|
||||
codex_protocol::protocol::HookSource::SessionFlags => "session_flags",
|
||||
codex_protocol::protocol::HookSource::Plugin => "plugin",
|
||||
codex_protocol::protocol::HookSource::CloudRequirements => "cloud_requirements",
|
||||
codex_protocol::protocol::HookSource::CloudManagedConfig => "cloud_managed_config",
|
||||
codex_protocol::protocol::HookSource::LegacyManagedConfigFile => {
|
||||
"legacy_managed_config_file"
|
||||
}
|
||||
codex_protocol::protocol::HookSource::LegacyManagedConfigMdm => "legacy_managed_config_mdm",
|
||||
codex_protocol::protocol::HookSource::Unknown => "unknown",
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use codex_protocol::protocol::HookEventName;
|
||||
use codex_protocol::protocol::HookSource;
|
||||
use codex_utils_absolute_path::test_support::PathBufExt;
|
||||
use codex_utils_absolute_path::test_support::test_path_buf;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::ConfiguredHandler;
|
||||
use super::ConfiguredHandlerKind;
|
||||
use super::select_handlers;
|
||||
use super::select_handlers_for_matcher_inputs;
|
||||
|
||||
fn make_handler(
|
||||
event_name: HookEventName,
|
||||
matcher: Option<&str>,
|
||||
command: &str,
|
||||
display_order: i64,
|
||||
) -> ConfiguredHandler {
|
||||
ConfiguredHandler {
|
||||
builtin: false,
|
||||
plugin_trust: None,
|
||||
event_name,
|
||||
matcher: matcher
|
||||
.map(|pattern| crate::engine::HookMatcher::new(pattern).expect("valid matcher")),
|
||||
timeout_sec: 5,
|
||||
status_message: None,
|
||||
additional_context_limit: Default::default(),
|
||||
source_path: test_path_buf("/tmp/hooks.json").abs().into(),
|
||||
source: HookSource::User,
|
||||
display_order,
|
||||
kind: ConfiguredHandlerKind::Command {
|
||||
command: command.to_string(),
|
||||
r#async: false,
|
||||
env: std::collections::HashMap::new(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_handlers_keeps_duplicate_stop_handlers() {
|
||||
let handlers = vec![
|
||||
make_handler(
|
||||
HookEventName::Stop,
|
||||
/*matcher*/ None,
|
||||
"echo same",
|
||||
/*display_order*/ 0,
|
||||
),
|
||||
make_handler(
|
||||
HookEventName::Stop,
|
||||
/*matcher*/ None,
|
||||
"echo same",
|
||||
/*display_order*/ 1,
|
||||
),
|
||||
];
|
||||
|
||||
let selected = select_handlers(&handlers, HookEventName::Stop, /*matcher_input*/ None);
|
||||
|
||||
assert_eq!(selected.len(), 2);
|
||||
assert_eq!(selected[0].display_order, 0);
|
||||
assert_eq!(selected[1].display_order, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_handlers_ignores_interrupt_matchers() {
|
||||
let handlers = vec![
|
||||
make_handler(
|
||||
HookEventName::Interrupt,
|
||||
Some("^interrupted$"),
|
||||
"echo first",
|
||||
/*display_order*/ 0,
|
||||
),
|
||||
make_handler(
|
||||
HookEventName::Interrupt,
|
||||
/*matcher*/ None,
|
||||
"echo second",
|
||||
/*display_order*/ 1,
|
||||
),
|
||||
];
|
||||
|
||||
let selected = select_handlers(
|
||||
&handlers,
|
||||
HookEventName::Interrupt,
|
||||
/*matcher_input*/ None,
|
||||
);
|
||||
|
||||
assert_eq!(selected.len(), 2);
|
||||
assert_eq!(selected[0].display_order, 0);
|
||||
assert_eq!(selected[1].display_order, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_handlers_keeps_overlapping_session_start_matchers() {
|
||||
let handlers = vec![
|
||||
make_handler(
|
||||
HookEventName::SessionStart,
|
||||
Some("start.*"),
|
||||
"echo same",
|
||||
/*display_order*/ 0,
|
||||
),
|
||||
make_handler(
|
||||
HookEventName::SessionStart,
|
||||
Some("^startup$"),
|
||||
"echo same",
|
||||
/*display_order*/ 1,
|
||||
),
|
||||
];
|
||||
|
||||
let selected = select_handlers(&handlers, HookEventName::SessionStart, Some("startup"));
|
||||
|
||||
assert_eq!(selected.len(), 2);
|
||||
assert_eq!(selected[0].display_order, 0);
|
||||
assert_eq!(selected[1].display_order, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compact_hooks_match_trigger() {
|
||||
let handlers = vec![
|
||||
make_handler(
|
||||
HookEventName::PreCompact,
|
||||
Some("manual"),
|
||||
"echo manual",
|
||||
/*display_order*/ 0,
|
||||
),
|
||||
make_handler(
|
||||
HookEventName::PreCompact,
|
||||
Some("auto"),
|
||||
"echo auto",
|
||||
/*display_order*/ 1,
|
||||
),
|
||||
];
|
||||
|
||||
let selected = select_handlers(&handlers, HookEventName::PreCompact, Some("manual"));
|
||||
|
||||
assert_eq!(selected.len(), 1);
|
||||
assert_eq!(selected[0].display_order, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pre_tool_use_matches_tool_name() {
|
||||
let handlers = vec![
|
||||
make_handler(
|
||||
HookEventName::PreToolUse,
|
||||
Some("^Bash$"),
|
||||
"echo same",
|
||||
/*display_order*/ 0,
|
||||
),
|
||||
make_handler(
|
||||
HookEventName::PreToolUse,
|
||||
Some("^Edit$"),
|
||||
"echo same",
|
||||
/*display_order*/ 1,
|
||||
),
|
||||
];
|
||||
|
||||
let selected = select_handlers(&handlers, HookEventName::PreToolUse, Some("Bash"));
|
||||
|
||||
assert_eq!(selected.len(), 1);
|
||||
assert_eq!(selected[0].display_order, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn post_tool_use_matches_tool_name() {
|
||||
let handlers = vec![
|
||||
make_handler(
|
||||
HookEventName::PostToolUse,
|
||||
Some("^Bash$"),
|
||||
"echo same",
|
||||
/*display_order*/ 0,
|
||||
),
|
||||
make_handler(
|
||||
HookEventName::PostToolUse,
|
||||
Some("^Edit$"),
|
||||
"echo same",
|
||||
/*display_order*/ 1,
|
||||
),
|
||||
];
|
||||
|
||||
let selected = select_handlers(&handlers, HookEventName::PostToolUse, Some("Bash"));
|
||||
|
||||
assert_eq!(selected.len(), 1);
|
||||
assert_eq!(selected[0].display_order, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pre_tool_use_star_matcher_matches_all_tools() {
|
||||
let handlers = vec![
|
||||
make_handler(
|
||||
HookEventName::PreToolUse,
|
||||
Some("*"),
|
||||
"echo same",
|
||||
/*display_order*/ 0,
|
||||
),
|
||||
make_handler(
|
||||
HookEventName::PreToolUse,
|
||||
Some("^Edit$"),
|
||||
"echo same",
|
||||
/*display_order*/ 1,
|
||||
),
|
||||
];
|
||||
|
||||
let selected = select_handlers(&handlers, HookEventName::PreToolUse, Some("Bash"));
|
||||
|
||||
assert_eq!(selected.len(), 1);
|
||||
assert_eq!(selected[0].display_order, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pre_tool_use_regex_alternation_matches_each_tool_name() {
|
||||
let handlers = vec![make_handler(
|
||||
HookEventName::PreToolUse,
|
||||
Some("Edit|Write"),
|
||||
"echo same",
|
||||
/*display_order*/ 0,
|
||||
)];
|
||||
|
||||
let selected_edit = select_handlers(&handlers, HookEventName::PreToolUse, Some("Edit"));
|
||||
let selected_write = select_handlers(&handlers, HookEventName::PreToolUse, Some("Write"));
|
||||
let selected_bash = select_handlers(&handlers, HookEventName::PreToolUse, Some("Bash"));
|
||||
|
||||
assert_eq!(selected_edit.len(), 1);
|
||||
assert_eq!(selected_write.len(), 1);
|
||||
assert_eq!(selected_bash.len(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pre_tool_use_aliases_match_once_per_handler() {
|
||||
let handlers = vec![
|
||||
make_handler(
|
||||
HookEventName::PreToolUse,
|
||||
Some("^apply_patch$"),
|
||||
"echo apply_patch",
|
||||
/*display_order*/ 0,
|
||||
),
|
||||
make_handler(
|
||||
HookEventName::PreToolUse,
|
||||
Some("^Write$"),
|
||||
"echo write",
|
||||
/*display_order*/ 1,
|
||||
),
|
||||
make_handler(
|
||||
HookEventName::PreToolUse,
|
||||
Some("^Edit$"),
|
||||
"echo edit",
|
||||
/*display_order*/ 2,
|
||||
),
|
||||
make_handler(
|
||||
HookEventName::PreToolUse,
|
||||
Some("apply_patch|Write|Edit"),
|
||||
"echo combined",
|
||||
/*display_order*/ 3,
|
||||
),
|
||||
];
|
||||
|
||||
let selected = select_handlers_for_matcher_inputs(
|
||||
&handlers,
|
||||
HookEventName::PreToolUse,
|
||||
&["apply_patch", "Write", "Edit"],
|
||||
);
|
||||
|
||||
assert_eq!(selected.len(), 4);
|
||||
assert_eq!(
|
||||
selected
|
||||
.iter()
|
||||
.map(|handler| handler.display_order)
|
||||
.collect::<Vec<_>>(),
|
||||
vec![0, 1, 2, 3],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn user_prompt_submit_ignores_matcher() {
|
||||
let handlers = vec![
|
||||
make_handler(
|
||||
HookEventName::UserPromptSubmit,
|
||||
Some("^hello"),
|
||||
"echo first",
|
||||
/*display_order*/ 0,
|
||||
),
|
||||
make_handler(
|
||||
HookEventName::UserPromptSubmit,
|
||||
Some("^unmatched$"),
|
||||
"echo second",
|
||||
/*display_order*/ 1,
|
||||
),
|
||||
];
|
||||
|
||||
let selected = select_handlers(
|
||||
&handlers,
|
||||
HookEventName::UserPromptSubmit,
|
||||
/*matcher_input*/ None,
|
||||
);
|
||||
|
||||
assert_eq!(selected.len(), 2);
|
||||
assert_eq!(selected[0].display_order, 0);
|
||||
assert_eq!(selected[1].display_order, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_handlers_preserves_declaration_order() {
|
||||
let handlers = vec![
|
||||
make_handler(
|
||||
HookEventName::Stop,
|
||||
/*matcher*/ None,
|
||||
"first",
|
||||
/*display_order*/ 0,
|
||||
),
|
||||
make_handler(
|
||||
HookEventName::Stop,
|
||||
/*matcher*/ None,
|
||||
"second",
|
||||
/*display_order*/ 1,
|
||||
),
|
||||
make_handler(
|
||||
HookEventName::Stop,
|
||||
/*matcher*/ None,
|
||||
"third",
|
||||
/*display_order*/ 2,
|
||||
),
|
||||
];
|
||||
|
||||
let selected = select_handlers(&handlers, HookEventName::Stop, /*matcher_input*/ None);
|
||||
|
||||
assert_eq!(selected, handlers);
|
||||
}
|
||||
}
|
||||
49
codex-rs/hooks/src/engine/matcher.rs
Normal file
49
codex-rs/hooks/src/engine/matcher.rs
Normal file
@@ -0,0 +1,49 @@
|
||||
//! Compiled hook matchers retain their original spelling for configuration identity.
|
||||
//! Regex parsing happens during discovery; dispatch only evaluates admitted matchers.
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) enum HookMatcher {
|
||||
All(String),
|
||||
Exact(String),
|
||||
Regex(regex::Regex),
|
||||
}
|
||||
|
||||
impl HookMatcher {
|
||||
pub(crate) fn new(pattern: &str) -> Result<Self, regex::Error> {
|
||||
if pattern.is_empty() || pattern == "*" {
|
||||
Ok(Self::All(pattern.to_string()))
|
||||
} else if pattern
|
||||
.chars()
|
||||
.all(|ch| ch.is_ascii_alphanumeric() || ch == '_' || ch == '|')
|
||||
{
|
||||
Ok(Self::Exact(pattern.to_string()))
|
||||
} else {
|
||||
regex::Regex::new(pattern).map(Self::Regex)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn as_str(&self) -> &str {
|
||||
match self {
|
||||
Self::All(pattern) | Self::Exact(pattern) => pattern,
|
||||
Self::Regex(regex) => regex.as_str(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn matches(&self, input: Option<&str>) -> bool {
|
||||
match self {
|
||||
Self::All(_) => true,
|
||||
Self::Exact(pattern) => {
|
||||
input.is_some_and(|input| pattern.split('|').any(|candidate| candidate == input))
|
||||
}
|
||||
Self::Regex(regex) => input.is_some_and(|input| regex.is_match(input)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for HookMatcher {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.as_str() == other.as_str()
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for HookMatcher {}
|
||||
183
codex-rs/hooks/src/engine/mcp_runner.rs
Normal file
183
codex-rs/hooks/src/engine/mcp_runner.rs
Normal file
@@ -0,0 +1,183 @@
|
||||
use std::sync::LazyLock;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use codex_protocol::models::ContentItemMetadata;
|
||||
use regex::Regex;
|
||||
use serde_json::Map;
|
||||
use serde_json::Value;
|
||||
|
||||
use super::ConfiguredHandler;
|
||||
use super::HandlerRunResult;
|
||||
use super::HandlerSourcePath;
|
||||
use crate::mcp::HookMcpCall;
|
||||
use crate::mcp::HookMcpExecutor;
|
||||
|
||||
/// Expands an MCP argument template against this hook event and invokes the configured tool.
|
||||
#[tracing::instrument(
|
||||
name = "codex.hooks.mcp_tool",
|
||||
level = "trace",
|
||||
skip_all,
|
||||
fields(
|
||||
hook.server = server,
|
||||
hook.tool = tool,
|
||||
hook.timeout_sec = handler.timeout_sec,
|
||||
)
|
||||
)]
|
||||
pub(crate) async fn run_mcp_tool(
|
||||
executor: &dyn HookMcpExecutor,
|
||||
handler: &ConfiguredHandler,
|
||||
server: &str,
|
||||
tool: &str,
|
||||
argument_template: &Map<String, Value>,
|
||||
hook_event: &Value,
|
||||
metadata: Option<&Map<String, Value>>,
|
||||
) -> HandlerRunResult {
|
||||
let started_at = chrono::Utc::now().timestamp();
|
||||
let started = Instant::now();
|
||||
let timeout_started = tokio::time::Instant::now();
|
||||
let duration = Duration::from_secs(handler.timeout_sec);
|
||||
let result = async {
|
||||
if let Some(trust) = &handler.plugin_trust {
|
||||
tokio::time::timeout(duration, trust.verify())
|
||||
.await
|
||||
.context("hook trust verification timed out")??;
|
||||
}
|
||||
let input = expand_mcp_argument_template(argument_template, hook_event)?;
|
||||
let (environment_id, mut call_metadata) = match &handler.source_path {
|
||||
HandlerSourcePath::Local(_) => (None, None),
|
||||
HandlerSourcePath::Environment { environment_id, .. } => {
|
||||
(Some(environment_id.clone()), None)
|
||||
}
|
||||
HandlerSourcePath::ExecutorScoped {
|
||||
environment_id,
|
||||
mcp_environment_id,
|
||||
mcp_metadata,
|
||||
..
|
||||
} => (
|
||||
Some(
|
||||
mcp_environment_id
|
||||
.as_ref()
|
||||
.unwrap_or(environment_id)
|
||||
.clone(),
|
||||
),
|
||||
mcp_metadata.as_deref().cloned(),
|
||||
),
|
||||
};
|
||||
if let Some(metadata) = metadata {
|
||||
call_metadata
|
||||
.get_or_insert_with(Map::new)
|
||||
.extend(metadata.clone());
|
||||
}
|
||||
executor
|
||||
.execute(HookMcpCall {
|
||||
server: server.to_string(),
|
||||
tool: tool.to_string(),
|
||||
environment_id,
|
||||
metadata: call_metadata,
|
||||
input,
|
||||
timeout: if handler.plugin_trust.is_some() {
|
||||
duration.saturating_sub(timeout_started.elapsed())
|
||||
} else {
|
||||
Duration::from_secs(handler.timeout_sec)
|
||||
},
|
||||
})
|
||||
.await
|
||||
}
|
||||
.await;
|
||||
|
||||
let (exit_code, stdout, error, source_tool_namespace) = match result {
|
||||
Ok(output) => (Some(0), output.text, None, output.source_tool_namespace),
|
||||
Err(error) => (None, String::new(), Some(error.to_string()), None),
|
||||
};
|
||||
HandlerRunResult {
|
||||
context_metadata: ContentItemMetadata::tool(source_tool_namespace.map(Into::into)),
|
||||
started_at,
|
||||
completed_at: chrono::Utc::now().timestamp(),
|
||||
duration_ms: started.elapsed().as_millis().try_into().unwrap_or(i64::MAX),
|
||||
exit_code,
|
||||
stdout,
|
||||
stderr: String::new(),
|
||||
error,
|
||||
}
|
||||
}
|
||||
|
||||
/// Recursively substitutes `${field.nested}` placeholders using values from a hook event.
|
||||
///
|
||||
/// A complete placeholder preserves its JSON type; a placeholder embedded in surrounding
|
||||
/// text is rendered as a string. Missing fields fail the hook instead of passing unresolved
|
||||
/// arguments to the server. For example, the template `{"count":"${tool_input.count}"}`
|
||||
/// becomes `{"count":3}` when the event contains `{"tool_input":{"count":3}}`.
|
||||
pub(crate) fn expand_mcp_argument_template(
|
||||
argument_template: &Map<String, Value>,
|
||||
hook_event: &Value,
|
||||
) -> Result<Map<String, Value>> {
|
||||
argument_template
|
||||
.iter()
|
||||
.map(|(key, value)| Ok((key.clone(), resolve_value(value, hook_event)?)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn resolve_value(value: &Value, hook_event: &Value) -> Result<Value> {
|
||||
match value {
|
||||
Value::Object(input) => Ok(Value::Object(expand_mcp_argument_template(
|
||||
input, hook_event,
|
||||
)?)),
|
||||
Value::Array(items) => items
|
||||
.iter()
|
||||
.map(|item| resolve_value(item, hook_event))
|
||||
.collect::<Result<Vec<_>>>()
|
||||
.map(Value::Array),
|
||||
Value::String(text) => resolve_string(text, hook_event),
|
||||
_ => Ok(value.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_string(text: &str, hook_event: &Value) -> Result<Value> {
|
||||
static PLACEHOLDER_PATTERN: LazyLock<Result<Regex, regex::Error>> =
|
||||
LazyLock::new(|| Regex::new(r"\$\{([^{}]+)\}"));
|
||||
let pattern = PLACEHOLDER_PATTERN.as_ref().map_err(Clone::clone)?;
|
||||
let captures = pattern.captures_iter(text).collect::<Vec<_>>();
|
||||
if captures.is_empty() {
|
||||
return Ok(Value::String(text.to_string()));
|
||||
}
|
||||
|
||||
if let [capture] = captures.as_slice()
|
||||
&& let Some(placeholder) = capture.get(0)
|
||||
&& placeholder.start() == 0
|
||||
&& placeholder.end() == text.len()
|
||||
{
|
||||
return resolve_path(hook_event, &capture[1]).cloned();
|
||||
}
|
||||
|
||||
let mut resolved = String::new();
|
||||
let mut previous_end = 0;
|
||||
for capture in captures {
|
||||
let Some(placeholder) = capture.get(0) else {
|
||||
continue;
|
||||
};
|
||||
resolved.push_str(&text[previous_end..placeholder.start()]);
|
||||
let value = resolve_path(hook_event, &capture[1])?;
|
||||
match value {
|
||||
Value::String(value) => resolved.push_str(value),
|
||||
_ => resolved.push_str(&serde_json::to_string(value)?),
|
||||
}
|
||||
previous_end = placeholder.end();
|
||||
}
|
||||
resolved.push_str(&text[previous_end..]);
|
||||
Ok(Value::String(resolved))
|
||||
}
|
||||
|
||||
fn resolve_path<'a>(hook_event: &'a Value, path: &str) -> Result<&'a Value> {
|
||||
path.split('.').try_fold(hook_event, |value, field| {
|
||||
value
|
||||
.get(field)
|
||||
.with_context(|| format!("hook input placeholder `${{{path}}}` was not found"))
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "mcp_runner_tests.rs"]
|
||||
mod tests;
|
||||
146
codex-rs/hooks/src/engine/mcp_runner_tests.rs
Normal file
146
codex-rs/hooks/src/engine/mcp_runner_tests.rs
Normal file
@@ -0,0 +1,146 @@
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::time::Duration;
|
||||
|
||||
use futures::FutureExt;
|
||||
use futures::future::BoxFuture;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::Map;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
|
||||
use super::expand_mcp_argument_template;
|
||||
use super::run_mcp_tool;
|
||||
use crate::engine::ConfiguredHandler;
|
||||
use crate::engine::ConfiguredHandlerKind;
|
||||
use crate::mcp::HookMcpCall;
|
||||
use crate::mcp::HookMcpExecutor;
|
||||
use crate::mcp::HookMcpOutput;
|
||||
use codex_protocol::protocol::HookEventName;
|
||||
use codex_protocol::protocol::HookSource;
|
||||
use codex_utils_absolute_path::test_support::PathBufExt;
|
||||
use codex_utils_absolute_path::test_support::test_path_buf;
|
||||
|
||||
struct RecordingExecutor {
|
||||
calls: Arc<Mutex<Vec<HookMcpCall>>>,
|
||||
output: String,
|
||||
}
|
||||
|
||||
impl HookMcpExecutor for RecordingExecutor {
|
||||
fn execute(&self, call: HookMcpCall) -> BoxFuture<'_, anyhow::Result<HookMcpOutput>> {
|
||||
async move {
|
||||
self.calls.lock().expect("lock calls").push(call);
|
||||
Ok(HookMcpOutput {
|
||||
text: self.output.clone(),
|
||||
source_tool_namespace: Some("security".into()),
|
||||
})
|
||||
}
|
||||
.boxed()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn placeholders_preserve_json_types_and_expand_nested_inputs() {
|
||||
let event_input = json!({
|
||||
"tool_input": {
|
||||
"file_path": "/tmp/example.rs",
|
||||
"count": 3,
|
||||
"optional": null,
|
||||
"metadata": { "language": "rust" },
|
||||
},
|
||||
});
|
||||
let input = serde_json::from_value::<Map<String, Value>>(json!({
|
||||
"path": "${tool_input.file_path}",
|
||||
"message": "scan ${tool_input.file_path}",
|
||||
"count": "${tool_input.count}",
|
||||
"optional": "${tool_input.optional}",
|
||||
"nested": ["${tool_input.metadata}", { "literal": true }],
|
||||
}))
|
||||
.expect("object input");
|
||||
|
||||
assert_eq!(
|
||||
Value::Object(
|
||||
expand_mcp_argument_template(&input, &event_input).expect("expand MCP arguments")
|
||||
),
|
||||
json!({
|
||||
"path": "/tmp/example.rs",
|
||||
"message": "scan /tmp/example.rs",
|
||||
"count": 3,
|
||||
"optional": null,
|
||||
"nested": [{ "language": "rust" }, { "literal": true }],
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_placeholder_fails_without_passing_unresolved_input() {
|
||||
let input = serde_json::from_value::<Map<String, Value>>(json!({
|
||||
"path": "${tool_input.missing}",
|
||||
}))
|
||||
.expect("object input");
|
||||
|
||||
let error = expand_mcp_argument_template(&input, &json!({ "tool_input": {} }))
|
||||
.expect_err("missing placeholder should fail");
|
||||
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
"hook input placeholder `${tool_input.missing}` was not found"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mcp_tool_results_use_command_hook_output_contract() {
|
||||
let configured_input = serde_json::from_value::<Map<String, Value>>(json!({
|
||||
"file_path": "${tool_input.file_path}",
|
||||
}))
|
||||
.expect("object input");
|
||||
let handler = ConfiguredHandler {
|
||||
builtin: false,
|
||||
plugin_trust: None,
|
||||
event_name: HookEventName::PostToolUse,
|
||||
matcher: None,
|
||||
timeout_sec: 30,
|
||||
status_message: None,
|
||||
additional_context_limit: Default::default(),
|
||||
source_path: test_path_buf("/tmp/hooks.json").abs().into(),
|
||||
source: HookSource::User,
|
||||
display_order: 0,
|
||||
kind: ConfiguredHandlerKind::McpTool {
|
||||
server: "security".to_string(),
|
||||
tool: "scan".to_string(),
|
||||
input: configured_input.clone(),
|
||||
},
|
||||
};
|
||||
let calls = Arc::new(Mutex::new(Vec::new()));
|
||||
let executor = RecordingExecutor {
|
||||
calls: Arc::clone(&calls),
|
||||
output: r#"{"decision":"block","reason":"unsafe file"}"#.to_string(),
|
||||
};
|
||||
|
||||
let result = run_mcp_tool(
|
||||
&executor,
|
||||
&handler,
|
||||
"security",
|
||||
"scan",
|
||||
&configured_input,
|
||||
&json!({ "tool_input": { "file_path": "/tmp/example.rs" } }),
|
||||
/*metadata*/ None,
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(result.exit_code, Some(0));
|
||||
assert_eq!(result.stdout, executor.output);
|
||||
assert_eq!(result.error, None);
|
||||
assert_eq!(
|
||||
*calls.lock().expect("lock calls"),
|
||||
vec![HookMcpCall {
|
||||
server: "security".to_string(),
|
||||
tool: "scan".to_string(),
|
||||
environment_id: None,
|
||||
metadata: None,
|
||||
input: serde_json::from_value(json!({ "file_path": "/tmp/example.rs" }))
|
||||
.expect("object input"),
|
||||
timeout: Duration::from_secs(30),
|
||||
}]
|
||||
);
|
||||
}
|
||||
571
codex-rs/hooks/src/engine/mod.rs
Normal file
571
codex-rs/hooks/src/engine/mod.rs
Normal file
@@ -0,0 +1,571 @@
|
||||
pub(crate) mod command_runner;
|
||||
pub(crate) mod discovery;
|
||||
pub(crate) mod dispatcher;
|
||||
mod matcher;
|
||||
pub(crate) mod mcp_runner;
|
||||
pub(crate) mod output_parser;
|
||||
mod plugin_fingerprint;
|
||||
mod plugin_trust;
|
||||
pub(crate) mod schema_loader;
|
||||
|
||||
pub(crate) use matcher::HookMatcher;
|
||||
|
||||
use crate::events::compact::PostCompactRequest;
|
||||
use crate::events::compact::PreCompactOutcome;
|
||||
use crate::events::compact::PreCompactRequest;
|
||||
use crate::events::compact::StatelessHookOutcome;
|
||||
use crate::events::interrupt::InterruptOutcome;
|
||||
use crate::events::interrupt::InterruptRequest;
|
||||
use crate::events::permission_request::PermissionRequestOutcome;
|
||||
use crate::events::permission_request::PermissionRequestRequest;
|
||||
use crate::events::post_tool_use::PostToolUseOutcome;
|
||||
use crate::events::post_tool_use::PostToolUseRequest;
|
||||
use crate::events::pre_tool_use::PreToolUseOutcome;
|
||||
use crate::events::pre_tool_use::PreToolUseRequest;
|
||||
use crate::events::session_end::SessionEndOutcome;
|
||||
use crate::events::session_end::SessionEndRequest;
|
||||
use crate::events::session_start::SessionStartOutcome;
|
||||
use crate::events::session_start::SessionStartRequest;
|
||||
use crate::events::stop::StopOutcome;
|
||||
use crate::events::stop::StopRequest;
|
||||
use crate::events::user_prompt_submit::UserPromptSubmitOutcome;
|
||||
use crate::events::user_prompt_submit::UserPromptSubmitRequest;
|
||||
use crate::mcp::HookMcpExecutor;
|
||||
use crate::output_spill::AdditionalContextLimit;
|
||||
use codex_config::ConfigLayerStack;
|
||||
use codex_config::HookHandlerConfig;
|
||||
use codex_plugin::ExecutorPluginHookSource;
|
||||
use codex_plugin::PluginHookSource;
|
||||
use codex_plugin::PluginId;
|
||||
use codex_protocol::protocol::HookEventName;
|
||||
use codex_protocol::protocol::HookExecutionMode;
|
||||
use codex_protocol::protocol::HookHandlerType;
|
||||
use codex_protocol::protocol::HookRunSummary;
|
||||
use codex_protocol::protocol::HookSource;
|
||||
use codex_protocol::protocol::HookTrustStatus;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use serde_json::Map;
|
||||
use serde_json::Value;
|
||||
use std::borrow::Cow;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use command_runner::CommandHookRuntime;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct CommandShell {
|
||||
pub program: String,
|
||||
pub args: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) struct ConfiguredHandler {
|
||||
/// Internally admitted cleanup hook, enabled independently of per-hook state.
|
||||
pub builtin: bool,
|
||||
pub plugin_trust: Option<plugin_trust::PluginHookTrust>,
|
||||
pub event_name: codex_protocol::protocol::HookEventName,
|
||||
pub matcher: Option<HookMatcher>,
|
||||
pub timeout_sec: u64,
|
||||
pub status_message: Option<String>,
|
||||
pub additional_context_limit: AdditionalContextLimit,
|
||||
pub source_path: HandlerSourcePath,
|
||||
pub source: HookSource,
|
||||
pub display_order: i64,
|
||||
pub kind: ConfiguredHandlerKind,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) enum HandlerSourcePath {
|
||||
Local(AbsolutePathBuf),
|
||||
Environment {
|
||||
environment_id: String,
|
||||
cwd: PathUri,
|
||||
source_path: PathUri,
|
||||
},
|
||||
/// Executor-scoped handlers are currently excluded from user-visible hook reporting
|
||||
/// (events, summary, telemetry). Their handlers are always executed async.
|
||||
///
|
||||
/// TODO: With CCA, all hooks will be executor-scoped, so user visibility
|
||||
/// (participation in lifecycle events and summaries) and execution behavior
|
||||
/// (non-blocking) will need to be determined independently.
|
||||
ExecutorScoped {
|
||||
plugin_id: PluginId,
|
||||
environment_id: String,
|
||||
mcp_environment_id: Option<String>,
|
||||
mcp_metadata: Option<Box<Map<String, Value>>>,
|
||||
manifest_path: PathUri,
|
||||
source_relative_path: String,
|
||||
},
|
||||
}
|
||||
|
||||
impl HandlerSourcePath {
|
||||
/// Use the environment's working directory and withhold controller-owned transcript paths.
|
||||
fn event_input<'a>(&self, input: &'a Value) -> Cow<'a, Value> {
|
||||
match self {
|
||||
Self::Environment { cwd, .. } => {
|
||||
let mut input = input.clone();
|
||||
input["cwd"] = Value::String(cwd.inferred_native_path_string());
|
||||
input["transcript_path"] = Value::Null;
|
||||
if let Some(path) = input.get_mut("agent_transcript_path") {
|
||||
*path = Value::Null;
|
||||
}
|
||||
Cow::Owned(input)
|
||||
}
|
||||
Self::Local(_) | Self::ExecutorScoped { .. } => Cow::Borrowed(input),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<AbsolutePathBuf> for HandlerSourcePath {
|
||||
fn from(path: AbsolutePathBuf) -> Self {
|
||||
Self::Local(path)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for HandlerSourcePath {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::Local(path) => write!(formatter, "{}", path.display()),
|
||||
Self::Environment { source_path, .. } => {
|
||||
write!(formatter, "{}", source_path.inferred_native_path_string())
|
||||
}
|
||||
Self::ExecutorScoped {
|
||||
environment_id,
|
||||
manifest_path,
|
||||
source_relative_path,
|
||||
..
|
||||
} => write!(
|
||||
formatter,
|
||||
"{environment_id}:{manifest_path}:{source_relative_path}"
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) enum ConfiguredHandlerKind {
|
||||
Command {
|
||||
command: String,
|
||||
env: HashMap<String, String>,
|
||||
r#async: bool,
|
||||
},
|
||||
McpTool {
|
||||
server: String,
|
||||
tool: String,
|
||||
input: serde_json::Map<String, serde_json::Value>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct HandlerRunResult {
|
||||
pub context_metadata: codex_protocol::models::ContentItemMetadata,
|
||||
pub started_at: i64,
|
||||
pub completed_at: i64,
|
||||
pub duration_ms: i64,
|
||||
pub exit_code: Option<i32>,
|
||||
pub stdout: String,
|
||||
pub stderr: String,
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
impl ConfiguredHandler {
|
||||
/// Internal memory work runs policy and executor hooks, not user or project hooks.
|
||||
pub(crate) fn runs_for_memory_consolidation(&self) -> bool {
|
||||
matches!(self.source_path, HandlerSourcePath::ExecutorScoped { .. })
|
||||
|| match self.source {
|
||||
HookSource::User
|
||||
| HookSource::Project
|
||||
| HookSource::SessionFlags
|
||||
| HookSource::Plugin => false,
|
||||
HookSource::System
|
||||
| HookSource::Mdm
|
||||
| HookSource::CloudRequirements
|
||||
| HookSource::CloudManagedConfig
|
||||
| HookSource::LegacyManagedConfigFile
|
||||
| HookSource::LegacyManagedConfigMdm
|
||||
// Required hooks can have unknown attribution; retain them fail-closed.
|
||||
| HookSource::Unknown => true,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn execution_mode(&self) -> HookExecutionMode {
|
||||
if matches!(self.source_path, HandlerSourcePath::ExecutorScoped { .. }) {
|
||||
return HookExecutionMode::Async;
|
||||
}
|
||||
|
||||
match self.kind {
|
||||
ConfiguredHandlerKind::Command { r#async: true, .. } => HookExecutionMode::Async,
|
||||
ConfiguredHandlerKind::Command { r#async: false, .. }
|
||||
| ConfiguredHandlerKind::McpTool { .. } => HookExecutionMode::Sync,
|
||||
}
|
||||
}
|
||||
|
||||
/// Only synchronous hooks can apply control effects.
|
||||
pub(crate) fn can_apply_control_effects(&self) -> bool {
|
||||
self.execution_mode() == HookExecutionMode::Sync
|
||||
}
|
||||
|
||||
pub fn run_id(&self) -> String {
|
||||
format!(
|
||||
"{}:{}:{}",
|
||||
self.event_name_label(),
|
||||
self.display_order,
|
||||
self.source_path
|
||||
)
|
||||
}
|
||||
|
||||
fn event_name_label(&self) -> &'static str {
|
||||
match self.event_name {
|
||||
codex_protocol::protocol::HookEventName::PreToolUse => "pre-tool-use",
|
||||
codex_protocol::protocol::HookEventName::PermissionRequest => "permission-request",
|
||||
codex_protocol::protocol::HookEventName::PostToolUse => "post-tool-use",
|
||||
codex_protocol::protocol::HookEventName::PreCompact => "pre-compact",
|
||||
codex_protocol::protocol::HookEventName::PostCompact => "post-compact",
|
||||
codex_protocol::protocol::HookEventName::PreModelRequest => "pre-model-request",
|
||||
codex_protocol::protocol::HookEventName::PostModelRequest => "post-model-request",
|
||||
codex_protocol::protocol::HookEventName::SessionStart => "session-start",
|
||||
codex_protocol::protocol::HookEventName::SessionEnd => "session-end",
|
||||
codex_protocol::protocol::HookEventName::UserPromptSubmit => "user-prompt-submit",
|
||||
codex_protocol::protocol::HookEventName::SubagentStart => "subagent-start",
|
||||
codex_protocol::protocol::HookEventName::SubagentStop => "subagent-stop",
|
||||
codex_protocol::protocol::HookEventName::Stop => "stop",
|
||||
codex_protocol::protocol::HookEventName::Interrupt => "interrupt",
|
||||
}
|
||||
}
|
||||
|
||||
fn handler_type(&self) -> HookHandlerType {
|
||||
match &self.kind {
|
||||
ConfiguredHandlerKind::Command { .. } => HookHandlerType::Command,
|
||||
ConfiguredHandlerKind::McpTool { .. } => HookHandlerType::McpTool,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum HookListEntryHandler {
|
||||
Command { command: String, r#async: bool },
|
||||
McpTool { server: String, tool: String },
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct HookListEntry {
|
||||
/// Builtin hooks remain available internally but are omitted from the public hooks list.
|
||||
pub builtin: bool,
|
||||
pub key: String,
|
||||
pub event_name: HookEventName,
|
||||
pub handler: HookListEntryHandler,
|
||||
pub matcher: Option<String>,
|
||||
pub timeout_sec: u64,
|
||||
pub status_message: Option<String>,
|
||||
pub additional_context_limit: Option<usize>,
|
||||
pub source_path: AbsolutePathBuf,
|
||||
pub source: HookSource,
|
||||
pub plugin_id: Option<String>,
|
||||
/// The owning execution environment, if this hook came from its requirements.
|
||||
pub environment_id: Option<String>,
|
||||
pub display_order: i64,
|
||||
pub enabled: bool,
|
||||
pub is_managed: bool,
|
||||
pub current_hash: String,
|
||||
pub trust_status: HookTrustStatus,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct ClaudeHooksEngine {
|
||||
pub(crate) enabled: bool,
|
||||
// Per-turn views share configuration; executor overlays copy handlers on mutation.
|
||||
pub(crate) handlers: Arc<Vec<ConfiguredHandler>>,
|
||||
/// Retain the session inventory without copying it for every hook dispatch.
|
||||
pub(crate) hook_entries: Arc<Vec<HookListEntry>>,
|
||||
pub(crate) warnings: Arc<[String]>,
|
||||
required_load_errors: Arc<[String]>,
|
||||
pub(crate) command_runtime: CommandHookRuntime,
|
||||
pub(crate) mcp_executor: Arc<dyn HookMcpExecutor>,
|
||||
}
|
||||
|
||||
impl ClaudeHooksEngine {
|
||||
pub(crate) fn new(
|
||||
enabled: bool,
|
||||
bypass_hook_trust: bool,
|
||||
config_layer_stack: Option<&ConfigLayerStack>,
|
||||
plugin_hook_sources: Vec<PluginHookSource>,
|
||||
plugin_hook_load_warnings: Vec<String>,
|
||||
command_runtime: CommandHookRuntime,
|
||||
mcp_executor: Arc<dyn HookMcpExecutor>,
|
||||
) -> Self {
|
||||
if !enabled && plugin_hook_sources.is_empty() {
|
||||
return Self {
|
||||
enabled,
|
||||
handlers: Arc::default(),
|
||||
hook_entries: Arc::default(),
|
||||
warnings: Arc::default(),
|
||||
required_load_errors: Arc::default(),
|
||||
command_runtime,
|
||||
mcp_executor,
|
||||
};
|
||||
}
|
||||
|
||||
let _ = schema_loader::generated_hook_schemas();
|
||||
let mut discovered = discovery::discover_handlers(
|
||||
config_layer_stack,
|
||||
plugin_hook_sources,
|
||||
plugin_hook_load_warnings,
|
||||
bypass_hook_trust,
|
||||
discovery::DiscoveryMode::Runtime,
|
||||
);
|
||||
if !enabled {
|
||||
discovered.handlers.retain(|handler| handler.builtin);
|
||||
discovered.hook_entries.clear();
|
||||
// Disabled ordinary hooks must not emit warnings or reject session startup.
|
||||
discovered.warnings.clear();
|
||||
discovered.required_load_errors.clear();
|
||||
}
|
||||
Self {
|
||||
enabled,
|
||||
handlers: Arc::new(discovered.handlers),
|
||||
hook_entries: Arc::new(discovered.hook_entries),
|
||||
warnings: discovered.warnings.into(),
|
||||
required_load_errors: discovered.required_load_errors.into(),
|
||||
command_runtime,
|
||||
mcp_executor,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn warnings(&self) -> &[String] {
|
||||
&self.warnings
|
||||
}
|
||||
|
||||
pub(crate) fn set_executor_hooks(&mut self, executor_hooks: Vec<ExecutorPluginHookSource>) {
|
||||
if executor_hooks.is_empty()
|
||||
&& !self.handlers.iter().any(|handler| {
|
||||
matches!(
|
||||
handler.source_path,
|
||||
HandlerSourcePath::ExecutorScoped { .. }
|
||||
)
|
||||
})
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let handlers = Arc::make_mut(&mut self.handlers);
|
||||
handlers.retain(|handler| {
|
||||
!matches!(
|
||||
handler.source_path,
|
||||
HandlerSourcePath::ExecutorScoped { .. }
|
||||
)
|
||||
});
|
||||
|
||||
let mut display_order = handlers
|
||||
.iter()
|
||||
.map(|handler| handler.display_order)
|
||||
.max()
|
||||
.map_or(0, |display_order| display_order.saturating_add(1));
|
||||
let mut seen_targets = HashSet::new();
|
||||
for source in executor_hooks {
|
||||
for (event_name, groups) in source.hooks.into_matcher_groups() {
|
||||
let Some(handler) = groups.into_iter().flat_map(|group| group.hooks).next() else {
|
||||
continue;
|
||||
};
|
||||
let HookHandlerConfig::McpTool {
|
||||
server,
|
||||
tool,
|
||||
input,
|
||||
timeout_sec,
|
||||
status_message,
|
||||
} = handler
|
||||
else {
|
||||
unreachable!("allowlisted executor handler must be an MCP tool");
|
||||
};
|
||||
|
||||
// Bundled plugins can share a cleanup target; run it once per event
|
||||
// and MCP environment.
|
||||
let target = (
|
||||
std::mem::discriminant(&event_name),
|
||||
source
|
||||
.mcp_environment_id
|
||||
.as_ref()
|
||||
.unwrap_or(&source.environment_id)
|
||||
.clone(),
|
||||
server.clone(),
|
||||
tool.clone(),
|
||||
);
|
||||
if !seen_targets.insert(target) {
|
||||
continue;
|
||||
}
|
||||
handlers.push(ConfiguredHandler {
|
||||
builtin: true,
|
||||
plugin_trust: None,
|
||||
event_name,
|
||||
matcher: None,
|
||||
timeout_sec: timeout_sec.unwrap_or(5).max(1),
|
||||
status_message,
|
||||
additional_context_limit: Default::default(),
|
||||
source_path: HandlerSourcePath::ExecutorScoped {
|
||||
plugin_id: source.plugin_id.clone(),
|
||||
environment_id: source.environment_id.clone(),
|
||||
mcp_environment_id: source.mcp_environment_id.clone(),
|
||||
mcp_metadata: source.mcp_metadata.clone().map(Box::new),
|
||||
manifest_path: source.manifest_path.clone(),
|
||||
source_relative_path: source.source_relative_path.clone(),
|
||||
},
|
||||
source: HookSource::Plugin,
|
||||
display_order,
|
||||
kind: ConfiguredHandlerKind::McpTool {
|
||||
server,
|
||||
tool,
|
||||
input,
|
||||
},
|
||||
});
|
||||
display_order = display_order.saturating_add(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn required_load_errors(&self) -> &[String] {
|
||||
&self.required_load_errors
|
||||
}
|
||||
|
||||
pub(crate) fn preview_session_start(
|
||||
&self,
|
||||
request: &SessionStartRequest,
|
||||
) -> Vec<HookRunSummary> {
|
||||
crate::events::session_start::preview(&self.handlers, request)
|
||||
}
|
||||
|
||||
pub(crate) fn preview_pre_tool_use(&self, request: &PreToolUseRequest) -> Vec<HookRunSummary> {
|
||||
crate::events::pre_tool_use::preview(&self.handlers, request)
|
||||
}
|
||||
|
||||
pub(crate) fn preview_permission_request(
|
||||
&self,
|
||||
request: &PermissionRequestRequest,
|
||||
) -> Vec<HookRunSummary> {
|
||||
crate::events::permission_request::preview(&self.handlers, request)
|
||||
}
|
||||
|
||||
pub(crate) fn max_permission_request_timeout(&self) -> Duration {
|
||||
Duration::from_secs(
|
||||
self.handlers
|
||||
.iter()
|
||||
.filter(|handler| {
|
||||
handler.event_name == HookEventName::PermissionRequest
|
||||
&& handler.can_apply_control_effects()
|
||||
})
|
||||
.map(|handler| handler.timeout_sec)
|
||||
.max()
|
||||
.unwrap_or_default(),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn preview_post_tool_use(
|
||||
&self,
|
||||
request: &PostToolUseRequest,
|
||||
) -> Vec<HookRunSummary> {
|
||||
crate::events::post_tool_use::preview(&self.handlers, request)
|
||||
}
|
||||
|
||||
pub(crate) async fn run_session_start(
|
||||
&self,
|
||||
request: SessionStartRequest,
|
||||
turn_id: Option<String>,
|
||||
) -> SessionStartOutcome {
|
||||
crate::events::session_start::run(self, request, turn_id).await
|
||||
}
|
||||
|
||||
pub(crate) async fn run_pre_tool_use(&self, request: PreToolUseRequest) -> PreToolUseOutcome {
|
||||
crate::events::pre_tool_use::run(self, request).await
|
||||
}
|
||||
|
||||
pub(crate) async fn run_permission_request(
|
||||
&self,
|
||||
request: PermissionRequestRequest,
|
||||
) -> PermissionRequestOutcome {
|
||||
crate::events::permission_request::run(self, request).await
|
||||
}
|
||||
|
||||
pub(crate) async fn run_post_tool_use(
|
||||
&self,
|
||||
request: PostToolUseRequest,
|
||||
) -> PostToolUseOutcome {
|
||||
let mut outcome = crate::events::post_tool_use::run(self, request).await;
|
||||
if let Some(feedback_message) = outcome.feedback_message.take() {
|
||||
outcome.feedback_message = Some(
|
||||
self.command_runtime
|
||||
.output_spiller()
|
||||
.maybe_spill_text(feedback_message)
|
||||
.await,
|
||||
);
|
||||
}
|
||||
outcome
|
||||
}
|
||||
|
||||
pub(crate) fn preview_pre_compact(&self, request: &PreCompactRequest) -> Vec<HookRunSummary> {
|
||||
crate::events::compact::preview_pre(&self.handlers, request)
|
||||
}
|
||||
|
||||
pub(crate) async fn run_pre_compact(&self, request: PreCompactRequest) -> PreCompactOutcome {
|
||||
crate::events::compact::run_pre(self, request).await
|
||||
}
|
||||
|
||||
pub(crate) fn preview_post_compact(&self, request: &PostCompactRequest) -> Vec<HookRunSummary> {
|
||||
crate::events::compact::preview_post(&self.handlers, request)
|
||||
}
|
||||
|
||||
pub(crate) async fn run_post_compact(
|
||||
&self,
|
||||
request: PostCompactRequest,
|
||||
) -> StatelessHookOutcome {
|
||||
crate::events::compact::run_post(self, request).await
|
||||
}
|
||||
|
||||
pub(crate) fn preview_user_prompt_submit(
|
||||
&self,
|
||||
request: &UserPromptSubmitRequest,
|
||||
) -> Vec<HookRunSummary> {
|
||||
crate::events::user_prompt_submit::preview(&self.handlers, request)
|
||||
}
|
||||
|
||||
pub(crate) async fn run_user_prompt_submit(
|
||||
&self,
|
||||
request: UserPromptSubmitRequest,
|
||||
) -> UserPromptSubmitOutcome {
|
||||
crate::events::user_prompt_submit::run(self, request).await
|
||||
}
|
||||
|
||||
pub(crate) fn preview_stop(&self, request: &StopRequest) -> Vec<HookRunSummary> {
|
||||
crate::events::stop::preview(&self.handlers, request)
|
||||
}
|
||||
|
||||
pub(crate) fn preview_session_end(&self) -> Vec<HookRunSummary> {
|
||||
crate::events::session_end::preview(&self.handlers)
|
||||
}
|
||||
|
||||
pub(crate) async fn run_session_end(&self, request: SessionEndRequest) -> SessionEndOutcome {
|
||||
crate::events::session_end::run(self, request).await
|
||||
}
|
||||
|
||||
pub(crate) async fn run_stop(&self, request: StopRequest) -> StopOutcome {
|
||||
let mut outcome = crate::events::stop::run(self, request).await;
|
||||
outcome.continuation_fragments = self
|
||||
.command_runtime
|
||||
.output_spiller()
|
||||
.maybe_spill_prompt_fragments(outcome.continuation_fragments)
|
||||
.await;
|
||||
outcome
|
||||
}
|
||||
|
||||
pub(crate) fn preview_interrupt(&self) -> Vec<HookRunSummary> {
|
||||
crate::events::interrupt::preview(&self.handlers)
|
||||
}
|
||||
|
||||
pub(crate) async fn run_interrupt(&self, request: InterruptRequest) -> InterruptOutcome {
|
||||
crate::events::interrupt::run(self, request).await
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "mod_tests.rs"]
|
||||
mod tests;
|
||||
3031
codex-rs/hooks/src/engine/mod_tests.rs
Normal file
3031
codex-rs/hooks/src/engine/mod_tests.rs
Normal file
File diff suppressed because it is too large
Load Diff
617
codex-rs/hooks/src/engine/output_parser.rs
Normal file
617
codex-rs/hooks/src/engine/output_parser.rs
Normal file
@@ -0,0 +1,617 @@
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct UniversalOutput {
|
||||
pub continue_processing: bool,
|
||||
pub stop_reason: Option<String>,
|
||||
pub suppress_output: bool,
|
||||
pub system_message: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct SessionStartOutput {
|
||||
pub universal: UniversalOutput,
|
||||
pub additional_context: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct PreToolUseOutput {
|
||||
pub universal: UniversalOutput,
|
||||
pub block_reason: Option<String>,
|
||||
pub additional_context: Option<String>,
|
||||
pub updated_input: Option<serde_json::Value>,
|
||||
pub invalid_reason: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) enum PermissionRequestDecision {
|
||||
Allow,
|
||||
Deny { message: String },
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct PermissionRequestOutput {
|
||||
pub universal: UniversalOutput,
|
||||
pub decision: Option<PermissionRequestDecision>,
|
||||
pub invalid_reason: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct PostToolUseOutput {
|
||||
pub universal: UniversalOutput,
|
||||
pub should_block: bool,
|
||||
pub reason: Option<String>,
|
||||
pub invalid_block_reason: Option<String>,
|
||||
pub additional_context: Option<String>,
|
||||
pub invalid_reason: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct UserPromptSubmitOutput {
|
||||
pub universal: UniversalOutput,
|
||||
pub should_block: bool,
|
||||
pub reason: Option<String>,
|
||||
pub invalid_block_reason: Option<String>,
|
||||
pub additional_context: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct StopOutput {
|
||||
pub universal: UniversalOutput,
|
||||
pub should_block: bool,
|
||||
pub reason: Option<String>,
|
||||
pub invalid_block_reason: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct StatelessHookOutput {
|
||||
pub universal: UniversalOutput,
|
||||
pub invalid_reason: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct InterruptOutput {
|
||||
pub system_message: Option<String>,
|
||||
}
|
||||
|
||||
use crate::schema::BlockDecisionWire;
|
||||
use crate::schema::HookUniversalOutputWire;
|
||||
use crate::schema::InterruptCommandOutputWire;
|
||||
use crate::schema::PermissionRequestBehaviorWire;
|
||||
use crate::schema::PermissionRequestCommandOutputWire;
|
||||
use crate::schema::PermissionRequestDecisionWire;
|
||||
use crate::schema::PostCompactCommandOutputWire;
|
||||
use crate::schema::PostToolUseCommandOutputWire;
|
||||
use crate::schema::PreCompactCommandOutputWire;
|
||||
use crate::schema::PreToolUseCommandOutputWire;
|
||||
use crate::schema::PreToolUseDecisionWire;
|
||||
use crate::schema::PreToolUsePermissionDecisionWire;
|
||||
use crate::schema::SessionStartCommandOutputWire;
|
||||
use crate::schema::StopCommandOutputWire;
|
||||
use crate::schema::SubagentStartCommandOutputWire;
|
||||
use crate::schema::SubagentStopCommandOutputWire;
|
||||
use crate::schema::UserPromptSubmitCommandOutputWire;
|
||||
|
||||
pub(crate) fn parse_session_start(stdout: &str) -> Option<SessionStartOutput> {
|
||||
let wire: SessionStartCommandOutputWire = parse_json(stdout)?;
|
||||
Some(session_start_output(
|
||||
wire.universal,
|
||||
wire.hook_specific_output
|
||||
.and_then(|output| output.additional_context),
|
||||
))
|
||||
}
|
||||
|
||||
pub(crate) fn parse_subagent_start(stdout: &str) -> Option<SessionStartOutput> {
|
||||
let wire: SubagentStartCommandOutputWire = parse_json(stdout)?;
|
||||
Some(session_start_output(
|
||||
wire.universal,
|
||||
wire.hook_specific_output
|
||||
.and_then(|output| output.additional_context),
|
||||
))
|
||||
}
|
||||
|
||||
fn session_start_output(
|
||||
universal: HookUniversalOutputWire,
|
||||
additional_context: Option<String>,
|
||||
) -> SessionStartOutput {
|
||||
SessionStartOutput {
|
||||
universal: UniversalOutput::from(universal),
|
||||
additional_context,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn parse_pre_tool_use(stdout: &str) -> Option<PreToolUseOutput> {
|
||||
let PreToolUseCommandOutputWire {
|
||||
universal: universal_wire,
|
||||
decision,
|
||||
reason,
|
||||
hook_specific_output,
|
||||
} = parse_json(stdout)?;
|
||||
let universal = UniversalOutput::from(universal_wire);
|
||||
let hook_specific_output = hook_specific_output.as_ref();
|
||||
let additional_context =
|
||||
hook_specific_output.and_then(|output| output.additional_context.clone());
|
||||
let use_hook_specific_decision = hook_specific_output.is_some_and(|output| {
|
||||
output.permission_decision.is_some()
|
||||
|| output.permission_decision_reason.is_some()
|
||||
|| output.updated_input.is_some()
|
||||
});
|
||||
let invalid_reason = unsupported_pre_tool_use_universal(&universal).or_else(|| {
|
||||
if use_hook_specific_decision {
|
||||
hook_specific_output.and_then(unsupported_pre_tool_use_hook_specific_output)
|
||||
} else {
|
||||
unsupported_pre_tool_use_legacy_decision(decision.as_ref(), reason.as_deref())
|
||||
}
|
||||
});
|
||||
let block_reason = if invalid_reason.is_none() {
|
||||
if use_hook_specific_decision {
|
||||
hook_specific_output.and_then(|output| match output.permission_decision {
|
||||
Some(PreToolUsePermissionDecisionWire::Deny) => output
|
||||
.permission_decision_reason
|
||||
.as_deref()
|
||||
.and_then(trimmed_reason),
|
||||
_ => None,
|
||||
})
|
||||
} else {
|
||||
match decision.as_ref() {
|
||||
Some(PreToolUseDecisionWire::Block) => reason.as_deref().and_then(trimmed_reason),
|
||||
Some(PreToolUseDecisionWire::Approve) | None => None,
|
||||
}
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let updated_input = if invalid_reason.is_none() {
|
||||
hook_specific_output.and_then(|output| {
|
||||
matches!(
|
||||
output.permission_decision,
|
||||
Some(PreToolUsePermissionDecisionWire::Allow)
|
||||
)
|
||||
.then(|| output.updated_input.clone())
|
||||
.flatten()
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
Some(PreToolUseOutput {
|
||||
universal,
|
||||
block_reason,
|
||||
additional_context,
|
||||
updated_input,
|
||||
invalid_reason,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn parse_permission_request(stdout: &str) -> Option<PermissionRequestOutput> {
|
||||
let wire: PermissionRequestCommandOutputWire = parse_json(stdout)?;
|
||||
let universal = UniversalOutput::from(wire.universal);
|
||||
let hook_specific_output = wire.hook_specific_output.as_ref();
|
||||
let decision = hook_specific_output.and_then(|output| output.decision.as_ref());
|
||||
let invalid_reason = unsupported_permission_request_universal(&universal).or_else(|| {
|
||||
hook_specific_output.and_then(|output| {
|
||||
unsupported_permission_request_hook_specific_output(output.decision.as_ref())
|
||||
})
|
||||
});
|
||||
let decision = if invalid_reason.is_none() {
|
||||
decision.map(permission_request_decision)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
Some(PermissionRequestOutput {
|
||||
universal,
|
||||
decision,
|
||||
invalid_reason,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn parse_post_tool_use(stdout: &str) -> Option<PostToolUseOutput> {
|
||||
let wire: PostToolUseCommandOutputWire = parse_json(stdout)?;
|
||||
let universal = UniversalOutput::from(wire.universal);
|
||||
let invalid_reason = unsupported_post_tool_use_universal(&universal).or_else(|| {
|
||||
wire.hook_specific_output
|
||||
.as_ref()
|
||||
.and_then(unsupported_post_tool_use_hook_specific_output)
|
||||
});
|
||||
let should_block = matches!(wire.decision, Some(BlockDecisionWire::Block));
|
||||
let invalid_block_reason = if should_block
|
||||
&& match wire.reason.as_deref() {
|
||||
Some(reason) => reason.trim().is_empty(),
|
||||
None => true,
|
||||
} {
|
||||
Some(invalid_block_message("PostToolUse"))
|
||||
} else if !should_block && universal.continue_processing && wire.reason.is_some() {
|
||||
Some("PostToolUse hook returned reason without decision".to_string())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let additional_context = wire
|
||||
.hook_specific_output
|
||||
.and_then(|output| output.additional_context);
|
||||
|
||||
Some(PostToolUseOutput {
|
||||
universal,
|
||||
should_block: should_block && invalid_reason.is_none() && invalid_block_reason.is_none(),
|
||||
reason: wire.reason,
|
||||
invalid_block_reason,
|
||||
additional_context,
|
||||
invalid_reason,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn parse_pre_compact(stdout: &str) -> Option<StatelessHookOutput> {
|
||||
let wire: PreCompactCommandOutputWire = parse_json(stdout)?;
|
||||
let universal = UniversalOutput::from(wire.universal);
|
||||
Some(StatelessHookOutput {
|
||||
universal,
|
||||
invalid_reason: None,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn parse_post_compact(stdout: &str) -> Option<StatelessHookOutput> {
|
||||
let wire: PostCompactCommandOutputWire = parse_json(stdout)?;
|
||||
let universal = UniversalOutput::from(wire.universal);
|
||||
Some(StatelessHookOutput {
|
||||
universal,
|
||||
invalid_reason: None,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn parse_interrupt(stdout: &str) -> Option<InterruptOutput> {
|
||||
let wire: InterruptCommandOutputWire = parse_json(stdout)?;
|
||||
Some(InterruptOutput {
|
||||
system_message: wire.system_message,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn parse_user_prompt_submit(stdout: &str) -> Option<UserPromptSubmitOutput> {
|
||||
let wire: UserPromptSubmitCommandOutputWire = parse_json(stdout)?;
|
||||
let should_block = matches!(wire.decision, Some(BlockDecisionWire::Block));
|
||||
let invalid_block_reason = if should_block
|
||||
&& match wire.reason.as_deref() {
|
||||
Some(reason) => reason.trim().is_empty(),
|
||||
None => true,
|
||||
} {
|
||||
Some(invalid_block_message("UserPromptSubmit"))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let additional_context = wire
|
||||
.hook_specific_output
|
||||
.and_then(|output| output.additional_context);
|
||||
Some(UserPromptSubmitOutput {
|
||||
universal: UniversalOutput::from(wire.universal),
|
||||
should_block: should_block && invalid_block_reason.is_none(),
|
||||
reason: wire.reason,
|
||||
invalid_block_reason,
|
||||
additional_context,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn parse_stop(stdout: &str) -> Option<StopOutput> {
|
||||
let wire: StopCommandOutputWire = parse_json(stdout)?;
|
||||
Some(stop_output(
|
||||
wire.universal,
|
||||
wire.decision,
|
||||
wire.reason,
|
||||
"Stop",
|
||||
))
|
||||
}
|
||||
|
||||
pub(crate) fn parse_subagent_stop(stdout: &str) -> Option<StopOutput> {
|
||||
let wire: SubagentStopCommandOutputWire = parse_json(stdout)?;
|
||||
Some(stop_output(
|
||||
wire.universal,
|
||||
wire.decision,
|
||||
wire.reason,
|
||||
"SubagentStop",
|
||||
))
|
||||
}
|
||||
|
||||
fn stop_output(
|
||||
universal: HookUniversalOutputWire,
|
||||
decision: Option<BlockDecisionWire>,
|
||||
reason: Option<String>,
|
||||
event_name: &str,
|
||||
) -> StopOutput {
|
||||
let should_block = matches!(decision, Some(BlockDecisionWire::Block));
|
||||
let invalid_block_reason = if should_block
|
||||
&& match reason.as_deref() {
|
||||
Some(reason) => reason.trim().is_empty(),
|
||||
None => true,
|
||||
} {
|
||||
Some(invalid_block_message(event_name))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
StopOutput {
|
||||
universal: UniversalOutput::from(universal),
|
||||
should_block: should_block && invalid_block_reason.is_none(),
|
||||
reason,
|
||||
invalid_block_reason,
|
||||
}
|
||||
}
|
||||
|
||||
impl From<HookUniversalOutputWire> for UniversalOutput {
|
||||
fn from(value: HookUniversalOutputWire) -> Self {
|
||||
Self {
|
||||
continue_processing: value.r#continue,
|
||||
stop_reason: value.stop_reason,
|
||||
suppress_output: value.suppress_output,
|
||||
system_message: value.system_message,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_json<T>(stdout: &str) -> Option<T>
|
||||
where
|
||||
T: for<'de> serde::Deserialize<'de>,
|
||||
{
|
||||
let trimmed = stdout.trim();
|
||||
if trimmed.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let value: serde_json::Value = serde_json::from_str(trimmed).ok()?;
|
||||
if !value.is_object() {
|
||||
return None;
|
||||
}
|
||||
serde_json::from_value(value).ok()
|
||||
}
|
||||
|
||||
pub(crate) fn looks_like_json(stdout: &str) -> bool {
|
||||
let trimmed = stdout.trim_start();
|
||||
trimmed.starts_with('{') || trimmed.starts_with('[')
|
||||
}
|
||||
|
||||
fn invalid_block_message(event_name: &str) -> String {
|
||||
format!("{event_name} hook returned decision:block without a non-empty reason")
|
||||
}
|
||||
|
||||
fn unsupported_pre_tool_use_universal(universal: &UniversalOutput) -> Option<String> {
|
||||
if !universal.continue_processing {
|
||||
Some("PreToolUse hook returned unsupported continue:false".to_string())
|
||||
} else if universal.stop_reason.is_some() {
|
||||
Some("PreToolUse hook returned unsupported stopReason".to_string())
|
||||
} else if universal.suppress_output {
|
||||
Some("PreToolUse hook returned unsupported suppressOutput".to_string())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn unsupported_permission_request_universal(universal: &UniversalOutput) -> Option<String> {
|
||||
if !universal.continue_processing {
|
||||
Some("PermissionRequest hook returned unsupported continue:false".to_string())
|
||||
} else if universal.stop_reason.is_some() {
|
||||
Some("PermissionRequest hook returned unsupported stopReason".to_string())
|
||||
} else if universal.suppress_output {
|
||||
Some("PermissionRequest hook returned unsupported suppressOutput".to_string())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn unsupported_post_tool_use_universal(universal: &UniversalOutput) -> Option<String> {
|
||||
if universal.suppress_output {
|
||||
Some("PostToolUse hook returned unsupported suppressOutput".to_string())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn unsupported_permission_request_hook_specific_output(
|
||||
decision: Option<&PermissionRequestDecisionWire>,
|
||||
) -> Option<String> {
|
||||
let decision = decision?;
|
||||
if decision.updated_input.is_some() {
|
||||
Some("PermissionRequest hook returned unsupported updatedInput".to_string())
|
||||
} else if decision.updated_permissions.is_some() {
|
||||
Some("PermissionRequest hook returned unsupported updatedPermissions".to_string())
|
||||
} else if decision.interrupt {
|
||||
Some("PermissionRequest hook returned unsupported interrupt:true".to_string())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn permission_request_decision(
|
||||
decision: &PermissionRequestDecisionWire,
|
||||
) -> PermissionRequestDecision {
|
||||
match decision.behavior {
|
||||
PermissionRequestBehaviorWire::Allow => PermissionRequestDecision::Allow,
|
||||
PermissionRequestBehaviorWire::Deny => PermissionRequestDecision::Deny {
|
||||
message: decision
|
||||
.message
|
||||
.as_deref()
|
||||
.and_then(trimmed_reason)
|
||||
.unwrap_or_else(|| "PermissionRequest hook denied approval".to_string()),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn unsupported_post_tool_use_hook_specific_output(
|
||||
output: &crate::schema::PostToolUseHookSpecificOutputWire,
|
||||
) -> Option<String> {
|
||||
if output.updated_mcp_tool_output.is_some() {
|
||||
Some("PostToolUse hook returned unsupported updatedMCPToolOutput".to_string())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn unsupported_pre_tool_use_hook_specific_output(
|
||||
output: &crate::schema::PreToolUseHookSpecificOutputWire,
|
||||
) -> Option<String> {
|
||||
if output.updated_input.is_some()
|
||||
&& !matches!(
|
||||
output.permission_decision,
|
||||
Some(PreToolUsePermissionDecisionWire::Allow)
|
||||
)
|
||||
{
|
||||
Some("PreToolUse hook returned updatedInput without permissionDecision:allow".to_string())
|
||||
} else {
|
||||
match output.permission_decision {
|
||||
Some(PreToolUsePermissionDecisionWire::Allow) => {
|
||||
output.updated_input.is_none().then(|| {
|
||||
"PreToolUse hook returned unsupported permissionDecision:allow".to_string()
|
||||
})
|
||||
}
|
||||
Some(PreToolUsePermissionDecisionWire::Ask) => {
|
||||
Some("PreToolUse hook returned unsupported permissionDecision:ask".to_string())
|
||||
}
|
||||
Some(PreToolUsePermissionDecisionWire::Deny) => {
|
||||
if output
|
||||
.permission_decision_reason
|
||||
.as_deref()
|
||||
.and_then(trimmed_reason)
|
||||
.is_none()
|
||||
{
|
||||
Some(invalid_pre_tool_use_reason_message())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
None => {
|
||||
if output.permission_decision_reason.is_some() {
|
||||
Some("PreToolUse hook returned permissionDecisionReason without permissionDecision".to_string())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn unsupported_pre_tool_use_legacy_decision(
|
||||
decision: Option<&PreToolUseDecisionWire>,
|
||||
reason: Option<&str>,
|
||||
) -> Option<String> {
|
||||
match decision {
|
||||
Some(PreToolUseDecisionWire::Approve) => {
|
||||
Some("PreToolUse hook returned unsupported decision:approve".to_string())
|
||||
}
|
||||
Some(PreToolUseDecisionWire::Block) => {
|
||||
if reason.and_then(trimmed_reason).is_none() {
|
||||
Some(invalid_block_message("PreToolUse"))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
None => {
|
||||
if reason.is_some() {
|
||||
Some("PreToolUse hook returned reason without decision".to_string())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn invalid_pre_tool_use_reason_message() -> String {
|
||||
"PreToolUse hook returned permissionDecision:deny without a non-empty permissionDecisionReason"
|
||||
.to_string()
|
||||
}
|
||||
|
||||
fn trimmed_reason(reason: &str) -> Option<String> {
|
||||
let trimmed = reason.trim();
|
||||
if trimmed.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(trimmed.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
|
||||
use super::parse_permission_request;
|
||||
use super::parse_user_prompt_submit;
|
||||
|
||||
#[test]
|
||||
fn structured_output_rejects_invalid_shapes_and_types() {
|
||||
for stdout in [
|
||||
"[]",
|
||||
r#"{"systemMessage":123}"#,
|
||||
r#"{"hookSpecificOutput":{"hookEventName":"UserPromptSubmit","additionalContext":123}}"#,
|
||||
r#"{"hookSpecificOutput":{"additionalContext":"missing event name"}}"#,
|
||||
r#"{"hookSpecificOutput":{"hookEventName":"UserPromptSubmit","updatedInput":{}}}"#,
|
||||
r#"{"unexpectedField":true}"#,
|
||||
"{",
|
||||
] {
|
||||
assert!(
|
||||
parse_user_prompt_submit(stdout).is_none(),
|
||||
"invalid structured output should fail: {stdout}",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn permission_request_rejects_reserved_updated_input_field() {
|
||||
let parsed = parse_permission_request(
|
||||
&json!({
|
||||
"continue": true,
|
||||
"hookSpecificOutput": {
|
||||
"hookEventName": "PermissionRequest",
|
||||
"decision": {
|
||||
"behavior": "allow",
|
||||
"updatedInput": {}
|
||||
}
|
||||
}
|
||||
})
|
||||
.to_string(),
|
||||
)
|
||||
.expect("permission request hook output should parse");
|
||||
|
||||
assert_eq!(
|
||||
parsed.invalid_reason,
|
||||
Some("PermissionRequest hook returned unsupported updatedInput".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn permission_request_rejects_reserved_updated_permissions_field() {
|
||||
let parsed = parse_permission_request(
|
||||
&json!({
|
||||
"continue": true,
|
||||
"hookSpecificOutput": {
|
||||
"hookEventName": "PermissionRequest",
|
||||
"decision": {
|
||||
"behavior": "allow",
|
||||
"updatedPermissions": {}
|
||||
}
|
||||
}
|
||||
})
|
||||
.to_string(),
|
||||
)
|
||||
.expect("permission request hook output should parse");
|
||||
|
||||
assert_eq!(
|
||||
parsed.invalid_reason,
|
||||
Some("PermissionRequest hook returned unsupported updatedPermissions".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn permission_request_rejects_reserved_interrupt_field() {
|
||||
let parsed = parse_permission_request(
|
||||
&json!({
|
||||
"continue": true,
|
||||
"hookSpecificOutput": {
|
||||
"hookEventName": "PermissionRequest",
|
||||
"decision": {
|
||||
"behavior": "allow",
|
||||
"interrupt": true
|
||||
}
|
||||
}
|
||||
})
|
||||
.to_string(),
|
||||
)
|
||||
.expect("permission request hook output should parse");
|
||||
|
||||
assert_eq!(
|
||||
parsed.invalid_reason,
|
||||
Some("PermissionRequest hook returned unsupported interrupt:true".to_string())
|
||||
);
|
||||
}
|
||||
}
|
||||
91
codex-rs/hooks/src/engine/plugin_fingerprint.rs
Normal file
91
codex-rs/hooks/src/engine/plugin_fingerprint.rs
Normal file
@@ -0,0 +1,91 @@
|
||||
//! Best-effort source identity for installed plugins used by hook trust.
|
||||
//!
|
||||
//! Hash bundle files, excluding generated Python bytecode, virtual environments,
|
||||
//! and package metadata. This detects source changes, not tampering inside those
|
||||
//! runtime artifacts. Cancellation is checked between entries and bounded reads.
|
||||
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::io::Read;
|
||||
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use sha2::Digest;
|
||||
use sha2::Sha256;
|
||||
|
||||
pub(super) fn plugin_content_hash(
|
||||
root: &AbsolutePathBuf,
|
||||
cancelled: &dyn Fn() -> bool,
|
||||
) -> io::Result<String> {
|
||||
let check_cancelled = || {
|
||||
if cancelled() {
|
||||
Err(io::Error::from(io::ErrorKind::Interrupted))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
check_cancelled()?;
|
||||
if !fs::symlink_metadata(root)?.is_dir() {
|
||||
return Err(io::Error::other("plugin root is not a directory"));
|
||||
}
|
||||
let mut pending = vec![root.to_path_buf()];
|
||||
let mut hash = Sha256::new();
|
||||
hash.update(b"codex-plugin-bundle-v1");
|
||||
let mut buffer = [0_u8; 64 * 1024];
|
||||
while let Some(path) = pending.pop() {
|
||||
check_cancelled()?;
|
||||
let relative_path = path.strip_prefix(root).map_err(io::Error::other)?;
|
||||
if relative_path
|
||||
.file_name()
|
||||
.and_then(std::ffi::OsStr::to_str)
|
||||
.is_some_and(|name| {
|
||||
matches!(name, "__pycache__" | ".venv")
|
||||
|| name.ends_with(".pyc")
|
||||
|| name.ends_with(".egg-info")
|
||||
})
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let name = relative_path.as_os_str().as_encoded_bytes();
|
||||
hash.update((name.len() as u64).to_le_bytes());
|
||||
hash.update(name);
|
||||
let metadata = fs::symlink_metadata(&path)?;
|
||||
if metadata.is_dir() {
|
||||
hash.update(b"directory");
|
||||
let mut entries = Vec::new();
|
||||
for entry in fs::read_dir(&path)? {
|
||||
check_cancelled()?;
|
||||
entries.push(entry?);
|
||||
}
|
||||
entries.sort_by_key(fs::DirEntry::file_name);
|
||||
pending.extend(entries.iter().rev().map(fs::DirEntry::path));
|
||||
} else if metadata.is_file() {
|
||||
hash.update(b"file");
|
||||
let length = metadata.len();
|
||||
hash.update(length.to_le_bytes());
|
||||
// Bound each read to the observed size, detecting growth or truncation
|
||||
// instead of trusting a partial fingerprint of a changing file.
|
||||
check_cancelled()?;
|
||||
let mut file = fs::File::open(&path)?.take(length.saturating_add(1));
|
||||
let mut bytes_read = 0_u64;
|
||||
loop {
|
||||
check_cancelled()?;
|
||||
let count = file.read(&mut buffer)?;
|
||||
if count == 0 {
|
||||
break;
|
||||
}
|
||||
bytes_read += count as u64;
|
||||
hash.update(&buffer[..count]);
|
||||
}
|
||||
if bytes_read != length {
|
||||
return Err(io::Error::other("plugin file changed while fingerprinting"));
|
||||
}
|
||||
} else {
|
||||
return Err(io::Error::other(format!(
|
||||
"unsupported plugin entry type: {}",
|
||||
path.display()
|
||||
)));
|
||||
}
|
||||
}
|
||||
check_cancelled()?;
|
||||
Ok(format!("sha256:{:x}", hash.finalize()))
|
||||
}
|
||||
115
codex-rs/hooks/src/engine/plugin_trust.rs
Normal file
115
codex-rs/hooks/src/engine/plugin_trust.rs
Normal file
@@ -0,0 +1,115 @@
|
||||
//! Verifies plugin contents at execution, including one-time legacy approval migration.
|
||||
//!
|
||||
//! Runtime discovery stores declarations and approvals without scanning bundles. Each
|
||||
//! execution verifies fresh contents; dropping its future cancels the scan. Legacy
|
||||
//! approvals share one immutable bundle baseline per plugin and config home, across
|
||||
//! hooks, profiles, versions, and sessions.
|
||||
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::io::Write;
|
||||
|
||||
use codex_config::ConfigLayerSource;
|
||||
use codex_config::ConfigLayerStack;
|
||||
use sha2::Digest;
|
||||
use sha2::Sha256;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) struct PluginHookTrust {
|
||||
pub(super) root: AbsolutePathBuf,
|
||||
pub(super) declaration_hash: String,
|
||||
pub(super) trusted_hash: String,
|
||||
pub(super) trusted_content_hash: Option<String>,
|
||||
pub(super) legacy_path: Option<AbsolutePathBuf>,
|
||||
}
|
||||
|
||||
impl PluginHookTrust {
|
||||
pub(super) async fn verify(&self) -> io::Result<()> {
|
||||
let trust = self.clone();
|
||||
// Receiver lifetime propagates cancellation even to a queued blocking job.
|
||||
let (cancelled, _cancel_on_drop) = tokio::sync::oneshot::channel::<()>();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let content_hash =
|
||||
super::plugin_fingerprint::plugin_content_hash(&trust.root, &|| {
|
||||
cancelled.is_closed()
|
||||
})?;
|
||||
if cancelled.is_closed() {
|
||||
return Err(io::ErrorKind::Interrupted.into());
|
||||
}
|
||||
if !trust.matches_hash(&content_hash)? {
|
||||
return Err(io::Error::other(
|
||||
"plugin contents changed; hook approval required",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
.map_err(io::Error::other)?
|
||||
}
|
||||
|
||||
pub(super) fn matches_hash(&self, content_hash: &str) -> io::Result<bool> {
|
||||
if self.trusted_hash != self.declaration_hash {
|
||||
return Ok(false);
|
||||
}
|
||||
if let Some(expected) = &self.trusted_content_hash {
|
||||
if expected != content_hash {
|
||||
return Ok(false);
|
||||
}
|
||||
if let Some(path) = &self.legacy_path {
|
||||
// A modern approval also pins the baseline for legacy siblings.
|
||||
migrate_legacy_trust(path, content_hash)?;
|
||||
}
|
||||
return Ok(true);
|
||||
}
|
||||
if let Some(path) = &self.legacy_path {
|
||||
return Ok(migrate_legacy_trust(path, content_hash)? == content_hash);
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn legacy_trust_path(
|
||||
stack: &ConfigLayerStack,
|
||||
plugin_id: &str,
|
||||
) -> Option<AbsolutePathBuf> {
|
||||
let config_file = stack.all_layers_low_to_high().find_map(|layer| {
|
||||
if let ConfigLayerSource::User { file, .. } = &layer.name {
|
||||
Some(file)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
});
|
||||
let config_file = config_file?;
|
||||
let parent = config_file.parent()?;
|
||||
let mut identity = Sha256::new();
|
||||
for part in [
|
||||
config_file.as_os_str().as_encoded_bytes(),
|
||||
plugin_id.as_bytes(),
|
||||
] {
|
||||
identity.update((part.len() as u64).to_le_bytes());
|
||||
identity.update(part);
|
||||
}
|
||||
let directory = parent.join(".hook-trust");
|
||||
Some(directory.join(format!("{:x}", identity.finalize())))
|
||||
}
|
||||
|
||||
fn migrate_legacy_trust(path: &AbsolutePathBuf, current_hash: &str) -> io::Result<String> {
|
||||
match fs::read_to_string(path) {
|
||||
Ok(baseline) => return Ok(baseline),
|
||||
Err(err) if err.kind() == io::ErrorKind::NotFound => {}
|
||||
Err(err) => return Err(err),
|
||||
}
|
||||
let directory = path
|
||||
.parent()
|
||||
.ok_or_else(|| io::Error::other("hook trust baseline has no parent"))?;
|
||||
fs::create_dir_all(directory.as_path())?;
|
||||
let mut temporary = tempfile::NamedTempFile::new_in(directory)?;
|
||||
temporary.write_all(current_hash.as_bytes())?;
|
||||
temporary.as_file().sync_all()?;
|
||||
match temporary.persist_noclobber(path) {
|
||||
Ok(_) => Ok(current_hash.to_owned()),
|
||||
Err(err) if err.error.kind() == io::ErrorKind::AlreadyExists => fs::read_to_string(path),
|
||||
Err(err) => Err(err.error),
|
||||
}
|
||||
}
|
||||
168
codex-rs/hooks/src/engine/schema_loader.rs
Normal file
168
codex-rs/hooks/src/engine/schema_loader.rs
Normal file
@@ -0,0 +1,168 @@
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub(crate) struct GeneratedHookSchemas {
|
||||
pub post_tool_use_command_input: Value,
|
||||
pub post_tool_use_command_output: Value,
|
||||
pub permission_request_command_input: Value,
|
||||
pub permission_request_command_output: Value,
|
||||
pub post_compact_command_input: Value,
|
||||
pub post_compact_command_output: Value,
|
||||
pub pre_tool_use_command_input: Value,
|
||||
pub pre_tool_use_command_output: Value,
|
||||
pub pre_compact_command_input: Value,
|
||||
pub pre_compact_command_output: Value,
|
||||
pub session_start_command_input: Value,
|
||||
pub session_start_command_output: Value,
|
||||
pub session_end_command_input: Value,
|
||||
pub subagent_start_command_input: Value,
|
||||
pub subagent_start_command_output: Value,
|
||||
pub subagent_stop_command_input: Value,
|
||||
pub subagent_stop_command_output: Value,
|
||||
pub user_prompt_submit_command_input: Value,
|
||||
pub user_prompt_submit_command_output: Value,
|
||||
pub stop_command_input: Value,
|
||||
pub stop_command_output: Value,
|
||||
pub interrupt_command_input: Value,
|
||||
pub interrupt_command_output: Value,
|
||||
}
|
||||
|
||||
pub(crate) fn generated_hook_schemas() -> &'static GeneratedHookSchemas {
|
||||
static SCHEMAS: OnceLock<GeneratedHookSchemas> = OnceLock::new();
|
||||
SCHEMAS.get_or_init(|| GeneratedHookSchemas {
|
||||
post_tool_use_command_input: parse_json_schema(
|
||||
"post-tool-use.command.input",
|
||||
include_str!("../../schema/generated/post-tool-use.command.input.schema.json"),
|
||||
),
|
||||
post_tool_use_command_output: parse_json_schema(
|
||||
"post-tool-use.command.output",
|
||||
include_str!("../../schema/generated/post-tool-use.command.output.schema.json"),
|
||||
),
|
||||
permission_request_command_input: parse_json_schema(
|
||||
"permission-request.command.input",
|
||||
include_str!("../../schema/generated/permission-request.command.input.schema.json"),
|
||||
),
|
||||
permission_request_command_output: parse_json_schema(
|
||||
"permission-request.command.output",
|
||||
include_str!("../../schema/generated/permission-request.command.output.schema.json"),
|
||||
),
|
||||
post_compact_command_input: parse_json_schema(
|
||||
"post-compact.command.input",
|
||||
include_str!("../../schema/generated/post-compact.command.input.schema.json"),
|
||||
),
|
||||
post_compact_command_output: parse_json_schema(
|
||||
"post-compact.command.output",
|
||||
include_str!("../../schema/generated/post-compact.command.output.schema.json"),
|
||||
),
|
||||
pre_tool_use_command_input: parse_json_schema(
|
||||
"pre-tool-use.command.input",
|
||||
include_str!("../../schema/generated/pre-tool-use.command.input.schema.json"),
|
||||
),
|
||||
pre_tool_use_command_output: parse_json_schema(
|
||||
"pre-tool-use.command.output",
|
||||
include_str!("../../schema/generated/pre-tool-use.command.output.schema.json"),
|
||||
),
|
||||
pre_compact_command_input: parse_json_schema(
|
||||
"pre-compact.command.input",
|
||||
include_str!("../../schema/generated/pre-compact.command.input.schema.json"),
|
||||
),
|
||||
pre_compact_command_output: parse_json_schema(
|
||||
"pre-compact.command.output",
|
||||
include_str!("../../schema/generated/pre-compact.command.output.schema.json"),
|
||||
),
|
||||
session_start_command_input: parse_json_schema(
|
||||
"session-start.command.input",
|
||||
include_str!("../../schema/generated/session-start.command.input.schema.json"),
|
||||
),
|
||||
session_start_command_output: parse_json_schema(
|
||||
"session-start.command.output",
|
||||
include_str!("../../schema/generated/session-start.command.output.schema.json"),
|
||||
),
|
||||
session_end_command_input: parse_json_schema(
|
||||
"session-end.command.input",
|
||||
include_str!("../../schema/generated/session-end.command.input.schema.json"),
|
||||
),
|
||||
subagent_start_command_input: parse_json_schema(
|
||||
"subagent-start.command.input",
|
||||
include_str!("../../schema/generated/subagent-start.command.input.schema.json"),
|
||||
),
|
||||
subagent_start_command_output: parse_json_schema(
|
||||
"subagent-start.command.output",
|
||||
include_str!("../../schema/generated/subagent-start.command.output.schema.json"),
|
||||
),
|
||||
subagent_stop_command_input: parse_json_schema(
|
||||
"subagent-stop.command.input",
|
||||
include_str!("../../schema/generated/subagent-stop.command.input.schema.json"),
|
||||
),
|
||||
subagent_stop_command_output: parse_json_schema(
|
||||
"subagent-stop.command.output",
|
||||
include_str!("../../schema/generated/subagent-stop.command.output.schema.json"),
|
||||
),
|
||||
user_prompt_submit_command_input: parse_json_schema(
|
||||
"user-prompt-submit.command.input",
|
||||
include_str!("../../schema/generated/user-prompt-submit.command.input.schema.json"),
|
||||
),
|
||||
user_prompt_submit_command_output: parse_json_schema(
|
||||
"user-prompt-submit.command.output",
|
||||
include_str!("../../schema/generated/user-prompt-submit.command.output.schema.json"),
|
||||
),
|
||||
stop_command_input: parse_json_schema(
|
||||
"stop.command.input",
|
||||
include_str!("../../schema/generated/stop.command.input.schema.json"),
|
||||
),
|
||||
stop_command_output: parse_json_schema(
|
||||
"stop.command.output",
|
||||
include_str!("../../schema/generated/stop.command.output.schema.json"),
|
||||
),
|
||||
interrupt_command_input: parse_json_schema(
|
||||
"interrupt.command.input",
|
||||
include_str!("../../schema/generated/interrupt.command.input.schema.json"),
|
||||
),
|
||||
interrupt_command_output: parse_json_schema(
|
||||
"interrupt.command.output",
|
||||
include_str!("../../schema/generated/interrupt.command.output.schema.json"),
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_json_schema(name: &str, schema: &str) -> Value {
|
||||
serde_json::from_str(schema)
|
||||
.unwrap_or_else(|err| panic!("invalid generated hooks schema {name}: {err}"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::generated_hook_schemas;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn loads_generated_hook_schemas() {
|
||||
let schemas = generated_hook_schemas();
|
||||
|
||||
assert_eq!(schemas.post_tool_use_command_input["type"], "object");
|
||||
assert_eq!(schemas.post_tool_use_command_output["type"], "object");
|
||||
assert_eq!(schemas.permission_request_command_input["type"], "object");
|
||||
assert_eq!(schemas.permission_request_command_output["type"], "object");
|
||||
assert_eq!(schemas.post_compact_command_input["type"], "object");
|
||||
assert_eq!(schemas.post_compact_command_output["type"], "object");
|
||||
assert_eq!(schemas.pre_tool_use_command_input["type"], "object");
|
||||
assert_eq!(schemas.pre_tool_use_command_output["type"], "object");
|
||||
assert_eq!(schemas.pre_compact_command_input["type"], "object");
|
||||
assert_eq!(schemas.pre_compact_command_output["type"], "object");
|
||||
assert_eq!(schemas.session_start_command_input["type"], "object");
|
||||
assert_eq!(schemas.session_start_command_output["type"], "object");
|
||||
assert_eq!(schemas.session_end_command_input["type"], "object");
|
||||
assert_eq!(schemas.subagent_start_command_input["type"], "object");
|
||||
assert_eq!(schemas.subagent_start_command_output["type"], "object");
|
||||
assert_eq!(schemas.subagent_stop_command_input["type"], "object");
|
||||
assert_eq!(schemas.subagent_stop_command_output["type"], "object");
|
||||
assert_eq!(schemas.user_prompt_submit_command_input["type"], "object");
|
||||
assert_eq!(schemas.user_prompt_submit_command_output["type"], "object");
|
||||
assert_eq!(schemas.stop_command_input["type"], "object");
|
||||
assert_eq!(schemas.stop_command_output["type"], "object");
|
||||
assert_eq!(schemas.interrupt_command_input["type"], "object");
|
||||
assert_eq!(schemas.interrupt_command_output["type"], "object");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user