mirror of
https://github.com/openai/codex.git
synced 2026-11-27 23:50:52 +00:00
## Why Dynamic tool clients could return JSON as text in `contentItems`, so Code Mode scripts had to parse that text to access fields in the result. ## What changed App server dynamic tool requests advertise `supportedResultFormat: "structuredContent"`. Clients can reply with `structuredContent` and a `success` flag, report a failure with `errorMessage` and `success: false`, or continue using `contentItems`. Code Mode exposes structured replies as MCP-style tool results, with the original JSON under `structuredContent` and failure status in `isError`. Completed tool items include a text representation of the reply. Matching post-tool-use hooks can receive the structured result for successful calls. ## Testing Add protocol tests for the wire formats and rejection of ambiguous replies, plus an app server integration test that exercises structured results, content items, and errors through Code Mode. GitOrigin-RevId: d63152633b43bd5bd236f6e0dcb41ee7e98e7947
1078 lines
41 KiB
Rust
1078 lines
41 KiB
Rust
use super::Submission;
|
|
use super::sampling_interrupt::SamplingInterrupt;
|
|
use super::submission::SubmissionOp;
|
|
use crate::McpRefreshReason;
|
|
use crate::WithTurnExtensionData;
|
|
use crate::realtime_conversation::handle_audio as handle_realtime_conversation_audio;
|
|
use crate::realtime_conversation::handle_close as handle_realtime_conversation_close;
|
|
use crate::realtime_conversation::handle_speech as handle_realtime_conversation_speech;
|
|
use crate::realtime_conversation::handle_start as handle_realtime_conversation_start;
|
|
use crate::realtime_conversation::handle_text as handle_realtime_conversation_text;
|
|
use async_channel::Receiver;
|
|
use codex_features::Feature;
|
|
use codex_otel::set_parent_from_w3c_trace_context;
|
|
use tracing::Instrument;
|
|
use tracing::debug_span;
|
|
use tracing::info_span;
|
|
|
|
use crate::session::session::Session;
|
|
use crate::session::thread_settings;
|
|
use crate::session::turn_input;
|
|
|
|
use crate::config::Config;
|
|
use crate::context::ContextualUserFragment;
|
|
use crate::context::GuardianApprovedAction;
|
|
use crate::review_prompts::resolve_review_request;
|
|
use crate::session::spawn_review_thread;
|
|
use crate::tasks::CompactTask;
|
|
use crate::tasks::UserShellCommandMode;
|
|
use crate::tasks::UserShellCommandTask;
|
|
use crate::tasks::execute_user_shell_command;
|
|
use crate::thread_manager::AgentTreeShutdownFailure;
|
|
use crate::thread_manager::thread_store_error_kind;
|
|
use codex_protocol::approvals::ExecApprovalKind;
|
|
use codex_protocol::error::CodexErr;
|
|
use codex_protocol::protocol::CodexErrorInfo;
|
|
use codex_protocol::protocol::ErrorEvent;
|
|
use codex_protocol::protocol::Event;
|
|
use codex_protocol::protocol::EventMsg;
|
|
use codex_protocol::protocol::GuardianAssessmentEvent;
|
|
use codex_protocol::protocol::GuardianAssessmentStatus;
|
|
use codex_protocol::protocol::Op;
|
|
use codex_protocol::protocol::RealtimeConversationListVoicesResponseEvent;
|
|
use codex_protocol::protocol::RealtimeVoicesList;
|
|
use codex_protocol::protocol::ReviewDecision;
|
|
use codex_protocol::protocol::ReviewRequest;
|
|
use codex_protocol::protocol::ThreadMemoryMode;
|
|
use codex_protocol::protocol::TurnAbortReason;
|
|
use codex_protocol::protocol::WarningEvent;
|
|
use codex_protocol::request_permissions::RequestPermissionsResponse;
|
|
use codex_protocol::request_user_input::RequestUserInputResponse;
|
|
use codex_thread_store::PersistContext;
|
|
|
|
use crate::context_manager::is_instruction_turn_boundary;
|
|
use codex_protocol::dynamic_tools::DynamicToolCallResult;
|
|
use codex_protocol::mcp::RequestId as ProtocolRequestId;
|
|
use codex_protocol::protocol::AgentStatus;
|
|
use codex_rmcp_client::ElicitationAction;
|
|
use codex_rmcp_client::ElicitationResponse;
|
|
use serde_json::Value;
|
|
use std::sync::Arc;
|
|
use tracing::debug;
|
|
use tracing::info;
|
|
use tracing::warn;
|
|
|
|
pub async fn interrupt(sess: &Arc<Session>) {
|
|
sess.interrupt_task(sess.active_turn.lock().await).await;
|
|
}
|
|
|
|
pub async fn clean_background_terminals(sess: &Arc<Session>) {
|
|
sess.close_unified_exec_processes().await;
|
|
}
|
|
|
|
pub async fn realtime_conversation_list_voices(sess: &Session, sub_id: String) {
|
|
sess.send_event_raw(Event {
|
|
id: sub_id,
|
|
msg: EventMsg::RealtimeConversationListVoicesResponse(
|
|
RealtimeConversationListVoicesResponseEvent {
|
|
voices: RealtimeVoicesList::builtin(),
|
|
},
|
|
),
|
|
})
|
|
.await;
|
|
}
|
|
|
|
/// Queues an inter-agent message, then lets the shared pending-work scheduler
|
|
/// decide whether an idle session should start a regular turn.
|
|
pub async fn inter_agent_communication(
|
|
sess: &Arc<Session>,
|
|
sub_id: String,
|
|
communication: crate::PendingAgentMessage,
|
|
start_options: codex_protocol::turn_input::TurnStartOptions,
|
|
) {
|
|
let trigger_turn = communication.trigger_turn;
|
|
sess.input_queue
|
|
.enqueue_mailbox_communication(communication, start_options)
|
|
.await;
|
|
crate::agent_communication::emit_agent_communication_receive(&sub_id);
|
|
if trigger_turn
|
|
|| sess.features.enabled(Feature::WakeOnAgentMessages)
|
|
|| sess.has_outstanding_durable_sleep()
|
|
{
|
|
sess.maybe_start_turn_for_pending_work_with_sub_id(sub_id)
|
|
.await;
|
|
}
|
|
}
|
|
|
|
pub async fn run_user_shell_command(
|
|
sess: &Arc<Session>,
|
|
sub_id: String,
|
|
command: String,
|
|
timeout_ms: Option<u64>,
|
|
) {
|
|
if let Some((turn_context, cancellation_token)) =
|
|
sess.active_turn_context_and_cancellation_token().await
|
|
{
|
|
let session = Arc::clone(sess);
|
|
tokio::spawn(async move {
|
|
execute_user_shell_command(
|
|
session,
|
|
turn_context,
|
|
command,
|
|
timeout_ms,
|
|
cancellation_token,
|
|
UserShellCommandMode::ActiveTurnAuxiliary,
|
|
)
|
|
.await;
|
|
});
|
|
return;
|
|
}
|
|
|
|
let turn_context = sess
|
|
.new_turn_with_default_settings(sub_id, Default::default())
|
|
.await;
|
|
sess.spawn_task(
|
|
turn_context,
|
|
Vec::new(),
|
|
UserShellCommandTask::new(command, timeout_ms),
|
|
)
|
|
.await;
|
|
}
|
|
|
|
pub async fn resolve_elicitation(
|
|
sess: &Arc<Session>,
|
|
server_name: String,
|
|
request_id: ProtocolRequestId,
|
|
decision: codex_protocol::approvals::ElicitationAction,
|
|
content: Option<Value>,
|
|
meta: Option<Value>,
|
|
) {
|
|
let action = match decision {
|
|
codex_protocol::approvals::ElicitationAction::Accept => ElicitationAction::Accept,
|
|
codex_protocol::approvals::ElicitationAction::Decline => ElicitationAction::Decline,
|
|
codex_protocol::approvals::ElicitationAction::Cancel => ElicitationAction::Cancel,
|
|
};
|
|
let content = match action {
|
|
// Preserve the legacy fallback for clients that only send an action.
|
|
ElicitationAction::Accept => Some(content.unwrap_or_else(|| serde_json::json!({}))),
|
|
ElicitationAction::Decline | ElicitationAction::Cancel => None,
|
|
_ => None,
|
|
};
|
|
let response = ElicitationResponse {
|
|
action,
|
|
content,
|
|
meta,
|
|
};
|
|
let request_id = match request_id {
|
|
ProtocolRequestId::String(value) => {
|
|
rmcp::model::NumberOrString::String(std::sync::Arc::from(value))
|
|
}
|
|
ProtocolRequestId::Integer(value) => rmcp::model::NumberOrString::Number(value),
|
|
};
|
|
if let Err(err) = sess
|
|
.resolve_elicitation(server_name, request_id, response)
|
|
.await
|
|
{
|
|
warn!(
|
|
error = %err,
|
|
"failed to resolve elicitation request in session"
|
|
);
|
|
}
|
|
}
|
|
|
|
impl Session {
|
|
/// Claim the prompt before applying a decision that can outlive the requesting execution.
|
|
pub(crate) async fn resolve_exec_approval(
|
|
self: &Arc<Self>,
|
|
approval_id: String,
|
|
turn_id: Option<String>,
|
|
decision: ReviewDecision,
|
|
) {
|
|
let Some((pending, active_turn_id)) = self
|
|
.take_pending_approval(&approval_id, turn_id.as_deref())
|
|
.await
|
|
else {
|
|
return;
|
|
};
|
|
let decision = pending.validate(decision);
|
|
if decision == ReviewDecision::Abort {
|
|
let turn_id = if pending.kind == ExecApprovalKind::HumanCommand {
|
|
Some(&pending.turn_id)
|
|
} else {
|
|
active_turn_id.as_ref()
|
|
};
|
|
if let Some(turn_id) = turn_id {
|
|
self.abort_turn_if_active(
|
|
turn_id,
|
|
TurnAbortReason::Interrupted,
|
|
/*error*/ None,
|
|
)
|
|
.await;
|
|
}
|
|
} else if let ReviewDecision::ApprovedExecpolicyAmendment {
|
|
proposed_execpolicy_amendment,
|
|
} = &decision
|
|
&& let Err(err) = self
|
|
.persist_execpolicy_amendment(proposed_execpolicy_amendment)
|
|
.await
|
|
{
|
|
let message = format!("Failed to apply execpolicy amendment: {err}");
|
|
tracing::warn!("{message}");
|
|
self.send_event_raw(Event {
|
|
id: turn_id.unwrap_or(approval_id),
|
|
msg: EventMsg::Warning(WarningEvent { message }),
|
|
})
|
|
.await;
|
|
}
|
|
let _ = pending.sender.send(decision);
|
|
}
|
|
}
|
|
|
|
async fn cancel_patch_approval(sess: &Arc<Session>, id: &str, expected_turn_id: Option<&str>) {
|
|
let Some((pending, _)) = sess.take_pending_approval(id, expected_turn_id).await else {
|
|
return;
|
|
};
|
|
sess.abort_turn_if_active(
|
|
&pending.turn_id,
|
|
TurnAbortReason::Interrupted,
|
|
/*error*/ None,
|
|
)
|
|
.await;
|
|
let _ = pending.sender.send(ReviewDecision::Abort);
|
|
}
|
|
|
|
pub async fn request_user_input_response(
|
|
sess: &Arc<Session>,
|
|
id: String,
|
|
response: RequestUserInputResponse,
|
|
) {
|
|
sess.notify_user_input_response(&id, response).await;
|
|
}
|
|
|
|
pub async fn request_permissions_response(
|
|
sess: &Arc<Session>,
|
|
id: String,
|
|
response: RequestPermissionsResponse,
|
|
) {
|
|
sess.notify_request_permissions_response(&id, response)
|
|
.await;
|
|
}
|
|
|
|
pub async fn dynamic_tool_response(
|
|
sess: &Arc<Session>,
|
|
id: String,
|
|
response: DynamicToolCallResult,
|
|
) {
|
|
sess.notify_dynamic_tool_response(&id, response).await;
|
|
}
|
|
|
|
pub fn refresh_mcp_servers(sess: &Session) {
|
|
sess.services.mcp_runtime.reconnect_on_next_refresh();
|
|
sess.request_mcp_runtime_refresh(McpRefreshReason::ExplicitServerReconnect);
|
|
}
|
|
|
|
pub async fn reload_user_config(sess: &Arc<Session>) {
|
|
Box::pin(sess.reload_user_config_layer()).await;
|
|
}
|
|
|
|
pub async fn compact(sess: &Arc<Session>, sub_id: String) {
|
|
let local_reset = sess.enabled(Feature::TokenBudget);
|
|
// Reject invalid settings before interrupting. Ordinary turn construction
|
|
// validates again after teardown, when a Guardian refresh may have landed.
|
|
let admission = if local_reset {
|
|
Ok(())
|
|
} else {
|
|
let state = sess.state.lock().await;
|
|
let configuration = &state.session_configuration;
|
|
configuration.validate(&configuration.environments)
|
|
};
|
|
if let Err(error) = admission {
|
|
let message = format!("Cannot start /compact. {error}");
|
|
// Keep the active turn's status and order the notice with turn registration.
|
|
let active = sess.active_turn.lock().await;
|
|
let status = sess.agent_status.borrow();
|
|
let turn_in_progress = active
|
|
.as_ref()
|
|
.is_some_and(|turn| turn.task.is_some() || matches!(*status, AgentStatus::Running));
|
|
let msg = if turn_in_progress {
|
|
EventMsg::Warning(WarningEvent { message })
|
|
} else {
|
|
drop(status);
|
|
sess.agent_status
|
|
.send_replace(AgentStatus::Errored(message.clone()));
|
|
EventMsg::Error(ErrorEvent {
|
|
misalignment: None,
|
|
message,
|
|
codex_error_info: Some(CodexErrorInfo::BadRequest),
|
|
})
|
|
};
|
|
if let Err(error) = sess.tx_event.try_send(Event { id: sub_id, msg }) {
|
|
debug!(%error, "dropping compaction rejection because the event channel is closed");
|
|
}
|
|
return;
|
|
}
|
|
// Stop the old turn before the compact task picks up the next turn's environments.
|
|
sess.abort_all_tasks(TurnAbortReason::Replaced).await;
|
|
let turn_context = if local_reset {
|
|
sess.new_turn_with_default_settings(sub_id, Default::default())
|
|
.await
|
|
} else {
|
|
let Ok((turn_context, _)) = sess
|
|
.new_turn_with_sub_id(sub_id, Default::default(), Default::default())
|
|
.await
|
|
else {
|
|
return;
|
|
};
|
|
turn_context
|
|
};
|
|
|
|
sess.spawn_task(turn_context, Vec::new(), CompactTask).await;
|
|
}
|
|
|
|
pub(super) async fn persist_thread_memory_mode_update(
|
|
sess: &Arc<Session>,
|
|
mode: ThreadMemoryMode,
|
|
) -> anyhow::Result<()> {
|
|
let live_thread = sess.live_thread_for_persistence("update thread memory mode")?;
|
|
live_thread.persist(PersistContext::Standard).await?;
|
|
live_thread.flush().await?;
|
|
live_thread
|
|
.update_memory_mode(mode, /*include_archived*/ false)
|
|
.await?;
|
|
live_thread.flush().await?;
|
|
Ok(())
|
|
}
|
|
|
|
/// Persists thread-level memory mode metadata for the active session.
|
|
///
|
|
/// This does not involve the model and only affects whether the thread is
|
|
/// eligible for future memory generation.
|
|
pub async fn set_thread_memory_mode(sess: &Arc<Session>, sub_id: String, mode: ThreadMemoryMode) {
|
|
if let Err(err) = persist_thread_memory_mode_update(sess, mode).await {
|
|
warn!("Failed to persist thread memory mode update to rollout: {err}");
|
|
let event = Event {
|
|
id: sub_id,
|
|
msg: EventMsg::Error(ErrorEvent {
|
|
misalignment: None,
|
|
message: err.to_string(),
|
|
codex_error_info: Some(CodexErrorInfo::Other),
|
|
}),
|
|
};
|
|
sess.send_event_raw(event).await;
|
|
}
|
|
}
|
|
|
|
pub(super) async fn shutdown_session_runtime(sess: &Arc<Session>) {
|
|
if let Some(reporting) = &sess.outcome_reporting {
|
|
reporting.handoffs.close();
|
|
}
|
|
let runtime = &sess.services.local_agent_runtime;
|
|
let wakes_root = runtime.suspension_root() == Some(sess.thread_id)
|
|
&& (sess.has_outstanding_durable_sleep() || sess.should_wake_on_agent_messages().await);
|
|
let startup_prewarm = {
|
|
let mut state = sess.state.lock().await;
|
|
// Stop admission and take the current warmup together so resume cannot replace it.
|
|
state.shutting_down = true;
|
|
state.take_session_startup_prewarm()
|
|
};
|
|
if let Some(startup_prewarm) = startup_prewarm {
|
|
startup_prewarm.abort().await;
|
|
}
|
|
let (conversation_shutdown, ()) = tokio::join!(
|
|
sess.conversation.shutdown(),
|
|
sess.abort_all_tasks(TurnAbortReason::Interrupted),
|
|
);
|
|
if let Err(err) = conversation_shutdown {
|
|
warn!("failed to shut down realtime conversation: {err}");
|
|
}
|
|
if let Some(reporting) = &sess.outcome_reporting {
|
|
reporting.handoffs.wait().await;
|
|
}
|
|
if runtime.suspension_root().is_some() {
|
|
let pending: Vec<_> = sess
|
|
.input_queue
|
|
.drain_mailbox()
|
|
.await
|
|
.into_iter()
|
|
.map(|mail| mail.communication)
|
|
.filter(crate::PendingAgentMessage::is_terminal_result)
|
|
.collect();
|
|
if !pending.is_empty() && sess.live_thread().is_some() {
|
|
let turn_id = {
|
|
let state = sess.state.lock().await;
|
|
state.last_started_turn_id.clone().or_else(|| {
|
|
state
|
|
.turn_attribution
|
|
.as_ref()
|
|
.map(|turn| turn.turn_id.clone())
|
|
})
|
|
};
|
|
if wakes_root {
|
|
if let Some(turn_id) = turn_id.as_ref() {
|
|
runtime.record_root_wake_after(turn_id.clone());
|
|
} else {
|
|
runtime.record_shutdown_failure(AgentTreeShutdownFailure::operation_failed(
|
|
"tree_suspension",
|
|
"record_root_wake",
|
|
Some(sess.thread_id),
|
|
"missing_previous_turn",
|
|
));
|
|
}
|
|
}
|
|
let context = sess
|
|
.new_turn_with_default_settings(
|
|
turn_id.unwrap_or_else(super::new_submission_id),
|
|
Default::default(),
|
|
)
|
|
.await;
|
|
for result in pending {
|
|
sess.record_inter_agent_communication(&context, context.model_info(), result)
|
|
.await;
|
|
}
|
|
}
|
|
}
|
|
super::async_compaction::shutdown(sess).await;
|
|
let shell_snapshot_prewarm = sess.state.lock().await.shell_snapshot_prewarm.take();
|
|
if let Some(shell_snapshot_prewarm) = shell_snapshot_prewarm {
|
|
shell_snapshot_prewarm.abort();
|
|
let _ = shell_snapshot_prewarm.await;
|
|
}
|
|
sess.hooks().shutdown().await;
|
|
sess.async_hook_results.close();
|
|
while sess.async_hook_results.try_recv().is_ok() {}
|
|
sess.services
|
|
.unified_exec_manager
|
|
.terminate_all_processes()
|
|
.await;
|
|
if let Err(err) = sess.services.code_mode_service.shutdown().await {
|
|
sess.services.local_agent_runtime.record_shutdown_failure(
|
|
AgentTreeShutdownFailure::operation_failed(
|
|
"session_shutdown",
|
|
"code_mode",
|
|
Some(sess.thread_id),
|
|
"code_mode_error",
|
|
),
|
|
);
|
|
warn!("failed to shutdown code mode session: {err}");
|
|
}
|
|
sess.stop_mcp_prewarm_worker().await;
|
|
{
|
|
let _refresh = sess.mcp_refresh.acquire().await;
|
|
sess.mcp_refresh.close();
|
|
}
|
|
sess.wait_for_apps_tool_refresh().await;
|
|
sess.services.mcp_runtime.shutdown().await;
|
|
|
|
sess.drain_code_mode_messages().await;
|
|
|
|
crate::hook_runtime::run_session_end_hooks(sess).await;
|
|
emit_thread_stop_lifecycle(sess).await;
|
|
}
|
|
|
|
async fn emit_thread_stop_lifecycle(sess: &Session) {
|
|
for contributor in sess.services.extensions.thread_lifecycle_contributors() {
|
|
contributor
|
|
.on_thread_stop(codex_extension_api::ThreadStopInput {
|
|
session_store: &sess.services.session_extension_data,
|
|
thread_store: &sess.services.thread_extension_data,
|
|
})
|
|
.await;
|
|
}
|
|
}
|
|
|
|
pub async fn shutdown(sess: &Arc<Session>, sub_id: String) -> bool {
|
|
shutdown_session_runtime(sess).await;
|
|
info!("Shutting down Codex instance");
|
|
let history = sess.clone_history().await;
|
|
let turn_count = history
|
|
.annotated_items()
|
|
.iter()
|
|
.filter(|item| is_instruction_turn_boundary(item))
|
|
.count();
|
|
sess.services.session_telemetry.counter(
|
|
"codex.conversation.turn.count",
|
|
i64::try_from(turn_count).unwrap_or(0),
|
|
&[],
|
|
);
|
|
|
|
// Gracefully flush and shutdown thread persistence on session end so tests
|
|
// that inspect durable state do not race with the background writer.
|
|
if let Some(live_thread) = sess.live_thread()
|
|
&& let Err(e) = live_thread.shutdown().await
|
|
{
|
|
sess.services.local_agent_runtime.record_shutdown_failure(
|
|
AgentTreeShutdownFailure::operation_failed(
|
|
"session_shutdown",
|
|
"close_persistence",
|
|
Some(sess.thread_id),
|
|
thread_store_error_kind(&e),
|
|
),
|
|
);
|
|
warn!("failed to shutdown thread persistence: {e}");
|
|
let event = Event {
|
|
id: sub_id.clone(),
|
|
msg: EventMsg::Error(ErrorEvent {
|
|
misalignment: None,
|
|
message: "Failed to shutdown thread persistence".to_string(),
|
|
codex_error_info: Some(CodexErrorInfo::Other),
|
|
}),
|
|
};
|
|
sess.send_event_raw(event).await;
|
|
}
|
|
|
|
let event = Event {
|
|
id: sub_id,
|
|
msg: EventMsg::ShutdownComplete,
|
|
};
|
|
sess.services
|
|
.rollout_thread_trace
|
|
.record_protocol_event(&event.msg);
|
|
sess.services
|
|
.rollout_thread_trace
|
|
.record_ended(codex_rollout_trace::RolloutStatus::Completed);
|
|
sess.deliver_event_raw(event).await;
|
|
true
|
|
}
|
|
|
|
pub async fn review(
|
|
sess: &Arc<Session>,
|
|
config: &Arc<Config>,
|
|
sub_id: String,
|
|
review_request: ReviewRequest,
|
|
) {
|
|
let turn_context = sess
|
|
.new_turn_with_default_settings(sub_id.clone(), Default::default())
|
|
.await;
|
|
sess.maybe_emit_model_warnings_for_turn(turn_context.as_ref())
|
|
.await;
|
|
#[allow(deprecated)]
|
|
match resolve_review_request(review_request, &turn_context.cwd) {
|
|
Ok(resolved) => {
|
|
spawn_review_thread(
|
|
Arc::clone(sess),
|
|
Arc::clone(config),
|
|
turn_context.clone(),
|
|
sub_id,
|
|
resolved,
|
|
)
|
|
.await;
|
|
}
|
|
Err(err) => {
|
|
let event = Event {
|
|
id: sub_id,
|
|
msg: EventMsg::Error(ErrorEvent {
|
|
misalignment: None,
|
|
message: err.to_string(),
|
|
codex_error_info: Some(CodexErrorInfo::Other),
|
|
}),
|
|
};
|
|
sess.send_event(&turn_context, event.msg).await;
|
|
}
|
|
}
|
|
}
|
|
|
|
pub(super) async fn submission_loop(
|
|
sess: Arc<Session>,
|
|
config: Arc<Config>,
|
|
rx_sub: Receiver<Box<Submission>>,
|
|
) {
|
|
// Session shutdown and tree shutdown both use the existing teardown handler.
|
|
let mut shutdown_received = false;
|
|
let mut admission_updates = sess.services.extensions.turn_start_admission_updates();
|
|
let mut catalog_updates = sess.services.models_manager.model_catalog_updates();
|
|
if let Some(updates) = &mut catalog_updates {
|
|
// A resumed chat must also consume a catalog fetched before it was opened.
|
|
updates.mark_changed();
|
|
}
|
|
let mut mailbox = sess.input_queue.mailbox_updates();
|
|
if let Some(updates) = &mut mailbox {
|
|
updates.mark_changed();
|
|
}
|
|
loop {
|
|
let sub = tokio::select! {
|
|
biased;
|
|
_ = sess.services.local_agent_runtime.shutdown.cancelled() => {
|
|
if sess.services.local_agent_runtime.suspension_root().is_some() {
|
|
// Keep accepting results until all direct children stop, then drain
|
|
// buffered submissions before deciding which parent work to hand off.
|
|
let runtime = &sess.services.local_agent_runtime;
|
|
tokio::join!(
|
|
async {
|
|
runtime.wait_for_children(sess.thread_id).await;
|
|
rx_sub.close();
|
|
},
|
|
async {
|
|
while let Ok(sub) = rx_sub.recv().await {
|
|
if let SubmissionOp::Protocol(op) = sub.op
|
|
&& let Op::InterAgentCommunication { communication, start_options } = *op
|
|
&& sub.message_delivery.as_ref().is_some_and(crate::agent_communication::MessageDelivery::awaits_result_write)
|
|
{
|
|
let mail = crate::PendingAgentMessage::new(communication, sub.message_delivery);
|
|
inter_agent_communication(&sess, sub.id, mail, start_options).await;
|
|
}
|
|
}
|
|
},
|
|
);
|
|
}
|
|
shutdown_received = super::turn_suspension::stop_tree_member(&sess).await;
|
|
break;
|
|
}
|
|
update = async {
|
|
match &mut catalog_updates {
|
|
Some(updates) => updates.changed().await,
|
|
None => std::future::pending().await,
|
|
}
|
|
} => {
|
|
if update.is_err() {
|
|
catalog_updates = None;
|
|
} else {
|
|
super::model_catalog_settings::apply(&sess).await;
|
|
}
|
|
continue;
|
|
}
|
|
sub = rx_sub.recv() => match sub {
|
|
Ok(sub) => *sub,
|
|
Err(_) => break,
|
|
},
|
|
_ = sess.input_queue.pending_work_wake.notified() => {
|
|
sess.maybe_start_turn_for_pending_work().await;
|
|
continue;
|
|
}
|
|
update = async {
|
|
match &mut admission_updates {
|
|
Some(updates) => updates.changed().await,
|
|
None => std::future::pending().await,
|
|
}
|
|
} => {
|
|
if update.is_err() {
|
|
admission_updates = None;
|
|
} else {
|
|
// Recheck the normal gate: another pause or shutdown may have
|
|
// begun since this notification, and mail must remain queued.
|
|
sess.maybe_start_turn_for_pending_work().await;
|
|
}
|
|
continue;
|
|
}
|
|
update = async {
|
|
match &mut mailbox {
|
|
Some(updates) => updates.changed().await.map(|()| *updates.borrow_and_update()),
|
|
None => std::future::pending().await,
|
|
}
|
|
} => {
|
|
match update {
|
|
Ok(true) => {
|
|
sess.input_queue.notify_mailbox();
|
|
if sess.features.enabled(Feature::WakeOnAgentMessages)
|
|
|| sess.has_outstanding_durable_sleep()
|
|
{
|
|
sess.maybe_start_turn_for_pending_work().await;
|
|
}
|
|
}
|
|
Ok(false) => {}
|
|
Err(_) => mailbox = None,
|
|
}
|
|
continue;
|
|
}
|
|
};
|
|
debug!(
|
|
thread_id = %sess.thread_id(),
|
|
submission_id = %sub.id,
|
|
operation = sub.op.kind(),
|
|
parent_turn_id = ?sub.parent_turn_id,
|
|
root_turn_id = ?sub.root_turn_id,
|
|
op = ?sub.op,
|
|
"Submission"
|
|
);
|
|
let dispatch_span = submission_dispatch_span(&sub);
|
|
let should_exit = async {
|
|
let op = match sub.op {
|
|
SubmissionOp::TurnInput {
|
|
request,
|
|
mode,
|
|
reply,
|
|
} => {
|
|
let request = WithTurnExtensionData {
|
|
request: *request,
|
|
turn_extension_init: sub.turn_extension_init,
|
|
};
|
|
let result = turn_input::handle(&sess, request, mode, sub.id.clone()).await;
|
|
let _ = reply.send(result);
|
|
return false;
|
|
}
|
|
SubmissionOp::Protocol(op) => *op,
|
|
};
|
|
match op {
|
|
Op::Interrupt => {
|
|
interrupt(&sess).await;
|
|
false
|
|
}
|
|
Op::InterruptAgent => {
|
|
SamplingInterrupt::request(&sess).await;
|
|
false
|
|
}
|
|
Op::InterruptIfNoPendingInput { turn_id, reply } => {
|
|
sess.interrupt_turn_if_no_pending_input(&turn_id, reply)
|
|
.await;
|
|
false
|
|
}
|
|
Op::CleanBackgroundTerminals => {
|
|
clean_background_terminals(&sess).await;
|
|
false
|
|
}
|
|
Op::RealtimeConversationStart(params) => {
|
|
if let Err(err) =
|
|
handle_realtime_conversation_start(&sess, sub.id.clone(), params).await
|
|
{
|
|
sess.send_event_raw(Event {
|
|
id: sub.id.clone(),
|
|
msg: EventMsg::Error(ErrorEvent {
|
|
misalignment: None,
|
|
message: err.to_string(),
|
|
codex_error_info: Some(CodexErrorInfo::Other),
|
|
}),
|
|
})
|
|
.await;
|
|
}
|
|
false
|
|
}
|
|
Op::RealtimeConversationAttach {
|
|
params,
|
|
options,
|
|
reply,
|
|
} => {
|
|
let result =
|
|
crate::realtime_conversation::handle_attach(&sess, sub.id, params, options)
|
|
.await;
|
|
let _ = reply.send(result);
|
|
false
|
|
}
|
|
Op::RealtimeConversationAttachStream {
|
|
params,
|
|
transport,
|
|
reply,
|
|
} => {
|
|
let result = crate::realtime_conversation::handle_attach_stream(
|
|
&sess, sub.id, params, transport,
|
|
)
|
|
.await;
|
|
let _ = reply.send(result);
|
|
false
|
|
}
|
|
Op::RealtimeConversationEnd { realtime_session_id, reply } => {
|
|
crate::realtime_conversation::handle_end(&sess, sub.id, &realtime_session_id, reply).await;
|
|
false
|
|
}
|
|
Op::RealtimeConversationDetach {
|
|
realtime_session_id,
|
|
reply,
|
|
} => {
|
|
crate::realtime_conversation::handle_detach(&sess, &realtime_session_id, reply)
|
|
.await;
|
|
false
|
|
}
|
|
Op::RealtimeConversationAudio(params) => {
|
|
handle_realtime_conversation_audio(&sess, sub.id.clone(), params).await;
|
|
false
|
|
}
|
|
Op::RealtimeConversationText(params) => {
|
|
handle_realtime_conversation_text(&sess, sub.id.clone(), params).await;
|
|
false
|
|
}
|
|
Op::RealtimeConversationSpeech(params) => {
|
|
handle_realtime_conversation_speech(&sess, sub.id.clone(), params).await;
|
|
false
|
|
}
|
|
Op::RealtimeConversationClose => {
|
|
handle_realtime_conversation_close(&sess, sub.id.clone()).await;
|
|
false
|
|
}
|
|
Op::RealtimeConversationListVoices => {
|
|
realtime_conversation_list_voices(&sess, sub.id.clone()).await;
|
|
false
|
|
}
|
|
Op::RecoverTurn {
|
|
thread_settings,
|
|
start_options,
|
|
reply,
|
|
} => {
|
|
let result = turn_input::handle_recovery(
|
|
&sess,
|
|
WithTurnExtensionData {
|
|
request: thread_settings,
|
|
turn_extension_init: sub.turn_extension_init,
|
|
},
|
|
start_options,
|
|
sub.id.clone(),
|
|
)
|
|
.await;
|
|
let _ = reply.send(result);
|
|
false
|
|
}
|
|
Op::SuspendTurnAndShutdown { reply } => {
|
|
let result =
|
|
super::turn_suspension::suspend_turn_and_shutdown(&sess, sub.id.clone())
|
|
.await;
|
|
// Exit only after history is durable and its writer has closed; an error
|
|
// must leave responsibility for the thread with the current worker.
|
|
let should_exit = matches!(
|
|
&result,
|
|
Ok(codex_protocol::turn_input::SuspendTurnOutcome::Suspended { .. })
|
|
);
|
|
let _ = reply.send(result);
|
|
should_exit
|
|
}
|
|
Op::ThreadSettings {
|
|
thread_settings,
|
|
reply,
|
|
} => {
|
|
let _settings_guard = thread_settings::acquire_persistence_lock(&sess).await;
|
|
let thread_settings = WithTurnExtensionData {
|
|
request: thread_settings,
|
|
turn_extension_init: sub.turn_extension_init,
|
|
};
|
|
match thread_settings::update(&sess, thread_settings, reply.is_some()).await {
|
|
Ok(commit) => {
|
|
match (reply, commit.host_acceptance) {
|
|
(Some(mut reply), Some(acceptance)) => {
|
|
// Leave the submission loop free to process interrupts.
|
|
tokio::spawn(async move {
|
|
tokio::select! {
|
|
_ = reply.closed() => {}
|
|
result = acceptance => {
|
|
let result = result.map_err(|error| {
|
|
CodexErr::from(std::io::Error::other(format!(
|
|
"service tier committed locally; host acceptance unconfirmed: {error}"
|
|
)))
|
|
});
|
|
let _ = reply.send(result);
|
|
}
|
|
}
|
|
});
|
|
}
|
|
(Some(reply), None) => {
|
|
// The caller may hold a lock its event consumer needs.
|
|
let _ = reply.send(Ok(()));
|
|
}
|
|
(None, _) => {}
|
|
}
|
|
thread_settings::emit_applied(&sess, sub.id.clone(), commit.snapshot)
|
|
.await;
|
|
}
|
|
Err(error) => {
|
|
let message = format!("invalid thread settings override: {error}");
|
|
if let Some(reply) = reply {
|
|
let _ = reply.send(Err(CodexErr::InvalidRequest(message)));
|
|
} else {
|
|
sess.send_event_raw(Event {
|
|
id: sub.id.clone(),
|
|
msg: EventMsg::Error(ErrorEvent {
|
|
misalignment: None,
|
|
message,
|
|
codex_error_info: Some(CodexErrorInfo::BadRequest),
|
|
}),
|
|
})
|
|
.await;
|
|
}
|
|
}
|
|
}
|
|
false
|
|
}
|
|
Op::ReplaceDynamicTools { tools, reply } => {
|
|
let _ = reply.send(sess.replace_dynamic_tools(tools).await);
|
|
false
|
|
}
|
|
Op::TurnSettings {
|
|
turn_id,
|
|
update,
|
|
reply,
|
|
} => {
|
|
let outcome = sess.apply_turn_settings(&turn_id, update).await;
|
|
let _ = reply.send(outcome);
|
|
false
|
|
}
|
|
Op::InterAgentCommunication {
|
|
communication,
|
|
start_options,
|
|
} => {
|
|
let communication =
|
|
crate::PendingAgentMessage::new(communication, sub.message_delivery);
|
|
inter_agent_communication(&sess, sub.id.clone(), communication, start_options)
|
|
.await;
|
|
false
|
|
}
|
|
Op::ExecApproval {
|
|
id: approval_id,
|
|
turn_id,
|
|
decision,
|
|
} => {
|
|
sess.resolve_exec_approval(approval_id, turn_id, decision)
|
|
.await;
|
|
false
|
|
}
|
|
Op::CancelPatchApproval { id, turn_id } => {
|
|
cancel_patch_approval(&sess, &id, Some(&turn_id)).await;
|
|
false
|
|
}
|
|
Op::PatchApproval {
|
|
id,
|
|
decision: ReviewDecision::Abort,
|
|
} => {
|
|
cancel_patch_approval(&sess, &id, /*expected_turn_id*/ None).await;
|
|
false
|
|
}
|
|
Op::PatchApproval { id, decision } => {
|
|
sess.notify_approval(&id, decision).await;
|
|
false
|
|
}
|
|
Op::UserInputAnswer { id, response } => {
|
|
request_user_input_response(&sess, id, response).await;
|
|
false
|
|
}
|
|
Op::RequestPermissionsResponse { id, response } => {
|
|
request_permissions_response(&sess, id, response).await;
|
|
false
|
|
}
|
|
Op::DynamicToolResponse { id, response } => {
|
|
dynamic_tool_response(&sess, id, DynamicToolCallResult::ContentItems(response)).await;
|
|
false
|
|
}
|
|
Op::DynamicToolResult { id, response } => {
|
|
dynamic_tool_response(&sess, id, response).await;
|
|
false
|
|
}
|
|
Op::RefreshMcpServers => {
|
|
refresh_mcp_servers(&sess);
|
|
false
|
|
}
|
|
Op::ReloadUserConfig => {
|
|
reload_user_config(&sess).await;
|
|
false
|
|
}
|
|
Op::Compact => {
|
|
compact(&sess, sub.id.clone()).await;
|
|
false
|
|
}
|
|
Op::SetThreadMemoryMode { mode } => {
|
|
set_thread_memory_mode(&sess, sub.id.clone(), mode).await;
|
|
false
|
|
}
|
|
Op::RunUserShellCommand {
|
|
command,
|
|
timeout_ms,
|
|
} => {
|
|
run_user_shell_command(&sess, sub.id.clone(), command, timeout_ms).await;
|
|
false
|
|
}
|
|
Op::ResolveElicitation {
|
|
server_name,
|
|
request_id,
|
|
decision,
|
|
content,
|
|
meta,
|
|
} => {
|
|
resolve_elicitation(&sess, server_name, request_id, decision, content, meta)
|
|
.await;
|
|
false
|
|
}
|
|
Op::Shutdown => shutdown(&sess, sub.id.clone()).await,
|
|
Op::Review { review_request } => {
|
|
review(&sess, &config, sub.id.clone(), review_request).await;
|
|
false
|
|
}
|
|
Op::ApproveGuardianDeniedAction { event } => {
|
|
approve_guardian_denied_action(&sess, event).await;
|
|
false
|
|
}
|
|
_ => false, // Ignore unknown ops; enum is non_exhaustive to allow extensions.
|
|
}
|
|
}
|
|
.instrument(dispatch_span)
|
|
.await;
|
|
drop(sub.residency_guard);
|
|
if should_exit {
|
|
shutdown_received = true;
|
|
break;
|
|
}
|
|
}
|
|
// If the submission loop exits because the channel closed without an
|
|
// explicit shutdown op, still run session teardown.
|
|
if !shutdown_received {
|
|
shutdown_session_runtime(&sess).await;
|
|
if let Some(live_thread) = sess.live_thread()
|
|
&& let Err(err) = live_thread.shutdown().await
|
|
{
|
|
sess.services.local_agent_runtime.record_shutdown_failure(
|
|
AgentTreeShutdownFailure::operation_failed(
|
|
"session_shutdown",
|
|
"close_persistence_after_channel_closed",
|
|
Some(sess.thread_id),
|
|
thread_store_error_kind(&err),
|
|
),
|
|
);
|
|
warn!("failed to shutdown thread persistence after submission channel closed: {err}");
|
|
}
|
|
sess.services
|
|
.rollout_thread_trace
|
|
.record_ended(codex_rollout_trace::RolloutStatus::Aborted);
|
|
}
|
|
debug!("Agent loop exited");
|
|
}
|
|
|
|
async fn approve_guardian_denied_action(sess: &Arc<Session>, event: GuardianAssessmentEvent) {
|
|
if event.status != GuardianAssessmentStatus::Denied {
|
|
warn!(
|
|
review_id = event.id.as_str(),
|
|
"ignoring approval for non-denied Guardian assessment"
|
|
);
|
|
return;
|
|
}
|
|
|
|
let approved_action = serde_json::json!({
|
|
"action": &event.action,
|
|
"outcome": "allowed",
|
|
});
|
|
let approved_action_json = match serde_json::to_string_pretty(&approved_action) {
|
|
Ok(approved_action_json) => approved_action_json,
|
|
Err(error) => {
|
|
warn!(%error, review_id = event.id.as_str(), "failed to serialize approved Guardian action");
|
|
return;
|
|
}
|
|
};
|
|
let items = vec![ContextualUserFragment::into(GuardianApprovedAction::new(
|
|
approved_action_json,
|
|
))];
|
|
|
|
sess.inject_no_new_turn(items, /*current_turn_context*/ None)
|
|
.await;
|
|
}
|
|
|
|
pub(super) fn submission_dispatch_span(sub: &Submission) -> tracing::Span {
|
|
let op_name = sub.op.kind();
|
|
let span_name = format!("op.dispatch.{op_name}");
|
|
let dispatch_span = match sub.op.as_protocol() {
|
|
Some(Op::RealtimeConversationAudio(_)) => {
|
|
debug_span!(
|
|
"submission_dispatch",
|
|
otel.name = span_name.as_str(),
|
|
submission.id = sub.id.as_str(),
|
|
codex.op = op_name
|
|
)
|
|
}
|
|
_ => info_span!(
|
|
"submission_dispatch",
|
|
otel.name = span_name.as_str(),
|
|
submission.id = sub.id.as_str(),
|
|
codex.op = op_name
|
|
),
|
|
};
|
|
if let Some(trace) = sub.trace.as_ref()
|
|
&& !set_parent_from_w3c_trace_context(&dispatch_span, trace)
|
|
{
|
|
warn!(
|
|
submission.id = sub.id.as_str(),
|
|
"ignoring invalid submission trace carrier"
|
|
);
|
|
}
|
|
dispatch_span
|
|
}
|