From 5529620b24d57748c263ea8eab93fcbbec3ae12f Mon Sep 17 00:00:00 2001 From: jif-oai Date: Mon, 15 Jun 2026 14:56:55 +0200 Subject: [PATCH] skip unused tool hook payloads --- codex-rs/core/src/hook_runtime.rs | 4 +- .../core/src/tools/handlers/apply_patch.rs | 4 + codex-rs/core/src/tools/handlers/mcp.rs | 4 + .../src/tools/handlers/shell/shell_command.rs | 4 + .../handlers/unified_exec/exec_command.rs | 4 + .../handlers/unified_exec/write_stdin.rs | 5 ++ codex-rs/core/src/tools/parallel.rs | 1 - codex-rs/core/src/tools/registry.rs | 39 +++++++--- codex-rs/core/src/tools/registry_tests.rs | 76 ++++++++++++++++++- codex-rs/hooks/src/engine/dispatcher.rs | 28 +++++-- codex-rs/hooks/src/engine/mod.rs | 22 ++++++ codex-rs/hooks/src/registry.rs | 12 +++ 12 files changed, 184 insertions(+), 19 deletions(-) diff --git a/codex-rs/core/src/hook_runtime.rs b/codex-rs/core/src/hook_runtime.rs index 325fd17c9f..c33f6515ee 100644 --- a/codex-rs/core/src/hook_runtime.rs +++ b/codex-rs/core/src/hook_runtime.rs @@ -162,6 +162,7 @@ pub(crate) async fn run_pending_session_start_hooks( pub(crate) async fn run_pre_tool_use_hooks( sess: &Arc, turn_context: &Arc, + hooks: &codex_hooks::Hooks, tool_use_id: String, tool_name: &HookToolName, tool_input: &Value, @@ -180,7 +181,6 @@ pub(crate) async fn run_pre_tool_use_hooks( tool_use_id, tool_input: tool_input.clone(), }; - let hooks = sess.hooks(); let preview_runs = hooks.preview_pre_tool_use(&request); emit_hook_started_events(sess, turn_context, preview_runs).await; @@ -263,6 +263,7 @@ pub(crate) async fn run_permission_request_hooks( pub(crate) async fn run_post_tool_use_hooks( sess: &Arc, turn_context: &Arc, + hooks: &codex_hooks::Hooks, tool_use_id: String, tool_name: String, matcher_aliases: Vec, @@ -284,7 +285,6 @@ pub(crate) async fn run_post_tool_use_hooks( tool_input, tool_response, }; - let hooks = sess.hooks(); let preview_runs = hooks.preview_post_tool_use(&request); emit_hook_started_events(sess, turn_context, preview_runs).await; diff --git a/codex-rs/core/src/tools/handlers/apply_patch.rs b/codex-rs/core/src/tools/handlers/apply_patch.rs index a719e9acd9..3a4e6439c4 100644 --- a/codex-rs/core/src/tools/handlers/apply_patch.rs +++ b/codex-rs/core/src/tools/handlers/apply_patch.rs @@ -466,6 +466,10 @@ impl ApplyPatchHandler { } impl CoreToolRuntime for ApplyPatchHandler { + fn hook_tool_name(&self, invocation: &ToolInvocation) -> Option { + matches!(&invocation.payload, ToolPayload::Custom { .. }).then(HookToolName::apply_patch) + } + fn matches_kind(&self, payload: &ToolPayload) -> bool { matches!(payload, ToolPayload::Custom { .. }) } diff --git a/codex-rs/core/src/tools/handlers/mcp.rs b/codex-rs/core/src/tools/handlers/mcp.rs index efb32aab94..875eda0630 100644 --- a/codex-rs/core/src/tools/handlers/mcp.rs +++ b/codex-rs/core/src/tools/handlers/mcp.rs @@ -162,6 +162,10 @@ impl McpHandler { } impl CoreToolRuntime for McpHandler { + fn hook_tool_name(&self, _invocation: &ToolInvocation) -> Option { + Some(self.hook_tool_name()) + } + fn telemetry_tags<'a>( &'a self, _invocation: &'a ToolInvocation, diff --git a/codex-rs/core/src/tools/handlers/shell/shell_command.rs b/codex-rs/core/src/tools/handlers/shell/shell_command.rs index b754187d4a..d4e7209be4 100644 --- a/codex-rs/core/src/tools/handlers/shell/shell_command.rs +++ b/codex-rs/core/src/tools/handlers/shell/shell_command.rs @@ -208,6 +208,10 @@ impl ShellCommandHandler { } impl CoreToolRuntime for ShellCommandHandler { + fn hook_tool_name(&self, invocation: &ToolInvocation) -> Option { + matches!(&invocation.payload, ToolPayload::Function { .. }).then(HookToolName::bash) + } + fn matches_kind(&self, payload: &ToolPayload) -> bool { matches!(payload, ToolPayload::Function { .. }) } diff --git a/codex-rs/core/src/tools/handlers/unified_exec/exec_command.rs b/codex-rs/core/src/tools/handlers/unified_exec/exec_command.rs index 92a37ae10d..b04c2adbeb 100644 --- a/codex-rs/core/src/tools/handlers/unified_exec/exec_command.rs +++ b/codex-rs/core/src/tools/handlers/unified_exec/exec_command.rs @@ -320,6 +320,10 @@ impl ExecCommandHandler { } impl CoreToolRuntime for ExecCommandHandler { + fn hook_tool_name(&self, invocation: &ToolInvocation) -> Option { + matches!(&invocation.payload, ToolPayload::Function { .. }).then(HookToolName::bash) + } + fn matches_kind(&self, payload: &ToolPayload) -> bool { matches!(payload, ToolPayload::Function { .. }) } diff --git a/codex-rs/core/src/tools/handlers/unified_exec/write_stdin.rs b/codex-rs/core/src/tools/handlers/unified_exec/write_stdin.rs index 8ddce65840..162445fe5d 100644 --- a/codex-rs/core/src/tools/handlers/unified_exec/write_stdin.rs +++ b/codex-rs/core/src/tools/handlers/unified_exec/write_stdin.rs @@ -3,6 +3,7 @@ use crate::tools::context::ToolInvocation; use crate::tools::context::ToolPayload; use crate::tools::context::boxed_tool_output; use crate::tools::handlers::parse_arguments; +use crate::tools::hook_names::HookToolName; use crate::tools::registry::CoreToolRuntime; use crate::tools::registry::PostToolUsePayload; use crate::tools::registry::PreToolUsePayload; @@ -103,6 +104,10 @@ impl WriteStdinHandler { } impl CoreToolRuntime for WriteStdinHandler { + fn hook_tool_name(&self, invocation: &ToolInvocation) -> Option { + matches!(&invocation.payload, ToolPayload::Function { .. }).then(HookToolName::bash) + } + fn matches_kind(&self, payload: &ToolPayload) -> bool { matches!(payload, ToolPayload::Function { .. }) } diff --git a/codex-rs/core/src/tools/parallel.rs b/codex-rs/core/src/tools/parallel.rs index c40886b56c..ab0b122520 100644 --- a/codex-rs/core/src/tools/parallel.rs +++ b/codex-rs/core/src/tools/parallel.rs @@ -217,7 +217,6 @@ impl ToolCallRuntime { result: Box::new(AbortedToolOutput { message: Self::abort_message(call, secs), }), - post_tool_use_payload: None, } } diff --git a/codex-rs/core/src/tools/registry.rs b/codex-rs/core/src/tools/registry.rs index 76e3f5f341..1099d2b199 100644 --- a/codex-rs/core/src/tools/registry.rs +++ b/codex-rs/core/src/tools/registry.rs @@ -65,6 +65,12 @@ pub(crate) trait CoreToolRuntime: ToolExecutor { Box::pin(async { Vec::new() }) } + /// Returns the stable hook identity without constructing the hook payload. + fn hook_tool_name(&self, invocation: &ToolInvocation) -> Option { + matches!(&invocation.payload, ToolPayload::Function { .. }) + .then(|| function_hook_tool_name(invocation)) + } + fn post_tool_use_payload( &self, invocation: &ToolInvocation, @@ -75,7 +81,7 @@ pub(crate) trait CoreToolRuntime: ToolExecutor { }; Some(PostToolUsePayload { - tool_name: function_hook_tool_name(invocation), + tool_name: self.hook_tool_name(invocation)?, tool_use_id: result.post_tool_use_id(&invocation.call_id), tool_input: result .post_tool_use_input(&invocation.payload) @@ -105,7 +111,7 @@ pub(crate) trait CoreToolRuntime: ToolExecutor { }; Some(PreToolUsePayload { - tool_name: function_hook_tool_name(invocation), + tool_name: self.hook_tool_name(invocation)?, tool_input: function_hook_tool_input(arguments), }) } @@ -160,7 +166,6 @@ pub(crate) struct AnyToolResult { pub(crate) call_id: String, pub(crate) payload: ToolPayload, pub(crate) result: Box, - pub(crate) post_tool_use_payload: Option, } impl AnyToolResult { @@ -285,6 +290,10 @@ impl CoreToolRuntime for ExposureOverride { self.handler.waits_for_runtime_cancellation() } + fn hook_tool_name(&self, invocation: &ToolInvocation) -> Option { + self.handler.hook_tool_name(invocation) + } + fn pre_tool_use_payload(&self, invocation: &ToolInvocation) -> Option { self.handler.pre_tool_use_payload(invocation) } @@ -490,10 +499,18 @@ impl ToolRegistry { notify_tool_start(&invocation).await; - if let Some(pre_tool_use_payload) = tool.pre_tool_use_payload(&invocation) { + let pre_tool_use_hooks = invocation.session.hooks(); + let has_matching_pre_tool_use = tool.hook_tool_name(&invocation).is_some_and(|tool_name| { + pre_tool_use_hooks + .has_matching_pre_tool_use(tool_name.name(), tool_name.matcher_aliases()) + }); + if has_matching_pre_tool_use + && let Some(pre_tool_use_payload) = tool.pre_tool_use_payload(&invocation) + { match run_pre_tool_use_hooks( &invocation.session, &invocation.turn, + pre_tool_use_hooks.as_ref(), invocation.call_id.clone(), &pre_tool_use_payload.tool_name, &pre_tool_use_payload.tool_input, @@ -570,11 +587,17 @@ impl ToolRegistry { Err(_) => false, }; emit_metric_for_tool_read(&invocation, success).await; - let post_tool_use_payload = if success { + let post_tool_use_hooks = invocation.session.hooks(); + let has_matching_post_tool_use = + tool.hook_tool_name(&invocation).is_some_and(|tool_name| { + post_tool_use_hooks + .has_matching_post_tool_use(tool_name.name(), tool_name.matcher_aliases()) + }); + let post_tool_use_payload = if success && has_matching_post_tool_use { let guard = response_cell.lock().await; guard .as_ref() - .and_then(|result| result.post_tool_use_payload.clone()) + .and_then(|result| tool.post_tool_use_payload(&invocation, result.result.as_ref())) } else { None }; @@ -583,6 +606,7 @@ impl ToolRegistry { run_post_tool_use_hooks( &invocation.session, &invocation.turn, + post_tool_use_hooks.as_ref(), post_tool_use_payload.tool_use_id, post_tool_use_payload.tool_name.name().to_string(), post_tool_use_payload.tool_name.matcher_aliases().to_vec(), @@ -703,13 +727,10 @@ async fn handle_any_tool( ) .await; } - let post_tool_use_payload = - CoreToolRuntime::post_tool_use_payload(tool, &invocation, output.as_ref()); Ok(AnyToolResult { call_id, payload, result: output, - post_tool_use_payload, }) } diff --git a/codex-rs/core/src/tools/registry_tests.rs b/codex-rs/core/src/tools/registry_tests.rs index 67613f1d08..3265e9afeb 100644 --- a/codex-rs/core/src/tools/registry_tests.rs +++ b/codex-rs/core/src/tools/registry_tests.rs @@ -28,6 +28,56 @@ impl ToolExecutor for TestHandler { impl CoreToolRuntime for TestHandler {} +struct HookPayloadCountingHandler { + tool_name: codex_tools::ToolName, + payloads_built: Arc, +} + +impl ToolExecutor for HookPayloadCountingHandler { + fn tool_name(&self) -> codex_tools::ToolName { + self.tool_name.clone() + } + + fn spec(&self) -> codex_tools::ToolSpec { + test_spec(&self.tool_name) + } + + fn handle(&self, _invocation: ToolInvocation) -> codex_tools::ToolExecutorFuture<'_> { + Box::pin(async { + Ok(Box::new(FunctionToolOutput::from_text( + "ok".to_string(), + /*success*/ Some(true), + )) as Box) + }) + } +} + +impl CoreToolRuntime for HookPayloadCountingHandler { + fn pre_tool_use_payload(&self, invocation: &ToolInvocation) -> Option { + self.payloads_built + .fetch_add(1, std::sync::atomic::Ordering::Relaxed); + Some(PreToolUsePayload { + tool_name: self.hook_tool_name(invocation)?, + tool_input: serde_json::json!({}), + }) + } + + fn post_tool_use_payload( + &self, + invocation: &ToolInvocation, + _result: &dyn ToolOutput, + ) -> Option { + self.payloads_built + .fetch_add(1, std::sync::atomic::Ordering::Relaxed); + Some(PostToolUsePayload { + tool_name: self.hook_tool_name(invocation)?, + tool_use_id: invocation.call_id.clone(), + tool_input: serde_json::json!({}), + tool_response: serde_json::json!({}), + }) + } +} + #[derive(Clone)] enum LifecycleTestResult { Ok { success: bool }, @@ -85,6 +135,30 @@ fn test_spec(tool_name: &codex_tools::ToolName) -> codex_tools::ToolSpec { }) } +#[tokio::test] +async fn dispatch_skips_hook_payloads_without_matching_handlers() -> anyhow::Result<()> { + let (session, turn) = crate::session::tests::make_session_and_context().await; + let tool_name = codex_tools::ToolName::plain("count_payloads"); + let payloads_built = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let handler = Arc::new(HookPayloadCountingHandler { + tool_name: tool_name.clone(), + payloads_built: Arc::clone(&payloads_built), + }) as Arc; + let registry = ToolRegistry::new(HashMap::from([(tool_name.clone(), handler)])); + + registry + .dispatch_any(test_invocation( + Arc::new(session), + Arc::new(turn), + "call-1", + tool_name, + )) + .await?; + + assert_eq!(payloads_built.load(std::sync::atomic::Ordering::Relaxed), 0); + Ok(()) +} + #[derive(Debug, PartialEq, Eq)] enum RecordedToolLifecycle { Start { @@ -334,7 +408,6 @@ fn post_tool_use_feedback_output_keeps_code_mode_result_typed() { /*success*/ None, ), }), - post_tool_use_payload: None, }; assert_eq!( @@ -361,7 +434,6 @@ fn post_tool_use_feedback_output_keeps_code_mode_result_typed() { /*success*/ None, ), }), - post_tool_use_payload: None, }; assert_eq!( diff --git a/codex-rs/hooks/src/engine/dispatcher.rs b/codex-rs/hooks/src/engine/dispatcher.rs index 50822bfc96..2b25e691db 100644 --- a/codex-rs/hooks/src/engine/dispatcher.rs +++ b/codex-rs/hooks/src/engine/dispatcher.rs @@ -43,8 +43,28 @@ pub(crate) fn select_handlers_for_matcher_inputs( // 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 { + .filter(|handler| handler_matches(handler, event_name, matcher_inputs)) + .cloned() + .collect() +} + +pub(crate) fn has_matching_handler( + handlers: &[ConfiguredHandler], + event_name: HookEventName, + matcher_inputs: &[&str], +) -> bool { + handlers + .iter() + .any(|handler| handler_matches(handler, event_name, matcher_inputs)) +} + +fn handler_matches( + handler: &ConfiguredHandler, + event_name: HookEventName, + matcher_inputs: &[&str], +) -> bool { + handler.event_name == event_name + && match event_name { HookEventName::PreToolUse | HookEventName::PermissionRequest | HookEventName::PostToolUse @@ -62,9 +82,7 @@ pub(crate) fn select_handlers_for_matcher_inputs( } } HookEventName::UserPromptSubmit | HookEventName::Stop => true, - }) - .cloned() - .collect() + } } pub(crate) fn running_summary(handler: &ConfiguredHandler) -> HookRunSummary { diff --git a/codex-rs/hooks/src/engine/mod.rs b/codex-rs/hooks/src/engine/mod.rs index 859fc54069..cebdb0c494 100644 --- a/codex-rs/hooks/src/engine/mod.rs +++ b/codex-rs/hooks/src/engine/mod.rs @@ -152,6 +152,15 @@ impl ClaudeHooksEngine { crate::events::pre_tool_use::preview(&self.handlers, request) } + pub(crate) fn has_matching_pre_tool_use( + &self, + tool_name: &str, + matcher_aliases: &[String], + ) -> bool { + let matcher_inputs = crate::events::common::matcher_inputs(tool_name, matcher_aliases); + dispatcher::has_matching_handler(&self.handlers, HookEventName::PreToolUse, &matcher_inputs) + } + pub(crate) fn preview_permission_request( &self, request: &PermissionRequestRequest, @@ -166,6 +175,19 @@ impl ClaudeHooksEngine { crate::events::post_tool_use::preview(&self.handlers, request) } + pub(crate) fn has_matching_post_tool_use( + &self, + tool_name: &str, + matcher_aliases: &[String], + ) -> bool { + let matcher_inputs = crate::events::common::matcher_inputs(tool_name, matcher_aliases); + dispatcher::has_matching_handler( + &self.handlers, + HookEventName::PostToolUse, + &matcher_inputs, + ) + } + pub(crate) async fn run_session_start( &self, request: SessionStartRequest, diff --git a/codex-rs/hooks/src/registry.rs b/codex-rs/hooks/src/registry.rs index 1f4e01aa59..566bc126c0 100644 --- a/codex-rs/hooks/src/registry.rs +++ b/codex-rs/hooks/src/registry.rs @@ -120,6 +120,12 @@ impl Hooks { self.engine.preview_pre_tool_use(request) } + /// Returns whether a `PreToolUse` handler matches this tool identity. + pub fn has_matching_pre_tool_use(&self, tool_name: &str, matcher_aliases: &[String]) -> bool { + self.engine + .has_matching_pre_tool_use(tool_name, matcher_aliases) + } + pub fn preview_permission_request( &self, request: &PermissionRequestRequest, @@ -134,6 +140,12 @@ impl Hooks { self.engine.preview_post_tool_use(request) } + /// Returns whether a `PostToolUse` handler matches this tool identity. + pub fn has_matching_post_tool_use(&self, tool_name: &str, matcher_aliases: &[String]) -> bool { + self.engine + .has_matching_post_tool_use(tool_name, matcher_aliases) + } + pub async fn run_session_start( &self, request: SessionStartRequest,