diff --git a/codex-rs/hooks/src/engine/async_command.rs b/codex-rs/hooks/src/engine/async_command.rs new file mode 100644 index 0000000000..2e9dbc9a44 --- /dev/null +++ b/codex-rs/hooks/src/engine/async_command.rs @@ -0,0 +1,254 @@ +//! Session-scoped runtime for detached command hooks. +//! +//! Async hooks cannot affect the operation that launched them. Successful +//! informational output is queued until a later user turn accepts input. Core +//! snapshots the ready completions at turn entry, before any hooks for that +//! turn run, so output that completes during the turn cannot race into it. +//! +//! The runtime survives hook configuration refreshes and bounds concurrent +//! commands, queued completions, and the amount delivered to one request. + +use std::collections::BTreeMap; +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::Mutex; +use std::sync::MutexGuard; + +use codex_protocol::ThreadId; +use codex_utils_output_truncation::approx_token_count; +use tokio::task::JoinSet; + +use super::CommandShell; +use super::ConfiguredHandler; +use super::command_runner::run_command; +use super::output_parser; +use crate::output_spill::HookOutputSpiller; + +const MAX_QUEUED_COMPLETIONS: usize = 64; +const MAX_IN_FLIGHT_COMMANDS: usize = 32; +const MAX_DELIVERED_COMPLETIONS_PER_REQUEST: usize = 8; +const MAX_DELIVERED_OUTPUT_TOKENS_PER_REQUEST: usize = 10_000; + +/// Informational async hook output ready to be recorded for a model request. +#[derive(Debug, Default, PartialEq, Eq)] +pub struct AsyncHookDelivery { + /// Context fragments to inject into model-visible conversation history. + pub additional_contexts: Vec, + /// User-visible messages to emit without adding them to model context. + pub system_messages: Vec, +} + +/// Async output that was ready when a user turn began. +/// +/// Dropping this value leaves the output queued. Calling [`Self::accept_turn`] +/// drains the snapshot for an accepted user turn. +pub struct PendingAsyncHookDelivery { + runtime: AsyncCommandRuntime, + ready: Vec, +} + +impl PendingAsyncHookDelivery { + pub fn accept_turn(self) -> AsyncHookDelivery { + self.runtime.drain_for_accepted_turn(self.ready) + } +} + +/// Shared runtime state for async commands launched during one Codex session. +/// +/// Clones refer to the same in-flight tasks and queued output. This lets hook +/// configuration refresh without orphaning work. +#[derive(Clone)] +pub(crate) struct AsyncCommandRuntime { + inner: Arc, +} + +struct AsyncCommandRuntimeInner { + state: Mutex, + output_spiller: HookOutputSpiller, +} + +impl AsyncCommandRuntimeInner { + fn lock_state(&self) -> MutexGuard<'_, AsyncCommandRuntimeState> { + self.state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + } +} + +#[derive(Default)] +struct AsyncCommandRuntimeState { + next_launch_sequence: u64, + shutting_down: bool, + completions: BTreeMap, + tasks: JoinSet<()>, +} + +impl AsyncCommandRuntime { + /// Creates an empty runtime for a newly started Codex session. + pub(crate) fn new() -> Self { + Self { + inner: Arc::new(AsyncCommandRuntimeInner { + state: Mutex::new(AsyncCommandRuntimeState::default()), + output_spiller: HookOutputSpiller::new(), + }), + } + } + + /// Returns the spiller shared by synchronous and asynchronous hook output. + /// + /// Keeping it with the refresh-stable runtime lets detached commands spill + /// output even if hook configuration changes before they finish. + pub(crate) fn output_spiller(&self) -> &HookOutputSpiller { + &self.inner.output_spiller + } + + /// Captures which async completions were ready when a user turn began. + /// + /// A completion registered after this snapshot is ineligible for the + /// accepted user turn associated with the snapshot, even if the command + /// finishes before that turn reaches the model. + pub(crate) fn pending_delivery(&self) -> PendingAsyncHookDelivery { + let state = self.inner.lock_state(); + PendingAsyncHookDelivery { + runtime: self.clone(), + ready: state.completions.keys().copied().collect(), + } + } + + /// Launches one command without waiting for it or emitting hook lifecycle events. + /// + /// Only successful informational output is queued. Control decisions are + /// discarded by the async parser. + pub(crate) fn spawn( + &self, + shell: CommandShell, + handler: ConfiguredHandler, + configured_order: usize, + input_json: String, + cwd: PathBuf, + thread_id: ThreadId, + ) { + let mut state = self.inner.lock_state(); + while state.tasks.try_join_next().is_some() {} + if state.shutting_down { + return; + } + if state.tasks.len() >= MAX_IN_FLIGHT_COMMANDS { + tracing::warn!( + event_name = ?handler.event_name, + hook_source = ?handler.source, + limit = MAX_IN_FLIGHT_COMMANDS, + "skipping async hook command after reaching the session concurrency limit" + ); + return; + } + + let launch_sequence = state.next_launch_sequence; + state.next_launch_sequence = state.next_launch_sequence.saturating_add(1); + let inner = Arc::clone(&self.inner); + state.tasks.spawn(async move { + let result = run_command(&shell, &handler, configured_order, &input_json, &cwd).await; + tracing::debug!( + event_name = ?handler.event_name, + hook_source = ?handler.source, + exit_code = result.exit_code, + duration_ms = result.duration_ms, + failed = result.error.is_some(), + "async hook command completed" + ); + if result.error.is_some() || result.exit_code != Some(0) { + return; + } + let Some(mut output) = + output_parser::parse_async_informational(handler.event_name, &result.stdout) + else { + return; + }; + output.additional_context = inner + .output_spiller + .maybe_spill_optional_text(thread_id, output.additional_context) + .await; + output.system_message = inner + .output_spiller + .maybe_spill_optional_text(thread_id, output.system_message) + .await; + let mut state = inner.lock_state(); + if state.shutting_down { + return; + } + state.completions.insert(launch_sequence, output); + if state.completions.len() > MAX_QUEUED_COMPLETIONS + && let Some((oldest, _)) = state.completions.pop_first() + { + tracing::warn!( + launch_sequence = oldest, + "dropping queued async hook output after reaching the session limit" + ); + } + }); + } + + /// Drains output that was ready when an accepted user turn began. + /// + /// Delivery is bounded; remaining output stays queued for later accepted + /// user turns. + fn drain_for_accepted_turn(&self, ready: Vec) -> AsyncHookDelivery { + let mut state = self.inner.lock_state(); + let mut eligible = Vec::new(); + let mut output_tokens = 0usize; + for launch_sequence in ready { + let Some(completion) = state.completions.get(&launch_sequence) else { + continue; + }; + if eligible.len() >= MAX_DELIVERED_COMPLETIONS_PER_REQUEST { + break; + } + let completion_output_tokens = completion + .additional_context + .as_deref() + .into_iter() + .chain(completion.system_message.as_deref()) + .map(approx_token_count) + .fold(0, usize::saturating_add); + if output_tokens.saturating_add(completion_output_tokens) + > MAX_DELIVERED_OUTPUT_TOKENS_PER_REQUEST + { + break; + } + eligible.push(launch_sequence); + output_tokens = output_tokens.saturating_add(completion_output_tokens); + } + let mut delivery = AsyncHookDelivery::default(); + for launch_sequence in eligible { + let Some(completion) = state.completions.remove(&launch_sequence) else { + continue; + }; + if let Some(additional_context) = completion.additional_context { + delivery.additional_contexts.push(additional_context); + } + if let Some(system_message) = completion.system_message { + delivery.system_messages.push(system_message); + } + } + delivery + } + + /// Stops accepting output, clears queued completions, and aborts all tasks. + /// + /// Shutdown waits for every aborted Tokio task so no detached hook command + /// remains owned by the session after this method returns. + pub(crate) async fn shutdown(&self) { + let mut tasks = { + let mut state = self.inner.lock_state(); + state.shutting_down = true; + state.completions.clear(); + std::mem::take(&mut state.tasks) + }; + tasks.abort_all(); + while tasks.join_next().await.is_some() {} + } +} + +#[cfg(test)] +#[path = "async_command_tests.rs"] +mod tests; diff --git a/codex-rs/hooks/src/engine/async_command_tests.rs b/codex-rs/hooks/src/engine/async_command_tests.rs new file mode 100644 index 0000000000..e9b03f613f --- /dev/null +++ b/codex-rs/hooks/src/engine/async_command_tests.rs @@ -0,0 +1,133 @@ +use pretty_assertions::assert_eq; + +use super::AsyncCommandRuntime; +use super::AsyncHookDelivery; +use super::MAX_DELIVERED_OUTPUT_TOKENS_PER_REQUEST; +use super::MAX_IN_FLIGHT_COMMANDS; +use crate::engine::CommandShell; +use crate::engine::ConfiguredHandler; +use crate::engine::output_parser::AsyncInformationalOutput; +use codex_protocol::ThreadId; +use codex_protocol::protocol::HookEventName; +use codex_protocol::protocol::HookSource; +use codex_utils_absolute_path::AbsolutePathBuf; +use std::collections::HashMap; + +enum TestOutput<'a> { + AdditionalContext(&'a str), + SystemMessage(&'a str), +} + +fn context_delivery(text: impl Into) -> AsyncHookDelivery { + AsyncHookDelivery { + additional_contexts: vec![text.into()], + ..Default::default() + } +} + +fn complete(runtime: &AsyncCommandRuntime, launch_sequence: u64, output: TestOutput<'_>) { + let mut state = runtime.inner.lock_state(); + let (additional_context, system_message) = match output { + TestOutput::AdditionalContext(text) => (Some(text.to_string()), None), + TestOutput::SystemMessage(text) => (None, Some(text.to_string())), + }; + state.completions.insert( + launch_sequence, + AsyncInformationalOutput { + additional_context, + system_message, + }, + ); +} + +#[test] +fn completion_after_turn_snapshot_waits_for_following_turn() { + let runtime = AsyncCommandRuntime::new(); + let pending = runtime.pending_delivery(); + complete( + &runtime, + /*launch_sequence*/ 0, + TestOutput::AdditionalContext("late"), + ); + + assert_eq!(pending.accept_turn(), Default::default()); + + let delivery = runtime.pending_delivery().accept_turn(); + assert_eq!(delivery, context_delivery("late")); +} + +#[test] +fn unfinished_earlier_launch_does_not_block_ready_output() { + let runtime = AsyncCommandRuntime::new(); + complete( + &runtime, + /*launch_sequence*/ 1, + TestOutput::AdditionalContext("ready"), + ); + + let delivery = runtime.pending_delivery().accept_turn(); + assert_eq!(delivery, context_delivery("ready")); +} + +#[tokio::test] +async fn launch_is_skipped_at_session_concurrency_limit() { + let runtime = AsyncCommandRuntime::new(); + { + let mut state = runtime.inner.lock_state(); + for _ in 0..MAX_IN_FLIGHT_COMMANDS { + state.tasks.spawn(std::future::pending()); + } + } + + runtime.spawn( + CommandShell { + program: String::new(), + args: Vec::new(), + }, + ConfiguredHandler { + event_name: HookEventName::PreToolUse, + matcher: None, + command: "exit 0".to_string(), + timeout_sec: 5, + status_message: None, + source_path: AbsolutePathBuf::current_dir().expect("current dir"), + source: HookSource::User, + display_order: 0, + env: HashMap::new(), + }, + /*configured_order*/ 0, + String::new(), + std::env::current_dir().expect("current dir"), + ThreadId::new(), + ); + + assert_eq!(runtime.inner.lock_state().next_launch_sequence, 0); + runtime.shutdown().await; +} + +#[test] +fn shared_output_budget_leaves_remaining_completions_queued() { + let runtime = AsyncCommandRuntime::new(); + let output = "x".repeat(MAX_DELIVERED_OUTPUT_TOKENS_PER_REQUEST); + for (launch_sequence, output) in (0_u64..).zip([ + TestOutput::AdditionalContext(&output), + TestOutput::SystemMessage(&output), + TestOutput::AdditionalContext(&output), + TestOutput::SystemMessage(&output), + TestOutput::AdditionalContext(&output), + ]) { + complete(&runtime, launch_sequence, output); + } + + let first_delivery = runtime.pending_delivery().accept_turn(); + assert_eq!( + first_delivery, + super::AsyncHookDelivery { + additional_contexts: vec![output.clone(), output.clone()], + system_messages: vec![output.clone(), output.clone()], + } + ); + + let second_delivery = runtime.pending_delivery().accept_turn(); + assert_eq!(second_delivery, context_delivery(output)); +} diff --git a/codex-rs/hooks/src/engine/mod.rs b/codex-rs/hooks/src/engine/mod.rs index 859fc54069..171e292414 100644 --- a/codex-rs/hooks/src/engine/mod.rs +++ b/codex-rs/hooks/src/engine/mod.rs @@ -1,3 +1,5 @@ +#[allow(dead_code)] +pub(crate) mod async_command; pub(crate) mod command_runner; pub(crate) mod discovery; pub(crate) mod dispatcher; diff --git a/codex-rs/hooks/src/engine/output_parser.rs b/codex-rs/hooks/src/engine/output_parser.rs index b4f214146a..28c5415061 100644 --- a/codex-rs/hooks/src/engine/output_parser.rs +++ b/codex-rs/hooks/src/engine/output_parser.rs @@ -1,3 +1,11 @@ +use codex_protocol::protocol::HookEventName; + +#[derive(Debug, PartialEq, Eq)] +pub(crate) struct AsyncInformationalOutput { + pub additional_context: Option, + pub system_message: Option, +} + #[derive(Debug, Clone)] pub(crate) struct UniversalOutput { pub continue_processing: bool, @@ -290,6 +298,76 @@ pub(crate) fn parse_stop(stdout: &str) -> Option { )) } +/// Extracts only informational fields from a successful async command result. +/// +/// Structured output is parsed through an async-only informational view, so +/// blocking decisions, steering, updated input, and every other control field +/// are ignored. Plain stdout remains context only for events that support it. +pub(crate) fn parse_async_informational( + event_name: HookEventName, + stdout: &str, +) -> Option { + let stdout = stdout.trim(); + if stdout.is_empty() { + return None; + } + + let (supports_structured_context, supports_plain_context) = match event_name { + HookEventName::SessionStart + | HookEventName::SubagentStart + | HookEventName::UserPromptSubmit => (true, true), + HookEventName::PreToolUse | HookEventName::PostToolUse => (true, false), + HookEventName::PermissionRequest + | HookEventName::PreCompact + | HookEventName::PostCompact + | HookEventName::SubagentStop + | HookEventName::Stop => (false, false), + }; + + if let Some(wire) = parse_json::(stdout) { + let additional_context = if supports_structured_context { + wire.hook_specific_output + .and_then(|output| output.additional_context) + } else { + None + }; + let parsed = AsyncInformationalOutput { + additional_context, + system_message: wire.system_message, + }; + return (parsed.additional_context.is_some() || parsed.system_message.is_some()) + .then_some(parsed); + } + if looks_like_json(stdout) { + return None; + } + + supports_plain_context.then(|| AsyncInformationalOutput { + additional_context: Some(stdout.to_string()), + system_message: None, + }) +} + +/// Informational fields accepted from async command output. +/// +/// Unknown fields are intentionally ignored because async hooks cannot apply +/// control behavior to the operation that launched them. +#[derive(serde::Deserialize)] +#[serde(rename_all = "camelCase")] +struct AsyncInformationalOutputWire { + #[serde(default)] + system_message: Option, + #[serde(default)] + hook_specific_output: Option, +} + +#[derive(serde::Deserialize)] +#[serde(rename_all = "camelCase")] +struct AsyncInformationalHookSpecificOutputWire { + #[serde(default)] + additional_context: Option, +} + pub(crate) fn parse_subagent_stop(stdout: &str) -> Option { let wire: SubagentStopCommandOutputWire = parse_json(stdout)?; Some(stop_output( @@ -515,11 +593,72 @@ fn trimmed_reason(reason: &str) -> Option { #[cfg(test)] mod tests { + use codex_protocol::protocol::HookEventName; use pretty_assertions::assert_eq; use serde_json::json; + use super::AsyncInformationalOutput; + use super::parse_async_informational; use super::parse_permission_request; + #[test] + fn async_output_keeps_information_and_ignores_control_fields() { + let stdout = json!({ + "continue": false, + "stopReason": "ignored", + "systemMessage": "shown later", + "decision": "block", + "reason": "ignored", + "hookSpecificOutput": { + "hookEventName": "UserPromptSubmit", + "additionalContext": "used later", + "updatedInput": {"ignored": true} + } + }) + .to_string(); + + assert_eq!( + parse_async_informational(HookEventName::UserPromptSubmit, &stdout), + Some(AsyncInformationalOutput { + additional_context: Some("used later".to_string()), + system_message: Some("shown later".to_string()), + }) + ); + assert_eq!( + parse_async_informational(HookEventName::PreToolUse, &stdout), + Some(AsyncInformationalOutput { + additional_context: Some("used later".to_string()), + system_message: Some("shown later".to_string()), + }) + ); + assert_eq!( + parse_async_informational(HookEventName::Stop, &stdout), + Some(AsyncInformationalOutput { + additional_context: None, + system_message: Some("shown later".to_string()), + }) + ); + } + + #[test] + fn async_plain_stdout_is_only_context_for_events_that_already_support_it() { + assert_eq!( + parse_async_informational(HookEventName::UserPromptSubmit, "plain output"), + Some(AsyncInformationalOutput { + additional_context: Some("plain output".to_string()), + system_message: None, + }) + ); + assert_eq!( + parse_async_informational(HookEventName::PreToolUse, "plain output"), + None + ); + assert_eq!( + parse_async_informational(HookEventName::Stop, "plain output"), + None + ); + } + #[test] fn permission_request_rejects_reserved_updated_input_field() { let parsed = parse_permission_request( diff --git a/codex-rs/hooks/src/output_spill.rs b/codex-rs/hooks/src/output_spill.rs index b1828c0825..fd966cb6d1 100644 --- a/codex-rs/hooks/src/output_spill.rs +++ b/codex-rs/hooks/src/output_spill.rs @@ -72,6 +72,17 @@ impl HookOutputSpiller { spilled } + pub(crate) async fn maybe_spill_optional_text( + &self, + thread_id: ThreadId, + text: Option, + ) -> Option { + match text { + Some(text) => Some(self.maybe_spill_text(thread_id, text).await), + None => None, + } + } + pub(crate) async fn maybe_spill_prompt_fragments( &self, thread_id: ThreadId,