mirror of
https://github.com/openai/codex.git
synced 2026-12-04 00:51:02 +00:00
Extract shared multi-agent v2 thread spawning (#53660)
## What changed Move child configuration, task path construction, fork usage hints, and backend spawning into `core::thread_spawn`. Add request, result, and error types that distinguish preparation failures from backend errors. Route the v2 `spawn_agent` handler through the shared helper while retaining tool-specific telemetry, activity events, and response formatting in the handler. GitOrigin-RevId: a09a8f66beb41c1403220750d236a12717dbfc6c
This commit is contained in:
@@ -147,6 +147,7 @@ pub use codex_protocol::config_types::ModelProviderAuthInfo;
|
||||
mod event_mapping;
|
||||
pub use codex_prompts as review_prompts;
|
||||
mod thread_manager;
|
||||
mod thread_spawn;
|
||||
pub(crate) mod web_search;
|
||||
pub(crate) mod windows_sandbox_read_grants;
|
||||
pub use agent::control::ThreadEvictionOutcome;
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
//! Shared native MAv2 child preparation and spawning.
|
||||
//!
|
||||
//! Callers supply captured step settings; the configured agent backend owns child lifetimes.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::agent::api::AgentInput;
|
||||
use crate::agent::api::SpawnRequest;
|
||||
use crate::agent::child_config::SpawnConfigOptions;
|
||||
use crate::agent::child_config::SpawnConfigVersion;
|
||||
use crate::agent::child_config::prepare_agent_spawn_config;
|
||||
use crate::agent::next_thread_spawn_depth;
|
||||
use crate::agent::types::AgentMessage;
|
||||
use crate::agent::types::LiveAgent;
|
||||
use crate::agent::types::MessageDeliveryMode;
|
||||
use crate::agent::types::SpawnAgentForkMode;
|
||||
use crate::agent::types::SpawnAgentOptions;
|
||||
use crate::codex_thread::ThreadConfigSnapshot;
|
||||
use crate::session::multi_agents::resolve_usage_hints;
|
||||
use crate::session::session::Session;
|
||||
use crate::session::step_context::StepContext;
|
||||
use codex_prompts::ResolvedModelMessages;
|
||||
use codex_protocol::AgentPath;
|
||||
use codex_protocol::error::CodexErr;
|
||||
use codex_protocol::openai_models::ReasoningEffort;
|
||||
use codex_protocol::protocol::MultiAgentVersion;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use codex_protocol::protocol::SubAgentSource;
|
||||
|
||||
/// Child creation options; omitted overrides retain native MAv2 inheritance and role rules.
|
||||
pub(crate) struct ThreadSpawnRequest {
|
||||
pub task_name: String,
|
||||
/// Explicit encoding: hosts normally provide plaintext; native tools can forward ciphertext.
|
||||
pub message: AgentMessage,
|
||||
/// `None` starts fresh; `FullHistory` uses native fork preparation.
|
||||
pub fork_mode: Option<SpawnAgentForkMode>,
|
||||
pub agent_type: Option<String>,
|
||||
pub model: Option<String>,
|
||||
pub reasoning_effort: Option<ReasoningEffort>,
|
||||
}
|
||||
|
||||
/// Accepted child and its effective configuration. Acceptance does not mean the turn completed.
|
||||
pub(crate) struct ThreadSpawnResult {
|
||||
pub agent: LiveAgent,
|
||||
pub config: ThreadConfigSnapshot,
|
||||
pub task_name: AgentPath,
|
||||
}
|
||||
|
||||
/// Separates preparation errors from backend failures to preserve native tool error reporting.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub(crate) enum ThreadSpawnError {
|
||||
#[error("{0}")]
|
||||
Preparation(String),
|
||||
#[error(transparent)]
|
||||
Backend(#[from] CodexErr),
|
||||
}
|
||||
|
||||
pub(crate) async fn spawn(
|
||||
session: &Arc<Session>,
|
||||
step_context: &Arc<StepContext>,
|
||||
call_id: &str,
|
||||
request: ThreadSpawnRequest,
|
||||
) -> Result<ThreadSpawnResult, ThreadSpawnError> {
|
||||
let turn = &step_context.turn;
|
||||
let ThreadSpawnRequest {
|
||||
task_name,
|
||||
message,
|
||||
fork_mode,
|
||||
agent_type,
|
||||
model,
|
||||
reasoning_effort,
|
||||
} = request;
|
||||
let message_text = match &message {
|
||||
AgentMessage::Plaintext(text) | AgentMessage::Encrypted(text) => text,
|
||||
};
|
||||
if message_text.trim().is_empty() {
|
||||
return Err(ThreadSpawnError::Preparation(
|
||||
"Empty message can't be sent to an agent".to_string(),
|
||||
));
|
||||
}
|
||||
let role_name = agent_type
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|role| !role.is_empty());
|
||||
let prepared = prepare_agent_spawn_config(
|
||||
session,
|
||||
step_context,
|
||||
SpawnConfigOptions {
|
||||
version: SpawnConfigVersion::V2,
|
||||
full_history_fork: matches!(fork_mode, Some(SpawnAgentForkMode::FullHistory)),
|
||||
role_name,
|
||||
model: model.as_deref(),
|
||||
reasoning_effort,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.map_err(ThreadSpawnError::Preparation)?;
|
||||
let config = prepared.config;
|
||||
let task_name = turn
|
||||
.session_source
|
||||
.get_agent_path()
|
||||
.unwrap_or_else(AgentPath::root)
|
||||
.join(&task_name)
|
||||
.map_err(ThreadSpawnError::Preparation)?;
|
||||
let spawn_source = SessionSource::SubAgent(SubAgentSource::ThreadSpawn {
|
||||
parent_thread_id: session.thread_id,
|
||||
depth: next_thread_spawn_depth(&turn.session_source),
|
||||
agent_path: Some(task_name.clone()),
|
||||
agent_nickname: None,
|
||||
agent_role: prepared.role_name,
|
||||
});
|
||||
let multi_agent_v2_usage_hints = if matches!(fork_mode, Some(SpawnAgentForkMode::FullHistory))
|
||||
&& turn.multi_agent_version == MultiAgentVersion::V2
|
||||
{
|
||||
let child_model_info = match config.model.as_deref() {
|
||||
Some(model) if model != turn.model_info().slug => Some(
|
||||
session
|
||||
.services
|
||||
.models_manager
|
||||
.get_model_info(model, &config.to_models_manager_config())
|
||||
.await,
|
||||
),
|
||||
_ => None,
|
||||
};
|
||||
let child_multi_agent_messages = ResolvedModelMessages::from_model(
|
||||
child_model_info.as_ref().unwrap_or(turn.model_info()),
|
||||
)
|
||||
.multi_agent();
|
||||
Some(resolve_usage_hints(
|
||||
&config.multi_agent_v2,
|
||||
child_multi_agent_messages,
|
||||
!config.update_plan_enabled && config.model_catalog.is_none(),
|
||||
))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let (agent, config) = session
|
||||
.services
|
||||
.agent_control
|
||||
.spawn(SpawnRequest {
|
||||
caller: session.thread_id,
|
||||
config,
|
||||
input: AgentInput::Message {
|
||||
message,
|
||||
mode: MessageDeliveryMode::TriggerTurn,
|
||||
},
|
||||
source: spawn_source,
|
||||
options: SpawnAgentOptions {
|
||||
fork_parent_spawn_call_id: fork_mode.as_ref().map(|_| call_id.to_string()),
|
||||
fork_mode,
|
||||
parent_thread_id: Some(session.thread_id),
|
||||
parent_turn_id: Some(turn.sub_id.clone()),
|
||||
root_turn_id: turn.turn_metadata_state.root_turn_id(),
|
||||
turn_trigger: turn.turn_metadata_state.current_turn_trigger(),
|
||||
environments: Some(step_context.environments.clone()),
|
||||
disabled_plugin_ids: Some(turn.disabled_plugin_ids.clone()),
|
||||
multi_agent_v2_usage_hints,
|
||||
cyber_access_program: turn.cyber_access_program,
|
||||
},
|
||||
})
|
||||
.await?;
|
||||
Ok(ThreadSpawnResult {
|
||||
agent,
|
||||
config,
|
||||
task_name,
|
||||
})
|
||||
}
|
||||
@@ -1,22 +1,14 @@
|
||||
use super::*;
|
||||
use crate::agent::api::AgentInput;
|
||||
use crate::agent::api::SpawnRequest;
|
||||
use crate::agent::child_config::SpawnConfigOptions;
|
||||
use crate::agent::child_config::SpawnConfigVersion;
|
||||
use crate::agent::child_config::prepare_agent_spawn_config;
|
||||
use crate::agent::next_thread_spawn_depth;
|
||||
use crate::agent::role::DEFAULT_ROLE_NAME;
|
||||
use crate::agent::types::MessageDeliveryMode;
|
||||
use crate::agent::types::SpawnAgentForkMode;
|
||||
use crate::agent::types::SpawnAgentOptions;
|
||||
use crate::codex_thread::ThreadConfigSnapshot;
|
||||
use crate::session::multi_agents::resolve_usage_hints;
|
||||
use crate::thread_spawn::ThreadSpawnError;
|
||||
use crate::thread_spawn::ThreadSpawnRequest;
|
||||
use crate::tools::handlers::multi_agents::collab_tool_call_status;
|
||||
use crate::tools::handlers::multi_agents_spec::SpawnAgentToolOptions;
|
||||
use crate::tools::handlers::multi_agents_spec::create_spawn_agent_tool_v2;
|
||||
use crate::tools::handlers::multi_agents_v2::message_tool::message_content;
|
||||
use crate::turn_timing::now_unix_timestamp_ms;
|
||||
use codex_prompts::ResolvedModelMessages;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::MultiAgentVersion;
|
||||
use codex_tools::ToolSpec;
|
||||
@@ -129,85 +121,23 @@ async fn handle_spawn_agent(
|
||||
.map(str::trim)
|
||||
.filter(|role| !role.is_empty());
|
||||
|
||||
let session_source = turn.session_source.clone();
|
||||
let child_depth = next_thread_spawn_depth(&session_source);
|
||||
let prepared = prepare_agent_spawn_config(
|
||||
let spawned = crate::thread_spawn::spawn(
|
||||
&session,
|
||||
step_context.as_ref(),
|
||||
SpawnConfigOptions {
|
||||
version: SpawnConfigVersion::V2,
|
||||
full_history_fork: matches!(fork_mode, Some(SpawnAgentForkMode::FullHistory)),
|
||||
role_name,
|
||||
model: args.model.as_deref(),
|
||||
reasoning_effort: args.reasoning_effort.clone(),
|
||||
&step_context,
|
||||
&call_id,
|
||||
ThreadSpawnRequest {
|
||||
task_name: args.task_name,
|
||||
message: agent_message_from_tool(message, &source),
|
||||
fork_mode: fork_mode.clone(),
|
||||
agent_type: args.agent_type.clone(),
|
||||
model: args.model,
|
||||
reasoning_effort: args.reasoning_effort,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.map_err(FunctionCallError::RespondToModel)?;
|
||||
let config = prepared.config;
|
||||
let is_full_history_fork = matches!(fork_mode, Some(SpawnAgentForkMode::FullHistory));
|
||||
let spawn_source = thread_spawn_source(
|
||||
session.thread_id,
|
||||
&turn.session_source,
|
||||
child_depth,
|
||||
prepared.role_name.as_deref(),
|
||||
Some(args.task_name.clone()),
|
||||
)?;
|
||||
let new_agent_path = spawn_source.get_agent_path().ok_or_else(|| {
|
||||
FunctionCallError::RespondToModel(
|
||||
"spawned agent is missing a canonical task name".to_string(),
|
||||
)
|
||||
})?;
|
||||
let multi_agent_v2_usage_hints =
|
||||
if is_full_history_fork && turn.multi_agent_version == MultiAgentVersion::V2 {
|
||||
let child_model_info = match config.model.as_deref() {
|
||||
Some(model) if model != turn.model_info().slug => Some(
|
||||
session
|
||||
.services
|
||||
.models_manager
|
||||
.get_model_info(model, &config.to_models_manager_config())
|
||||
.await,
|
||||
),
|
||||
_ => None,
|
||||
};
|
||||
let child_multi_agent_messages = ResolvedModelMessages::from_model(
|
||||
child_model_info.as_ref().unwrap_or(turn.model_info()),
|
||||
)
|
||||
.multi_agent();
|
||||
Some(resolve_usage_hints(
|
||||
&config.multi_agent_v2,
|
||||
child_multi_agent_messages,
|
||||
!config.update_plan_enabled && config.model_catalog.is_none(),
|
||||
))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let (spawned_agent, agent_snapshot) = session
|
||||
.services
|
||||
.agent_control
|
||||
.spawn(SpawnRequest {
|
||||
caller: session.thread_id,
|
||||
config,
|
||||
input: AgentInput::Message {
|
||||
message: agent_message_from_tool(message, &source),
|
||||
mode: MessageDeliveryMode::TriggerTurn,
|
||||
},
|
||||
source: spawn_source,
|
||||
options: SpawnAgentOptions {
|
||||
fork_parent_spawn_call_id: fork_mode.as_ref().map(|_| call_id.clone()),
|
||||
fork_mode: fork_mode.clone(),
|
||||
parent_thread_id: Some(session.thread_id),
|
||||
parent_turn_id: Some(turn.sub_id.clone()),
|
||||
root_turn_id: turn.turn_metadata_state.root_turn_id(),
|
||||
turn_trigger: turn.turn_metadata_state.current_turn_trigger(),
|
||||
environments: Some(step_context.environments.clone()),
|
||||
disabled_plugin_ids: Some(turn.disabled_plugin_ids.clone()),
|
||||
multi_agent_v2_usage_hints,
|
||||
cyber_access_program: turn.cyber_access_program,
|
||||
},
|
||||
})
|
||||
.await
|
||||
.map_err(|err| {
|
||||
.map_err(|err| match err {
|
||||
ThreadSpawnError::Preparation(message) => FunctionCallError::RespondToModel(message),
|
||||
ThreadSpawnError::Backend(err) => {
|
||||
record_collab_spawn_failure(
|
||||
&turn.session_telemetry,
|
||||
turn.config.apps_mcp_product_sku.as_deref(),
|
||||
@@ -218,7 +148,11 @@ async fn handle_spawn_agent(
|
||||
MultiAgentVersion::V2,
|
||||
);
|
||||
collab_spawn_error(err)
|
||||
})?;
|
||||
}
|
||||
})?;
|
||||
let spawned_agent = spawned.agent;
|
||||
let agent_snapshot = spawned.config;
|
||||
let new_agent_path = spawned.task_name;
|
||||
let new_thread_id = spawned_agent.thread_id;
|
||||
let agent_status = spawned_agent.status;
|
||||
let nickname = agent_snapshot
|
||||
|
||||
Reference in New Issue
Block a user