Implement environment-bound exec plumbing

Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
starr-openai
2026-03-20 18:52:02 -07:00
co-authored by Codex
parent fc135afd78
commit 2de2b1bfbd
77 changed files with 1775 additions and 53 deletions
+64
View File
@@ -25,16 +25,31 @@ use tracing::warn;
use crate::connection::JsonRpcConnection;
use crate::process::ExecServerEvent;
use crate::protocol::ENVIRONMENT_CAPABILITIES_METHOD;
use crate::protocol::ENVIRONMENT_GET_METHOD;
use crate::protocol::ENVIRONMENT_LIST_METHOD;
use crate::protocol::EXEC_EXITED_METHOD;
use crate::protocol::EXEC_METHOD;
use crate::protocol::EXEC_OUTPUT_DELTA_METHOD;
use crate::protocol::EXEC_READ_METHOD;
use crate::protocol::EXEC_RESIZE_METHOD;
use crate::protocol::EXEC_TERMINATE_METHOD;
use crate::protocol::EXEC_WAIT_METHOD;
use crate::protocol::EXEC_WRITE_METHOD;
use crate::protocol::EnvironmentCapabilitiesParams;
use crate::protocol::EnvironmentCapabilitiesResponse;
use crate::protocol::EnvironmentGetParams;
use crate::protocol::EnvironmentGetResponse;
use crate::protocol::EnvironmentListParams;
use crate::protocol::EnvironmentListResponse;
use crate::protocol::ExecExitedNotification;
use crate::protocol::ExecOutputDeltaNotification;
use crate::protocol::ExecParams;
use crate::protocol::ExecResizeParams;
use crate::protocol::ExecResizeResponse;
use crate::protocol::ExecResponse;
use crate::protocol::ExecWaitParams;
use crate::protocol::ExecWaitResponse;
use crate::protocol::FS_COPY_METHOD;
use crate::protocol::FS_CREATE_DIRECTORY_METHOD;
use crate::protocol::FS_GET_METADATA_METHOD;
@@ -245,6 +260,55 @@ impl ExecServerClient {
.map_err(Into::into)
}
pub async fn resize(
&self,
params: ExecResizeParams,
) -> Result<ExecResizeResponse, ExecServerError> {
self.inner
.client
.call(EXEC_RESIZE_METHOD, &params)
.await
.map_err(Into::into)
}
pub async fn wait(&self, params: ExecWaitParams) -> Result<ExecWaitResponse, ExecServerError> {
self.inner
.client
.call(EXEC_WAIT_METHOD, &params)
.await
.map_err(Into::into)
}
pub async fn environment_list(&self) -> Result<EnvironmentListResponse, ExecServerError> {
self.inner
.client
.call(ENVIRONMENT_LIST_METHOD, &EnvironmentListParams::default())
.await
.map_err(Into::into)
}
pub async fn environment_get(
&self,
params: EnvironmentGetParams,
) -> Result<EnvironmentGetResponse, ExecServerError> {
self.inner
.client
.call(ENVIRONMENT_GET_METHOD, &params)
.await
.map_err(Into::into)
}
pub async fn environment_capabilities(
&self,
params: EnvironmentCapabilitiesParams,
) -> Result<EnvironmentCapabilitiesResponse, ExecServerError> {
self.inner
.client
.call(ENVIRONMENT_CAPABILITIES_METHOD, &params)
.await
.map_err(Into::into)
}
pub async fn fs_read_file(
&self,
params: FsReadFileParams,
+316 -15
View File
@@ -1,5 +1,9 @@
use std::sync::Arc;
use async_trait::async_trait;
use base64::Engine as _;
use codex_utils_absolute_path::AbsolutePathBuf;
use crate::ExecServerClient;
use crate::ExecServerError;
use crate::RemoteExecServerConnectArgs;
@@ -7,8 +11,196 @@ use crate::fs;
use crate::fs::ExecutorFileSystem;
use crate::local_process::LocalProcess;
use crate::process::ExecProcess;
use crate::protocol::EnvironmentCapabilities;
use crate::protocol::EnvironmentCapabilitiesParams;
use crate::protocol::EnvironmentGetParams;
use crate::protocol::EnvironmentGetResponse;
use crate::protocol::EnvironmentInfo;
use crate::protocol::EnvironmentListResponse;
use crate::remote_process::RemoteProcess;
#[derive(Clone)]
struct EnvironmentFileSystem {
filesystem: Arc<dyn ExecutorFileSystem>,
}
#[async_trait]
impl ExecutorFileSystem for EnvironmentFileSystem {
async fn read_file(&self, path: &AbsolutePathBuf) -> crate::fs::FileSystemResult<Vec<u8>> {
self.filesystem.read_file(path).await
}
async fn write_file(
&self,
path: &AbsolutePathBuf,
contents: Vec<u8>,
) -> crate::fs::FileSystemResult<()> {
self.filesystem.write_file(path, contents).await
}
async fn create_directory(
&self,
path: &AbsolutePathBuf,
options: crate::fs::CreateDirectoryOptions,
) -> crate::fs::FileSystemResult<()> {
self.filesystem.create_directory(path, options).await
}
async fn get_metadata(
&self,
path: &AbsolutePathBuf,
) -> crate::fs::FileSystemResult<crate::fs::FileMetadata> {
self.filesystem.get_metadata(path).await
}
async fn read_directory(
&self,
path: &AbsolutePathBuf,
) -> crate::fs::FileSystemResult<Vec<crate::fs::ReadDirectoryEntry>> {
self.filesystem.read_directory(path).await
}
async fn remove(
&self,
path: &AbsolutePathBuf,
options: crate::fs::RemoveOptions,
) -> crate::fs::FileSystemResult<()> {
self.filesystem.remove(path, options).await
}
async fn copy(
&self,
source_path: &AbsolutePathBuf,
destination_path: &AbsolutePathBuf,
options: crate::fs::CopyOptions,
) -> crate::fs::FileSystemResult<()> {
self.filesystem
.copy(source_path, destination_path, options)
.await
}
}
#[derive(Clone)]
struct RemoteEnvironmentFileSystem {
client: ExecServerClient,
}
#[async_trait]
impl ExecutorFileSystem for RemoteEnvironmentFileSystem {
async fn read_file(&self, path: &AbsolutePathBuf) -> crate::fs::FileSystemResult<Vec<u8>> {
let response = self
.client
.fs_read_file(codex_app_server_protocol::FsReadFileParams { path: path.clone() })
.await
.map_err(exec_server_error_to_io)?;
base64::engine::general_purpose::STANDARD
.decode(response.data_base64)
.map_err(|err| std::io::Error::new(std::io::ErrorKind::InvalidData, err))
}
async fn write_file(
&self,
path: &AbsolutePathBuf,
contents: Vec<u8>,
) -> crate::fs::FileSystemResult<()> {
self.client
.fs_write_file(codex_app_server_protocol::FsWriteFileParams {
path: path.clone(),
data_base64: base64::engine::general_purpose::STANDARD.encode(contents),
})
.await
.map_err(exec_server_error_to_io)?;
Ok(())
}
async fn create_directory(
&self,
path: &AbsolutePathBuf,
options: crate::fs::CreateDirectoryOptions,
) -> crate::fs::FileSystemResult<()> {
self.client
.fs_create_directory(codex_app_server_protocol::FsCreateDirectoryParams {
path: path.clone(),
recursive: Some(options.recursive),
})
.await
.map_err(exec_server_error_to_io)?;
Ok(())
}
async fn get_metadata(
&self,
path: &AbsolutePathBuf,
) -> crate::fs::FileSystemResult<crate::fs::FileMetadata> {
let response = self
.client
.fs_get_metadata(codex_app_server_protocol::FsGetMetadataParams { path: path.clone() })
.await
.map_err(exec_server_error_to_io)?;
Ok(crate::fs::FileMetadata {
is_directory: response.is_directory,
is_file: response.is_file,
created_at_ms: response.created_at_ms,
modified_at_ms: response.modified_at_ms,
})
}
async fn read_directory(
&self,
path: &AbsolutePathBuf,
) -> crate::fs::FileSystemResult<Vec<crate::fs::ReadDirectoryEntry>> {
let response = self
.client
.fs_read_directory(codex_app_server_protocol::FsReadDirectoryParams {
path: path.clone(),
})
.await
.map_err(exec_server_error_to_io)?;
Ok(response
.entries
.into_iter()
.map(|entry| crate::fs::ReadDirectoryEntry {
file_name: entry.file_name,
is_directory: entry.is_directory,
is_file: entry.is_file,
})
.collect())
}
async fn remove(
&self,
path: &AbsolutePathBuf,
options: crate::fs::RemoveOptions,
) -> crate::fs::FileSystemResult<()> {
self.client
.fs_remove(codex_app_server_protocol::FsRemoveParams {
path: path.clone(),
recursive: Some(options.recursive),
force: Some(options.force),
})
.await
.map_err(exec_server_error_to_io)?;
Ok(())
}
async fn copy(
&self,
source_path: &AbsolutePathBuf,
destination_path: &AbsolutePathBuf,
options: crate::fs::CopyOptions,
) -> crate::fs::FileSystemResult<()> {
self.client
.fs_copy(codex_app_server_protocol::FsCopyParams {
source_path: source_path.clone(),
destination_path: destination_path.clone(),
recursive: options.recursive,
})
.await
.map_err(exec_server_error_to_io)?;
Ok(())
}
}
pub trait ExecutorEnvironment: Send + Sync {
fn get_executor(&self) -> Arc<dyn ExecProcess>;
}
@@ -16,14 +208,20 @@ pub trait ExecutorEnvironment: Send + Sync {
#[derive(Clone)]
pub struct Environment {
experimental_exec_server_url: Option<String>,
environment_id: String,
capabilities: EnvironmentCapabilities,
executor: Arc<dyn ExecProcess>,
filesystem: Arc<dyn ExecutorFileSystem>,
}
impl Default for Environment {
fn default() -> Self {
Self {
experimental_exec_server_url: None,
environment_id: "local".to_string(),
capabilities: EnvironmentCapabilities::default(),
executor: Arc::new(LocalProcess::default()),
filesystem: Arc::new(fs::LocalFileSystem),
}
}
}
@@ -35,27 +233,42 @@ impl std::fmt::Debug for Environment {
"experimental_exec_server_url",
&self.experimental_exec_server_url,
)
.field(
"has_remote_exec_server_client",
&self.experimental_exec_server_url.is_some(),
)
.field("environment_id", &self.environment_id)
.field("capabilities", &self.capabilities)
.finish()
}
}
impl Environment {
pub fn default_environment_id(experimental_exec_server_url: Option<&str>) -> String {
experimental_exec_server_url.map_or_else(
|| "local".to_string(),
|websocket_url| format!("remote:{websocket_url}"),
)
}
pub async fn create(
experimental_exec_server_url: Option<String>,
) -> Result<Self, ExecServerError> {
let executor: Arc<dyn ExecProcess> =
let (environment_id, executor, filesystem, capabilities) =
if let Some(websocket_url) = experimental_exec_server_url.as_deref() {
Arc::new(RemoteProcess::new(
ExecServerClient::connect_websocket(RemoteExecServerConnectArgs::new(
websocket_url.to_string(),
"codex-core".to_string(),
))
.await?,
let client = ExecServerClient::connect_websocket(RemoteExecServerConnectArgs::new(
websocket_url.to_string(),
"codex-core".to_string(),
))
.await?;
let environment_id = Environment::default_environment_id(Some(websocket_url));
let capabilities = client
.environment_capabilities(EnvironmentCapabilitiesParams {
environment_id: environment_id.clone(),
})
.await
.map(|response| response.capabilities)
.unwrap_or_else(|_| EnvironmentCapabilities::default());
let executor = Arc::new(RemoteProcess::new(client.clone())) as Arc<dyn ExecProcess>;
let filesystem =
Arc::new(RemoteEnvironmentFileSystem { client }) as Arc<dyn ExecutorFileSystem>;
(environment_id, executor, filesystem, capabilities)
} else {
let process = LocalProcess::default();
process
@@ -65,12 +278,20 @@ impl Environment {
message: error.message,
})?;
process.initialized().map_err(ExecServerError::Protocol)?;
Arc::new(process)
(
Environment::default_environment_id(None),
Arc::new(process) as Arc<dyn ExecProcess>,
Arc::new(fs::LocalFileSystem) as Arc<dyn ExecutorFileSystem>,
EnvironmentCapabilities::default(),
)
};
Ok(Self {
experimental_exec_server_url,
environment_id,
capabilities,
executor,
filesystem,
})
}
@@ -78,30 +299,110 @@ impl Environment {
self.experimental_exec_server_url.as_deref()
}
pub fn environment_id(&self) -> &str {
&self.environment_id
}
pub fn capabilities(&self) -> &EnvironmentCapabilities {
&self.capabilities
}
pub fn info(&self) -> EnvironmentInfo {
EnvironmentInfo {
environment_id: self.environment_id.clone(),
experimental_exec_server_url: self.experimental_exec_server_url.clone(),
capabilities: self.capabilities.clone(),
}
}
pub fn list_response(&self) -> EnvironmentListResponse {
EnvironmentListResponse {
environments: vec![self.info()],
}
}
pub fn get_response(
&self,
params: EnvironmentGetParams,
) -> Result<EnvironmentGetResponse, ExecServerError> {
if params.environment_id != self.environment_id {
return Err(ExecServerError::Protocol(format!(
"unknown environment id `{}`",
params.environment_id
)));
}
Ok(EnvironmentGetResponse {
environment: self.info(),
})
}
pub fn get_executor(&self) -> Arc<dyn ExecProcess> {
Arc::clone(&self.executor)
}
pub fn get_filesystem(&self) -> impl ExecutorFileSystem + use<> {
fs::LocalFileSystem
EnvironmentFileSystem {
filesystem: Arc::clone(&self.filesystem),
}
}
}
fn exec_server_error_to_io(err: ExecServerError) -> std::io::Error {
std::io::Error::other(err.to_string())
}
impl ExecutorEnvironment for Environment {
fn get_executor(&self) -> Arc<dyn ExecProcess> {
self.get_executor()
Arc::clone(&self.executor)
}
}
#[cfg(test)]
mod tests {
use super::Environment;
use super::EnvironmentCapabilities;
use crate::fs::ExecutorFileSystem;
use codex_utils_absolute_path::AbsolutePathBuf;
use pretty_assertions::assert_eq;
use tempfile::tempdir;
#[tokio::test]
async fn create_without_remote_exec_server_url_does_not_connect() {
async fn default_environment_uses_local_identity_and_capabilities() {
let environment = Environment::default();
assert_eq!(environment.experimental_exec_server_url(), None);
assert_eq!(environment.environment_id(), "local");
assert_eq!(
environment.capabilities(),
&EnvironmentCapabilities::default()
);
}
#[tokio::test]
async fn create_without_remote_exec_server_url_uses_local_identity_and_capabilities() {
let environment = Environment::create(None).await.expect("create environment");
assert_eq!(environment.experimental_exec_server_url(), None);
assert_eq!(environment.environment_id(), "local");
assert_eq!(
environment.capabilities(),
&EnvironmentCapabilities::default()
);
}
#[tokio::test]
async fn default_environment_filesystem_delegates_to_local_filesystem() {
let temp_dir = tempdir().expect("temp dir");
let file_path = AbsolutePathBuf::try_from(temp_dir.path().join("example.txt"))
.expect("absolute file path");
std::fs::write(file_path.as_path(), b"delegated filesystem").expect("write sample file");
let bytes = Environment::default()
.get_filesystem()
.read_file(&file_path)
.await
.expect("read sample file");
assert_eq!(bytes, b"delegated filesystem");
}
}
+13
View File
@@ -40,11 +40,24 @@ pub use fs::ReadDirectoryEntry;
pub use fs::RemoveOptions;
pub use process::ExecProcess;
pub use process::ExecServerEvent;
pub use protocol::EnvironmentCapabilities;
pub use protocol::EnvironmentCapabilitiesParams;
pub use protocol::EnvironmentCapabilitiesResponse;
pub use protocol::EnvironmentGetParams;
pub use protocol::EnvironmentGetResponse;
pub use protocol::EnvironmentInfo;
pub use protocol::EnvironmentListParams;
pub use protocol::EnvironmentListResponse;
pub use protocol::ExecExitedNotification;
pub use protocol::ExecOutputDeltaNotification;
pub use protocol::ExecOutputStream;
pub use protocol::ExecParams;
pub use protocol::ExecResizeParams;
pub use protocol::ExecResizeResponse;
pub use protocol::ExecResponse;
pub use protocol::ExecTerminalSize;
pub use protocol::ExecWaitParams;
pub use protocol::ExecWaitResponse;
pub use protocol::InitializeParams;
pub use protocol::InitializeResponse;
pub use protocol::ReadParams;
+97
View File
@@ -22,7 +22,11 @@ use crate::protocol::ExecExitedNotification;
use crate::protocol::ExecOutputDeltaNotification;
use crate::protocol::ExecOutputStream;
use crate::protocol::ExecParams;
use crate::protocol::ExecResizeParams;
use crate::protocol::ExecResizeResponse;
use crate::protocol::ExecResponse;
use crate::protocol::ExecWaitParams;
use crate::protocol::ExecWaitResponse;
use crate::protocol::InitializeResponse;
use crate::protocol::ProcessOutputChunk;
use crate::protocol::ReadParams;
@@ -353,6 +357,88 @@ impl LocalProcess {
Ok(WriteResponse { accepted: true })
}
pub(crate) async fn resize_process(
&self,
params: ExecResizeParams,
) -> Result<ExecResizeResponse, JSONRPCErrorError> {
self.require_initialized_for("exec")?;
let size = TerminalSize {
rows: params.size.rows,
cols: params.size.cols,
};
{
let process_map = self.inner.processes.lock().await;
let process = process_map.get(&params.process_id).ok_or_else(|| {
invalid_request(format!("unknown process id {}", params.process_id))
})?;
let ProcessEntry::Running(process) = process else {
return Err(invalid_request(format!(
"process id {} is starting",
params.process_id
)));
};
if process.exit_code.is_some() {
return Err(invalid_request(format!(
"process id {} has already exited",
params.process_id
)));
}
if !process.tty {
return Err(invalid_request(format!(
"process id {} is not attached to a tty",
params.process_id
)));
}
process
.session
.resize(size)
.map_err(|err| internal_error(err.to_string()))?;
}
Ok(ExecResizeResponse {})
}
pub(crate) async fn wait_process(
&self,
params: ExecWaitParams,
) -> Result<ExecWaitResponse, JSONRPCErrorError> {
self.require_initialized_for("exec")?;
let wait = Duration::from_millis(params.wait_ms.unwrap_or(0));
let deadline = tokio::time::Instant::now() + wait;
loop {
let (response, output_notify) = {
let process_map = self.inner.processes.lock().await;
let process = process_map.get(&params.process_id).ok_or_else(|| {
invalid_request(format!("unknown process id {}", params.process_id))
})?;
let ProcessEntry::Running(process) = process else {
return Err(invalid_request(format!(
"process id {} is starting",
params.process_id
)));
};
(
ExecWaitResponse {
exited: process.exit_code.is_some(),
exit_code: process.exit_code,
},
Arc::clone(&process.output_notify),
)
};
if response.exited || tokio::time::Instant::now() >= deadline {
return Ok(response);
}
let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
if remaining.is_zero() {
return Ok(response);
}
let _ = tokio::time::timeout(remaining, output_notify.notified()).await;
}
}
pub(crate) async fn terminate_process(
&self,
params: TerminateParams,
@@ -399,6 +485,17 @@ impl ExecProcess for LocalProcess {
.map_err(map_handler_error)
}
async fn resize(
&self,
params: ExecResizeParams,
) -> Result<ExecResizeResponse, ExecServerError> {
self.resize_process(params).await.map_err(map_handler_error)
}
async fn wait(&self, params: ExecWaitParams) -> Result<ExecWaitResponse, ExecServerError> {
self.wait_process(params).await.map_err(map_handler_error)
}
async fn terminate(&self, process_id: &str) -> Result<TerminateResponse, ExecServerError> {
self.terminate_process(TerminateParams {
process_id: process_id.to_string(),
+9
View File
@@ -5,7 +5,11 @@ use crate::ExecServerError;
use crate::protocol::ExecExitedNotification;
use crate::protocol::ExecOutputDeltaNotification;
use crate::protocol::ExecParams;
use crate::protocol::ExecResizeParams;
use crate::protocol::ExecResizeResponse;
use crate::protocol::ExecResponse;
use crate::protocol::ExecWaitParams;
use crate::protocol::ExecWaitResponse;
use crate::protocol::ReadParams;
use crate::protocol::ReadResponse;
use crate::protocol::TerminateResponse;
@@ -29,6 +33,11 @@ pub trait ExecProcess: Send + Sync {
chunk: Vec<u8>,
) -> Result<WriteResponse, ExecServerError>;
async fn resize(&self, params: ExecResizeParams)
-> Result<ExecResizeResponse, ExecServerError>;
async fn wait(&self, params: ExecWaitParams) -> Result<ExecWaitResponse, ExecServerError>;
async fn terminate(&self, process_id: &str) -> Result<TerminateResponse, ExecServerError>;
fn subscribe_events(&self) -> broadcast::Receiver<ExecServerEvent>;
+223
View File
@@ -11,8 +11,13 @@ pub const EXEC_METHOD: &str = "process/start";
pub const EXEC_READ_METHOD: &str = "process/read";
pub const EXEC_WRITE_METHOD: &str = "process/write";
pub const EXEC_TERMINATE_METHOD: &str = "process/terminate";
pub const EXEC_RESIZE_METHOD: &str = "process/resize";
pub const EXEC_WAIT_METHOD: &str = "process/wait";
pub const EXEC_OUTPUT_DELTA_METHOD: &str = "process/output";
pub const EXEC_EXITED_METHOD: &str = "process/exited";
pub const ENVIRONMENT_LIST_METHOD: &str = "environment/list";
pub const ENVIRONMENT_GET_METHOD: &str = "environment/get";
pub const ENVIRONMENT_CAPABILITIES_METHOD: &str = "environment/capabilities";
pub const FS_READ_FILE_METHOD: &str = "fs/readFile";
pub const FS_WRITE_FILE_METHOD: &str = "fs/writeFile";
pub const FS_CREATE_DIRECTORY_METHOD: &str = "fs/createDirectory";
@@ -60,6 +65,38 @@ pub struct ExecParams {
pub arg0: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExecTerminalSize {
pub rows: u16,
pub cols: u16,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExecResizeParams {
pub process_id: String,
pub size: ExecTerminalSize,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExecResizeResponse {}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExecWaitParams {
pub process_id: String,
pub wait_ms: Option<u64>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExecWaitResponse {
pub exited: bool,
pub exit_code: Option<i32>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExecResponse {
@@ -140,6 +177,67 @@ pub struct ExecExitedNotification {
pub exit_code: i32,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EnvironmentCapabilities {
pub filesystem: bool,
pub process_resize: bool,
pub process_wait: bool,
}
impl Default for EnvironmentCapabilities {
fn default() -> Self {
Self {
filesystem: true,
process_resize: true,
process_wait: true,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EnvironmentInfo {
pub environment_id: String,
pub experimental_exec_server_url: Option<String>,
pub capabilities: EnvironmentCapabilities,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EnvironmentListParams {}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EnvironmentListResponse {
pub environments: Vec<EnvironmentInfo>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EnvironmentGetParams {
pub environment_id: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EnvironmentGetResponse {
pub environment: EnvironmentInfo,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EnvironmentCapabilitiesParams {
pub environment_id: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EnvironmentCapabilitiesResponse {
pub environment_id: String,
pub capabilities: EnvironmentCapabilities,
}
mod base64_bytes {
use super::BASE64_STANDARD;
use base64::Engine as _;
@@ -164,3 +262,128 @@ mod base64_bytes {
.map_err(serde::de::Error::custom)
}
}
#[cfg(test)]
mod tests {
use super::EnvironmentCapabilities;
use super::EnvironmentCapabilitiesParams;
use super::EnvironmentCapabilitiesResponse;
use super::EnvironmentGetParams;
use super::EnvironmentGetResponse;
use super::EnvironmentInfo;
use super::EnvironmentListParams;
use super::EnvironmentListResponse;
use super::ExecResizeParams;
use super::ExecTerminalSize;
use super::ExecWaitParams;
use super::ExecWaitResponse;
use pretty_assertions::assert_eq;
#[test]
fn environment_payloads_round_trip() {
let capabilities = EnvironmentCapabilities::default();
let info = EnvironmentInfo {
environment_id: "local".to_string(),
experimental_exec_server_url: None,
capabilities: capabilities.clone(),
};
let list_response = EnvironmentListResponse {
environments: vec![info.clone()],
};
let get_response = EnvironmentGetResponse {
environment: info.clone(),
};
let capabilities_response = EnvironmentCapabilitiesResponse {
environment_id: info.environment_id,
capabilities,
};
assert_eq!(
serde_json::to_value(EnvironmentListParams {}).expect("serialize list params"),
serde_json::json!({})
);
assert_eq!(
serde_json::from_value::<EnvironmentListParams>(serde_json::json!({}))
.expect("deserialize list params"),
EnvironmentListParams {}
);
assert_eq!(
serde_json::from_value::<EnvironmentListResponse>(
serde_json::to_value(&list_response).expect("serialize list response"),
)
.expect("deserialize list response"),
list_response
);
assert_eq!(
serde_json::from_value::<EnvironmentGetParams>(serde_json::json!({
"environmentId": "local"
}))
.expect("deserialize get params"),
EnvironmentGetParams {
environment_id: "local".to_string(),
}
);
assert_eq!(
serde_json::from_value::<EnvironmentGetResponse>(
serde_json::to_value(&get_response).expect("serialize get response"),
)
.expect("deserialize get response"),
get_response
);
assert_eq!(
serde_json::from_value::<EnvironmentCapabilitiesParams>(serde_json::json!({
"environmentId": "local"
}))
.expect("deserialize capabilities params"),
EnvironmentCapabilitiesParams {
environment_id: "local".to_string(),
}
);
assert_eq!(
serde_json::from_value::<EnvironmentCapabilitiesResponse>(
serde_json::to_value(&capabilities_response)
.expect("serialize capabilities response"),
)
.expect("deserialize capabilities response"),
capabilities_response
);
}
#[test]
fn process_payloads_round_trip() {
let resize_params = ExecResizeParams {
process_id: "proc-1".to_string(),
size: ExecTerminalSize { rows: 24, cols: 80 },
};
let wait_params = ExecWaitParams {
process_id: "proc-1".to_string(),
wait_ms: Some(250),
};
let wait_response = ExecWaitResponse {
exited: true,
exit_code: Some(0),
};
assert_eq!(
serde_json::from_value::<ExecResizeParams>(
serde_json::to_value(&resize_params).expect("serialize resize params"),
)
.expect("deserialize resize params"),
resize_params
);
assert_eq!(
serde_json::from_value::<ExecWaitParams>(
serde_json::to_value(&wait_params).expect("serialize wait params"),
)
.expect("deserialize wait params"),
wait_params
);
assert_eq!(
serde_json::from_value::<ExecWaitResponse>(
serde_json::to_value(&wait_response).expect("serialize wait response"),
)
.expect("deserialize wait response"),
wait_response
);
}
}
@@ -6,7 +6,11 @@ use crate::ExecServerClient;
use crate::ExecServerError;
use crate::ExecServerEvent;
use crate::protocol::ExecParams;
use crate::protocol::ExecResizeParams;
use crate::protocol::ExecResizeResponse;
use crate::protocol::ExecResponse;
use crate::protocol::ExecWaitParams;
use crate::protocol::ExecWaitResponse;
use crate::protocol::ReadParams;
use crate::protocol::ReadResponse;
use crate::protocol::TerminateResponse;
@@ -41,6 +45,17 @@ impl ExecProcess for RemoteProcess {
self.client.write(process_id, chunk).await
}
async fn resize(
&self,
params: ExecResizeParams,
) -> Result<ExecResizeResponse, ExecServerError> {
self.client.resize(params).await
}
async fn wait(&self, params: ExecWaitParams) -> Result<ExecWaitResponse, ExecServerError> {
self.client.wait(params).await
}
async fn terminate(&self, process_id: &str) -> Result<TerminateResponse, ExecServerError> {
self.client.terminate(process_id).await
}
@@ -35,8 +35,14 @@ pub(crate) struct ExecServerFileSystem {
impl Default for ExecServerFileSystem {
fn default() -> Self {
Self::new(&Environment::default())
}
}
impl ExecServerFileSystem {
pub(crate) fn new(environment: &Environment) -> Self {
Self {
file_system: Arc::new(Environment::default().get_filesystem()),
file_system: Arc::new(environment.get_filesystem()),
}
}
}
+78 -1
View File
@@ -14,8 +14,21 @@ use codex_app_server_protocol::FsWriteFileParams;
use codex_app_server_protocol::FsWriteFileResponse;
use codex_app_server_protocol::JSONRPCErrorError;
use crate::Environment;
use crate::EnvironmentCapabilities;
use crate::EnvironmentCapabilitiesParams;
use crate::EnvironmentCapabilitiesResponse;
use crate::EnvironmentGetParams;
use crate::EnvironmentGetResponse;
use crate::EnvironmentInfo;
use crate::EnvironmentListParams;
use crate::EnvironmentListResponse;
use crate::protocol::ExecParams;
use crate::protocol::ExecResizeParams;
use crate::protocol::ExecResizeResponse;
use crate::protocol::ExecResponse;
use crate::protocol::ExecWaitParams;
use crate::protocol::ExecWaitResponse;
use crate::protocol::InitializeResponse;
use crate::protocol::ReadParams;
use crate::protocol::ReadResponse;
@@ -30,13 +43,20 @@ use crate::server::process_handler::ExecServerProcess;
pub(crate) struct ExecServerHandler {
process: ExecServerProcess,
file_system: ExecServerFileSystem,
environment: EnvironmentInfo,
}
impl ExecServerHandler {
pub(crate) fn new(notifications: RpcNotificationSender) -> Self {
let environment = EnvironmentInfo {
environment_id: Environment::default_environment_id(None),
experimental_exec_server_url: None,
capabilities: EnvironmentCapabilities::default(),
};
Self {
process: ExecServerProcess::new(notifications),
file_system: ExecServerFileSystem::default(),
file_system: ExecServerFileSystem::new(&Environment::default()),
environment,
}
}
@@ -77,6 +97,63 @@ impl ExecServerHandler {
self.process.terminate(params).await
}
pub(crate) async fn resize(
&self,
params: ExecResizeParams,
) -> Result<ExecResizeResponse, JSONRPCErrorError> {
self.process.resize(params).await
}
pub(crate) async fn wait(
&self,
params: ExecWaitParams,
) -> Result<ExecWaitResponse, JSONRPCErrorError> {
self.process.wait(params).await
}
pub(crate) async fn environment_list(
&self,
_params: EnvironmentListParams,
) -> Result<EnvironmentListResponse, JSONRPCErrorError> {
self.process.require_initialized_for("environment")?;
Ok(EnvironmentListResponse {
environments: vec![self.environment.clone()],
})
}
pub(crate) async fn environment_get(
&self,
params: EnvironmentGetParams,
) -> Result<EnvironmentGetResponse, JSONRPCErrorError> {
self.process.require_initialized_for("environment")?;
if params.environment_id != self.environment.environment_id {
return Err(crate::rpc::invalid_request(format!(
"unknown environment id `{}`",
params.environment_id
)));
}
Ok(EnvironmentGetResponse {
environment: self.environment.clone(),
})
}
pub(crate) async fn environment_capabilities(
&self,
params: EnvironmentCapabilitiesParams,
) -> Result<EnvironmentCapabilitiesResponse, JSONRPCErrorError> {
self.process.require_initialized_for("environment")?;
if params.environment_id != self.environment.environment_id {
return Err(crate::rpc::invalid_request(format!(
"unknown environment id `{}`",
params.environment_id
)));
}
Ok(EnvironmentCapabilitiesResponse {
environment_id: self.environment.environment_id.clone(),
capabilities: self.environment.capabilities.clone(),
})
}
pub(crate) async fn fs_read_file(
&self,
params: FsReadFileParams,
@@ -6,7 +6,13 @@ use pretty_assertions::assert_eq;
use tokio::sync::mpsc;
use super::ExecServerHandler;
use crate::protocol::EnvironmentCapabilitiesParams;
use crate::protocol::EnvironmentGetParams;
use crate::protocol::EnvironmentListParams;
use crate::protocol::ExecParams;
use crate::protocol::ExecResizeParams;
use crate::protocol::ExecTerminalSize;
use crate::protocol::ExecWaitParams;
use crate::protocol::InitializeResponse;
use crate::protocol::TerminateParams;
use crate::protocol::TerminateResponse;
@@ -14,13 +20,14 @@ use crate::rpc::RpcNotificationSender;
fn exec_params(process_id: &str) -> ExecParams {
let mut env = HashMap::new();
if let Some(path) = std::env::var_os("PATH") {
env.insert("PATH".to_string(), path.to_string_lossy().into_owned());
}
env.insert(
"PATH".to_string(),
std::env::var("PATH").unwrap_or_else(|_| "/usr/bin:/bin".to_string()),
);
ExecParams {
process_id: process_id.to_string(),
argv: vec![
"bash".to_string(),
"/bin/bash".to_string(),
"-lc".to_string(),
"sleep 0.1".to_string(),
],
@@ -31,6 +38,12 @@ fn exec_params(process_id: &str) -> ExecParams {
}
}
fn tty_exec_params(process_id: &str) -> ExecParams {
let mut params = exec_params(process_id);
params.tty = true;
params
}
async fn initialized_handler() -> Arc<ExecServerHandler> {
let (outgoing_tx, _outgoing_rx) = mpsc::channel(16);
let handler = Arc::new(ExecServerHandler::new(RpcNotificationSender::new(
@@ -100,3 +113,97 @@ async fn terminate_reports_false_after_process_exit() {
handler.shutdown().await;
}
#[tokio::test]
async fn environment_list_returns_local_environment() {
let handler = initialized_handler().await;
let response = handler
.environment_list(EnvironmentListParams {})
.await
.expect("environment list");
assert_eq!(response.environments.len(), 1);
assert_eq!(response.environments[0].environment_id, "local");
assert_eq!(response.environments[0].experimental_exec_server_url, None);
assert_eq!(
response.environments[0].capabilities,
crate::protocol::EnvironmentCapabilities::default()
);
handler.shutdown().await;
}
#[tokio::test]
async fn environment_get_returns_local_environment() {
let handler = initialized_handler().await;
let response = handler
.environment_get(EnvironmentGetParams {
environment_id: "local".to_string(),
})
.await
.expect("environment get");
assert_eq!(response.environment.environment_id, "local");
handler.shutdown().await;
}
#[tokio::test]
async fn environment_capabilities_returns_local_capabilities() {
let handler = initialized_handler().await;
let response = handler
.environment_capabilities(EnvironmentCapabilitiesParams {
environment_id: "local".to_string(),
})
.await
.expect("environment capabilities");
assert_eq!(response.environment_id, "local");
assert_eq!(
response.capabilities,
crate::protocol::EnvironmentCapabilities::default()
);
handler.shutdown().await;
}
#[tokio::test]
async fn resize_and_wait_are_routed_for_running_processes() {
let handler = initialized_handler().await;
handler
.exec(tty_exec_params("proc-tty"))
.await
.expect("start tty process");
handler
.resize(ExecResizeParams {
process_id: "proc-tty".to_string(),
size: ExecTerminalSize { rows: 24, cols: 80 },
})
.await
.expect("resize tty process");
let deadline = tokio::time::Instant::now() + Duration::from_secs(1);
loop {
let response = handler
.wait(ExecWaitParams {
process_id: "proc-tty".to_string(),
wait_ms: Some(50),
})
.await
.expect("wait response");
if response.exited {
assert_eq!(response.exit_code, Some(0));
break;
}
assert!(
tokio::time::Instant::now() < deadline,
"process should have exited within 1s"
);
}
handler.shutdown().await;
}
@@ -2,7 +2,11 @@ use codex_app_server_protocol::JSONRPCErrorError;
use crate::local_process::LocalProcess;
use crate::protocol::ExecParams;
use crate::protocol::ExecResizeParams;
use crate::protocol::ExecResizeResponse;
use crate::protocol::ExecResponse;
use crate::protocol::ExecWaitParams;
use crate::protocol::ExecWaitResponse;
use crate::protocol::InitializeResponse;
use crate::protocol::ReadParams;
use crate::protocol::ReadResponse;
@@ -67,4 +71,18 @@ impl ExecServerProcess {
) -> Result<TerminateResponse, JSONRPCErrorError> {
self.process.terminate_process(params).await
}
pub(crate) async fn resize(
&self,
params: ExecResizeParams,
) -> Result<ExecResizeResponse, JSONRPCErrorError> {
self.process.resize_process(params).await
}
pub(crate) async fn wait(
&self,
params: ExecWaitParams,
) -> Result<ExecWaitResponse, JSONRPCErrorError> {
self.process.wait_process(params).await
}
}
@@ -1,10 +1,20 @@
use std::sync::Arc;
use crate::protocol::ENVIRONMENT_CAPABILITIES_METHOD;
use crate::protocol::ENVIRONMENT_GET_METHOD;
use crate::protocol::ENVIRONMENT_LIST_METHOD;
use crate::protocol::EXEC_METHOD;
use crate::protocol::EXEC_READ_METHOD;
use crate::protocol::EXEC_RESIZE_METHOD;
use crate::protocol::EXEC_TERMINATE_METHOD;
use crate::protocol::EXEC_WAIT_METHOD;
use crate::protocol::EXEC_WRITE_METHOD;
use crate::protocol::EnvironmentCapabilitiesParams;
use crate::protocol::EnvironmentGetParams;
use crate::protocol::EnvironmentListParams;
use crate::protocol::ExecParams;
use crate::protocol::ExecResizeParams;
use crate::protocol::ExecWaitParams;
use crate::protocol::FS_COPY_METHOD;
use crate::protocol::FS_CREATE_DIRECTORY_METHOD;
use crate::protocol::FS_GET_METADATA_METHOD;
@@ -64,6 +74,36 @@ pub(crate) fn build_router() -> RpcRouter<ExecServerHandler> {
handler.terminate(params).await
},
);
router.request(
EXEC_RESIZE_METHOD,
|handler: Arc<ExecServerHandler>, params: ExecResizeParams| async move {
handler.resize(params).await
},
);
router.request(
EXEC_WAIT_METHOD,
|handler: Arc<ExecServerHandler>, params: ExecWaitParams| async move {
handler.wait(params).await
},
);
router.request(
ENVIRONMENT_LIST_METHOD,
|handler: Arc<ExecServerHandler>, params: EnvironmentListParams| async move {
handler.environment_list(params).await
},
);
router.request(
ENVIRONMENT_GET_METHOD,
|handler: Arc<ExecServerHandler>, params: EnvironmentGetParams| async move {
handler.environment_get(params).await
},
);
router.request(
ENVIRONMENT_CAPABILITIES_METHOD,
|handler: Arc<ExecServerHandler>, params: EnvironmentCapabilitiesParams| async move {
handler.environment_capabilities(params).await
},
);
router.request(
FS_READ_FILE_METHOD,
|handler: Arc<ExecServerHandler>, params: FsReadFileParams| async move {
@@ -108,3 +148,27 @@ pub(crate) fn build_router() -> RpcRouter<ExecServerHandler> {
);
router
}
#[cfg(test)]
mod tests {
use super::build_router;
use crate::protocol::ENVIRONMENT_CAPABILITIES_METHOD;
use crate::protocol::ENVIRONMENT_GET_METHOD;
use crate::protocol::ENVIRONMENT_LIST_METHOD;
use crate::protocol::EXEC_RESIZE_METHOD;
use crate::protocol::EXEC_WAIT_METHOD;
#[test]
fn build_router_registers_process_control_and_environment_routes() {
let router = build_router();
assert!(router.request_route(EXEC_RESIZE_METHOD).is_some());
assert!(router.request_route(EXEC_WAIT_METHOD).is_some());
assert!(router.request_route(ENVIRONMENT_LIST_METHOD).is_some());
assert!(router.request_route(ENVIRONMENT_GET_METHOD).is_some());
assert!(
router
.request_route(ENVIRONMENT_CAPABILITIES_METHOD)
.is_some()
);
}
}