Support remote app servers in codex exec (#61707)

## What changed

Allow `codex exec --remote <ADDR>` to run a noninteractive turn using an existing app server's configuration and credentials. Support starting a new thread or resuming one by UUID, with human-readable or JSON output and optional bearer-token authentication through `--remote-auth-token-env`.

Accept remote options before or after `exec`, and reject conflicting endpoints. Reject unsupported agent configuration overrides and active threads, and report an error if the server disconnects before the turn completes.

## Testing

Extend CLI integration coverage for remote execution and resume using server authentication, JSON completion events, human-readable thread IDs, and conflicting endpoints. Add a snapshot for `--remote` help text.

GitOrigin-RevId: d4c3b16fb80eb6e8c523aff92110eaa878cbd3ee
This commit is contained in:
Eric Traut
2026-11-16 00:02:00 +00:00
committed by copyberry
parent 598df2d015
commit e51c551fb4
9 changed files with 287 additions and 7 deletions
+18
View File
@@ -17,6 +17,24 @@ pub struct Cli {
#[command(subcommand)]
pub command: Option<Command>,
/// Connect to an existing app server.
#[arg(
id = "exec_remote",
long = "remote",
value_name = "ADDR",
global = true
)]
pub remote: Option<String>,
/// Environment variable containing the remote WebSocket bearer token.
#[arg(
id = "exec_remote_auth_token_env",
long = "remote-auth-token-env",
value_name = "ENV_VAR",
global = true
)]
pub remote_auth_token_env: Option<String>,
/// Error out when config.toml contains fields that are not recognized by this version of Codex.
#[arg(long = "strict-config", global = true, default_value_t = false)]
pub strict_config: bool,
+2
View File
@@ -21,6 +21,8 @@ pub(crate) trait EventProcessor {
session_configured: &SessionConfiguredEvent,
);
fn print_thread_started(&mut self, thread_id: &str);
/// Handle a single typed app-server notification emitted by the agent.
fn process_server_notification(&mut self, notification: ServerNotification) -> CodexStatus;
@@ -227,6 +227,10 @@ impl EventProcessor for EventProcessorWithHumanOutput {
eprintln!("{}\n{}", "user".style(self.cyan), prompt);
}
fn print_thread_started(&mut self, thread_id: &str) {
eprintln!("thread id: {thread_id}");
}
fn process_server_notification(&mut self, notification: ServerNotification) -> CodexStatus {
match notification {
ServerNotification::ConfigWarning(notification) => {
@@ -615,6 +615,12 @@ impl EventProcessor for EventProcessorWithJsonOutput {
self.emit(Self::thread_started_event(session_configured));
}
fn print_thread_started(&mut self, thread_id: &str) {
self.emit(ThreadEvent::ThreadStarted(ThreadStartedEvent {
thread_id: thread_id.to_owned(),
}));
}
fn process_server_notification(&mut self, notification: ServerNotification) -> CodexStatus {
let collected = self.collect_thread_events(notification);
for event in collected.events {
+12
View File
@@ -11,6 +11,7 @@ mod event_processor;
mod event_processor_with_human_output;
pub(crate) mod event_processor_with_jsonl_output;
pub(crate) mod exec_events;
mod remote;
mod worktree;
pub use cli::Cli;
@@ -272,6 +273,12 @@ fn exec_stderr_env_filter() -> EnvFilter {
}
pub async fn run_main(cli: Cli, arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> {
if let Some(endpoint) = codex_app_server_client::resolve_remote_endpoint(
cli.remote.clone(),
cli.remote_auth_token_env.clone(),
)? {
return remote::run(cli, endpoint).await;
}
if cli.trust && cli.ignore_user_config {
anyhow::bail!(
"--trust cannot be combined with --ignore-user-config: saved project trust decisions must be checked"
@@ -283,6 +290,8 @@ pub async fn run_main(cli: Cli, arg0_paths: Arg0DispatchPaths) -> anyhow::Result
let Cli {
mut command,
remote: _,
remote_auth_token_env: _,
strict_config,
shared,
thread_source,
@@ -1450,6 +1459,9 @@ async fn finish_turn(
};
let Some(server_event) = server_event else {
if matches!(client, AppServerClient::Remote(_)) {
anyhow::bail!("app-server disconnected before turn completion");
}
break;
};
+148
View File
@@ -0,0 +1,148 @@
//! Execute a noninteractive turn on an existing app server, using its configuration and credentials.
use super::*;
use codex_app_server_client::RemoteAppServerClient;
use codex_app_server_client::RemoteAppServerConnectArgs;
use codex_app_server_client::RemoteAppServerEndpoint;
pub(super) async fn run(cli: Cli, endpoint: RemoteAppServerEndpoint) -> anyhow::Result<()> {
anyhow::ensure!(
!cli.trust
&& !cli.ignore_user_config
&& !cli.ignore_rules
&& !cli.strict_config
&& !cli.ephemeral
&& cli.thread_source.is_none()
&& cli.cyber_access_program.is_none()
&& cli.output_schema.is_none()
&& cli.config_overrides.raw_overrides.is_empty()
&& cli.images.is_empty()
&& cli.model.is_none()
&& !cli.oss
&& cli.oss_provider.is_none()
&& cli.config_profile_v2.is_none()
&& cli.sandbox_mode.is_none()
&& !cli.auto_review
&& !cli.dangerously_bypass_approvals_and_sandbox
&& !cli.bypass_hook_trust
&& cli.cwd.is_none()
&& !cli.worktree
&& cli.add_dir.is_empty(),
"--remote currently supports only prompt, resume by UUID, and output options; configure the agent on the server"
);
let (session_id, prompt) = match cli.command {
None => (None, resolve_root_prompt(cli.prompt)),
Some(ExecCommand::Resume(args)) => {
anyhow::ensure!(
!args.last && !args.all && args.images.is_empty(),
"remote resume requires a thread UUID"
);
let id = args
.session_id
.filter(|id| Uuid::parse_str(id).is_ok())
.ok_or_else(|| anyhow::anyhow!("remote resume requires a thread UUID"))?;
(Some(id), resolve_prompt(args.prompt.or(cli.prompt)))
}
_ => anyhow::bail!("--remote supports exec and exec resume"),
};
let bound_output = cli
.last_message_file
.as_deref()
.map(codex_exec_server::BoundOutput::open)
.transpose()?;
let mut processor: Box<dyn EventProcessor> = if cli.json {
Box::new(EventProcessorWithJsonOutput::new(cli.last_message_file))
} else {
let ansi = match cli.color {
cli::Color::Always => true,
cli::Color::Never => false,
cli::Color::Auto => supports_color::on_cached(Stream::Stderr).is_some(),
};
Box::new(EventProcessorWithHumanOutput::create_with_ansi(
ansi,
/*config*/ None,
cli.last_message_file,
))
};
let client = AppServerClient::Remote(
RemoteAppServerClient::connect(RemoteAppServerConnectArgs {
required_human_approval: false,
endpoint,
client_name: "codex_exec".into(),
client_version: env!("CARGO_PKG_VERSION").into(),
experimental_api: true,
mcp_server_openai_form_elicitation: false,
opt_out_notification_methods: Vec::new(),
channel_capacity: DEFAULT_IN_PROCESS_CHANNEL_CAPACITY,
})
.await?,
);
let mut ids = RequestIdSequencer::new();
let thread = if let Some(thread_id) = session_id {
client
.request_typed::<ThreadResumeResponse>(ClientRequest::ThreadResume {
request_id: ids.next(),
params: ThreadResumeParams {
thread_id,
exclude_turns: true,
..Default::default()
},
})
.await?
.thread
} else {
client
.request_typed::<ThreadStartResponse>(ClientRequest::ThreadStart {
request_id: ids.next(),
params: ThreadStartParams {
approval_policy: Some(codex_app_server_protocol::AskForApproval::Never),
..Default::default()
},
})
.await?
.thread
};
anyhow::ensure!(
!matches!(
thread.status,
codex_app_server_protocol::ThreadStatus::Active { .. }
),
"remote thread already has an active turn"
);
processor.print_thread_started(&thread.id);
let (interrupt_tx, interrupt_rx) = mpsc::unbounded_channel();
tokio::spawn(async move {
if tokio::signal::ctrl_c().await.is_ok() {
let _ = interrupt_tx.send(());
}
});
let response: TurnStartResponse = client
.request_typed(ClientRequest::TurnStart {
request_id: ids.next(),
params: TurnStartParams {
thread_id: thread.id.clone(),
turn_trigger: Some("exec".into()),
input: vec![codex_app_server_protocol::UserInput::Text {
text: prompt,
text_elements: Vec::new(),
}],
approval_policy: Some(codex_app_server_protocol::AskForApproval::Never),
..Default::default()
},
})
.await?;
finish_turn(
client,
ids,
ExecTurn {
thread_id: thread.id,
turn_id: response.turn.id,
ephemeral: thread.ephemeral,
history_mode: thread.history_mode,
},
processor,
bound_output,
interrupt_rx,
)
.await
}