Route agent lookups and V2 context through AgentControl (#47536)

## Why

V2 tools and model context need to use the controller's agent tree even when the session's local runtime has no registry entries.

## What changed

- Add target resolution and direct-child path lookup to `AgentControl`.
- Move lazy root registration into the controller's resolution and listing methods.
- Build V2 subagent context from controller-provided paths, keeping formatting and size limits in the session layer and preserving loaded-first ordering.

## Testing

Extend the V2 spawn and messaging test with an empty session-local registry to cover relative-path resolution, message delivery, and subagent environment context through the controller.

GitOrigin-RevId: c935b34a6d3314e968ba451ff981cf2a223bbfa8
This commit is contained in:
jif
2026-09-23 11:07:41 +00:00
committed by copyberry
parent a69d757cd8
commit 0b23f365f8
7 changed files with 162 additions and 96 deletions
+7 -14
View File
@@ -11,15 +11,15 @@ pub(crate) async fn resolve_agent_target(
turn: &Arc<TurnContext>,
target: &str,
) -> Result<ThreadId, FunctionCallError> {
register_session_root(session, turn);
if let Ok(thread_id) = ThreadId::from_string(target) {
return Ok(thread_id);
}
session
.services
.local_agent_runtime
.resolve_agent_reference(session.thread_id, &turn.session_source, target)
.agent_control
.resolve(
session.thread_id,
turn.parent_thread_id,
&turn.session_source,
target,
)
.await
.map_err(|err| match err.details() {
CodexErrorDetails::UnsupportedOperation(message) => {
@@ -28,10 +28,3 @@ pub(crate) async fn resolve_agent_target(
_ => FunctionCallError::RespondToModel(err.to_string()),
})
}
fn register_session_root(session: &Arc<Session>, turn: &Arc<TurnContext>) {
session
.services
.local_agent_runtime
.register_session_root(session.thread_id, turn.parent_thread_id);
}
+19 -1
View File
@@ -40,6 +40,17 @@ const _: Option<&dyn AgentControl> = None;
pub trait AgentControl: Send + Sync {
fn identity(&self) -> SessionId;
/// Resolve an ID or a name relative to the caller's captured source, without loading.
/// The local backend lazily registers callers with no parent before resolving, including
/// for direct IDs. Keeping resolution separate preserves tool error and analytics ordering.
fn resolve<'a>(
&'a self,
caller: ThreadId,
parent: Option<ThreadId>,
source: &'a SessionSource,
target: &'a str,
) -> BoxFuture<'a, Result<ThreadId>>;
/// Start a child and accept its initial input, returning its effective settings.
fn spawn(
&self,
@@ -61,13 +72,20 @@ pub trait AgentControl: Send + Sync {
) -> BoxFuture<'_, Result<AgentInfo>>;
/// List loaded agents using the caller's captured source to resolve a path prefix.
/// Callers own model and UI formatting.
/// The local backend lazily registers callers with no parent. Callers own formatting.
fn list<'a>(
&'a self,
caller: ThreadId,
parent: Option<ThreadId>,
source: &'a SessionSource,
path_prefix: Option<&'a str>,
) -> BoxFuture<'a, Result<Vec<LiveAgent>>>;
/// Known direct children for V2 model context, including unloaded agents. Loaded
/// children come first, alphabetically within each group; an unknown parent yields none.
/// This reads existing membership without registering the parent or loading children.
fn child_agent_paths(&self, parent: ThreadId) -> BoxFuture<'_, Vec<AgentPath>>;
/// Check capacity before accepting work. This advisory check does not reserve a slot.
fn check_turn_admission(
&self,
+63 -1
View File
@@ -30,12 +30,31 @@ use codex_protocol::protocol::SessionSource;
use codex_protocol::protocol::TokenUsage;
use codex_rollout_trace::ThreadTraceContext;
use futures::future::BoxFuture;
use std::collections::HashSet;
impl AgentControl for LocalAgentControl {
fn identity(&self) -> SessionId {
self.session_id()
}
fn resolve<'a>(
&'a self,
caller: ThreadId,
parent: Option<ThreadId>,
source: &'a SessionSource,
target: &'a str,
) -> BoxFuture<'a, Result<ThreadId>> {
Box::pin(async move {
self.runtime.register_session_root(caller, parent);
if let Ok(thread_id) = ThreadId::from_string(target) {
return Ok(thread_id);
}
self.runtime
.resolve_agent_reference(caller, source, target)
.await
})
}
fn spawn(
&self,
request: SpawnRequest,
@@ -167,10 +186,53 @@ impl AgentControl for LocalAgentControl {
fn list<'a>(
&'a self,
caller: ThreadId,
parent: Option<ThreadId>,
source: &'a SessionSource,
path_prefix: Option<&'a str>,
) -> BoxFuture<'a, Result<Vec<LiveAgent>>> {
Box::pin(self.list_agents(source, path_prefix))
Box::pin(async move {
self.runtime.register_session_root(caller, parent);
self.list_agents(source, path_prefix).await
})
}
fn child_agent_paths(&self, parent: ThreadId) -> BoxFuture<'_, Vec<AgentPath>> {
Box::pin(async move {
let Some(parent_path) = self
.runtime
.registry
.agent_metadata_for_thread(parent)
.and_then(|metadata| metadata.agent_path)
else {
return Vec::new();
};
let parent_prefix = format!("{parent_path}/");
let mut agent_paths = self
.runtime
.registry
.live_agents()
.into_iter()
.filter_map(|metadata| metadata.agent_path)
.filter(|path| {
path.as_str()
.strip_prefix(&parent_prefix)
.is_some_and(|name| !name.contains('/'))
})
.collect::<Vec<_>>();
let loaded_paths = self
.runtime
.open_thread_spawn_children(parent)
.await
.unwrap_or_default()
.into_iter()
.filter_map(|(_, metadata)| metadata.agent_path)
.collect::<HashSet<_>>();
agent_paths.sort();
// Stable sorting preserves alphabetical order within each group.
agent_paths.sort_by_key(|path| !loaded_paths.contains(path));
agent_paths
})
}
fn check_turn_admission(
@@ -1,4 +1,4 @@
//! Local registry lookups for startup, host context and loaded descendant checks.
//! Local registry lookups for startup, legacy context and loaded descendant checks.
//! These use the same local registry and thread manager as lifecycle operations.
use super::LocalAgentRuntime;
@@ -8,14 +8,9 @@ use crate::thread_manager::ThreadManagerState;
use codex_protocol::ThreadId;
use codex_protocol::error::CodexErr;
use codex_protocol::error::Result as CodexResult;
use codex_protocol::protocol::MultiAgentVersion;
use std::collections::HashMap;
use std::collections::HashSet;
use std::sync::Arc;
const MAX_ENVIRONMENT_SUBAGENTS: usize = 8;
const MAX_ENVIRONMENT_SUBAGENT_BYTES: usize = 1_024;
impl LocalAgentRuntime {
pub(crate) fn register_session_root(
&self,
@@ -42,73 +37,25 @@ impl LocalAgentRuntime {
Ok(thread_ids)
}
pub(crate) async fn format_environment_context_subagents(
pub(crate) async fn format_legacy_environment_context_subagents(
&self,
parent_thread_id: ThreadId,
multi_agent_version: MultiAgentVersion,
) -> String {
if multi_agent_version != MultiAgentVersion::V2 {
let Ok(agents) = self.open_thread_spawn_children(parent_thread_id).await else {
return String::new();
};
return agents
.into_iter()
.map(|(thread_id, metadata)| {
let reference = metadata
.agent_path
.as_ref()
.map(|path| path.name().to_string())
.unwrap_or_else(|| thread_id.to_string());
format_subagent_context_line(&reference, metadata.agent_nickname.as_deref())
})
.collect::<Vec<_>>()
.join("\n");
}
let Some(parent_path) = self
.registry
.agent_metadata_for_thread(parent_thread_id)
.and_then(|metadata| metadata.agent_path)
else {
let Ok(agents) = self.open_thread_spawn_children(parent_thread_id).await else {
return String::new();
};
let parent_prefix = format!("{parent_path}/");
let mut agent_paths = self
.registry
.live_agents()
agents
.into_iter()
.filter_map(|metadata| metadata.agent_path)
.filter(|path| {
path.as_str()
.strip_prefix(&parent_prefix)
.is_some_and(|name| !name.contains('/'))
.map(|(thread_id, metadata)| {
let reference = metadata
.agent_path
.as_ref()
.map(|path| path.name().to_string())
.unwrap_or_else(|| thread_id.to_string());
format_subagent_context_line(&reference, metadata.agent_nickname.as_deref())
})
.collect::<Vec<_>>();
let loaded_paths = self
.open_thread_spawn_children(parent_thread_id)
.await
.unwrap_or_default()
.into_iter()
.filter_map(|(_, metadata)| metadata.agent_path)
.collect::<HashSet<_>>();
agent_paths.sort();
// Stable sorting preserves alphabetical order within each group.
agent_paths.sort_by_key(|path| !loaded_paths.contains(path));
let mut lines = Vec::with_capacity(agent_paths.len().min(MAX_ENVIRONMENT_SUBAGENTS));
let mut rendered_bytes = " <subagents>\n </subagents>\n".len();
for agent_path in agent_paths {
if lines.len() == MAX_ENVIRONMENT_SUBAGENTS {
break;
}
let line = format!(r#"<agent name="{agent_path}" />"#);
let line_bytes = " \n".len() + line.len();
if rendered_bytes + line_bytes <= MAX_ENVIRONMENT_SUBAGENT_BYTES {
rendered_bytes += line_bytes;
lines.push(line);
}
}
lines.join("\n")
.collect::<Vec<_>>()
.join("\n")
}
pub(super) async fn open_thread_spawn_children(
+34 -7
View File
@@ -29,6 +29,10 @@ use codex_prompts::ResolvedModelMessages;
use codex_prompts::render_model_instructions;
use codex_protocol::error::Result as CodexResult;
use codex_protocol::models::BaseInstructionsProvenance;
use codex_protocol::protocol::MultiAgentVersion;
const MAX_ENVIRONMENT_SUBAGENTS: usize = 8;
const MAX_ENVIRONMENT_SUBAGENT_BYTES: usize = 1_024;
impl Session {
#[tracing::instrument(name = "world_state.build", level = "info", skip_all)]
@@ -75,13 +79,36 @@ impl Session {
})
};
let environment_subagents = if turn_context.config.include_environment_context {
self.services
.local_agent_runtime
.format_environment_context_subagents(
self.thread_id,
turn_context.multi_agent_version,
)
.await
match turn_context.multi_agent_version {
MultiAgentVersion::V2 => {
let agent_paths = self
.services
.agent_control
.child_agent_paths(self.thread_id)
.await;
let mut lines =
Vec::with_capacity(agent_paths.len().min(MAX_ENVIRONMENT_SUBAGENTS));
let mut rendered_bytes = " <subagents>\n </subagents>\n".len();
for agent_path in agent_paths {
if lines.len() == MAX_ENVIRONMENT_SUBAGENTS {
break;
}
let line = format!(r#"<agent name="{agent_path}" />"#);
let line_bytes = " \n".len() + line.len();
if rendered_bytes + line_bytes <= MAX_ENVIRONMENT_SUBAGENT_BYTES {
rendered_bytes += line_bytes;
lines.push(line);
}
}
lines.join("\n")
}
MultiAgentVersion::Disabled | MultiAgentVersion::V1 => {
self.services
.local_agent_runtime
.format_legacy_environment_context_subagents(self.thread_id)
.await
}
}
} else {
String::new()
};
@@ -1043,6 +1043,10 @@ async fn multi_agent_v2_spawn_returns_path_and_send_message_accepts_relative_pat
.expect("test config should allow feature update");
set_turn_config(&mut turn, config);
// V2 tools and model context must use the controller's tree, even when the
// caller's local runtime has no registry entries.
session.services.local_agent_runtime = crate::agent::LocalAgentControl::default().runtime;
let session = Arc::new(session);
let turn = Arc::new(turn);
let spawn_output = SpawnAgentHandlerV2::default()
@@ -1065,8 +1069,13 @@ async fn multi_agent_v2_spawn_returns_path_and_send_message_accepts_relative_pat
let child_thread_id = session
.services
.local_agent_runtime
.resolve_agent_reference(session.thread_id, &turn.session_source, "test_process")
.agent_control
.resolve(
session.thread_id,
turn.parent_thread_id,
&turn.session_source,
"test_process",
)
.await
.expect("relative path should resolve");
let child_snapshot = manager
@@ -1093,6 +1102,15 @@ async fn multi_agent_v2_spawn_returns_path_and_send_message_accepts_relative_pat
)
}));
let world_state = session
.build_world_state_for_step(&StepContext::for_test(Arc::clone(&turn)))
.await
.expect("world state should build");
assert_eq!(
world_state.snapshot().into_object()["environments"]["subagents"],
json!(r#"<agent name="/root/test_process" />"#),
);
SendMessageHandlerV2
.handle(invocation(
session.clone(),
@@ -40,14 +40,15 @@ impl Handler {
} = invocation;
let arguments = function_arguments(payload)?;
let args: ListAgentsArgs = parse_arguments(&arguments)?;
session
.services
.local_agent_runtime
.register_session_root(session.thread_id, turn.parent_thread_id);
let agents = session
.services
.agent_control
.list(&turn.session_source, args.path_prefix.as_deref())
.list(
session.thread_id,
turn.parent_thread_id,
&turn.session_source,
args.path_prefix.as_deref(),
)
.await
.map_err(collab_spawn_error)?;