mirror of
https://github.com/openai/codex.git
synced 2026-11-27 23:50:52 +00:00
Fix lifecycle hook dispatch for hosted subagents (#64310)
## Why Hosted workers keep the host's session source, so hook dispatch can mistake them for root sessions and run `SessionStart` and `Stop` on worker turns. ## What changed Recognize host-managed workers by their inherited session ID and dispatch `SubagentStart` and `SubagentStop` for them. Resolve the parent transcript for `SubagentStop` using the immediate parent thread ID when available. ## Testing Add a regression test that verifies a hosted worker runs only the subagent lifecycle hooks, receives start-hook context, and reports its own transcript and final message in the stop hook. GitOrigin-RevId: 272d29d275120a1b020b1a00a0db2e00402ebe06
This commit is contained in:
@@ -62,6 +62,7 @@ use tokio::sync::Mutex;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tracing::instrument;
|
||||
|
||||
use crate::agent::host::AgentRuntimeServices;
|
||||
use crate::context::ContextualUserFragment;
|
||||
use crate::context::HookAdditionalContext;
|
||||
use crate::environment_selection::TurnEnvironmentSnapshot;
|
||||
@@ -140,26 +141,26 @@ pub(crate) async fn run_pending_session_start_hooks(
|
||||
while let Some(session_start_source) = sess.pending_session_start_source().await {
|
||||
// Spawned subagents can start fresh or fork their parent's history, so both
|
||||
// sources dispatch SubagentStart. Internal/system subagents skip start hooks.
|
||||
let target = match &turn_context.session_source {
|
||||
SessionSource::SubAgent(SubAgentSource::ThreadSpawn { agent_role, .. })
|
||||
let subagent = lifecycle_subagent_hook_context(sess, turn_context);
|
||||
let target = match (&turn_context.session_source, subagent) {
|
||||
(_, Some(context))
|
||||
if matches!(
|
||||
session_start_source,
|
||||
codex_hooks::SessionStartSource::Startup
|
||||
| codex_hooks::SessionStartSource::Fork
|
||||
) =>
|
||||
{
|
||||
let context = subagent_hook_context(sess, agent_role);
|
||||
StartHookTarget::SubagentStart {
|
||||
turn_id: turn_context.sub_id.clone(),
|
||||
agent_id: context.agent_id,
|
||||
agent_type: context.agent_type,
|
||||
}
|
||||
}
|
||||
SessionSource::SubAgent(_) => {
|
||||
(_, Some(_)) | (SessionSource::SubAgent(_), None) => {
|
||||
sess.take_pending_session_start_source().await;
|
||||
return false;
|
||||
}
|
||||
_ => StartHookTarget::SessionStart {
|
||||
(_, None) => StartHookTarget::SessionStart {
|
||||
source: session_start_source,
|
||||
},
|
||||
};
|
||||
@@ -398,35 +399,36 @@ pub(crate) async fn run_turn_stop_hooks(
|
||||
last_assistant_message: Option<String>,
|
||||
) -> StopOutcome {
|
||||
let turn_context = &step_context.turn;
|
||||
// Resolve the stop hook kind from the session source before building the
|
||||
// request. Root turns run Stop; thread-spawned child turns run SubagentStop.
|
||||
let (target, transcript_path) = match &turn_context.session_source {
|
||||
SessionSource::SubAgent(SubAgentSource::ThreadSpawn {
|
||||
agent_role,
|
||||
parent_thread_id,
|
||||
..
|
||||
}) => {
|
||||
let context = subagent_hook_context(sess, agent_role);
|
||||
let subagent = lifecycle_subagent_hook_context(sess, turn_context);
|
||||
let (target, transcript_path) = match (&turn_context.session_source, subagent) {
|
||||
(source, Some(context)) => {
|
||||
let agent_transcript_path = sess.hook_transcript_path().await;
|
||||
let parent_transcript_path = match sess
|
||||
.services
|
||||
.thread_store
|
||||
.read_thread(ReadThreadParams {
|
||||
thread_id: *parent_thread_id,
|
||||
include_archived: true,
|
||||
include_history: false,
|
||||
})
|
||||
.await
|
||||
// A hosted session ID identifies the root, which may not be the immediate parent.
|
||||
let parent_transcript_path = if let Some(parent_thread_id) =
|
||||
source.parent_thread_id().or(turn_context.parent_thread_id)
|
||||
{
|
||||
Ok(thread) => thread.rollout_path,
|
||||
Err(error) => {
|
||||
tracing::warn!(
|
||||
parent_thread_id = %parent_thread_id,
|
||||
error = %error,
|
||||
"failed to resolve parent transcript path for subagent hook"
|
||||
);
|
||||
None
|
||||
match sess
|
||||
.services
|
||||
.thread_store
|
||||
.read_thread(ReadThreadParams {
|
||||
thread_id: parent_thread_id,
|
||||
include_archived: true,
|
||||
include_history: false,
|
||||
})
|
||||
.await
|
||||
{
|
||||
Ok(thread) => thread.rollout_path,
|
||||
Err(error) => {
|
||||
tracing::warn!(
|
||||
parent_thread_id = %parent_thread_id,
|
||||
error = %error,
|
||||
"failed to resolve parent transcript path for subagent hook"
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
(
|
||||
StopHookTarget::SubagentStop {
|
||||
@@ -439,12 +441,12 @@ pub(crate) async fn run_turn_stop_hooks(
|
||||
}
|
||||
// Internal/synthetic subagents do not expose user-configured lifecycle
|
||||
// hooks, so there is no Stop or SubagentStop request to dispatch.
|
||||
SessionSource::SubAgent(_) => return StopOutcome::default(),
|
||||
SessionSource::Internal(InternalSessionSource::MemoryConsolidation) => (
|
||||
(SessionSource::SubAgent(_), None) => return StopOutcome::default(),
|
||||
(SessionSource::Internal(InternalSessionSource::MemoryConsolidation), None) => (
|
||||
StopHookTarget::MemoryConsolidation,
|
||||
sess.hook_transcript_path().await,
|
||||
),
|
||||
_ => (StopHookTarget::Stop, sess.hook_transcript_path().await),
|
||||
(_, None) => (StopHookTarget::Stop, sess.hook_transcript_path().await),
|
||||
};
|
||||
let request_metadata = build_request_metadata(Some(step_context), turn_context);
|
||||
let request = codex_hooks::StopRequest {
|
||||
@@ -1134,6 +1136,20 @@ fn hook_permission_mode(approval_policy: AskForApproval) -> String {
|
||||
.to_string()
|
||||
}
|
||||
|
||||
/// Hosted workers keep the host's session source and inherit the root's session ID.
|
||||
fn lifecycle_subagent_hook_context(
|
||||
sess: &Arc<Session>,
|
||||
turn_context: &TurnContext,
|
||||
) -> Option<SubagentHookContext> {
|
||||
if matches!(sess.agent_runtime, AgentRuntimeServices::Host(_))
|
||||
&& !turn_context.session_source.is_non_root_agent()
|
||||
&& sess.session_id() != SessionId::from(sess.thread_id())
|
||||
{
|
||||
return Some(subagent_hook_context(sess, /*agent_role*/ &None));
|
||||
}
|
||||
thread_spawn_subagent_hook_context(sess, turn_context)
|
||||
}
|
||||
|
||||
fn thread_spawn_subagent_hook_context(
|
||||
sess: &Arc<Session>,
|
||||
turn_context: &TurnContext,
|
||||
|
||||
@@ -7,6 +7,10 @@ use codex_agent_graph_store::ThreadSpawnEdgeStatus;
|
||||
use codex_config::ConfigLayerEntry;
|
||||
use codex_config::ConfigLayerSource;
|
||||
use codex_config::ConfigLayerStack;
|
||||
use codex_core::AgentRuntimeOwnership;
|
||||
use codex_core::AgentTurnAdmission;
|
||||
use codex_core::InheritedSessionId;
|
||||
use codex_core::RestrictRootCapabilities;
|
||||
use codex_core::StartThreadOptions;
|
||||
use codex_core::ThreadConfigSnapshot;
|
||||
use codex_core::TurnInputRequest;
|
||||
@@ -38,6 +42,7 @@ use codex_protocol::protocol::SubAgentActivityKind;
|
||||
use codex_protocol::protocol::SubAgentSource;
|
||||
use codex_protocol::protocol::ThreadHistoryMode;
|
||||
use codex_protocol::protocol::ThreadSettingsOverrides;
|
||||
use codex_protocol::protocol::ThreadSource;
|
||||
use codex_protocol::user_input::UserInput;
|
||||
use codex_skills_extension::SkillsExtensionConfig;
|
||||
use codex_thread_store::DeleteThreadsParams;
|
||||
@@ -781,6 +786,92 @@ async fn subagent_start_replaces_session_start_and_injects_context(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn hosted_child_runs_subagent_start_and_stop_hooks() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
let server = start_mock_server().await;
|
||||
let response = core_test_support::responses::mount_sse_once(
|
||||
&server,
|
||||
sse(vec![
|
||||
ev_response_created("child"),
|
||||
ev_assistant_message("answer", "worker done"),
|
||||
ev_completed("child"),
|
||||
]),
|
||||
)
|
||||
.await;
|
||||
let test = test_codex()
|
||||
.with_pre_build_hook(|home| {
|
||||
write_subagent_lifecycle_hooks(home, /*stop_prompts*/ &[], "default")
|
||||
.expect("write lifecycle hooks");
|
||||
})
|
||||
.with_config(trust_discovered_hooks)
|
||||
// Command hooks run on the host and require a host-native working directory.
|
||||
.build(&server)
|
||||
.await?;
|
||||
|
||||
let session_id = test.session_configured.session_id;
|
||||
let mut options = test.start_thread_options().await;
|
||||
options.session_source = Some(SessionSource::Custom("host".into()));
|
||||
options.thread_source = Some(ThreadSource::Subagent);
|
||||
options
|
||||
.thread_extension_init
|
||||
.insert(AgentRuntimeOwnership::Host);
|
||||
options
|
||||
.thread_extension_init
|
||||
.insert(Arc::new(super::agent_control::HostRuntime) as Arc<dyn AgentTurnAdmission>);
|
||||
options
|
||||
.thread_extension_init
|
||||
.insert(RestrictRootCapabilities);
|
||||
options
|
||||
.thread_extension_init
|
||||
.insert(InheritedSessionId(session_id));
|
||||
let child = test.thread_manager.start_thread(options).await?;
|
||||
child
|
||||
.thread
|
||||
.start_or_steer_turn(TurnInputRequest::user_input(vec![UserInput::Text {
|
||||
text: CHILD_PROMPT.into(),
|
||||
text_elements: Vec::new(),
|
||||
}]))
|
||||
.await?;
|
||||
wait_for_event(&child.thread, |event| {
|
||||
matches!(event, EventMsg::TurnComplete(_))
|
||||
})
|
||||
.await;
|
||||
child.thread.shutdown_and_wait().await?;
|
||||
|
||||
let home = test.codex_home_path();
|
||||
let start = read_hook_log(home, "subagent_start_hook_log.jsonl")?;
|
||||
let stop = read_hook_log(home, "subagent_stop_hook_log.jsonl")?;
|
||||
assert_eq!(
|
||||
(
|
||||
start.len(),
|
||||
stop.len(),
|
||||
read_hook_log(home, "session_start_hook_log.jsonl")?.len(),
|
||||
read_hook_log(home, "stop_hook_log.jsonl")?.len()
|
||||
),
|
||||
(1, 1, 0, 0),
|
||||
"expected SubagentStart and SubagentStop only"
|
||||
);
|
||||
for input in [&start[0], &stop[0]] {
|
||||
assert_eq!(input["session_id"], session_id.to_string());
|
||||
assert_eq!(input["agent_id"], child.thread_id.to_string());
|
||||
assert_eq!(input["agent_type"], "default");
|
||||
}
|
||||
assert!(
|
||||
response
|
||||
.single_request()
|
||||
.body_contains_text(SUBAGENT_START_CONTEXT)
|
||||
);
|
||||
assert_eq!(stop[0]["last_assistant_message"], "worker done");
|
||||
assert_eq!(
|
||||
stop[0]["agent_transcript_path"],
|
||||
start[0]["transcript_path"]
|
||||
);
|
||||
assert_eq!(stop[0]["transcript_path"], Value::Null);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn subagent_stop_replaces_stop_and_skips_internal_subagents() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
Reference in New Issue
Block a user