Add SessionEnd hooks for thread teardown (#33895)

## What changed

- Add the `SessionEnd` hook event to hook configuration, protocol schemas, analytics, and the hooks browser.
- Run matching hooks for root threads during shutdown, including app-server archive, delete, idle unload, and graceful shutdown. Flush the transcript first and provide the session ID, transcript path, working directory, and `reason: "other"`.
- Keep teardown bounded: hook output is advisory, the default timeout is one second, configured timeouts are capped at three seconds, and async hooks run synchronously with a warning.

## Testing

- Cover transcript availability, matcher selection, timeout normalization, ignored control output, subagent exclusion, archive/delete ordering, and graceful shutdown of multiple loaded threads.

GitOrigin-RevId: 5d19a658677a137caf836ed5042dcb43f5eb6d1a
This commit is contained in:
Abhinav authored and copyberry committed 2026-07-17 19:58:56 +00:00
1 parent b9680065b0
commit 7bd44085e1
46 files changed
+930 -14

No files matched your search

+7
View File
@@ -1310,6 +1310,13 @@
},
"type": "array"
},
"SessionEnd": {
"default": [],
"items": {
"$ref": "#/definitions/MatcherGroup"
},
"type": "array"
},
"SessionStart": {
"default": [],
"items": {
+33
View File
@@ -365,6 +365,38 @@ pub(crate) async fn run_turn_stop_hooks(
outcome
}
#[instrument(level = "trace", skip_all)]
pub(crate) async fn run_session_end_hooks(sess: &Arc<Session>) {
let hooks = sess.hooks();
let preview_runs = hooks.preview_session_end();
if preview_runs.is_empty() {
return;
}
let turn_context = sess.new_default_turn().await;
// SessionEnd is root-only; ThreadSpawn uses SubagentStart/SubagentStop and other subagents
// are internal implementation details.
if matches!(&turn_context.session_source, SessionSource::SubAgent(_)) {
return;
}
let request = codex_hooks::SessionEndRequest {
session_id: sess.session_id().into(),
turn_id: turn_context.sub_id.clone(),
#[allow(deprecated)]
cwd: turn_context.cwd.clone(),
transcript_path: sess.hook_transcript_path().await,
};
if let Err(err) = sess.flush_rollout().await {
tracing::warn!("failed to flush transcript before SessionEnd hook: {err}");
}
emit_hook_started_events(sess, &turn_context, preview_runs).await;
let outcome = hooks.run_session_end(request).await;
emit_hook_completed_events(sess, &turn_context, outcome.hook_events).await;
}
pub(crate) async fn run_pre_compact_hooks(
sess: &Arc<Session>,
turn_context: &Arc<TurnContext>,
@@ -703,6 +735,7 @@ fn hook_run_metric_tags(run: &HookRunSummary) -> [(&'static str, &'static str);
HookEventName::PreCompact => "PreCompact",
HookEventName::PostCompact => "PostCompact",
HookEventName::SessionStart => "SessionStart",
HookEventName::SessionEnd => "SessionEnd",
HookEventName::UserPromptSubmit => "UserPromptSubmit",
HookEventName::SubagentStart => "SubagentStart",
HookEventName::SubagentStop => "SubagentStop",
+2
View File
@@ -609,6 +609,8 @@ async fn shutdown_session_runtime(sess: &Arc<Session>) {
}
sess.services.mcp_runtime.shutdown().await;
sess.guardian_review_session.shutdown().await;
crate::hook_runtime::run_session_end_hooks(sess).await;
}
async fn emit_thread_stop_lifecycle(sess: &Session) {
+132
View File
@@ -3,6 +3,7 @@ use std::path::Path;
use anyhow::Context;
use anyhow::Result;
use codex_core::StartThreadOptions;
use codex_core::config::Config;
use codex_core::config::Constrained;
use codex_features::Feature;
@@ -18,9 +19,12 @@ use codex_protocol::models::ResponseItem;
use codex_protocol::permissions::NetworkSandboxPolicy;
use codex_protocol::protocol::AskForApproval;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::InitialHistory;
use codex_protocol::protocol::Op;
use codex_protocol::protocol::RolloutItem;
use codex_protocol::protocol::RolloutLine;
use codex_protocol::protocol::SessionSource;
use codex_protocol::protocol::SubAgentSource;
use codex_protocol::request_permissions::PermissionGrantScope;
use codex_protocol::request_permissions::RequestPermissionProfile;
use codex_protocol::request_permissions::RequestPermissionsResponse;
@@ -176,6 +180,41 @@ else:
Ok(())
}
fn write_session_end_hook(home: &Path) -> Result<()> {
let script_path = home.join("session_end_hook.py");
let log_path = home.join("session_end_hook_log.jsonl");
let script = format!(
r#"import json
from pathlib import Path
import sys
payload = json.load(sys.stdin)
transcript = Path(payload["transcript_path"])
payload["transcript_exists"] = transcript.exists()
payload["transcript_text"] = transcript.read_text(encoding="utf-8") if transcript.exists() else ""
with Path(r"{log_path}").open("a", encoding="utf-8") as handle:
handle.write(json.dumps(payload) + "\n")
print(json.dumps({{"continue": False, "decision": "block", "reason": "ignored"}}))
"#,
log_path = log_path.display(),
);
let hooks = serde_json::json!({
"hooks": {
"SessionEnd": [{
"matcher": "other",
"hooks": [{
"type": "command",
"command": format!("python3 {}", script_path.display()),
}]
}]
}
});
fs::write(&script_path, script).context("write session end hook script")?;
fs::write(home.join("hooks.json"), hooks.to_string()).context("write hooks.json")?;
Ok(())
}
fn write_parallel_stop_hooks(home: &Path, prompts: &[&str]) -> Result<()> {
let hook_entries = prompts
.iter()
@@ -1220,6 +1259,99 @@ async fn session_start_hook_sees_materialized_transcript_path() -> Result<()> {
Ok(())
}
#[tokio::test]
async fn session_end_flushes_transcript_and_ignores_control_output() -> Result<()> {
skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
let _response = mount_sse_once(
&server,
sse(vec![
ev_response_created("resp-1"),
ev_assistant_message("msg-1", "persisted answer"),
ev_completed("resp-1"),
]),
)
.await;
let mut builder = test_codex()
.with_pre_build_hook(|home| {
write_session_end_hook(home).expect("write session end hook fixture");
})
.with_config(trust_discovered_hooks);
let test = builder.build(&server).await?;
test.submit_turn("persist this before shutdown").await?;
test.codex.shutdown_and_wait().await?;
let inputs = read_hook_inputs_from_log(
test.codex_home_path()
.join("session_end_hook_log.jsonl")
.as_path(),
)?;
assert_eq!(inputs.len(), 1);
assert_eq!(inputs[0]["hook_event_name"], "SessionEnd");
assert_eq!(inputs[0]["reason"], "other");
assert_eq!(inputs[0]["transcript_exists"], true);
let transcript = inputs[0]["transcript_text"]
.as_str()
.expect("session end transcript text");
assert!(transcript.contains("persist this before shutdown"));
assert!(transcript.contains("persisted answer"));
Ok(())
}
#[tokio::test]
async fn session_end_skips_subagents() -> Result<()> {
skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
let mut builder = test_codex()
.with_pre_build_hook(|home| {
write_session_end_hook(home).expect("write session end hook fixture");
})
.with_config(trust_discovered_hooks);
let test = builder.build(&server).await?;
for source in [
SubAgentSource::Review,
SubAgentSource::ThreadSpawn {
parent_thread_id: test.session_configured.thread_id,
depth: 1,
agent_path: None,
agent_nickname: None,
agent_role: None,
},
] {
let subagent = test
.thread_manager
.start_thread_with_options(StartThreadOptions {
config: test.config.clone(),
allow_provider_model_fallback: false,
initial_history: InitialHistory::New,
history_mode: None,
session_source: Some(SessionSource::SubAgent(source)),
thread_source: None,
dynamic_tools: Vec::new(),
metrics_service_name: None,
parent_trace: None,
environments: Vec::new(),
thread_extension_init: Default::default(),
supports_openai_form_elicitation: false,
})
.await?;
subagent.thread.shutdown_and_wait().await?;
}
assert!(
!test
.codex_home_path()
.join("session_end_hook_log.jsonl")
.exists(),
"subagents must not run SessionEnd hooks"
);
Ok(())
}
#[tokio::test]
async fn session_start_runs_before_user_prompt_submit_on_first_turn() -> Result<()> {
skip_if_no_network!(Ok(()));