diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 64abfaac3c..0ee45f2fc5 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1371,6 +1371,33 @@ version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e9b18233253483ce2f65329a24072ec414db782531bdbb7d0bbc4bd2ce6b7e21" +[[package]] +name = "codex-acp-server" +version = "0.0.0" +dependencies = [ + "anyhow", + "chrono", + "codex-app-server-client", + "codex-app-server-protocol", + "codex-arg0", + "codex-cloud-requirements", + "codex-core", + "codex-feedback", + "codex-protocol", + "codex-rmcp-client", + "codex-utils-cargo-bin", + "codex-utils-cli", + "futures", + "pretty_assertions", + "rmcp", + "serde", + "serde_json", + "tempfile", + "tokio", + "tracing", + "tracing-subscriber", +] + [[package]] name = "codex-ansi-escape" version = "0.0.0" @@ -1637,6 +1664,7 @@ dependencies = [ "assert_matches", "clap", "clap_complete", + "codex-acp-server", "codex-app-server", "codex-app-server-protocol", "codex-app-server-test-client", diff --git a/codex-rs/Cargo.toml b/codex-rs/Cargo.toml index 681487c099..a0087559ef 100644 --- a/codex-rs/Cargo.toml +++ b/codex-rs/Cargo.toml @@ -2,6 +2,7 @@ members = [ "backend-client", "ansi-escape", + "acp-server", "async-utils", "app-server", "app-server-client", @@ -84,6 +85,7 @@ license = "Apache-2.0" app_test_support = { path = "app-server/tests/common" } codex-ansi-escape = { path = "ansi-escape" } codex-api = { path = "codex-api" } +codex-acp-server = { path = "acp-server" } codex-artifacts = { path = "artifacts" } codex-package-manager = { path = "package-manager" } codex-app-server = { path = "app-server" } diff --git a/codex-rs/acp-server/Cargo.toml b/codex-rs/acp-server/Cargo.toml new file mode 100644 index 0000000000..9d9268ae8b --- /dev/null +++ b/codex-rs/acp-server/Cargo.toml @@ -0,0 +1,48 @@ +[package] +name = "codex-acp-server" +version.workspace = true +edition.workspace = true +license.workspace = true + +[[bin]] +name = "codex-acp-server" +path = "src/main.rs" + +[lib] +name = "codex_acp_server" +path = "src/lib.rs" + +[lints] +workspace = true + +[dependencies] +anyhow = { workspace = true } +chrono = { workspace = true } +codex-app-server-client = { workspace = true } +codex-app-server-protocol = { workspace = true } +codex-arg0 = { workspace = true } +codex-cloud-requirements = { workspace = true } +codex-core = { workspace = true } +codex-feedback = { workspace = true } +codex-protocol = { workspace = true } +codex-rmcp-client = { workspace = true } +codex-utils-cli = { workspace = true } +futures = { workspace = true, default-features = false, features = ["std"] } +rmcp = { workspace = true, default-features = false, features = ["client", "server"] } +serde = { workspace = true, features = ["derive"] } +serde_json = { workspace = true } +tokio = { workspace = true, features = [ + "io-std", + "macros", + "rt-multi-thread", + "signal", + "sync", +] } +tracing = { workspace = true, features = ["log"] } +tracing-subscriber = { workspace = true, features = ["env-filter", "fmt"] } + +[dev-dependencies] +anyhow = { workspace = true } +codex-utils-cargo-bin = { workspace = true } +pretty_assertions = { workspace = true } +tempfile = { workspace = true } diff --git a/codex-rs/acp-server/src/lib.rs b/codex-rs/acp-server/src/lib.rs new file mode 100644 index 0000000000..347cfb23fa --- /dev/null +++ b/codex-rs/acp-server/src/lib.rs @@ -0,0 +1,3224 @@ +#![deny(clippy::print_stdout, clippy::print_stderr)] + +use std::collections::HashMap; +use std::io::Error; +use std::io::ErrorKind; +use std::io::Result as IoResult; +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::Mutex as StdMutex; +use std::sync::atomic::AtomicI64; +use std::sync::atomic::Ordering; + +use chrono::SecondsFormat; +use chrono::Utc; +use codex_app_server_client::DEFAULT_IN_PROCESS_CHANNEL_CAPACITY; +use codex_app_server_client::InProcessAppServerClient; +use codex_app_server_client::InProcessClientStartArgs; +use codex_app_server_client::InProcessServerEvent; +use codex_app_server_protocol::ClientRequest; +use codex_app_server_protocol::CollaborationModeListParams; +use codex_app_server_protocol::CollaborationModeListResponse; +use codex_app_server_protocol::CollaborationModeMask; +use codex_app_server_protocol::CommandExecutionApprovalDecision; +use codex_app_server_protocol::CommandExecutionRequestApprovalParams; +use codex_app_server_protocol::CommandExecutionRequestApprovalResponse; +use codex_app_server_protocol::FileChangeApprovalDecision; +use codex_app_server_protocol::FileChangeRequestApprovalParams; +use codex_app_server_protocol::FileChangeRequestApprovalResponse; +use codex_app_server_protocol::ItemCompletedNotification; +use codex_app_server_protocol::ItemStartedNotification; +use codex_app_server_protocol::JSONRPCErrorError; +use codex_app_server_protocol::McpServerElicitationRequest as AppMcpServerElicitationRequest; +use codex_app_server_protocol::McpServerElicitationRequestParams; +use codex_app_server_protocol::McpServerElicitationRequestResponse; +use codex_app_server_protocol::Model; +use codex_app_server_protocol::ModelListParams; +use codex_app_server_protocol::ModelListResponse; +use codex_app_server_protocol::RequestId; +use codex_app_server_protocol::ServerNotification; +use codex_app_server_protocol::ServerRequest; +use codex_app_server_protocol::ThreadForkParams; +use codex_app_server_protocol::ThreadForkResponse; +use codex_app_server_protocol::ThreadItem; +use codex_app_server_protocol::ThreadListParams; +use codex_app_server_protocol::ThreadListResponse; +use codex_app_server_protocol::ThreadReadParams; +use codex_app_server_protocol::ThreadReadResponse; +use codex_app_server_protocol::ThreadResumeParams; +use codex_app_server_protocol::ThreadResumeResponse; +use codex_app_server_protocol::ThreadStartParams; +use codex_app_server_protocol::ThreadStartResponse; +use codex_app_server_protocol::ThreadUnsubscribeParams; +use codex_app_server_protocol::ThreadUnsubscribeResponse; +use codex_app_server_protocol::ToolRequestUserInputAnswer; +use codex_app_server_protocol::ToolRequestUserInputParams; +use codex_app_server_protocol::ToolRequestUserInputQuestion; +use codex_app_server_protocol::ToolRequestUserInputResponse; +use codex_app_server_protocol::TurnCompletedNotification; +use codex_app_server_protocol::TurnInterruptParams; +use codex_app_server_protocol::TurnPlanStepStatus; +use codex_app_server_protocol::TurnPlanUpdatedNotification; +use codex_app_server_protocol::TurnStartParams; +use codex_app_server_protocol::TurnStartResponse; +use codex_app_server_protocol::TurnStatus; +use codex_app_server_protocol::UserInput; +use codex_arg0::Arg0DispatchPaths; +use codex_cloud_requirements::cloud_requirements_loader; +use codex_core::AuthManager; +use codex_core::config::Config; +use codex_core::config::types::McpServerConfig; +use codex_core::config::types::McpServerTransportConfig; +use codex_core::config_loader::LoaderOverrides; +use codex_feedback::CodexFeedback; +use codex_protocol::config_types::CollaborationMode; +use codex_protocol::config_types::CollaborationModeMask as CoreCollaborationModeMask; +use codex_protocol::config_types::Settings; +use codex_protocol::openai_models::ReasoningEffort; +use codex_protocol::protocol::SessionSource; +use codex_rmcp_client::AcpBridge; +use codex_rmcp_client::AcpConnection; +use codex_rmcp_client::set_acp_bridge; +use codex_utils_cli::CliConfigOverrides; +use futures::future::BoxFuture; +use rmcp::model::ClientJsonRpcMessage; +use rmcp::model::ClientResult as McpClientResult; +use rmcp::model::ErrorCode as McpErrorCode; +use rmcp::model::ErrorData as McpErrorData; +use rmcp::model::JsonRpcError as McpJsonRpcError; +use rmcp::model::JsonRpcMessage as McpJsonRpcMessage; +use rmcp::model::JsonRpcNotification as McpJsonRpcNotification; +use rmcp::model::JsonRpcRequest as McpJsonRpcRequest; +use rmcp::model::JsonRpcResponse as McpJsonRpcResponse; +use rmcp::model::RequestId as McpRequestId; +use rmcp::model::ServerJsonRpcMessage; +use serde::de::DeserializeOwned; +use serde_json::Value as JsonValue; +use tokio::io::AsyncBufReadExt; +use tokio::io::AsyncWriteExt; +use tokio::io::BufReader; +use tokio::io::{self}; +use tokio::sync::mpsc; +use tracing::debug; +use tracing::error; +use tracing::info; +use tracing_subscriber::EnvFilter; +use tracing_subscriber::prelude::*; + +mod protocol; + +use crate::protocol::AgentCapabilities; +use crate::protocol::AgentInfo; +use crate::protocol::ConfigOption; +use crate::protocol::ConfigOptionValue; +use crate::protocol::ElicitationAction; +use crate::protocol::ElicitationCapabilities; +use crate::protocol::InitializeParams; +use crate::protocol::InitializeResult; +use crate::protocol::JSONRPC_VERSION; +use crate::protocol::JsonRpcError; +use crate::protocol::JsonRpcErrorBody; +use crate::protocol::JsonRpcMessage; +use crate::protocol::JsonRpcNotification; +use crate::protocol::JsonRpcRequest; +use crate::protocol::JsonRpcResponse; +use crate::protocol::Location; +use crate::protocol::McpCapabilities; +use crate::protocol::McpConnectParams; +use crate::protocol::McpConnectResult; +use crate::protocol::McpDisconnectParams; +use crate::protocol::McpDisconnectResult; +use crate::protocol::McpMessageParams; +use crate::protocol::McpMessageResult; +use crate::protocol::Mode; +use crate::protocol::Modes; +use crate::protocol::PROTOCOL_VERSION; +use crate::protocol::PermissionOption; +use crate::protocol::PermissionOutcome; +use crate::protocol::PermissionResponse; +use crate::protocol::PermissionToolCall; +use crate::protocol::PlanEntry; +use crate::protocol::PromptCapabilities; +use crate::protocol::PromptContent; +use crate::protocol::SessionCancelParams; +use crate::protocol::SessionCapabilities; +use crate::protocol::SessionCloseParams; +use crate::protocol::SessionCloseResult; +use crate::protocol::SessionElicitationParams; +use crate::protocol::SessionElicitationRequest; +use crate::protocol::SessionElicitationResponse; +use crate::protocol::SessionForkParams; +use crate::protocol::SessionForkResult; +use crate::protocol::SessionInfo; +use crate::protocol::SessionListParams; +use crate::protocol::SessionListResult; +use crate::protocol::SessionLoadParams; +use crate::protocol::SessionLoadResult; +use crate::protocol::SessionNewParams; +use crate::protocol::SessionNewResult; +use crate::protocol::SessionPromptParams; +use crate::protocol::SessionPromptResult; +use crate::protocol::SessionRequestPermissionParams; +use crate::protocol::SessionResumeParams; +use crate::protocol::SessionResumeResult; +use crate::protocol::SessionSetModeParams; +use crate::protocol::SessionSetModeResult; +use crate::protocol::SessionUpdate; +use crate::protocol::SessionUpdateParams; +use crate::protocol::TextContent; +use crate::protocol::ToolCallContent; + +const CHANNEL_CAPACITY: usize = 128; +const CLIENT_NAME: &str = "codex-acp-server"; + +#[derive(Clone)] +struct ModeBinding { + acp_mode: Mode, + mask: CoreCollaborationModeMask, +} + +struct SessionState { + active_turn_id: Option, + config_options: Vec, + current_mode_id: String, + current_mode: CollaborationMode, + cwd: String, + last_title: Option, + modes: Vec, + thread_id: String, +} + +impl SessionState { + fn modes_payload(&self) -> Modes { + Modes { + current_mode_id: self.current_mode_id.clone(), + available_modes: self + .modes + .iter() + .map(|binding| binding.acp_mode.clone()) + .collect(), + } + } +} + +struct PendingPrompt { + request_id: RequestId, + session_id: String, +} + +struct PendingPermissionRequest { + app_request_id: RequestId, + option_results: HashMap, + fallback_result: JsonValue, +} + +struct PendingElicitationRequest { + app_request_id: RequestId, + fallback_result: JsonValue, + kind: PendingElicitationKind, +} + +enum PendingElicitationKind { + ToolUserInput { + questions: Vec, + }, + McpServer, +} + +struct PendingMcpConnect { + responder: tokio::sync::oneshot::Sender>, +} + +struct PendingMcpDisconnect { + responder: tokio::sync::oneshot::Sender>, +} + +struct PendingMcpRequest { + inbound_tx: mpsc::UnboundedSender, + request_id: McpRequestId, +} + +struct RegisteredMcpConnection { + inbound_tx: mpsc::UnboundedSender, +} + +struct AcpBridgeState { + next_request_id: AtomicI64, + outgoing_tx: mpsc::UnboundedSender, + connections: StdMutex>, + pending_connects: StdMutex>, + pending_disconnects: StdMutex>, + pending_requests: StdMutex>, +} + +impl AcpBridgeState { + fn new(outgoing_tx: mpsc::UnboundedSender) -> Self { + Self { + next_request_id: AtomicI64::new(1), + outgoing_tx, + connections: StdMutex::new(HashMap::new()), + pending_connects: StdMutex::new(HashMap::new()), + pending_disconnects: StdMutex::new(HashMap::new()), + pending_requests: StdMutex::new(HashMap::new()), + } + } + + fn next_request_id(&self, prefix: &str) -> RequestId { + RequestId::String(format!( + "{prefix}:{}", + self.next_request_id.fetch_add(1, Ordering::Relaxed) + )) + } + + fn register_connection( + &self, + connection_id: String, + inbound_tx: mpsc::UnboundedSender, + ) { + self.connections + .lock() + .unwrap_or_else(|_| panic!("ACP MCP connections registry poisoned")) + .insert(connection_id, RegisteredMcpConnection { inbound_tx }); + } + + fn unregister_connection(&self, connection_id: &str) -> Option { + self.connections + .lock() + .unwrap_or_else(|_| panic!("ACP MCP connections registry poisoned")) + .remove(connection_id) + } + + fn connection_sender( + &self, + connection_id: &str, + ) -> Option> { + self.connections + .lock() + .unwrap_or_else(|_| panic!("ACP MCP connections registry poisoned")) + .get(connection_id) + .map(|connection| connection.inbound_tx.clone()) + } + + fn send_jsonrpc_message(&self, message: JsonRpcMessage) -> IoResult<()> { + self.outgoing_tx + .send(message) + .map_err(|_| Error::new(ErrorKind::BrokenPipe, "ACP stdout writer channel closed")) + } + + fn send_request(&self, id: RequestId, method: &str, params: JsonValue) -> IoResult<()> { + self.send_jsonrpc_message(JsonRpcMessage::Request(JsonRpcRequest { + jsonrpc: JSONRPC_VERSION.to_string(), + id, + method: method.to_string(), + params: Some(params), + })) + } + + fn send_notification(&self, method: &str, params: JsonValue) -> IoResult<()> { + self.send_jsonrpc_message(JsonRpcMessage::Notification(JsonRpcNotification { + jsonrpc: JSONRPC_VERSION.to_string(), + method: method.to_string(), + params: Some(params), + })) + } + + fn send_result(&self, id: RequestId, result: JsonValue) -> IoResult<()> { + self.send_jsonrpc_message(JsonRpcMessage::Response(JsonRpcResponse { + jsonrpc: JSONRPC_VERSION.to_string(), + id, + result, + })) + } + + fn handle_response(&self, response: JsonRpcResponse) -> bool { + if let Some(pending_connect) = self + .pending_connects + .lock() + .unwrap_or_else(|_| panic!("ACP MCP connect registry poisoned")) + .remove(&response.id) + { + let result = serde_json::from_value::(response.result) + .map_err(invalid_params_error); + let _ = pending_connect.responder.send(result); + return true; + } + + if let Some(pending_disconnect) = self + .pending_disconnects + .lock() + .unwrap_or_else(|_| panic!("ACP MCP disconnect registry poisoned")) + .remove(&response.id) + { + let result = serde_json::from_value::(response.result) + .map(|_| ()) + .map_err(invalid_params_error); + let _ = pending_disconnect.responder.send(result); + return true; + } + + let Some(pending_request) = self + .pending_requests + .lock() + .unwrap_or_else(|_| panic!("ACP MCP request registry poisoned")) + .remove(&response.id) + else { + return false; + }; + + let message = match serde_json::from_value::(response.result) { + Ok(result) => mcp_result_to_server_message(pending_request.request_id, result), + Err(error) => ServerJsonRpcMessage::Error(McpJsonRpcError { + jsonrpc: rmcp::model::JsonRpcVersion2_0, + id: pending_request.request_id, + error: McpErrorData::new( + McpErrorCode::INTERNAL_ERROR, + format!("invalid ACP mcp/message response: {error}"), + None, + ), + }), + }; + let _ = pending_request.inbound_tx.send(message); + true + } + + fn handle_error(&self, error_message: JsonRpcError) -> bool { + if let Some(pending_connect) = self + .pending_connects + .lock() + .unwrap_or_else(|_| panic!("ACP MCP connect registry poisoned")) + .remove(&error_message.id) + { + let _ = pending_connect + .responder + .send(Err(io_error_from_jsonrpc_error(&error_message.error))); + return true; + } + + if let Some(pending_disconnect) = self + .pending_disconnects + .lock() + .unwrap_or_else(|_| panic!("ACP MCP disconnect registry poisoned")) + .remove(&error_message.id) + { + let _ = pending_disconnect + .responder + .send(Err(io_error_from_jsonrpc_error(&error_message.error))); + return true; + } + + let Some(pending_request) = self + .pending_requests + .lock() + .unwrap_or_else(|_| panic!("ACP MCP request registry poisoned")) + .remove(&error_message.id) + else { + return false; + }; + + let _ = pending_request + .inbound_tx + .send(ServerJsonRpcMessage::Error(McpJsonRpcError { + jsonrpc: rmcp::model::JsonRpcVersion2_0, + id: pending_request.request_id, + error: acp_error_to_mcp_error(error_message.error), + })); + true + } +} + +struct AcpBridgeHandle { + bridge_state: Arc, +} + +struct AcpBridgeConnection { + bridge_state: Arc, + connection_id: String, + inbound_rx: Arc>>, +} + +impl AcpConnection for AcpBridgeConnection { + fn send(&self, message: ClientJsonRpcMessage) -> BoxFuture<'static, anyhow::Result<()>> { + let bridge_state = Arc::clone(&self.bridge_state); + let connection_id = self.connection_id.clone(); + Box::pin(async move { + forward_client_mcp_message(&bridge_state, &connection_id, message) + .map_err(anyhow::Error::from) + }) + } + + fn recv(&self) -> BoxFuture<'static, anyhow::Result>> { + let inbound_rx = Arc::clone(&self.inbound_rx); + Box::pin(async move { Ok(inbound_rx.lock().await.recv().await) }) + } + + fn close(&self) -> BoxFuture<'static, anyhow::Result<()>> { + let bridge_state = Arc::clone(&self.bridge_state); + let connection_id = self.connection_id.clone(); + Box::pin(async move { + close_mcp_connection(&bridge_state, &connection_id) + .await + .map_err(anyhow::Error::from) + }) + } +} + +impl AcpBridge for AcpBridgeHandle { + fn connect( + &self, + acp_id: String, + ) -> BoxFuture<'static, anyhow::Result>> { + let bridge_state = Arc::clone(&self.bridge_state); + Box::pin(async move { + let request_id = bridge_state.next_request_id("mcp-connect"); + let (responder, receiver) = tokio::sync::oneshot::channel(); + bridge_state + .pending_connects + .lock() + .unwrap_or_else(|_| panic!("ACP MCP connect registry poisoned")) + .insert(request_id.clone(), PendingMcpConnect { responder }); + bridge_state.send_request( + request_id, + "mcp/connect", + serde_json::to_value(McpConnectParams { acp_id, meta: None })?, + )?; + let result = receiver.await.map_err(|_| { + Error::new( + ErrorKind::BrokenPipe, + "ACP MCP connect response channel closed", + ) + })??; + let (inbound_tx, inbound_rx) = mpsc::unbounded_channel(); + bridge_state.register_connection(result.connection_id.clone(), inbound_tx); + Ok(Arc::new(AcpBridgeConnection { + bridge_state, + connection_id: result.connection_id, + inbound_rx: Arc::new(tokio::sync::Mutex::new(inbound_rx)), + }) as Arc) + }) + } +} + +struct AcpServer { + app_client: InProcessAppServerClient, + bridge_state: Arc, + client_elicitation_capabilities: Option, + incoming_rx: mpsc::Receiver, + initialized: bool, + next_acp_request_id: i64, + next_app_request_id: i64, + outgoing_tx: mpsc::UnboundedSender, + pending_elicitations: HashMap, + pending_permissions: HashMap, + pending_prompts: HashMap, + sessions: HashMap, +} + +impl AcpServer { + async fn run(mut self) -> IoResult<()> { + loop { + tokio::select! { + incoming = self.incoming_rx.recv() => { + let Some(message) = incoming else { + break; + }; + self.handle_incoming_message(message).await?; + } + event = self.app_client.next_event() => { + let Some(event) = event else { + break; + }; + self.handle_app_event(event).await?; + } + } + } + + self.app_client.shutdown().await + } + + async fn handle_incoming_message(&mut self, message: JsonRpcMessage) -> IoResult<()> { + match message { + JsonRpcMessage::Request(request) => self.handle_request(request).await, + JsonRpcMessage::Notification(notification) => { + self.handle_notification(notification).await + } + JsonRpcMessage::Response(response) => self.handle_response(response).await, + JsonRpcMessage::Error(error_message) => self.handle_error_message(error_message).await, + } + } + + async fn handle_request(&mut self, request: JsonRpcRequest) -> IoResult<()> { + if request.jsonrpc != JSONRPC_VERSION { + self.send_error( + request.id, + -32600, + format!("unsupported jsonrpc version: {}", request.jsonrpc), + )?; + return Ok(()); + } + + match request.method.as_str() { + "initialize" => self.handle_initialize(request).await, + "session/list" => self.handle_session_list(request).await, + "session/new" => self.handle_session_new(request).await, + "session/load" => self.handle_session_load(request).await, + "session/resume" => self.handle_session_resume(request).await, + "session/fork" => self.handle_session_fork(request).await, + "session/prompt" => self.handle_session_prompt(request).await, + "session/set_mode" => self.handle_session_set_mode(request).await, + "session/close" => self.handle_session_close(request).await, + "mcp/message" => self.handle_mcp_message_request(request).await, + "mcp/disconnect" => self.handle_mcp_disconnect(request).await, + other => { + self.send_error(request.id, -32601, format!("method not found: {other}"))?; + Ok(()) + } + } + } + + async fn handle_notification(&mut self, notification: JsonRpcNotification) -> IoResult<()> { + if notification.jsonrpc != JSONRPC_VERSION { + return Ok(()); + } + + match notification.method.as_str() { + "session/cancel" => { + let params = self.parse_params::(notification.params)?; + self.handle_session_cancel(params).await + } + "mcp/message" => { + let params = self.parse_params::(notification.params)?; + self.handle_mcp_message_notification(params) + } + other => { + debug!("ignoring ACP notification {other}"); + Ok(()) + } + } + } + + async fn handle_response(&mut self, response: JsonRpcResponse) -> IoResult<()> { + if self.bridge_state.handle_response(response.clone()) { + return Ok(()); + } + + if let Some(pending_elicitation) = self.pending_elicitations.remove(&response.id) { + let result = serde_json::from_value::(response.result) + .map(|response| { + session_elicitation_to_app_result(response, &pending_elicitation.kind) + }) + .unwrap_or_else(|_| pending_elicitation.fallback_result); + return self + .app_client + .resolve_server_request(pending_elicitation.app_request_id, result) + .await; + } + + let Some(pending_permission) = self.pending_permissions.remove(&response.id) else { + debug!("ignoring unmatched ACP response id {:?}", response.id); + return Ok(()); + }; + + let result = serde_json::from_value::(response.result) + .ok() + .and_then(|permission_response| match permission_response.outcome { + PermissionOutcome::Selected { option_id } => { + pending_permission.option_results.get(&option_id).cloned() + } + PermissionOutcome::Cancelled => None, + }) + .unwrap_or(pending_permission.fallback_result); + + self.app_client + .resolve_server_request(pending_permission.app_request_id, result) + .await + } + + async fn handle_error_message(&mut self, error_message: JsonRpcError) -> IoResult<()> { + if self.bridge_state.handle_error(error_message.clone()) { + return Ok(()); + } + + if let Some(pending_elicitation) = self.pending_elicitations.remove(&error_message.id) { + return self + .app_client + .resolve_server_request( + pending_elicitation.app_request_id, + pending_elicitation.fallback_result, + ) + .await; + } + + if let Some(pending_permission) = self.pending_permissions.remove(&error_message.id) { + return self + .app_client + .resolve_server_request( + pending_permission.app_request_id, + pending_permission.fallback_result, + ) + .await; + } + + error!("received unmatched ACP error response: {error_message:?}"); + Ok(()) + } + + async fn handle_initialize(&mut self, request: JsonRpcRequest) -> IoResult<()> { + let params = self.parse_params::(request.params)?; + if self.initialized { + self.send_error(request.id, -32600, "initialize called more than once")?; + return Ok(()); + } + + self.client_elicitation_capabilities = + params.client_capabilities.and_then(|caps| caps.elicitation); + self.initialized = true; + let result = InitializeResult { + protocol_version: PROTOCOL_VERSION, + agent_capabilities: AgentCapabilities { + load_session: true, + session_capabilities: SessionCapabilities { + list: Default::default(), + fork: Default::default(), + resume: Default::default(), + close: Default::default(), + }, + prompt_capabilities: PromptCapabilities { + image: true, + audio: false, + embedded_context: true, + }, + mcp_capabilities: McpCapabilities { + http: false, + sse: false, + acp: true, + }, + }, + agent_info: AgentInfo { + name: CLIENT_NAME.to_string(), + title: "Codex ACP Server".to_string(), + version: env!("CARGO_PKG_VERSION").to_string(), + }, + auth_methods: Vec::new(), + }; + self.send_result(request.id, serde_json::to_value(result)?)?; + Ok(()) + } + + async fn handle_session_new(&mut self, request: JsonRpcRequest) -> IoResult<()> { + self.require_initialized(&request.id)?; + let params = self.parse_params::(request.params)?; + let request_overrides = build_request_overrides_from_mcp_servers(¶ms.mcp_servers) + .map_err(invalid_params_error)?; + + let request_id = self.next_app_request_id(); + let response: ThreadStartResponse = self + .app_client + .request_typed(ClientRequest::ThreadStart { + request_id, + params: ThreadStartParams { + cwd: Some(params.cwd.clone()), + config: request_overrides, + ..Default::default() + }, + }) + .await + .map_err(io_error_from_typed_request)?; + + let session_id = response.thread.id.clone(); + let session_state = self + .build_session_state( + response.thread.id.clone(), + params.cwd.clone(), + response.thread.name.clone(), + &response.model, + response.reasoning_effort, + ) + .await?; + let modes = session_state.modes_payload(); + let config_options = session_state.config_options.clone(); + let updated_at = rfc3339_timestamp(response.thread.updated_at); + self.sessions.insert(session_id.clone(), session_state); + + self.send_result( + request.id.clone(), + serde_json::to_value(SessionNewResult { + session_id: session_id.clone(), + modes, + config_options, + })?, + )?; + self.maybe_send_session_info_update(&session_id, updated_at)?; + Ok(()) + } + + async fn handle_session_list(&mut self, request: JsonRpcRequest) -> IoResult<()> { + self.require_initialized(&request.id)?; + let params = self.parse_params::(request.params)?; + let filter_cwd = params.cwd.clone(); + let request_id = self.next_app_request_id(); + let response: ThreadListResponse = self + .app_client + .request_typed(ClientRequest::ThreadList { + request_id, + params: ThreadListParams { + cursor: params.cursor, + limit: None, + sort_key: None, + model_providers: None, + source_kinds: None, + archived: None, + cwd: filter_cwd.clone(), + search_term: None, + }, + }) + .await + .map_err(io_error_from_typed_request)?; + let mut sessions = response + .data + .into_iter() + .map(|thread| SessionInfo { + session_id: thread.id, + cwd: thread.cwd.display().to_string(), + title: thread.name, + updated_at: rfc3339_timestamp(thread.updated_at), + meta: None, + }) + .collect::>(); + for session in self.sessions.values() { + if sessions + .iter() + .any(|info| info.session_id == session.thread_id) + { + continue; + } + if let Some(filter_cwd) = filter_cwd.as_deref() + && session.cwd != filter_cwd + { + continue; + } + sessions.push(SessionInfo { + session_id: session.thread_id.clone(), + cwd: session.cwd.clone(), + title: session.last_title.clone(), + updated_at: None, + meta: Some(serde_json::json!({ "loaded": true })), + }); + } + + self.send_result( + request.id, + serde_json::to_value(SessionListResult { + sessions, + next_cursor: response.next_cursor, + })?, + ) + } + + async fn handle_session_load(&mut self, request: JsonRpcRequest) -> IoResult<()> { + self.require_initialized(&request.id)?; + let params = self.parse_params::(request.params)?; + let request_overrides = build_request_overrides_from_mcp_servers(¶ms.mcp_servers) + .map_err(invalid_params_error)?; + + let read_request_id = self.next_app_request_id(); + let read_response: ThreadReadResponse = self + .app_client + .request_typed(ClientRequest::ThreadRead { + request_id: read_request_id, + params: ThreadReadParams { + thread_id: params.session_id.clone(), + include_turns: true, + }, + }) + .await + .map_err(io_error_from_typed_request)?; + + let resume_request_id = self.next_app_request_id(); + let resume_response: ThreadResumeResponse = self + .app_client + .request_typed(ClientRequest::ThreadResume { + request_id: resume_request_id, + params: ThreadResumeParams { + thread_id: params.session_id.clone(), + cwd: Some(params.cwd.clone()), + config: request_overrides, + ..Default::default() + }, + }) + .await + .map_err(io_error_from_typed_request)?; + + let session_state = self + .build_session_state( + resume_response.thread.id.clone(), + params.cwd.clone(), + resume_response.thread.name.clone(), + &resume_response.model, + resume_response.reasoning_effort, + ) + .await?; + let modes = session_state.modes_payload(); + let config_options = session_state.config_options.clone(); + let updated_at = rfc3339_timestamp(resume_response.thread.updated_at); + self.sessions + .insert(params.session_id.clone(), session_state); + + self.replay_thread_history(¶ms.session_id, read_response) + .await?; + self.send_result( + request.id.clone(), + serde_json::to_value(SessionLoadResult { + modes, + config_options, + })?, + )?; + self.maybe_send_session_info_update(¶ms.session_id, updated_at)?; + Ok(()) + } + + async fn handle_session_resume(&mut self, request: JsonRpcRequest) -> IoResult<()> { + self.require_initialized(&request.id)?; + let params = self.parse_params::(request.params)?; + let cwd = params.cwd.clone(); + let request_overrides = build_request_overrides_from_mcp_servers(¶ms.mcp_servers) + .map_err(invalid_params_error)?; + + let request_id = self.next_app_request_id(); + let response: ThreadResumeResponse = self + .app_client + .request_typed(ClientRequest::ThreadResume { + request_id, + params: ThreadResumeParams { + thread_id: params.session_id.clone(), + cwd: Some(cwd.clone()), + config: request_overrides, + ..Default::default() + }, + }) + .await + .map_err(io_error_from_typed_request)?; + + let session_state = self + .build_session_state( + response.thread.id.clone(), + cwd, + response.thread.name.clone(), + &response.model, + response.reasoning_effort, + ) + .await?; + let modes = session_state.modes_payload(); + let config_options = session_state.config_options.clone(); + let updated_at = rfc3339_timestamp(response.thread.updated_at); + self.sessions + .insert(params.session_id.clone(), session_state); + + self.send_result( + request.id.clone(), + serde_json::to_value(SessionResumeResult { + modes, + config_options, + })?, + )?; + self.maybe_send_session_info_update(¶ms.session_id, updated_at)?; + Ok(()) + } + + async fn handle_session_fork(&mut self, request: JsonRpcRequest) -> IoResult<()> { + self.require_initialized(&request.id)?; + let params = self.parse_params::(request.params)?; + let cwd = params.cwd.clone(); + let request_overrides = build_request_overrides_from_mcp_servers(¶ms.mcp_servers) + .map_err(invalid_params_error)?; + + let request_id = self.next_app_request_id(); + let response: ThreadForkResponse = self + .app_client + .request_typed(ClientRequest::ThreadFork { + request_id, + params: ThreadForkParams { + thread_id: params.session_id, + cwd: Some(cwd.clone()), + config: request_overrides, + ..Default::default() + }, + }) + .await + .map_err(io_error_from_typed_request)?; + + let session_id = response.thread.id.clone(); + let session_state = self + .build_session_state( + response.thread.id.clone(), + cwd, + response.thread.name.clone(), + &response.model, + response.reasoning_effort, + ) + .await?; + let modes = session_state.modes_payload(); + let config_options = session_state.config_options.clone(); + let updated_at = rfc3339_timestamp(response.thread.updated_at); + self.sessions.insert(session_id.clone(), session_state); + + self.send_result( + request.id.clone(), + serde_json::to_value(SessionForkResult { + session_id: session_id.clone(), + modes, + config_options, + })?, + )?; + self.maybe_send_session_info_update(&session_id, updated_at)?; + Ok(()) + } + + async fn handle_session_close(&mut self, request: JsonRpcRequest) -> IoResult<()> { + self.require_initialized(&request.id)?; + let params = self.parse_params::(request.params)?; + let request_id = self.next_app_request_id(); + let _: ThreadUnsubscribeResponse = self + .app_client + .request_typed(ClientRequest::ThreadUnsubscribe { + request_id, + params: ThreadUnsubscribeParams { + thread_id: params.session_id.clone(), + }, + }) + .await + .map_err(io_error_from_typed_request)?; + self.sessions.remove(¶ms.session_id); + self.send_result(request.id, serde_json::to_value(SessionCloseResult {})?)?; + Ok(()) + } + + async fn handle_session_prompt(&mut self, request: JsonRpcRequest) -> IoResult<()> { + self.require_initialized(&request.id)?; + let params = self.parse_params::(request.params)?; + let input = prompt_to_user_input(¶ms.prompt).map_err(invalid_params_error)?; + + let Some(session) = self.sessions.get(¶ms.session_id) else { + self.send_error(request.id, -32602, "unknown sessionId")?; + return Ok(()); + }; + if session.active_turn_id.is_some() { + self.send_error(request.id, -32600, "session already has an active turn")?; + return Ok(()); + } + let thread_id = session.thread_id.clone(); + let collaboration_mode = Some(session.current_mode.clone()); + + let request_id = self.next_app_request_id(); + let response: TurnStartResponse = self + .app_client + .request_typed(ClientRequest::TurnStart { + request_id, + params: TurnStartParams { + thread_id, + input, + collaboration_mode, + ..Default::default() + }, + }) + .await + .map_err(io_error_from_typed_request)?; + + let turn_id = response.turn.id; + if let Some(session) = self.sessions.get_mut(¶ms.session_id) { + session.active_turn_id = Some(turn_id.clone()); + } + self.pending_prompts.insert( + turn_id, + PendingPrompt { + request_id: request.id, + session_id: params.session_id, + }, + ); + Ok(()) + } + + async fn handle_session_set_mode(&mut self, request: JsonRpcRequest) -> IoResult<()> { + self.require_initialized(&request.id)?; + let params = self.parse_params::(request.params)?; + + let Some(session) = self.sessions.get_mut(¶ms.session_id) else { + self.send_error(request.id, -32602, "unknown sessionId")?; + return Ok(()); + }; + + let Some(binding) = session + .modes + .iter() + .find(|binding| binding.acp_mode.id == params.mode_id) + .cloned() + else { + self.send_error( + request.id, + -32602, + format!("unknown modeId: {}", params.mode_id), + )?; + return Ok(()); + }; + + session.current_mode_id = binding.acp_mode.id.clone(); + session.current_mode = session.current_mode.apply_mask(&binding.mask); + update_mode_config_options( + &mut session.config_options, + &session.current_mode_id, + session.current_mode.model(), + session.current_mode.reasoning_effort(), + ); + + let config_options = session.config_options.clone(); + let current_mode_id = session.current_mode_id.clone(); + + self.send_result(request.id, serde_json::to_value(SessionSetModeResult {})?)?; + self.send_session_update( + ¶ms.session_id, + SessionUpdate::CurrentModeUpdate { current_mode_id }, + )?; + self.send_session_update( + ¶ms.session_id, + SessionUpdate::ConfigOptionsUpdate { config_options }, + )?; + Ok(()) + } + + async fn handle_session_cancel(&mut self, params: SessionCancelParams) -> IoResult<()> { + let Some(active_turn_id) = self + .sessions + .get(¶ms.session_id) + .and_then(|session| session.active_turn_id.clone()) + else { + return Ok(()); + }; + + let Some(thread_id) = self + .sessions + .get(¶ms.session_id) + .map(|session| session.thread_id.clone()) + else { + return Ok(()); + }; + let request_id = self.next_app_request_id(); + + let _: codex_app_server_protocol::TurnInterruptResponse = self + .app_client + .request_typed(ClientRequest::TurnInterrupt { + request_id, + params: TurnInterruptParams { + thread_id, + turn_id: active_turn_id, + }, + }) + .await + .map_err(io_error_from_typed_request)?; + Ok(()) + } + + async fn handle_mcp_message_request(&mut self, request: JsonRpcRequest) -> IoResult<()> { + self.require_initialized(&request.id)?; + let params = self.parse_params::(request.params)?; + let connection_id = params.connection_id.clone(); + let Some(inbound_tx) = self.bridge_state.connection_sender(&connection_id) else { + self.send_error( + request.id, + -32602, + format!("unknown MCP connectionId: {connection_id}"), + )?; + return Ok(()); + }; + inbound_tx + .send(mcp_request_from_acp(request.id, params)?) + .map_err(|_| Error::new(ErrorKind::BrokenPipe, "ACP MCP inbound channel closed"))?; + Ok(()) + } + + fn handle_mcp_message_notification(&mut self, params: McpMessageParams) -> IoResult<()> { + let connection_id = params.connection_id.clone(); + let Some(inbound_tx) = self.bridge_state.connection_sender(&connection_id) else { + debug!("ignoring MCP notification for unknown connection {connection_id}"); + return Ok(()); + }; + inbound_tx + .send(mcp_notification_from_acp(params)?) + .map_err(|_| Error::new(ErrorKind::BrokenPipe, "ACP MCP inbound channel closed")) + } + + async fn handle_mcp_disconnect(&mut self, request: JsonRpcRequest) -> IoResult<()> { + self.require_initialized(&request.id)?; + let params = self.parse_params::(request.params)?; + if self + .bridge_state + .connection_sender(¶ms.connection_id) + .is_none() + { + self.send_error( + request.id, + -32602, + format!("unknown MCP connectionId: {}", params.connection_id), + )?; + return Ok(()); + } + self.send_result( + request.id, + serde_json::to_value(McpDisconnectResult { meta: None }) + .map_err(invalid_params_error)?, + )?; + self.bridge_state + .unregister_connection(¶ms.connection_id); + Ok(()) + } + + async fn handle_app_event(&mut self, event: InProcessServerEvent) -> IoResult<()> { + match event { + InProcessServerEvent::ServerNotification(notification) => { + self.handle_server_notification(notification).await + } + InProcessServerEvent::ServerRequest(request) => { + self.handle_server_request(request).await + } + InProcessServerEvent::LegacyNotification(_) | InProcessServerEvent::Lagged { .. } => { + Ok(()) + } + } + } + + async fn handle_server_notification( + &mut self, + notification: ServerNotification, + ) -> IoResult<()> { + match notification { + ServerNotification::AgentMessageDelta(update) => self.send_session_update( + &update.thread_id, + SessionUpdate::AgentMessageChunk { + content: text_content(update.delta), + }, + ), + ServerNotification::TurnPlanUpdated(update) => self.send_turn_plan_update(update), + ServerNotification::ItemStarted(notification) => self.send_item_started(notification), + ServerNotification::ItemCompleted(notification) => { + self.send_item_completed(notification) + } + ServerNotification::TurnCompleted(notification) => { + self.handle_turn_completed(notification).await + } + _ => Ok(()), + } + } + + async fn handle_server_request(&mut self, request: ServerRequest) -> IoResult<()> { + match request { + ServerRequest::CommandExecutionRequestApproval { request_id, params } => { + self.forward_command_approval(request_id, params).await + } + ServerRequest::FileChangeRequestApproval { request_id, params } => { + self.forward_file_change_approval(request_id, params).await + } + ServerRequest::ToolRequestUserInput { request_id, params } => { + self.forward_tool_user_input(request_id, params).await + } + ServerRequest::McpServerElicitationRequest { request_id, params } => { + self.forward_mcp_elicitation(request_id, params).await + } + other => { + self.app_client + .reject_server_request( + other.id().clone(), + JSONRPCErrorError { + code: -32601, + data: None, + message: "ACP adapter does not support this interactive request yet" + .to_string(), + }, + ) + .await + } + } + } + + async fn forward_command_approval( + &mut self, + app_request_id: RequestId, + params: CommandExecutionRequestApprovalParams, + ) -> IoResult<()> { + let (options, option_results, fallback_result) = + build_command_permission_options(¶ms.available_decisions); + let acp_request_id = self.next_acp_request_id(); + let title = params + .command + .clone() + .unwrap_or_else(|| "Approve command execution".to_string()); + self.pending_permissions.insert( + acp_request_id.clone(), + PendingPermissionRequest { + app_request_id, + option_results, + fallback_result, + }, + ); + self.send_request( + acp_request_id, + "session/request_permission", + serde_json::to_value(SessionRequestPermissionParams { + session_id: params.thread_id, + tool_call: PermissionToolCall { + tool_call_id: params.item_id, + title, + kind: "exec".to_string(), + status: "pending".to_string(), + }, + options, + })?, + ) + } + + async fn forward_file_change_approval( + &mut self, + app_request_id: RequestId, + params: FileChangeRequestApprovalParams, + ) -> IoResult<()> { + let (options, option_results, fallback_result) = build_file_permission_options(); + let acp_request_id = self.next_acp_request_id(); + self.pending_permissions.insert( + acp_request_id.clone(), + PendingPermissionRequest { + app_request_id, + option_results, + fallback_result, + }, + ); + self.send_request( + acp_request_id, + "session/request_permission", + serde_json::to_value(SessionRequestPermissionParams { + session_id: params.thread_id, + tool_call: PermissionToolCall { + tool_call_id: params.item_id, + title: "Approve file changes".to_string(), + kind: "edit".to_string(), + status: "pending".to_string(), + }, + options, + })?, + ) + } + + async fn forward_tool_user_input( + &mut self, + app_request_id: RequestId, + params: ToolRequestUserInputParams, + ) -> IoResult<()> { + if !self.client_supports_form_elicitation() { + return self + .app_client + .reject_server_request( + app_request_id, + JSONRPCErrorError { + code: -32601, + data: None, + message: "ACP client does not advertise form elicitation support" + .to_string(), + }, + ) + .await; + } + + let requested_schema = + tool_user_input_schema(¶ms.questions).map_err(invalid_params_error)?; + let acp_request_id = self.next_acp_request_id(); + self.pending_elicitations.insert( + acp_request_id.clone(), + PendingElicitationRequest { + app_request_id, + fallback_result: serde_json::to_value(ToolRequestUserInputResponse { + answers: HashMap::new(), + })?, + kind: PendingElicitationKind::ToolUserInput { + questions: params.questions.clone(), + }, + }, + ); + self.send_request( + acp_request_id, + "session/elicitation", + serde_json::to_value(SessionElicitationParams { + session_id: params.thread_id, + elicitation: SessionElicitationRequest::Form { + message: tool_user_input_message(¶ms.questions), + requested_schema, + meta: Some(tool_user_input_meta( + ¶ms.turn_id, + ¶ms.item_id, + ¶ms.questions, + )), + }, + })?, + ) + } + + async fn forward_mcp_elicitation( + &mut self, + app_request_id: RequestId, + params: McpServerElicitationRequestParams, + ) -> IoResult<()> { + let supports_mode = match ¶ms.request { + AppMcpServerElicitationRequest::Form { .. } => self.client_supports_form_elicitation(), + AppMcpServerElicitationRequest::Url { .. } => self.client_supports_url_elicitation(), + }; + if !supports_mode { + let mode = match ¶ms.request { + AppMcpServerElicitationRequest::Form { .. } => "form", + AppMcpServerElicitationRequest::Url { .. } => "url", + }; + return self + .app_client + .reject_server_request( + app_request_id, + JSONRPCErrorError { + code: -32601, + data: None, + message: format!( + "ACP client does not advertise {mode} elicitation support" + ), + }, + ) + .await; + } + + let acp_request_id = self.next_acp_request_id(); + self.pending_elicitations.insert( + acp_request_id.clone(), + PendingElicitationRequest { + app_request_id, + fallback_result: serde_json::to_value(McpServerElicitationRequestResponse { + action: codex_app_server_protocol::McpServerElicitationAction::Decline, + content: None, + meta: None, + })?, + kind: PendingElicitationKind::McpServer, + }, + ); + self.send_request( + acp_request_id, + "session/elicitation", + serde_json::to_value(SessionElicitationParams { + session_id: params.thread_id.clone(), + elicitation: app_elicitation_to_acp_request(params), + })?, + ) + } + + async fn build_session_state( + &mut self, + thread_id: String, + cwd: String, + last_title: Option, + current_model: &str, + current_reasoning_effort: Option, + ) -> IoResult { + let mode_bindings = self.list_mode_bindings().await?; + let current_mode = + default_collaboration_mode(&mode_bindings, current_model, current_reasoning_effort); + let current_mode_id = mode_bindings + .first() + .map(|binding| binding.acp_mode.id.clone()) + .unwrap_or_else(|| "default".to_string()); + let models = self.list_models().await?; + let config_options = build_config_options( + &mode_bindings, + current_model, + current_reasoning_effort, + ¤t_mode_id, + &models, + ); + + Ok(SessionState { + active_turn_id: None, + config_options, + current_mode, + current_mode_id, + cwd, + last_title, + modes: mode_bindings, + thread_id, + }) + } + + async fn list_mode_bindings(&mut self) -> IoResult> { + let request_id = self.next_app_request_id(); + let response: CollaborationModeListResponse = self + .app_client + .request_typed(ClientRequest::CollaborationModeList { + request_id, + params: CollaborationModeListParams::default(), + }) + .await + .map_err(io_error_from_typed_request)?; + + let mode_bindings = response + .data + .into_iter() + .map(|mask| ModeBinding { + acp_mode: Mode { + id: mode_id(&mask.name), + name: mask.name.clone(), + description: None, + }, + mask: core_mode_mask(&mask), + }) + .collect::>(); + + Ok(if mode_bindings.is_empty() { + vec![fallback_mode_binding()] + } else { + mode_bindings + }) + } + + async fn list_models(&mut self) -> IoResult> { + let request_id = self.next_app_request_id(); + let response: ModelListResponse = self + .app_client + .request_typed(ClientRequest::ModelList { + request_id, + params: ModelListParams::default(), + }) + .await + .map_err(io_error_from_typed_request)?; + Ok(response.data) + } + + async fn replay_thread_history( + &mut self, + session_id: &str, + response: ThreadReadResponse, + ) -> IoResult<()> { + for turn in response.thread.turns { + for item in turn.items { + match item { + ThreadItem::UserMessage { content, .. } => { + for text in flatten_user_message_text(&content) { + self.send_session_update( + session_id, + SessionUpdate::UserMessageChunk { + content: text_content(text), + }, + )?; + } + } + ThreadItem::AgentMessage { text, .. } => { + self.send_session_update( + session_id, + SessionUpdate::AgentMessageChunk { + content: text_content(text), + }, + )?; + } + ThreadItem::Plan { text, .. } => { + self.send_session_update( + session_id, + SessionUpdate::Plan { + entries: vec![PlanEntry { + content: text, + priority: "medium".to_string(), + status: "completed".to_string(), + }], + }, + )?; + } + ThreadItem::CommandExecution { + id, + command, + cwd, + status, + aggregated_output, + .. + } => { + self.send_session_update( + session_id, + SessionUpdate::ToolCall { + tool_call_id: id.clone(), + title: command.clone(), + kind: "exec".to_string(), + status: "completed".to_string(), + locations: Some(vec![Location { + path: cwd.display().to_string(), + }]), + }, + )?; + self.send_session_update( + session_id, + SessionUpdate::ToolCallUpdate { + tool_call_id: id, + status: map_command_status(status), + content: tool_call_text_output( + aggregated_output + .or(Some(format!("{command}\n({})", cwd.display()))), + ), + }, + )?; + } + ThreadItem::FileChange { + id, + changes, + status, + } => { + let locations = changes + .iter() + .map(|change| Location { + path: change.path.clone(), + }) + .collect::>(); + self.send_session_update( + session_id, + SessionUpdate::ToolCall { + tool_call_id: id.clone(), + title: "Applying file changes".to_string(), + kind: "edit".to_string(), + status: "completed".to_string(), + locations: Some(locations), + }, + )?; + self.send_session_update( + session_id, + SessionUpdate::ToolCallUpdate { + tool_call_id: id, + status: map_patch_status(status), + content: tool_call_text_output(Some( + changes + .into_iter() + .map(|change| change.diff) + .collect::>() + .join("\n"), + )), + }, + )?; + } + _ => {} + } + } + } + Ok(()) + } + + async fn handle_turn_completed( + &mut self, + notification: TurnCompletedNotification, + ) -> IoResult<()> { + let turn_id = notification.turn.id.clone(); + if let Some(pending_prompt) = self.pending_prompts.remove(&turn_id) { + if let Some(session) = self.sessions.get_mut(&pending_prompt.session_id) + && session.active_turn_id.as_deref() == Some(turn_id.as_str()) + { + session.active_turn_id = None; + } + + match notification.turn.status { + TurnStatus::Completed => { + let _ = self.send_result( + pending_prompt.request_id, + serde_json::to_value(SessionPromptResult { + stop_reason: "end_turn".to_string(), + }) + .unwrap_or(JsonValue::Null), + ); + } + TurnStatus::Interrupted => { + let _ = self.send_result( + pending_prompt.request_id, + serde_json::to_value(SessionPromptResult { + stop_reason: "cancelled".to_string(), + }) + .unwrap_or(JsonValue::Null), + ); + } + TurnStatus::Failed => { + let message = notification + .turn + .error + .map(|error| error.message) + .unwrap_or_else(|| "turn failed".to_string()); + let _ = self.send_error(pending_prompt.request_id, -32000, message); + } + TurnStatus::InProgress => {} + } + } + + let request_id = self.next_app_request_id(); + let response: ThreadReadResponse = self + .app_client + .request_typed(ClientRequest::ThreadRead { + request_id, + params: ThreadReadParams { + thread_id: notification.thread_id.clone(), + include_turns: false, + }, + }) + .await + .map_err(io_error_from_typed_request)?; + self.maybe_update_session_info( + ¬ification.thread_id, + response.thread.name, + rfc3339_timestamp(response.thread.updated_at), + )?; + Ok(()) + } + + fn send_turn_plan_update(&mut self, update: TurnPlanUpdatedNotification) -> IoResult<()> { + self.send_session_update( + &update.thread_id, + SessionUpdate::Plan { + entries: update + .plan + .into_iter() + .map(|step| PlanEntry { + content: step.step, + priority: "medium".to_string(), + status: match step.status { + TurnPlanStepStatus::Pending => "pending".to_string(), + TurnPlanStepStatus::InProgress => "in_progress".to_string(), + TurnPlanStepStatus::Completed => "completed".to_string(), + }, + }) + .collect(), + }, + ) + } + + fn send_item_started(&mut self, notification: ItemStartedNotification) -> IoResult<()> { + match notification.item { + ThreadItem::CommandExecution { + id, command, cwd, .. + } => self.send_session_update( + ¬ification.thread_id, + SessionUpdate::ToolCall { + tool_call_id: id, + title: command, + kind: "exec".to_string(), + status: "in_progress".to_string(), + locations: Some(vec![Location { + path: cwd.display().to_string(), + }]), + }, + ), + ThreadItem::FileChange { id, changes, .. } => self.send_session_update( + ¬ification.thread_id, + SessionUpdate::ToolCall { + tool_call_id: id, + title: "Applying file changes".to_string(), + kind: "edit".to_string(), + status: "in_progress".to_string(), + locations: Some( + changes + .into_iter() + .map(|change| Location { path: change.path }) + .collect(), + ), + }, + ), + _ => Ok(()), + } + } + + fn send_item_completed(&mut self, notification: ItemCompletedNotification) -> IoResult<()> { + match notification.item { + ThreadItem::CommandExecution { + id, + status, + aggregated_output, + .. + } => self.send_session_update( + ¬ification.thread_id, + SessionUpdate::ToolCallUpdate { + tool_call_id: id, + status: map_command_status(status), + content: tool_call_text_output(aggregated_output), + }, + ), + ThreadItem::FileChange { + id, + status, + changes, + } => self.send_session_update( + ¬ification.thread_id, + SessionUpdate::ToolCallUpdate { + tool_call_id: id, + status: map_patch_status(status), + content: tool_call_text_output(Some( + changes + .into_iter() + .map(|change| change.diff) + .collect::>() + .join("\n"), + )), + }, + ), + _ => Ok(()), + } + } + + fn client_supports_form_elicitation(&self) -> bool { + self.client_elicitation_capabilities + .as_ref() + .is_some_and(|caps| caps.form.is_some() || caps.url.is_none()) + } + + fn client_supports_url_elicitation(&self) -> bool { + self.client_elicitation_capabilities + .as_ref() + .is_some_and(|caps| caps.url.is_some()) + } + + fn maybe_send_session_info_update( + &mut self, + session_id: &str, + updated_at: Option, + ) -> IoResult<()> { + let Some(session) = self.sessions.get(session_id) else { + return Ok(()); + }; + if session.last_title.is_none() && updated_at.is_none() { + return Ok(()); + } + self.send_session_update( + session_id, + SessionUpdate::SessionInfoUpdate { + title: session.last_title.clone(), + updated_at, + meta: None, + }, + ) + } + + fn maybe_update_session_info( + &mut self, + session_id: &str, + title: Option, + updated_at: Option, + ) -> IoResult<()> { + let Some(session) = self.sessions.get_mut(session_id) else { + return Ok(()); + }; + if session.last_title == title { + if updated_at.is_none() { + return Ok(()); + } + } else { + session.last_title = title.clone(); + } + + self.send_session_update( + session_id, + SessionUpdate::SessionInfoUpdate { + title, + updated_at, + meta: None, + }, + ) + } + + fn parse_params(&self, params: Option) -> IoResult + where + T: DeserializeOwned, + { + serde_json::from_value(params.unwrap_or(JsonValue::Null)).map_err(invalid_params_error) + } + + fn require_initialized(&self, request_id: &RequestId) -> IoResult<()> { + if self.initialized { + return Ok(()); + } + + self.send_error(request_id.clone(), -32002, "server not initialized") + } + + fn next_acp_request_id(&mut self) -> RequestId { + let request_id = self.next_acp_request_id; + self.next_acp_request_id += 1; + RequestId::Integer(request_id) + } + + fn next_app_request_id(&mut self) -> RequestId { + let request_id = self.next_app_request_id; + self.next_app_request_id += 1; + RequestId::Integer(request_id) + } + + fn send_session_update(&mut self, session_id: &str, update: SessionUpdate) -> IoResult<()> { + self.send_notification( + "session/update", + serde_json::to_value(SessionUpdateParams { + session_id: session_id.to_string(), + update, + })?, + ) + } + + fn send_notification(&self, method: &str, params: JsonValue) -> IoResult<()> { + self.outgoing_tx + .send(JsonRpcMessage::Notification(JsonRpcNotification { + jsonrpc: JSONRPC_VERSION.to_string(), + method: method.to_string(), + params: Some(params), + })) + .map_err(|_| Error::new(ErrorKind::BrokenPipe, "ACP stdout writer channel closed")) + } + + fn send_request(&self, id: RequestId, method: &str, params: JsonValue) -> IoResult<()> { + self.outgoing_tx + .send(JsonRpcMessage::Request(JsonRpcRequest { + jsonrpc: JSONRPC_VERSION.to_string(), + id, + method: method.to_string(), + params: Some(params), + })) + .map_err(|_| Error::new(ErrorKind::BrokenPipe, "ACP stdout writer channel closed")) + } + + fn send_result(&self, id: RequestId, result: JsonValue) -> IoResult<()> { + self.outgoing_tx + .send(JsonRpcMessage::Response(JsonRpcResponse { + jsonrpc: JSONRPC_VERSION.to_string(), + id, + result, + })) + .map_err(|_| Error::new(ErrorKind::BrokenPipe, "ACP stdout writer channel closed")) + } + + fn send_error(&self, id: RequestId, code: i64, message: impl Into) -> IoResult<()> { + self.outgoing_tx + .send(JsonRpcMessage::Error(JsonRpcError { + jsonrpc: JSONRPC_VERSION.to_string(), + id, + error: JsonRpcErrorBody { + code, + message: message.into(), + data: None, + }, + })) + .map_err(|_| Error::new(ErrorKind::BrokenPipe, "ACP stdout writer channel closed")) + } +} + +pub async fn run_main( + arg0_paths: Arg0DispatchPaths, + cli_config_overrides: CliConfigOverrides, +) -> IoResult<()> { + let fmt_layer = tracing_subscriber::fmt::layer() + .with_writer(std::io::stderr) + .with_filter(EnvFilter::from_default_env()); + let _ = tracing_subscriber::registry().with(fmt_layer).try_init(); + + let cli_kv_overrides = cli_config_overrides.parse_overrides().map_err(|error| { + Error::new( + ErrorKind::InvalidInput, + format!("error parsing -c overrides: {error}"), + ) + })?; + let config = Config::load_with_cli_overrides(cli_kv_overrides.clone()).await?; + let auth_manager = AuthManager::shared( + config.codex_home.clone(), + false, + config.cli_auth_credentials_store_mode, + ); + let cloud_requirements = cloud_requirements_loader( + auth_manager, + config.chatgpt_base_url.clone(), + config.codex_home.clone(), + ); + let config_warnings = config + .startup_warnings + .iter() + .map( + |warning| codex_app_server_protocol::ConfigWarningNotification { + summary: warning.clone(), + details: None, + path: None, + range: None, + }, + ) + .collect(); + let (incoming_tx, incoming_rx) = mpsc::channel(CHANNEL_CAPACITY); + let (outgoing_tx, mut outgoing_rx) = mpsc::unbounded_channel::(); + let bridge_state = Arc::new(AcpBridgeState::new(outgoing_tx.clone())); + let app_client = InProcessAppServerClient::start(InProcessClientStartArgs { + arg0_paths, + config: Arc::new(config), + cli_overrides: cli_kv_overrides, + loader_overrides: LoaderOverrides::default(), + cloud_requirements, + feedback: CodexFeedback::new(), + config_warnings, + session_source: SessionSource::Acp, + enable_codex_api_key_env: true, + client_name: CLIENT_NAME.to_string(), + client_version: env!("CARGO_PKG_VERSION").to_string(), + experimental_api: true, + opt_out_notification_methods: Vec::new(), + channel_capacity: DEFAULT_IN_PROCESS_CHANNEL_CAPACITY, + }) + .await?; + set_acp_bridge(Some(Arc::new(AcpBridgeHandle { + bridge_state: Arc::clone(&bridge_state), + }))); + + let stdin_reader_handle = tokio::spawn(async move { + let stdin = io::stdin(); + let reader = BufReader::new(stdin); + let mut lines = reader.lines(); + + while let Some(line) = lines.next_line().await.unwrap_or_default() { + match serde_json::from_str::(&line) { + Ok(message) => { + if incoming_tx.send(message).await.is_err() { + break; + } + } + Err(error) => error!("failed to deserialize ACP JSON-RPC message: {error}"), + } + } + + debug!("ACP stdin reader finished (EOF)"); + }); + + let stdout_writer_handle = tokio::spawn(async move { + let mut stdout = io::stdout(); + while let Some(message) = outgoing_rx.recv().await { + match serde_json::to_string(&message) { + Ok(json) => { + if stdout.write_all(json.as_bytes()).await.is_err() { + break; + } + if stdout.write_all(b"\n").await.is_err() { + break; + } + } + Err(error) => error!("failed to serialize ACP JSON-RPC message: {error}"), + } + } + info!("ACP stdout writer finished"); + }); + + let server_result = AcpServer { + app_client, + bridge_state, + client_elicitation_capabilities: None, + incoming_rx, + initialized: false, + next_acp_request_id: 1, + next_app_request_id: 1, + outgoing_tx, + pending_elicitations: HashMap::new(), + pending_permissions: HashMap::new(), + pending_prompts: HashMap::new(), + sessions: HashMap::new(), + } + .run() + .await; + set_acp_bridge(None); + + let _ = tokio::join!(stdin_reader_handle, stdout_writer_handle); + server_result +} + +fn prompt_to_user_input(prompt: &[PromptContent]) -> Result, Error> { + let mut input = Vec::new(); + for content in prompt { + match content { + PromptContent::Text { text } => input.push(UserInput::Text { + text: text.clone(), + text_elements: Vec::new(), + }), + PromptContent::Resource { resource } => input.push(resource_to_user_input(resource)?), + } + } + if input.is_empty() { + return Err(invalid_params_error( + "prompt must contain at least one text item", + )); + } + Ok(input) +} + +fn session_elicitation_to_app_result( + response: SessionElicitationResponse, + kind: &PendingElicitationKind, +) -> JsonValue { + match kind { + PendingElicitationKind::ToolUserInput { questions } => serde_json::to_value( + tool_user_input_response_from_elicitation(response, questions), + ) + .unwrap_or(JsonValue::Null), + PendingElicitationKind::McpServer => { + serde_json::to_value(McpServerElicitationRequestResponse { + action: match response.action { + ElicitationAction::Accept => { + codex_app_server_protocol::McpServerElicitationAction::Accept + } + ElicitationAction::Decline => { + codex_app_server_protocol::McpServerElicitationAction::Decline + } + ElicitationAction::Cancel => { + codex_app_server_protocol::McpServerElicitationAction::Cancel + } + }, + content: response.content, + meta: response.meta, + }) + .unwrap_or(JsonValue::Null) + } + } +} + +fn tool_user_input_response_from_elicitation( + response: SessionElicitationResponse, + questions: &[ToolRequestUserInputQuestion], +) -> ToolRequestUserInputResponse { + if !matches!(response.action, ElicitationAction::Accept) { + return ToolRequestUserInputResponse { + answers: HashMap::new(), + }; + } + + let Some(JsonValue::Object(content)) = response.content else { + return ToolRequestUserInputResponse { + answers: HashMap::new(), + }; + }; + + ToolRequestUserInputResponse { + answers: questions + .iter() + .filter_map(|question| { + let value = content.get(&question.id)?; + let answers = match value { + JsonValue::String(value) => vec![value.clone()], + JsonValue::Array(values) => values + .iter() + .filter_map(|value| value.as_str().map(ToOwned::to_owned)) + .collect(), + _ => Vec::new(), + }; + Some((question.id.clone(), ToolRequestUserInputAnswer { answers })) + }) + .collect(), + } +} + +fn app_elicitation_to_acp_request( + params: McpServerElicitationRequestParams, +) -> SessionElicitationRequest { + match params.request { + AppMcpServerElicitationRequest::Form { + meta, + message, + requested_schema, + } => SessionElicitationRequest::Form { + message, + requested_schema: serde_json::to_value(requested_schema).unwrap_or(JsonValue::Null), + meta: merge_json_objects( + meta, + serde_json::json!({ + "serverName": params.server_name, + "turnId": params.turn_id, + }), + ), + }, + AppMcpServerElicitationRequest::Url { + meta, + message, + url, + elicitation_id, + } => SessionElicitationRequest::Url { + message, + url, + elicitation_id, + meta: merge_json_objects( + meta, + serde_json::json!({ + "serverName": params.server_name, + "turnId": params.turn_id, + }), + ), + }, + } +} + +fn tool_user_input_schema( + questions: &[ToolRequestUserInputQuestion], +) -> Result { + let properties = questions + .iter() + .map(|question| { + let schema = match &question.options { + Some(options) if !options.is_empty() && !question.is_other => { + serde_json::json!({ + "type": "string", + "title": question.header, + "description": question.question, + "enum": options.iter().map(|option| option.label.clone()).collect::>(), + }) + } + _ => serde_json::json!({ + "type": "string", + "title": question.header, + "description": question.question, + }), + }; + Ok((question.id.clone(), schema)) + }) + .collect::, serde_json::Error>>()?; + Ok(JsonValue::Object(serde_json::Map::from_iter([ + ("type".to_string(), JsonValue::String("object".to_string())), + ("properties".to_string(), JsonValue::Object(properties)), + ( + "required".to_string(), + JsonValue::Array( + questions + .iter() + .map(|question| JsonValue::String(question.id.clone())) + .collect(), + ), + ), + ]))) +} + +fn tool_user_input_message(questions: &[ToolRequestUserInputQuestion]) -> String { + questions + .iter() + .map(|question| format!("{}: {}", question.header, question.question)) + .collect::>() + .join("\n") +} + +fn tool_user_input_meta( + turn_id: &str, + item_id: &str, + questions: &[ToolRequestUserInputQuestion], +) -> JsonValue { + serde_json::json!({ + "turnId": turn_id, + "itemId": item_id, + "questions": questions.iter().map(|question| { + serde_json::json!({ + "id": question.id, + "header": question.header, + "question": question.question, + "isOther": question.is_other, + "isSecret": question.is_secret, + "options": question.options.as_ref().map(|options| { + options.iter().map(|option| { + serde_json::json!({ + "label": option.label, + "description": option.description, + }) + }).collect::>() + }), + }) + }).collect::>(), + }) +} + +fn merge_json_objects(left: Option, right: JsonValue) -> Option { + match (left, right) { + (Some(JsonValue::Object(mut left)), JsonValue::Object(right)) => { + left.extend(right); + Some(JsonValue::Object(left)) + } + (Some(value), _) => Some(value), + (None, value) => Some(value), + } +} + +fn rfc3339_timestamp(seconds: i64) -> Option { + chrono::DateTime::::from_timestamp(seconds, 0) + .map(|timestamp| timestamp.to_rfc3339_opts(SecondsFormat::Secs, true)) +} + +fn resource_to_user_input(resource: &crate::protocol::ResourceContent) -> Result { + if let Some(text) = resource.text.as_ref() { + return Ok(UserInput::Text { + text: format_resource_text(resource, text), + text_elements: Vec::new(), + }); + } + + if resource + .mime_type + .as_deref() + .is_some_and(|mime_type| mime_type.starts_with("image/")) + { + if let Some(path) = file_uri_to_path(&resource.uri) { + return Ok(UserInput::LocalImage { path }); + } + if resource.uri.starts_with("http://") || resource.uri.starts_with("https://") { + return Ok(UserInput::Image { + url: resource.uri.clone(), + }); + } + } + + Err(invalid_params_error(format!( + "unsupported resource prompt item: {}", + resource.uri + ))) +} + +fn format_resource_text(resource: &crate::protocol::ResourceContent, text: &str) -> String { + let mime_type = resource.mime_type.as_deref().unwrap_or("text/plain"); + format!( + "\n{text}\n", + resource.uri + ) +} + +fn file_uri_to_path(uri: &str) -> Option { + uri.strip_prefix("file://").map(PathBuf::from) +} + +fn build_command_permission_options( + available_decisions: &Option>, +) -> (Vec, HashMap, JsonValue) { + let mut options = Vec::new(); + let mut option_results = HashMap::new(); + let mut decisions = available_decisions.clone().unwrap_or_else(|| { + vec![ + CommandExecutionApprovalDecision::Accept, + CommandExecutionApprovalDecision::Decline, + CommandExecutionApprovalDecision::Cancel, + ] + }); + if decisions.is_empty() { + decisions = vec![ + CommandExecutionApprovalDecision::Accept, + CommandExecutionApprovalDecision::Decline, + CommandExecutionApprovalDecision::Cancel, + ]; + } + + for decision in decisions { + let (option_id, name, kind, response) = match decision { + CommandExecutionApprovalDecision::Accept => ( + "accept", + "Accept", + "allow_once", + CommandExecutionRequestApprovalResponse { + decision: CommandExecutionApprovalDecision::Accept, + }, + ), + CommandExecutionApprovalDecision::AcceptForSession => ( + "accept-session", + "Accept for session", + "allow_always", + CommandExecutionRequestApprovalResponse { + decision: CommandExecutionApprovalDecision::AcceptForSession, + }, + ), + CommandExecutionApprovalDecision::Decline => ( + "decline", + "Decline", + "reject_once", + CommandExecutionRequestApprovalResponse { + decision: CommandExecutionApprovalDecision::Decline, + }, + ), + CommandExecutionApprovalDecision::Cancel => ( + "cancel", + "Cancel turn", + "reject_once", + CommandExecutionRequestApprovalResponse { + decision: CommandExecutionApprovalDecision::Cancel, + }, + ), + CommandExecutionApprovalDecision::AcceptWithExecpolicyAmendment { .. } + | CommandExecutionApprovalDecision::ApplyNetworkPolicyAmendment { .. } => { + continue; + } + }; + options.push(PermissionOption { + option_id: option_id.to_string(), + name: name.to_string(), + kind: kind.to_string(), + }); + option_results.insert( + option_id.to_string(), + serde_json::to_value(response).unwrap_or(JsonValue::Null), + ); + } + + let fallback_result = serde_json::to_value(CommandExecutionRequestApprovalResponse { + decision: CommandExecutionApprovalDecision::Cancel, + }) + .unwrap_or(JsonValue::Null); + + (options, option_results, fallback_result) +} + +fn build_file_permission_options() -> (Vec, HashMap, JsonValue) +{ + let mut options = Vec::new(); + let mut option_results = HashMap::new(); + for (option_id, name, kind, decision) in [ + ( + "accept", + "Accept", + "allow_once", + FileChangeApprovalDecision::Accept, + ), + ( + "accept-session", + "Accept for session", + "allow_always", + FileChangeApprovalDecision::AcceptForSession, + ), + ( + "decline", + "Decline", + "reject_once", + FileChangeApprovalDecision::Decline, + ), + ( + "cancel", + "Cancel turn", + "reject_once", + FileChangeApprovalDecision::Cancel, + ), + ] { + options.push(PermissionOption { + option_id: option_id.to_string(), + name: name.to_string(), + kind: kind.to_string(), + }); + option_results.insert( + option_id.to_string(), + serde_json::to_value(FileChangeRequestApprovalResponse { decision }) + .unwrap_or(JsonValue::Null), + ); + } + + let fallback_result = serde_json::to_value(FileChangeRequestApprovalResponse { + decision: FileChangeApprovalDecision::Cancel, + }) + .unwrap_or(JsonValue::Null); + + (options, option_results, fallback_result) +} + +fn build_request_overrides_from_mcp_servers( + mcp_servers: &[JsonValue], +) -> Result>, Error> { + if mcp_servers.is_empty() { + return Ok(None); + } + + let mut server_map = serde_json::Map::new(); + for server in mcp_servers { + let (name, config) = acp_mcp_server_to_config(server)?; + server_map.insert( + name, + serde_json::to_value(config).map_err(invalid_params_error)?, + ); + } + + Ok(Some(HashMap::from([( + "mcp_servers".to_string(), + JsonValue::Object(server_map), + )]))) +} + +fn acp_mcp_server_to_config(server: &JsonValue) -> Result<(String, McpServerConfig), Error> { + let object = server + .as_object() + .ok_or_else(|| invalid_params_error("mcpServers entries must be objects"))?; + let name = object + .get("name") + .and_then(JsonValue::as_str) + .filter(|name| !name.is_empty()) + .ok_or_else(|| invalid_params_error("mcpServers entries must include a non-empty name"))? + .to_string(); + + let transport = object + .get("transport") + .or_else(|| object.get("type")) + .and_then(JsonValue::as_str); + + let transport = match transport { + Some("acp") => build_acp_transport(object)?, + Some("http") | Some("streamable_http") => build_http_transport(object)?, + Some("stdio") => build_stdio_transport(object)?, + Some(other) => { + return Err(invalid_params_error(format!( + "mcpServers entry '{name}' has unsupported transport '{other}'" + ))); + } + None if object.contains_key("url") => build_http_transport(object)?, + None if object.contains_key("command") => build_stdio_transport(object)?, + None => { + return Err(invalid_params_error(format!( + "mcpServers entry '{name}' must include either transport, url, or command" + ))); + } + }; + + Ok(( + name, + McpServerConfig { + transport, + enabled: true, + required: false, + disabled_reason: None, + startup_timeout_sec: None, + tool_timeout_sec: None, + enabled_tools: None, + disabled_tools: None, + scopes: None, + oauth_resource: None, + }, + )) +} + +fn build_stdio_transport( + object: &serde_json::Map, +) -> Result { + let command = object + .get("command") + .and_then(JsonValue::as_str) + .filter(|command| !command.is_empty()) + .ok_or_else(|| invalid_params_error("stdio MCP server must include a non-empty command"))? + .to_string(); + let args = object + .get("args") + .and_then(JsonValue::as_array) + .map(|args| { + args.iter() + .map(|value| { + value.as_str().map(str::to_string).ok_or_else(|| { + invalid_params_error("stdio MCP server args must be strings") + }) + }) + .collect::, Error>>() + }) + .transpose()? + .unwrap_or_default(); + let env = parse_name_value_map(object.get("env"), "stdio MCP server env")?; + + Ok(McpServerTransportConfig::Stdio { + command, + args, + env, + env_vars: Vec::new(), + cwd: None, + }) +} + +fn build_http_transport( + object: &serde_json::Map, +) -> Result { + let url = object + .get("url") + .and_then(JsonValue::as_str) + .filter(|url| !url.is_empty()) + .ok_or_else(|| invalid_params_error("HTTP MCP server must include a non-empty url"))? + .to_string(); + let http_headers = parse_name_value_map(object.get("headers"), "HTTP MCP server headers")?; + + Ok(McpServerTransportConfig::StreamableHttp { + url, + bearer_token_env_var: None, + http_headers, + env_http_headers: None, + }) +} + +fn build_acp_transport( + object: &serde_json::Map, +) -> Result { + let id = object + .get("id") + .and_then(JsonValue::as_str) + .filter(|id| !id.is_empty()) + .ok_or_else(|| invalid_params_error("ACP MCP server must include a non-empty id"))? + .to_string(); + + Ok(McpServerTransportConfig::Acp { + transport: "acp".to_string(), + id, + }) +} + +fn parse_name_value_map( + value: Option<&JsonValue>, + label: &str, +) -> Result>, Error> { + let Some(value) = value else { + return Ok(None); + }; + + if let Some(object) = value.as_object() { + let map = object + .iter() + .map(|(key, value)| { + value + .as_str() + .map(|value| (key.clone(), value.to_string())) + .ok_or_else(|| invalid_params_error(format!("{label} values must be strings"))) + }) + .collect::, Error>>()?; + return Ok(Some(map)); + } + + if let Some(items) = value.as_array() { + let map = items + .iter() + .map(|item| { + let item = item.as_object().ok_or_else(|| { + invalid_params_error(format!("{label} entries must be objects")) + })?; + let name = item + .get("name") + .and_then(JsonValue::as_str) + .filter(|name| !name.is_empty()) + .ok_or_else(|| { + invalid_params_error(format!( + "{label} entries must include a non-empty name" + )) + })?; + let value = item + .get("value") + .and_then(JsonValue::as_str) + .ok_or_else(|| { + invalid_params_error(format!("{label} entries must include a string value")) + })?; + Ok((name.to_string(), value.to_string())) + }) + .collect::, Error>>()?; + return Ok(Some(map)); + } + + Err(invalid_params_error(format!( + "{label} must be an object or an array of name/value pairs" + ))) +} + +fn fallback_mode_binding() -> ModeBinding { + let name = "Default".to_string(); + ModeBinding { + acp_mode: Mode { + id: mode_id(&name), + name: name.clone(), + description: None, + }, + mask: CoreCollaborationModeMask { + name, + mode: None, + model: None, + reasoning_effort: None, + developer_instructions: None, + }, + } +} + +fn core_mode_mask(mask: &CollaborationModeMask) -> CoreCollaborationModeMask { + CoreCollaborationModeMask { + name: mask.name.clone(), + mode: mask.mode, + model: mask.model.clone(), + reasoning_effort: mask.reasoning_effort, + developer_instructions: None, + } +} + +fn default_collaboration_mode( + mode_bindings: &[ModeBinding], + model: &str, + reasoning_effort: Option, +) -> CollaborationMode { + let base = CollaborationMode { + mode: mode_bindings + .first() + .and_then(|binding| binding.mask.mode) + .unwrap_or_default(), + settings: Settings { + model: model.to_string(), + reasoning_effort, + developer_instructions: None, + }, + }; + + mode_bindings + .first() + .map(|binding| base.apply_mask(&binding.mask)) + .unwrap_or(base) +} + +fn build_config_options( + mode_bindings: &[ModeBinding], + current_model: &str, + current_reasoning_effort: Option, + current_mode_id: &str, + models: &[Model], +) -> Vec { + let mut config_options = vec![ConfigOption { + id: "mode".to_string(), + name: "Session Mode".to_string(), + description: Some("Controls how Codex behaves for future turns.".to_string()), + category: Some("mode".to_string()), + option_type: "select".to_string(), + current_value: current_mode_id.to_string(), + options: mode_bindings + .iter() + .map(|binding| ConfigOptionValue { + value: binding.acp_mode.id.clone(), + name: binding.acp_mode.name.clone(), + description: binding.acp_mode.description.clone(), + }) + .collect(), + }]; + + if !models.is_empty() { + config_options.push(ConfigOption { + id: "model".to_string(), + name: "Model".to_string(), + description: Some("Current model for this session.".to_string()), + category: Some("model".to_string()), + option_type: "select".to_string(), + current_value: current_model.to_string(), + options: models + .iter() + .map(|model| ConfigOptionValue { + value: model.model.clone(), + name: model.display_name.clone(), + description: Some(model.description.clone()), + }) + .collect(), + }); + + if let Some(current_model_info) = models.iter().find(|model| model.model == current_model) { + config_options.push(ConfigOption { + id: "thought_level".to_string(), + name: "Thought Level".to_string(), + description: Some("Reasoning effort for the current model.".to_string()), + category: Some("thought_level".to_string()), + option_type: "select".to_string(), + current_value: reasoning_effort_id( + current_reasoning_effort.unwrap_or(current_model_info.default_reasoning_effort), + ), + options: current_model_info + .supported_reasoning_efforts + .iter() + .map(|effort| ConfigOptionValue { + value: reasoning_effort_id(effort.reasoning_effort), + name: reasoning_effort_name(effort.reasoning_effort), + description: Some(effort.description.clone()), + }) + .collect(), + }); + } + } + + config_options +} + +fn update_mode_config_options( + config_options: &mut [ConfigOption], + current_mode_id: &str, + current_model: &str, + current_reasoning_effort: Option, +) { + for option in config_options { + match option.id.as_str() { + "mode" => option.current_value = current_mode_id.to_string(), + "model" => option.current_value = current_model.to_string(), + "thought_level" => { + if let Some(reasoning_effort) = current_reasoning_effort { + option.current_value = reasoning_effort_id(reasoning_effort); + } + } + _ => {} + } + } +} + +fn mode_id(name: &str) -> String { + let mut id = String::new(); + let mut last_was_separator = false; + for ch in name.chars() { + if ch.is_ascii_alphanumeric() { + id.push(ch.to_ascii_lowercase()); + last_was_separator = false; + } else if !last_was_separator && !id.is_empty() { + id.push('_'); + last_was_separator = true; + } + } + id.trim_end_matches('_').to_string() +} + +fn reasoning_effort_id(reasoning_effort: ReasoningEffort) -> String { + match reasoning_effort { + ReasoningEffort::None => "none".to_string(), + ReasoningEffort::Minimal => "minimal".to_string(), + ReasoningEffort::Low => "low".to_string(), + ReasoningEffort::Medium => "medium".to_string(), + ReasoningEffort::High => "high".to_string(), + ReasoningEffort::XHigh => "xhigh".to_string(), + } +} + +fn reasoning_effort_name(reasoning_effort: ReasoningEffort) -> String { + match reasoning_effort { + ReasoningEffort::None => "None".to_string(), + ReasoningEffort::Minimal => "Minimal".to_string(), + ReasoningEffort::Low => "Low".to_string(), + ReasoningEffort::Medium => "Medium".to_string(), + ReasoningEffort::High => "High".to_string(), + ReasoningEffort::XHigh => "XHigh".to_string(), + } +} + +fn flatten_user_message_text(content: &[UserInput]) -> Vec { + content + .iter() + .filter_map(|item| match item { + UserInput::Text { text, .. } => Some(text.clone()), + _ => None, + }) + .collect() +} + +fn tool_call_text_output(text: Option) -> Option> { + text.filter(|text| !text.is_empty()).map(|text| { + vec![ToolCallContent::Content { + content: text_content(text), + }] + }) +} + +fn text_content(text: String) -> TextContent { + TextContent { + content_type: "text".to_string(), + text, + } +} + +fn map_command_status(status: codex_app_server_protocol::CommandExecutionStatus) -> String { + match status { + codex_app_server_protocol::CommandExecutionStatus::Completed => "completed".to_string(), + codex_app_server_protocol::CommandExecutionStatus::Failed => "failed".to_string(), + codex_app_server_protocol::CommandExecutionStatus::Declined => "cancelled".to_string(), + codex_app_server_protocol::CommandExecutionStatus::InProgress => "in_progress".to_string(), + } +} + +fn map_patch_status(status: codex_app_server_protocol::PatchApplyStatus) -> String { + match status { + codex_app_server_protocol::PatchApplyStatus::Completed => "completed".to_string(), + codex_app_server_protocol::PatchApplyStatus::Failed => "failed".to_string(), + codex_app_server_protocol::PatchApplyStatus::Declined => "cancelled".to_string(), + codex_app_server_protocol::PatchApplyStatus::InProgress => "in_progress".to_string(), + } +} + +fn invalid_params_error(error: impl std::fmt::Display) -> Error { + Error::new(ErrorKind::InvalidInput, error.to_string()) +} + +fn io_error_from_typed_request(error: impl std::fmt::Display) -> Error { + Error::other(error.to_string()) +} + +fn io_error_from_jsonrpc_error(error: &JsonRpcErrorBody) -> Error { + Error::other(format!("ACP error {}: {}", error.code, error.message)) +} + +fn acp_request_id_to_rmcp(id: RequestId) -> McpRequestId { + match id { + RequestId::Integer(value) => McpRequestId::Number(value), + RequestId::String(value) => McpRequestId::String(value.into()), + } +} + +fn rmcp_request_id_to_acp(id: McpRequestId) -> RequestId { + match id { + McpRequestId::Number(value) => RequestId::Integer(value), + McpRequestId::String(value) => RequestId::String(value.to_string()), + } +} + +fn acp_error_to_mcp_error(error: JsonRpcErrorBody) -> McpErrorData { + McpErrorData::new(McpErrorCode(error.code as i32), error.message, error.data) +} + +fn mcp_request_from_acp( + id: RequestId, + params: McpMessageParams, +) -> Result { + let mut value = serde_json::Map::new(); + value.insert( + "jsonrpc".to_string(), + JsonValue::String(JSONRPC_VERSION.to_string()), + ); + value.insert( + "id".to_string(), + serde_json::to_value(acp_request_id_to_rmcp(id)).map_err(invalid_params_error)?, + ); + value.insert("method".to_string(), JsonValue::String(params.method)); + if let Some(request_params) = params.params { + value.insert("params".to_string(), request_params); + } + if let Some(meta) = params.meta { + value.insert("_meta".to_string(), meta); + } + serde_json::from_value(JsonValue::Object(value)).map_err(invalid_params_error) +} + +fn mcp_notification_from_acp(params: McpMessageParams) -> Result { + let mut value = serde_json::Map::new(); + value.insert( + "jsonrpc".to_string(), + JsonValue::String(JSONRPC_VERSION.to_string()), + ); + value.insert("method".to_string(), JsonValue::String(params.method)); + if let Some(request_params) = params.params { + value.insert("params".to_string(), request_params); + } + if let Some(meta) = params.meta { + value.insert("_meta".to_string(), meta); + } + serde_json::from_value(JsonValue::Object(value)).map_err(invalid_params_error) +} + +fn mcp_message_params_from_value( + connection_id: &str, + value: JsonValue, +) -> Result { + let mut object = value + .as_object() + .cloned() + .ok_or_else(|| invalid_params_error("MCP message must serialize to an object"))?; + let method = object + .remove("method") + .and_then(|value| value.as_str().map(str::to_string)) + .ok_or_else(|| invalid_params_error("MCP message is missing method"))?; + Ok(McpMessageParams { + connection_id: connection_id.to_string(), + method, + params: object.remove("params"), + meta: object.remove("_meta").or_else(|| object.remove("meta")), + }) +} + +fn mcp_result_to_server_message( + request_id: McpRequestId, + result: McpMessageResult, +) -> ServerJsonRpcMessage { + let McpMessageResult { + result: result_value, + error, + meta, + } = result; + if let Some(error) = error { + let error = serde_json::from_value::(with_meta(error, meta)).unwrap_or_else( + |error| { + McpErrorData::new( + McpErrorCode::INTERNAL_ERROR, + format!("invalid ACP mcp/message error payload: {error}"), + None, + ) + }, + ); + return ServerJsonRpcMessage::Error(McpJsonRpcError { + jsonrpc: rmcp::model::JsonRpcVersion2_0, + id: request_id, + error, + }); + } + + let result_value = with_meta( + result_value.unwrap_or(JsonValue::Object(serde_json::Map::new())), + meta, + ); + match serde_json::from_value(result_value) { + Ok(result) => ServerJsonRpcMessage::Response(McpJsonRpcResponse { + jsonrpc: rmcp::model::JsonRpcVersion2_0, + id: request_id, + result, + }), + Err(error) => ServerJsonRpcMessage::Error(McpJsonRpcError { + jsonrpc: rmcp::model::JsonRpcVersion2_0, + id: request_id, + error: McpErrorData::new( + McpErrorCode::INTERNAL_ERROR, + format!("invalid ACP mcp/message result payload: {error}"), + None, + ), + }), + } +} + +fn mcp_result_from_client_response( + response: McpJsonRpcResponse, +) -> Result { + let mut result = serde_json::to_value(response.result).map_err(invalid_params_error)?; + let meta = take_meta(&mut result); + Ok(McpMessageResult { + result: Some(result), + error: None, + meta, + }) +} + +fn mcp_result_from_client_error(error: McpJsonRpcError) -> Result { + let mut error_value = serde_json::to_value(error.error).map_err(invalid_params_error)?; + let meta = take_meta(&mut error_value); + Ok(McpMessageResult { + result: None, + error: Some(error_value), + meta, + }) +} + +fn forward_client_mcp_message( + bridge_state: &AcpBridgeState, + connection_id: &str, + message: ClientJsonRpcMessage, +) -> IoResult<()> { + match message { + McpJsonRpcMessage::Request(McpJsonRpcRequest { id, request, .. }) => { + let inbound_tx = bridge_state + .connection_sender(connection_id) + .ok_or_else(|| Error::new(ErrorKind::NotFound, "ACP MCP connection not found"))?; + let outer_request_id = bridge_state.next_request_id("mcp-message"); + let params = mcp_message_params_from_value( + connection_id, + serde_json::to_value(request).map_err(invalid_params_error)?, + )?; + bridge_state + .pending_requests + .lock() + .unwrap_or_else(|_| panic!("ACP MCP request registry poisoned")) + .insert( + outer_request_id.clone(), + PendingMcpRequest { + inbound_tx, + request_id: id, + }, + ); + bridge_state.send_request( + outer_request_id, + "mcp/message", + serde_json::to_value(params).map_err(invalid_params_error)?, + ) + } + McpJsonRpcMessage::Notification(McpJsonRpcNotification { notification, .. }) => { + let params = mcp_message_params_from_value( + connection_id, + serde_json::to_value(notification).map_err(invalid_params_error)?, + )?; + bridge_state.send_notification( + "mcp/message", + serde_json::to_value(params).map_err(invalid_params_error)?, + ) + } + McpJsonRpcMessage::Response(response) => { + let request_id = rmcp_request_id_to_acp(response.id.clone()); + bridge_state.send_result( + request_id, + serde_json::to_value(mcp_result_from_client_response(response)?) + .map_err(invalid_params_error)?, + ) + } + McpJsonRpcMessage::Error(error) => { + let request_id = rmcp_request_id_to_acp(error.id.clone()); + bridge_state.send_result( + request_id, + serde_json::to_value(mcp_result_from_client_error(error)?) + .map_err(invalid_params_error)?, + ) + } + } +} + +async fn close_mcp_connection(bridge_state: &AcpBridgeState, connection_id: &str) -> IoResult<()> { + let request_id = bridge_state.next_request_id("mcp-disconnect"); + let (responder, receiver) = tokio::sync::oneshot::channel(); + bridge_state + .pending_disconnects + .lock() + .unwrap_or_else(|_| panic!("ACP MCP disconnect registry poisoned")) + .insert(request_id.clone(), PendingMcpDisconnect { responder }); + bridge_state.send_request( + request_id, + "mcp/disconnect", + serde_json::to_value(McpDisconnectParams { + connection_id: connection_id.to_string(), + meta: None, + }) + .map_err(invalid_params_error)?, + )?; + let result = receiver.await.map_err(|_| { + Error::new( + ErrorKind::BrokenPipe, + "ACP MCP disconnect response channel closed", + ) + })?; + bridge_state.unregister_connection(connection_id); + result +} + +fn take_meta(value: &mut JsonValue) -> Option { + value + .as_object_mut() + .and_then(|object| object.remove("_meta").or_else(|| object.remove("meta"))) +} + +fn with_meta(value: JsonValue, meta: Option) -> JsonValue { + let Some(meta) = meta else { + return value; + }; + match value { + JsonValue::Object(mut object) => { + object.insert("_meta".to_string(), meta); + JsonValue::Object(object) + } + other => other, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use pretty_assertions::assert_eq; + + #[test] + fn prompt_to_user_input_supports_text_resources() { + let input = prompt_to_user_input(&[PromptContent::Resource { + resource: crate::protocol::ResourceContent { + uri: "file:///tmp/test.txt".to_string(), + mime_type: None, + text: Some("hello".to_string()), + }, + }]) + .expect("text resources should be supported"); + assert_eq!( + input, + vec![UserInput::Text { + text: "\nhello\n" + .to_string(), + text_elements: Vec::new(), + }] + ); + } + + #[test] + fn command_permission_options_skip_advanced_variants() { + let (options, _, _) = build_command_permission_options(&Some(vec![ + CommandExecutionApprovalDecision::Accept, + CommandExecutionApprovalDecision::AcceptForSession, + CommandExecutionApprovalDecision::Decline, + CommandExecutionApprovalDecision::Cancel, + ])); + assert_eq!(options.len(), 4); + assert_eq!(options[0].option_id, "accept"); + assert_eq!(options[1].option_id, "accept-session"); + } + + #[test] + fn request_overrides_translate_stdio_mcp_servers() { + let overrides = build_request_overrides_from_mcp_servers(&[serde_json::json!({ + "name": "docs", + "transport": "stdio", + "command": "mcp-docs", + "args": ["--stdio"], + "env": [{"name": "ROOT", "value": "/tmp/project"}], + })]) + .expect("stdio MCP server should parse") + .expect("mcp overrides should be present"); + + let mcp_servers: HashMap = + serde_json::from_value(overrides["mcp_servers"].clone()) + .expect("mcp_servers should deserialize"); + let docs = mcp_servers.get("docs").expect("docs config missing"); + match &docs.transport { + McpServerTransportConfig::Stdio { + command, args, env, .. + } => { + assert_eq!(command, "mcp-docs"); + assert_eq!(args, &vec!["--stdio".to_string()]); + assert_eq!( + env.as_ref().and_then(|env| env.get("ROOT")), + Some(&"/tmp/project".to_string()) + ); + } + other => panic!("expected stdio transport, got {other:?}"), + } + } + + #[test] + fn request_overrides_translate_acp_transport_mcp_servers() { + let overrides = build_request_overrides_from_mcp_servers(&[serde_json::json!({ + "name": "docs", + "transport": "acp", + "id": "srv_123", + })]) + .expect("ACP transport should parse") + .expect("mcp overrides should be present"); + + let mcp_servers: HashMap = + serde_json::from_value(overrides["mcp_servers"].clone()) + .expect("mcp_servers should deserialize"); + let docs = mcp_servers.get("docs").expect("docs config missing"); + assert_eq!( + docs.transport, + McpServerTransportConfig::Acp { + transport: "acp".to_string(), + id: "srv_123".to_string(), + } + ); + } + + #[test] + fn update_mode_config_options_updates_mode_and_model_values() { + let mut config_options = vec![ + ConfigOption { + id: "mode".to_string(), + name: "Session Mode".to_string(), + description: None, + category: Some("mode".to_string()), + option_type: "select".to_string(), + current_value: "default".to_string(), + options: Vec::new(), + }, + ConfigOption { + id: "model".to_string(), + name: "Model".to_string(), + description: None, + category: Some("model".to_string()), + option_type: "select".to_string(), + current_value: "gpt-5".to_string(), + options: Vec::new(), + }, + ConfigOption { + id: "thought_level".to_string(), + name: "Thought Level".to_string(), + description: None, + category: Some("thought_level".to_string()), + option_type: "select".to_string(), + current_value: "low".to_string(), + options: Vec::new(), + }, + ]; + + update_mode_config_options( + &mut config_options, + "plan", + "gpt-5.2-codex", + Some(ReasoningEffort::High), + ); + + assert_eq!(config_options[0].current_value, "plan"); + assert_eq!(config_options[1].current_value, "gpt-5.2-codex"); + assert_eq!(config_options[2].current_value, "high"); + } +} diff --git a/codex-rs/acp-server/src/main.rs b/codex-rs/acp-server/src/main.rs new file mode 100644 index 0000000000..738c7e3a3b --- /dev/null +++ b/codex-rs/acp-server/src/main.rs @@ -0,0 +1,11 @@ +use codex_acp_server::run_main; +use codex_arg0::Arg0DispatchPaths; +use codex_arg0::arg0_dispatch_or_else; +use codex_utils_cli::CliConfigOverrides; + +fn main() -> anyhow::Result<()> { + arg0_dispatch_or_else(|arg0_paths: Arg0DispatchPaths| async move { + run_main(arg0_paths, CliConfigOverrides::default()).await?; + Ok(()) + }) +} diff --git a/codex-rs/acp-server/src/protocol.rs b/codex-rs/acp-server/src/protocol.rs new file mode 100644 index 0000000000..ac9e6c8584 --- /dev/null +++ b/codex-rs/acp-server/src/protocol.rs @@ -0,0 +1,546 @@ +use codex_app_server_protocol::RequestId; +use serde::Deserialize; +use serde::Serialize; +use serde_json::Value as JsonValue; + +pub const JSONRPC_VERSION: &str = "2.0"; +pub const PROTOCOL_VERSION: i64 = 1; + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(untagged)] +pub enum JsonRpcMessage { + Request(JsonRpcRequest), + Notification(JsonRpcNotification), + Response(JsonRpcResponse), + Error(JsonRpcError), +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct JsonRpcRequest { + pub jsonrpc: String, + pub id: RequestId, + pub method: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub params: Option, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct JsonRpcNotification { + pub jsonrpc: String, + pub method: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub params: Option, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct JsonRpcResponse { + pub jsonrpc: String, + pub id: RequestId, + pub result: JsonValue, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct JsonRpcError { + pub jsonrpc: String, + pub id: RequestId, + pub error: JsonRpcErrorBody, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct JsonRpcErrorBody { + pub code: i64, + pub message: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub data: Option, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct InitializeParams { + pub protocol_version: i64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub client_capabilities: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub client_info: Option, +} + +#[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ClientCapabilities { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub elicitation: Option, +} + +#[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ElicitationCapabilities { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub form: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub url: Option, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ClientInfo { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub name: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub title: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub version: Option, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct InitializeResult { + pub protocol_version: i64, + pub agent_capabilities: AgentCapabilities, + pub agent_info: AgentInfo, + pub auth_methods: Vec, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct AgentCapabilities { + pub load_session: bool, + pub session_capabilities: SessionCapabilities, + pub prompt_capabilities: PromptCapabilities, + pub mcp_capabilities: McpCapabilities, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionCapabilities { + pub list: EmptyCapability, + pub fork: EmptyCapability, + pub resume: EmptyCapability, + pub close: EmptyCapability, +} + +#[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)] +pub struct EmptyCapability {} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct McpCapabilities { + pub http: bool, + pub sse: bool, + pub acp: bool, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PromptCapabilities { + pub image: bool, + pub audio: bool, + pub embedded_context: bool, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Mode { + pub id: String, + pub name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub description: Option, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Modes { + pub current_mode_id: String, + pub available_modes: Vec, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct AgentInfo { + pub name: String, + pub title: String, + pub version: String, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionNewParams { + pub cwd: String, + #[serde(default)] + pub mcp_servers: Vec, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionNewResult { + pub session_id: String, + pub modes: Modes, + pub config_options: Vec, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionLoadParams { + pub session_id: String, + pub cwd: String, + #[serde(default)] + pub mcp_servers: Vec, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionLoadResult { + pub modes: Modes, + pub config_options: Vec, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionResumeParams { + pub session_id: String, + pub cwd: String, + #[serde(default)] + pub mcp_servers: Vec, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionResumeResult { + pub modes: Modes, + pub config_options: Vec, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionForkParams { + pub session_id: String, + pub cwd: String, + #[serde(default)] + pub mcp_servers: Vec, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionForkResult { + pub session_id: String, + pub modes: Modes, + pub config_options: Vec, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionListParams { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cwd: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cursor: Option, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionListResult { + pub sessions: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub next_cursor: Option, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionInfo { + pub session_id: String, + pub cwd: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub title: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub updated_at: Option, + #[serde(default, rename = "_meta", skip_serializing_if = "Option::is_none")] + pub meta: Option, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionCloseParams { + pub session_id: String, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct SessionCloseResult {} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionSetModeParams { + pub session_id: String, + pub mode_id: String, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct SessionSetModeResult {} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionPromptParams { + pub session_id: String, + pub prompt: Vec, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum PromptContent { + Text { text: String }, + Resource { resource: ResourceContent }, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ResourceContent { + pub uri: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub mime_type: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub text: Option, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionPromptResult { + pub stop_reason: String, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionCancelParams { + pub session_id: String, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionUpdateParams { + pub session_id: String, + pub update: SessionUpdate, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(tag = "sessionUpdate", rename_all = "snake_case")] +pub enum SessionUpdate { + UserMessageChunk { + content: TextContent, + }, + AgentMessageChunk { + content: TextContent, + }, + Plan { + entries: Vec, + }, + CurrentModeUpdate { + current_mode_id: String, + }, + ConfigOptionsUpdate { + config_options: Vec, + }, + SessionInfoUpdate { + #[serde(default, skip_serializing_if = "Option::is_none")] + title: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + updated_at: Option, + #[serde(default, rename = "_meta", skip_serializing_if = "Option::is_none")] + meta: Option, + }, + ToolCall { + tool_call_id: String, + title: String, + kind: String, + status: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + locations: Option>, + }, + ToolCallUpdate { + tool_call_id: String, + status: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + content: Option>, + }, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct TextContent { + #[serde(rename = "type")] + pub content_type: String, + pub text: String, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PlanEntry { + pub content: String, + pub priority: String, + pub status: String, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ConfigOption { + pub id: String, + pub name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub description: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub category: Option, + #[serde(rename = "type")] + pub option_type: String, + pub current_value: String, + pub options: Vec, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ConfigOptionValue { + pub value: String, + pub name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub description: Option, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct Location { + pub path: String, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum ToolCallContent { + Content { content: TextContent }, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionRequestPermissionParams { + pub session_id: String, + pub tool_call: PermissionToolCall, + pub options: Vec, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionElicitationParams { + pub session_id: String, + pub elicitation: SessionElicitationRequest, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(tag = "mode", rename_all = "camelCase")] +pub enum SessionElicitationRequest { + #[serde(rename_all = "camelCase")] + Form { + message: String, + requested_schema: JsonValue, + #[serde(default, rename = "_meta", skip_serializing_if = "Option::is_none")] + meta: Option, + }, + #[serde(rename_all = "camelCase")] + Url { + message: String, + url: String, + elicitation_id: String, + #[serde(default, rename = "_meta", skip_serializing_if = "Option::is_none")] + meta: Option, + }, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionElicitationResponse { + pub action: ElicitationAction, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub content: Option, + #[serde(default, rename = "_meta", skip_serializing_if = "Option::is_none")] + pub meta: Option, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum ElicitationAction { + Accept, + Decline, + Cancel, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct McpConnectParams { + pub acp_id: String, + #[serde(default, alias = "_meta", skip_serializing_if = "Option::is_none")] + pub meta: Option, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct McpConnectResult { + pub connection_id: String, + #[serde(default, alias = "_meta", skip_serializing_if = "Option::is_none")] + pub meta: Option, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct McpDisconnectParams { + pub connection_id: String, + #[serde(default, alias = "_meta", skip_serializing_if = "Option::is_none")] + pub meta: Option, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct McpDisconnectResult { + #[serde(default, alias = "_meta", skip_serializing_if = "Option::is_none")] + pub meta: Option, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct McpMessageParams { + pub connection_id: String, + pub method: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub params: Option, + #[serde(default, alias = "_meta", skip_serializing_if = "Option::is_none")] + pub meta: Option, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct McpMessageResult { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub result: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub error: Option, + #[serde(default, alias = "_meta", skip_serializing_if = "Option::is_none")] + pub meta: Option, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PermissionToolCall { + pub tool_call_id: String, + pub title: String, + pub kind: String, + pub status: String, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PermissionOption { + pub option_id: String, + pub name: String, + pub kind: String, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct PermissionResponse { + pub outcome: PermissionOutcome, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(tag = "outcome", rename_all = "snake_case")] +pub enum PermissionOutcome { + Selected { option_id: String }, + Cancelled, +} diff --git a/codex-rs/acp-server/tests/stdio.rs b/codex-rs/acp-server/tests/stdio.rs new file mode 100644 index 0000000000..058c34157e --- /dev/null +++ b/codex-rs/acp-server/tests/stdio.rs @@ -0,0 +1,174 @@ +use std::io::BufRead; +use std::io::BufReader; +use std::io::Write; +use std::process::Command; +use std::process::Stdio; + +use anyhow::Context; +use anyhow::Result; +use pretty_assertions::assert_eq; +use serde_json::Value as JsonValue; +use tempfile::TempDir; + +fn write_json_line(stdin: &mut std::process::ChildStdin, value: JsonValue) -> Result<()> { + writeln!(stdin, "{}", serde_json::to_string(&value)?)?; + stdin.flush()?; + Ok(()) +} + +fn read_json_line(stdout: &mut BufReader) -> Result { + let mut line = String::new(); + stdout.read_line(&mut line)?; + serde_json::from_str(&line).context("parse ACP JSON-RPC response") +} + +fn read_response(stdout: &mut BufReader, id: i64) -> Result { + loop { + let message = read_json_line(stdout)?; + if message["id"] == id { + return Ok(message); + } + } +} + +fn read_session_update_kinds( + stdout: &mut BufReader, + count: usize, +) -> Result> { + let mut kinds = Vec::new(); + while kinds.len() < count { + let message = read_json_line(stdout)?; + if message["method"] == "session/update" { + kinds.push( + message["params"]["update"]["sessionUpdate"] + .as_str() + .context("session update kind missing")? + .to_string(), + ); + } + } + Ok(kinds) +} + +#[test] +fn acp_server_supports_session_setup_and_mode_switching() -> Result<()> { + let codex_home = TempDir::new()?; + let workspace = TempDir::new()?; + let mut child = Command::new(codex_utils_cargo_bin::cargo_bin("codex-acp-server")?) + .env("CODEX_HOME", codex_home.path()) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::inherit()) + .spawn() + .context("spawn codex-acp-server")?; + + let mut stdin = child.stdin.take().context("take stdin")?; + let stdout = child.stdout.take().context("take stdout")?; + let mut stdout = BufReader::new(stdout); + + write_json_line( + &mut stdin, + serde_json::json!({ + "jsonrpc": "2.0", + "id": 1, + "method": "initialize", + "params": { + "protocolVersion": 1, + "clientInfo": { + "name": "acp-test", + "version": "0.0.0" + } + } + }), + )?; + + let initialize = read_response(&mut stdout, 1)?; + assert_eq!(initialize["id"], 1); + assert_eq!(initialize["result"]["protocolVersion"], 1); + assert_eq!( + initialize["result"]["agentCapabilities"]["promptCapabilities"]["embeddedContext"], + JsonValue::Bool(true) + ); + assert_eq!( + initialize["result"]["agentCapabilities"]["promptCapabilities"]["image"], + JsonValue::Bool(true) + ); + assert_eq!( + initialize["result"]["agentCapabilities"]["mcpCapabilities"]["acp"], + JsonValue::Bool(true) + ); + assert_eq!( + initialize["result"]["agentCapabilities"]["sessionCapabilities"]["list"], + serde_json::json!({}) + ); + assert_eq!( + initialize["result"]["agentCapabilities"]["sessionCapabilities"]["fork"], + serde_json::json!({}) + ); + assert_eq!( + initialize["result"]["agentCapabilities"]["sessionCapabilities"]["resume"], + serde_json::json!({}) + ); + assert_eq!( + initialize["result"]["agentCapabilities"]["sessionCapabilities"]["close"], + serde_json::json!({}) + ); + + write_json_line( + &mut stdin, + serde_json::json!({ + "jsonrpc": "2.0", + "id": 2, + "method": "session/new", + "params": { + "cwd": workspace.path(), + "mcpServers": [] + } + }), + )?; + + let session_new = read_response(&mut stdout, 2)?; + assert_eq!(session_new["id"], 2); + let session_id = session_new["result"]["sessionId"] + .as_str() + .context("sessionId missing")? + .to_string(); + let modes = session_new["result"]["modes"]["availableModes"] + .as_array() + .context("availableModes missing")?; + assert!(!modes.is_empty(), "expected at least one ACP mode"); + let first_mode_id = modes[0]["id"] + .as_str() + .context("mode id missing")? + .to_string(); + assert_eq!( + session_new["result"]["configOptions"][0]["id"], + JsonValue::String("mode".to_string()) + ); + + write_json_line( + &mut stdin, + serde_json::json!({ + "jsonrpc": "2.0", + "id": 3, + "method": "session/set_mode", + "params": { + "sessionId": session_id, + "modeId": first_mode_id + } + }), + )?; + + let set_mode = read_response(&mut stdout, 3)?; + assert_eq!(set_mode["id"], 3); + assert_eq!(set_mode["result"], serde_json::json!({})); + + let updates = read_session_update_kinds(&mut stdout, 2)?; + assert!(updates.contains(&"current_mode_update".to_string())); + assert!(updates.contains(&"config_options_update".to_string())); + + drop(stdin); + child.kill()?; + let _ = child.wait()?; + Ok(()) +} diff --git a/codex-rs/app-server-protocol/schema/json/ServerNotification.json b/codex-rs/app-server-protocol/schema/json/ServerNotification.json index a3836b48f3..cfa6fd6900 100644 --- a/codex-rs/app-server-protocol/schema/json/ServerNotification.json +++ b/codex-rs/app-server-protocol/schema/json/ServerNotification.json @@ -1701,6 +1701,7 @@ "cli", "vscode", "exec", + "acp", "appServer", "unknown" ], diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json index 228a49d351..f4f2e418d7 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json @@ -14336,6 +14336,7 @@ "cli", "vscode", "exec", + "acp", "appServer", "unknown" ], diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json index b5fdebe7dd..3935e0d466 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json @@ -12134,6 +12134,7 @@ "cli", "vscode", "exec", + "acp", "appServer", "unknown" ], diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json index 96772c6aae..3705ebd4ab 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json @@ -760,6 +760,7 @@ "cli", "vscode", "exec", + "acp", "appServer", "unknown" ], diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadListResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadListResponse.json index 3965739d1a..83fc390cb6 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadListResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadListResponse.json @@ -518,6 +518,7 @@ "cli", "vscode", "exec", + "acp", "appServer", "unknown" ], diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadMetadataUpdateResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadMetadataUpdateResponse.json index a74ee5d63c..1f7f21ce8f 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadMetadataUpdateResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadMetadataUpdateResponse.json @@ -518,6 +518,7 @@ "cli", "vscode", "exec", + "acp", "appServer", "unknown" ], diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadReadResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadReadResponse.json index f00275398f..b1f81ab1d6 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadReadResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadReadResponse.json @@ -518,6 +518,7 @@ "cli", "vscode", "exec", + "acp", "appServer", "unknown" ], diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json index 013485bd12..4f92635e53 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json @@ -760,6 +760,7 @@ "cli", "vscode", "exec", + "acp", "appServer", "unknown" ], diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadRollbackResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadRollbackResponse.json index e95b2d850f..a554a40fcd 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadRollbackResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadRollbackResponse.json @@ -518,6 +518,7 @@ "cli", "vscode", "exec", + "acp", "appServer", "unknown" ], diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json index 97193de56d..f7c8cc5bdb 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json @@ -760,6 +760,7 @@ "cli", "vscode", "exec", + "acp", "appServer", "unknown" ], diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartedNotification.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartedNotification.json index 698793bbdc..8892beda45 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartedNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartedNotification.json @@ -518,6 +518,7 @@ "cli", "vscode", "exec", + "acp", "appServer", "unknown" ], diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadUnarchiveResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadUnarchiveResponse.json index 30d1e2841f..a0be9adefc 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadUnarchiveResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadUnarchiveResponse.json @@ -518,6 +518,7 @@ "cli", "vscode", "exec", + "acp", "appServer", "unknown" ], diff --git a/codex-rs/app-server-protocol/schema/typescript/SessionSource.ts b/codex-rs/app-server-protocol/schema/typescript/SessionSource.ts index e5e746e384..a7cec5ba4c 100644 --- a/codex-rs/app-server-protocol/schema/typescript/SessionSource.ts +++ b/codex-rs/app-server-protocol/schema/typescript/SessionSource.ts @@ -3,4 +3,4 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. import type { SubAgentSource } from "./SubAgentSource"; -export type SessionSource = "cli" | "vscode" | "exec" | "mcp" | { "subagent": SubAgentSource } | "unknown"; +export type SessionSource = "cli" | "vscode" | "exec" | "acp" | "mcp" | { "subagent": SubAgentSource } | "unknown"; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/SessionSource.ts b/codex-rs/app-server-protocol/schema/typescript/v2/SessionSource.ts index b35b421fcd..18e030bff7 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/SessionSource.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/SessionSource.ts @@ -3,4 +3,4 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. import type { SubAgentSource } from "../SubAgentSource"; -export type SessionSource = "cli" | "vscode" | "exec" | "appServer" | { "subAgent": SubAgentSource } | "unknown"; +export type SessionSource = "cli" | "vscode" | "exec" | "acp" | "appServer" | { "subAgent": SubAgentSource } | "unknown"; diff --git a/codex-rs/app-server-protocol/src/protocol/v2.rs b/codex-rs/app-server-protocol/src/protocol/v2.rs index e557ef586d..f78fa05c2e 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2.rs @@ -1382,6 +1382,7 @@ pub enum SessionSource { #[default] VsCode, Exec, + Acp, AppServer, SubAgent(CoreSubAgentSource), #[serde(other)] @@ -1394,6 +1395,7 @@ impl From for SessionSource { CoreSessionSource::Cli => SessionSource::Cli, CoreSessionSource::VSCode => SessionSource::VsCode, CoreSessionSource::Exec => SessionSource::Exec, + CoreSessionSource::Acp => SessionSource::Acp, CoreSessionSource::Mcp => SessionSource::AppServer, CoreSessionSource::SubAgent(sub) => SessionSource::SubAgent(sub), CoreSessionSource::Unknown => SessionSource::Unknown, @@ -1407,6 +1409,7 @@ impl From for CoreSessionSource { SessionSource::Cli => CoreSessionSource::Cli, SessionSource::VsCode => CoreSessionSource::VSCode, SessionSource::Exec => CoreSessionSource::Exec, + SessionSource::Acp => CoreSessionSource::Acp, SessionSource::AppServer => CoreSessionSource::Mcp, SessionSource::SubAgent(sub) => CoreSessionSource::SubAgent(sub), SessionSource::Unknown => CoreSessionSource::Unknown, diff --git a/codex-rs/cli/Cargo.toml b/codex-rs/cli/Cargo.toml index 7c51f84bde..74c9e87ce9 100644 --- a/codex-rs/cli/Cargo.toml +++ b/codex-rs/cli/Cargo.toml @@ -22,6 +22,7 @@ clap_complete = { workspace = true } codex-app-server = { workspace = true } codex-app-server-protocol = { workspace = true } codex-app-server-test-client = { workspace = true } +codex-acp-server = { workspace = true } codex-arg0 = { workspace = true } codex-chatgpt = { workspace = true } codex-cloud-tasks = { path = "../cloud-tasks" } diff --git a/codex-rs/cli/src/main.rs b/codex-rs/cli/src/main.rs index d977979b89..cbf9ab3136 100644 --- a/codex-rs/cli/src/main.rs +++ b/codex-rs/cli/src/main.rs @@ -102,6 +102,9 @@ enum Subcommand { /// Start Codex as an MCP server (stdio). McpServer, + /// Start Codex as an ACP server (stdio). + AcpServer, + /// [experimental] Run the app server or related tooling. AppServer(AppServerCommand), @@ -597,6 +600,9 @@ async fn cli_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> { Some(Subcommand::McpServer) => { codex_mcp_server::run_main(arg0_paths.clone(), root_config_overrides).await?; } + Some(Subcommand::AcpServer) => { + codex_acp_server::run_main(arg0_paths.clone(), root_config_overrides).await?; + } Some(Subcommand::Mcp(mut mcp_cli)) => { // Propagate any root-level config overrides (e.g. `-c key=value`). prepend_config_flags(&mut mcp_cli.config_overrides, root_config_overrides.clone()); @@ -1207,6 +1213,14 @@ mod tests { app_server } + #[test] + fn parses_acp_server_subcommand() { + let cli = MultitoolCli::try_parse_from(["codex", "acp-server"]).expect("parse"); + let Some(Subcommand::AcpServer) = cli.subcommand else { + panic!("expected acp-server subcommand"); + }; + } + fn sample_exit_info(conversation_id: Option<&str>, thread_name: Option<&str>) -> AppExitInfo { let token_usage = TokenUsage { output_tokens: 2, diff --git a/codex-rs/cli/src/mcp_cmd.rs b/codex-rs/cli/src/mcp_cmd.rs index 00a04693f9..ace1dc8969 100644 --- a/codex-rs/cli/src/mcp_cmd.rs +++ b/codex-rs/cli/src/mcp_cmd.rs @@ -426,6 +426,10 @@ async fn run_list(config_overrides: &CliConfigOverrides, list_args: ListArgs) -> .map(|entry| entry.auth_status) .unwrap_or(McpAuthStatus::Unsupported); let transport = match &cfg.transport { + McpServerTransportConfig::Acp { id, .. } => serde_json::json!({ + "type": "acp", + "id": id, + }), McpServerTransportConfig::Stdio { command, args, @@ -482,10 +486,20 @@ async fn run_list(config_overrides: &CliConfigOverrides, list_args: ListArgs) -> } let mut stdio_rows: Vec<[String; 7]> = Vec::new(); + let mut acp_rows: Vec<[String; 4]> = Vec::new(); let mut http_rows: Vec<[String; 5]> = Vec::new(); for (name, cfg) in entries { match &cfg.transport { + McpServerTransportConfig::Acp { id, .. } => { + let status = format_mcp_status(cfg); + let auth_status = auth_statuses + .get(name.as_str()) + .map(|entry| entry.auth_status) + .unwrap_or(McpAuthStatus::Unsupported) + .to_string(); + acp_rows.push([name.clone(), id.clone(), status, auth_status]); + } McpServerTransportConfig::Stdio { command, args, @@ -603,6 +617,45 @@ async fn run_list(config_overrides: &CliConfigOverrides, list_args: ListArgs) -> println!(); } + if !acp_rows.is_empty() { + let mut widths = ["Name".len(), "ACP Id".len(), "Status".len(), "Auth".len()]; + for row in &acp_rows { + for (i, cell) in row.iter().enumerate() { + widths[i] = widths[i].max(cell.len()); + } + } + + println!( + "{name: Re if get_args.json { let transport = match &server.transport { + McpServerTransportConfig::Acp { id, .. } => serde_json::json!({ + "type": "acp", + "id": id, + }), McpServerTransportConfig::Stdio { command, args, @@ -739,6 +796,10 @@ async fn run_get(config_overrides: &CliConfigOverrides, get_args: GetArgs) -> Re println!(" disabled_tools: {disabled_tools_display}"); } match &server.transport { + McpServerTransportConfig::Acp { id, .. } => { + println!(" transport: acp"); + println!(" id: {id}"); + } McpServerTransportConfig::Stdio { command, args, diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index 573b35218a..984bf217cb 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -1245,6 +1245,10 @@ }, "type": "object" }, + "id": { + "default": null, + "type": "string" + }, "oauth_resource": { "default": null, "type": "string" @@ -1276,6 +1280,10 @@ "format": "double", "type": "number" }, + "transport": { + "default": null, + "type": "string" + }, "url": { "type": "string" } diff --git a/codex-rs/core/src/config/edit.rs b/codex-rs/core/src/config/edit.rs index cf139d3a5e..fef051fef2 100644 --- a/codex-rs/core/src/config/edit.rs +++ b/codex-rs/core/src/config/edit.rs @@ -147,6 +147,10 @@ mod document_helpers { entry.set_implicit(false); match &config.transport { + McpServerTransportConfig::Acp { id, .. } => { + entry["transport"] = value("acp"); + entry["id"] = value(id.clone()); + } McpServerTransportConfig::Stdio { command, args, diff --git a/codex-rs/core/src/config/types.rs b/codex-rs/core/src/config/types.rs index d3e3542c57..fd2baebb79 100644 --- a/codex-rs/core/src/config/types.rs +++ b/codex-rs/core/src/config/types.rs @@ -111,6 +111,11 @@ pub struct McpServerConfig { #[derive(Deserialize, Clone, JsonSchema)] #[schemars(deny_unknown_fields)] pub(crate) struct RawMcpServerConfig { + #[serde(default)] + pub transport: Option, + #[serde(default)] + pub id: Option, + // stdio pub command: Option, #[serde(default)] @@ -187,7 +192,31 @@ impl<'de> Deserialize<'de> for McpServerConfig { ))) } - let transport = if let Some(command) = raw.command.clone() { + let transport = if raw.transport.as_deref() == Some("acp") || raw.id.is_some() { + throw_if_set("acp", "command", raw.command.as_ref())?; + throw_if_set("acp", "args", raw.args.as_ref())?; + throw_if_set("acp", "env", raw.env.as_ref())?; + throw_if_set("acp", "env_vars", raw.env_vars.as_ref())?; + throw_if_set("acp", "cwd", raw.cwd.as_ref())?; + throw_if_set("acp", "url", raw.url.as_ref())?; + throw_if_set( + "acp", + "bearer_token_env_var", + raw.bearer_token_env_var.as_ref(), + )?; + throw_if_set("acp", "bearer_token", raw.bearer_token.as_ref())?; + throw_if_set("acp", "http_headers", raw.http_headers.as_ref())?; + throw_if_set("acp", "env_http_headers", raw.env_http_headers.as_ref())?; + let acp_id = raw + .id + .clone() + .filter(|id| !id.is_empty()) + .ok_or_else(|| SerdeError::custom("acp transport requires non-empty id"))?; + McpServerTransportConfig::Acp { + transport: "acp".to_string(), + id: acp_id, + } + } else if let Some(command) = raw.command.clone() { throw_if_set("stdio", "url", raw.url.as_ref())?; throw_if_set( "stdio", @@ -243,6 +272,8 @@ const fn default_enabled() -> bool { #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema)] #[serde(untagged, deny_unknown_fields, rename_all = "snake_case")] pub enum McpServerTransportConfig { + /// ACP draft MCP-over-ACP transport. + Acp { transport: String, id: String }, /// https://modelcontextprotocol.io/specification/2025-06-18/basic/transports#stdio Stdio { command: String, diff --git a/codex-rs/core/src/mcp/auth.rs b/codex-rs/core/src/mcp/auth.rs index f095c930dc..63473e15c5 100644 --- a/codex-rs/core/src/mcp/auth.rs +++ b/codex-rs/core/src/mcp/auth.rs @@ -92,6 +92,7 @@ async fn compute_auth_status( store_mode: OAuthCredentialsStoreMode, ) -> Result { match &config.transport { + McpServerTransportConfig::Acp { .. } => Ok(McpAuthStatus::Unsupported), McpServerTransportConfig::Stdio { .. } => Ok(McpAuthStatus::Unsupported), McpServerTransportConfig::StreamableHttp { url, diff --git a/codex-rs/core/src/mcp/skill_dependencies.rs b/codex-rs/core/src/mcp/skill_dependencies.rs index f15bb6ec57..c68b0847ba 100644 --- a/codex-rs/core/src/mcp/skill_dependencies.rs +++ b/codex-rs/core/src/mcp/skill_dependencies.rs @@ -284,6 +284,7 @@ fn canonical_mcp_key(transport: &str, identifier: &str, fallback: &str) -> Strin fn canonical_mcp_server_key(name: &str, config: &McpServerConfig) -> String { match &config.transport { + McpServerTransportConfig::Acp { id, .. } => canonical_mcp_key("acp", id, name), McpServerTransportConfig::Stdio { command, .. } => { canonical_mcp_key("stdio", command, name) } diff --git a/codex-rs/core/src/mcp_connection_manager.rs b/codex-rs/core/src/mcp_connection_manager.rs index 713e16c812..8f99719d2c 100644 --- a/codex-rs/core/src/mcp_connection_manager.rs +++ b/codex-rs/core/src/mcp_connection_manager.rs @@ -1439,6 +1439,9 @@ async fn make_rmcp_client( .await .map_err(StartupOutcomeError::from) } + McpServerTransportConfig::Acp { id, .. } => RmcpClient::new_acp_client(id) + .await + .map_err(StartupOutcomeError::from), } } @@ -1549,6 +1552,7 @@ fn transport_origin(transport: &McpServerTransportConfig) -> Option { let parsed = Url::parse(url).ok()?; Some(parsed.origin().ascii_serialization()) } + McpServerTransportConfig::Acp { id, .. } => Some(format!("acp:{id}")), McpServerTransportConfig::Stdio { .. } => Some("stdio".to_string()), } } diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index 98ff8f7f55..2f7b9710d9 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -2191,6 +2191,7 @@ pub enum SessionSource { #[default] VSCode, Exec, + Acp, Mcp, SubAgent(SubAgentSource), #[serde(other)] @@ -2221,6 +2222,7 @@ impl fmt::Display for SessionSource { SessionSource::Cli => f.write_str("cli"), SessionSource::VSCode => f.write_str("vscode"), SessionSource::Exec => f.write_str("exec"), + SessionSource::Acp => f.write_str("acp"), SessionSource::Mcp => f.write_str("mcp"), SessionSource::SubAgent(sub_source) => write!(f, "subagent_{sub_source}"), SessionSource::Unknown => f.write_str("unknown"), diff --git a/codex-rs/rmcp-client/src/acp_bridge.rs b/codex-rs/rmcp-client/src/acp_bridge.rs new file mode 100644 index 0000000000..40fa0937ea --- /dev/null +++ b/codex-rs/rmcp-client/src/acp_bridge.rs @@ -0,0 +1,36 @@ +use std::sync::Arc; +use std::sync::LazyLock; +use std::sync::RwLock; + +use anyhow::Result; +use futures::future::BoxFuture; +use rmcp::model::ClientJsonRpcMessage; +use rmcp::model::ServerJsonRpcMessage; + +pub trait AcpConnection: Send + Sync + 'static { + fn send(&self, message: ClientJsonRpcMessage) -> BoxFuture<'static, Result<()>>; + fn recv(&self) -> BoxFuture<'static, Result>>; + fn close(&self) -> BoxFuture<'static, Result<()>>; +} + +pub trait AcpBridge: Send + Sync + 'static { + fn connect(&self, acp_id: String) -> BoxFuture<'static, Result>>; +} + +static ACP_BRIDGE: LazyLock>>> = + LazyLock::new(|| RwLock::new(None)); + +pub fn set_acp_bridge(bridge: Option>) { + let mut slot = ACP_BRIDGE + .write() + .unwrap_or_else(|_| panic!("ACP bridge registry poisoned")); + *slot = bridge; +} + +pub(crate) fn get_acp_bridge() -> Result> { + ACP_BRIDGE + .read() + .unwrap_or_else(|_| panic!("ACP bridge registry poisoned")) + .clone() + .ok_or_else(|| anyhow::anyhow!("ACP MCP bridge is not installed")) +} diff --git a/codex-rs/rmcp-client/src/lib.rs b/codex-rs/rmcp-client/src/lib.rs index a10d3b29ae..297b7e7d8f 100644 --- a/codex-rs/rmcp-client/src/lib.rs +++ b/codex-rs/rmcp-client/src/lib.rs @@ -1,3 +1,4 @@ +mod acp_bridge; mod auth_status; mod logging_client_handler; mod oauth; @@ -6,6 +7,9 @@ mod program_resolver; mod rmcp_client; mod utils; +pub use acp_bridge::AcpBridge; +pub use acp_bridge::AcpConnection; +pub use acp_bridge::set_acp_bridge; pub use auth_status::determine_streamable_http_auth_status; pub use auth_status::supports_oauth_login; pub use codex_protocol::protocol::McpAuthStatus; diff --git a/codex-rs/rmcp-client/src/rmcp_client.rs b/codex-rs/rmcp-client/src/rmcp_client.rs index c3bb6be0e6..fc2446597b 100644 --- a/codex-rs/rmcp-client/src/rmcp_client.rs +++ b/codex-rs/rmcp-client/src/rmcp_client.rs @@ -53,6 +53,11 @@ use rmcp::transport::streamable_http_client::StreamableHttpClient; use rmcp::transport::streamable_http_client::StreamableHttpClientTransportConfig; use rmcp::transport::streamable_http_client::StreamableHttpError; use rmcp::transport::streamable_http_client::StreamableHttpPostResponse; +use rmcp::transport::worker::Worker; +use rmcp::transport::worker::WorkerConfig; +use rmcp::transport::worker::WorkerContext; +use rmcp::transport::worker::WorkerQuitReason; +use rmcp::transport::worker::WorkerTransport; use serde::Deserialize; use serde::Serialize; use serde_json::Value; @@ -66,6 +71,8 @@ use tokio::time; use tracing::info; use tracing::warn; +use crate::acp_bridge::AcpConnection; +use crate::acp_bridge::get_acp_bridge; use crate::load_oauth_tokens; use crate::logging_client_handler::LoggingClientHandler; use crate::oauth::OAuthCredentialsStoreMode; @@ -295,6 +302,84 @@ impl StreamableHttpClient for StreamableHttpResponseClient { } } +#[derive(Debug, thiserror::Error)] +enum AcpTransportError { + #[error("ACP transport bridge is closed")] + Closed, + #[error("ACP transport join failed: {0}")] + Join(#[source] tokio::task::JoinError), + #[error(transparent)] + Bridge(#[from] anyhow::Error), +} + +struct AcpTransportWorker { + connection: Arc, +} + +impl Worker for AcpTransportWorker { + type Error = AcpTransportError; + type Role = RoleClient; + + fn err_closed() -> Self::Error { + AcpTransportError::Closed + } + + fn err_join(error: tokio::task::JoinError) -> Self::Error { + AcpTransportError::Join(error) + } + + fn config(&self) -> WorkerConfig { + WorkerConfig { + name: Some("mcp_acp_transport".to_string()), + channel_buffer_capacity: 32, + } + } + + async fn run( + self, + mut context: WorkerContext, + ) -> Result<(), WorkerQuitReason> { + let cancellation_token = context.cancellation_token.clone(); + loop { + tokio::select! { + _ = cancellation_token.cancelled() => { + self.connection + .close() + .await + .map_err(AcpTransportError::from) + .map_err(WorkerQuitReason::fatal_context("closing ACP transport"))?; + return Err(WorkerQuitReason::Cancelled); + } + incoming = self.connection.recv() => { + match incoming + .map_err(AcpTransportError::from) + .map_err(WorkerQuitReason::fatal_context("receiving ACP MCP message"))? + { + Some(message) => context.send_to_handler(message).await?, + None => return Err(WorkerQuitReason::TransportClosed), + } + } + outbound = context.recv_from_handler() => { + let outbound = outbound?; + let send_result = self.connection + .send(outbound.message) + .await + .map_err(AcpTransportError::from); + match send_result { + Ok(()) => { + let _ = outbound.responder.send(Ok(())); + } + Err(error) => { + let _ = outbound.responder.send(Err(AcpTransportError::Closed)); + return Err(WorkerQuitReason::fatal(error, "sending ACP MCP message")); + } + } + } + } + } + } +} + enum PendingTransport { ChildProcess { transport: TokioChildProcess, @@ -307,6 +392,9 @@ enum PendingTransport { transport: StreamableHttpClientTransport>, oauth_persistor: OAuthPersistor, }, + Acp { + transport: WorkerTransport, + }, } enum ClientState { @@ -396,6 +484,9 @@ enum TransportRecipe { env_http_headers: Option>, store_mode: OAuthCredentialsStoreMode, }, + Acp { + acp_id: String, + }, } #[derive(Clone)] @@ -524,6 +615,19 @@ impl RmcpClient { }) } + pub async fn new_acp_client(acp_id: String) -> Result { + let transport_recipe = TransportRecipe::Acp { acp_id }; + let transport = Self::create_pending_transport(&transport_recipe).await?; + Ok(Self { + state: Mutex::new(ClientState::Connecting { + transport: Some(transport), + }), + transport_recipe, + initialize_context: Mutex::new(None), + session_recovery_lock: Mutex::new(()), + }) + } + /// Perform the initialization handshake with the MCP server. /// https://modelcontextprotocol.io/specification/2025-06-18/basic/lifecycle#initialization pub async fn initialize( @@ -947,6 +1051,13 @@ impl RmcpClient { Ok(PendingTransport::StreamableHttp { transport }) } } + TransportRecipe::Acp { acp_id } => { + let bridge = get_acp_bridge()?; + let connection = bridge.connect(acp_id.clone()).await?; + Ok(PendingTransport::Acp { + transport: WorkerTransport::spawn(AcpTransportWorker { connection }), + }) + } } } @@ -981,6 +1092,11 @@ impl RmcpClient { Some(oauth_persistor), None, ), + PendingTransport::Acp { transport } => ( + service::serve_client(client_handler, transport).boxed(), + None, + None, + ), }; let service = match timeout { @@ -1163,3 +1279,145 @@ async fn create_oauth_transport_and_runtime( Ok((transport, runtime)) } + +#[cfg(test)] +mod tests { + use super::*; + use pretty_assertions::assert_eq; + use rmcp::model::ClientCapabilities; + use rmcp::model::ClientJsonRpcMessage; + use rmcp::model::ClientRequest; + use rmcp::model::Implementation; + use rmcp::model::InitializeRequestParams; + use rmcp::model::InitializeResult; + use rmcp::model::JsonRpcRequest; + use rmcp::model::JsonRpcResponse; + use rmcp::model::ListToolsResult; + use rmcp::model::ProtocolVersion; + use rmcp::model::ServerCapabilities; + use rmcp::model::ServerJsonRpcMessage; + use rmcp::model::ServerResult; + use serial_test::serial; + use tokio::sync::mpsc; + + struct FakeAcpBridge { + connection: Arc, + } + + impl crate::AcpBridge for FakeAcpBridge { + fn connect( + &self, + _acp_id: String, + ) -> BoxFuture<'static, Result>> { + let connection = Arc::clone(&self.connection); + Box::pin(async move { Ok(connection as Arc) }) + } + } + + struct FakeAcpConnection { + inbound_tx: mpsc::UnboundedSender, + inbound_rx: Arc>>, + } + + impl crate::AcpConnection for FakeAcpConnection { + fn send(&self, message: ClientJsonRpcMessage) -> BoxFuture<'static, Result<()>> { + let inbound_tx = self.inbound_tx.clone(); + Box::pin(async move { + if let ClientJsonRpcMessage::Request(JsonRpcRequest { id, request, .. }) = message { + match request { + ClientRequest::InitializeRequest(_) => inbound_tx + .send(ServerJsonRpcMessage::Response(JsonRpcResponse { + jsonrpc: rmcp::model::JsonRpcVersion2_0, + id, + result: ServerResult::InitializeResult(InitializeResult { + protocol_version: ProtocolVersion::default(), + capabilities: ServerCapabilities::builder() + .enable_tools() + .build(), + server_info: Implementation { + name: "fake-acp".to_string(), + version: "0.0.0".to_string(), + title: None, + description: None, + icons: None, + website_url: None, + }, + instructions: None, + }), + })) + .map_err(|_| anyhow!("failed to enqueue initialize response"))?, + ClientRequest::ListToolsRequest(_) => inbound_tx + .send(ServerJsonRpcMessage::Response(JsonRpcResponse { + jsonrpc: rmcp::model::JsonRpcVersion2_0, + id, + result: ServerResult::ListToolsResult(ListToolsResult { + tools: Vec::new(), + next_cursor: None, + meta: None, + }), + })) + .map_err(|_| anyhow!("failed to enqueue tools response"))?, + _ => {} + } + } + Ok(()) + }) + } + + fn recv(&self) -> BoxFuture<'static, Result>> { + let inbound_rx = Arc::clone(&self.inbound_rx); + Box::pin(async move { Ok(inbound_rx.lock().await.recv().await) }) + } + + fn close(&self) -> BoxFuture<'static, Result<()>> { + Box::pin(async { Ok(()) }) + } + } + + #[tokio::test] + #[serial] + async fn acp_transport_initializes_and_lists_tools() { + let (inbound_tx, inbound_rx) = mpsc::unbounded_channel(); + crate::set_acp_bridge(Some(Arc::new(FakeAcpBridge { + connection: Arc::new(FakeAcpConnection { + inbound_tx, + inbound_rx: Arc::new(tokio::sync::Mutex::new(inbound_rx)), + }), + }))); + + let client = RmcpClient::new_acp_client("srv-123".to_string()) + .await + .expect("ACP client should initialize"); + let send_elicitation: SendElicitation = + Box::new(|_, _| async { anyhow::bail!("elicitation should be unused") }.boxed()); + + let initialize_result = client + .initialize( + InitializeRequestParams { + meta: None, + protocol_version: ProtocolVersion::default(), + capabilities: ClientCapabilities::default(), + client_info: Implementation { + name: "test-client".to_string(), + version: "0.0.0".to_string(), + title: None, + description: None, + icons: None, + website_url: None, + }, + }, + None, + send_elicitation, + ) + .await + .expect("initialize should succeed"); + let tools = client + .list_tools(None, None) + .await + .expect("tools/list should succeed"); + + assert_eq!(initialize_result.server_info.name, "fake-acp"); + assert_eq!(tools.tools, Vec::new()); + crate::set_acp_bridge(None); + } +} diff --git a/codex-rs/tui/src/history_cell.rs b/codex-rs/tui/src/history_cell.rs index e6feef2cfd..0a7bf20d57 100644 --- a/codex-rs/tui/src/history_cell.rs +++ b/codex-rs/tui/src/history_cell.rs @@ -1767,6 +1767,9 @@ pub(crate) fn new_mcp_tools_output( lines.push(vec![" • Auth: ".into(), auth_status.to_string().into()].into()); match &cfg.transport { + McpServerTransportConfig::Acp { id, .. } => { + lines.push(vec![" • ACP Id: ".into(), id.clone().into()].into()); + } McpServerTransportConfig::Stdio { command, args, diff --git a/docs/plans/active/2026-03-10-native-acp-support.md b/docs/plans/active/2026-03-10-native-acp-support.md new file mode 100644 index 0000000000..11ecfa321d --- /dev/null +++ b/docs/plans/active/2026-03-10-native-acp-support.md @@ -0,0 +1,285 @@ +# Add Native ACP Support to Codex + +This ExecPlan is a living document. Keep the sections Progress, Surprises & Discoveries, Decision Log, and Outcomes & Retrospective up to date as work proceeds. + +No repo-specific `docs/PLANS.md` policy exists as of 2026-03-10, so this plan follows the shared ExecPlan template. + +## Purpose / Big Picture + +Add native Agent Client Protocol (ACP) support to Codex so ACP-aware editors and clients can drive Codex without a bespoke integration. The intended end state is a thin ACP adapter over the existing app-server v2/runtime stack, preserving current thread/turn/item semantics, approvals, and streaming behavior instead of creating a second direct integration into `codex-core`. + +Someone can see this working when an ACP client can: + +- `initialize` successfully and negotiate capabilities. +- create or load a session backed by a Codex thread. +- send `session/prompt` and receive streamed `session/update` notifications. +- handle permission/interactivity flows without losing parity with current app-server behavior. +- cancel or resume sessions without hanging or duplicating state. + +## Progress + +- [x] (2026-03-10 14:23Z) Completed initial discovery across ACP docs, app-server/app-server-protocol/mcp-server, and likely stakeholder surfaces. +- [x] (2026-03-10 20:31Z) Prototyped a native ACP adapter crate and CLI entrypoint as `codex acp-server`. +- [x] (2026-03-10 23:18Z) Added ACP session modes/config options, `session/set_mode`, stdio+HTTP `mcpServers` passthrough via request config overrides, text/image resource prompt support, and a distinct `SessionSource::Acp`. +- [x] (2026-03-10 23:18Z) Added local ACP transcript coverage for `initialize`, `session/new`, and `session/set_mode`. +- [ ] Flesh out the ACP-to-app-server v2 mapping table in the plan doc with the concrete implementation decisions now in code. +- [x] Add focused ACP integration tests that exercise stdio JSON-RPC flows against the in-process runtime. +- [x] Implement `session/set_mode` support instead of returning not implemented. +- [ ] Replace the current `mcpServers` stdio+HTTP passthrough with MCP-over-ACP session wiring for ACP-transport servers or make the unsupported capability boundary explicit in initialize. +- [x] Consider adding a distinct `SessionSource::Acp` once we are ready to pay the shared-protocol validation cost. +- [ ] Draft the ACP-to-app-server v2 mapping table and record protocol gaps, including `session/load`, `session/request_permission`, `session/set_mode`, and MCP-over-ACP. +- [ ] Decide whether to adopt the official ACP Rust SDK or a smaller transport-only adapter. +- [ ] Implement and validate stable-core ACP compliance. +- [ ] Implement and validate extended ACP support for session replay, modes, and MCP-over-ACP. +- [ ] Build interop coverage and documentation against official ACP SDKs/examples. + +## Surprises & Discoveries + +- Observation: `codex-app-server` already exposes nearly all of the interaction primitives ACP needs: lifecycle, streaming notifications, server-initiated approval requests, tool user-input requests, and MCP elicitation requests. Evidence: `codex-rs/app-server/README.md`, `codex-rs/app-server/src/bespoke_event_handling.rs`, `codex-rs/app-server-protocol/src/protocol/common.rs`. +- Observation: local embedders already reuse app-server semantics through the in-process runtime and `codex-app-server-client` instead of reaching into `core` directly. Evidence: `codex-rs/app-server/src/in_process.rs`, `codex-rs/app-server-client/src/lib.rs`. +- Observation: `codex-mcp-server` is prior art for an adapter layer, but it constructs its own `ThreadManager`, which is probably the wrong long-term pattern for a new native rich-client protocol. Evidence: `codex-rs/mcp-server/src/message_processor.rs`. +- Observation: ACP's stable core is JSON-RPC 2.0 with `initialize`, `session/new`, `session/prompt`, `session/cancel`, and `session/update`; `session/load` and `session/set_mode` are optional capabilities. Evidence: ACP docs in `initialization`, `session-setup`, and `session-modes` from `/agentclientprotocol/agent-client-protocol` via Context7. +- Observation: ACP includes client-advertised filesystem and terminal capabilities plus agent-driven `session/request_permission`, which overlap strongly with Codex approvals and `tool/requestUserInput`, but not one-to-one. Evidence: ACP docs in `initialization` and `tool-calls` from `/agentclientprotocol/agent-client-protocol` via Context7. +- Observation: ACP session loading is stronger than a simple resume. If Codex advertises `loadSession`, ACP expects replay via `session/update` before returning. Evidence: ACP `session-setup` docs from `/agentclientprotocol/agent-client-protocol` via Context7. +- Observation: I did not find an official ACP-wide conformance suite in the official docs I queried. The closest official validation assets are the Rust and TypeScript SDKs, their examples, and SDK test helpers. This is an inference from the available docs, not a guarantee that no such suite exists elsewhere. Evidence: ACP docs in `libraries/rust`, `libraries/typescript`, and `rust-sdk-v1` from `/agentclientprotocol/agent-client-protocol` via Context7. +- Observation: the current app-server API collapses `CoreSessionSource::Mcp` into API `SessionSource::AppServer`, so ACP likely needs its own session source if we want clean analytics/compliance attribution. Evidence: `codex-rs/app-server-protocol/src/protocol/v2.rs`. +- Observation: ACP richer elicitation and several session-management capabilities are still evolving via RFDs, so the implementation should separate stable compliance from draft/extended support. Evidence: ACP `elicitation`, `session-stop`, `session-info-update`, and `mcp-over-acp` RFDs from `/agentclientprotocol/agent-client-protocol` and subagent research. + +## Decision Log + +- Decision: plan around an ACP adapter layered on top of app-server v2 rather than a new direct `core` integration. Rationale: app-server already owns the stable rich-client contract, state management, approvals, and backpressure. Date/Author: 2026-03-10 / Codex. +- Decision: treat `codex-app-server-client` as the preferred internal seam for a native ACP implementation. Rationale: it preserves app-server semantics while avoiding a second process boundary and already supports typed requests plus server-request resolution. Date/Author: 2026-03-10 / Codex. +- Decision: engage app-server owners first, especially Owen Lin, with Michael Bolin and Celia Chen as key follow-ups for runtime-contract stability and interactivity. Rationale: git history and doc ownership point there more strongly than any formal `CODEOWNERS` file. Date/Author: 2026-03-10 / Codex. +- Decision: explicitly split delivery into stable-core ACP compliance and extended ACP support for evolving features. Rationale: this lets Codex make a credible compliance claim for the stable protocol while still planning for draft features like richer elicitation and broader session management. Date/Author: 2026-03-10 / Codex. + +## Outcomes & Retrospective + +The first implementation slice is now in place: + +- a new `codex-rs/acp-server` crate starts the in-process app-server runtime through `codex-app-server-client`. +- `codex acp-server` is wired as a new CLI entrypoint. +- the adapter handles ACP `initialize`, `session/new`, `session/load`, `session/prompt`, `session/cancel`, and `session/set_mode`. +- app-server notifications are translated into ACP `session/update` events for agent text, plans, command/file tool calls, and tool call completion updates. +- app-server approval requests for command execution and file changes are translated into ACP `session/request_permission`. +- ACP session setup now returns modes plus config options for mode/model/thought level derived from app-server collaboration mode and model APIs. +- ACP `mcpServers` declarations are now translated into Codex config overrides for stdio and streamable HTTP MCP servers. +- ACP text resources and image resources can now be converted into Codex input items, so the adapter advertises embedded-context and image prompt support. +- ACP sessions are now recorded with a distinct `SessionSource::Acp`, and app-server schema fixtures were regenerated accordingly. +- local transcript coverage now exercises `initialize`, `session/new`, and `session/set_mode` against the real stdio server binary. + +Current known gaps after the first slice: + +- ACP transport MCP servers from the MCP-over-ACP RFD are still rejected; only stdio and HTTP declarations are currently translated. +- richer elicitation remains unsupported because ACP `session/request_permission` cannot carry MCP form/URL elicitation content; unsupported server requests are still rejected back to app-server. +- compliance is still demonstrated only with local crate/unit/protocol/CLI tests, not official ACP SDK counterpart interop. + +The main remaining unknowns are whether the official ACP Rust SDK fits cleanly into Codex's runtime architecture, how far to go on MCP-over-ACP in the first user-facing milestone, and whether a distinct ACP session source should be introduced in the shared protocol soon or deferred until the adapter semantics settle. + +## Context and Orientation + +The most relevant local layers are: + +- `codex-rs/app-server-protocol/src/protocol/common.rs` + Defines the JSON-RPC request, server request, and notification surface for app-server v2, including approval, tool-input, and elicitation requests. +- `codex-rs/app-server-protocol/src/protocol/v2.rs` + Defines the typed v2 payloads and session/thread metadata exposed over app-server. +- `codex-rs/app-server/src/message_processor.rs` + Owns initialization, capability gating, and dispatch for app-server requests. +- `codex-rs/app-server/src/bespoke_event_handling.rs` + Translates core runtime events into app-server notifications and server requests. This is where user-input, approval, and MCP elicitation flows are already bridged. +- `codex-rs/app-server/src/in_process.rs` + Hosts the app-server runtime in-process with bounded queues and server-request reply plumbing. +- `codex-rs/app-server-client/src/lib.rs` + Provides the reusable in-process client facade that TUI and exec already use. +- `codex-rs/mcp-server/src/message_processor.rs` + Shows how a protocol adapter can sit above the shared runtime, but also shows the maintenance cost of duplicating lifecycle handling. +- `codex-rs/app-server/tests/suite/v2/` + Provides the best existing model for request/notification regression coverage. +- `codex-rs/app-server-test-client/src/lib.rs` + Provides a practical harness for app-server transport tests and scripted interaction flows. +- `codex-rs/cli/src/main.rs` + Defines top-level CLI entrypoints; ACP support will likely need a new subcommand or server mode here. + +Relevant ACP concepts: + +- `initialize` negotiates protocol version plus client and agent capabilities. +- `session/new` and optional `session/load` establish or resume a conversation. +- `session/prompt` and `session/cancel` drive one user turn and interrupt it. +- `session/update` streams agent message chunks, plan updates, tool activity, diffs, and mode changes. +- `session/request_permission` asks the client to surface approval options and return a user choice. +- `session/set_mode` is optional and adjacent to Codex collaboration modes. +- MCP-over-ACP allows clients to declare ACP-managed MCP servers and expects the agent to connect to them directly. +- draft session-management and elicitation extensions should remain behind explicit seams until the protocol settles. + +## Plan of Work + +Requirements driving scope: + +- Reuse the existing app-server/runtime contract instead of duplicating stateful logic in a parallel ACP-specific core integration. +- Preserve interaction parity for approvals, request-user-input, cancellation, and streaming updates. +- Keep analytics/compliance attribution explicit so ACP traffic is distinguishable from MCP/app-server traffic. +- Ship with an interop harness because the official ACP docs do not currently point to a dedicated conformance suite. +- Support the stable ACP core well enough to make a concrete compliance claim, then layer in extended support for `session/load`, `session/set_mode`, and MCP-over-ACP. + +Sequence of work: + +First, produce a protocol mapping document that aligns ACP requests and notifications with app-server v2 methods, notifications, and server requests. This must explicitly cover `initialize`, `session/new`, `session/load`, `session/prompt`, `session/cancel`, `session/update`, `session/request_permission`, `session/set_mode`, and MCP-over-ACP, and it must call out mismatches such as ACP client capabilities (`fs`, `terminal`) and ACP-managed MCP servers from `session/new`. + +Next, decide whether to build on the official ACP Rust SDK or implement only the ACP wire protocol/transport glue manually. The default should be to use the official SDK if it cleanly supports Codex's bounded async runtime, server-initiated interactions, and a stable test harness. If the SDK makes the embedding awkward, keep a very thin ACP adapter crate with minimal protocol code and put all business logic behind `codex-app-server-client`. + +Then, create a new crate, tentatively `codex-rs/acp-server`, and expose it through the CLI, likely as `codex acp-server`. This crate should start the in-process app-server runtime through `codex-app-server-client`, stamp a distinct `SessionSource::Acp` if approved, and translate ACP messages into typed app-server calls and events. The adapter should own only translation, capability negotiation, and session bookkeeping required by ACP; it should not own core conversation logic. + +After the transport skeleton works, implement the stable ACP core: + +- `initialize` mapped to ACP protocol negotiation plus a derived Codex capability view. +- `session/new` mapped to `thread/start`. +- `session/prompt` mapped to `turn/start`. +- `session/cancel` mapped to `turn/interrupt`. +- `session/update` synthesized from app-server `ServerNotification` events and, where needed, `ServerRequestResolved`. +- `session/request_permission` mapped from app-server approval and elicitation flows with ACP-native option/outcome semantics. + +Then implement the extended ACP slice needed for a stronger compliance story: + +- `session/load` mapped to persisted Codex sessions with full ACP-style replay through `session/update` before the response completes. +- `session/set_mode` mapped to collaboration modes or an ACP-specific mode layer only if the mapping remains explicit and user-visible. +- MCP-over-ACP support for ACP-declared MCP servers passed in `session/new`, reusing existing Codex MCP connection machinery where possible. +- Draft-rich interactivity support behind explicit feature gates so ACP elicitation can evolve without destabilizing the stable core. + +Finally, add test coverage and docs. Mirror the style of `codex-rs/app-server/tests/suite/v2/`, add ACP interop tests that run against a real adapter instance, and update user-facing docs under `codex-rs/docs/` plus CLI help text in `codex-rs/cli/src/main.rs`. If shared app-server v2 payloads change, update the app-server README and regenerate schema fixtures. + +## Concrete Steps + +Discovery and design: + +1. From repo root, inspect the current rich-client boundary: + `rg -n "initialize|ServerRequest|ServerNotification|requestUserInput|ElicitationRequest|RequestPermissions" codex-rs/app-server codex-rs/app-server-protocol codex-rs/app-server-client` +2. Review the lifecycle docs: + `sed -n '1,260p' codex-rs/app-server/README.md` +3. Review the protocol surfaces: + `sed -n '430,770p' codex-rs/app-server-protocol/src/protocol/common.rs` + `rg -n "SessionSource" codex-rs/app-server-protocol/src/protocol/v2.rs` +4. Review ACP docs through Context7 before implementation begins: + resolve `/agentclientprotocol/agent-client-protocol` + query for `initialization`, `session-setup`, `prompt-turn`, `session-modes`, and `request_permission` +5. Produce an explicit compliance matrix with rows for stable-core ACP, optional ACP features, and draft/RFD features. + +Implementation: + +1. Create the adapter crate: + `cargo new -w codex-rs/acp-server --bin` +2. Add workspace wiring in `codex-rs/Cargo.toml` and CLI wiring in `codex-rs/cli/src/main.rs`. +3. Implement ACP connection/session translation on top of `codex-app-server-client`. +4. Add focused tests for the new crate: + `cargo test -p codex-acp-server` +5. If app-server protocol or docs change, regenerate or refresh the relevant artifacts: + `just write-app-server-schema` +6. Run ACP SDK/example interop checks for at least one official ACP client or harness implementation. + +Expected implementation proof points: + +- ACP `initialize` returns negotiated capabilities and agent metadata. +- ACP `session/new` yields a persistent Codex-backed session id. +- ACP `session/prompt` streams incremental `session/update` events and completes cleanly. +- ACP permission prompts round-trip with ACP-native option and outcome shapes and without orphaned pending requests. +- ACP `session/load` replays prior conversation history as `session/update` events before returning when `loadSession` is advertised. +- ACP mode changes behave deterministically and visibly when `session/set_mode` is advertised. +- ACP-declared MCP servers can be connected and used through the ACP session lifecycle when MCP-over-ACP is enabled. + +## Validation and Acceptance + +Acceptance criteria: + +- An ACP client can complete `initialize`, `session/new`, and `session/prompt` against Codex without using MCP as a wrapper transport. +- Streaming updates include enough fidelity to render agent text, plans, tool calls, tool-call updates, and diffs in an ACP client. +- At least one sensitive operation path exercises ACP permission prompting and maps cleanly to existing Codex approval semantics. +- Cancellation ends the active prompt turn and results in a stable terminal state instead of a stuck pending turn. +- A previously created session can be loaded and its prior history replayed in ACP shape when `loadSession` is advertised. +- If `session/set_mode` is advertised, the mode list and mode transitions conform to ACP expectations and remain aligned with Codex policy behavior. +- If MCP-over-ACP is advertised, ACP-provided MCP server declarations connect successfully and do not require a parallel runtime path. +- The implementation ships with a written compliance matrix that marks which stable, optional, and draft ACP features are supported. + +Proof artifacts to capture: + +- A saved ACP transcript showing `initialize`, `session/new`, `session/prompt`, and streamed `session/update`. +- A saved ACP transcript covering one permission prompt round-trip. +- A saved ACP transcript for `session/load` showing replay before completion. +- A saved ACP transcript for `session/set_mode`, if supported. +- A saved ACP transcript for one MCP-over-ACP session, if supported. +- Test output from `cargo test -p codex-acp-server`. +- Interop logs or transcripts from at least one official ACP SDK/example counterpart. +- If shared app-server types change, a diff to the regenerated schema fixtures and README docs. + +Suggested test strategy: + +- Unit tests for ACP-to-app-server mapping functions. +- Integration tests that run the ACP adapter against the in-process app-server runtime. +- Replay-focused tests for `session/load` so ordering and completion semantics are pinned down. +- Permission-shape tests to verify ACP option IDs, kinds, and selected/cancelled outcomes. +- Mode tests to verify `availableModes`, `currentModeId`, and `session/set_mode` behavior if advertised. +- MCP-over-ACP tests that verify agent-side connection setup from ACP session declarations. +- Interop smoke tests using the official ACP Rust or TypeScript examples/SDKs as counterpart clients where practical. + +## Idempotence and Recovery + +The implementation should be additive: + +- the new ACP adapter must live behind a dedicated crate and CLI entrypoint. +- no existing `app-server`, `mcp-server`, TUI, or exec flows should change behavior unless they share a deliberate supporting abstraction. +- if the ACP prototype proves unstable, disable the CLI entrypoint and keep the internal mapping code out of existing startup paths. + +Recovery path: + +- revert the ACP crate and CLI entrypoint if the adapter destabilizes startup or transport logic. +- if a shared app-server abstraction becomes too ACP-specific, move that logic back to the adapter boundary and restore the previous app-server surface. + +## Artifacts and Notes + +Local references: + +- `codex-rs/app-server/README.md` +- `codex-rs/app-server-protocol/src/protocol/common.rs` +- `codex-rs/app-server-protocol/src/protocol/v2.rs` +- `codex-rs/app-server/src/bespoke_event_handling.rs` +- `codex-rs/app-server/src/in_process.rs` +- `codex-rs/app-server-client/src/lib.rs` +- `codex-rs/mcp-server/src/message_processor.rs` +- `codex-rs/core/src/connectors.rs` +- `codex-rs/app-server/tests/suite/v2/` +- `codex-rs/app-server-test-client/src/lib.rs` + +External ACP references consulted through Context7: + +- `/agentclientprotocol/agent-client-protocol` `docs/protocol/initialization.mdx` +- `/agentclientprotocol/agent-client-protocol` `docs/protocol/session-setup.mdx` +- `/agentclientprotocol/agent-client-protocol` `docs/protocol/prompt-turn.mdx` +- `/agentclientprotocol/agent-client-protocol` `docs/protocol/session-modes.mdx` +- `/agentclientprotocol/agent-client-protocol` `docs/protocol/tool-calls.mdx` +- `/agentclientprotocol/agent-client-protocol` `docs/rfds/mcp-over-acp.mdx` +- `/agentclientprotocol/agent-client-protocol` `docs/rfds/elicitation.mdx` +- `/agentclientprotocol/agent-client-protocol` `docs/rfds/session-stop.mdx` +- `/agentclientprotocol/agent-client-protocol` `docs/rfds/session-info-update.mdx` +- `/agentclientprotocol/agent-client-protocol` `docs/libraries/rust.mdx` +- `/agentclientprotocol/agent-client-protocol` `docs/libraries/typescript.mdx` +- `/agentclientprotocol/agent-client-protocol` `docs/rfds/rust-sdk-v1.mdx` + +Stakeholder starting point: + +- Primary discussion: Owen Lin +- Secondary discussion: Michael Bolin, Celia Chen +- Focus area for initial review: app-server v2 lifecycle, approval semantics, and analytics/compliance identity for ACP sessions + +## Interfaces and Dependencies + +Expected local modules and crates: + +- `codex-app-server-client` as the primary internal runtime seam. +- `codex-app-server` and `codex-app-server-protocol` for any shared lifecycle or schema extensions. +- `codex-cli` for surfacing a user-facing ACP server command. +- `codex-protocol::protocol::SessionSource` if ACP needs a distinct session identity. +- `codex-core` MCP connector plumbing if MCP-over-ACP needs to reuse the existing connector stack. +- `codex-app-server/tests` and `codex-app-server-test-client` for reusable harness patterns. + +Expected external dependencies: + +- ACP official Rust SDK if it fits Codex's embedding model. +- Otherwise, no large ACP-specific runtime dependency beyond JSON-RPC/transport helpers already compatible with the workspace.