From e73da8bd1be78317a8748867606dd143a6c6a63b Mon Sep 17 00:00:00 2001 From: jif Date: Tue, 17 Nov 2026 22:16:23 +0000 Subject: [PATCH] Preserve base and developer instructions in host child preparation (#62128) ## Why Hosts preparing a child thread lacked the parent's effective base instructions and the developer instructions a native subagent would inherit. Hosts also need the base instruction provenance to preserve custom text while letting model-owned instructions resolve for the child's model. ## What changed Include effective base instruction text and provenance in `PreparedChildContext`. Share developer instruction selection with native subagent creation so host preparation uses the configured V2 subagent override when present and falls back to the parent turn's developer instructions otherwise. ## Testing Add integration coverage that starts a child on a different model and checks that custom base instructions persist, model-owned instructions resolve for the child model, and the V2 override takes precedence over the parent developer instructions. GitOrigin-RevId: 0e151e343e58d995c8901a9ba819cb7f60d248f5 --- codex-rs/core/src/agent/child_config.rs | 20 +-- codex-rs/core/src/agent/host/invocation.rs | 3 + codex-rs/core/src/agent/host/types.rs | 8 ++ .../tests/suite/scenarios_reserved_spawn.rs | 111 +++++++++++++++ ..._child_instructions_subagent_override.snap | 133 ++++++++++++++++++ 5 files changed, 265 insertions(+), 10 deletions(-) create mode 100644 codex-rs/core/tests/suite/snapshots/all__suite__scenarios__reserved_spawn__prepared_child_instructions_subagent_override.snap diff --git a/codex-rs/core/src/agent/child_config.rs b/codex-rs/core/src/agent/child_config.rs index e7b094fa01..dd6ada7a38 100644 --- a/codex-rs/core/src/agent/child_config.rs +++ b/codex-rs/core/src/agent/child_config.rs @@ -167,21 +167,21 @@ fn build_agent_shared_config(turn: &TurnContext) -> Result { .or(turn.model_info().default_reasoning_level.as_ref()) .cloned(); config.model_reasoning_summary = Some(turn.reasoning_summary()); - config.developer_instructions = turn.developer_instructions.clone(); - if turn.multi_agent_version == MultiAgentVersion::V2 - && let Some(developer_instructions) = turn - .config - .multi_agent_v2 - .subagent_developer_instructions - .clone() - { - config.developer_instructions = Some(developer_instructions); - } + config.developer_instructions = inherited_developer_instructions(turn); apply_spawn_agent_runtime_overrides(&mut config, turn)?; Ok(config) } +pub(crate) fn inherited_developer_instructions(turn: &TurnContext) -> Option { + if turn.multi_agent_version == MultiAgentVersion::V2 + && let Some(instructions) = &turn.config.multi_agent_v2.subagent_developer_instructions + { + return Some(instructions.clone()); + } + turn.developer_instructions.clone() +} + fn reject_full_fork_agent_type_override(agent_type: Option<&str>) -> Result<(), String> { if agent_type.is_some() { return Err( diff --git a/codex-rs/core/src/agent/host/invocation.rs b/codex-rs/core/src/agent/host/invocation.rs index 4a37183374..0f99056a08 100644 --- a/codex-rs/core/src/agent/host/invocation.rs +++ b/codex-rs/core/src/agent/host/invocation.rs @@ -3,6 +3,7 @@ use super::spawn::create_spawn; use super::types::HostThreadSpawnReservation; use super::types::PreparedChildContext; +use crate::agent::child_config::inherited_developer_instructions; use crate::agent::control::inherited_dynamic_tools; use crate::codex_thread::CodexThread; use crate::function_tool::FunctionCallError; @@ -229,6 +230,8 @@ pub(crate) async fn prepare( thread.session.services.exec_policy.snapshot(); Ok(PreparedChildContext { originator: turn.originator.clone(), + base_instructions: thread.session.get_base_instructions().await, + developer_instructions: inherited_developer_instructions(turn), user_instructions: instructions .and_then(|md| md.user_instructions.as_ref()) .map(|entry| entry.text.clone()), diff --git a/codex-rs/core/src/agent/host/types.rs b/codex-rs/core/src/agent/host/types.rs index 68c8795ab2..e768ced684 100644 --- a/codex-rs/core/src/agent/host/types.rs +++ b/codex-rs/core/src/agent/host/types.rs @@ -12,6 +12,7 @@ use codex_protocol::ThreadId; use codex_protocol::capabilities::SelectedCapabilityRoot; use codex_protocol::config_types::ApprovalsReviewer; use codex_protocol::dynamic_tools::DynamicToolSpec; +use codex_protocol::models::BaseInstructions; use codex_protocol::models::PermissionProfile; use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::TurnEnvironmentRequest; @@ -62,6 +63,13 @@ pub struct HostThreadSpawnReservation { /// Repository instructions are discovered at the destination. pub struct PreparedChildContext { pub originator: String, + /// Effective parent base instructions, including whether they are custom or model-owned. + /// Apply both `text` and `provenance` to the destination config so model-owned instructions + /// retain their normal model-switch behavior. Apply requested child overrides afterwards. + pub base_instructions: BaseInstructions, + /// Developer instructions under native inheritance rules, including the V2 subagent override. + /// Requested child role overrides are applied after this inherited value. + pub developer_instructions: Option, pub user_instructions: Option, pub thread_instructions: Option, pub cwd: AbsolutePathBuf, diff --git a/codex-rs/core/tests/suite/scenarios_reserved_spawn.rs b/codex-rs/core/tests/suite/scenarios_reserved_spawn.rs index 90dd1310cf..ed426b77cf 100644 --- a/codex-rs/core/tests/suite/scenarios_reserved_spawn.rs +++ b/codex-rs/core/tests/suite/scenarios_reserved_spawn.rs @@ -24,6 +24,8 @@ use codex_http_client::NetworkPolicy; use codex_http_client::NetworkPolicyController; use codex_protocol::ThreadId; use codex_protocol::dynamic_tools::DynamicToolCallRequest; +use codex_protocol::models::BaseInstructions; +use codex_protocol::models::BaseInstructionsProvenance; use codex_protocol::models::PermissionProfile; use codex_protocol::protocol::ThreadHistoryMode; use codex_protocol::protocol::ThreadSettingsOverrides; @@ -164,6 +166,115 @@ fn create_request(name: &str, fork_history: bool) -> ThreadCreateRequest { } } +#[test_case::test_case(Some("Keep the custom base instructions."), None; "custom")] +#[test_case::test_case(Some("Keep the custom base instructions."), Some("Report worker findings concisely."); "subagent override")] +#[test_case::test_case(None, None; "model owned")] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn prepared_child_instructions_preserve_native_inheritance( + custom_base: Option<&'static str>, + subagent_developer: Option<&'static str>, +) -> Result<()> { + const PARENT_DEVELOPER: &str = "Explain the reasoning behind your findings."; + const CHILD_MODEL: &str = "gpt-5.6-terra"; + skip_if_no_network!(Ok(())); + let server = start_mock_server().await; + let (test, parent, _) = host_spawn_fixture( + &server, + test_codex().with_config(move |config| { + config.workspace_roots = vec![config.cwd.clone()]; + config.base_instructions = custom_base.map(str::to_owned); + config.developer_instructions = Some(PARENT_DEVELOPER.into()); + config.multi_agent_v2.subagent_developer_instructions = + subagent_developer.map(str::to_owned); + config + .features + .enable(Feature::IncrementalTools) + .expect("test config should allow incremental tools"); + }), + NetworkPolicy::unmanaged(), + /*thread_instructions_provider*/ None, + ) + .await?; + let invocation = host_spawn_invocation( + &server, + &parent, + "prepare-worker", + TurnInputRequest::user_input(vec![text("Prepare a worker with my instructions.")]), + ) + .await?; + let context = parent.tool_invocation(&invocation.turn_id, &invocation.call_id)?; + let prepared = parent.prepare_child(&context).await?; + let catalog = bundled_models_response()?; + let parent_model = catalog + .models + .iter() + .find(|model| model.slug == "gpt-6-astra") + .context("parent model")?; + assert_eq!( + prepared.base_instructions, + BaseInstructions { + text: custom_base + .map(str::to_owned) + .unwrap_or_else(|| codex_prompts::render_model_instructions(parent_model)), + provenance: Some(match custom_base { + Some(_) => BaseInstructionsProvenance::Custom, + None => BaseInstructionsProvenance::Model { + model: parent_model.slug.clone(), + }, + }), + } + ); + + // A portable host forwards prepared instructions into its destination config, then applies + // the requested child model. Model-owned instructions must still resolve for that model. + let mut options = test.start_thread_options().await; + options.config.base_instructions = Some(prepared.base_instructions.text); + options.config.base_instructions_provenance = prepared.base_instructions.provenance; + options.config.developer_instructions = prepared.developer_instructions; + options.config.model = Some(CHILD_MODEL.into()); + options.environments = Some(prepared.environments); + let child = test.thread_manager.start_thread(options).await?.thread; + finish_spawn_tool(&server, &parent, &invocation).await?; + let mock = responses::mount_sse_once(&server, sse(vec![ev_completed("worker-done")])).await; + child + .start_or_steer_turn(TurnInputRequest::user_input(vec![text( + "Report your findings.", + )])) + .await?; + wait_for_successful_turn(&child).await; + let request = mock.single_request(); + let child_model = catalog + .models + .iter() + .find(|model| model.slug == CHILD_MODEL) + .context("child model")?; + let expected_base = custom_base + .map(str::to_owned) + .unwrap_or_else(|| codex_prompts::render_model_instructions(child_model)); + assert!(request.body_contains_text(&expected_base)); + assert!(request.body_contains_text(subagent_developer.unwrap_or(PARENT_DEVELOPER))); + assert_eq!( + request.body_contains_text(PARENT_DEVELOPER), + subagent_developer.is_none() + ); + let requests = responses::received_responses_requests(&server).await; + assert_eq!(requests.len(), 3); + // One complete history shows both inherited fields; the assertions above cover every case. + if custom_base.is_some() && subagent_developer.is_some() { + insta::assert_snapshot!( + "prepared_child_instructions_subagent_override", + context_snapshot::format_request_history_snapshot( + "Host preparation preserves custom base instructions and applies the native subagent developer override when starting a child with a different model.", + &requests, + &ContextSnapshotOptions::default().include_request_settings(), + ) + ); + } + child.shutdown_and_wait().await?; + parent.shutdown_and_wait().await?; + Ok(()) +} + #[test_case::test_case(false; "fresh")] #[test_case::test_case(true; "forked")] #[tokio::test(flavor = "multi_thread", worker_threads = 2)] diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__scenarios__reserved_spawn__prepared_child_instructions_subagent_override.snap b/codex-rs/core/tests/suite/snapshots/all__suite__scenarios__reserved_spawn__prepared_child_instructions_subagent_override.snap new file mode 100644 index 0000000000..0780dbe542 --- /dev/null +++ b/codex-rs/core/tests/suite/snapshots/all__suite__scenarios__reserved_spawn__prepared_child_instructions_subagent_override.snap @@ -0,0 +1,133 @@ +--- +source: core/tests/suite/scenarios_reserved_spawn.rs +assertion_line: 264 +expression: "context_snapshot::format_request_history_snapshot(\"Host preparation preserves custom base instructions and applies the native subagent developer override when starting a child with a different model.\",\n&requests, &ContextSnapshotOptions::default().include_request_settings(),)" +--- +Scenario: Host preparation preserves custom base instructions and applies the native subagent developer override when starting a child with a different model. + +## Window 1 +Settings: + include: ["reasoning.encrypted_content"] + model: "gpt-6-astra" + parallel_tool_calls: false + prompt_cache_key: "" + reasoning: {"context":"all_turns","effort":"low"} + store: false + stream: true + text: {"verbosity":"low"} + tool_choice: "auto" +-- request 1 (turn) -- +00:additional_tools/developer (2; hash=2dea6cdae5007237): + - namespace/functions; hash=99cb31e479060441 + - custom/exec + - function/wait + - function/request_user_input + - function/request_user_input_async + - namespace/clock: Tools for reading and waiting on time.; hash=f402e8c5e9b5e317 + - function/sleep +01:message/developer: + Keep the custom base instructions. +02:message/developer[3]: + [01] Explain the reasoning behind your findings. + [02] + Filesystem sandboxing defines which files can be read or written. `sandbox_mode` is `read-only`: The san... permits reading files. Network access is restricted. [hash=be7da4425f89053c] + # Escalation Requests + + Commands are run outside the sandbox if they are approved by the user, or match an existing rule that al...hell control operators, including but not limited to: [hash=d24ebf5fa4e4b9bb] + + - Pipes: | + - Logical operators: &&, || + + NEVER provide a prefix_rule if your command uses a heredoc or herestring. + + ### Examples + Good examples of prefixes: + - ["npm", "run", "dev"] + - ["gh", "pr", "check"] + - ["cargo", "test"] + + [03] # Collaboration Mode: Default + + You are now in Default mode. Any previous instructions for other modes (e.g. Plan mode) are no longer active. + + Your active mode changes only when new developer instructions with a different `...<...by themselves. Known mode names are Default and Plan. [hash=e75f6b12fc52d812] + + ## request_user_input availability + + Use the `request_user_input` tool only when it is listed in the available tools for this turn. + + Use the `request_user_input` tool only for optional questions where the answer would materially improve the quality of the work. + + If `request_user_input` returns no answers, continue with best judgment instead of asking again or treating the turn as blocked. + + Never use the `request_user_input` tool for permission requests or permission-related escalations. + +03:message/developer: + + Any earlier instruction enabling proactive multi-agent delegation no longer applies. Do not spawn sub-ag...k for sub-agents, delegation, or parallel agent work. [hash=6e1e1baf5a87faf5] + + Before calling any multi-agent tool, read the full multi-agent skill using its listed package locator. S...context. If the read fails, make note of the blocker. [hash=104096cdd6a881da] + +04:message/user: + + + + + + [hash=e8c1de60307d0a3d] + +05:message/user: + Prepare a worker with my instructions. +06:configuration_update:reasoning={"effort":"low"} +-- request 2 (turn) -- +07:function_call/host_spawn:{} +08:function_call_output:Done. + +## Window 2 (after request 2: input diverged at item 00) +Settings: relative to window 1 + model: "gpt-5.6-terra" + prompt_cache_key: "" + reasoning: {"context":"all_turns","effort":"medium"} +-- request 3 (turn) -- +00:additional_tools/developer (1; hash=60e22890380a03a6): + - namespace/functions; hash=501aefb2ebd05682 + - custom/exec + - function/wait + - function/request_user_input +01:message/developer: + Keep the custom base instructions. +02:message/developer[2]: + [01] Report worker findings concisely. + [02] + Filesystem sandboxing defines which files can be read or written. `sandbox_mode` is `read-only`: The san... permits reading files. Network access is restricted. [hash=be7da4425f89053c] + # Escalation Requests + + Commands are run outside the sandbox if they are approved by the user, or match an existing rule that al...hell control operators, including but not limited to: [hash=d24ebf5fa4e4b9bb] + + - Pipes: | + - Logical operators: &&, || + + NEVER provide a prefix_rule if your command uses a heredoc or herestring. + + ### Examples + Good examples of prefixes: + - ["npm", "run", "dev"] + - ["gh", "pr", "check"] + - ["cargo", "test"] + +03:message/developer: + + Any earlier instruction enabling proactive multi-agent delegation no longer applies. Do not spawn sub-ag...k for sub-agents, delegation, or parallel agent work. [hash=6e1e1baf5a87faf5] + + Before calling any multi-agent tool, read the full multi-agent skill using its listed package locator. S...context. If the read fails, make note of the blocker. [hash=104096cdd6a881da] + +04:message/user: + + + + + + [hash=e8c1de60307d0a3d] + +05:message/user: + Report your findings.