From 5f8b2e544710b48d3e083fa127d65b2e5e7370cc Mon Sep 17 00:00:00 2001 From: Nikil Pancha Date: Tue, 16 Jun 2026 13:36:40 -0700 Subject: [PATCH] Add configurable multi-agent model routing --- codex-rs/core/config.schema.json | 10 +- codex-rs/core/src/agent/control.rs | 39 +++++ codex-rs/core/src/agent/control/legacy.rs | 1 + codex-rs/core/src/agent/control/spawn.rs | 133 +++++++++++++++++- codex-rs/core/src/agent/control_tests.rs | 50 ++++++- codex-rs/core/src/config/config_tests.rs | 41 ++++++ codex-rs/core/src/config/mod.rs | 42 ++++++ .../src/tools/handlers/multi_agents/spawn.rs | 1 + .../src/tools/handlers/multi_agents_common.rs | 34 ++++- .../src/tools/handlers/multi_agents_spec.rs | 41 +++++- .../tools/handlers/multi_agents_spec_tests.rs | 42 ++++++ .../src/tools/handlers/multi_agents_tests.rs | 91 ++++++++++++ .../tools/handlers/multi_agents_v2/spawn.rs | 28 ++++ codex-rs/core/src/tools/spec_plan.rs | 6 + codex-rs/features/src/feature_configs.rs | 7 + codex-rs/features/src/tests.rs | 6 + 16 files changed, 549 insertions(+), 23 deletions(-) diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index 31daf2feb4..df98fc87ba 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -1622,6 +1622,14 @@ "root_agent_usage_hint_text": { "type": "string" }, + "spawn_agent_model_overrides": { + "description": "Models that the parent model may explicitly select for a spawned agent.\n\nWhen set, the spawn tool exposes only the `model` metadata override and constrains it to this list.", + "items": { + "type": "string" + }, + "minItems": 1, + "type": "array" + }, "subagent_usage_hint_text": { "type": "string" }, @@ -5274,4 +5282,4 @@ }, "title": "ConfigToml", "type": "object" -} +} \ No newline at end of file diff --git a/codex-rs/core/src/agent/control.rs b/codex-rs/core/src/agent/control.rs index bd982b3c6f..90a1c6df94 100644 --- a/codex-rs/core/src/agent/control.rs +++ b/codex-rs/core/src/agent/control.rs @@ -98,6 +98,8 @@ pub(crate) struct AgentControl { manager: Weak, state: Arc, v2_residency: Arc, + v2_resume_configs: Arc>>>, + v2_load_locks: Arc>>>, agent_execution_limiter: Arc, } @@ -120,6 +122,42 @@ impl AgentControl { self.session_id } + fn remember_v2_resume_config(&self, thread_id: ThreadId, config: Arc) { + self.v2_resume_configs + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .insert(thread_id, config); + } + + fn v2_resume_config(&self, thread_id: ThreadId) -> Option { + self.v2_resume_configs + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .get(&thread_id) + .map(|config| config.as_ref().clone()) + } + + fn v2_load_lock(&self, thread_id: ThreadId) -> Arc { + Arc::clone( + self.v2_load_locks + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .entry(thread_id) + .or_insert_with(|| Arc::new(tokio::sync::Semaphore::new(1))), + ) + } + + fn forget_v2_reload_state(&self, thread_id: ThreadId) { + self.v2_resume_configs + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .remove(&thread_id); + self.v2_load_locks + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .remove(&thread_id); + } + /// Send rich user input items to an existing agent thread. pub(crate) async fn send_input( &self, @@ -206,6 +244,7 @@ impl AgentControl { if matches!(result, Err(CodexErr::InternalAgentDied)) { let _ = state.remove_thread(&agent_id).await; self.forget_v2_residency(agent_id); + self.forget_v2_reload_state(agent_id); self.state.release_spawned_thread(agent_id); } result diff --git a/codex-rs/core/src/agent/control/legacy.rs b/codex-rs/core/src/agent/control/legacy.rs index aa41472687..f645aa3b35 100644 --- a/codex-rs/core/src/agent/control/legacy.rs +++ b/codex-rs/core/src/agent/control/legacy.rs @@ -20,6 +20,7 @@ impl AgentControl { }; let _ = state.remove_thread(&agent_id).await; self.forget_v2_residency(agent_id); + self.forget_v2_reload_state(agent_id); self.state.release_spawned_thread(agent_id); result } diff --git a/codex-rs/core/src/agent/control/spawn.rs b/codex-rs/core/src/agent/control/spawn.rs index 9c12d60e6a..176c6c6afe 100644 --- a/codex-rs/core/src/agent/control/spawn.rs +++ b/codex-rs/core/src/agent/control/spawn.rs @@ -1,5 +1,6 @@ use super::residency::is_v2_resident_session_source; use super::*; +use crate::agent::role::apply_role_to_config; const AGENT_NAMES: &str = include_str!("../agent_names.txt"); @@ -16,6 +17,72 @@ fn default_agent_nickname_list() -> Vec<&'static str> { .collect() } +async fn rebuild_v2_resume_config( + mut config: Config, + thread_id: ThreadId, + agent_role: Option<&str>, + stored_model_provider: &str, + history: &[RolloutItem], +) -> CodexResult { + apply_role_to_config(&mut config, agent_role) + .await + .map_err(|err| { + CodexErr::Fatal(format!( + "failed to restore agent role for thread {thread_id}: {err}" + )) + })?; + + let mut model_provider_id = stored_model_provider.to_string(); + if let Some(session_configured) = history.iter().find_map(|item| match item { + RolloutItem::EventMsg(codex_protocol::protocol::EventMsg::SessionConfigured(event)) + if event.thread_id == thread_id => + { + Some(event) + } + _ => None, + }) { + config.model = Some(session_configured.model.clone()); + config.model_reasoning_effort = session_configured.reasoning_effort.clone(); + config.service_tier = session_configured.service_tier.clone(); + model_provider_id = session_configured.model_provider_id.clone(); + } else { + let own_session_start = history + .iter() + .rposition(|item| { + matches!( + item, + RolloutItem::SessionMeta(meta) if meta.meta.id == thread_id + ) + }) + .map_or(0, |index| index + 1); + if let Some(turn_context) = + history[own_session_start..] + .iter() + .find_map(|item| match item { + RolloutItem::TurnContext(turn_context) => Some(turn_context), + _ => None, + }) + { + config.model = Some(turn_context.model.clone()); + config.model_reasoning_effort = turn_context.effort.clone(); + } + } + + if model_provider_id != config.model_provider_id { + config.model_provider = config + .model_providers + .get(&model_provider_id) + .cloned() + .ok_or_else(|| { + CodexErr::Fatal(format!( + "model provider `{model_provider_id}` recorded for thread {thread_id} was not found" + )) + })?; + config.model_provider_id = model_provider_id; + } + Ok(config) +} + pub(super) fn agent_nickname_candidates(config: &Config, role_name: Option<&str>) -> Vec { let role_name = role_name.unwrap_or(DEFAULT_ROLE_NAME); if let Some(candidates) = @@ -116,14 +183,20 @@ impl AgentControl { config: Config, thread_id: ThreadId, ) -> CodexResult<()> { + let load_lock = self.v2_load_lock(thread_id); + let _load_permit = load_lock.acquire().await.map_err(|err| { + CodexErr::Fatal(format!( + "failed to acquire reload permit for thread {thread_id}: {err}" + )) + })?; let state = self.upgrade()?; if state.get_thread(thread_id).await.is_ok() { self.touch_loaded_v2_residency(&state, thread_id).await; return Ok(()); } - if self.state.agent_metadata_for_thread(thread_id).is_none() { + let Some(agent_metadata) = self.state.agent_metadata_for_thread(thread_id) else { return Err(CodexErr::ThreadNotFound(thread_id)); - } + }; let stored_thread = state .read_stored_thread(ReadThreadParams { @@ -134,10 +207,25 @@ impl AgentControl { .await?; let stored_source = stored_thread.source.clone(); let stored_parent_thread_id = stored_thread.parent_thread_id; + let stored_model_provider = stored_thread.model_provider.clone(); let history = stored_thread .history .ok_or(CodexErr::ThreadNotFound(thread_id))? .items; + let config = if let Some(config) = self.v2_resume_config(thread_id) { + config + } else { + let config = rebuild_v2_resume_config( + config, + thread_id, + agent_metadata.agent_role.as_deref(), + &stored_model_provider, + &history, + ) + .await?; + self.remember_v2_resume_config(thread_id, Arc::new(config.clone())); + config + }; let initial_history = InitialHistory::Resumed(ResumedHistory { conversation_id: thread_id, history, @@ -260,6 +348,7 @@ impl AgentControl { other => (other, AgentMetadata::default()), }; let notification_source = session_source.clone(); + let v2_resume_config = spawn_uses_v2_residency.then(|| Arc::new(config.clone())); // The same `AgentControl` is sent to spawn the thread. let new_thread = match (session_source, options.fork_mode.as_ref(), inheritance) { @@ -293,6 +382,9 @@ impl AgentControl { }; agent_metadata.agent_id = Some(new_thread.thread_id); reservation.commit(agent_metadata.clone()); + if let Some(v2_resume_config) = v2_resume_config { + self.remember_v2_resume_config(new_thread.thread_id, v2_resume_config); + } if let Some(residency_slot) = residency_slot { residency_slot.commit(new_thread.thread_id); } @@ -614,16 +706,46 @@ impl AgentControl { include_history: true, }) .await?; + let stored_agent_role = stored_thread.agent_role.clone(); + let stored_model_provider = stored_thread.model_provider.clone(); + let rollout_path = stored_thread.rollout_path.clone(); + let parent_thread_id = stored_thread.parent_thread_id; let history = stored_thread .history .ok_or_else(|| CodexErr::ThreadNotFound(thread_id))? .items; + let stored_multi_agent_version = history + .iter() + .rev() + .find_map(|item| match item { + RolloutItem::SessionMeta(meta) if meta.meta.id == thread_id => { + meta.meta.multi_agent_version + } + _ => None, + }) + .or_else(|| { + history.iter().rev().find_map(|item| match item { + RolloutItem::TurnContext(turn_context) => turn_context.multi_agent_version, + _ => None, + }) + }); + let config = if stored_multi_agent_version == Some(MultiAgentVersion::V2) { + rebuild_v2_resume_config( + config, + thread_id, + stored_agent_role.as_deref(), + &stored_model_provider, + &history, + ) + .await? + } else { + config + }; let initial_history = InitialHistory::Resumed(ResumedHistory { conversation_id: thread_id, history, - rollout_path: stored_thread.rollout_path, + rollout_path, }); - let parent_thread_id = stored_thread.parent_thread_id; let multi_agent_version = state .effective_multi_agent_version_for_spawn( &initial_history, @@ -686,6 +808,9 @@ impl AgentControl { let mut agent_metadata = agent_metadata; agent_metadata.agent_id = Some(resumed_thread.thread_id); reservation.commit(agent_metadata.clone()); + if multi_agent_version == MultiAgentVersion::V2 { + self.remember_v2_resume_config(thread_id, Arc::new(config)); + } // Resumed threads are re-registered in-memory and need the same listener // attachment path as freshly spawned threads. state.notify_thread_created(resumed_thread.thread_id); diff --git a/codex-rs/core/src/agent/control_tests.rs b/codex-rs/core/src/agent/control_tests.rs index 410e1beaf6..e276534d9a 100644 --- a/codex-rs/core/src/agent/control_tests.rs +++ b/codex-rs/core/src/agent/control_tests.rs @@ -17,6 +17,7 @@ use codex_protocol::config_types::ModeKind; use codex_protocol::models::ContentItem; use codex_protocol::models::MessagePhase; use codex_protocol::models::ResponseItem; +use codex_protocol::openai_models::ReasoningEffort; use codex_protocol::protocol::CompactedItem; use codex_protocol::protocol::ErrorEvent; use codex_protocol::protocol::EventMsg; @@ -545,13 +546,22 @@ async fn ensure_v2_agent_loaded_reloads_registered_unloaded_agent() { let (home, mut config) = test_config().await; let _ = config.features.enable(Feature::MultiAgentV2); let _ = config.features.enable(Feature::Sqlite); + config.model = Some("policy".to_string()); + config.model_reasoning_effort = Some(ReasoningEffort::High); + config.service_tier = Some("default".to_string()); + config.developer_instructions = Some("parent instructions".to_string()); let harness = AgentControlHarness::new_with_config(home, config).await; let (parent_thread_id, _parent_thread) = harness.start_thread().await; let agent_path = AgentPath::try_from("/root/worker").expect("agent path"); + let mut child_config = harness.config.clone(); + child_config.model = Some("mini".to_string()); + child_config.model_reasoning_effort = Some(ReasoningEffort::Low); + child_config.service_tier = Some("priority".to_string()); + child_config.developer_instructions = Some("child instructions".to_string()); let spawned_agent = harness .control .spawn_agent_with_metadata( - harness.config.clone(), + child_config, text_input("hello child"), Some(SessionSource::SubAgent(SubAgentSource::ThreadSpawn { parent_thread_id, @@ -567,6 +577,15 @@ async fn ensure_v2_agent_loaded_reloads_registered_unloaded_agent() { ) .await .expect("spawn_agent should succeed"); + let remembered_config = harness + .control + .v2_resume_config(spawned_agent.thread_id) + .expect("v2 child config should be retained for eviction reloads"); + assert_eq!( + remembered_config.developer_instructions.as_deref(), + Some("child instructions") + ); + assert_eq!(remembered_config.service_tier.as_deref(), Some("priority")); let child_thread = harness .manager .get_thread(spawned_agent.thread_id) @@ -596,17 +615,34 @@ async fn ensure_v2_agent_loaded_reloads_registered_unloaded_agent() { Err(err) => panic!("expected ThreadNotFound, got {err:?}"), Ok(_) => panic!("expected thread to be removed"), } - - harness + let first_reload = harness .control - .ensure_v2_agent_loaded(harness.config.clone(), spawned_agent.thread_id) - .await - .expect("known v2 agent should reload"); - let _ = harness + .ensure_v2_agent_loaded(harness.config.clone(), spawned_agent.thread_id); + let second_reload = harness + .control + .ensure_v2_agent_loaded(harness.config.clone(), spawned_agent.thread_id); + let (first_result, second_result) = tokio::join!(first_reload, second_reload); + first_result.expect("first concurrent reload should succeed"); + second_result.expect("second concurrent reload should coalesce"); + let reloaded_thread = harness .manager .get_thread(spawned_agent.thread_id) .await .expect("reloaded child thread should exist"); + assert_eq!(reloaded_thread.session_configured().model, "mini"); + assert_eq!( + reloaded_thread.session_configured().reasoning_effort, + Some(ReasoningEffort::Low) + ); + let reloaded_config = harness + .control + .v2_resume_config(spawned_agent.thread_id) + .expect("v2 child config should remain available after reload"); + assert_eq!(reloaded_config.service_tier.as_deref(), Some("priority")); + assert_eq!( + reloaded_config.developer_instructions.as_deref(), + Some("child instructions") + ); let communication = InterAgentCommunication::new( AgentPath::root(), diff --git a/codex-rs/core/src/config/config_tests.rs b/codex-rs/core/src/config/config_tests.rs index 38f04d23b6..c29fe0c536 100644 --- a/codex-rs/core/src/config/config_tests.rs +++ b/codex-rs/core/src/config/config_tests.rs @@ -9758,6 +9758,7 @@ root_agent_usage_hint_text = "Root guidance." subagent_usage_hint_text = "Subagent guidance." tool_namespace = "agents" hide_spawn_agent_metadata = true +spawn_agent_model_overrides = ["gpt-5.4", "gpt-5.3-codex"] non_code_mode_only = true "#, )?; @@ -9798,6 +9799,10 @@ non_code_mode_only = true Some("agents") ); assert!(config.multi_agent_v2.hide_spawn_agent_metadata); + assert_eq!( + config.multi_agent_v2.spawn_agent_model_overrides, + Some(vec!["gpt-5.4".to_string(), "gpt-5.3-codex".to_string()]) + ); assert!(config.multi_agent_v2.non_code_mode_only); Ok(()) @@ -10178,6 +10183,42 @@ tool_namespace = "{namespace}" Ok(()) } +#[tokio::test] +async fn multi_agent_v2_rejects_invalid_spawn_agent_model_overrides() -> std::io::Result<()> { + for (models, expected_message) in [ + ( + "[]", + "features.multi_agent_v2.spawn_agent_model_overrides must contain at least one model", + ), + ( + r#"["gpt-5.4", "gpt-5.4"]"#, + "features.multi_agent_v2.spawn_agent_model_overrides contains duplicate model `gpt-5.4`", + ), + ] { + let codex_home = TempDir::new()?; + std::fs::write( + codex_home.path().join(CONFIG_TOML_FILE), + format!( + r#"[features.multi_agent_v2] +enabled = true +spawn_agent_model_overrides = {models} +"# + ), + )?; + + let err = ConfigBuilder::without_managed_config_for_tests() + .codex_home(codex_home.path().to_path_buf()) + .fallback_cwd(Some(codex_home.path().to_path_buf())) + .build() + .await + .expect_err("invalid model override list should fail"); + assert_eq!(err.kind(), std::io::ErrorKind::InvalidInput); + assert_eq!(err.to_string(), expected_message); + } + + Ok(()) +} + #[tokio::test] async fn multi_agent_v2_session_thread_cap_one_disallows_subagents() -> std::io::Result<()> { let codex_home = TempDir::new()?; diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index 1dd4117e65..0ddee1e70f 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -1071,6 +1071,7 @@ pub struct MultiAgentV2Config { pub subagent_usage_hint_text: Option, pub tool_namespace: Option, pub hide_spawn_agent_metadata: bool, + pub spawn_agent_model_overrides: Option>, pub non_code_mode_only: bool, } @@ -1093,6 +1094,7 @@ impl MultiAgentV2Config { )), tool_namespace: None, hide_spawn_agent_metadata: true, + spawn_agent_model_overrides: None, non_code_mode_only: true, } } @@ -2441,6 +2443,10 @@ fn resolve_multi_agent_v2_config(config_toml: &ConfigToml) -> MultiAgentV2Config let hide_spawn_agent_metadata = base .and_then(|config| config.hide_spawn_agent_metadata) .unwrap_or(default.hide_spawn_agent_metadata); + let spawn_agent_model_overrides = base + .and_then(|config| config.spawn_agent_model_overrides.as_ref()) + .cloned() + .or(default.spawn_agent_model_overrides); let non_code_mode_only = base .and_then(|config| config.non_code_mode_only) .unwrap_or(default.non_code_mode_only); @@ -2456,6 +2462,7 @@ fn resolve_multi_agent_v2_config(config_toml: &ConfigToml) -> MultiAgentV2Config subagent_usage_hint_text, tool_namespace, hide_spawn_agent_metadata, + spawn_agent_model_overrides, non_code_mode_only, } } @@ -2621,6 +2628,38 @@ fn validate_multi_agent_v2_tool_namespace(namespace: Option<&str>) -> std::io::R Ok(()) } +fn validate_multi_agent_v2_spawn_agent_model_overrides( + models: Option<&[String]>, +) -> std::io::Result<()> { + const LABEL: &str = "features.multi_agent_v2.spawn_agent_model_overrides"; + + let Some(models) = models else { + return Ok(()); + }; + if models.is_empty() { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidInput, + format!("{LABEL} must contain at least one model"), + )); + } + for (index, model) in models.iter().enumerate() { + if model.is_empty() || model.trim() != model { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidInput, + format!("{LABEL}[{index}] must be non-empty and have no surrounding whitespace"), + )); + } + if models[..index].contains(model) { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidInput, + format!("{LABEL} contains duplicate model `{model}`"), + )); + } + } + + Ok(()) +} + impl Config { #[cfg(test)] async fn load_from_base_config_with_overrides( @@ -3187,6 +3226,9 @@ impl Config { )); } validate_multi_agent_v2_tool_namespace(multi_agent_v2.tool_namespace.as_deref())?; + validate_multi_agent_v2_spawn_agent_model_overrides( + multi_agent_v2.spawn_agent_model_overrides.as_deref(), + )?; let agent_max_threads = cfg.agents.as_ref().and_then(|agents| agents.max_threads); if agent_max_threads == Some(0) { return Err(std::io::Error::new( diff --git a/codex-rs/core/src/tools/handlers/multi_agents/spawn.rs b/codex-rs/core/src/tools/handlers/multi_agents/spawn.rs index 204385934e..b349a6f01f 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents/spawn.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents/spawn.rs @@ -101,6 +101,7 @@ async fn handle_spawn_agent( turn.as_ref(), &mut config, args.model.as_deref(), + /*configured_model_overrides*/ None, args.reasoning_effort.clone(), ) .await?; diff --git a/codex-rs/core/src/tools/handlers/multi_agents_common.rs b/codex-rs/core/src/tools/handlers/multi_agents_common.rs index 5958892152..edf404dd58 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents_common.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents_common.rs @@ -282,6 +282,7 @@ pub(crate) async fn apply_requested_spawn_agent_model_overrides( turn: &TurnContext, config: &mut Config, requested_model: Option<&str>, + configured_model_overrides: Option<&[String]>, requested_reasoning_effort: Option, ) -> Result<(), FunctionCallError> { if requested_model.is_none() && requested_reasoning_effort.is_none() { @@ -289,12 +290,17 @@ pub(crate) async fn apply_requested_spawn_agent_model_overrides( } if let Some(requested_model) = requested_model { - let available_models = session - .services - .models_manager - .list_models(RefreshStrategy::Offline) - .await; - let selected_model_name = find_spawn_agent_model_name(&available_models, requested_model)?; + let selected_model_name = + if let Some(configured_model_overrides) = configured_model_overrides { + find_configured_spawn_agent_model_name(configured_model_overrides, requested_model)? + } else { + let available_models = session + .services + .models_manager + .list_models(RefreshStrategy::Offline) + .await; + find_spawn_agent_model_name(&available_models, requested_model)? + }; let selected_model_info = session .services .models_manager @@ -328,6 +334,22 @@ pub(crate) async fn apply_requested_spawn_agent_model_overrides( Ok(()) } +fn find_configured_spawn_agent_model_name( + configured_models: &[String], + requested_model: &str, +) -> Result { + configured_models + .iter() + .find(|model| model.as_str() == requested_model) + .cloned() + .ok_or_else(|| { + FunctionCallError::RespondToModel(format!( + "Model `{requested_model}` is not allowed for spawn_agent. Configured models: {}", + configured_models.join(", ") + )) + }) +} + pub(crate) async fn apply_spawn_agent_service_tier( session: &Session, config: &mut Config, diff --git a/codex-rs/core/src/tools/handlers/multi_agents_spec.rs b/codex-rs/core/src/tools/handlers/multi_agents_spec.rs index 70f71f3114..d980e96364 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents_spec.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents_spec.rs @@ -14,6 +14,7 @@ const MULTI_AGENT_V1_NAMESPACE_DESCRIPTION: &str = "Tools for spawning and manag const SPAWN_AGENT_INHERITED_MODEL_GUIDANCE: &str = "Spawned agents inherit your current model by default. Omit `model` to use that preferred default; set `model` only when an explicit override is needed."; const SPAWN_AGENT_MODEL_OVERRIDE_DESCRIPTION: &str = "Model override for the new agent. Omit unless an explicit override is needed."; +const SPAWN_AGENT_MODEL_ALLOWLIST_GUIDANCE: &str = "Choose `model` from the configured list when a different model is appropriate. Model overrides require `fork_turns` to be `none` or a positive integer; full-history forks inherit the parent model."; const SPAWN_AGENT_SERVICE_TIER_OVERRIDE_DESCRIPTION: &str = "Service tier override for the new agent. Omit unless explicitly requested."; const MAX_MODEL_OVERRIDES_IN_SPAWN_AGENT_DESCRIPTION: usize = 5; @@ -24,6 +25,7 @@ pub struct SpawnAgentToolOptions { pub available_models: Vec, pub agent_type_description: String, pub hide_agent_type_model_reasoning: bool, + pub model_overrides: Option>, pub include_usage_hint: bool, pub usage_hint_text: Option, } @@ -78,14 +80,34 @@ pub fn create_spawn_agent_tool_v1(options: SpawnAgentToolOptions) -> ToolSpec { } pub fn create_spawn_agent_tool_v2(options: SpawnAgentToolOptions) -> ToolSpec { - let available_models_description = (!options.hide_agent_type_model_reasoning) - .then(|| spawn_agent_models_description(&options.available_models)); - let inherited_model_guidance = - (!options.hide_agent_type_model_reasoning).then_some(SPAWN_AGENT_INHERITED_MODEL_GUIDANCE); + let model_only_overrides = options.model_overrides.as_deref(); + let available_models_description = match model_only_overrides { + Some(models) => Some(spawn_agent_model_allowlist_description(models)), + None if !options.hide_agent_type_model_reasoning => { + Some(spawn_agent_models_description(&options.available_models)) + } + None => None, + }; + let inherited_model_guidance = match model_only_overrides { + Some(_) => Some(SPAWN_AGENT_MODEL_ALLOWLIST_GUIDANCE), + None if !options.hide_agent_type_model_reasoning => { + Some(SPAWN_AGENT_INHERITED_MODEL_GUIDANCE) + } + None => None, + }; let mut properties = spawn_agent_common_properties_v2(&options.agent_type_description); - if options.hide_agent_type_model_reasoning { + if options.hide_agent_type_model_reasoning || model_only_overrides.is_some() { hide_spawn_agent_metadata_options(&mut properties); } + if let Some(models) = model_only_overrides { + properties.insert( + "model".to_string(), + JsonSchema::string_enum( + models.iter().cloned().map(Value::String).collect(), + Some(SPAWN_AGENT_MODEL_OVERRIDE_DESCRIPTION.to_string()), + ), + ); + } properties.insert( "task_name".to_string(), JsonSchema::string(Some( @@ -644,6 +666,15 @@ fn hide_spawn_agent_metadata_options(properties: &mut BTreeMap String { + let models = models + .iter() + .map(|model| format!("`{model}`")) + .collect::>() + .join(", "); + format!("Available model overrides: {models}.") +} + fn spawn_agent_tool_description( available_models_description: Option<&str>, inherited_model_guidance: Option<&str>, diff --git a/codex-rs/core/src/tools/handlers/multi_agents_spec_tests.rs b/codex-rs/core/src/tools/handlers/multi_agents_spec_tests.rs index 1ef93b77f0..f03bb86a0e 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents_spec_tests.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents_spec_tests.rs @@ -45,6 +45,7 @@ fn spawn_agent_tool_v2_requires_task_name_and_lists_visible_models() { ], agent_type_description: "role help".to_string(), hide_agent_type_model_reasoning: false, + model_overrides: None, include_usage_hint: true, usage_hint_text: None, }); @@ -121,6 +122,7 @@ fn spawn_agent_tool_v1_keeps_legacy_fork_context_field() { available_models: Vec::new(), agent_type_description: "role help".to_string(), hide_agent_type_model_reasoning: false, + model_overrides: None, include_usage_hint: true, usage_hint_text: None, }); @@ -178,6 +180,7 @@ fn spawn_agent_tool_caps_visible_model_summaries() { ], agent_type_description: "role help".to_string(), hide_agent_type_model_reasoning: false, + model_overrides: None, include_usage_hint: true, usage_hint_text: None, }); @@ -222,6 +225,7 @@ fn spawn_agent_tool_hides_service_tier_with_spawn_metadata() { available_models: vec![model_preset("visible", /*show_in_picker*/ true)], agent_type_description: "role help".to_string(), hide_agent_type_model_reasoning: true, + model_overrides: None, include_usage_hint: true, usage_hint_text: None, }); @@ -247,6 +251,44 @@ fn spawn_agent_tool_hides_service_tier_with_spawn_metadata() { assert!(!description.contains("Available model overrides")); } +#[test] +fn spawn_agent_tool_exposes_only_configured_model_overrides() { + let tool = create_spawn_agent_tool_v2(SpawnAgentToolOptions { + available_models: vec![model_preset("catalog", /*show_in_picker*/ true)], + agent_type_description: "role help".to_string(), + hide_agent_type_model_reasoning: true, + model_overrides: Some(vec!["gpt-5.4".to_string(), "gpt-5.3-codex".to_string()]), + include_usage_hint: true, + usage_hint_text: None, + }); + + let ToolSpec::Function(ResponsesApiTool { + description, + parameters, + .. + }) = tool + else { + panic!("spawn_agent should be a function tool"); + }; + let properties = parameters + .properties + .as_ref() + .expect("spawn_agent should use object params"); + + assert!(!properties.contains_key("agent_type")); + assert_eq!( + properties + .get("model") + .and_then(|schema| schema.enum_values.as_ref()), + Some(&vec![json!("gpt-5.4"), json!("gpt-5.3-codex")]) + ); + assert!(!properties.contains_key("reasoning_effort")); + assert!(!properties.contains_key("service_tier")); + assert!(description.contains("Available model overrides: `gpt-5.4`, `gpt-5.3-codex`.")); + assert!(!description.contains("catalog-model")); + assert!(description.contains(SPAWN_AGENT_MODEL_ALLOWLIST_GUIDANCE)); +} + #[test] fn send_message_tool_requires_message_and_has_no_output_schema() { let ToolSpec::Function(ResponsesApiTool { diff --git a/codex-rs/core/src/tools/handlers/multi_agents_tests.rs b/codex-rs/core/src/tools/handlers/multi_agents_tests.rs index 8c3ea14325..010154f62c 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents_tests.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents_tests.rs @@ -462,6 +462,97 @@ async fn multi_agent_v2_spawn_defaults_to_full_fork_and_rejects_child_model_over ); } +#[tokio::test] +async fn multi_agent_v2_spawn_rejects_model_outside_configured_overrides() { + let (session, mut turn) = make_session_and_context().await; + let mut config = (*turn.config).clone(); + config + .features + .enable(Feature::MultiAgentV2) + .expect("test config should allow feature update"); + config.multi_agent_v2.spawn_agent_model_overrides = + Some(vec!["gpt-5.4".to_string(), "gpt-5.3-codex".to_string()]); + set_turn_config(&mut turn, config); + + let err = SpawnAgentHandlerV2::default() + .handle(invocation( + Arc::new(session), + Arc::new(turn), + "spawn_agent", + function_payload(json!({ + "message": "inspect this repo", + "task_name": "disallowed_model", + "fork_turns": "none", + "model": "gpt-5.2" + })), + )) + .await + .err() + .expect("model outside configured overrides should fail"); + + assert_eq!( + err, + FunctionCallError::RespondToModel( + "Model `gpt-5.2` is not allowed for spawn_agent. Configured models: gpt-5.4, gpt-5.3-codex" + .to_string(), + ) + ); +} + +#[tokio::test] +async fn multi_agent_v2_spawn_accepts_freeform_configured_model_override() { + let (mut session, mut turn) = make_session_and_context().await; + let manager = thread_manager(); + let root = manager + .start_thread((*turn.config).clone()) + .await + .expect("root thread should start"); + session.services.agent_control = manager.agent_control(); + session.thread_id = root.thread_id; + let mut config = (*turn.config).clone(); + config + .features + .enable(Feature::MultiAgentV2) + .expect("test config should allow feature update"); + config.multi_agent_v2.spawn_agent_model_overrides = Some(vec![ + "self".to_string(), + "mini".to_string(), + "nano".to_string(), + "nano3093".to_string(), + ]); + set_turn_config(&mut turn, config); + + SpawnAgentHandlerV2::default() + .handle(invocation( + Arc::new(session), + Arc::new(turn), + "spawn_agent", + function_payload(json!({ + "message": "inspect this repo", + "task_name": "freeform_model", + "fork_turns": "none", + "model": "nano3093" + })), + )) + .await + .expect("configured freeform model should be accepted"); + + let agent_id = manager + .captured_ops() + .into_iter() + .map(|(thread_id, _)| thread_id) + .find(|thread_id| *thread_id != root.thread_id) + .expect("spawned agent should receive an op"); + let snapshot = manager + .get_thread(agent_id) + .await + .expect("spawned agent thread should exist") + .config_snapshot() + .await; + + assert_eq!(snapshot.model, "nano3093"); +} + #[tokio::test] async fn spawn_agent_service_tier_override_validates_the_effective_child_model() { #[derive(Debug, Deserialize)] diff --git a/codex-rs/core/src/tools/handlers/multi_agents_v2/spawn.rs b/codex-rs/core/src/tools/handlers/multi_agents_v2/spawn.rs index 2186a4a6d6..38566abdac 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents_v2/spawn.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents_v2/spawn.rs @@ -54,6 +54,13 @@ async fn handle_spawn_agent( .as_deref() .map(str::trim) .filter(|role| !role.is_empty()); + validate_configured_model_override( + args.model.as_deref(), + turn.config + .multi_agent_v2 + .spawn_agent_model_overrides + .as_deref(), + )?; let message = args.message.clone(); let initial_operation = parse_collab_input(Some(args.message), /*items*/ None)?; @@ -76,6 +83,10 @@ async fn handle_spawn_agent( turn.as_ref(), &mut config, args.model.as_deref(), + turn.config + .multi_agent_v2 + .spawn_agent_model_overrides + .as_deref(), args.reasoning_effort.clone(), ) .await?; @@ -176,6 +187,23 @@ async fn handle_spawn_agent( } } +fn validate_configured_model_override( + requested_model: Option<&str>, + allowed_models: Option<&[String]>, +) -> Result<(), FunctionCallError> { + let (Some(requested_model), Some(allowed_models)) = (requested_model, allowed_models) else { + return Ok(()); + }; + if allowed_models.iter().any(|model| model == requested_model) { + return Ok(()); + } + + Err(FunctionCallError::RespondToModel(format!( + "Model `{requested_model}` is not allowed for spawn_agent. Configured models: {}", + allowed_models.join(", ") + ))) +} + impl CoreToolRuntime for Handler { fn matches_kind(&self, payload: &ToolPayload) -> bool { matches!(payload, ToolPayload::Function { .. }) diff --git a/codex-rs/core/src/tools/spec_plan.rs b/codex-rs/core/src/tools/spec_plan.rs index 8728476110..eaa75143b2 100644 --- a/codex-rs/core/src/tools/spec_plan.rs +++ b/codex-rs/core/src/tools/spec_plan.rs @@ -727,6 +727,11 @@ fn add_collaboration_tools(context: &CoreToolPlanContext<'_>, planned_tools: &mu .config .multi_agent_v2 .hide_spawn_agent_metadata, + model_overrides: turn_context + .config + .multi_agent_v2 + .spawn_agent_model_overrides + .clone(), include_usage_hint: turn_context.config.multi_agent_v2.usage_hint_enabled, usage_hint_text: turn_context.config.multi_agent_v2.usage_hint_text.clone(), }), @@ -771,6 +776,7 @@ fn add_collaboration_tools(context: &CoreToolPlanContext<'_>, planned_tools: &mu available_models: turn_context.available_models.clone(), agent_type_description, hide_agent_type_model_reasoning: false, + model_overrides: None, include_usage_hint: turn_context.config.multi_agent_v2.usage_hint_enabled, usage_hint_text: turn_context.config.multi_agent_v2.usage_hint_text.clone(), }), diff --git a/codex-rs/features/src/feature_configs.rs b/codex-rs/features/src/feature_configs.rs index f59b89e9a8..eceac45fc7 100644 --- a/codex-rs/features/src/feature_configs.rs +++ b/codex-rs/features/src/feature_configs.rs @@ -54,6 +54,13 @@ pub struct MultiAgentV2ConfigToml { pub tool_namespace: Option, #[serde(skip_serializing_if = "Option::is_none")] pub hide_spawn_agent_metadata: Option, + /// Models that the parent model may explicitly select for a spawned agent. + /// + /// When set, the spawn tool exposes only the `model` metadata override and + /// constrains it to this list. + #[serde(skip_serializing_if = "Option::is_none")] + #[schemars(length(min = 1))] + pub spawn_agent_model_overrides: Option>, #[serde(skip_serializing_if = "Option::is_none")] pub non_code_mode_only: Option, } diff --git a/codex-rs/features/src/tests.rs b/codex-rs/features/src/tests.rs index 0995dfe019..18ecbce633 100644 --- a/codex-rs/features/src/tests.rs +++ b/codex-rs/features/src/tests.rs @@ -576,6 +576,7 @@ root_agent_usage_hint_text = "Root guidance." subagent_usage_hint_text = "Subagent guidance." tool_namespace = "agents" hide_spawn_agent_metadata = true +spawn_agent_model_overrides = ["gpt-5.4", "gpt-5.3-codex"] non_code_mode_only = true "#, ) @@ -599,6 +600,10 @@ non_code_mode_only = true subagent_usage_hint_text: Some("Subagent guidance.".to_string()), tool_namespace: Some("agents".to_string()), hide_spawn_agent_metadata: Some(true), + spawn_agent_model_overrides: Some(vec![ + "gpt-5.4".to_string(), + "gpt-5.3-codex".to_string(), + ]), non_code_mode_only: Some(true), })) ); @@ -638,6 +643,7 @@ usage_hint_enabled = false subagent_usage_hint_text: None, tool_namespace: None, hide_spawn_agent_metadata: None, + spawn_agent_model_overrides: None, non_code_mode_only: None, })) );