mirror of
https://github.com/openai/codex.git
synced 2026-11-20 22:40:37 +00:00
Unify turn input submission and routing (#38275)
## What changed - Add `TurnInputRequest` and typed submission results for atomically starting a turn, steering the active turn, or declining input with a specific reason. - Expose `start_or_steer_turn`, `start_turn_if_idle`, and `steer_turn` on `CodexThread`, and migrate Core consumers to these APIs. - Make app-server `turn/start` steer an active regular turn and return that turn's ID. Reject incompatible output schemas and non-steerable turns without applying settings or enqueueing input. ## Testing - Cover concurrent start-or-steer submissions, accepted and rejected settings updates, output-schema compatibility, idle-start rejection, and app-server steering. GitOrigin-RevId: dd9b5528d76ec650c019e97af420bc13190ea86a
This commit is contained in:
@@ -4,10 +4,7 @@ use crate::elicitation::ElicitationRegistration;
|
||||
use crate::environment_config::EnvironmentConfig;
|
||||
use crate::session::SessionIo;
|
||||
use crate::session::SessionSettingsUpdate;
|
||||
use crate::session::SteerInputError;
|
||||
use crate::session::TurnInput;
|
||||
use crate::session::session::Session;
|
||||
use crate::user_message_admission::UserMessageAdmission;
|
||||
use codex_diagnostics::Gauge;
|
||||
use codex_diagnostics::GaugeGuard;
|
||||
use codex_exec_server::SelectedCapabilityRootsStatus;
|
||||
@@ -29,7 +26,6 @@ use codex_protocol::models::ContentItem;
|
||||
use codex_protocol::models::PermissionProfile;
|
||||
use codex_protocol::models::ResponseItem;
|
||||
use codex_protocol::openai_models::ReasoningEffort;
|
||||
use codex_protocol::protocol::AdditionalContextEntry;
|
||||
use codex_protocol::protocol::AskForApproval;
|
||||
use codex_protocol::protocol::Event;
|
||||
use codex_protocol::protocol::MultiAgentVersion;
|
||||
@@ -37,7 +33,6 @@ use codex_protocol::protocol::Op;
|
||||
use codex_protocol::protocol::SandboxPolicy;
|
||||
use codex_protocol::protocol::SessionConfiguredEvent;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use codex_protocol::protocol::Submission;
|
||||
use codex_protocol::protocol::ThreadHistoryMode;
|
||||
use codex_protocol::protocol::ThreadMemoryMode;
|
||||
use codex_protocol::protocol::ThreadSettingsSnapshot;
|
||||
@@ -46,7 +41,11 @@ use codex_protocol::protocol::TokenUsageInfo;
|
||||
use codex_protocol::protocol::TurnEnvironmentSelection;
|
||||
use codex_protocol::protocol::TurnEnvironmentSelections;
|
||||
use codex_protocol::protocol::W3cTraceContext;
|
||||
use codex_protocol::user_input::UserInput;
|
||||
use codex_protocol::turn_input::StartIfIdleSubmission;
|
||||
use codex_protocol::turn_input::SteerSubmission;
|
||||
use codex_protocol::turn_input::TurnInputMode;
|
||||
use codex_protocol::turn_input::TurnInputRequest;
|
||||
use codex_protocol::turn_input::TurnInputSubmission;
|
||||
use codex_thread_store::PersistContext;
|
||||
use codex_thread_store::StoredThread;
|
||||
use codex_thread_store::StoredThreadHistory;
|
||||
@@ -57,8 +56,6 @@ use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_path_uri::LegacyAppPathString;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use rmcp::model::ReadResourceRequestParams;
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::Mutex;
|
||||
@@ -94,46 +91,6 @@ pub struct ThreadConfigSnapshot {
|
||||
pub originator: String,
|
||||
}
|
||||
|
||||
/// Explains why `CodexThread::try_start_turn_if_idle` rejected an automatic
|
||||
/// idle turn.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum TryStartTurnIfIdleRejectionReason {
|
||||
/// User/client-triggered mailbox work is already queued and must take
|
||||
/// priority over extension-initiated idle work.
|
||||
PendingTriggerTurn,
|
||||
/// The thread is in Plan mode, where idle work without user input must not
|
||||
/// start a new model turn.
|
||||
PlanMode,
|
||||
/// Another turn or task is active, or the idle reservation was lost before
|
||||
/// the automatic turn could start.
|
||||
Busy,
|
||||
}
|
||||
|
||||
/// Rejection returned when an extension asks to start automatic idle work but
|
||||
/// the thread is not eligible to run it.
|
||||
#[derive(Debug)]
|
||||
pub struct TryStartTurnIfIdleError {
|
||||
reason: TryStartTurnIfIdleRejectionReason,
|
||||
input: Vec<TurnInput>,
|
||||
}
|
||||
|
||||
impl TryStartTurnIfIdleError {
|
||||
pub(crate) fn new(reason: TryStartTurnIfIdleRejectionReason, input: Vec<TurnInput>) -> Self {
|
||||
Self { reason, input }
|
||||
}
|
||||
|
||||
/// Returns the stable reason the automatic idle turn was rejected.
|
||||
pub fn reason(&self) -> TryStartTurnIfIdleRejectionReason {
|
||||
self.reason
|
||||
}
|
||||
|
||||
/// Consumes the rejection and returns the original turn input
|
||||
/// unchanged, so callers can retry, drop, or log it explicitly.
|
||||
pub fn into_input(self) -> Vec<TurnInput> {
|
||||
self.input
|
||||
}
|
||||
}
|
||||
|
||||
impl ThreadConfigSnapshot {
|
||||
pub fn cwd(&self) -> &AbsolutePathBuf {
|
||||
&self.environments.legacy_fallback_cwd
|
||||
@@ -300,88 +257,83 @@ impl CodexThread {
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn submit_user_input_with_client_user_message_id(
|
||||
/// Submits turn input without requiring the caller to inspect thread state.
|
||||
///
|
||||
/// The result describes whether Core started a turn, steered an active
|
||||
/// turn, or declined it without recording or enqueueing the input. Only
|
||||
/// user input is accepted.
|
||||
pub async fn start_or_steer_turn(
|
||||
&self,
|
||||
op: Op,
|
||||
trace: Option<W3cTraceContext>,
|
||||
client_user_message_id: Option<String>,
|
||||
) -> CodexResult<String> {
|
||||
self.session
|
||||
.services
|
||||
.agent_control
|
||||
.ensure_execution_capacity_for_op(self.session.thread_id(), &op)
|
||||
.await?;
|
||||
self.io
|
||||
.submit_user_input_with_client_user_message_id(op, trace, client_user_message_id)
|
||||
request: TurnInputRequest,
|
||||
) -> CodexResult<TurnInputSubmission> {
|
||||
self.submit_turn_input_with_mode(request, TurnInputMode::StartOrSteer)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Waits until Core has started a turn or steered the active turn.
|
||||
pub async fn submit_user_input_and_wait_for_admission(
|
||||
/// Starts a regular turn only when the thread is idle.
|
||||
///
|
||||
/// Core declines the input without recording or enqueueing it when idle
|
||||
/// work cannot start.
|
||||
pub async fn start_turn_if_idle(
|
||||
&self,
|
||||
op: Op,
|
||||
trace: Option<W3cTraceContext>,
|
||||
client_user_message_id: Option<String>,
|
||||
) -> CodexResult<UserMessageAdmission> {
|
||||
let Op::UserInput { .. } = &op else {
|
||||
return Err(CodexErr::InvalidRequest(
|
||||
"user message admission requires user input".to_string(),
|
||||
));
|
||||
};
|
||||
self.session
|
||||
.services
|
||||
.agent_control
|
||||
.ensure_execution_capacity_for_op(self.session.thread_id(), &op)
|
||||
.await?;
|
||||
let submission_id = crate::session::new_submission_id();
|
||||
let (_pending_admission, admission) = self
|
||||
.session
|
||||
.pending_user_message_admissions
|
||||
.register(submission_id.clone());
|
||||
self.io
|
||||
.submit_with_id(Submission {
|
||||
id: submission_id.clone(),
|
||||
op,
|
||||
client_user_message_id,
|
||||
trace,
|
||||
parent_turn_id: None,
|
||||
root_turn_id: None,
|
||||
})
|
||||
.await?;
|
||||
tokio::select! {
|
||||
biased;
|
||||
result = admission => result.unwrap_or(Err(CodexErr::InternalAgentDied)),
|
||||
() = self.io.session_loop_termination.clone() => {
|
||||
Err(CodexErr::InternalAgentDied)
|
||||
},
|
||||
request: TurnInputRequest,
|
||||
) -> CodexResult<StartIfIdleSubmission> {
|
||||
match self
|
||||
.submit_turn_input_with_mode(request, TurnInputMode::StartIfIdle)
|
||||
.await?
|
||||
{
|
||||
TurnInputSubmission::Started { turn_id } => {
|
||||
Ok(StartIfIdleSubmission::Started { turn_id })
|
||||
}
|
||||
TurnInputSubmission::NotSubmitted { reason } => {
|
||||
Ok(StartIfIdleSubmission::NotSubmitted { reason })
|
||||
}
|
||||
TurnInputSubmission::Steered { .. } => {
|
||||
unreachable!("start-if-idle submission cannot steer")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Steers only if `expected_turn_id` is still the active regular turn.
|
||||
pub async fn steer_turn(
|
||||
&self,
|
||||
request: TurnInputRequest,
|
||||
expected_turn_id: String,
|
||||
) -> CodexResult<SteerSubmission> {
|
||||
match self
|
||||
.submit_turn_input_with_mode(request, TurnInputMode::Steer { expected_turn_id })
|
||||
.await?
|
||||
{
|
||||
TurnInputSubmission::Steered { turn_id } => Ok(SteerSubmission::Steered { turn_id }),
|
||||
TurnInputSubmission::NotSubmitted { reason } => {
|
||||
Ok(SteerSubmission::NotSubmitted { reason })
|
||||
}
|
||||
TurnInputSubmission::Started { .. } => {
|
||||
unreachable!("steer-only submission cannot start a turn")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn submit_turn_input_with_mode(
|
||||
&self,
|
||||
request: TurnInputRequest,
|
||||
mode: TurnInputMode,
|
||||
) -> CodexResult<TurnInputSubmission> {
|
||||
if !matches!(mode, TurnInputMode::Steer { .. }) {
|
||||
self.session
|
||||
.services
|
||||
.agent_control
|
||||
.ensure_execution_capacity_for_turn_start(self)
|
||||
.await?;
|
||||
}
|
||||
self.io.submit_turn_input(request, mode).await
|
||||
}
|
||||
|
||||
/// Persist whether this thread is eligible for future memory generation.
|
||||
pub async fn set_thread_memory_mode(&self, mode: ThreadMemoryMode) -> anyhow::Result<()> {
|
||||
self.session.set_thread_memory_mode(mode).await
|
||||
}
|
||||
|
||||
pub async fn steer_input(
|
||||
&self,
|
||||
input: Vec<UserInput>,
|
||||
additional_context: BTreeMap<String, AdditionalContextEntry>,
|
||||
expected_turn_id: Option<&str>,
|
||||
client_user_message_id: Option<String>,
|
||||
responsesapi_client_metadata: Option<HashMap<String, String>>,
|
||||
) -> Result<String, SteerInputError> {
|
||||
self.session
|
||||
.steer_input(
|
||||
input,
|
||||
additional_context,
|
||||
expected_turn_id,
|
||||
client_user_message_id,
|
||||
responsesapi_client_metadata,
|
||||
/*incoming_turn_metadata*/ None,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Injects model-visible items into the currently active turn.
|
||||
///
|
||||
/// This is the thread-level bridge to `Session::inject_if_running` for
|
||||
@@ -394,26 +346,6 @@ impl CodexThread {
|
||||
self.session.inject_if_running(items).await
|
||||
}
|
||||
|
||||
/// Starts an automatic regular turn with response items or user input only
|
||||
/// when idle work is allowed for this thread.
|
||||
///
|
||||
/// This is the required entry point for extensions that want to launch
|
||||
/// model-visible work from `ThreadLifecycleContributor::on_thread_idle`.
|
||||
/// The call succeeds only if no user/client-triggered turn is queued and no
|
||||
/// task is currently active. Work without user input is also rejected in
|
||||
/// Plan mode. Active Review tasks are rejected by the active-task check
|
||||
/// because Review turns are not steerable.
|
||||
///
|
||||
/// On rejection, the returned error includes a stable reason and carries
|
||||
/// the original `items` unchanged so the caller can decide whether to drop
|
||||
/// them, retry later, or log why no automatic turn was started.
|
||||
pub async fn try_start_turn_if_idle(
|
||||
&self,
|
||||
items: Vec<TurnInput>,
|
||||
) -> Result<(), TryStartTurnIfIdleError> {
|
||||
self.session.try_start_turn_if_idle(items).await
|
||||
}
|
||||
|
||||
pub async fn set_app_server_client_info(
|
||||
&self,
|
||||
app_server_client_name: Option<String>,
|
||||
@@ -484,13 +416,6 @@ impl CodexThread {
|
||||
}
|
||||
}
|
||||
|
||||
/// Use sparingly: this is intended to be removed soon.
|
||||
pub async fn submit_with_id(&self, mut sub: Submission) -> CodexResult<()> {
|
||||
sub.parent_turn_id = None;
|
||||
sub.root_turn_id = None;
|
||||
self.io.submit_with_id(sub).await
|
||||
}
|
||||
|
||||
pub async fn next_event(&self) -> CodexResult<Event> {
|
||||
self.io.next_event().await
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user