Add configurable multi-agent model routing

This commit is contained in:
Nikil Pancha
2026-06-16 20:19:54 -07:00
parent 2ec687715d
commit 7e965a9964
12 changed files with 346 additions and 20 deletions
+9 -1
View File
@@ -1608,6 +1608,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"
},
@@ -5218,4 +5226,4 @@
},
"title": "ConfigToml",
"type": "object"
}
}
+41
View File
@@ -9852,6 +9852,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
"#,
)?;
@@ -9892,6 +9893,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(())
@@ -10276,6 +10281,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()?;
+42
View File
@@ -1051,6 +1051,7 @@ pub struct MultiAgentV2Config {
pub subagent_usage_hint_text: Option<String>,
pub tool_namespace: Option<String>,
pub hide_spawn_agent_metadata: bool,
pub spawn_agent_model_overrides: Option<Vec<String>>,
pub non_code_mode_only: bool,
}
@@ -1072,6 +1073,7 @@ impl Default for MultiAgentV2Config {
),
tool_namespace: None,
hide_spawn_agent_metadata: true,
spawn_agent_model_overrides: None,
non_code_mode_only: true,
}
}
@@ -2349,6 +2351,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);
@@ -2364,6 +2370,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,
}
}
@@ -2538,6 +2545,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(
@@ -3122,6 +3161,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(
@@ -105,6 +105,7 @@ async fn handle_spawn_agent(
turn.as_ref(),
&mut config,
args.model.as_deref(),
/*configured_model_overrides*/ None,
args.reasoning_effort.clone(),
)
.await?;
@@ -281,6 +281,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<ReasoningEffort>,
) -> Result<(), FunctionCallError> {
if requested_model.is_none() && requested_reasoning_effort.is_none() {
@@ -288,12 +289,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
@@ -327,6 +333,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<String, FunctionCallError> {
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,
@@ -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<ModelPreset>,
pub agent_type_description: String,
pub hide_agent_type_model_reasoning: bool,
pub model_overrides: Option<Vec<String>>,
pub include_usage_hint: bool,
pub usage_hint_text: Option<String>,
pub max_concurrent_threads_per_session: Option<usize>,
@@ -79,14 +81,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(
@@ -637,6 +659,15 @@ fn hide_spawn_agent_metadata_options(properties: &mut BTreeMap<String, JsonSchem
properties.remove("service_tier");
}
fn spawn_agent_model_allowlist_description(models: &[String]) -> String {
let models = models
.iter()
.map(|model| format!("`{model}`"))
.collect::<Vec<_>>()
.join(", ");
format!("Available model overrides: {models}.")
}
fn spawn_agent_tool_description(
available_models_description: Option<&str>,
inherited_model_guidance: Option<&str>,
@@ -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,
max_concurrent_threads_per_session: Some(4),
@@ -116,6 +117,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,
max_concurrent_threads_per_session: None,
@@ -168,6 +170,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,
max_concurrent_threads_per_session: Some(4),
@@ -213,6 +216,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,
max_concurrent_threads_per_session: Some(4),
@@ -239,6 +243,45 @@ 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,
max_concurrent_threads_per_session: Some(4),
});
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 {
@@ -457,6 +457,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)]
@@ -60,6 +60,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 initial_operation = parse_collab_input(Some(args.message), /*items*/ None)?;
let prompt = render_input_preview(&initial_operation);
@@ -97,6 +104,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?;
@@ -237,6 +248,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 { .. })
+14 -8
View File
@@ -716,6 +716,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(),
max_concurrent_threads_per_session: max_concurrent_threads_per_session(
@@ -759,14 +764,15 @@ fn add_collaboration_tools(context: &CoreToolPlanContext<'_>, planned_tools: &mu
ToolExposure::Direct
};
planned_tools.add_with_exposure(
SpawnAgentHandler::new(SpawnAgentToolOptions {
available_models: turn_context.available_models.clone(),
agent_type_description,
hide_agent_type_model_reasoning: turn_context
.config
.multi_agent_v2
.hide_spawn_agent_metadata,
include_usage_hint: turn_context.config.multi_agent_v2.usage_hint_enabled,
SpawnAgentHandler::new(SpawnAgentToolOptions {
available_models: turn_context.available_models.clone(),
agent_type_description,
hide_agent_type_model_reasoning: turn_context
.config
.multi_agent_v2
.hide_spawn_agent_metadata,
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(),
max_concurrent_threads_per_session: max_concurrent_threads_per_session(
turn_context,
+7
View File
@@ -54,6 +54,13 @@ pub struct MultiAgentV2ConfigToml {
pub tool_namespace: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub hide_spawn_agent_metadata: Option<bool>,
/// 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<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub non_code_mode_only: Option<bool>,
}
+6
View File
@@ -546,6 +546,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
"#,
)
@@ -569,6 +570,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),
}))
);
@@ -608,6 +613,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,
}))
);