Route session agent operations through AgentControl (#47520)

## What changed

- Store `Arc<dyn AgentControl>` in session services and route agent tools, turn admission, usage accounting, completion notifications, and shared settings through the trait.
- Add `AgentControlInit` so delegated and guardian sessions inherit the parent's controller and local runtime.
- Move local registry and context helpers to `LocalAgentRuntime`, keep resume, close, inspection, and status subscriptions on the local controller, and simplify synchronous and infallible trait methods.

GitOrigin-RevId: ad3f213eb483ac524bde56d769f20a78f20989a0
This commit is contained in:
jif
2026-09-23 09:39:30 +00:00
committed by copyberry
parent 40eac3ce8a
commit 27969c0ae9
53 changed files with 624 additions and 559 deletions
+2 -2
View File
@@ -18,7 +18,7 @@ pub(crate) async fn resolve_agent_target(
session
.services
.agent_control
.local_agent_runtime
.resolve_agent_reference(session.thread_id, &turn.session_source, target)
.await
.map_err(|err| match err.details() {
@@ -32,6 +32,6 @@ pub(crate) async fn resolve_agent_target(
fn register_session_root(session: &Arc<Session>, turn: &Arc<TurnContext>) {
session
.services
.agent_control
.local_agent_runtime
.register_session_root(session.thread_id, turn.parent_thread_id);
}
+8 -40
View File
@@ -26,11 +26,6 @@ use codex_protocol::turn_input::TurnStartOptions;
use codex_protocol::user_input::UserInput;
use codex_rollout_trace::ThreadTraceContext;
use futures::future::BoxFuture;
use futures::stream::BoxStream;
/// An initial runtime snapshot followed by coalesced status changes. The local stream
/// ends when that runtime's status channel closes; it does not follow a later reload.
pub type StatusSubscription = BoxStream<'static, Result<AgentInfo>>;
// Keep dynamic dispatch a compile-time property of the contract.
const _: Option<&dyn AgentControl> = None;
@@ -51,17 +46,6 @@ pub trait AgentControl: Send + Sync {
request: SpawnRequest,
) -> BoxFuture<'_, Result<(LiveAgent, ThreadConfigSnapshot)>>;
/// Reopen an absent runtime with the captured settings and session source. An already
/// loaded runtime keeps its current settings. Legacy ID-based resume can reopen a
/// stored thread that is not in the controller's registry.
fn resume(
&self,
caller: ThreadId,
target: AgentTarget,
config: Config,
source: SessionSource,
) -> BoxFuture<'_, Result<(LiveAgent, ThreadConfigSnapshot)>>;
/// Resolve, reload if needed and accept input. Agent messages retain their attribution
/// and wake mode: queue-only messages do not start work and follow-ups cannot target
/// the root. Legacy user input can address loaded threads outside the agent registry.
@@ -76,12 +60,6 @@ pub trait AgentControl: Send + Sync {
version: MultiAgentVersion,
) -> BoxFuture<'_, Result<AgentInfo>>;
/// Close the agent and its live descendants, returning its pre-close snapshot.
fn close(&self, caller: ThreadId, target: AgentTarget) -> BoxFuture<'_, Result<AgentInfo>>;
/// Read runtime settings or known unloaded metadata without loading an agent.
fn inspect(&self, caller: ThreadId, target: AgentTarget) -> BoxFuture<'_, Result<AgentInfo>>;
/// List loaded agents using the caller's captured source to resolve a path prefix.
/// Callers own model and UI formatting.
fn list<'a>(
@@ -90,13 +68,6 @@ pub trait AgentControl: Send + Sync {
path_prefix: Option<&'a str>,
) -> BoxFuture<'a, Result<Vec<LiveAgent>>>;
/// Subscribe to a loaded runtime without restoring it.
fn watch(
&self,
caller: ThreadId,
target: AgentTarget,
) -> BoxFuture<'_, Result<StatusSubscription>>;
/// Check capacity before accepting work. This advisory check does not reserve a slot.
fn check_turn_admission(
&self,
@@ -110,8 +81,8 @@ pub trait AgentControl: Send + Sync {
fn admit_turn(
&self,
version: MultiAgentVersion,
source: SessionSource,
) -> BoxFuture<'_, Result<Option<AgentExecutionGuard>>>;
source: &SessionSource,
) -> Option<AgentExecutionGuard>;
/// Account for one inference response, including compaction. Each call records usage;
/// callers report it once. `SessionBudgetExceeded` means the usage was recorded and
@@ -125,26 +96,23 @@ pub trait AgentControl: Send + Sync {
&'a self,
outcome: AgentTurnOutcome,
trace: &'a ThreadTraceContext,
) -> BoxFuture<'a, Result<()>>;
) -> BoxFuture<'a, ()>;
/// Read the latest shared service tier for use at normal runtime config update points.
fn service_tier(&self) -> Option<String>;
/// Publish a shared setting when the runtime accepts a root-owned config update.
fn propagate_config_update(&self, update: AgentConfigUpdate) -> BoxFuture<'_, Result<()>>;
/// Publish a shared setting synchronously with the runtime's root-owned config update.
fn propagate_config_update(&self, update: AgentConfigUpdate);
/// Read the existing bounded root evidence for a worker. The local backend returns
/// `None` for the root, a non-V2 tree, or an unavailable root runtime.
fn get_guardian_package(
&self,
agent: ThreadId,
) -> BoxFuture<'_, Result<Option<GuardianRootSnapshot>>>;
fn get_guardian_package(&self, agent: ThreadId) -> BoxFuture<'_, Option<GuardianRootSnapshot>>;
fn pending_budget_reminder<'a>(
&'a self,
agent: ThreadId,
window: &'a str,
) -> BoxFuture<'a, Result<Option<RolloutBudgetReminder>>>;
) -> BoxFuture<'a, Option<RolloutBudgetReminder>>;
/// Acknowledge only after inserting the reminder into the agent's history.
fn mark_budget_reminder_delivered<'a>(
@@ -152,7 +120,7 @@ pub trait AgentControl: Send + Sync {
agent: ThreadId,
window: &'a str,
reminder: RolloutBudgetReminder,
) -> BoxFuture<'a, Result<()>>;
) -> BoxFuture<'a, ()>;
}
/// References resolve relative to the registered caller. IDs retain each operation's
+2 -2
View File
@@ -164,7 +164,7 @@ fn reject_full_fork_agent_type_override(agent_type: Option<&str>) -> Result<(),
Ok(())
}
/// Copies runtime-only turn state onto a child config before it is handed to `LocalAgentControl`.
/// Copies runtime-only turn state onto a child config before it is handed to `AgentControl`.
///
/// These values are chosen by the live turn rather than persisted config, so leaving them stale can
/// make a child agent disagree with its parent about approval policy, cwd, or sandboxing.
@@ -256,7 +256,7 @@ pub(crate) async fn apply_spawn_agent_service_tier(
session: &Session,
config: &mut Config,
) -> Result<(), String> {
let Some(service_tier) = session.services.agent_control.root_service_tier() else {
let Some(service_tier) = session.services.agent_control.service_tier() else {
config.service_tier = None;
return Ok(());
};
+13 -219
View File
@@ -15,14 +15,12 @@ use crate::context::SubagentNotification;
use crate::environment_selection::TurnEnvironmentSnapshot;
use crate::session::emit_subagent_session_started;
use crate::session_prefix::format_inter_agent_completion_message;
use crate::session_prefix::format_subagent_context_line;
use crate::thread_manager::ResumeThreadWithHistoryOptions;
use crate::thread_manager::ThreadIdGenerator;
use crate::thread_manager::ThreadManagerState;
use crate::thread_manager::default_thread_id_generator;
use crate::thread_rollout_truncation::truncate_rollout_to_last_n_fork_turns;
use crate::turn_timing::now_unix_timestamp_ms;
use codex_extension_api::ThreadInstructionsProvider;
use codex_history::InitialHistory;
use codex_history::ResumedHistory;
use codex_history::RolloutItem;
@@ -53,15 +51,15 @@ use codex_protocol::user_input::UserInput;
use codex_thread_store::LoadThreadHistoryParams;
use codex_thread_store::ReadThreadParams;
use futures::StreamExt;
use std::collections::HashMap;
use std::collections::HashSet;
use std::collections::VecDeque;
use std::sync::Arc;
use std::sync::Weak;
use tracing::warn;
use uuid::Uuid;
pub(crate) use self::runtime::AgentControlInit;
pub(crate) use self::runtime::LocalAgentRuntime;
pub(crate) use self::watch::StatusSubscription;
mod api;
mod budget;
@@ -74,6 +72,7 @@ mod legacy;
mod residency;
mod resume;
mod runtime;
mod runtime_context;
mod sender_context;
mod service_tier;
mod spawn;
@@ -82,9 +81,6 @@ mod target;
mod user_authorization;
mod watch;
const MAX_ENVIRONMENT_SUBAGENTS: usize = 8;
const MAX_ENVIRONMENT_SUBAGENT_BYTES: usize = 1_024;
/// Per-session controller handle for a local agent tree.
/// Handles retain a session identity and share their tree's `LocalAgentRuntime`.
/// Local startup preserves that state when creating or resuming children.
@@ -128,31 +124,6 @@ impl LocalAgentControl {
self.session_id
}
pub(crate) fn generate_thread_id(&self) -> ThreadId {
(self.runtime.thread_id_generator)()
}
pub(crate) fn root_thread_instructions_provider(
&self,
root_thread_id: ThreadId,
provider: Option<Arc<dyn ThreadInstructionsProvider>>,
) -> Option<Arc<dyn ThreadInstructionsProvider>> {
let provider = match self.runtime.manager.upgrade() {
Some(manager) => manager.shared_thread_instructions_provider(root_thread_id, provider),
None => provider,
};
if let Some(provider) = provider
.as_ref()
.filter(|provider| provider.share_with_subagents())
{
let _ = self
.runtime
.shared_thread_instructions_provider
.set(Arc::clone(provider));
}
provider
}
/// Send rich user input items to an existing agent thread.
pub(crate) async fn send_input(
&self,
@@ -160,7 +131,7 @@ impl LocalAgentControl {
input: Vec<UserInput>,
start_options: TurnStartOptions,
) -> CodexResult<String> {
let state = self.upgrade()?;
let state = self.runtime.upgrade()?;
let thread = state.get_thread(agent_id).await?;
let result = match thread
.start_or_steer_turn(TurnInputRequest::user_input(input).on_start(start_options))
@@ -190,10 +161,11 @@ impl LocalAgentControl {
agent_communication_context: AgentCommunicationContext,
start_options: TurnStartOptions,
) -> CodexResult<String> {
let state = self.upgrade()?;
let state = self.runtime.upgrade()?;
if communication.trigger_turn {
let thread = state.get_thread(agent_id).await?;
self.ensure_execution_capacity_for_turn_start(&thread)
thread
.ensure_execution_capacity_for_turn_start(self)
.await?;
}
self.send_inter_agent_communication_after_capacity_check(
@@ -212,7 +184,7 @@ impl LocalAgentControl {
turn_id: String,
item: SubAgentActivityItem,
) -> CodexResult<()> {
let state = self.upgrade()?;
let state = self.runtime.upgrade()?;
let thread = state.get_thread(thread_id).await?;
let started_at_ms = now_unix_timestamp_ms();
let item = TurnItem::SubAgentActivity(item);
@@ -323,7 +295,7 @@ impl LocalAgentControl {
/// Interrupt the current task for an existing agent thread.
pub(crate) async fn interrupt_agent(&self, agent_id: ThreadId) -> CodexResult<String> {
let state = self.upgrade()?;
let state = self.runtime.upgrade()?;
self.handle_thread_request_result(
agent_id,
&state,
@@ -358,7 +330,7 @@ impl LocalAgentControl {
/// Fetch the last known status for `agent_id`, returning `NotFound` when unavailable.
pub(crate) async fn get_status(&self, agent_id: ThreadId) -> AgentStatus {
let Ok(state) = self.upgrade() else {
let Ok(state) = self.runtime.upgrade() else {
// No agent available if upgrade fails.
return AgentStatus::NotFound;
};
@@ -368,115 +340,16 @@ impl LocalAgentControl {
thread.agent_status().await
}
pub(crate) fn register_session_root(
&self,
current_thread_id: ThreadId,
current_parent_thread_id: Option<ThreadId>,
) {
if current_parent_thread_id.is_none() {
self.runtime
.registry
.register_root_thread(current_thread_id);
}
}
pub(crate) fn get_agent_metadata(&self, agent_id: ThreadId) -> Option<AgentMetadata> {
self.runtime.registry.agent_metadata_for_thread(agent_id)
}
pub(crate) fn ensure_agent_known(&self, agent_id: ThreadId) -> CodexResult<AgentMetadata> {
self.runtime
.registry
.agent_metadata_for_thread(agent_id)
.ok_or_else(|| CodexErr::ThreadNotFound(agent_id))
}
pub(crate) async fn list_live_agent_subtree_thread_ids(
&self,
agent_id: ThreadId,
) -> CodexResult<Vec<ThreadId>> {
let mut thread_ids = vec![agent_id];
thread_ids.extend(self.live_thread_spawn_descendants(agent_id).await?);
Ok(thread_ids)
}
pub(crate) async fn format_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
.runtime
.registry
.agent_metadata_for_thread(parent_thread_id)
.and_then(|metadata| metadata.agent_path)
else {
return String::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
.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")
}
pub(crate) async fn list_agents(
&self,
current_session_source: &SessionSource,
path_prefix: Option<&str>,
) -> CodexResult<Vec<LiveAgent>> {
let state = self.upgrade()?;
let state = self.runtime.upgrade()?;
let resolved_prefix = path_prefix
.map(|prefix| {
current_session_source
@@ -585,7 +458,7 @@ impl LocalAgentControl {
return;
}
let Ok(state) = control.upgrade() else {
let Ok(state) = control.runtime.upgrade() else {
return;
};
let child_thread = state.get_thread(child_thread_id).await.ok();
@@ -700,13 +573,6 @@ impl LocalAgentControl {
Ok((session_source, agent_metadata))
}
fn upgrade(&self) -> CodexResult<Arc<ThreadManagerState>> {
self.runtime
.manager
.upgrade()
.ok_or_else(|| CodexErr::UnsupportedOperation("thread manager dropped".to_string()))
}
async fn inherited_environments_for_source(
&self,
state: &Arc<ThreadManagerState>,
@@ -752,52 +618,6 @@ impl LocalAgentControl {
Some(Arc::clone(&parent_thread.session.services.exec_policy))
}
async fn open_thread_spawn_children(
&self,
parent_thread_id: ThreadId,
) -> CodexResult<Vec<(ThreadId, AgentMetadata)>> {
let mut children_by_parent = self.live_thread_spawn_children().await?;
Ok(children_by_parent
.remove(&parent_thread_id)
.unwrap_or_default())
}
async fn live_thread_spawn_children(
&self,
) -> CodexResult<HashMap<ThreadId, Vec<(ThreadId, AgentMetadata)>>> {
let state = self.upgrade()?;
let mut children_by_parent = HashMap::<ThreadId, Vec<(ThreadId, AgentMetadata)>>::new();
for (parent_thread_id, child_thread_id) in state.list_live_thread_spawn_edges().await {
children_by_parent
.entry(parent_thread_id)
.or_default()
.push((
child_thread_id,
self.runtime
.registry
.agent_metadata_for_thread(child_thread_id)
.unwrap_or(AgentMetadata {
agent_id: Some(child_thread_id),
..Default::default()
}),
));
}
for children in children_by_parent.values_mut() {
children.sort_by(|left, right| {
left.1
.agent_path
.as_deref()
.unwrap_or_default()
.cmp(right.1.agent_path.as_deref().unwrap_or_default())
.then_with(|| left.0.to_string().cmp(&right.0.to_string()))
});
}
Ok(children_by_parent)
}
async fn persist_thread_spawn_edge_for_source(
&self,
child_thread: &crate::CodexThread,
@@ -811,7 +631,7 @@ impl LocalAgentControl {
if child_thread.config_snapshot().await.ephemeral {
return;
}
let Ok(state) = self.upgrade() else {
let Ok(state) = self.runtime.upgrade() else {
return;
};
let Some(agent_graph_store) = state.agent_graph_store() else {
@@ -828,32 +648,6 @@ impl LocalAgentControl {
warn!("failed to persist thread-spawn edge: {err}");
}
}
async fn live_thread_spawn_descendants(
&self,
root_thread_id: ThreadId,
) -> CodexResult<Vec<ThreadId>> {
let mut children_by_parent = self.live_thread_spawn_children().await?;
let mut descendants = Vec::new();
let mut stack = children_by_parent
.remove(&root_thread_id)
.unwrap_or_default()
.into_iter()
.map(|(child_thread_id, _)| child_thread_id)
.rev()
.collect::<Vec<_>>();
while let Some(thread_id) = stack.pop() {
descendants.push(thread_id);
if let Some(children) = children_by_parent.remove(&thread_id) {
for (child_thread_id, _) in children.into_iter().rev() {
stack.push(child_thread_id);
}
}
}
Ok(descendants)
}
}
fn agent_matches_prefix(agent_path: Option<&AgentPath>, prefix: &AgentPath) -> bool {
+16 -69
View File
@@ -12,7 +12,6 @@ use crate::agent::api::AgentTurnOutcome;
use crate::agent::api::DeliveryReceipt;
use crate::agent::api::SendRequest;
use crate::agent::api::SpawnRequest;
use crate::agent::api::StatusSubscription;
use crate::agent::types::AgentExecutionGuard;
use crate::agent::types::LiveAgent;
use crate::agent::types::MessageDeliveryMode;
@@ -20,7 +19,6 @@ use crate::agent_communication::AgentCommunicationContext;
use crate::agent_communication::AgentCommunicationKind;
use crate::codex_thread::GuardianRootSnapshot;
use crate::codex_thread::ThreadConfigSnapshot;
use crate::config::Config;
use crate::rollout_budget::RolloutBudgetReminder;
use codex_protocol::AgentPath;
use codex_protocol::SessionId;
@@ -80,19 +78,6 @@ impl AgentControl for LocalAgentControl {
})
}
fn resume(
&self,
caller: ThreadId,
target: AgentTarget,
config: Config,
source: SessionSource,
) -> BoxFuture<'_, Result<(LiveAgent, ThreadConfigSnapshot)>> {
Box::pin(async move {
let target = self.resolve_target(caller, &target)?;
self.resume_agent(config, target, source).await
})
}
fn send(&self, request: SendRequest) -> BoxFuture<'_, Result<DeliveryReceipt>> {
Box::pin(async move {
let SendRequest {
@@ -114,8 +99,9 @@ impl AgentControl for LocalAgentControl {
(receiver.unwrap_or_default(), submission_id)
}
AgentInput::Message { message, mode } => {
let receiver = self.ensure_agent_known(target)?;
let receiver = self.runtime.ensure_agent_known(target)?;
let author = self
.runtime
.ensure_agent_known(caller)?
.agent_path
.unwrap_or_else(AgentPath::root);
@@ -179,20 +165,6 @@ impl AgentControl for LocalAgentControl {
})
}
fn close(&self, caller: ThreadId, target: AgentTarget) -> BoxFuture<'_, Result<AgentInfo>> {
Box::pin(async move {
let target = self.resolve_target(caller, &target)?;
self.close_agent(target).await
})
}
fn inspect(&self, caller: ThreadId, target: AgentTarget) -> BoxFuture<'_, Result<AgentInfo>> {
Box::pin(async move {
let target = self.resolve_target(caller, &target)?;
self.inspect_agent(target).await
})
}
fn list<'a>(
&'a self,
source: &'a SessionSource,
@@ -201,17 +173,6 @@ impl AgentControl for LocalAgentControl {
Box::pin(self.list_agents(source, path_prefix))
}
fn watch(
&self,
caller: ThreadId,
target: AgentTarget,
) -> BoxFuture<'_, Result<StatusSubscription>> {
Box::pin(async move {
let target = self.resolve_target(caller, &target)?;
self.subscribe_status(target).await
})
}
fn check_turn_admission(
&self,
version: MultiAgentVersion,
@@ -223,9 +184,9 @@ impl AgentControl for LocalAgentControl {
fn admit_turn(
&self,
version: MultiAgentVersion,
source: SessionSource,
) -> BoxFuture<'_, Result<Option<AgentExecutionGuard>>> {
Box::pin(async move { Ok(self.execution_guard(version, &source)) })
source: &SessionSource,
) -> Option<AgentExecutionGuard> {
self.execution_guard(version, source)
}
fn record_usage(&self, usage: TokenUsage) -> BoxFuture<'_, Result<()>> {
@@ -236,43 +197,30 @@ impl AgentControl for LocalAgentControl {
&'a self,
outcome: AgentTurnOutcome,
trace: &'a ThreadTraceContext,
) -> BoxFuture<'a, Result<()>> {
Box::pin(async move {
self.notify_parent_of_terminal_turn(outcome, trace).await;
Ok(())
})
) -> BoxFuture<'a, ()> {
Box::pin(self.notify_parent_of_terminal_turn(outcome, trace))
}
fn service_tier(&self) -> Option<String> {
self.root_service_tier()
}
fn propagate_config_update(&self, update: AgentConfigUpdate) -> BoxFuture<'_, Result<()>> {
Box::pin(async move {
match update {
AgentConfigUpdate::ServiceTier(tier) => self.set_root_service_tier(tier),
}
Ok(())
})
fn propagate_config_update(&self, update: AgentConfigUpdate) {
match update {
AgentConfigUpdate::ServiceTier(tier) => self.set_root_service_tier(tier),
}
}
fn get_guardian_package(
&self,
agent: ThreadId,
) -> BoxFuture<'_, Result<Option<GuardianRootSnapshot>>> {
Box::pin(async move { Ok(self.root_user_authorization(agent).await) })
fn get_guardian_package(&self, agent: ThreadId) -> BoxFuture<'_, Option<GuardianRootSnapshot>> {
Box::pin(self.root_user_authorization(agent))
}
fn pending_budget_reminder<'a>(
&'a self,
agent: ThreadId,
window: &'a str,
) -> BoxFuture<'a, Result<Option<RolloutBudgetReminder>>> {
Box::pin(async move {
Ok(LocalAgentControl::pending_budget_reminder(
self, agent, window,
))
})
) -> BoxFuture<'a, Option<RolloutBudgetReminder>> {
Box::pin(async move { LocalAgentControl::pending_budget_reminder(self, agent, window) })
}
fn mark_budget_reminder_delivered<'a>(
@@ -280,10 +228,9 @@ impl AgentControl for LocalAgentControl {
agent: ThreadId,
window: &'a str,
reminder: RolloutBudgetReminder,
) -> BoxFuture<'a, Result<()>> {
) -> BoxFuture<'a, ()> {
Box::pin(async move {
LocalAgentControl::mark_budget_reminder_delivered(self, agent, window, reminder);
Ok(())
})
}
}
@@ -50,7 +50,7 @@ impl LocalAgentControl {
{
let initiating_thread_id = match outcome.initiating_agent_path.as_ref() {
Some(initiating_agent_path) if initiating_agent_path != &parent_agent_path => {
self.resolve_agent_reference(
self.runtime.resolve_agent_reference(
outcome.thread_id,
&outcome.source,
initiating_agent_path.as_str(),
@@ -3,7 +3,6 @@
use super::LocalAgentControl;
use crate::agent::types::AgentExecutionGuard;
use crate::codex_thread::CodexThread;
use codex_protocol::error::CodexErr;
use codex_protocol::error::CodexErrorDetails;
use codex_protocol::error::Result as CodexResult;
@@ -31,20 +30,6 @@ impl Drop for LocalExecutionPermit {
}
impl LocalAgentControl {
pub(crate) async fn ensure_execution_capacity_for_turn_start(
&self,
thread: &CodexThread,
) -> CodexResult<()> {
if thread.session.active_turn.lock().await.is_some() {
return Ok(());
}
let config = thread.session.get_config().await;
let multi_agent_version = thread
.multi_agent_version()
.unwrap_or_else(|| config.multi_agent_version_from_features());
self.ensure_execution_capacity(multi_agent_version, &thread.session_source)
}
pub(crate) fn ensure_execution_capacity(
&self,
multi_agent_version: MultiAgentVersion,
@@ -10,11 +10,13 @@ use codex_protocol::error::Result as CodexResult;
impl LocalAgentControl {
pub(super) async fn inspect_agent(&self, thread_id: ThreadId) -> CodexResult<AgentInfo> {
let manager = self.upgrade()?;
let manager = self.runtime.upgrade()?;
let thread = match manager.get_thread(thread_id).await {
Ok(thread) => thread,
Err(err) if matches!(err.details(), CodexErrorDetails::ThreadNotFound(_)) => {
return Ok(AgentInfo::Unloaded(self.ensure_agent_known(thread_id)?));
return Ok(AgentInfo::Unloaded(
self.runtime.ensure_agent_known(thread_id)?,
));
}
Err(err) => return Err(err),
};
+1 -1
View File
@@ -18,7 +18,7 @@ impl LocalAgentControl {
caller: ThreadId,
target: ThreadId,
) -> CodexResult<AgentInfo> {
let receiver_agent = self.ensure_agent_known(target)?;
let receiver_agent = self.runtime.ensure_agent_known(target)?;
if receiver_agent
.agent_path
.as_ref()
+3 -3
View File
@@ -7,7 +7,7 @@ impl LocalAgentControl {
/// Submit a shutdown request for a live agent without marking it explicitly closed in
/// persisted spawn-edge state.
pub(crate) async fn shutdown_live_agent(&self, agent_id: ThreadId) -> CodexResult<String> {
let state = self.upgrade()?;
let state = self.runtime.upgrade()?;
let result = if let Ok(thread) = state.get_thread(agent_id).await {
thread
.session
@@ -47,7 +47,7 @@ impl LocalAgentControl {
/// Mark `agent_id` as explicitly closed in persisted spawn-edge state, then shut down the
/// agent and any live descendants reached from the in-memory tree.
pub(crate) async fn close_agent(&self, agent_id: ThreadId) -> CodexResult<AgentInfo> {
let state = self.upgrade()?;
let state = self.runtime.upgrade()?;
let metadata = self.get_agent_metadata(agent_id);
let known_agent = metadata.is_some();
let snapshot = match state.get_thread(agent_id).await {
@@ -106,7 +106,7 @@ impl LocalAgentControl {
/// Shut down `agent_id` and any live descendants reachable from the in-memory spawn tree.
pub(crate) async fn shutdown_agent_tree(&self, agent_id: ThreadId) -> CodexResult<String> {
let descendant_ids = self.live_thread_spawn_descendants(agent_id).await?;
let descendant_ids = self.runtime.live_thread_spawn_descendants(agent_id).await?;
let result = self.shutdown_live_agent(agent_id).await;
for descendant_id in descendant_ids {
match self.shutdown_live_agent(descendant_id).await {
@@ -38,7 +38,10 @@ async fn residency_slot_reservation_unloads_oldest_idle_v2_agent() {
.await
.expect("start root thread");
let control = manager.agent_control();
let state = control.upgrade().expect("thread manager should be live");
let state = control
.runtime
.upgrade()
.expect("thread manager should be live");
let first_slot = control
.reserve_v2_residency_slot(&state, &config, /*protected_thread_id*/ None)
@@ -86,7 +89,10 @@ async fn interrupted_v2_agent_is_lost_after_residency_eviction() {
.await
.expect("start root thread");
let control = manager.agent_control();
let state = control.upgrade().expect("thread manager should be live");
let state = control
.runtime
.upgrade()
.expect("thread manager should be live");
let first_slot = control
.reserve_v2_residency_slot(&state, &config, /*protected_thread_id*/ None)
+1 -1
View File
@@ -17,7 +17,7 @@ impl LocalAgentControl {
thread_id: ThreadId,
source: SessionSource,
) -> CodexResult<(LiveAgent, ThreadConfigSnapshot)> {
let manager = self.upgrade()?;
let manager = self.runtime.upgrade()?;
let thread = match manager.get_thread(thread_id).await {
Ok(thread) => thread,
Err(err) if matches!(err.details(), CodexErrorDetails::ThreadNotFound(_)) => {
@@ -4,6 +4,7 @@
use super::LocalAgentControl;
use super::execution::AgentExecutionLimiter;
use super::residency::V2Residency;
use crate::agent::api::AgentControl;
use crate::agent::registry::AgentRegistry;
use crate::config::RolloutBudgetConfig;
use crate::rollout_budget::RolloutBudget;
@@ -12,6 +13,7 @@ use crate::thread_manager::ThreadManagerState;
use arc_swap::ArcSwapOption;
use codex_extension_api::ThreadInstructionsProvider;
use codex_protocol::SessionId;
use codex_protocol::ThreadId;
use std::sync::Arc;
use std::sync::OnceLock;
use std::sync::Weak;
@@ -67,3 +69,62 @@ impl LocalAgentRuntime {
}
}
}
/// Local construction binds identity after reading history; internal children inherit
/// an already-bound controller without selecting a backend again.
#[derive(Clone)]
pub(crate) enum AgentControlInit {
Local(LocalAgentControl),
Inherited {
control: Arc<dyn AgentControl>,
runtime: LocalAgentRuntime,
},
}
impl From<LocalAgentControl> for AgentControlInit {
fn from(control: LocalAgentControl) -> Self {
Self::Local(control)
}
}
impl AgentControlInit {
pub(crate) fn runtime(&self) -> &LocalAgentRuntime {
match self {
Self::Local(control) => &control.runtime,
Self::Inherited { runtime, .. } => runtime,
}
}
pub(crate) fn control(&self) -> &dyn AgentControl {
match self {
Self::Local(control) => control,
Self::Inherited { control, .. } => control.as_ref(),
}
}
}
impl LocalAgentRuntime {
pub(crate) fn generate_thread_id(&self) -> ThreadId {
(self.thread_id_generator)()
}
pub(crate) fn root_thread_instructions_provider(
&self,
root_thread_id: ThreadId,
provider: Option<Arc<dyn ThreadInstructionsProvider>>,
) -> Option<Arc<dyn ThreadInstructionsProvider>> {
let provider = match self.manager.upgrade() {
Some(manager) => manager.shared_thread_instructions_provider(root_thread_id, provider),
None => provider,
};
if let Some(provider) = provider
.as_ref()
.filter(|provider| provider.share_with_subagents())
{
let _ = self
.shared_thread_instructions_provider
.set(Arc::clone(provider));
}
provider
}
}
@@ -0,0 +1,190 @@
//! Local registry lookups for startup, host context and loaded descendant checks.
//! These use the same local registry and thread manager as lifecycle operations.
use super::LocalAgentRuntime;
use crate::agent::types::AgentMetadata;
use crate::session_prefix::format_subagent_context_line;
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,
current_thread_id: ThreadId,
current_parent_thread_id: Option<ThreadId>,
) {
if current_parent_thread_id.is_none() {
self.registry.register_root_thread(current_thread_id);
}
}
pub(crate) fn ensure_agent_known(&self, agent_id: ThreadId) -> CodexResult<AgentMetadata> {
self.registry
.agent_metadata_for_thread(agent_id)
.ok_or_else(|| CodexErr::ThreadNotFound(agent_id))
}
pub(crate) async fn list_live_agent_subtree_thread_ids(
&self,
agent_id: ThreadId,
) -> CodexResult<Vec<ThreadId>> {
let mut thread_ids = vec![agent_id];
thread_ids.extend(self.live_thread_spawn_descendants(agent_id).await?);
Ok(thread_ids)
}
pub(crate) async fn format_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 {
return String::new();
};
let parent_prefix = format!("{parent_path}/");
let mut agent_paths = self
.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
.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")
}
pub(super) async fn open_thread_spawn_children(
&self,
parent_thread_id: ThreadId,
) -> CodexResult<Vec<(ThreadId, AgentMetadata)>> {
let mut children_by_parent = self.live_thread_spawn_children().await?;
Ok(children_by_parent
.remove(&parent_thread_id)
.unwrap_or_default())
}
pub(super) async fn live_thread_spawn_children(
&self,
) -> CodexResult<HashMap<ThreadId, Vec<(ThreadId, AgentMetadata)>>> {
let state = self.upgrade()?;
let mut children_by_parent = HashMap::<ThreadId, Vec<(ThreadId, AgentMetadata)>>::new();
for (parent_thread_id, child_thread_id) in state.list_live_thread_spawn_edges().await {
children_by_parent
.entry(parent_thread_id)
.or_default()
.push((
child_thread_id,
self.registry
.agent_metadata_for_thread(child_thread_id)
.unwrap_or(AgentMetadata {
agent_id: Some(child_thread_id),
..Default::default()
}),
));
}
for children in children_by_parent.values_mut() {
children.sort_by(|left, right| {
left.1
.agent_path
.as_deref()
.unwrap_or_default()
.cmp(right.1.agent_path.as_deref().unwrap_or_default())
.then_with(|| left.0.to_string().cmp(&right.0.to_string()))
});
}
Ok(children_by_parent)
}
pub(super) async fn live_thread_spawn_descendants(
&self,
root_thread_id: ThreadId,
) -> CodexResult<Vec<ThreadId>> {
let mut children_by_parent = self.live_thread_spawn_children().await?;
let mut descendants = Vec::new();
let mut stack = children_by_parent
.remove(&root_thread_id)
.unwrap_or_default()
.into_iter()
.map(|(child_thread_id, _)| child_thread_id)
.rev()
.collect::<Vec<_>>();
while let Some(thread_id) = stack.pop() {
descendants.push(thread_id);
if let Some(children) = children_by_parent.remove(&thread_id) {
for (child_thread_id, _) in children.into_iter().rev() {
stack.push(child_thread_id);
}
}
}
Ok(descendants)
}
pub(super) fn upgrade(&self) -> CodexResult<Arc<ThreadManagerState>> {
self.manager
.upgrade()
.ok_or_else(|| CodexErr::UnsupportedOperation("thread manager dropped".to_string()))
}
}
@@ -10,9 +10,9 @@ use codex_history::SenderUserMessages;
use codex_protocol::ThreadId;
use codex_protocol::models::ResponseItem;
use super::LocalAgentControl;
use super::LocalAgentRuntime;
impl LocalAgentControl {
impl LocalAgentRuntime {
pub(crate) async fn capture_sender_user_messages(
&self,
item: &ResponseItem,
+5 -5
View File
@@ -192,7 +192,7 @@ impl LocalAgentControl {
let registry = &self.runtime.registry;
registry.register_root_thread(root_thread_id);
let Ok(state) = self.upgrade() else {
let Ok(state) = self.runtime.upgrade() else {
return;
};
let Some(agent_graph_store) = state.agent_graph_store() else {
@@ -314,7 +314,7 @@ impl LocalAgentControl {
thread_id: ThreadId,
parent: Option<Arc<CodexThread>>,
) -> CodexResult<()> {
let state = self.upgrade()?;
let state = self.runtime.upgrade()?;
let owner_thread_id = parent.as_ref().map(|parent| parent.session.thread_id);
if let Some(parent) = &parent {
let parent_thread_id = parent.session.thread_id;
@@ -633,7 +633,7 @@ impl LocalAgentControl {
session_source: Option<SessionSource>,
options: SpawnAgentOptions,
) -> CodexResult<(LiveAgent, ThreadConfigSnapshot)> {
let state = self.upgrade()?;
let state = self.runtime.upgrade()?;
let multi_agent_version = state
.effective_multi_agent_version_for_spawn(
&InitialHistory::New,
@@ -1200,7 +1200,7 @@ impl LocalAgentControl {
self.resume_single_agent_from_rollout(config.clone(), thread_id, session_source),
)
.await?;
let state = self.upgrade()?;
let state = self.runtime.upgrade()?;
if config.multi_agent_version_from_features() == MultiAgentVersion::V2
|| resumed_multi_agent_version == MultiAgentVersion::V2
{
@@ -1270,7 +1270,7 @@ impl LocalAgentControl {
thread_id: ThreadId,
session_source: SessionSource,
) -> CodexResult<(ThreadId, MultiAgentVersion)> {
let state = self.upgrade()?;
let state = self.runtime.upgrade()?;
let stored_thread = state
.read_stored_thread(ReadThreadParams {
thread_id,
+7 -4
View File
@@ -2,6 +2,7 @@
//! Legacy callers can still supply their captured session source for path resolution.
use super::LocalAgentControl;
use super::LocalAgentRuntime;
use crate::agent::api::AgentTarget;
use codex_protocol::AgentPath;
use codex_protocol::ThreadId;
@@ -18,15 +19,17 @@ impl LocalAgentControl {
match target {
AgentTarget::Id(thread_id) => Ok(*thread_id),
AgentTarget::Reference(reference) => {
let caller = self.ensure_agent_known(caller)?;
self.resolve_path_reference(
let caller = self.runtime.ensure_agent_known(caller)?;
self.runtime.resolve_path_reference(
&caller.agent_path.unwrap_or_else(AgentPath::root),
reference,
)
}
}
}
}
impl LocalAgentRuntime {
pub(crate) async fn resolve_agent_reference(
&self,
_current_thread_id: ThreadId,
@@ -39,7 +42,7 @@ impl LocalAgentControl {
self.resolve_path_reference(&current_agent_path, agent_reference)
}
fn resolve_path_reference(
pub(super) fn resolve_path_reference(
&self,
current_agent_path: &AgentPath,
agent_reference: &str,
@@ -47,7 +50,7 @@ impl LocalAgentControl {
let agent_path = current_agent_path
.resolve(agent_reference)
.map_err(CodexErr::UnsupportedOperation)?;
if let Some(thread_id) = self.runtime.registry.agent_id_for_path(&agent_path) {
if let Some(thread_id) = self.registry.agent_id_for_path(&agent_path) {
return Ok(thread_id);
}
Err(CodexErr::UnsupportedOperation(format!(
@@ -45,7 +45,7 @@ impl LocalAgentControl {
if root_thread_id == thread_id {
return None;
}
let manager = self.upgrade().ok()?;
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) {
return None;
+6 -2
View File
@@ -3,20 +3,24 @@
use super::LocalAgentControl;
use crate::agent::api::AgentInfo;
use crate::agent::api::StatusSubscription;
use crate::agent::types::LiveAgent;
use codex_protocol::ThreadId;
use codex_protocol::error::Result as CodexResult;
use futures::StreamExt;
use futures::stream;
use futures::stream::BoxStream;
use std::sync::Arc;
/// An initial runtime snapshot followed by coalesced status changes. The stream ends
/// when that local runtime's status channel closes; it does not follow a later reload.
pub(crate) type StatusSubscription = BoxStream<'static, CodexResult<AgentInfo>>;
impl LocalAgentControl {
pub(crate) async fn subscribe_status(
&self,
agent_id: ThreadId,
) -> CodexResult<StatusSubscription> {
let manager = self.upgrade()?;
let manager = self.runtime.upgrade()?;
let thread = manager.get_thread(agent_id).await?;
// Subscribe before reading settings; mark the initial status seen only afterward.
let mut receiver = thread.subscribe_status();
+36 -9
View File
@@ -6,7 +6,6 @@ use crate::agent::agent_status_from_event;
use crate::agent::api::AgentControl;
use crate::agent::api::AgentInfo;
use crate::agent::api::AgentInput;
use crate::agent::api::AgentTarget;
use crate::agent::api::SpawnRequest;
use crate::agent::next_thread_spawn_depth;
use crate::agent::types::AgentMessage;
@@ -207,7 +206,9 @@ fn assistant_message(text: &str, phase: Option<MessagePhase>) -> ResponseItem {
fn register_session_root_skips_threads_with_explicit_parent() {
let control = LocalAgentControl::default();
control.register_session_root(ThreadId::new(), Some(ThreadId::new()));
control
.runtime
.register_session_root(ThreadId::new(), Some(ThreadId::new()));
assert_eq!(
control
@@ -518,6 +519,7 @@ async fn wait_for_live_thread_spawn_children(
timeout(Duration::from_secs(5), async {
loop {
let mut child_ids = control
.runtime
.open_thread_spawn_children(parent_thread_id)
.await
.expect("live child list should load")
@@ -914,7 +916,12 @@ async fn check_v2_agent_reload(route: V2ReloadRoute) {
})
.await
.expect("start root thread");
let control = root.thread.session.services.agent_control.clone();
let control = root
.thread
.session
.services
.local_agent_runtime
.control(root.thread.session.session_id());
let parent_thread = match route {
V2ReloadRoute::Sender => root.thread,
V2ReloadRoute::NestedParent => {
@@ -978,7 +985,7 @@ async fn check_v2_agent_reload(route: V2ReloadRoute) {
);
assert_matches!(
control
.inspect(parent_thread_id, AgentTarget::Id(spawned_agent.thread_id))
.inspect_agent(spawned_agent.thread_id)
.await
.expect("inspect registered unloaded agent"),
AgentInfo::Unloaded(_)
@@ -1233,7 +1240,12 @@ async fn resume_agent_from_rollout_does_not_reopen_v2_descendants() {
.restore_v2_agent_metadata(&harness.config, parent_thread_id)
.await;
for thread_id in [worker_thread_id, sibling_thread_id] {
assert!(resumed_control.ensure_agent_known(thread_id).is_ok());
assert!(
resumed_control
.runtime
.ensure_agent_known(thread_id)
.is_ok()
);
}
resumed_control
@@ -1241,8 +1253,10 @@ async fn resume_agent_from_rollout_does_not_reopen_v2_descendants() {
.await
.expect("closing a restored sibling should succeed");
let closed_worker = resumed_control.ensure_agent_known(worker_thread_id);
let surviving_sibling = resumed_control.ensure_agent_known(sibling_thread_id);
let closed_worker = resumed_control.runtime.ensure_agent_known(worker_thread_id);
let surviving_sibling = resumed_control
.runtime
.ensure_agent_known(sibling_thread_id);
assert!(closed_worker.is_err());
assert!(surviving_sibling.is_ok());
assert_thread_not_loaded(&resumed_manager, sibling_thread_id).await;
@@ -1301,7 +1315,12 @@ async fn cold_resume_with_thread_instructions_preserves_lazy_v2_child_inheritanc
.await
.expect("start parent with thread instructions");
let parent_thread_id = parent.thread_id;
let control = &parent.thread.session.services.agent_control;
let control = &parent
.thread
.session
.services
.local_agent_runtime
.control(parent.thread.session.session_id());
let worker_thread_id =
spawn_v2_reload_test_child(control, harness.config.clone(), &parent.thread, "worker")
.await
@@ -1476,7 +1495,12 @@ async fn v2_sibling_reload_preserves_shared_instructions_after_root_unloads(shar
.inherited_instructions()
.await
.thread_provider;
let control = &root.thread.session.services.agent_control;
let control = &root
.thread
.session
.services
.local_agent_runtime
.control(root.thread.session.session_id());
let sender_id =
spawn_v2_reload_test_child(control, harness.config.clone(), &root.thread, "sender")
.await
@@ -1588,12 +1612,14 @@ async fn resumed_root_reuses_or_freezes_surviving_shared_instructions() {
let shared = harness
.manager
.agent_control()
.runtime
.root_thread_instructions_provider(id, Some(original.clone()))
.expect("shared provider");
let snapshot = shared.load_thread_instructions().await;
let reused = harness
.manager
.agent_control()
.runtime
.root_thread_instructions_provider(id, /*provider*/ None)
.expect("reuse the live tree's provider");
assert!(Arc::ptr_eq(&shared, &reused));
@@ -1605,6 +1631,7 @@ async fn resumed_root_reuses_or_freezes_surviving_shared_instructions() {
let root_only = harness
.manager
.agent_control()
.runtime
.root_thread_instructions_provider(id, Some(private.clone()))
.expect("private root provider");
*original.text.write().expect("update old provider") = "stale shared update";
+4 -4
View File
@@ -84,7 +84,7 @@ impl LocalBoardHost {
actor
.session
.services
.agent_control
.local_agent_runtime
.register_session_root(self.caller, /*current_parent_thread_id*/ None);
}
Ok(actor)
@@ -98,7 +98,7 @@ impl MessageBoardHost for LocalBoardHost {
.await?
.session
.services
.agent_control
.local_agent_runtime
.ensure_agent_known(caller)?
.agent_path
.ok_or_else(|| CodexErr::InvalidRequest("agent has no tree path".into()))
@@ -111,7 +111,7 @@ impl MessageBoardHost for LocalBoardHost {
actor
.session
.services
.agent_control
.local_agent_runtime
.resolve_agent_reference(self.caller, &actor.session_source, path.as_str())
.await
})
@@ -164,7 +164,7 @@ impl MessageBoardHost for LocalBoardHost {
let recipient_path = recipient
.session
.services
.agent_control
.local_agent_runtime
.ensure_agent_known(recipient_id)?
.agent_path
.ok_or_else(|| CodexErr::InvalidRequest("agent has no tree path".into()))?;
+4 -4
View File
@@ -114,10 +114,10 @@ pub(crate) async fn run_codex_thread_interactive(
ThreadSource::Subagent
}),
originator: parent_ctx.originator.clone(),
agent_control: parent_session
.services
.local_agent_runtime
.control(parent_session.session_id()),
agent_control: crate::agent::control::AgentControlInit::Inherited {
control: Arc::clone(&parent_session.services.agent_control),
runtime: parent_session.services.local_agent_runtime.clone(),
},
dynamic_tools: Vec::new(),
metrics_service_name: None,
user_shell_override: None,
+21 -10
View File
@@ -1,4 +1,5 @@
use crate::agent::AgentStatus;
use crate::agent::api::AgentControl;
use crate::config::ConstraintResult;
use crate::context::ContextualUserFragment;
use crate::context::GuardianReviewEvidence;
@@ -397,10 +398,7 @@ impl CodexThread {
&self,
request: RecoverTurnRequest,
) -> CodexResult<StartIfIdleSubmission> {
self.session
.services
.agent_control
.ensure_execution_capacity_for_turn_start(self)
self.ensure_execution_capacity_for_turn_start(self.session.services.agent_control.as_ref())
.await?;
let RecoverTurnRequest {
turn_id,
@@ -504,11 +502,10 @@ impl CodexThread {
mode: TurnInputMode,
) -> CodexResult<TurnInputSubmission> {
if !matches!(mode, TurnInputMode::Steer { .. }) {
self.session
.services
.agent_control
.ensure_execution_capacity_for_turn_start(self)
.await?;
self.ensure_execution_capacity_for_turn_start(
self.session.services.agent_control.as_ref(),
)
.await?;
}
self.io.submit_turn_input(request, mode).await
}
@@ -910,7 +907,7 @@ impl CodexThread {
self.session
.services
.agent_control
.root_user_authorization(self.session.thread_id)
.get_guardian_package(self.session.thread_id)
.await
}
@@ -1062,4 +1059,18 @@ impl CodexThread {
}
Ok(elicitations.count)
}
pub(crate) async fn ensure_execution_capacity_for_turn_start(
&self,
control: &dyn AgentControl,
) -> CodexResult<()> {
if self.session.active_turn.lock().await.is_some() {
return Ok(());
}
let config = self.session.get_config().await;
let multi_agent_version = self
.multi_agent_version()
.unwrap_or_else(|| config.multi_agent_version_from_features());
control.check_turn_admission(multi_agent_version, &self.session_source)
}
}
+1 -1
View File
@@ -302,7 +302,7 @@ async fn run_remote_compact_task_inner_impl(
owned_client_session: _owned_client_session,
} = attempt;
if let Some(token_usage) = token_usage {
sess.record_rollout_budget_usage(&token_usage)?;
sess.record_rollout_budget_usage(&token_usage).await?;
analytics_details.active_context_tokens_before = Some(token_usage.input_tokens);
analytics_details.compaction_summary_tokens = Some(token_usage.output_tokens);
analytics_details.cached_input_tokens = Some(token_usage.cached_input_tokens);
@@ -125,6 +125,7 @@ pub(crate) async fn finalize(
.services
.agent_control
.pending_budget_reminder(session.thread_id(), &session.current_window_id().await)
.await
{
let reminder = ContextualUserFragment::into(crate::context::RolloutBudgetContext {
remaining_tokens: reminder.remaining_tokens,
+1 -1
View File
@@ -99,7 +99,7 @@ pub(crate) async fn build_guardian_prompt_items_with_parent_turn(
let root_authorization = session
.services
.agent_control
.root_user_authorization(session.thread_id)
.get_guardian_package(session.thread_id)
.await
.map(|snapshot| snapshot.messages);
let trusted_user_inputs = session
+2 -2
View File
@@ -108,7 +108,7 @@ impl ReviewHost for super::super::runtime::ReviewRuntime {
let root_authorization_version = session
.services
.agent_control
.root_user_authorization(session.thread_id)
.get_guardian_package(session.thread_id)
.await
.map(|snapshot| snapshot.authorization_version);
// Keep the authorization revision even when no cacheable review evidence exists.
@@ -168,7 +168,7 @@ impl ReviewHost for super::super::runtime::ReviewRuntime {
!= session
.services
.agent_control
.root_user_authorization(session.thread_id)
.get_guardian_package(session.thread_id)
.await
.map(|snapshot| snapshot.authorization_version)
|| user_message_revision
@@ -40,7 +40,7 @@ impl ReviewContextPolicy {
session
.services
.agent_control
.root_user_authorization(session.thread_id)
.get_guardian_package(session.thread_id)
.await
.map(|snapshot| snapshot.authorization_version)
}
@@ -102,11 +102,10 @@ impl PreparedGuardianContext {
internal_parent: Some(crate::thread_manager::InternalSessionParent {
thread_id: self.parent.thread_id(),
auth_manager: Arc::clone(&self.parent.services.auth_manager),
agent_control: self
.parent
.services
.local_agent_runtime
.control(self.parent.session_id()),
agent_control: crate::agent::control::AgentControlInit::Inherited {
control: Arc::clone(&self.parent.services.agent_control),
runtime: self.parent.services.local_agent_runtime.clone(),
},
originator: self.context.turn().originator.clone(),
// Review the same applied instructions captured by the reuse key.
// A live provider could advance independently while reviewing this action.
-1
View File
@@ -62,7 +62,6 @@ pub use agent::api::AgentTurnOutcome;
pub use agent::api::DeliveryReceipt;
pub use agent::api::SendRequest;
pub use agent::api::SpawnRequest;
pub use agent::api::StatusSubscription;
pub use agent::types::AgentExecutionGuard;
pub use agent::types::AgentMessage;
pub use agent::types::AgentMetadata;
+14 -11
View File
@@ -11,9 +11,10 @@ use std::time::SystemTime;
use std::time::UNIX_EPOCH;
use crate::agent::AgentStatus;
use crate::agent::LocalAgentControl;
use crate::agent::agent_status_from_event;
use crate::agent::api::AgentConfigUpdate;
use crate::agent::api::AgentTurnOutcome;
use crate::agent::control::AgentControlInit;
use crate::agent::status::is_final;
use crate::agents_md_manager::SessionInstructions;
use crate::attestation::AttestationProvider;
@@ -450,7 +451,7 @@ pub(crate) struct SessionSpawnArgs {
pub(crate) parent_thread_id: Option<ThreadId>,
pub(crate) thread_source: Option<ThreadSource>,
pub(crate) originator: String,
pub(crate) agent_control: LocalAgentControl,
pub(crate) agent_control: AgentControlInit,
pub(crate) dynamic_tools: Vec<DynamicToolSpec>,
pub(crate) metrics_service_name: Option<String>,
pub(crate) inherited_exec_policy: Option<Arc<ExecPolicyManager>>,
@@ -1909,12 +1910,14 @@ impl Session {
// Save new environment defaults for future turns. The running turn keeps its own.
state.session_configuration = updated;
if root_service_tier_changed {
self.services.agent_control.set_root_service_tier(
state
.session_configuration
.step_settings
.service_tier
.clone(),
self.services.agent_control.propagate_config_update(
AgentConfigUpdate::ServiceTier(
state
.session_configuration
.step_settings
.service_tier
.clone(),
),
);
}
let new_config = notify_config_contributors
@@ -2433,7 +2436,7 @@ impl Session {
self.services
.agent_control
.notify_parent_of_terminal_turn(
.turn_finished(
AgentTurnOutcome {
thread_id: self.thread_id,
turn_id: turn_context.sub_id.clone(),
@@ -3799,7 +3802,7 @@ impl Session {
turn_context.session_source,
SessionSource::SubAgent(SubAgentSource::ThreadSpawn { .. })
) {
let root_service_tier = self.services.agent_control.root_service_tier();
let root_service_tier = self.services.agent_control.service_tier();
if settings.selected().service_tier != root_service_tier {
let mut selected = settings.selected().clone();
selected.service_tier = root_service_tier;
@@ -4756,7 +4759,7 @@ impl Session {
token_usage,
);
}
let budget_result = self.record_rollout_budget_usage(token_usage);
let budget_result = self.record_rollout_budget_usage(token_usage).await;
if let Some(token_info) = token_info.as_ref() {
for contributor in self.services.extensions.token_usage_contributors() {
contributor
+10 -4
View File
@@ -10,7 +10,10 @@ pub(super) async fn maybe_record_reminder(
window_id: &str,
) {
let agent_control = &sess.services.agent_control;
let Some(reminder) = agent_control.pending_budget_reminder(sess.thread_id(), window_id) else {
let Some(reminder) = agent_control
.pending_budget_reminder(sess.thread_id(), window_id)
.await
else {
return;
};
let response_item = ContextualUserFragment::into(crate::context::RolloutBudgetContext {
@@ -22,13 +25,16 @@ pub(super) async fn maybe_record_reminder(
std::slice::from_ref(&response_item),
)
.await;
agent_control.mark_budget_reminder_delivered(sess.thread_id(), window_id, reminder);
agent_control
.mark_budget_reminder_delivered(sess.thread_id(), window_id, reminder)
.await;
}
impl Session {
pub(crate) fn record_rollout_budget_usage(&self, usage: &TokenUsage) -> CodexResult<()> {
pub(crate) async fn record_rollout_budget_usage(&self, usage: &TokenUsage) -> CodexResult<()> {
self.services
.agent_control
.record_rollout_budget_usage(usage)
.record_usage(usage.clone())
.await
}
}
+29 -18
View File
@@ -6,6 +6,7 @@ use super::step_settings::StepSettings;
use super::step_settings::StepSettingsConstraints;
use super::step_settings::StepSettingsUpdate;
use super::*;
use crate::agent::api::AgentControl;
use crate::agents_md_manager::AgentsMdManager;
use crate::agents_md_manager::SessionInstructions;
use crate::config::ConstraintError;
@@ -647,7 +648,7 @@ impl Session {
/// Returns the identity shared by the root thread and all descendant threads.
pub(crate) fn session_id(&self) -> SessionId {
self.services.agent_control.session_id()
self.services.agent_control.identity()
}
pub(crate) async fn originator(&self) -> String {
@@ -759,7 +760,7 @@ impl Session {
extensions: Arc<codex_extension_api::ExtensionRegistry<crate::config::Config>>,
mut thread_extension_init: ExtensionDataInit,
client_mcp_extensions: ClientMcpExtensions,
agent_control: LocalAgentControl,
agent_control: AgentControlInit,
reserved_thread_id: Option<ThreadId>,
environment_manager: Arc<EnvironmentManager>,
inherited_environments: Option<TurnEnvironmentSnapshot>,
@@ -836,13 +837,15 @@ impl Session {
.or_else(|| initial_history.get_resumed_parent_thread_id());
session_configuration.parent_thread_id = parent_thread_id;
if parent_thread_id.is_none() {
agent_control.set_root_service_tier(
session_configuration
.step_settings
.service_tier
.clone()
.or_else(|| config.service_tier.clone()),
);
agent_control
.control()
.propagate_config_update(AgentConfigUpdate::ServiceTier(
session_configuration
.step_settings
.service_tier
.clone()
.or_else(|| config.service_tier.clone()),
));
}
let is_paginated_subagent = matches!(
session_configuration.history_mode,
@@ -863,7 +866,7 @@ impl Session {
Some(thread_id),
) => thread_id,
(InitialHistory::New | InitialHistory::Cleared | InitialHistory::Forked(_), None) => {
agent_control.generate_thread_id()
agent_control.runtime().generate_thread_id()
}
(InitialHistory::Resumed(resumed_history), None) => resumed_history.conversation_id,
(InitialHistory::Resumed(_), Some(_)) => {
@@ -880,6 +883,7 @@ impl Session {
&& isolation != codex_extension_api::SessionIsolation::Isolated
{
instructions.thread_provider = agent_control
.runtime()
.root_thread_instructions_provider(thread_id, instructions.thread_provider);
}
// Ephemeral forks reuse cache routing, without sharing storage or lifecycle identity.
@@ -915,7 +919,7 @@ impl Session {
// session_id is equal to the root thread's ID.
let session_id = resumed_session_id.unwrap_or_else(|| {
if session_configuration.session_source.is_non_root_agent() {
agent_control.session_id()
agent_control.control().identity()
} else {
SessionId::from(thread_id)
}
@@ -935,12 +939,19 @@ impl Session {
}
}
}
let agent_control = agent_control.with_session_id(
session_id,
config
.effective_agent_max_threads(MultiAgentVersion::V2)
.unwrap_or(usize::MAX),
);
let (agent_control, local_agent_runtime): (Arc<dyn AgentControl>, _) = match agent_control {
AgentControlInit::Local(control) => {
let control = control.with_session_id(
session_id,
config
.effective_agent_max_threads(MultiAgentVersion::V2)
.unwrap_or(usize::MAX),
);
let runtime = control.runtime.clone();
(Arc::new(control), runtime)
}
AgentControlInit::Inherited { control, runtime } => (control, runtime),
};
let time_provider = crate::current_time::resolve_time_provider(
config.current_time_reminder.as_ref(),
external_time_provider,
@@ -1685,7 +1696,7 @@ impl Session {
selected_capability_roots,
mcp_thread_init,
client_mcp_extensions,
local_agent_runtime: agent_control.runtime.clone(),
local_agent_runtime,
agent_control,
network_proxy: arc_swap::ArcSwapOption::from(network_proxy.map(Arc::new)),
network_proxy_audit_metadata,
+6 -5
View File
@@ -1,3 +1,4 @@
use crate::agent::LocalAgentControl;
#[path = "notification_tests.rs"]
mod notification_tests;
@@ -6199,7 +6200,7 @@ async fn session_new_fails_when_zsh_fork_enabled_without_packaged_zsh() {
Arc::new(codex_extension_api::ExtensionRegistryBuilder::new().build()),
codex_extension_api::ExtensionDataInit::default(),
ClientMcpExtensions::default(),
LocalAgentControl::default(),
LocalAgentControl::default().into(),
/*reserved_thread_id*/ None,
environment_manager,
/*inherited_environments*/ None,
@@ -6488,7 +6489,7 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) {
mcp_thread_init: codex_extension_api::ExtensionDataInit::default(),
client_mcp_extensions: ClientMcpExtensions::default(),
local_agent_runtime: agent_control.runtime.clone(),
agent_control,
agent_control: Arc::new(agent_control),
network_proxy: arc_swap::ArcSwapOption::from(None),
network_proxy_audit_metadata: crate::config::NetworkProxyAuditMetadata::default(),
managed_network_requirements_configured: false,
@@ -6748,7 +6749,7 @@ async fn make_session_with_config_and_rx(
Arc::new(codex_extension_api::ExtensionRegistryBuilder::new().build()),
codex_extension_api::ExtensionDataInit::default(),
ClientMcpExtensions::default(),
LocalAgentControl::default(),
LocalAgentControl::default().into(),
/*reserved_thread_id*/ None,
environment_manager,
/*inherited_environments*/ None,
@@ -6880,7 +6881,7 @@ async fn make_session_with_history_source_and_agent_control_and_rx(
Arc::new(codex_extension_api::ExtensionRegistryBuilder::new().build()),
codex_extension_api::ExtensionDataInit::default(),
ClientMcpExtensions::default(),
agent_control,
agent_control.into(),
/*reserved_thread_id*/ None,
environment_manager,
/*inherited_environments*/ None,
@@ -8758,7 +8759,7 @@ where
mcp_thread_init: codex_extension_api::ExtensionDataInit::default(),
client_mcp_extensions: ClientMcpExtensions::default(),
local_agent_runtime: agent_control.runtime.clone(),
agent_control,
agent_control: Arc::new(agent_control),
network_proxy: arc_swap::ArcSwapOption::from(None),
network_proxy_audit_metadata: crate::config::NetworkProxyAuditMetadata::default(),
managed_network_requirements_configured: false,
@@ -1325,7 +1325,7 @@ async fn guardian_subagent_does_not_inherit_parent_exec_policy_rules() {
parent_thread_id: None,
thread_source: None,
originator: "test_originator".to_string(),
agent_control: LocalAgentControl::default(),
agent_control: LocalAgentControl::default().into(),
dynamic_tools: Vec::new(),
metrics_service_name: None,
inherited_environments: None,
+1 -1
View File
@@ -743,7 +743,7 @@ async fn pending_turn_input(
let metadata = if session.guardian_context_mode == GuardianContextMode::ThreadOwned
&& let Some(messages) = session
.services
.agent_control
.local_agent_runtime
.capture_sender_user_messages(&item, session.thread_id, turn_id)
.await
{
+1 -1
View File
@@ -28,7 +28,7 @@ pub(super) async fn suspend_turn_and_shutdown(
// Previously closed descendants and concurrent future spawns remain best effort.
if session
.services
.agent_control
.local_agent_runtime
.list_live_agent_subtree_thread_ids(session.thread_id)
.await?
.len()
+1 -1
View File
@@ -76,7 +76,7 @@ impl Session {
};
let environment_subagents = if turn_context.config.include_environment_context {
self.services
.agent_control
.local_agent_runtime
.format_environment_context_subagents(
self.thread_id,
turn_context.multi_agent_version,
+2 -2
View File
@@ -1,7 +1,7 @@
use std::path::PathBuf;
use std::sync::Arc;
use crate::agent::LocalAgentControl;
use crate::agent::api::AgentControl;
use crate::agent::control::LocalAgentRuntime;
use crate::agents_md_manager::AgentsMdManager;
use crate::attestation::AttestationProvider;
@@ -83,7 +83,7 @@ pub(crate) struct SessionServices {
/// current executor environments before using them.
pub(crate) selected_capability_roots: Vec<SelectedCapabilityRoot>,
pub(crate) mcp_thread_init: ExtensionDataInit,
pub(crate) agent_control: LocalAgentControl,
pub(crate) agent_control: Arc<dyn AgentControl>,
pub(crate) local_agent_runtime: LocalAgentRuntime,
pub(crate) network_proxy: ArcSwapOption<StartedNetworkProxy>,
pub(crate) network_proxy_audit_metadata: NetworkProxyAuditMetadata,
+1 -1
View File
@@ -332,7 +332,7 @@ impl Session {
let mut active = self.active_turn.lock().await;
let turn = active.get_or_insert_with(ActiveTurn::default);
debug_assert!(turn.task.is_none());
let agent_execution_guard = self.services.agent_control.execution_guard(
let agent_execution_guard = self.services.agent_control.admit_turn(
turn_context.multi_agent_version,
&turn_context.session_source,
);
+12 -10
View File
@@ -3,6 +3,7 @@ mod shared_instructions;
use crate::CodexAppsToolsCache;
use crate::agent::LocalAgentControl;
use crate::agent::control::AgentControlInit;
use crate::agents_md_manager::SessionInstructions;
use crate::attestation::AttestationProvider;
use crate::codex_thread::CodexThread;
@@ -240,7 +241,7 @@ pub struct ThreadManager {
pub struct InternalSessionParent {
pub(crate) thread_id: ThreadId,
pub(crate) auth_manager: Arc<AuthManager>,
pub(crate) agent_control: LocalAgentControl,
pub(crate) agent_control: AgentControlInit,
pub(crate) originator: String,
pub(crate) inherited_instructions: Option<SessionInstructions>,
}
@@ -312,7 +313,7 @@ struct ThreadSpawnRequest {
startup: Option<Arc<crate::session::startup::SessionStartup>>,
options: StartThreadOptions,
auth_manager: Arc<AuthManager>,
agent_control: LocalAgentControl,
agent_control: AgentControlInit,
parent_thread_id: Option<ThreadId>,
parent_originator: Option<String>,
forked_from_thread_id: Option<ThreadId>,
@@ -327,13 +328,13 @@ impl ThreadSpawnRequest {
fn new(
options: StartThreadOptions,
auth_manager: Arc<AuthManager>,
agent_control: LocalAgentControl,
agent_control: impl Into<AgentControlInit>,
) -> Self {
Self {
startup: None,
options,
auth_manager,
agent_control,
agent_control: agent_control.into(),
parent_thread_id: None,
parent_originator: None,
forked_from_thread_id: None,
@@ -989,6 +990,7 @@ impl ThreadManager {
for descendant_id in self
.agent_control()
.runtime
.list_live_agent_subtree_thread_ids(thread_id)
.await?
{
@@ -1058,11 +1060,10 @@ impl ThreadManager {
options.internal_parent = Some(InternalSessionParent {
thread_id: parent_thread_id,
auth_manager: Arc::clone(&parent.session.services.auth_manager),
agent_control: parent
.session
.services
.local_agent_runtime
.control(parent.session.session_id()),
agent_control: AgentControlInit::Inherited {
control: Arc::clone(&parent.session.services.agent_control),
runtime: parent.session.services.local_agent_runtime.clone(),
},
originator: parent.config_snapshot().await.originator,
inherited_instructions,
});
@@ -2100,8 +2101,9 @@ impl ThreadManagerState {
if let InitialHistory::Resumed(resumed) = &initial_history
&& initial_history.get_multi_agent_version() == Some(MultiAgentVersion::V2)
&& !session_source.is_non_root_agent()
&& let AgentControlInit::Local(control) = &agent_control
{
agent_control
control
.restore_v2_agent_metadata(&config, resumed.conversation_id)
.await;
}
+15 -5
View File
@@ -287,8 +287,8 @@ fn thread_id_generator_defaults_to_standard_ids() {
let agent_control = LocalAgentControl::default();
assert_ne!(
agent_control.generate_thread_id(),
agent_control.generate_thread_id()
agent_control.runtime.generate_thread_id(),
agent_control.runtime.generate_thread_id()
);
}
@@ -378,7 +378,8 @@ async fn thread_id_generator_applies_to_roots_children_and_forks() {
.thread
.session
.services
.agent_control
.local_agent_runtime
.control(root.thread.session.session_id())
.spawn_agent_with_metadata(
config.clone(),
vec![UserInput::Text {
@@ -1382,6 +1383,10 @@ async fn spawn_internal_session_preserves_parent_lineage_without_forking_history
.await
.expect("start internal reviewer");
let reviewer_config = reviewer.thread.config_snapshot().await;
assert!(Arc::ptr_eq(
&reviewer.thread.session.services.agent_control,
&parent.thread.session.services.agent_control,
));
assert_eq!(
reviewer.session_configured.session_id,
@@ -1392,10 +1397,11 @@ async fn spawn_internal_session_preserves_parent_lineage_without_forking_history
.session
.services
.agent_control
.record_rollout_budget_usage(&TokenUsage {
.record_usage(TokenUsage {
output_tokens: 25,
..Default::default()
})
.await
.expect("record reviewer usage");
let reminder = parent
.thread
@@ -1403,6 +1409,7 @@ async fn spawn_internal_session_preserves_parent_lineage_without_forking_history
.services
.agent_control
.pending_budget_reminder(parent.thread_id, "window")
.await
.expect("parent budget reminder");
assert_eq!(reminder.remaining_tokens, 75);
assert_eq!(reviewer_config.parent_thread_id, Some(parent.thread_id));
@@ -1497,7 +1504,10 @@ async fn spawn_internal_session_preserves_parent_lineage_without_forking_history
internal_parent: Some(InternalSessionParent {
thread_id: parent.thread_id,
auth_manager: Arc::clone(&parent.thread.session.services.auth_manager),
agent_control: parent.thread.session.services.agent_control.clone(),
agent_control: AgentControlInit::Inherited {
control: Arc::clone(&parent.thread.session.services.agent_control),
runtime: parent.thread.session.services.local_agent_runtime.clone(),
},
originator: reviewer_config.originator.clone(),
inherited_instructions: None,
}),
@@ -1,6 +1,6 @@
//! Implements the collaboration tool surface for spawning and managing sub-agents.
//!
//! This handler translates model tool calls into `LocalAgentControl` operations and keeps spawned
//! This handler translates model tool calls into `AgentControl` operations and keeps spawned
//! agents aligned with the live turn that created them. Sub-agents start from the turn's effective
//! config, inherit runtime-only state such as provider, approval policy, sandbox, and cwd, and
//! then optionally layer role-specific config on top.
@@ -41,7 +41,11 @@ async fn handle_close_agent(
let arguments = function_arguments(payload)?;
let args: CloseAgentArgs = parse_arguments(&arguments)?;
let agent_id = parse_agent_id_target(&args.target)?;
let receiver_agent = session.services.agent_control.get_agent_metadata(agent_id);
let local_agent_control = session
.services
.local_agent_runtime
.control(session.session_id());
let receiver_agent = local_agent_control.get_agent_metadata(agent_id);
let receiver_agent = receiver_agent.unwrap_or_default();
session
.emit_turn_item_started(
@@ -61,8 +65,8 @@ async fn handle_close_agent(
)
.await;
// Shutdown may remove the target before a descendant fails to close.
let previous_status = session.services.agent_control.get_status(agent_id).await;
let result = Box::pin(session.services.agent_control.close_agent(agent_id)).await;
let previous_status = local_agent_control.get_status(agent_id).await;
let result = local_agent_control.close_agent(agent_id).await;
let (status, receiver_agent) = match &result {
Ok(snapshot) => (
snapshot.status().cloned().unwrap_or(AgentStatus::NotFound),
@@ -45,9 +45,11 @@ async fn handle_resume_agent(
let receiver_thread_id = ThreadId::from_string(&args.id).map_err(|err| {
FunctionCallError::RespondToModel(format!("invalid agent id {}: {err:?}", args.id))
})?;
let receiver_agent = session
let local_agent_control = session
.services
.agent_control
.local_agent_runtime
.control(session.session_id());
let receiver_agent = local_agent_control
.get_agent_metadata(receiver_thread_id)
.unwrap_or_default();
let child_depth = next_thread_spawn_depth(&turn.session_source);
@@ -89,24 +91,16 @@ async fn handle_resume_agent(
/*agent_role*/ None,
/*task_name*/ None,
)?;
Box::pin(
session
.services
.agent_control
.resume_agent(config, receiver_thread_id, source),
)
.await
.map_err(|err| collab_agent_error(receiver_thread_id, err))
local_agent_control
.resume_agent(config, receiver_thread_id, source)
.await
.map_err(|err| collab_agent_error(receiver_thread_id, err))
}
.await;
let (status, receiver_agent, error) = match result {
Ok((agent, _)) => (agent.status, agent.metadata, None),
Err(err) => (
session
.services
.agent_control
.get_status(receiver_thread_id)
.await,
local_agent_control.get_status(receiver_thread_id).await,
receiver_agent,
Some(err),
),
@@ -1,7 +1,9 @@
use super::*;
use crate::agent::api::AgentTarget;
use crate::agent::child_config::build_agent_resume_config;
use crate::agent::control::render_input_preview;
use crate::tools::handlers::multi_agents_spec::create_send_input_tool_v1;
use codex_protocol::protocol::MultiAgentVersion;
use codex_tools::ToolSpec;
pub(crate) struct Handler;
@@ -47,16 +49,15 @@ impl Handler {
let receiver_thread_id = parse_agent_id_target(&args.target)?;
let input_items = parse_collab_input(args.message, args.items)?;
let prompt = render_input_preview(&input_items);
let receiver_agent = session
let local_agent_control = session
.services
.agent_control
.get_agent_metadata(receiver_thread_id);
.local_agent_runtime
.control(session.session_id());
let receiver_agent = local_agent_control.get_agent_metadata(receiver_thread_id);
if receiver_agent.is_some() {
let resume_config = build_agent_resume_config(turn.as_ref())
.map_err(FunctionCallError::RespondToModel)?;
session
.services
.agent_control
local_agent_control
.ensure_v2_agent_loaded(resume_config, receiver_thread_id, /*parent*/ None)
.await
.map_err(|err| collab_agent_error(receiver_thread_id, err))?;
@@ -66,7 +67,11 @@ impl Handler {
session
.services
.agent_control
.interrupt_agent(receiver_thread_id)
.interrupt(
session.thread_id,
AgentTarget::Id(receiver_thread_id),
MultiAgentVersion::V1,
)
.await
.map_err(|err| collab_agent_error(receiver_thread_id, err))?;
}
@@ -87,8 +92,7 @@ impl Handler {
}),
)
.await;
let agent_control = session.services.agent_control.clone();
let result = agent_control
let result = local_agent_control
.send_input(
receiver_thread_id,
input_items,
@@ -102,11 +106,7 @@ impl Handler {
)
.await
.map_err(|err| collab_agent_error(receiver_thread_id, err));
let status = session
.services
.agent_control
.get_status(receiver_thread_id)
.await;
let status = local_agent_control.get_status(receiver_thread_id).await;
session
.emit_turn_item_completed(
&turn,
@@ -1,5 +1,4 @@
use super::*;
use crate::agent::api::AgentControl;
use crate::agent::api::AgentInput;
use crate::agent::api::SpawnRequest;
use crate::agent::child_config::SpawnConfigOptions;
@@ -1,5 +1,5 @@
use super::*;
use crate::agent::api::StatusSubscription;
use crate::agent::control::StatusSubscription;
use crate::agent::status::is_final;
use crate::session::session::Session;
use crate::tools::handlers::multi_agents_spec::WaitAgentTimeoutOptions;
@@ -67,12 +67,14 @@ impl Handler {
let arguments = function_arguments(payload)?;
let args: WaitArgs = parse_arguments(&arguments)?;
let receiver_thread_ids = parse_agent_id_targets(args.targets)?;
let local_agent_control = session
.services
.local_agent_runtime
.control(session.session_id());
let mut receiver_agents = Vec::with_capacity(receiver_thread_ids.len());
let mut target_by_thread_id = HashMap::with_capacity(receiver_thread_ids.len());
for receiver_thread_id in &receiver_thread_ids {
let agent_metadata = session
.services
.agent_control
let agent_metadata = local_agent_control
.get_agent_metadata(*receiver_thread_id)
.unwrap_or_default();
target_by_thread_id.insert(
@@ -122,7 +124,7 @@ impl Handler {
let mut initial_final_statuses = Vec::new();
for id in &receiver_thread_ids {
let subscription = async {
let mut updates = session.services.agent_control.subscribe_status(*id).await?;
let mut updates = local_agent_control.subscribe_status(*id).await?;
let initial = updates
.next()
.await
@@ -144,7 +146,7 @@ impl Handler {
}
Err(err) => {
let mut statuses = HashMap::with_capacity(1);
statuses.insert(*id, session.services.agent_control.get_status(*id).await);
statuses.insert(*id, local_agent_control.get_status(*id).await);
session
.emit_turn_item_completed(
&turn,
@@ -329,6 +331,11 @@ async fn wait_for_final_status(
return Ok(Some((thread_id, status)));
}
}
let latest = session.services.agent_control.get_status(thread_id).await;
let latest = session
.services
.local_agent_runtime
.control(session.session_id())
.get_status(thread_id)
.await;
Ok(is_final(&latest).then_some((thread_id, latest)))
}
@@ -89,7 +89,7 @@ fn set_agent_control(
control: crate::agent::LocalAgentControl,
) {
session.services.local_agent_runtime = control.runtime.clone();
session.services.agent_control = control;
session.services.agent_control = Arc::new(control);
}
fn invocation(
@@ -485,7 +485,11 @@ async fn spawn_agent_service_tier_inheritance_uses_root_preference_and_child_mod
.expect("root thread should start");
set_agent_control(
&mut session,
root.thread.session.services.agent_control.clone(),
root.thread
.session
.services
.local_agent_runtime
.control(root.thread.session.session_id()),
);
session.services.models_manager = Arc::new(StaticModelsManager::new(
/*auth_manager*/ None,
@@ -534,7 +538,11 @@ async fn spawn_agent_service_tier_inheritance_uses_root_preference_and_child_mod
.expect("root thread should start");
set_agent_control(
&mut session,
root.thread.session.services.agent_control.clone(),
root.thread
.session
.services
.local_agent_runtime
.control(root.thread.session.session_id()),
);
session.services.models_manager = Arc::new(StaticModelsManager::new(
/*auth_manager*/ None,
@@ -674,7 +682,11 @@ service_tier = "turbo"
.expect("root thread should start");
set_agent_control(
&mut session,
root.thread.session.services.agent_control.clone(),
root.thread
.session
.services
.local_agent_runtime
.control(root.thread.session.session_id()),
);
session.thread_id = root.thread_id;
@@ -727,7 +739,11 @@ async fn spawn_agent_full_history_fork_inherits_root_service_tier() {
.expect("root thread should start");
set_agent_control(
&mut session,
root.thread.session.services.agent_control.clone(),
root.thread
.session
.services
.local_agent_runtime
.control(root.thread.session.session_id()),
);
session.thread_id = root.thread_id;
@@ -784,7 +800,11 @@ async fn multi_agent_v2_full_history_fork_inherits_root_service_tier() {
.expect("root thread should start");
set_agent_control(
&mut session,
root.thread.session.services.agent_control.clone(),
root.thread
.session
.services
.local_agent_runtime
.control(root.thread.session.session_id()),
);
session.thread_id = root.thread_id;
let session = Arc::new(session);
@@ -807,7 +827,7 @@ async fn multi_agent_v2_full_history_fork_inherits_root_service_tier() {
serde_json::from_str(&content).expect("spawn_agent result should be json");
let child_thread_id = session
.services
.agent_control
.local_agent_runtime
.resolve_agent_reference(
session.thread_id,
&turn.session_source,
@@ -1045,7 +1065,7 @@ async fn multi_agent_v2_spawn_returns_path_and_send_message_accepts_relative_pat
let child_thread_id = session
.services
.agent_control
.local_agent_runtime
.resolve_agent_reference(session.thread_id, &turn.session_source, "test_process")
.await
.expect("relative path should resolve");
@@ -1241,7 +1261,8 @@ async fn multi_agent_v2_send_message_accepts_root_target_from_child() {
let child_path = AgentPath::try_from("/root/worker").expect("agent path");
let child_thread_id = session
.services
.agent_control
.local_agent_runtime
.control(session.session_id())
.spawn_agent_with_metadata(
(*turn.config).clone(),
vec![UserInput::Text {
@@ -1317,7 +1338,8 @@ async fn multi_agent_v2_followup_task_rejects_root_target_from_child() {
let child_path = AgentPath::try_from("/root/worker").expect("agent path");
let child_thread_id = session
.services
.agent_control
.local_agent_runtime
.control(session.session_id())
.spawn_agent_with_metadata(
(*turn.config).clone(),
vec![UserInput::Text {
@@ -1411,7 +1433,7 @@ async fn multi_agent_v2_list_agents_returns_completed_status() {
let agent_id = session
.services
.agent_control
.local_agent_runtime
.resolve_agent_reference(session.thread_id, &turn.session_source, "worker")
.await
.expect("worker path should resolve");
@@ -1482,7 +1504,8 @@ async fn multi_agent_v2_list_agents_filters_by_relative_path_prefix() {
let worker_path = AgentPath::from_string("/root/researcher/worker".to_string()).expect("path");
session
.services
.agent_control
.local_agent_runtime
.control(session.session_id())
.spawn_agent_with_metadata(
config.clone(),
vec![UserInput::Text {
@@ -1502,7 +1525,8 @@ async fn multi_agent_v2_list_agents_filters_by_relative_path_prefix() {
.expect("researcher agent should spawn");
session
.services
.agent_control
.local_agent_runtime
.control(session.session_id())
.spawn_agent_with_metadata(
config,
vec![UserInput::Text {
@@ -1580,13 +1604,14 @@ async fn multi_agent_v2_list_agents_omits_closed_agents() {
let agent_id = session
.services
.agent_control
.local_agent_runtime
.resolve_agent_reference(session.thread_id, &turn.session_source, "worker")
.await
.expect("worker path should resolve");
session
.services
.agent_control
.local_agent_runtime
.control(session.session_id())
.close_agent(agent_id)
.await
.expect("close_agent should succeed");
@@ -1640,14 +1665,14 @@ async fn multi_agent_v2_list_agents_keeps_interrupted_resident_agents() {
let agent_id = session
.services
.agent_control
.local_agent_runtime
.resolve_agent_reference(session.thread_id, &turn.session_source, "worker")
.await
.expect("worker path should resolve");
let agent_path = session
.services
.agent_control
.get_agent_metadata(agent_id)
.local_agent_runtime
.ensure_agent_known(agent_id)
.expect("worker metadata should exist")
.agent_path
.expect("worker path should exist");
@@ -1710,7 +1735,7 @@ async fn multi_agent_v2_send_message_rejects_legacy_items_field() {
.expect("spawn worker");
let agent_id = session
.services
.agent_control
.local_agent_runtime
.resolve_agent_reference(session.thread_id, &turn.session_source, "worker")
.await
.expect("worker should resolve");
@@ -1766,7 +1791,7 @@ async fn multi_agent_v2_send_message_rejects_interrupt_parameter() {
.expect("spawn worker");
let agent_id = session
.services
.agent_control
.local_agent_runtime
.resolve_agent_reference(session.thread_id, &turn.session_source, "worker")
.await
.expect("worker should resolve");
@@ -1843,7 +1868,7 @@ async fn multi_agent_v2_followup_task_completion_notifies_parent_on_every_turn()
.expect("spawn worker");
let agent_id = session
.services
.agent_control
.local_agent_runtime
.resolve_agent_reference(session.thread_id, &turn.session_source, "worker")
.await
.expect("worker should resolve");
@@ -1996,7 +2021,7 @@ async fn multi_agent_v2_followup_task_rejects_legacy_items_field() {
.expect("spawn worker");
let agent_id = session
.services
.agent_control
.local_agent_runtime
.resolve_agent_reference(session.thread_id, &turn.session_source, "worker")
.await
.expect("worker should resolve");
@@ -2049,7 +2074,7 @@ async fn multi_agent_v2_interrupted_turn_does_not_notify_parent() {
.expect("spawn worker");
let agent_id = session
.services
.agent_control
.local_agent_runtime
.resolve_agent_reference(session.thread_id, &turn.session_source, "worker")
.await
.expect("worker should resolve");
@@ -2912,14 +2937,14 @@ async fn multi_agent_v2_wait_agent_accepts_timeout_only_argument() {
.expect("spawn worker");
let agent_id = session
.services
.agent_control
.local_agent_runtime
.resolve_agent_reference(session.thread_id, &turn.session_source, "worker")
.await
.expect("worker should resolve");
let worker_path = session
.services
.agent_control
.get_agent_metadata(agent_id)
.local_agent_runtime
.ensure_agent_known(agent_id)
.expect("worker metadata")
.agent_path
.expect("worker path");
@@ -3413,14 +3438,14 @@ async fn multi_agent_v2_wait_agent_returns_summary_for_mailbox_activity() {
let agent_id = session
.services
.agent_control
.local_agent_runtime
.resolve_agent_reference(session.thread_id, &turn.session_source, "test_process")
.await
.expect("relative path should resolve");
let worker_path = session
.services
.agent_control
.get_agent_metadata(agent_id)
.local_agent_runtime
.ensure_agent_known(agent_id)
.expect("worker metadata")
.agent_path
.expect("worker path");
@@ -3504,14 +3529,14 @@ async fn multi_agent_v2_wait_agent_returns_for_already_queued_mail() {
.expect("spawn worker");
let agent_id = session
.services
.agent_control
.local_agent_runtime
.resolve_agent_reference(session.thread_id, &turn.session_source, "worker")
.await
.expect("worker should resolve");
let worker_path = session
.services
.agent_control
.get_agent_metadata(agent_id)
.local_agent_runtime
.ensure_agent_known(agent_id)
.expect("worker metadata")
.agent_path
.expect("worker path");
@@ -3590,14 +3615,14 @@ async fn multi_agent_v2_wait_agent_wakes_on_any_mailbox_notification() {
}
let worker_b_id = session
.services
.agent_control
.local_agent_runtime
.resolve_agent_reference(session.thread_id, &turn.session_source, "worker_b")
.await
.expect("worker_b should resolve");
let worker_b_path = session
.services
.agent_control
.get_agent_metadata(worker_b_id)
.local_agent_runtime
.ensure_agent_known(worker_b_id)
.expect("worker_b metadata")
.agent_path
.expect("worker_b path");
@@ -3682,14 +3707,14 @@ async fn multi_agent_v2_wait_agent_does_not_return_completed_content() {
.expect("spawn worker");
let agent_id = session
.services
.agent_control
.local_agent_runtime
.resolve_agent_reference(session.thread_id, &turn.session_source, "worker")
.await
.expect("worker should resolve");
let worker_path = session
.services
.agent_control
.get_agent_metadata(agent_id)
.local_agent_runtime
.ensure_agent_known(agent_id)
.expect("worker metadata")
.agent_path
.expect("worker path");
@@ -3775,7 +3800,7 @@ async fn multi_agent_v2_interrupt_agent_accepts_task_name_target() {
let agent_id = session
.services
.agent_control
.local_agent_runtime
.resolve_agent_reference(session.thread_id, &turn.session_source, "worker")
.await
.expect("worker path should resolve");
@@ -3798,7 +3823,7 @@ async fn multi_agent_v2_interrupt_agent_accepts_task_name_target() {
.expect("child spawn should succeed");
let child_id = session
.services
.agent_control
.local_agent_runtime
.resolve_agent_reference(session.thread_id, &turn.session_source, "worker/child")
.await
.expect("child path should resolve");
@@ -3820,7 +3845,7 @@ async fn multi_agent_v2_interrupt_agent_accepts_task_name_target() {
assert_eq!(
session
.services
.agent_control
.local_agent_runtime
.resolve_agent_reference(session.thread_id, &turn.session_source, "worker")
.await
.expect("worker path should remain resolvable"),
@@ -3896,7 +3921,7 @@ async fn multi_agent_v2_interrupt_agent_accepts_unloaded_task_name_target() {
let agent_id = session
.services
.agent_control
.local_agent_runtime
.resolve_agent_reference(session.thread_id, &turn.session_source, "worker")
.await
.expect("worker path should resolve");
@@ -4028,7 +4053,8 @@ async fn multi_agent_v2_interrupt_agent_rejects_self_target_by_id() {
let child_path = AgentPath::try_from("/root/worker").expect("agent path");
let child_thread_id = session
.services
.agent_control
.local_agent_runtime
.control(session.session_id())
.spawn_agent_with_metadata(
(*turn.config).clone(),
vec![UserInput::Text {
@@ -4095,7 +4121,8 @@ async fn multi_agent_v2_interrupt_agent_rejects_self_target_by_task_name() {
let child_path = AgentPath::try_from("/root/worker").expect("agent path");
let child_thread_id = session
.services
.agent_control
.local_agent_runtime
.control(session.session_id())
.spawn_agent_with_metadata(
(*turn.config).clone(),
vec![UserInput::Text {
@@ -1,6 +1,8 @@
use super::analytics::ToolCallAnalytics;
use super::*;
use crate::agent::api::AgentTarget;
use crate::tools::handlers::multi_agents_spec::create_interrupt_agent_tool_v2;
use codex_protocol::protocol::MultiAgentVersion;
use codex_tools::ToolSpec;
pub(crate) struct Handler;
@@ -46,7 +48,11 @@ async fn handle_interrupt_agent(
let snapshot = session
.services
.agent_control
.interrupt_spawned_agent(session.thread_id, agent_id)
.interrupt(
session.thread_id,
AgentTarget::Id(agent_id),
MultiAgentVersion::V2,
)
.await
.map_err(|err| collab_v2_agent_error(agent_id, err))?;
let agent_path = snapshot.metadata().agent_path.clone().ok_or_else(|| {
@@ -42,12 +42,12 @@ impl Handler {
let args: ListAgentsArgs = parse_arguments(&arguments)?;
session
.services
.agent_control
.local_agent_runtime
.register_session_root(session.thread_id, turn.parent_thread_id);
let agents = session
.services
.agent_control
.list_agents(&turn.session_source, args.path_prefix.as_deref())
.list(&turn.session_source, args.path_prefix.as_deref())
.await
.map_err(collab_spawn_error)?;
@@ -6,7 +6,6 @@
use super::analytics::ToolCallAnalytics;
use super::*;
use crate::TurnStartOptions;
use crate::agent::api::AgentControl;
use crate::agent::api::AgentInput;
use crate::agent::api::AgentTarget;
use crate::agent::api::SendRequest;
@@ -1,5 +1,4 @@
use super::*;
use crate::agent::api::AgentControl;
use crate::agent::api::AgentInput;
use crate::agent::api::SpawnRequest;
use crate::agent::child_config::SpawnConfigOptions;