Add sticky thread environments

Carry thread-level environment selections through app-server, core turn context, unified exec, and environment manager plumbing. Update generated schema and existing tests for the new environment fields.

Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
starr-openai
2026-04-21 11:49:13 -07:00
co-authored by Codex
parent 4d41e8abe2
commit ddd61b9243
48 changed files with 994 additions and 113 deletions
+79 -11
View File
@@ -14,13 +14,17 @@ use tokio::sync::OnceCell;
use tokio::sync::mpsc;
use tokio::sync::watch;
use tokio::process::Child;
use tokio::process::Command;
use tokio::time::timeout;
use tokio_tungstenite::connect_async;
use tracing::debug;
use crate::ProcessId;
use crate::client_api::CommandExecServerConnectArgs;
use crate::client_api::ExecServerClientConnectOptions;
use crate::client_api::RemoteExecServerConnectArgs;
use crate::client_api::RemoteExecServerTransport;
use crate::connection::JsonRpcConnection;
use crate::process::ExecProcessEvent;
use crate::process::ExecProcessEventLog;
@@ -102,6 +106,16 @@ impl From<RemoteExecServerConnectArgs> for ExecServerClientConnectOptions {
}
}
impl From<CommandExecServerConnectArgs> for ExecServerClientConnectOptions {
fn from(value: CommandExecServerConnectArgs) -> Self {
Self {
client_name: value.client_name,
initialize_timeout: value.initialize_timeout,
resume_session_id: value.resume_session_id,
}
}
}
impl RemoteExecServerConnectArgs {
pub fn new(websocket_url: String, client_name: String) -> Self {
Self {
@@ -162,11 +176,15 @@ struct Inner {
http_body_stream_next_id: AtomicU64,
session_id: std::sync::RwLock<Option<String>>,
reader_task: tokio::task::JoinHandle<()>,
child: Option<Child>,
}
impl Drop for Inner {
fn drop(&mut self) {
self.reader_task.abort();
if let Some(child) = &mut self.child {
let _ = child.start_kill();
}
}
}
@@ -177,14 +195,14 @@ pub struct ExecServerClient {
#[derive(Clone)]
pub(crate) struct LazyRemoteExecServerClient {
websocket_url: String,
transport: RemoteExecServerTransport,
client: Arc<OnceCell<ExecServerClient>>,
}
impl LazyRemoteExecServerClient {
pub(crate) fn new(websocket_url: String) -> Self {
pub(crate) fn new(transport: RemoteExecServerTransport) -> Self {
Self {
websocket_url,
transport,
client: Arc::new(OnceCell::new()),
}
}
@@ -192,14 +210,27 @@ impl LazyRemoteExecServerClient {
pub(crate) async fn get(&self) -> Result<ExecServerClient, ExecServerError> {
self.client
.get_or_try_init(|| async {
ExecServerClient::connect_websocket(RemoteExecServerConnectArgs {
websocket_url: self.websocket_url.clone(),
client_name: "codex-environment".to_string(),
connect_timeout: Duration::from_secs(5),
initialize_timeout: Duration::from_secs(5),
resume_session_id: None,
})
.await
match &self.transport {
RemoteExecServerTransport::WebSocket { url } => {
ExecServerClient::connect_websocket(RemoteExecServerConnectArgs {
websocket_url: url.clone(),
client_name: "codex-environment".to_string(),
connect_timeout: Duration::from_secs(5),
initialize_timeout: Duration::from_secs(5),
resume_session_id: None,
})
.await
}
RemoteExecServerTransport::Command { command } => {
ExecServerClient::connect_command(CommandExecServerConnectArgs {
command: command.clone(),
client_name: "codex-environment".to_string(),
initialize_timeout: Duration::from_secs(5),
resume_session_id: None,
})
.await
}
}
})
.await
.cloned()
@@ -255,6 +286,39 @@ impl ExecServerClient {
format!("exec-server websocket {websocket_url}"),
),
args.into(),
/*child*/ None,
)
.await
}
pub async fn connect_command(
args: CommandExecServerConnectArgs,
) -> Result<Self, ExecServerError> {
let command = args.command.clone();
let mut child = Command::new("sh")
.arg("-lc")
.arg(&command)
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::inherit())
.kill_on_drop(true)
.spawn()
.map_err(ExecServerError::Spawn)?;
let stdout = child.stdout.take().ok_or_else(|| {
ExecServerError::Protocol(format!("exec-server command `{command}` has no stdout"))
})?;
let stdin = child.stdin.take().ok_or_else(|| {
ExecServerError::Protocol(format!("exec-server command `{command}` has no stdin"))
})?;
Self::connect(
JsonRpcConnection::from_stdio(
stdout,
stdin,
format!("exec-server command `{command}`"),
),
args.into(),
Some(child),
)
.await
}
@@ -410,6 +474,7 @@ impl ExecServerClient {
async fn connect(
connection: JsonRpcConnection,
options: ExecServerClientConnectOptions,
child: Option<Child>,
) -> Result<Self, ExecServerError> {
let (rpc_client, mut events_rx) = RpcClient::new(connection);
let inner = Arc::new_cyclic(|weak| {
@@ -455,6 +520,7 @@ impl ExecServerClient {
http_body_stream_next_id: AtomicU64::new(1),
session_id: std::sync::RwLock::new(None),
reader_task,
child,
}
});
@@ -949,6 +1015,7 @@ mod tests {
"test-exec-server-client".to_string(),
),
ExecServerClientConnectOptions::default(),
/*child*/ None,
)
.await
.expect("client should connect");
@@ -1092,6 +1159,7 @@ mod tests {
"test-exec-server-client".to_string(),
),
ExecServerClientConnectOptions::default(),
/*child*/ None,
)
.await
.expect("client should connect");
+16
View File
@@ -8,6 +8,13 @@ pub struct ExecServerClientConnectOptions {
pub resume_session_id: Option<String>,
}
/// Transport used to connect to a remote exec-server.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RemoteExecServerTransport {
WebSocket { url: String },
Command { command: String },
}
/// WebSocket connection arguments for a remote exec-server.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RemoteExecServerConnectArgs {
@@ -17,3 +24,12 @@ pub struct RemoteExecServerConnectArgs {
pub initialize_timeout: Duration,
pub resume_session_id: Option<String>,
}
/// Command-spawn connection arguments for a remote exec-server over stdio.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CommandExecServerConnectArgs {
pub command: String,
pub client_name: String,
pub initialize_timeout: Duration,
pub resume_session_id: Option<String>,
}
+4 -11
View File
@@ -1,22 +1,17 @@
use codex_app_server_protocol::JSONRPCMessage;
use futures::SinkExt;
use futures::StreamExt;
use tokio::io::AsyncBufReadExt;
use tokio::io::AsyncRead;
use tokio::io::AsyncWrite;
use tokio::io::AsyncWriteExt;
use tokio::io::BufReader;
use tokio::io::BufWriter;
use tokio::sync::mpsc;
use tokio::sync::watch;
use tokio_tungstenite::WebSocketStream;
use tokio_tungstenite::tungstenite::Message;
#[cfg(test)]
use tokio::io::AsyncBufReadExt;
#[cfg(test)]
use tokio::io::AsyncWriteExt;
#[cfg(test)]
use tokio::io::BufReader;
#[cfg(test)]
use tokio::io::BufWriter;
pub(crate) const CHANNEL_CAPACITY: usize = 128;
#[derive(Debug)]
@@ -34,7 +29,6 @@ pub(crate) struct JsonRpcConnection {
}
impl JsonRpcConnection {
#[cfg(test)]
pub(crate) fn from_stdio<R, W>(reader: R, writer: W, connection_label: String) -> Self
where
R: AsyncRead + Unpin + Send + 'static,
@@ -298,7 +292,6 @@ async fn send_malformed_message(
.await;
}
#[cfg(test)]
async fn write_jsonrpc_line_message<W>(
writer: &mut BufWriter<W>,
message: &JSONRPCMessage,
+151 -19
View File
@@ -3,6 +3,7 @@ use std::sync::Arc;
use crate::ExecServerError;
use crate::ExecServerRuntimePaths;
use crate::RemoteExecServerTransport;
use crate::client::LazyRemoteExecServerClient;
use crate::file_system::ExecutorFileSystem;
use crate::local_file_system::LocalFileSystem;
@@ -16,10 +17,13 @@ pub const CODEX_EXEC_SERVER_URL_ENV_VAR: &str = "CODEX_EXEC_SERVER_URL";
/// Owns the execution/filesystem environments available to the Codex runtime.
///
/// `EnvironmentManager` is a shared registry for concrete environments. It
/// always creates a local environment under [`LOCAL_ENVIRONMENT_ID`]. When
/// `CODEX_EXEC_SERVER_URL` is set to a websocket URL, it also creates a remote
/// environment under [`REMOTE_ENVIRONMENT_ID`] and makes that the default
/// environment. Otherwise the local environment is the default.
/// always creates a local environment under [`LOCAL_ENVIRONMENT_ID`]. Additional
/// environments are remote exec-server endpoints that can connect over either a
/// websocket URL or a command-backed stdio JSON-RPC transport.
///
/// In legacy mode, when `CODEX_EXEC_SERVER_URL` is set to a websocket URL, it
/// also creates a remote environment under [`REMOTE_ENVIRONMENT_ID`] and makes
/// that the default environment. Otherwise the local environment is the default.
///
/// Setting `CODEX_EXEC_SERVER_URL=none` disables environment access by leaving
/// the default environment unset while still keeping the local environment
@@ -63,6 +67,25 @@ impl EnvironmentManagerArgs {
}
}
#[derive(Clone, Debug, Default)]
pub struct ConfiguredEnvironmentManagerArgs {
pub default_environment: Option<String>,
pub environments: Vec<ConfiguredEnvironmentSpec>,
pub local_runtime_paths: Option<ExecServerRuntimePaths>,
}
#[derive(Clone, Debug)]
pub struct ConfiguredEnvironmentSpec {
pub id: String,
pub transport: RemoteExecServerTransport,
}
#[derive(Clone, Debug)]
pub enum EnvironmentManagerConfig {
ExecServerUrl(EnvironmentManagerArgs),
Configured(ConfiguredEnvironmentManagerArgs),
}
impl From<Option<String>> for EnvironmentManagerArgs {
fn from(exec_server_url: Option<String>) -> Self {
Self {
@@ -72,6 +95,24 @@ impl From<Option<String>> for EnvironmentManagerArgs {
}
}
impl From<EnvironmentManagerArgs> for EnvironmentManagerConfig {
fn from(args: EnvironmentManagerArgs) -> Self {
Self::ExecServerUrl(args)
}
}
impl From<Option<String>> for EnvironmentManagerConfig {
fn from(exec_server_url: Option<String>) -> Self {
Self::ExecServerUrl(EnvironmentManagerArgs::from(exec_server_url))
}
}
impl From<ConfiguredEnvironmentManagerArgs> for EnvironmentManagerConfig {
fn from(args: ConfiguredEnvironmentManagerArgs) -> Self {
Self::Configured(args)
}
}
impl Default for EnvironmentManager {
fn default() -> Self {
Self::new(EnvironmentManagerArgs::default())
@@ -85,8 +126,15 @@ impl EnvironmentManager {
/// Builds a manager from the raw `CODEX_EXEC_SERVER_URL` value and local
/// runtime paths used when creating local filesystem helpers.
pub fn new(exec_server_url: impl Into<EnvironmentManagerArgs>) -> Self {
let args = exec_server_url.into();
pub fn new(config: impl Into<EnvironmentManagerConfig>) -> Self {
match config.into() {
EnvironmentManagerConfig::ExecServerUrl(args) => Self::from_exec_server_url_args(args),
EnvironmentManagerConfig::Configured(args) => Self::from_configured_args(args)
.unwrap_or_else(|err| panic!("invalid environment manager config: {err}")),
}
}
fn from_exec_server_url_args(args: EnvironmentManagerArgs) -> Self {
let EnvironmentManagerArgs {
exec_server_url,
local_runtime_paths,
@@ -106,7 +154,9 @@ impl EnvironmentManager {
environments.insert(
REMOTE_ENVIRONMENT_ID.to_string(),
Arc::new(Environment::remote_with_runtime_paths(
exec_server_url,
RemoteExecServerTransport::WebSocket {
url: exec_server_url,
},
local_runtime_paths,
)),
);
@@ -122,6 +172,75 @@ impl EnvironmentManager {
}
}
pub fn try_new(config: impl Into<EnvironmentManagerConfig>) -> Result<Self, ExecServerError> {
match config.into() {
EnvironmentManagerConfig::ExecServerUrl(args) => {
Ok(Self::from_exec_server_url_args(args))
}
EnvironmentManagerConfig::Configured(args) => Self::from_configured_args(args),
}
}
fn from_configured_args(
args: ConfiguredEnvironmentManagerArgs,
) -> Result<Self, ExecServerError> {
let ConfiguredEnvironmentManagerArgs {
default_environment,
environments: configured_environments,
local_runtime_paths,
} = args;
let mut environments = HashMap::from([(
LOCAL_ENVIRONMENT_ID.to_string(),
Arc::new(Environment::local_with_runtime_paths(
local_runtime_paths.clone(),
)),
)]);
for environment in configured_environments {
let id = environment.id.trim();
if id.is_empty() {
return Err(ExecServerError::Protocol(
"environment id must not be empty".to_string(),
));
}
if id == LOCAL_ENVIRONMENT_ID || id.eq_ignore_ascii_case("none") {
return Err(ExecServerError::Protocol(format!(
"environment id `{id}` is reserved"
)));
}
if environments.contains_key(id) {
return Err(ExecServerError::Protocol(format!(
"duplicate environment id `{id}`"
)));
}
environments.insert(
id.to_string(),
Arc::new(Environment::remote_with_runtime_paths(
environment.transport,
local_runtime_paths.clone(),
)),
);
}
let default_environment = match default_environment.as_deref().map(str::trim) {
None | Some("") => Some(LOCAL_ENVIRONMENT_ID.to_string()),
Some(default_environment) if default_environment.eq_ignore_ascii_case("none") => None,
Some(default_environment) => {
if !environments.contains_key(default_environment) {
return Err(ExecServerError::Protocol(format!(
"default_environment `{default_environment}` is not a configured environment id"
)));
}
Some(default_environment.to_string())
}
};
Ok(Self {
default_environment,
environments,
})
}
/// Returns the default environment instance.
pub fn default_environment(&self) -> Option<Arc<Environment>> {
self.default_environment
@@ -141,7 +260,7 @@ impl EnvironmentManager {
/// paths used by filesystem helpers.
#[derive(Clone)]
pub struct Environment {
exec_server_url: Option<String>,
remote_transport: Option<RemoteExecServerTransport>,
exec_backend: Arc<dyn ExecBackend>,
filesystem: Arc<dyn ExecutorFileSystem>,
local_runtime_paths: Option<ExecServerRuntimePaths>,
@@ -150,7 +269,7 @@ pub struct Environment {
impl Default for Environment {
fn default() -> Self {
Self {
exec_server_url: None,
remote_transport: None,
exec_backend: Arc::new(LocalProcess::default()),
filesystem: Arc::new(LocalFileSystem::unsandboxed()),
local_runtime_paths: None,
@@ -161,7 +280,7 @@ impl Default for Environment {
impl std::fmt::Debug for Environment {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Environment")
.field("exec_server_url", &self.exec_server_url)
.field("remote_transport", &self.remote_transport)
.finish_non_exhaustive()
}
}
@@ -186,9 +305,12 @@ impl Environment {
}
Ok(match exec_server_url {
Some(exec_server_url) => {
Self::remote_with_runtime_paths(exec_server_url, local_runtime_paths)
}
Some(exec_server_url) => Self::remote_with_runtime_paths(
RemoteExecServerTransport::WebSocket {
url: exec_server_url,
},
local_runtime_paths,
),
None => Self::local_with_runtime_paths(local_runtime_paths),
})
}
@@ -200,7 +322,7 @@ impl Environment {
};
Self {
exec_server_url: None,
remote_transport: None,
exec_backend: Arc::new(LocalProcess::default()),
filesystem,
local_runtime_paths,
@@ -208,15 +330,15 @@ impl Environment {
}
fn remote_with_runtime_paths(
exec_server_url: String,
transport: RemoteExecServerTransport,
local_runtime_paths: Option<ExecServerRuntimePaths>,
) -> Self {
let client = LazyRemoteExecServerClient::new(exec_server_url.clone());
let client = LazyRemoteExecServerClient::new(transport.clone());
let exec_backend: Arc<dyn ExecBackend> = Arc::new(RemoteProcess::new(client.clone()));
let filesystem: Arc<dyn ExecutorFileSystem> = Arc::new(RemoteFileSystem::new(client));
Self {
exec_server_url: Some(exec_server_url),
remote_transport: Some(transport),
exec_backend,
filesystem,
local_runtime_paths,
@@ -224,12 +346,22 @@ impl Environment {
}
pub fn is_remote(&self) -> bool {
self.exec_server_url.is_some()
self.remote_transport.is_some()
}
/// Returns the remote exec-server URL when this environment is remote.
pub fn exec_server_url(&self) -> Option<&str> {
self.exec_server_url.as_deref()
match self.remote_transport.as_ref() {
Some(RemoteExecServerTransport::WebSocket { url }) => Some(url.as_str()),
Some(RemoteExecServerTransport::Command { .. }) | None => None,
}
}
pub fn exec_server_command(&self) -> Option<&str> {
match self.remote_transport.as_ref() {
Some(RemoteExecServerTransport::Command { command }) => Some(command.as_str()),
Some(RemoteExecServerTransport::WebSocket { .. }) | None => None,
}
}
pub fn local_runtime_paths(&self) -> Option<&ExecServerRuntimePaths> {
+5
View File
@@ -20,12 +20,17 @@ mod server;
pub use client::ExecServerClient;
pub use client::ExecServerError;
pub use client_api::CommandExecServerConnectArgs;
pub use client_api::ExecServerClientConnectOptions;
pub use client_api::RemoteExecServerConnectArgs;
pub use client_api::RemoteExecServerTransport;
pub use environment::CODEX_EXEC_SERVER_URL_ENV_VAR;
pub use environment::ConfiguredEnvironmentManagerArgs;
pub use environment::ConfiguredEnvironmentSpec;
pub use environment::Environment;
pub use environment::EnvironmentManager;
pub use environment::EnvironmentManagerArgs;
pub use environment::EnvironmentManagerConfig;
pub use file_system::CopyOptions;
pub use file_system::CreateDirectoryOptions;
pub use file_system::ExecutorFileSystem;
+20 -1
View File
@@ -1,5 +1,6 @@
use std::io::Write as _;
use std::net::SocketAddr;
use tokio::io;
use tokio::net::TcpListener;
use tokio_tungstenite::accept_async;
use tracing::warn;
@@ -21,7 +22,7 @@ impl std::fmt::Display for ExecServerListenUrlParseError {
match self {
ExecServerListenUrlParseError::UnsupportedListenUrl(listen_url) => write!(
f,
"unsupported --listen URL `{listen_url}`; expected `ws://IP:PORT`"
"unsupported --listen URL `{listen_url}`; expected `ws://IP:PORT` or `stdio://`"
),
ExecServerListenUrlParseError::InvalidWebSocketListenUrl(listen_url) => write!(
f,
@@ -51,10 +52,28 @@ pub(crate) async fn run_transport(
listen_url: &str,
runtime_paths: ExecServerRuntimePaths,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
if listen_url == "stdio://" {
return run_stdio(runtime_paths).await;
}
let bind_address = parse_listen_url(listen_url)?;
run_websocket_listener(bind_address, runtime_paths).await
}
async fn run_stdio(
runtime_paths: ExecServerRuntimePaths,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let processor = ConnectionProcessor::new(runtime_paths);
processor
.run_connection(JsonRpcConnection::from_stdio(
io::stdin(),
io::stdout(),
"exec-server stdio".to_string(),
))
.await;
Ok(())
}
async fn run_websocket_listener(
bind_address: SocketAddr,
runtime_paths: ExecServerRuntimePaths,