Add detached async command hooks

This commit is contained in:
Abhinav Vedmala
2026-06-08 11:31:34 -07:00
parent 6d8e12ac42
commit 0082977ceb
26 changed files with 1162 additions and 76 deletions
+1
View File
@@ -625,6 +625,7 @@ pub async fn set_thread_memory_mode(sess: &Arc<Session>, sub_id: String, mode: T
async fn shutdown_session_runtime(sess: &Arc<Session>) {
sess.abort_all_tasks(TurnAbortReason::Interrupted).await;
sess.services.async_hook_output_queue.shutdown().await;
let _ = sess.conversation.shutdown().await;
sess.services
.unified_exec_manager
+3
View File
@@ -1514,6 +1514,7 @@ impl Session {
config.as_ref(),
self.services.plugins_manager.as_ref(),
self.services.user_shell.as_ref(),
self.services.async_hook_output_queue.clone(),
)
.await;
@@ -3403,6 +3404,7 @@ async fn build_hooks_for_config(
config: &Config,
plugins_manager: &PluginsManager,
user_shell: &crate::shell::Shell,
async_output_queue: codex_hooks::AsyncHookOutputQueue,
) -> Hooks {
let mut hook_shell_argv = user_shell.derive_exec_args("", /*use_login_shell*/ false);
let hook_shell_program = hook_shell_argv.remove(0);
@@ -3420,6 +3422,7 @@ async fn build_hooks_for_config(
plugin_hook_load_warnings,
shell_program: Some(hook_shell_program),
shell_args: hook_shell_argv,
async_output_queue,
})
}
+9 -2
View File
@@ -925,8 +925,14 @@ impl Session {
(None, None)
};
let hooks =
build_hooks_for_config(&config, plugins_manager.as_ref(), &default_shell).await;
let async_hook_output_queue = codex_hooks::AsyncHookOutputQueue::default();
let hooks = build_hooks_for_config(
&config,
plugins_manager.as_ref(),
&default_shell,
async_hook_output_queue.clone(),
)
.await;
for warning in hooks.startup_warnings() {
post_session_configured_events.push(Event {
id: INITIAL_SUBMIT_ID.to_owned(),
@@ -991,6 +997,7 @@ impl Session {
main_execve_wrapper_exe: config.main_execve_wrapper_exe.clone(),
analytics_events_client,
hooks: arc_swap::ArcSwap::from_pointee(hooks),
async_hook_output_queue,
rollout_thread_trace,
user_shell: Arc::new(default_shell),
shell_snapshot_tx,
+44 -1
View File
@@ -105,6 +105,7 @@ use codex_protocol::protocol::CompactedItem;
use codex_protocol::protocol::ConversationAudioParams;
use codex_protocol::protocol::CreditsSnapshot;
use codex_protocol::protocol::GranularApprovalConfig;
use codex_protocol::protocol::HookEventName;
use codex_protocol::protocol::InitialHistory;
use codex_protocol::protocol::InterAgentCommunication;
use codex_protocol::protocol::MultiAgentVersion;
@@ -4776,6 +4777,7 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) {
.expect("create environment"),
);
let async_hook_output_queue = codex_hooks::AsyncHookOutputQueue::default();
let services = SessionServices {
mcp_connection_manager: Arc::new(RwLock::new(
McpConnectionManager::new_uninitialized_with_permission_profile(
@@ -4797,8 +4799,10 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) {
),
hooks: arc_swap::ArcSwap::from_pointee(Hooks::new(HooksConfig {
legacy_notify_argv: config.notify.clone(),
async_output_queue: async_hook_output_queue.clone(),
..HooksConfig::default()
})),
async_hook_output_queue,
rollout_thread_trace: codex_rollout_trace::ThreadTraceContext::disabled(),
user_shell: Arc::new(default_user_shell()),
shell_snapshot_tx: watch::channel(None).0,
@@ -6853,6 +6857,7 @@ where
.expect("create environment"),
);
let async_hook_output_queue = codex_hooks::AsyncHookOutputQueue::default();
let services = SessionServices {
mcp_connection_manager: Arc::new(RwLock::new(
McpConnectionManager::new_uninitialized_with_permission_profile(
@@ -6874,8 +6879,10 @@ where
),
hooks: arc_swap::ArcSwap::from_pointee(Hooks::new(HooksConfig {
legacy_notify_argv: config.notify.clone(),
async_output_queue: async_hook_output_queue.clone(),
..HooksConfig::default()
})),
async_hook_output_queue,
rollout_thread_trace: codex_rollout_trace::ThreadTraceContext::disabled(),
user_shell: Arc::new(default_user_shell()),
shell_snapshot_tx: watch::channel(None).0,
@@ -8559,6 +8566,10 @@ async fn abort_gracefully_emits_marker_before_turn_aborted() {
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn task_finish_emits_turn_item_lifecycle_for_leftover_pending_user_input() {
let (sess, tc, rx) = make_session_and_context_with_rx().await;
let queued_context = "queued async hook context";
sess.services
.async_hook_output_queue
.push(HookEventName::PostToolUse, queued_context.to_string());
let input = vec![TurnInput::UserInput {
content: vec![UserInput::Text {
text: "hello".to_string(),
@@ -8612,6 +8623,32 @@ async fn task_finish_emits_turn_item_lifecycle_for_leftover_pending_user_input()
history.raw_items().iter().any(|item| item == &expected),
"expected pending input to be persisted into history on turn completion"
);
let user_index = history
.raw_items()
.iter()
.position(|item| item == &expected)
.expect("pending user input in history");
let developer_index = history
.raw_items()
.iter()
.position(|item| {
matches!(
item,
ResponseItem::Message { role, content, .. }
if role == "developer"
&& content.iter().any(|content| {
matches!(content, ContentItem::InputText { text } if text.contains(queued_context))
})
)
})
.expect("queued async hook context in history");
assert!(user_index < developer_index);
assert!(
sess.services
.async_hook_output_queue
.pending_batch()
.is_none()
);
let first = tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv())
.await
@@ -8663,11 +8700,17 @@ async fn task_finish_emits_turn_item_lifecycle_for_leftover_pending_user_input()
));
let fifth = tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv())
.await
.expect("expected async hook context event")
.expect("channel open");
assert!(matches!(fifth.msg, EventMsg::RawResponseItem(_)));
let sixth = tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv())
.await
.expect("expected turn complete event")
.expect("channel open");
assert!(matches!(
fifth.msg,
sixth.msg,
EventMsg::TurnComplete(TurnCompleteEvent {
turn_id,
last_agent_message: None,
+17 -3
View File
@@ -396,20 +396,34 @@ async fn turn_diff_display_roots(turn_context: &TurnContext) -> Vec<(String, Pat
display_roots
}
async fn run_hooks_and_record_inputs(
pub(crate) async fn run_hooks_and_record_inputs(
sess: &Arc<Session>,
turn_context: &Arc<TurnContext>,
input: &[TurnInput],
) -> bool {
let mut blocked_input = false;
let mut accepted_user_input = false;
let mut async_hook_output_batch = None;
let mut async_hook_output_batch_prepared = false;
for input_item in input {
let hook_outcome = inspect_pending_input(sess, turn_context, input_item).await;
let is_real_user_input =
matches!(input_item, TurnInput::UserInput { content, .. } if !content.is_empty());
if is_real_user_input && !async_hook_output_batch_prepared {
async_hook_output_batch = sess.services.async_hook_output_queue.pending_batch();
async_hook_output_batch_prepared = true;
}
let mut hook_outcome = inspect_pending_input(sess, turn_context, input_item).await;
if hook_outcome.should_stop {
blocked_input = true;
record_additional_contexts(sess, turn_context, hook_outcome.additional_contexts).await;
} else {
if matches!(input_item, TurnInput::UserInput { content, .. } if !content.is_empty()) {
if is_real_user_input && let Some(batch) = async_hook_output_batch.take() {
sess.services.async_hook_output_queue.commit(&batch);
hook_outcome
.additional_contexts
.insert(0, batch.into_text());
}
if is_real_user_input {
accepted_user_input = true;
}
record_pending_input(
+2
View File
@@ -22,6 +22,7 @@ use codex_core_plugins::PluginsManager;
use codex_exec_server::EnvironmentManager;
use codex_extension_api::ExtensionData;
use codex_extension_api::ExtensionRegistry;
use codex_hooks::AsyncHookOutputQueue;
use codex_hooks::Hooks;
use codex_login::AuthManager;
use codex_mcp::McpConnectionManager;
@@ -48,6 +49,7 @@ pub(crate) struct SessionServices {
pub(crate) main_execve_wrapper_exe: Option<PathBuf>,
pub(crate) analytics_events_client: AnalyticsEventsClient,
pub(crate) hooks: ArcSwap<Hooks>,
pub(crate) async_hook_output_queue: AsyncHookOutputQueue,
pub(crate) rollout_thread_trace: ThreadTraceContext,
pub(crate) user_shell: Arc<crate::shell::Shell>,
pub(crate) shell_snapshot_tx: watch::Sender<Option<Arc<crate::shell_snapshot::ShellSnapshot>>>,
+2 -23
View File
@@ -23,11 +23,9 @@ use tracing::warn;
use crate::config::Config;
use crate::context::ContextualUserFragment;
use crate::hook_runtime::inspect_pending_input;
use crate::hook_runtime::record_additional_contexts;
use crate::hook_runtime::record_pending_input;
use crate::session::TurnInput;
use crate::session::session::Session;
use crate::session::turn::run_hooks_and_record_inputs;
use crate::session::turn_context::TurnContext;
use crate::state::ActiveTurn;
use crate::state::RunningTask;
@@ -583,26 +581,7 @@ impl Session {
)
};
if !pending_input.is_empty() {
for pending_input_item in pending_input {
let hook_outcome =
inspect_pending_input(self, &turn_context, &pending_input_item).await;
if hook_outcome.should_stop {
record_additional_contexts(
self,
&turn_context,
hook_outcome.additional_contexts,
)
.await;
} else {
record_pending_input(
self,
&turn_context,
pending_input_item,
hook_outcome.additional_contexts,
)
.await;
}
}
run_hooks_and_record_inputs(self, &turn_context, &pending_input).await;
}
// Emit token usage metrics.
{