Centralize multi-agent V2 runtime checks (#64731)

Add `MultiAgentVersion::uses_v2_runtime` to identify versions that use
path-addressed workers and turn-scoped execution slots. Use it to gate
runtime behavior such as subagent spawning and resumption, forked
history handling, and message routing. The predicate matches only
`MultiAgentVersion::V2`, preserving existing behavior.

GitOrigin-RevId: 712243c5df310c0745bf69c4faff660a44f05be5
This commit is contained in:
jif
2026-11-30 13:09:06 +00:00
committed by copyberry
parent acd1a3794b
commit bda8fc3c04
26 changed files with 88 additions and 54 deletions
+3 -1
View File
@@ -277,7 +277,9 @@ impl MessageBoardHost for LocalBoardHost {
}
match self.notification_route {
NotificationRoute::Injection
if recipient.multi_agent_version() == Some(MultiAgentVersion::V2)
if recipient
.multi_agent_version()
.is_some_and(MultiAgentVersion::uses_v2_runtime)
&& !recipient.config().await.multi_agent_v2.disable_native_tools =>
{
recipient
@@ -13,7 +13,7 @@ pub(super) fn can_accept_direct_input(
multi_agent_version: Option<MultiAgentVersion>,
session_source: &SessionSource,
) -> bool {
multi_agent_version != Some(MultiAgentVersion::V2)
!multi_agent_version.is_some_and(MultiAgentVersion::uses_v2_runtime)
|| !matches!(
session_source,
SessionSource::SubAgent(SubAgentSource::ThreadSpawn { .. })
@@ -218,7 +218,9 @@ pub(super) async fn attach_created_thread_listener(
continue;
}
if connection_ids.is_empty()
&& (thread.multi_agent_version() != Some(MultiAgentVersion::V2)
&& (!thread
.multi_agent_version()
.is_some_and(MultiAgentVersion::uses_v2_runtime)
|| config_snapshot.ephemeral)
{
return;
@@ -351,7 +353,9 @@ async fn start_listener(
&environments,
)
.await;
let is_v2_child = conversation.multi_agent_version() == Some(MultiAgentVersion::V2)
let is_v2_child = conversation
.multi_agent_version()
.is_some_and(MultiAgentVersion::uses_v2_runtime)
&& matches!(config_snapshot.session_source, SessionSource::SubAgent(_));
let thread_settings_baseline = thread_settings_from_config_snapshot(&config_snapshot).ok();
let thread_state = Arc::clone(listener_state.state());
+2 -2
View File
@@ -26,7 +26,7 @@ pub(crate) fn model_supports_multi_agent_backend(
model: &ModelPreset,
multi_agent_version: MultiAgentVersion,
) -> bool {
multi_agent_version != MultiAgentVersion::V2
!multi_agent_version.uses_v2_runtime()
|| model.multi_agent_version != Some(MultiAgentVersion::Disabled)
}
@@ -193,7 +193,7 @@ fn build_agent_shared_config(turn: &TurnContext) -> Result<Config, String> {
}
pub(crate) fn inherited_developer_instructions(turn: &TurnContext) -> Option<String> {
if turn.multi_agent_version == MultiAgentVersion::V2
if turn.multi_agent_version.uses_v2_runtime()
&& let Some(instructions) = &turn.config.multi_agent_v2.subagent_developer_instructions
{
return Some(instructions.clone());
+3 -3
View File
@@ -521,9 +521,9 @@ impl LocalAgentControl {
};
let child_thread = state.get_thread(child_thread_id).await.ok();
let child_uses_multi_agent_v2 = match child_thread.as_ref() {
Some(child_thread) => {
child_thread.multi_agent_version() == Some(MultiAgentVersion::V2)
}
Some(child_thread) => child_thread
.multi_agent_version()
.is_some_and(MultiAgentVersion::uses_v2_runtime),
None => true,
};
if child_agent_path.is_some() && child_uses_multi_agent_v2 {
+1 -2
View File
@@ -83,8 +83,7 @@ fn is_execution_limited(
multi_agent_version: MultiAgentVersion,
session_source: &SessionSource,
) -> bool {
multi_agent_version == MultiAgentVersion::V2
&& matches!(session_source, SessionSource::SubAgent(_))
multi_agent_version.uses_v2_runtime() && matches!(session_source, SessionSource::SubAgent(_))
}
#[cfg(test)]
+3 -1
View File
@@ -328,7 +328,9 @@ fn touch_resident(residents: &mut VecDeque<ThreadId>, thread_id: ThreadId) {
}
fn is_resident_candidate(thread: &CodexThread) -> bool {
thread.multi_agent_version() == Some(MultiAgentVersion::V2)
thread
.multi_agent_version()
.is_some_and(MultiAgentVersion::uses_v2_runtime)
&& is_v2_resident_session_source(&thread.session_source)
}
+5 -1
View File
@@ -26,7 +26,11 @@ impl LocalAgentControl {
child_id: ThreadId,
) -> CodexResult<LoadedSuspendedAgent> {
let root_id = root.startup_metadata().thread_id;
if child_id == root_id || root.multi_agent_version() != Some(MultiAgentVersion::V2) {
if child_id == root_id
|| !root
.multi_agent_version()
.is_some_and(MultiAgentVersion::uses_v2_runtime)
{
return Err(CodexErr::InvalidRequest(
"expected a named V2 descendant".to_owned(),
));
+17 -12
View File
@@ -102,9 +102,7 @@ pub(in crate::agent) async fn inherited_dynamic_tools(
config: &Config,
version: MultiAgentVersion,
) -> Vec<DynamicToolSpec> {
if version == MultiAgentVersion::V2
&& config.features.enabled(Feature::MultiAgentV2DynamicTools)
{
if version.uses_v2_runtime() && config.features.enabled(Feature::MultiAgentV2DynamicTools) {
parent.session.dynamic_tools().await.to_vec()
} else {
Vec::new()
@@ -229,7 +227,9 @@ impl LocalAgentControl {
parent_thread_id: ThreadId,
) -> CodexResult<()> {
if thread.is_running()
&& thread.multi_agent_version() == Some(MultiAgentVersion::V2)
&& thread
.multi_agent_version()
.is_some_and(MultiAgentVersion::uses_v2_runtime)
&& thread.session_source.parent_thread_id() == Some(parent_thread_id)
&& Arc::ptr_eq(
&self.runtime.registry,
@@ -262,7 +262,9 @@ impl LocalAgentControl {
.as_ref()
.is_some_and(|registered| Arc::ptr_eq(registered, parent))
|| !parent.is_running()
|| parent.multi_agent_version() != Some(MultiAgentVersion::V2)
|| !parent
.multi_agent_version()
.is_some_and(MultiAgentVersion::uses_v2_runtime)
|| !Arc::ptr_eq(
&self.runtime.registry,
&parent.session.services.local_agent_runtime.registry,
@@ -324,7 +326,10 @@ impl LocalAgentControl {
history: Arc::new(history.items),
rollout_path: stored_thread.rollout_path,
});
if initial_history.get_multi_agent_version() != Some(MultiAgentVersion::V2) {
if !initial_history
.get_multi_agent_version()
.is_some_and(MultiAgentVersion::uses_v2_runtime)
{
return Err(CodexErr::ThreadNotFound(thread_id));
}
let (session_source, _) = initial_history
@@ -694,7 +699,7 @@ impl LocalAgentControl {
self.ensure_execution_capacity(multi_agent_version, session_source)?;
}
let agent_max_threads = config.effective_agent_max_threads(multi_agent_version);
let spawn_uses_v2_residency = multi_agent_version == MultiAgentVersion::V2
let spawn_uses_v2_residency = multi_agent_version.uses_v2_runtime()
&& session_source
.as_ref()
.is_some_and(is_v2_resident_session_source);
@@ -974,7 +979,7 @@ impl LocalAgentControl {
let durability_wait = edge_write + durability_wait_started_at.elapsed();
// Capture startup settings before the child can publish metadata for a later turn.
let spawn_config = if multi_agent_version == MultiAgentVersion::V2 {
let spawn_config = if multi_agent_version.uses_v2_runtime() {
Some(effective_spawn_config(&new_thread.thread).await?)
} else {
None
@@ -1046,7 +1051,7 @@ impl LocalAgentControl {
// to subscribe or drain this newly created thread.
// TODO(jif) add helper for drain
state.notify_thread_created(new_thread.thread_id);
if multi_agent_version != MultiAgentVersion::V2 {
if !multi_agent_version.uses_v2_runtime() {
let child_reference = agent_metadata
.agent_path
.as_ref()
@@ -1100,8 +1105,8 @@ impl LocalAgentControl {
)
.await?;
let state = self.runtime.upgrade()?;
if config.multi_agent_version_from_features() == MultiAgentVersion::V2
|| resumed_multi_agent_version == MultiAgentVersion::V2
if config.multi_agent_version_from_features().uses_v2_runtime()
|| resumed_multi_agent_version.uses_v2_runtime()
{
return Ok(resumed_thread_id);
}
@@ -1262,7 +1267,7 @@ impl LocalAgentControl {
// 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);
if multi_agent_version != MultiAgentVersion::V2 {
if !multi_agent_version.uses_v2_runtime() {
let child_reference = agent_metadata
.agent_path
.as_ref()
@@ -260,7 +260,10 @@ impl LocalAgentControl {
}
let manager = self.runtime.upgrade().ok()?;
let root_thread = manager.get_thread(root_thread_id).await.ok()?;
if root_thread.multi_agent_version() != Some(MultiAgentVersion::V2) {
if !root_thread
.multi_agent_version()
.is_some_and(MultiAgentVersion::uses_v2_runtime)
{
return None;
}
+8 -7
View File
@@ -75,7 +75,7 @@ fn sanitize_forked_rollout_item(
let explicitly_retained = child_retention == Some(true);
if preserve_fork_prefix
|| explicitly_retained
|| (version == MultiAgentVersion::V2
|| (version.uses_v2_runtime()
&& matches!(&envelope.item, ResponseItem::Message { role, .. } if role == "user" || role == "assistant"))
{
envelope
@@ -103,15 +103,16 @@ fn sanitize_forked_rollout_item(
}
}
compacted.guardian_history = None;
compacted.retained_context =
(version == MultiAgentVersion::V2).then(codex_history::RetainedContext::default);
compacted.retained_context = version
.uses_v2_runtime()
.then(codex_history::RetainedContext::default);
if let Some(history) = &mut compacted.replacement_history {
history.retain_mut(&mut retain_envelope);
}
true
}
RolloutItem::WorldState(world_state)
if version == MultiAgentVersion::V2 || preserve_fork_prefix =>
if version.uses_v2_runtime() || preserve_fork_prefix =>
{
world_state.state.remove("multi_agent_usage_hint");
true
@@ -416,7 +417,7 @@ pub(super) async fn prepare_forked_history(
.items;
let multi_agent_v2_usage_hint_texts_to_filter: Vec<String> =
if multi_agent_version == MultiAgentVersion::V2 {
if multi_agent_version.uses_v2_runtime() {
let parent_config = parent_thread.session.get_config().await;
let parent_usage_hints = resolve_usage_hints(
&parent_config.multi_agent_v2,
@@ -444,7 +445,7 @@ pub(super) async fn prepare_forked_history(
break;
}
let mut replaced_parent_developer_instructions = false;
let preserve_fork_prefix = multi_agent_version == MultiAgentVersion::V2
let preserve_fork_prefix = multi_agent_version.uses_v2_runtime()
&& config.multi_agent_v2.preserve_fork_prefix
&& preserve_context_baselines;
if preserve_fork_prefix && let Some(turn) = unfinished_turn(&forked_rollout_items) {
@@ -558,7 +559,7 @@ pub(super) async fn prepare_forked_history(
forked_rollout_items.push(RolloutItem::ResponseItem(developer_message.into()));
}
if preserve_context_baselines
&& multi_agent_version == MultiAgentVersion::V2
&& multi_agent_version.uses_v2_runtime()
&& let Some(subagent_usage_hint) = options
.multi_agent_v2_usage_hints
.as_ref()
+1 -2
View File
@@ -16,7 +16,6 @@ use crate::thread_spawn::ThreadSpawnResult;
use crate::tools::context::ToolInvocation;
use codex_protocol::error::CodexErr;
use codex_protocol::error::Result as CodexResult;
use codex_protocol::protocol::MultiAgentVersion;
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::future::Future;
@@ -111,7 +110,7 @@ impl InvocationReservation {
turn: &TurnContext,
call_id: &str,
) -> Result<(), FunctionCallError> {
if turn.multi_agent_version != MultiAgentVersion::V2
if !turn.multi_agent_version.uses_v2_runtime()
|| session
.services
.thread_extension_data
+2 -1
View File
@@ -1291,7 +1291,8 @@ impl CodexThread {
self.selected_model_info().await.as_ref(),
&config,
),
} == MultiAgentVersion::V2
}
.uses_v2_runtime()
{
// Keep capacity eviction out between individual submissions. Each
// submission retains its own pin through dispatch after this batch returns.
+1 -1
View File
@@ -33,7 +33,7 @@ impl GuardianReviewContext {
pub(super) fn native_agent_history_enabled(&self) -> bool {
let turn = self.turn();
turn.config.guardian_native_multi_agent_history_enabled()
&& turn.multi_agent_version == codex_protocol::protocol::MultiAgentVersion::V2
&& turn.multi_agent_version.uses_v2_runtime()
}
}
@@ -12,7 +12,10 @@ use codex_protocol::protocol::TokenCountEvent;
impl Session {
/// Only MultiAgent V2 workers use a separate root history for review.
pub(crate) async fn guardian_root_history_version(&self) -> Option<(ThreadId, u64)> {
if self.multi_agent_version() != Some(MultiAgentVersion::V2) {
if !self
.multi_agent_version()
.is_some_and(MultiAgentVersion::uses_v2_runtime)
{
return None;
}
let version = self.state.lock().await.history.reset_version;
+2 -1
View File
@@ -80,7 +80,8 @@ impl Session {
&& self.session_id() == SessionId::from(self.thread_id())
&& self.has_outstanding_durable_sleep()
} else {
self.multi_agent_version() == Some(MultiAgentVersion::V2)
self.multi_agent_version()
.is_some_and(MultiAgentVersion::uses_v2_runtime)
};
if !eligible {
return Ok(());
+1 -1
View File
@@ -2903,7 +2903,7 @@ impl Session {
return;
}
let notify_native_parent = turn_context.multi_agent_version == MultiAgentVersion::V2
let notify_native_parent = turn_context.multi_agent_version.uses_v2_runtime()
&& matches!(
&turn_context.session_source,
SessionSource::SubAgent(SubAgentSource::ThreadSpawn {
+2 -3
View File
@@ -7,7 +7,6 @@ use codex_prompts::ResolvedModelMessages;
use codex_prompts::ResolvedMultiAgentMessages;
use codex_protocol::config_types::MultiAgentMode;
use codex_protocol::openai_models::ReasoningEffort;
use codex_protocol::protocol::MultiAgentVersion;
use codex_protocol::protocol::SessionSource;
use codex_protocol::protocol::SubAgentSource;
@@ -15,7 +14,7 @@ const HOSTED_MULTI_AGENT_SKILL_GUIDANCE: &str = "Before calling any multi-agent
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 {
if !turn_context.multi_agent_version.uses_v2_runtime() {
return None;
}
@@ -83,7 +82,7 @@ pub(crate) fn resolve_usage_hints(
pub(crate) fn effective_multi_agent_mode(step_context: &StepContext) -> Option<MultiAgentMode> {
let turn_context = step_context.turn.as_ref();
let settings = &step_context.settings;
if turn_context.multi_agent_version != MultiAgentVersion::V2 {
if !turn_context.multi_agent_version.uses_v2_runtime() {
return None;
}
@@ -6,7 +6,6 @@ use crate::state::ActiveTurn;
use codex_features::Feature;
use codex_protocol::error::CodexErr;
use codex_protocol::error::Result as CodexResult;
use codex_protocol::protocol::MultiAgentVersion;
use std::ops::ControlFlow;
use std::sync::Arc;
use tokio_util::sync::CancellationToken;
@@ -26,7 +25,7 @@ impl Drop for SamplingInterrupt {
impl SamplingInterrupt {
pub(crate) fn enabled(turn: &TurnContext) -> bool {
turn.config.multi_agent_v2.interrupt_at_item_boundary
&& turn.multi_agent_version == MultiAgentVersion::V2
&& turn.multi_agent_version.uses_v2_runtime()
&& turn.parent_thread_id.is_some()
}
+3 -1
View File
@@ -129,7 +129,9 @@ pub(super) async fn stop_tree_member(session: &Arc<Session>) -> bool {
if let Some(root) = runtime.suspension_root()
&& session.live_thread().is_some()
&& (root == session.thread_id
|| session.multi_agent_version() == Some(MultiAgentVersion::V2)
|| session
.multi_agent_version()
.is_some_and(MultiAgentVersion::uses_v2_runtime)
&& session
.state
.lock()
+1 -1
View File
@@ -87,7 +87,7 @@ impl Session {
turn_context: &TurnContext,
) -> Option<&Arc<dyn AgentSessionReader>> {
if turn_context.config.include_environment_context
&& turn_context.multi_agent_version == MultiAgentVersion::V2
&& turn_context.multi_agent_version.uses_v2_runtime()
&& let AgentRuntimeServices::Host(services) = &self.agent_runtime
{
services.session_reader.as_ref()
+2 -2
View File
@@ -109,7 +109,7 @@ impl InterruptedTurnHistoryMarker {
if !config.agent_interrupt_message_enabled {
return Self::Disabled;
}
if multi_agent_version == MultiAgentVersion::V2 {
if multi_agent_version.uses_v2_runtime() {
Self::Developer
} else {
Self::ContextualUser
@@ -383,7 +383,7 @@ impl Session {
.as_ref()
.filter(|reporting| {
reporting.reporter.is_some()
|| turn_context.multi_agent_version == MultiAgentVersion::V2
|| turn_context.multi_agent_version.uses_v2_runtime()
&& (!turn_context.session_source.is_non_root_agent()
|| turn_context.session_source.get_agent_path().is_some())
})
+3 -1
View File
@@ -2858,7 +2858,9 @@ impl ThreadManagerState {
};
// Both resume entry points must restore identities before children can be loaded lazily.
if let InitialHistory::Resumed(resumed) = &initial_history
&& initial_history.get_multi_agent_version() == Some(MultiAgentVersion::V2)
&& initial_history
.get_multi_agent_version()
.is_some_and(MultiAgentVersion::uses_v2_runtime)
&& !session_source.is_non_root_agent()
&& let AgentControlInit::Local(control) = &agent_control
{
+1 -2
View File
@@ -24,7 +24,6 @@ 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;
use codex_tool_call_id::ToolCallId;
@@ -188,7 +187,7 @@ pub(crate) async fn prepare(
agent_role: prepared.role_name,
});
let multi_agent_v2_usage_hints = if matches!(fork_mode, Some(SpawnAgentForkMode::FullHistory))
&& turn.multi_agent_version == MultiAgentVersion::V2
&& turn.multi_agent_version.uses_v2_runtime()
{
let child_model_info = match config.model.as_deref() {
Some(model) if model != turn.model_info().slug => Some(
+4 -2
View File
@@ -726,7 +726,7 @@ pub(crate) fn tool_suggest_enabled(turn_context: &TurnContext) -> bool {
}
fn multi_agent_v2_enabled(turn_context: &TurnContext) -> bool {
turn_context.multi_agent_version == MultiAgentVersion::V2
turn_context.multi_agent_version.uses_v2_runtime()
}
fn collab_tools_enabled(turn_context: &TurnContext, model_info: &ModelInfo) -> bool {
@@ -739,7 +739,9 @@ fn collab_tools_enabled(turn_context: &TurnContext, model_info: &ModelInfo) -> b
MultiAgentVersion::V2 => {
!turn_context.config.multi_agent_v2.disable_native_tools
&& (turn_context.session_source.get_agent_path().is_none()
|| model_info.multi_agent_version == Some(MultiAgentVersion::V2))
|| model_info
.multi_agent_version
.is_some_and(MultiAgentVersion::uses_v2_runtime))
}
}
}
+7
View File
@@ -3506,6 +3506,13 @@ pub enum MultiAgentVersion {
V2,
}
impl MultiAgentVersion {
/// Whether this version uses path-addressed workers with turn-scoped execution slots.
pub fn uses_v2_runtime(self) -> bool {
matches!(self, Self::V2)
}
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)]
pub struct SessionContextWindow {
/// Persisted model-facing window identity.