mirror of
https://github.com/openai/codex.git
synced 2026-11-16 22:00:36 +00:00
Refactor exec to use the shared app-server client (#61706)
## What changed - Use `AppServerClient` throughout exec and extract turn completion into `finish_turn`, including handling for server and thread-stream disconnections. - Move remote address parsing and auth-token resolution into `codex-app-server-client`, with re-exports from the TUI. - Allow human-readable exec output to be initialized without a local `Config`. ## Testing Move remote address and auth-token tests into `codex-app-server-client`, retaining coverage for WebSocket and Unix socket addresses, invalid addresses, and missing, empty, or whitespace-padded tokens. GitOrigin-RevId: 465b17a1c03392a7d4e7700d83ce67c2cf5ef021
This commit is contained in:
@@ -25,6 +25,7 @@ pub mod cloud_backend;
|
||||
pub use codex_cloud_client::ProjectEnvironment;
|
||||
mod path;
|
||||
mod remote;
|
||||
mod remote_addr;
|
||||
mod remote_websocket;
|
||||
pub use cloud::CloudClient;
|
||||
pub use cloud::CloudCommand;
|
||||
@@ -83,6 +84,8 @@ pub use crate::path::AppServerPath;
|
||||
pub use crate::remote::RemoteAppServerClient;
|
||||
pub use crate::remote::RemoteAppServerConnectArgs;
|
||||
pub use crate::remote::RemoteAppServerEndpoint;
|
||||
pub use crate::remote_addr::resolve_remote_addr;
|
||||
pub use crate::remote_addr::resolve_remote_endpoint;
|
||||
|
||||
/// Transitional access to core-only embedded app-server types.
|
||||
///
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
//! Parse CLI remote app-server endpoints and determine whether they can carry bearer tokens.
|
||||
|
||||
use crate::RemoteAppServerEndpoint;
|
||||
use crate::remote::websocket_url_supports_auth_token;
|
||||
use codex_core::config::find_codex_home;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use color_eyre::eyre::WrapErr;
|
||||
use url::Url;
|
||||
|
||||
fn remote_addr_has_explicit_port(addr: &str, parsed: &Url) -> bool {
|
||||
let Some(host) = parsed.host_str() else {
|
||||
return false;
|
||||
};
|
||||
if parsed.port().is_some() {
|
||||
return true;
|
||||
}
|
||||
|
||||
let Some((_, rest)) = addr.split_once("://") else {
|
||||
return false;
|
||||
};
|
||||
let authority_end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
|
||||
let authority = &rest[..authority_end];
|
||||
let host_and_port = authority
|
||||
.rsplit_once('@')
|
||||
.map_or(authority, |(_, host_and_port)| host_and_port);
|
||||
let explicit_default_port = match parsed.scheme() {
|
||||
"ws" => 80,
|
||||
"wss" => 443,
|
||||
_ => return false,
|
||||
};
|
||||
let expected_host = if host.contains(':') {
|
||||
format!("[{host}]")
|
||||
} else {
|
||||
host.to_string()
|
||||
};
|
||||
host_and_port == format!("{expected_host}:{explicit_default_port}")
|
||||
}
|
||||
|
||||
pub fn resolve_remote_addr(addr: &str) -> color_eyre::Result<RemoteAppServerEndpoint> {
|
||||
if let Some(socket_path) = addr.strip_prefix("unix://") {
|
||||
let socket_path = if socket_path.is_empty() {
|
||||
let codex_home = find_codex_home().wrap_err("failed to resolve CODEX_HOME")?;
|
||||
crate::app_server_control_socket_path(&codex_home).map_err(color_eyre::Report::new)?
|
||||
} else {
|
||||
AbsolutePathBuf::relative_to_current_dir(socket_path)
|
||||
.map_err(color_eyre::Report::new)?
|
||||
};
|
||||
return Ok(RemoteAppServerEndpoint::UnixSocket { socket_path });
|
||||
}
|
||||
|
||||
let parsed = match Url::parse(addr) {
|
||||
Ok(parsed) => parsed,
|
||||
Err(_) => {
|
||||
color_eyre::eyre::bail!(
|
||||
"invalid remote address `{addr}`; expected `ws://host:port`, `wss://host:port`, `unix://`, or `unix://PATH`"
|
||||
);
|
||||
}
|
||||
};
|
||||
if matches!(parsed.scheme(), "ws" | "wss")
|
||||
&& parsed.host_str().is_some()
|
||||
&& remote_addr_has_explicit_port(addr, &parsed)
|
||||
&& parsed.path() == "/"
|
||||
&& parsed.query().is_none()
|
||||
&& parsed.fragment().is_none()
|
||||
{
|
||||
return Ok(RemoteAppServerEndpoint::WebSocket {
|
||||
websocket_url: parsed.to_string(),
|
||||
auth_token: None,
|
||||
});
|
||||
}
|
||||
|
||||
color_eyre::eyre::bail!(
|
||||
"invalid remote address `{addr}`; expected `ws://host:port`, `wss://host:port`, `unix://`, or `unix://PATH`"
|
||||
);
|
||||
}
|
||||
|
||||
pub fn resolve_remote_endpoint(
|
||||
remote: Option<String>,
|
||||
remote_auth_token_env: Option<String>,
|
||||
) -> std::io::Result<Option<RemoteAppServerEndpoint>> {
|
||||
let mut remote_endpoint = remote
|
||||
.as_deref()
|
||||
.map(resolve_remote_addr)
|
||||
.transpose()
|
||||
.map_err(std::io::Error::other)?;
|
||||
if let Some(remote_auth_token_env) = remote_auth_token_env {
|
||||
let Some(endpoint) = remote_endpoint.as_mut() else {
|
||||
return Err(std::io::Error::other(
|
||||
"`--remote-auth-token-env` requires `--remote`.",
|
||||
));
|
||||
};
|
||||
let slot = match endpoint {
|
||||
RemoteAppServerEndpoint::WebSocket {
|
||||
websocket_url,
|
||||
auth_token,
|
||||
} if Url::parse(websocket_url)
|
||||
.is_ok_and(|parsed| websocket_url_supports_auth_token(&parsed)) =>
|
||||
{
|
||||
auth_token
|
||||
}
|
||||
RemoteAppServerEndpoint::WebSocket { .. }
|
||||
| RemoteAppServerEndpoint::UnixSocket { .. } => {
|
||||
return Err(std::io::Error::other(
|
||||
"`--remote-auth-token-env` requires a `wss://` or loopback `ws://` remote.",
|
||||
));
|
||||
}
|
||||
};
|
||||
*slot = Some(read_remote_auth_token_from_env_var(&remote_auth_token_env)?);
|
||||
}
|
||||
Ok(remote_endpoint)
|
||||
}
|
||||
|
||||
fn read_remote_auth_token_from_env_var_with<F>(
|
||||
env_var_name: &str,
|
||||
get_var: F,
|
||||
) -> std::io::Result<String>
|
||||
where
|
||||
F: FnOnce(&str) -> Result<String, std::env::VarError>,
|
||||
{
|
||||
let auth_token = get_var(env_var_name).map_err(|_| {
|
||||
std::io::Error::other(format!("environment variable `{env_var_name}` is not set"))
|
||||
})?;
|
||||
let auth_token = auth_token.trim().to_string();
|
||||
if auth_token.is_empty() {
|
||||
return Err(std::io::Error::other(format!(
|
||||
"environment variable `{env_var_name}` is empty"
|
||||
)));
|
||||
}
|
||||
Ok(auth_token)
|
||||
}
|
||||
|
||||
fn read_remote_auth_token_from_env_var(env_var_name: &str) -> std::io::Result<String> {
|
||||
read_remote_auth_token_from_env_var_with(env_var_name, |name| std::env::var(name))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "remote_addr_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,106 @@
|
||||
#![cfg(test)]
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
|
||||
#[test]
|
||||
fn resolve_remote_addr_accepts_websocket_url() {
|
||||
assert_eq!(
|
||||
resolve_remote_addr("ws://127.0.0.1:4500").expect("ws URL should normalize"),
|
||||
RemoteAppServerEndpoint::WebSocket {
|
||||
websocket_url: "ws://127.0.0.1:4500/".to_string(),
|
||||
auth_token: None,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_remote_addr_accepts_secure_websocket_url() {
|
||||
assert_eq!(
|
||||
resolve_remote_addr("wss://example.com:443").expect("wss URL should normalize"),
|
||||
RemoteAppServerEndpoint::WebSocket {
|
||||
websocket_url: "wss://example.com/".to_string(),
|
||||
auth_token: None,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_remote_addr_accepts_default_socket() -> color_eyre::Result<()> {
|
||||
let codex_home = find_codex_home().wrap_err("failed to resolve CODEX_HOME")?;
|
||||
assert_eq!(
|
||||
resolve_remote_addr("unix://")?,
|
||||
RemoteAppServerEndpoint::UnixSocket {
|
||||
socket_path: crate::app_server_control_socket_path(&codex_home)?,
|
||||
}
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_remote_addr_accepts_relative_socket_path() -> color_eyre::Result<()> {
|
||||
assert_eq!(
|
||||
resolve_remote_addr("unix://codex.sock")?,
|
||||
RemoteAppServerEndpoint::UnixSocket {
|
||||
socket_path: AbsolutePathBuf::relative_to_current_dir("codex.sock")?,
|
||||
}
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_remote_addr_accepts_absolute_socket_path() -> color_eyre::Result<()> {
|
||||
let temp_dir = TempDir::new()?;
|
||||
let socket_path = temp_dir.path().join("codex.sock");
|
||||
assert_eq!(
|
||||
resolve_remote_addr(&format!("unix://{}", socket_path.display()))?,
|
||||
RemoteAppServerEndpoint::UnixSocket {
|
||||
socket_path: AbsolutePathBuf::from_absolute_path(&socket_path)?,
|
||||
}
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_remote_addr_rejects_invalid_remote_addresses() {
|
||||
for addr in [
|
||||
"ws://127.0.0.1",
|
||||
"wss://example.com",
|
||||
"127.0.0.1:4500",
|
||||
"https://127.0.0.1:4500",
|
||||
] {
|
||||
let err = resolve_remote_addr(addr).expect_err("invalid remote addresses should fail");
|
||||
assert!(
|
||||
err.to_string().contains(
|
||||
"expected `ws://host:port`, `wss://host:port`, `unix://`, or `unix://PATH`"
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn read_remote_auth_token_from_env_var_reports_missing_values() {
|
||||
let err = read_remote_auth_token_from_env_var_with("CODEX_REMOTE_AUTH_TOKEN", |_| {
|
||||
Err(std::env::VarError::NotPresent)
|
||||
})
|
||||
.expect_err("missing env vars should be rejected");
|
||||
assert!(err.to_string().contains("is not set"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_remote_auth_token_from_env_var_trims_values() {
|
||||
let auth_token = read_remote_auth_token_from_env_var_with("CODEX_REMOTE_AUTH_TOKEN", |_| {
|
||||
Ok(" bearer-token ".to_string())
|
||||
})
|
||||
.expect("env var should parse");
|
||||
assert_eq!(auth_token, "bearer-token");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_remote_auth_token_from_env_var_rejects_empty_values() {
|
||||
let err = read_remote_auth_token_from_env_var_with("CODEX_REMOTE_AUTH_TOKEN", |_| {
|
||||
Ok(" \n\t ".to_string())
|
||||
})
|
||||
.expect_err("empty env vars should be rejected");
|
||||
assert!(err.to_string().contains("is empty"));
|
||||
}
|
||||
@@ -32,6 +32,7 @@ use codex_tui::AppExitInfo;
|
||||
use codex_tui::Cli as TuiCli;
|
||||
use codex_tui::ExitReason;
|
||||
use codex_tui::UpdateAction;
|
||||
use codex_tui::resolve_remote_endpoint;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_cli::CliConfigOverrides;
|
||||
use codex_utils_cli::ProfileV2Name;
|
||||
@@ -2540,26 +2541,6 @@ async fn print_app_server_remote_control_output(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn read_remote_auth_token_from_env_var_with<F>(
|
||||
env_var_name: &str,
|
||||
get_var: F,
|
||||
) -> anyhow::Result<String>
|
||||
where
|
||||
F: FnOnce(&str) -> Result<String, std::env::VarError>,
|
||||
{
|
||||
let auth_token = get_var(env_var_name)
|
||||
.map_err(|_| anyhow::anyhow!("environment variable `{env_var_name}` is not set"))?;
|
||||
let auth_token = auth_token.trim().to_string();
|
||||
if auth_token.is_empty() {
|
||||
anyhow::bail!("environment variable `{env_var_name}` is empty");
|
||||
}
|
||||
Ok(auth_token)
|
||||
}
|
||||
|
||||
fn read_remote_auth_token_from_env_var(env_var_name: &str) -> anyhow::Result<String> {
|
||||
read_remote_auth_token_from_env_var_with(env_var_name, |name| std::env::var(name))
|
||||
}
|
||||
|
||||
async fn run_interactive_tui(
|
||||
mut interactive: TuiCli,
|
||||
remote: Option<String>,
|
||||
@@ -2673,41 +2654,6 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_remote_endpoint(
|
||||
remote: Option<String>,
|
||||
remote_auth_token_env: Option<String>,
|
||||
) -> std::io::Result<Option<codex_tui::RemoteAppServerEndpoint>> {
|
||||
let mut remote_endpoint = remote
|
||||
.as_deref()
|
||||
.map(codex_tui::resolve_remote_addr)
|
||||
.transpose()
|
||||
.map_err(std::io::Error::other)?;
|
||||
if let Some(remote_auth_token_env) = remote_auth_token_env {
|
||||
let Some(endpoint) = remote_endpoint.as_mut() else {
|
||||
return Err(std::io::Error::other(
|
||||
"`--remote-auth-token-env` requires `--remote`.",
|
||||
));
|
||||
};
|
||||
if !codex_tui::remote_addr_supports_auth_token(endpoint) {
|
||||
return Err(std::io::Error::other(
|
||||
"`--remote-auth-token-env` requires a `wss://` or loopback `ws://` remote.",
|
||||
));
|
||||
}
|
||||
let auth_token = read_remote_auth_token_from_env_var(&remote_auth_token_env)
|
||||
.map_err(std::io::Error::other)?;
|
||||
let codex_tui::RemoteAppServerEndpoint::WebSocket {
|
||||
auth_token: slot, ..
|
||||
} = endpoint
|
||||
else {
|
||||
return Err(std::io::Error::other(
|
||||
"`--remote-auth-token-env` requires a `wss://` or loopback `ws://` remote.",
|
||||
));
|
||||
};
|
||||
*slot = Some(auth_token);
|
||||
}
|
||||
Ok(remote_endpoint)
|
||||
}
|
||||
|
||||
fn is_remote_auth_usage_error(err: &std::io::Error) -> bool {
|
||||
err.to_string()
|
||||
.starts_with("`--remote-auth-token-env` requires")
|
||||
@@ -4629,34 +4575,6 @@ enabled = true
|
||||
assert!(err.to_string().contains("generate-internal-json-schema"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_remote_auth_token_from_env_var_reports_missing_values() {
|
||||
let err = read_remote_auth_token_from_env_var_with("CODEX_REMOTE_AUTH_TOKEN", |_| {
|
||||
Err(std::env::VarError::NotPresent)
|
||||
})
|
||||
.expect_err("missing env vars should be rejected");
|
||||
assert!(err.to_string().contains("is not set"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_remote_auth_token_from_env_var_trims_values() {
|
||||
let auth_token =
|
||||
read_remote_auth_token_from_env_var_with("CODEX_REMOTE_AUTH_TOKEN", |_| {
|
||||
Ok(" bearer-token ".to_string())
|
||||
})
|
||||
.expect("env var should parse");
|
||||
assert_eq!(auth_token, "bearer-token");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_remote_auth_token_from_env_var_rejects_empty_values() {
|
||||
let err = read_remote_auth_token_from_env_var_with("CODEX_REMOTE_AUTH_TOKEN", |_| {
|
||||
Ok(" \n\t ".to_string())
|
||||
})
|
||||
.expect_err("empty env vars should be rejected");
|
||||
assert!(err.to_string().contains("is empty"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn app_server_grpc_code_mode_host_url_parses_independently_of_listen_transport() {
|
||||
let app_server = app_server_from_args(
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Resolve the cyber treatment for an exec turn from the connected server's catalog.
|
||||
|
||||
use crate::RequestIdSequencer;
|
||||
use codex_app_server_client::InProcessAppServerClient;
|
||||
use codex_app_server_client::AppServerClient;
|
||||
use codex_app_server_protocol::Account;
|
||||
use codex_app_server_protocol::ClientRequest;
|
||||
use codex_app_server_protocol::CyberAccessProgram;
|
||||
@@ -16,7 +16,7 @@ use codex_protocol::openai_models::ModelAccessPrograms;
|
||||
|
||||
pub(crate) async fn program_for_turn(
|
||||
features: &Features,
|
||||
client: &InProcessAppServerClient,
|
||||
client: &AppServerClient,
|
||||
request_ids: &mut RequestIdSequencer,
|
||||
model: &str,
|
||||
provider_id: &str,
|
||||
@@ -94,7 +94,7 @@ pub(crate) async fn program_for_turn(
|
||||
}
|
||||
|
||||
async fn read_account(
|
||||
client: &InProcessAppServerClient,
|
||||
client: &AppServerClient,
|
||||
request_ids: &mut RequestIdSequencer,
|
||||
) -> anyhow::Result<Option<Account>> {
|
||||
let account = client
|
||||
|
||||
@@ -44,7 +44,7 @@ pub(crate) struct EventProcessorWithHumanOutput {
|
||||
impl EventProcessorWithHumanOutput {
|
||||
pub(crate) fn create_with_ansi(
|
||||
with_ansi: bool,
|
||||
config: &Config,
|
||||
config: Option<&Config>,
|
||||
last_message_path: Option<PathBuf>,
|
||||
) -> Self {
|
||||
let style = |styled: Style, plain: Style| if with_ansi { styled } else { plain };
|
||||
@@ -57,8 +57,8 @@ impl EventProcessorWithHumanOutput {
|
||||
magenta: style(Style::new().magenta(), Style::new()),
|
||||
red: style(Style::new().red(), Style::new()),
|
||||
yellow: style(Style::new().yellow(), Style::new()),
|
||||
show_agent_reasoning: !config.hide_agent_reasoning,
|
||||
show_raw_agent_reasoning: config.show_raw_agent_reasoning,
|
||||
show_agent_reasoning: config.is_none_or(|config| !config.hide_agent_reasoning),
|
||||
show_raw_agent_reasoning: config.is_some_and(|config| config.show_raw_agent_reasoning),
|
||||
last_message_path,
|
||||
final_message: None,
|
||||
final_message_rendered: false,
|
||||
|
||||
+68
-21
@@ -16,12 +16,13 @@ mod worktree;
|
||||
pub use cli::Cli;
|
||||
pub use cli::Command;
|
||||
pub use cli::ReviewArgs;
|
||||
use codex_app_server_client::AppServerClient;
|
||||
use codex_app_server_client::AppServerEvent;
|
||||
use codex_app_server_client::DEFAULT_IN_PROCESS_CHANNEL_CAPACITY;
|
||||
use codex_app_server_client::EnvironmentManager;
|
||||
use codex_app_server_client::ExecServerRuntimeOptions;
|
||||
use codex_app_server_client::InProcessAppServerClient;
|
||||
use codex_app_server_client::InProcessClientStartArgs;
|
||||
use codex_app_server_client::InProcessServerEvent;
|
||||
use codex_app_server_client::TypedRequestError;
|
||||
use codex_app_server_protocol::ClientRequest;
|
||||
use codex_app_server_protocol::ConfigWarningNotification;
|
||||
@@ -957,7 +958,7 @@ async fn run_exec_session(args: ExecRunArgs) -> anyhow::Result<()> {
|
||||
true => Box::new(EventProcessorWithJsonOutput::new(last_message_file.clone())),
|
||||
_ => Box::new(EventProcessorWithHumanOutput::create_with_ansi(
|
||||
stderr_with_ansi,
|
||||
&config,
|
||||
Some(&config),
|
||||
last_message_file.clone(),
|
||||
)),
|
||||
};
|
||||
@@ -1094,11 +1095,13 @@ async fn run_exec_session(args: ExecRunArgs) -> anyhow::Result<()> {
|
||||
.transpose()?;
|
||||
|
||||
let mut request_ids = RequestIdSequencer::new();
|
||||
let mut client = InProcessAppServerClient::start(in_process_start_args)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
anyhow::anyhow!("failed to initialize in-process app-server client: {err}")
|
||||
})?;
|
||||
let client = AppServerClient::InProcess(
|
||||
InProcessAppServerClient::start(in_process_start_args)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
anyhow::anyhow!("failed to initialize in-process app-server client: {err}")
|
||||
})?,
|
||||
);
|
||||
|
||||
let mut daybreak_enabled = config.daybreak_enabled;
|
||||
// Resolve resume and fork through existing app-server thread lifecycle APIs.
|
||||
@@ -1263,7 +1266,7 @@ async fn run_exec_session(args: ExecRunArgs) -> anyhow::Result<()> {
|
||||
|
||||
info!("Codex initialized with event: {session_configured:?}");
|
||||
|
||||
let (interrupt_tx, mut interrupt_rx) = mpsc::unbounded_channel::<()>();
|
||||
let (interrupt_tx, interrupt_rx) = mpsc::unbounded_channel::<()>();
|
||||
tokio::spawn(async move {
|
||||
if tokio::signal::ctrl_c().await.is_ok() {
|
||||
tracing::debug!("Keyboard interrupt");
|
||||
@@ -1376,12 +1379,49 @@ async fn run_exec_session(args: ExecRunArgs) -> anyhow::Result<()> {
|
||||
};
|
||||
exec_span.record("turn.id", task_id.as_str());
|
||||
|
||||
finish_turn(
|
||||
client,
|
||||
request_ids,
|
||||
ExecTurn {
|
||||
thread_id: primary_thread_id.to_string(),
|
||||
turn_id: task_id,
|
||||
ephemeral: config.ephemeral,
|
||||
history_mode,
|
||||
},
|
||||
event_processor,
|
||||
bound_output,
|
||||
interrupt_rx,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
struct ExecTurn {
|
||||
thread_id: String,
|
||||
turn_id: String,
|
||||
ephemeral: bool,
|
||||
history_mode: ThreadHistoryMode,
|
||||
}
|
||||
|
||||
async fn finish_turn(
|
||||
mut client: AppServerClient,
|
||||
mut request_ids: RequestIdSequencer,
|
||||
turn: ExecTurn,
|
||||
mut event_processor: Box<dyn EventProcessor>,
|
||||
bound_output: Option<codex_exec_server::BoundOutput>,
|
||||
mut interrupt_rx: mpsc::UnboundedReceiver<()>,
|
||||
) -> anyhow::Result<()> {
|
||||
let ExecTurn {
|
||||
thread_id,
|
||||
turn_id: task_id,
|
||||
ephemeral: thread_ephemeral,
|
||||
history_mode,
|
||||
} = turn;
|
||||
// Run the loop until the task is complete.
|
||||
// Track whether a fatal error was reported by the server so we can
|
||||
// exit with a non-zero status for automation-friendly signaling.
|
||||
let mut error_seen = false;
|
||||
let mut interrupt_channel_open = true;
|
||||
let primary_thread_id_for_requests = primary_thread_id.to_string();
|
||||
let primary_thread_id_for_requests = thread_id;
|
||||
loop {
|
||||
let server_event = tokio::select! {
|
||||
maybe_interrupt = interrupt_rx.recv(), if interrupt_channel_open => {
|
||||
@@ -1414,10 +1454,10 @@ async fn run_exec_session(args: ExecRunArgs) -> anyhow::Result<()> {
|
||||
};
|
||||
|
||||
match server_event {
|
||||
InProcessServerEvent::ServerRequest(request) => {
|
||||
AppServerEvent::ServerRequest(request) => {
|
||||
handle_server_request(&client, *request, &mut error_seen).await;
|
||||
}
|
||||
InProcessServerEvent::ServerNotification(notification) => {
|
||||
AppServerEvent::ServerNotification(notification) => {
|
||||
let mut notification = *notification;
|
||||
if let ServerNotification::Error(payload) = ¬ification {
|
||||
if payload.thread_id == primary_thread_id_for_requests
|
||||
@@ -1444,7 +1484,7 @@ async fn run_exec_session(args: ExecRunArgs) -> anyhow::Result<()> {
|
||||
&task_id,
|
||||
) {
|
||||
maybe_backfill_turn_completed_items(
|
||||
config.ephemeral,
|
||||
thread_ephemeral,
|
||||
history_mode,
|
||||
&client,
|
||||
&mut request_ids,
|
||||
@@ -1469,7 +1509,14 @@ async fn run_exec_session(args: ExecRunArgs) -> anyhow::Result<()> {
|
||||
}
|
||||
}
|
||||
}
|
||||
InProcessServerEvent::Lagged { skipped } => {
|
||||
AppServerEvent::Disconnected { message } => {
|
||||
anyhow::bail!("app-server disconnected: {message}")
|
||||
}
|
||||
AppServerEvent::ThreadStreamDisconnected(error) => {
|
||||
anyhow::bail!("app-server stream disconnected: {}", error.error.message)
|
||||
}
|
||||
AppServerEvent::ThreadStreamReconnected(_) => {}
|
||||
AppServerEvent::Lagged { skipped } => {
|
||||
let message = lagged_event_warning_message(skipped);
|
||||
warn!("{message}");
|
||||
event_processor.process_warning(message);
|
||||
@@ -1489,7 +1536,7 @@ async fn run_exec_session(args: ExecRunArgs) -> anyhow::Result<()> {
|
||||
}
|
||||
|
||||
async fn start_thread(
|
||||
client: &InProcessAppServerClient,
|
||||
client: &AppServerClient,
|
||||
request_ids: &mut RequestIdSequencer,
|
||||
config: &Config,
|
||||
thread_source: &ThreadSource,
|
||||
@@ -1616,7 +1663,7 @@ fn sandbox_mode_from_permission_profile(
|
||||
}
|
||||
|
||||
async fn send_request_with_response<T>(
|
||||
client: &InProcessAppServerClient,
|
||||
client: &AppServerClient,
|
||||
request: ClientRequest,
|
||||
method: &str,
|
||||
) -> Result<T, String>
|
||||
@@ -1816,7 +1863,7 @@ fn should_process_notification(
|
||||
async fn maybe_backfill_turn_completed_items(
|
||||
thread_ephemeral: bool,
|
||||
history_mode: ThreadHistoryMode,
|
||||
client: &InProcessAppServerClient,
|
||||
client: &AppServerClient,
|
||||
request_ids: &mut RequestIdSequencer,
|
||||
notification: &mut ServerNotification,
|
||||
) {
|
||||
@@ -1991,7 +2038,7 @@ fn cwds_match(current_cwd: &Path, session_cwd: &Path) -> bool {
|
||||
}
|
||||
|
||||
async fn resolve_resume_thread_id(
|
||||
client: &InProcessAppServerClient,
|
||||
client: &AppServerClient,
|
||||
config: &Config,
|
||||
state_db: Option<&StateDbHandle>,
|
||||
args: &crate::cli::ResumeArgs,
|
||||
@@ -2169,7 +2216,7 @@ fn canceled_mcp_server_elicitation_response(
|
||||
}
|
||||
|
||||
async fn request_shutdown(
|
||||
client: &InProcessAppServerClient,
|
||||
client: &AppServerClient,
|
||||
request_ids: &mut RequestIdSequencer,
|
||||
thread_id: &str,
|
||||
) -> Result<(), String> {
|
||||
@@ -2185,7 +2232,7 @@ async fn request_shutdown(
|
||||
}
|
||||
|
||||
async fn resolve_server_request(
|
||||
client: &InProcessAppServerClient,
|
||||
client: &AppServerClient,
|
||||
request_id: RequestId,
|
||||
value: serde_json::Value,
|
||||
method: &str,
|
||||
@@ -2197,7 +2244,7 @@ async fn resolve_server_request(
|
||||
}
|
||||
|
||||
async fn reject_server_request(
|
||||
client: &InProcessAppServerClient,
|
||||
client: &AppServerClient,
|
||||
request_id: RequestId,
|
||||
method: &str,
|
||||
reason: String,
|
||||
@@ -2228,7 +2275,7 @@ fn server_request_method_name(request: &ServerRequest) -> String {
|
||||
}
|
||||
|
||||
async fn handle_server_request(
|
||||
client: &InProcessAppServerClient,
|
||||
client: &AppServerClient,
|
||||
request: ServerRequest,
|
||||
error_seen: &mut bool,
|
||||
) {
|
||||
|
||||
@@ -54,6 +54,7 @@ pub(super) async fn fork_source(
|
||||
channel_capacity: DEFAULT_IN_PROCESS_CHANNEL_CAPACITY,
|
||||
})
|
||||
.await?;
|
||||
let client = AppServerClient::InProcess(client);
|
||||
let result = async {
|
||||
let lookup = crate::cli::ResumeArgs {
|
||||
session_id: Some(args.session_id.clone()),
|
||||
|
||||
+2
-88
@@ -39,6 +39,8 @@ use codex_app_server_client::RemoteAppServerClient;
|
||||
use codex_app_server_client::RemoteAppServerConnectArgs;
|
||||
pub use codex_app_server_client::RemoteAppServerEndpoint;
|
||||
use codex_app_server_client::cloud_backend;
|
||||
pub use codex_app_server_client::resolve_remote_addr;
|
||||
pub use codex_app_server_client::resolve_remote_endpoint;
|
||||
use codex_app_server_protocol::Account as AppServerAccount;
|
||||
use codex_app_server_protocol::AskForApproval;
|
||||
use codex_app_server_protocol::ConfigWarningNotification;
|
||||
@@ -97,7 +99,6 @@ use tracing::warn;
|
||||
use tracing_appender::non_blocking;
|
||||
use tracing_subscriber::EnvFilter;
|
||||
use tracing_subscriber::prelude::*;
|
||||
use url::Url;
|
||||
use uuid::Uuid;
|
||||
|
||||
pub(crate) use codex_app_server_client::legacy_core;
|
||||
@@ -441,93 +442,6 @@ fn remove_legacy_tui_log_file(codex_home: &Path) {
|
||||
let _ = std::fs::remove_file(codex_home.join("log").join(TUI_LOG_FILE_NAME));
|
||||
}
|
||||
|
||||
fn remote_addr_has_explicit_port(addr: &str, parsed: &Url) -> bool {
|
||||
let Some(host) = parsed.host_str() else {
|
||||
return false;
|
||||
};
|
||||
if parsed.port().is_some() {
|
||||
return true;
|
||||
}
|
||||
|
||||
let Some((_, rest)) = addr.split_once("://") else {
|
||||
return false;
|
||||
};
|
||||
let authority_end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
|
||||
let authority = &rest[..authority_end];
|
||||
let host_and_port = authority
|
||||
.rsplit_once('@')
|
||||
.map_or(authority, |(_, host_and_port)| host_and_port);
|
||||
let explicit_default_port = match parsed.scheme() {
|
||||
"ws" => 80,
|
||||
"wss" => 443,
|
||||
_ => return false,
|
||||
};
|
||||
let expected_host = if host.contains(':') {
|
||||
format!("[{host}]")
|
||||
} else {
|
||||
host.to_string()
|
||||
};
|
||||
host_and_port == format!("{expected_host}:{explicit_default_port}")
|
||||
}
|
||||
|
||||
fn websocket_url_supports_auth_token(parsed: &Url) -> bool {
|
||||
match (parsed.scheme(), parsed.host()) {
|
||||
("wss", Some(_)) => true,
|
||||
("ws", Some(url::Host::Domain(domain))) => domain.eq_ignore_ascii_case("localhost"),
|
||||
("ws", Some(url::Host::Ipv4(addr))) => addr.is_loopback(),
|
||||
("ws", Some(url::Host::Ipv6(addr))) => addr.is_loopback(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn resolve_remote_addr(addr: &str) -> color_eyre::Result<RemoteAppServerEndpoint> {
|
||||
if let Some(socket_path) = addr.strip_prefix("unix://") {
|
||||
let socket_path = if socket_path.is_empty() {
|
||||
let codex_home = find_codex_home().wrap_err("failed to resolve CODEX_HOME")?;
|
||||
codex_app_server_client::app_server_control_socket_path(&codex_home)
|
||||
.map_err(color_eyre::Report::new)?
|
||||
} else {
|
||||
AbsolutePathBuf::relative_to_current_dir(socket_path)
|
||||
.map_err(color_eyre::Report::new)?
|
||||
};
|
||||
return Ok(RemoteAppServerEndpoint::UnixSocket { socket_path });
|
||||
}
|
||||
|
||||
let parsed = match Url::parse(addr) {
|
||||
Ok(parsed) => parsed,
|
||||
Err(_) => {
|
||||
color_eyre::eyre::bail!(
|
||||
"invalid remote address `{addr}`; expected `ws://host:port`, `wss://host:port`, `unix://`, or `unix://PATH`"
|
||||
);
|
||||
}
|
||||
};
|
||||
if matches!(parsed.scheme(), "ws" | "wss")
|
||||
&& parsed.host_str().is_some()
|
||||
&& remote_addr_has_explicit_port(addr, &parsed)
|
||||
&& parsed.path() == "/"
|
||||
&& parsed.query().is_none()
|
||||
&& parsed.fragment().is_none()
|
||||
{
|
||||
return Ok(RemoteAppServerEndpoint::WebSocket {
|
||||
websocket_url: parsed.to_string(),
|
||||
auth_token: None,
|
||||
});
|
||||
}
|
||||
|
||||
color_eyre::eyre::bail!(
|
||||
"invalid remote address `{addr}`; expected `ws://host:port`, `wss://host:port`, `unix://`, or `unix://PATH`"
|
||||
);
|
||||
}
|
||||
|
||||
pub fn remote_addr_supports_auth_token(endpoint: &RemoteAppServerEndpoint) -> bool {
|
||||
match endpoint {
|
||||
RemoteAppServerEndpoint::WebSocket { websocket_url, .. } => {
|
||||
Url::parse(websocket_url).is_ok_and(|parsed| websocket_url_supports_auth_token(&parsed))
|
||||
}
|
||||
RemoteAppServerEndpoint::UnixSocket { .. } => false,
|
||||
}
|
||||
}
|
||||
|
||||
async fn connect_remote_app_server(
|
||||
endpoint: RemoteAppServerEndpoint,
|
||||
) -> color_eyre::Result<AppServerClient> {
|
||||
|
||||
@@ -747,81 +747,6 @@ fn session_target_display_label_falls_back_to_thread_id() {
|
||||
assert_eq!(target.display_label(), format!("thread {thread_id}"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_remote_addr_accepts_websocket_url() {
|
||||
assert_eq!(
|
||||
resolve_remote_addr("ws://127.0.0.1:4500").expect("ws URL should normalize"),
|
||||
RemoteAppServerEndpoint::WebSocket {
|
||||
websocket_url: "ws://127.0.0.1:4500/".to_string(),
|
||||
auth_token: None,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_remote_addr_accepts_secure_websocket_url() {
|
||||
assert_eq!(
|
||||
resolve_remote_addr("wss://example.com:443").expect("wss URL should normalize"),
|
||||
RemoteAppServerEndpoint::WebSocket {
|
||||
websocket_url: "wss://example.com/".to_string(),
|
||||
auth_token: None,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_remote_addr_accepts_default_socket() -> color_eyre::Result<()> {
|
||||
let codex_home = find_codex_home().wrap_err("failed to resolve CODEX_HOME")?;
|
||||
assert_eq!(
|
||||
resolve_remote_addr("unix://")?,
|
||||
RemoteAppServerEndpoint::UnixSocket {
|
||||
socket_path: codex_app_server_client::app_server_control_socket_path(&codex_home)?,
|
||||
}
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_remote_addr_accepts_relative_socket_path() -> color_eyre::Result<()> {
|
||||
assert_eq!(
|
||||
resolve_remote_addr("unix://codex.sock")?,
|
||||
RemoteAppServerEndpoint::UnixSocket {
|
||||
socket_path: AbsolutePathBuf::relative_to_current_dir("codex.sock")?,
|
||||
}
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_remote_addr_accepts_absolute_socket_path() -> color_eyre::Result<()> {
|
||||
let temp_dir = TempDir::new()?;
|
||||
let socket_path = temp_dir.path().join("codex.sock");
|
||||
assert_eq!(
|
||||
resolve_remote_addr(&format!("unix://{}", socket_path.display()))?,
|
||||
RemoteAppServerEndpoint::UnixSocket {
|
||||
socket_path: AbsolutePathBuf::from_absolute_path(&socket_path)?,
|
||||
}
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_remote_addr_rejects_invalid_remote_addresses() {
|
||||
for addr in [
|
||||
"ws://127.0.0.1",
|
||||
"wss://example.com",
|
||||
"127.0.0.1:4500",
|
||||
"https://127.0.0.1:4500",
|
||||
] {
|
||||
let err = resolve_remote_addr(addr).expect_err("invalid remote addresses should fail");
|
||||
assert!(
|
||||
err.to_string().contains(
|
||||
"expected `ws://host:port`, `wss://host:port`, `unix://`, or `unix://PATH`"
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn default_daemon_auto_connect_skips_missing_socket() -> color_eyre::Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
|
||||
Reference in New Issue
Block a user