mirror of
https://github.com/openai/codex.git
synced 2026-11-24 23:20:47 +00:00
codex: centralize sandbox spawn env preparation
Prepare sandbox env inside the sandbox transform result so core and exec-server do not have to mutate the request at their spawn boundaries. Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
@@ -242,7 +242,7 @@ The crate exports:
|
||||
- `RemoteExecServerConnectArgs`
|
||||
- protocol structs `InitializeParams` and `InitializeResponse`
|
||||
- `DEFAULT_LISTEN_URL` and `ExecServerListenUrlParseError`
|
||||
- `run_main_with_listen_url()`
|
||||
- `run_main_with_runtime()`
|
||||
- `run_main()` for embedding the websocket server in a binary
|
||||
|
||||
## Example session
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use clap::Parser;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
use std::future::Future;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
@@ -18,6 +18,26 @@ struct ExecServerArgs {
|
||||
}
|
||||
|
||||
fn main() -> anyhow::Result<()> {
|
||||
linux_sandbox_arg0_dispatch_or_else(run_main)
|
||||
}
|
||||
|
||||
async fn run_main(codex_linux_sandbox_exe: Option<PathBuf>) -> anyhow::Result<()> {
|
||||
let args = ExecServerArgs::parse();
|
||||
let runtime = codex_exec_server::ExecServerRuntimeConfig::new(codex_linux_sandbox_exe);
|
||||
codex_exec_server::run_main_with_runtime(&args.listen, runtime)
|
||||
.await
|
||||
.map_err(|err| anyhow::Error::msg(err.to_string()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Keep this standalone-server wrapper local instead of using
|
||||
// codex_arg0::arg0_dispatch_or_else: codex-arg0 owns CLI aliases such as
|
||||
// apply_patch, and depends on codex-exec-server to apply patches.
|
||||
fn linux_sandbox_arg0_dispatch_or_else<F, Fut>(main_fn: F) -> anyhow::Result<()>
|
||||
where
|
||||
F: FnOnce(Option<PathBuf>) -> Fut,
|
||||
Fut: Future<Output = anyhow::Result<()>>,
|
||||
{
|
||||
dispatch_linux_sandbox_arg0();
|
||||
|
||||
let _linux_sandbox_alias = LinuxSandboxAlias::create();
|
||||
@@ -31,14 +51,7 @@ fn main() -> anyhow::Result<()> {
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.enable_all()
|
||||
.build()?;
|
||||
runtime.block_on(async move {
|
||||
let args = ExecServerArgs::parse();
|
||||
let runtime = codex_exec_server::ExecServerRuntimeConfig::new(codex_linux_sandbox_exe);
|
||||
codex_exec_server::run_main_with_runtime(&args.listen, runtime)
|
||||
.await
|
||||
.map_err(|err| anyhow::Error::msg(err.to_string()))?;
|
||||
Ok(())
|
||||
})
|
||||
runtime.block_on(main_fn(codex_linux_sandbox_exe))
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
|
||||
@@ -4,6 +4,7 @@ use tokio::sync::OnceCell;
|
||||
|
||||
use crate::ExecServerClient;
|
||||
use crate::ExecServerError;
|
||||
use crate::ExecServerRuntimeConfig;
|
||||
use crate::RemoteExecServerConnectArgs;
|
||||
use crate::file_system::ExecutorFileSystem;
|
||||
use crate::local_file_system::LocalFileSystem;
|
||||
@@ -22,6 +23,7 @@ pub const CODEX_EXEC_SERVER_URL_ENV_VAR: &str = "CODEX_EXEC_SERVER_URL";
|
||||
pub struct EnvironmentManager {
|
||||
exec_server_url: Option<String>,
|
||||
disabled: bool,
|
||||
runtime: ExecServerRuntimeConfig,
|
||||
current_environment: OnceCell<Option<Arc<Environment>>>,
|
||||
}
|
||||
|
||||
@@ -34,17 +36,33 @@ impl Default for EnvironmentManager {
|
||||
impl EnvironmentManager {
|
||||
/// Builds a manager from the raw `CODEX_EXEC_SERVER_URL` value.
|
||||
pub fn new(exec_server_url: Option<String>) -> Self {
|
||||
Self::new_with_runtime(exec_server_url, ExecServerRuntimeConfig::detect())
|
||||
}
|
||||
|
||||
/// Builds a manager from the raw `CODEX_EXEC_SERVER_URL` value and the
|
||||
/// runtime resources available in this client process.
|
||||
pub fn new_with_runtime(
|
||||
exec_server_url: Option<String>,
|
||||
runtime: ExecServerRuntimeConfig,
|
||||
) -> Self {
|
||||
let (exec_server_url, disabled) = normalize_exec_server_url(exec_server_url);
|
||||
Self {
|
||||
exec_server_url,
|
||||
disabled,
|
||||
runtime,
|
||||
current_environment: OnceCell::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds a manager from process environment variables.
|
||||
pub fn from_env() -> Self {
|
||||
Self::new(std::env::var(CODEX_EXEC_SERVER_URL_ENV_VAR).ok())
|
||||
Self::from_env_with_runtime(ExecServerRuntimeConfig::detect())
|
||||
}
|
||||
|
||||
/// Builds a manager from process environment variables and explicit local
|
||||
/// runtime resources.
|
||||
pub fn from_env_with_runtime(runtime: ExecServerRuntimeConfig) -> Self {
|
||||
Self::new_with_runtime(std::env::var(CODEX_EXEC_SERVER_URL_ENV_VAR).ok(), runtime)
|
||||
}
|
||||
|
||||
/// Builds a manager from the currently selected environment, or from the
|
||||
@@ -54,11 +72,13 @@ impl EnvironmentManager {
|
||||
Some(environment) => Self {
|
||||
exec_server_url: environment.exec_server_url().map(str::to_owned),
|
||||
disabled: false,
|
||||
runtime: ExecServerRuntimeConfig::detect(),
|
||||
current_environment: OnceCell::new(),
|
||||
},
|
||||
None => Self {
|
||||
exec_server_url: None,
|
||||
disabled: true,
|
||||
runtime: ExecServerRuntimeConfig::detect(),
|
||||
current_environment: OnceCell::new(),
|
||||
},
|
||||
}
|
||||
@@ -82,7 +102,11 @@ impl EnvironmentManager {
|
||||
Ok(None)
|
||||
} else {
|
||||
Ok(Some(Arc::new(
|
||||
Environment::create(self.exec_server_url.clone()).await?,
|
||||
Environment::create_with_runtime(
|
||||
self.exec_server_url.clone(),
|
||||
self.runtime.clone(),
|
||||
)
|
||||
.await?,
|
||||
)))
|
||||
}
|
||||
})
|
||||
@@ -132,6 +156,15 @@ impl std::fmt::Debug for Environment {
|
||||
impl Environment {
|
||||
/// Builds an environment from the raw `CODEX_EXEC_SERVER_URL` value.
|
||||
pub async fn create(exec_server_url: Option<String>) -> Result<Self, ExecServerError> {
|
||||
Self::create_with_runtime(exec_server_url, ExecServerRuntimeConfig::detect()).await
|
||||
}
|
||||
|
||||
/// Builds an environment from the raw `CODEX_EXEC_SERVER_URL` value and
|
||||
/// runtime resources available when spawning local processes.
|
||||
pub async fn create_with_runtime(
|
||||
exec_server_url: Option<String>,
|
||||
runtime: ExecServerRuntimeConfig,
|
||||
) -> Result<Self, ExecServerError> {
|
||||
let (exec_server_url, disabled) = normalize_exec_server_url(exec_server_url);
|
||||
if disabled {
|
||||
return Err(ExecServerError::Protocol(
|
||||
@@ -161,7 +194,7 @@ impl Environment {
|
||||
));
|
||||
}
|
||||
None => {
|
||||
let local_process = LocalProcess::default();
|
||||
let local_process = LocalProcess::default_with_runtime(runtime);
|
||||
local_process
|
||||
.initialize()
|
||||
.map_err(|err| ExecServerError::Protocol(err.message))?;
|
||||
|
||||
@@ -66,5 +66,4 @@ pub use protocol::WriteStatus;
|
||||
pub use server::DEFAULT_LISTEN_URL;
|
||||
pub use server::ExecServerListenUrlParseError;
|
||||
pub use server::run_main;
|
||||
pub use server::run_main_with_listen_url;
|
||||
pub use server::run_main_with_runtime;
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
use std::collections::HashMap;
|
||||
use std::collections::VecDeque;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
@@ -11,6 +10,7 @@ use async_trait::async_trait;
|
||||
use codex_app_server_protocol::JSONRPCErrorError;
|
||||
use codex_sandboxing::SandboxCommand;
|
||||
use codex_sandboxing::SandboxExecRequest;
|
||||
use codex_sandboxing::SandboxManager;
|
||||
use codex_sandboxing::SandboxType;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_pty::ExecCommandSession;
|
||||
@@ -123,18 +123,20 @@ struct StartedProcess {
|
||||
|
||||
impl Default for LocalProcess {
|
||||
fn default() -> Self {
|
||||
let (outgoing_tx, mut outgoing_rx) =
|
||||
mpsc::channel::<RpcServerOutboundMessage>(NOTIFICATION_CHANNEL_CAPACITY);
|
||||
tokio::spawn(async move { while outgoing_rx.recv().await.is_some() {} });
|
||||
Self::new(RpcNotificationSender::new(outgoing_tx))
|
||||
Self::default_with_runtime(ExecServerRuntimeConfig::detect())
|
||||
}
|
||||
}
|
||||
|
||||
impl LocalProcess {
|
||||
pub(crate) fn new(notifications: RpcNotificationSender) -> Self {
|
||||
Self::new_with_runtime(notifications, ExecServerRuntimeConfig::detect())
|
||||
pub(crate) fn default_with_runtime(runtime: ExecServerRuntimeConfig) -> Self {
|
||||
let (outgoing_tx, mut outgoing_rx) =
|
||||
mpsc::channel::<RpcServerOutboundMessage>(NOTIFICATION_CHANNEL_CAPACITY);
|
||||
tokio::spawn(async move { while outgoing_rx.recv().await.is_some() {} });
|
||||
Self::new_with_runtime(RpcNotificationSender::new(outgoing_tx), runtime)
|
||||
}
|
||||
}
|
||||
|
||||
impl LocalProcess {
|
||||
pub(crate) fn new_with_runtime(
|
||||
notifications: RpcNotificationSender,
|
||||
runtime: ExecServerRuntimeConfig,
|
||||
@@ -502,48 +504,33 @@ impl ExecProcess for LocalExecProcess {
|
||||
}
|
||||
}
|
||||
|
||||
fn build_sandbox_command(
|
||||
argv: &[String],
|
||||
cwd: &Path,
|
||||
env: &HashMap<String, String>,
|
||||
additional_permissions: Option<codex_protocol::models::PermissionProfile>,
|
||||
) -> Result<SandboxCommand, JSONRPCErrorError> {
|
||||
let (program, args) = argv
|
||||
.split_first()
|
||||
.ok_or_else(|| invalid_params("argv must not be empty".to_string()))?;
|
||||
Ok(SandboxCommand {
|
||||
program: program.clone().into(),
|
||||
args: args.to_vec(),
|
||||
cwd: AbsolutePathBuf::try_from(cwd)
|
||||
.map_err(|err| invalid_params(format!("cwd must be absolute: {err}")))?,
|
||||
env: env.clone(),
|
||||
additional_permissions,
|
||||
})
|
||||
}
|
||||
|
||||
fn prepare_exec_launch(
|
||||
params: &ExecParams,
|
||||
runtime: &ExecServerRuntimeConfig,
|
||||
) -> Result<SandboxExecRequest, JSONRPCErrorError> {
|
||||
let command = build_sandbox_command(
|
||||
¶ms.argv,
|
||||
params.cwd.as_path(),
|
||||
¶ms.env,
|
||||
params.sandbox.additional_permissions.clone(),
|
||||
)?;
|
||||
let mut launch = params
|
||||
.sandbox
|
||||
let (program, args) = params
|
||||
.argv
|
||||
.split_first()
|
||||
.ok_or_else(|| invalid_params("argv must not be empty".to_string()))?;
|
||||
let command = SandboxCommand {
|
||||
program: program.clone().into(),
|
||||
args: args.to_vec(),
|
||||
cwd: AbsolutePathBuf::try_from(params.cwd.as_path())
|
||||
.map_err(|err| invalid_params(format!("cwd must be absolute: {err}")))?,
|
||||
env: params.env.clone(),
|
||||
additional_permissions: params.sandbox.additional_permissions.clone(),
|
||||
};
|
||||
SandboxManager::new()
|
||||
.transform(
|
||||
command,
|
||||
¶ms.sandbox,
|
||||
// TODO: Thread managed-network proxy state across exec-server so
|
||||
// sandbox profile generation preserves proxy-specific allowances.
|
||||
/*network*/
|
||||
None,
|
||||
runtime.codex_linux_sandbox_exe.as_deref(),
|
||||
)
|
||||
.map_err(|err| internal_error(format!("failed to build sandbox launch: {err}")))?;
|
||||
launch.prepare_env_for_spawn();
|
||||
Ok(launch)
|
||||
.map_err(|err| internal_error(format!("failed to build sandbox launch: {err}")))
|
||||
}
|
||||
|
||||
impl LocalProcess {
|
||||
|
||||
@@ -10,13 +10,7 @@ pub use transport::DEFAULT_LISTEN_URL;
|
||||
pub use transport::ExecServerListenUrlParseError;
|
||||
|
||||
pub async fn run_main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
run_main_with_listen_url(DEFAULT_LISTEN_URL).await
|
||||
}
|
||||
|
||||
pub async fn run_main_with_listen_url(
|
||||
listen_url: &str,
|
||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
transport::run_transport(listen_url, crate::ExecServerRuntimeConfig::detect()).await
|
||||
run_main_with_runtime(DEFAULT_LISTEN_URL, crate::ExecServerRuntimeConfig::detect()).await
|
||||
}
|
||||
|
||||
pub async fn run_main_with_runtime(
|
||||
|
||||
Reference in New Issue
Block a user