Enforce subagent ownership across app-server inputs (#40464)

## Why

Parent-owned Multi-Agent V2 subagents must remain controlled by their parent,
but several app-server endpoints could still mutate them directly.

## What changed

- Centralize the direct-input ownership check and apply it to turn injection,
  MCP calls, reviews, compaction, rollback and revert, shell and Guardian
  actions, realtime requests, and goal mutations.
- Enforce the same policy for goal mutations on unloaded threads while keeping
  goal reads and turn interruption available.
- Document the affected endpoint behavior and continue exposing
  `canAcceptDirectInput: false` for parent-owned subagents.

## Testing

- Cover direct-input rejection for both legacy and paginated thread history.
- Cover goal mutation ownership checks for unloaded V2 subagents, V1
  subagents, and non-subagent V2 threads.

GitOrigin-RevId: 791b7af98490aed5eab4e672b90661acad11ec23
This commit is contained in:
rhan-oai authored and copyberry committed 2026-08-24 19:44:14 +00:00
1 parent bf3eb2ec91
commit b6333bb1bb
12 files changed
+419 -62

No files matched your search

@@ -1,3 +1,4 @@
use super::thread_input::ensure_direct_input_allowed;
use super::*;
use codex_core::McpManager;
use codex_mcp::McpServerSource;
@@ -524,6 +525,7 @@ impl McpRequestProcessor {
let outgoing = Arc::clone(&self.outgoing);
let thread_id = params.thread_id.clone();
let (_, thread) = self.load_thread(&thread_id).await?;
ensure_direct_input_allowed(thread.as_ref()).await?;
let meta = with_mcp_tool_call_thread_id_meta(params.meta, &thread_id);
let request_id = request_id.clone();
@@ -1,4 +1,4 @@
use super::turn_processor::can_accept_direct_input;
use super::thread_input::can_accept_direct_input;
use crate::thread_status::ThreadWatchManager;
use crate::thread_status::resolve_thread_status;
use codex_app_server_protocol::SessionSource;
@@ -1,11 +1,22 @@
use super::thread_input::DIRECT_INPUT_TO_MULTI_AGENT_V2_SUBAGENT_ERROR;
use super::thread_input::can_accept_direct_input;
use super::thread_input::ensure_direct_input_allowed;
use super::*;
use codex_goal_extension::GoalObjectiveUpdate;
use codex_goal_extension::GoalService;
use codex_goal_extension::GoalServiceError;
use codex_goal_extension::GoalSetRequest;
use codex_goal_extension::GoalTokenBudgetUpdate;
use codex_protocol::protocol::SessionSource;
use codex_protocol::protocol::SubAgentSource;
use codex_protocol::protocol::ThreadSettingsAppliedEvent;
use codex_protocol::protocol::ThreadSettingsSnapshot;
use codex_rollout::RolloutRecorder;
enum GoalAccess {
Read,
Mutate,
}
#[derive(Clone)]
pub(crate) struct ThreadGoalRequestProcessor {
@@ -119,7 +130,9 @@ impl ThreadGoalRequestProcessor {
}
let thread_id = parse_thread_id_for_request(params.thread_id.as_str())?;
let state_db = self.state_db_for_materialized_thread(thread_id).await?;
let state_db = self
.state_db_for_materialized_thread(thread_id, GoalAccess::Mutate)
.await?;
self.reconcile_thread_goal_rollout(thread_id, &state_db)
.await?;
let max_goal_token_budget = match self.thread_manager.get_thread(thread_id).await {
@@ -216,7 +229,9 @@ impl ThreadGoalRequestProcessor {
}
let thread_id = parse_thread_id_for_request(params.thread_id.as_str())?;
let state_db = self.state_db_for_materialized_thread(thread_id).await?;
let state_db = self
.state_db_for_materialized_thread(thread_id, GoalAccess::Read)
.await?;
let goal = self
.goal_service
.get_thread_goal(&state_db, thread_id)
@@ -236,7 +251,9 @@ impl ThreadGoalRequestProcessor {
}
let thread_id = parse_thread_id_for_request(params.thread_id.as_str())?;
let state_db = self.state_db_for_materialized_thread(thread_id).await?;
let state_db = self
.state_db_for_materialized_thread(thread_id, GoalAccess::Mutate)
.await?;
self.reconcile_thread_goal_rollout(thread_id, &state_db)
.await?;
@@ -264,8 +281,12 @@ impl ThreadGoalRequestProcessor {
async fn state_db_for_materialized_thread(
&self,
thread_id: ThreadId,
access: GoalAccess,
) -> Result<StateDbHandle, JSONRPCErrorError> {
if let Ok(thread) = self.thread_manager.get_thread(thread_id).await {
if matches!(access, GoalAccess::Mutate) {
ensure_direct_input_allowed(thread.as_ref()).await?;
}
if thread.rollout_path().is_none() {
return Err(invalid_request(format!(
"ephemeral thread does not support goals: {thread_id}"
@@ -275,7 +296,7 @@ impl ThreadGoalRequestProcessor {
return Ok(state_db);
}
} else {
codex_rollout::find_thread_path_by_id_str(
let rollout_path = codex_rollout::find_thread_path_by_id_str(
&self.config.codex_home,
&thread_id.to_string(),
self.state_db.as_deref(),
@@ -285,6 +306,38 @@ impl ThreadGoalRequestProcessor {
internal_error(format!("failed to locate thread id {thread_id}: {err}"))
})?
.ok_or_else(|| invalid_request(format!("thread not found: {thread_id}")))?;
if matches!(access, GoalAccess::Mutate) {
let session_meta = codex_rollout::read_session_meta_line(&rollout_path)
.await
.map_err(|err| {
internal_error(format!("failed to read thread ownership: {err}"))
})?;
if session_meta.meta.id != thread_id {
return Err(invalid_request(
"thread metadata does not match requested id",
));
}
if matches!(
session_meta.meta.source,
SessionSource::SubAgent(SubAgentSource::ThreadSpawn { .. })
) {
// Match resume's latest version metadata, including legacy TurnContext
// fallback, rather than trusting only the initial session header.
let history = RolloutRecorder::get_rollout_history(&rollout_path)
.await
.map_err(|err| {
internal_error(format!("failed to read thread ownership: {err}"))
})?;
if !can_accept_direct_input(
history.get_multi_agent_version(),
&session_meta.meta.source,
) {
return Err(invalid_request(
DIRECT_INPUT_TO_MULTI_AGENT_V2_SUBAGENT_ERROR,
));
}
}
}
}
self.state_db
@@ -342,7 +395,10 @@ impl ThreadGoalRequestProcessor {
}
pub(crate) async fn emit_thread_goal_snapshot(&self, thread_id: ThreadId) {
let state_db = match self.state_db_for_materialized_thread(thread_id).await {
let state_db = match self
.state_db_for_materialized_thread(thread_id, GoalAccess::Read)
.await
{
Ok(state_db) => state_db,
Err(err) => {
warn!(
@@ -0,0 +1,37 @@
use super::invalid_request;
use codex_app_server_protocol::JSONRPCErrorError;
use codex_core::CodexThread;
use codex_protocol::protocol::MultiAgentVersion;
use codex_protocol::protocol::SessionSource;
use codex_protocol::protocol::SubAgentSource;
pub(super) const DIRECT_INPUT_TO_MULTI_AGENT_V2_SUBAGENT_ERROR: &str =
"direct app-server input is not allowed for multi-agent v2 sub-agents";
/// Mirrors the ownership policy in request validation and thread capability responses.
pub(super) fn can_accept_direct_input(
multi_agent_version: Option<MultiAgentVersion>,
session_source: &SessionSource,
) -> bool {
multi_agent_version != Some(MultiAgentVersion::V2)
|| !matches!(
session_source,
SessionSource::SubAgent(SubAgentSource::ThreadSpawn { .. })
)
}
pub(super) async fn ensure_direct_input_allowed(
thread: &CodexThread,
) -> Result<(), JSONRPCErrorError> {
let config_snapshot = thread.config_snapshot().await;
if !can_accept_direct_input(
thread.multi_agent_version(),
&config_snapshot.session_source,
) {
return Err(invalid_request(
DIRECT_INPUT_TO_MULTI_AGENT_V2_SUBAGENT_ERROR,
));
}
Ok(())
}
@@ -2,7 +2,8 @@ use super::persisted_resume_settings::PersistedResumeSettings;
use super::persisted_resume_settings::latest_persisted_resume_settings;
use super::thread_enrichment::enrich_loaded_threads;
use super::thread_fork_goal::inherit_thread_goal_snapshot;
use super::turn_processor::can_accept_direct_input;
use super::thread_input::can_accept_direct_input;
use super::thread_input::ensure_direct_input_allowed;
use super::*;
use crate::error_code::method_not_found;
use codex_app_server_protocol::SelectedCapabilityRoot;
@@ -914,6 +915,7 @@ impl ThreadRequestProcessor {
Ok((thread_id, thread))
}
pub(super) async fn acquire_thread_list_state_permit(
&self,
) -> Result<SemaphorePermit<'_>, JSONRPCErrorError> {
@@ -2013,6 +2015,7 @@ impl ThreadRequestProcessor {
before_turn_id,
} = params;
let (thread_id, thread) = self.load_thread(&thread_id).await?;
ensure_direct_input_allowed(thread.as_ref()).await?;
let config_snapshot = thread.config_snapshot().await;
if !matches!(config_snapshot.history_mode, ThreadHistoryMode::Paginated) {
return Err(invalid_request(
@@ -2231,6 +2234,7 @@ impl ThreadRequestProcessor {
}
let (thread_id, thread) = self.load_thread(&thread_id).await?;
ensure_direct_input_allowed(thread.as_ref()).await?;
if matches!(
thread.config_snapshot().await.history_mode,
ThreadHistoryMode::Paginated
@@ -2284,6 +2288,7 @@ impl ThreadRequestProcessor {
let ThreadCompactStartParams { thread_id } = params;
let (_, thread) = self.load_thread(&thread_id).await?;
ensure_direct_input_allowed(thread.as_ref()).await?;
self.submit_core_op(request_id, thread.as_ref(), Op::Compact)
.await
.map_err(|err| internal_error(format!("failed to start compaction: {err}")))?;
@@ -2364,6 +2369,10 @@ impl ThreadRequestProcessor {
if command.is_empty() {
return Err(invalid_request("command must not be empty"));
}
let (_, thread) = self.load_thread(&thread_id).await?;
ensure_direct_input_allowed(thread.as_ref()).await?;
// `thread/shellCommand` is app-server's local-host shell escape hatch,
// not the normal turn-selected shell tool path.
if self
@@ -2375,7 +2384,6 @@ impl ThreadRequestProcessor {
return Err(internal_error("local environment is not configured"));
}
let (_, thread) = self.load_thread(&thread_id).await?;
self.submit_core_op(
request_id,
thread.as_ref(),
@@ -2395,6 +2403,7 @@ impl ThreadRequestProcessor {
let event = serde_json::from_value(event)
.map_err(|err| invalid_request(format!("invalid Guardian denial event: {err}")))?;
let (_, thread) = self.load_thread(&thread_id).await?;
ensure_direct_input_allowed(thread.as_ref()).await?;
self.submit_core_op(
request_id,
@@ -38,10 +38,10 @@ use codex_thread_store::ThreadStore;
use codex_thread_store::ThreadStoreError;
use super::TurnRequestProcessor;
use super::thread_input::DIRECT_INPUT_TO_MULTI_AGENT_V2_SUBAGENT_ERROR;
use super::thread_input::can_accept_direct_input;
use super::thread_processor::THREAD_LIST_DEFAULT_LIMIT;
use super::thread_processor::THREAD_LIST_MAX_LIMIT;
use super::turn_processor::DIRECT_INPUT_TO_MULTI_AGENT_V2_SUBAGENT_ERROR;
use super::turn_processor::can_accept_direct_input;
use super::turn_processor::validate_user_input_image_urls;
const DIRECT_INPUT_TO_UNLOADED_SUBAGENT_ERROR: &str =
@@ -1,3 +1,4 @@
use super::thread_input::ensure_direct_input_allowed;
use super::*;
use codex_agent_extension::AgentInvocation;
use codex_agent_extension::AgentRun;
@@ -7,29 +8,11 @@ use codex_protocol::models::ContentItem;
use codex_protocol::models::FunctionCallOutputContentItem;
use codex_protocol::protocol::AdditionalContextEntry as CoreAdditionalContextEntry;
use codex_protocol::protocol::AdditionalContextKind as CoreAdditionalContextKind;
use codex_protocol::protocol::MultiAgentVersion;
use codex_protocol::protocol::SessionSource;
use codex_protocol::protocol::SubAgentSource;
use codex_skills::system_cache_root_dir;
use crate::image_url::REMOTE_IMAGE_URL_ERROR;
use crate::image_url::is_remote_image_url;
pub(super) const DIRECT_INPUT_TO_MULTI_AGENT_V2_SUBAGENT_ERROR: &str =
"direct app-server input is not allowed for multi-agent v2 sub-agents";
/// Mirrors the direct-input policy in both request validation and thread capability responses.
pub(super) fn can_accept_direct_input(
multi_agent_version: Option<MultiAgentVersion>,
session_source: &SessionSource,
) -> bool {
multi_agent_version != Some(MultiAgentVersion::V2)
|| !matches!(
session_source,
SessionSource::SubAgent(SubAgentSource::ThreadSpawn { .. })
)
}
pub(super) fn validate_user_input_image_urls(
input: &[V2UserInput],
) -> Result<(), JSONRPCErrorError> {
@@ -196,9 +179,10 @@ impl TurnRequestProcessor {
pub(crate) async fn thread_inject_items(
&self,
request_id: &ConnectionRequestId,
params: ThreadInjectItemsParams,
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
self.thread_inject_items_response_inner(params)
self.thread_inject_items_response_inner(request_id, params)
.await
.map(|response| Some(response.into()))
}
@@ -343,17 +327,11 @@ impl TurnRequestProcessor {
request_id: &ConnectionRequestId,
thread: &CodexThread,
) -> Result<(), JSONRPCErrorError> {
let config_snapshot = thread.config_snapshot().await;
if !can_accept_direct_input(
thread.multi_agent_version(),
&config_snapshot.session_source,
) {
let error = invalid_request(DIRECT_INPUT_TO_MULTI_AGENT_V2_SUBAGENT_ERROR);
self.track_error_response(request_id, &error, /*error_type*/ None);
return Err(error);
}
Ok(())
ensure_direct_input_allowed(thread)
.await
.inspect_err(|error| {
self.track_error_response(request_id, error, /*error_type*/ None);
})
}
fn normalize_collaboration_mode(
@@ -870,9 +848,12 @@ impl TurnRequestProcessor {
async fn thread_inject_items_response_inner(
&self,
request_id: &ConnectionRequestId,
params: ThreadInjectItemsParams,
) -> Result<ThreadInjectItemsResponse, JSONRPCErrorError> {
let (_, thread) = self.load_thread(&params.thread_id).await?;
self.ensure_direct_input_allowed(request_id, thread.as_ref())
.await?;
let items = params
.items
@@ -1052,6 +1033,8 @@ impl TurnRequestProcessor {
thread_id: &str,
) -> Result<Option<(ThreadId, Arc<CodexThread>)>, JSONRPCErrorError> {
let (thread_id, thread) = self.load_thread(thread_id).await?;
self.ensure_direct_input_allowed(request_id, thread.as_ref())
.await?;
match self
.ensure_conversation_listener(
@@ -1439,6 +1422,8 @@ impl TurnRequestProcessor {
} = params;
let (_, parent_thread) = self.load_thread(&thread_id).await?;
self.ensure_direct_input_allowed(request_id, parent_thread.as_ref())
.await?;
let (review_request, display_text, target_prompt) =
Self::review_request_from_target(target)?;
match delivery.unwrap_or(ApiReviewDelivery::Inline).to_core() {