Skip to content

armgit / codex

Public Imported from GitHub
0

Lightweight coding agent that runs in your terminal

Rust

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

jif0b23f365f8dc
diff --git a/codex-rs/core/src/agent/agent_resolver.rs b/codex-rs/core/src/agent/agent_resolver.rs
index d02999b040..dea0ccf414 100644
--- a/codex-rs/core/src/agent/agent_resolver.rs
+++ b/codex-rs/core/src/agent/agent_resolver.rs
@@ -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);
-}
diff --git a/codex-rs/core/src/agent/api.rs b/codex-rs/core/src/agent/api.rs
index c920e5c161..25115088b2 100644
--- a/codex-rs/core/src/agent/api.rs
+++ b/codex-rs/core/src/agent/api.rs
@@ -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,
diff --git a/codex-rs/core/src/agent/control/api.rs b/codex-rs/core/src/agent/control/api.rs
index 650d5b4ffc..9bac5f779e 100644
--- a/codex-rs/core/src/agent/control/api.rs
+++ b/codex-rs/core/src/agent/control/api.rs
@@ -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(
diff --git a/codex-rs/core/src/agent/control/runtime_context.rs b/codex-rs/core/src/agent/control/runtime_context.rs
index c5824dd21c..2034d03fbd 100644
--- a/codex-rs/core/src/agent/control/runtime_context.rs
+++ b/codex-rs/core/src/agent/control/runtime_context.rs
@@ -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(
diff --git a/codex-rs/core/src/session/world_state.rs b/codex-rs/core/src/session/world_state.rs
index 083076fd46..323ddfbf28 100644
--- a/codex-rs/core/src/session/world_state.rs
+++ b/codex-rs/core/src/session/world_state.rs
@@ -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()
};
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 82c3e46545..98360657ed 100644
--- a/codex-rs/core/src/tools/handlers/multi_agents_tests.rs
+++ b/codex-rs/core/src/tools/handlers/multi_agents_tests.rs
@@ -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(),
diff --git a/codex-rs/core/src/tools/handlers/multi_agents_v2/list_agents.rs b/codex-rs/core/src/tools/handlers/multi_agents_v2/list_agents.rs
index 83ff63f45a..9e0eaa74c0 100644
--- a/codex-rs/core/src/tools/handlers/multi_agents_v2/list_agents.rs
+++ b/codex-rs/core/src/tools/handlers/multi_agents_v2/list_agents.rs
@@ -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)?;