Use captured step settings when spawning subagents (#46075)

## Why

After a settings update during an active turn, spawned agents could inherit the turn's initial model and reasoning settings. Effort-only overrides could also be validated against the wrong model.

## What changed

Build child configuration from the invoking step's captured model, effective reasoning effort, and reasoning summary in both multi-agent versions. Validate effort-only overrides against that captured model's supported reasoning levels.

## Testing

Add regression coverage for spawning after an active-turn settings update in both multi-agent versions, including effort-only overrides. Update configuration tests to check captured settings and the model's default reasoning effort.

GitOrigin-RevId: 068bdb744149048829cdaa68d254b62e96e6e6af
This commit is contained in:
rhan-oai
2026-09-17 01:51:14 +00:00
committed by copyberry
parent 6749535c8f
commit 800d183e2d
9 changed files with 196 additions and 27 deletions
+19 -11
View File
@@ -1,4 +1,4 @@
//! Prepares child configuration from the invoking turn and requested overrides.
//! Prepares child configuration from captured step settings and requested overrides.
//!
//! Spawn and reload share live runtime policy; role and model precedence, full-history
//! inheritance, and validation messages remain the same for each multi-agent version.
@@ -7,6 +7,7 @@ use crate::agent::role::DEFAULT_ROLE_NAME;
use crate::agent::role::apply_role_to_config;
use crate::config::Config;
use crate::session::session::Session;
use crate::session::step_context::StepContext;
use crate::session::turn_context::TurnContext;
use codex_models_manager::manager::RefreshStrategy;
use codex_protocol::config_types::SERVICE_TIER_DEFAULT_REQUEST_VALUE;
@@ -49,16 +50,18 @@ pub(crate) struct PreparedSpawnConfig {
/// Resolves child settings before starting the thread, retaining the invoking tool's precedence.
pub(crate) async fn prepare_agent_spawn_config(
session: &Session,
turn: &TurnContext,
step_context: &StepContext,
options: SpawnConfigOptions<'_>,
) -> Result<PreparedSpawnConfig, String> {
let mut config = build_agent_spawn_config(&session.get_base_instructions().await, turn)?;
let turn = step_context.turn.as_ref();
let mut config =
build_agent_spawn_config(&session.get_base_instructions().await, step_context)?;
if options.version == SpawnConfigVersion::V1 && options.full_history_fork {
reject_full_fork_agent_type_override(options.role_name)?;
}
apply_requested_spawn_agent_model_overrides(
session,
turn,
step_context,
&mut config,
options.model,
options.reasoning_effort,
@@ -99,15 +102,19 @@ pub(crate) async fn prepare_agent_spawn_config(
/// Builds the base config snapshot for a newly spawned sub-agent.
///
/// The returned config starts from the parent's effective config and then refreshes the
/// runtime-owned fields carried by the turn, including model selection, reasoning settings,
/// approval policy, sandbox, and cwd. Role-specific overrides are layered
/// model selection and reasoning settings captured for the invoking step, plus the turn's
/// runtime approval policy, sandbox, and cwd. Role-specific overrides are layered
/// after this step; skipping this helper and cloning stale config state directly can send the child
/// agent out with the wrong provider or runtime policy.
pub(crate) fn build_agent_spawn_config(
base_instructions: &BaseInstructions,
turn: &TurnContext,
step_context: &StepContext,
) -> Result<Config, String> {
let mut config = build_agent_shared_config(turn)?;
let mut config = build_agent_shared_config(step_context.turn.as_ref())?;
let settings = &step_context.settings;
config.model = Some(settings.model_info.slug.clone());
config.model_reasoning_effort = settings.effective_reasoning_effort();
config.model_reasoning_summary = Some(settings.reasoning_summary);
config.base_instructions = Some(base_instructions.text.clone());
config.base_instructions_provenance = base_instructions.provenance.clone();
Ok(config)
@@ -188,11 +195,12 @@ fn apply_spawn_agent_runtime_overrides(
async fn apply_requested_spawn_agent_model_overrides(
session: &Session,
turn: &TurnContext,
step_context: &StepContext,
config: &mut Config,
requested_model: Option<&str>,
requested_reasoning_effort: Option<ReasoningEffort>,
) -> Result<(), String> {
let turn = step_context.turn.as_ref();
let requested_model = requested_model.or(turn.config.agent_default_subagent_model.as_deref());
let requested_reasoning_effort = requested_reasoning_effort
.or_else(|| turn.config.agent_default_subagent_reasoning_effort.clone());
@@ -234,8 +242,8 @@ async fn apply_requested_spawn_agent_model_overrides(
if let Some(reasoning_effort) = requested_reasoning_effort {
validate_spawn_agent_reasoning_effort(
&turn.model_info().slug,
&turn.model_info().supported_reasoning_levels,
&step_context.settings.model_info.slug,
&step_context.settings.model_info.supported_reasoning_levels,
&reasoning_effort,
)?;
config.model_reasoning_effort = Some(reasoning_effort);
+2 -5
View File
@@ -16,10 +16,7 @@ pub(crate) struct ResolvedMultiAgentV2UsageHints {
pub(crate) subagent: Option<MultiAgentRoleInstructions>,
}
pub(super) fn usage_hint_text(
step_context: &StepContext,
session_source: &SessionSource,
) -> Option<MultiAgentRoleInstructions> {
pub(super) fn usage_hint_text(step_context: &StepContext) -> Option<MultiAgentRoleInstructions> {
let turn_context = step_context.turn.as_ref();
if turn_context.multi_agent_version != MultiAgentVersion::V2 {
return None;
@@ -32,7 +29,7 @@ pub(super) fn usage_hint_text(
multi_agent_messages,
!turn_context.config.update_plan_enabled && turn_context.config.model_catalog.is_none(),
);
match session_source {
match &turn_context.session_source {
SessionSource::SubAgent(SubAgentSource::ThreadSpawn { .. }) => snapshot.subagent,
SessionSource::Cli
| SessionSource::VSCode
+1 -3
View File
@@ -275,9 +275,7 @@ impl Session {
let mut multi_agent_mode = MultiAgentModeState::new(
super::multi_agents::effective_multi_agent_mode(step_context),
);
if let Some(usage_hint_text) =
super::multi_agents::usage_hint_text(step_context, &turn_context.session_source)
{
if let Some(usage_hint_text) = super::multi_agents::usage_hint_text(step_context) {
let usage_hint = MultiAgentUsageHintState::new(usage_hint_text);
multi_agent_mode = multi_agent_mode.with_usage_hint(&usage_hint);
world_state.add_section(usage_hint);
@@ -94,7 +94,7 @@ async fn handle_spawn_agent(
.await;
let prepared = prepare_agent_spawn_config(
&session,
turn.as_ref(),
step_context.as_ref(),
SpawnConfigOptions {
version: SpawnConfigVersion::V1,
full_history_fork: args.fork_context,
@@ -14,6 +14,8 @@ use crate::init_state_db;
use crate::local_agent_graph_store_from_state_db;
use crate::session::step_context::StepContext;
use crate::session::tests::make_session_and_context;
use crate::session::tests::update_selected_settings_for_test;
use crate::session::tests::update_turn_settings_for_test;
use crate::session::turn_context::TurnContext;
use crate::session_prefix::format_inter_agent_completion_message;
use crate::thread_manager::thread_store_from_config;
@@ -37,6 +39,7 @@ use codex_models_manager::manager::StaticModelsManager;
use codex_protocol::AgentPath;
use codex_protocol::ThreadId;
use codex_protocol::config_types::ApprovalsReviewer;
use codex_protocol::config_types::ReasoningSummary;
use codex_protocol::config_types::ServiceTier;
use codex_protocol::config_types::ShellEnvironmentPolicy;
use codex_protocol::items::TurnItem;
@@ -4405,7 +4408,9 @@ async fn tool_handlers_cascade_close_and_resume_and_keep_explicitly_closed_subtr
#[test_case::test_case(false; "inactive_parent")]
#[test_case::test_case(true; "active_parent")]
#[tokio::test]
async fn build_agent_spawn_config_uses_turn_context_values(parent_enabled: bool) {
async fn build_agent_spawn_config_uses_captured_step_settings_and_turn_context_values(
parent_enabled: bool,
) {
fn pick_allowed_sandbox_policy(
permissions: &crate::config::Permissions,
base: SandboxPolicy,
@@ -4430,10 +4435,18 @@ async fn build_agent_spawn_config_uses_turn_context_values(parent_enabled: bool)
}
let (_session, mut turn) = make_session_and_context().await;
update_turn_settings_for_test(&mut turn, |settings| {
update_selected_settings_for_test(settings, |selected| {
selected.collaboration_mode.settings.model = "stale-turn-model".to_string();
selected.collaboration_mode.settings.reasoning_effort = Some(ReasoningEffort::Low);
});
Arc::make_mut(&mut settings.model_info).slug = "stale-turn-model".to_string();
settings.reasoning_summary = ReasoningSummary::Concise;
});
let base_instructions = BaseInstructions {
text: "base".to_string(),
provenance: Some(BaseInstructionsProvenance::Model {
model: turn.model_info().slug.clone(),
model: "captured-step-model".to_string(),
}),
};
turn.developer_instructions = Some("dev".to_string());
@@ -4495,13 +4508,30 @@ async fn build_agent_spawn_config_uses_turn_context_values(parent_enabled: bool)
.get_or_insert_default()
.guidance_message = Some("Parent model's resolved guidance.".to_string());
let config = build_agent_spawn_config(&base_instructions, &turn).expect("spawn config");
let mut step_context = StepContext::for_test(Arc::new(turn));
let settings = Arc::make_mut(
&mut Arc::get_mut(&mut step_context)
.expect("step context should not be shared")
.settings,
);
update_selected_settings_for_test(settings, |selected| {
selected.collaboration_mode.settings.model = "captured-step-model".to_string();
selected.collaboration_mode.settings.reasoning_effort = None;
});
let model_info = Arc::make_mut(&mut settings.model_info);
model_info.slug = "captured-step-model".to_string();
model_info.default_reasoning_level = Some(ReasoningEffort::High);
settings.reasoning_summary = ReasoningSummary::Detailed;
let turn = step_context.turn.as_ref();
let config =
build_agent_spawn_config(&base_instructions, step_context.as_ref()).expect("spawn config");
expected.base_instructions_provenance = base_instructions.provenance.clone();
expected.base_instructions = Some(base_instructions.text);
expected.model = Some(turn.model_info().slug.clone());
expected.model = Some("captured-step-model".to_string());
expected.model_provider = turn.provider.info().clone();
expected.model_reasoning_effort = turn.reasoning_effort().cloned();
expected.model_reasoning_summary = Some(turn.reasoning_summary());
expected.model_reasoning_effort = Some(ReasoningEffort::High);
expected.model_reasoning_summary = Some(ReasoningSummary::Detailed);
expected.developer_instructions = turn.developer_instructions.clone();
#[allow(deprecated)]
{
@@ -129,7 +129,7 @@ async fn handle_spawn_agent(
let child_depth = next_thread_spawn_depth(&session_source);
let prepared = prepare_agent_spawn_config(
&session,
turn.as_ref(),
step_context.as_ref(),
SpawnConfigOptions {
version: SpawnConfigVersion::V2,
full_history_fork: matches!(fork_mode, Some(SpawnAgentForkMode::FullHistory)),
@@ -109,6 +109,8 @@ use test_case::test_case;
use super::rmcp_client::remote_aware_environment_id;
use super::rmcp_client::remote_aware_stdio_server_bin;
#[path = "step_settings/agent_spawn_tests.rs"]
mod agent_spawn;
mod code_mode_notifications;
const MODEL_A: &str = "step-settings-a";
@@ -0,0 +1,128 @@
//! Spawned agents inherit the invoking step's model settings after active-turn updates.
use super::*;
use pretty_assertions::assert_eq;
use test_case::test_case;
#[test_case(false, None; "v1 inherits captured settings")]
#[test_case(true, None; "v2 inherits captured settings")]
#[test_case(false, Some(ReasoningEffort::Medium); "v1 validates effort against captured model")]
#[test_case(true, Some(ReasoningEffort::Medium); "v2 validates effort against captured model")]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn spawn_inherits_captured_settings_after_a_turn_update(
multi_agent_v2: bool,
requested_effort: Option<ReasoningEffort>,
) -> Result<()> {
skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
let mut spawn_arguments = json!({ "message": "Complete the delegated task." });
let namespace = if multi_agent_v2 {
spawn_arguments["task_name"] = json!("worker");
spawn_arguments["fork_turns"] = json!("none");
"collaboration"
} else {
"multi_agent_v1"
};
if let Some(effort) = &requested_effort {
spawn_arguments["reasoning_effort"] = json!(effort);
}
let response_mock = mount_sse_sequence(
&server,
vec![
paused_response("resp-original", "pause-before-spawn"),
sse(vec![
ev_response_created("resp-spawn"),
ev_function_call_with_namespace(
"spawn-worker",
namespace,
"spawn_agent",
&spawn_arguments.to_string(),
),
ev_completed("resp-spawn"),
]),
sse_completed("resp-first-completion"),
sse_completed("resp-second-completion"),
],
)
.await;
// Child completion can trigger another parent request after the parent finishes.
mount_sse_once(&server, sse_completed("resp-child-notification")).await;
let test = step_settings_test()
.with_config(move |config| {
config
.features
.enable(Feature::Collab)
.expect("enable collab");
if multi_agent_v2 {
config
.features
.enable(Feature::MultiAgentV2)
.expect("enable V2");
} else {
config
.features
.disable(Feature::MultiAgentV2)
.expect("disable V2");
}
for model in &mut config.model_catalog.as_mut().expect("model catalog").models {
// An effort-only override must be validated against B, not the turn's initial A.
model.supported_reasoning_levels = if model.slug == MODEL_B {
vec![ReasoningEffort::Medium, ReasoningEffort::High]
} else {
vec![ReasoningEffort::Low]
}
.into_iter()
.map(|effort| ReasoningEffortPreset {
description: effort.to_string(),
effort,
})
.collect();
model.supports_reasoning_summary_parameter = true;
model.use_responses_lite = false;
}
})
.build_with_auto_env(&server)
.await?;
let mut created_threads = test.thread_manager.subscribe_thread_created();
let request = start_paused_turn(&test.codex).await?;
apply_turn_settings(
&test.codex,
&request.turn_id,
TurnSettingsUpdate {
model: Some(MODEL_B.to_string()),
effort: Some(Some(ReasoningEffort::High)),
summary: Some(ReasoningSummary::Detailed),
..Default::default()
},
)
.await?;
answer_paused_turn(&test.codex, &request.turn_id).await?;
let child_thread_id = tokio::time::timeout(
std::time::Duration::from_secs(/*secs*/ 10),
created_threads.recv(),
)
.await??;
let child_thread = test.thread_manager.get_thread(child_thread_id).await?;
for thread in [child_thread.as_ref(), test.codex.as_ref()] {
wait_for_event(thread, |event| matches!(event, EventMsg::TurnComplete(_))).await;
}
let expected_effort = requested_effort.unwrap_or(ReasoningEffort::High);
let requests = response_mock.requests();
let child_request = requests
.iter()
.find(|request| request.header("thread-id") == Some(child_thread_id.to_string()))
.expect("child should make a model request");
assert_eq!(
request_settings(child_request),
json!({
"model": MODEL_B,
"reasoning": { "effort": expected_effort, "summary": "detailed" },
"service_tier": null,
})
);
Ok(())
}
@@ -67,6 +67,7 @@ use tokio::time::Instant;
use tokio::time::sleep;
use tokio::time::timeout;
use tracing::Level;
use tracing_subscriber::layer::SubscriberExt;
use tracing_test::internal::MockWriter;
use wiremock::Mock;
use wiremock::MockServer;
@@ -2212,6 +2213,11 @@ async fn multi_agent_v2_spawn_sends_agent_message_to_child(
.with_writer(MockWriter::new(output))
.finish();
let _guard = tracing::subscriber::set_default(subscriber);
// Keep two dispatchers alive so a parallel test that first registers a communication
// callsite without a subscriber cannot globally disable it for our capturing subscriber.
let _parallel_dispatch = tracing::Dispatch::new(
tracing_subscriber::registry().with(tracing_subscriber::filter::LevelFilter::OFF),
);
let server = start_mock_server().await;
let message = if plaintext {