From 49bc385d612324e86a02cf3b4fe0925351ce369f Mon Sep 17 00:00:00 2001 From: Hakula Chen Date: Tue, 1 Dec 2026 18:18:32 +0800 Subject: [PATCH] feat(acp): add ox-acp frontend crate and ox acp subcommand --- Cargo.lock | 15 + Cargo.toml | 3 +- crates/ox-acp/Cargo.toml | 23 + crates/ox-acp/src/lib.rs | 1059 ++++++++++++++++++++++++++++++++++++++ crates/ox/Cargo.toml | 1 + crates/ox/src/lib.rs | 67 +++ crates/ox/tests/cli.rs | 70 ++- docs/README.md | 1 + docs/reference/acp.md | 41 ++ 9 files changed, 1278 insertions(+), 2 deletions(-) create mode 100644 crates/ox-acp/Cargo.toml create mode 100644 crates/ox-acp/src/lib.rs create mode 100644 docs/reference/acp.md diff --git a/Cargo.lock b/Cargo.lock index c6e7b3967..1cb64671f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1486,6 +1486,7 @@ dependencies = [ "clap", "futures-util", "indoc", + "ox-acp", "ox-core", "ox-tui", "serde_json", @@ -1494,6 +1495,20 @@ dependencies = [ "wiremock", ] +[[package]] +name = "ox-acp" +version = "0.2.0-alpha.1" +dependencies = [ + "anyhow", + "async-trait", + "futures-util", + "ox-core", + "serde", + "serde_json", + "tempfile", + "tokio", +] + [[package]] name = "ox-core" version = "0.2.0-alpha.1" diff --git a/Cargo.toml b/Cargo.toml index 15912e6b2..f87938aea 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,5 @@ [workspace] -members = ["crates/ox-core", "crates/ox-tui", "crates/ox", "plugins/ox-plugin-mcp"] +members = ["crates/ox-core", "crates/ox-acp", "crates/ox-tui", "crates/ox", "plugins/ox-plugin-mcp"] resolver = "3" [workspace.package] @@ -37,6 +37,7 @@ clap = { version = "4", features = ["derive", "env"] } crossterm = { version = "0.29", features = ["event-stream"] } futures-util = "0.3" indoc = "2" +ox-acp = { path = "crates/ox-acp" } ox-core = { path = "crates/ox-core" } ox-tui = { path = "crates/ox-tui" } ratatui = "0.30" diff --git a/crates/ox-acp/Cargo.toml b/crates/ox-acp/Cargo.toml new file mode 100644 index 000000000..9db67240c --- /dev/null +++ b/crates/ox-acp/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "ox-acp" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +authors.workspace = true +license.workspace = true +publish.workspace = true + +[lints] +workspace = true + +[dependencies] +anyhow.workspace = true +futures-util.workspace = true +ox-core.workspace = true +serde.workspace = true +serde_json.workspace = true +tokio = { workspace = true, features = ["io-std", "io-util"] } + +[dev-dependencies] +async-trait.workspace = true +tempfile.workspace = true diff --git a/crates/ox-acp/src/lib.rs b/crates/ox-acp/src/lib.rs new file mode 100644 index 000000000..4bb39d82e --- /dev/null +++ b/crates/ox-acp/src/lib.rs @@ -0,0 +1,1059 @@ +//! Agent Client Protocol (ACP) stdio frontend for `oxide-code`. +//! +//! Speaks newline-delimited JSON-RPC 2.0 over stdio and bridges ACP sessions onto +//! [`ox_core::agent::Agent`]. + +use std::collections::HashMap; +use std::path::PathBuf; + +use anyhow::Result; +use futures_util::StreamExt as _; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use tokio::io::{ + AsyncBufReadExt as _, AsyncRead, AsyncWrite, AsyncWriteExt as _, BufReader, Lines, +}; + +use ox_core::agent::{Agent, AgentEvent, AgentStopReason}; +use ox_core::client::StopReason; +use ox_core::message::Message; + +const JSONRPC_VERSION: &str = "2.0"; +const ACP_PROTOCOL_VERSION: u32 = 1; + +const ERR_PARSE: i64 = -32700; +const ERR_INVALID_REQUEST: i64 = -32600; +const ERR_METHOD_NOT_FOUND: i64 = -32601; +const ERR_INVALID_PARAMS: i64 = -32602; +const ERR_INTERNAL: i64 = -32603; + +/// Runs the ACP JSON-RPC 2.0 server on process stdin and stdout. +/// +/// The `factory` closure builds an [`Agent`] for each prompt turn, receiving the +/// session's optional working directory override. +pub async fn run_stdio(factory: F) -> Result<()> +where + F: FnMut(Option) -> Result, +{ + serve_stdio(tokio::io::stdin(), tokio::io::stdout(), factory).await +} + +/// Runs the ACP JSON-RPC 2.0 server over arbitrary async streams. +/// +/// Reads newline-delimited JSON-RPC 2.0 requests from `reader` and writes +/// responses and `session/update` notifications to `writer` until `shutdown` is +/// received or `reader` reaches EOF. +pub async fn serve_stdio(reader: R, writer: W, factory: F) -> Result<()> +where + R: AsyncRead + Unpin, + W: AsyncWrite + Unpin, + F: FnMut(Option) -> Result, +{ + let mut server = Server { + lines: BufReader::new(reader).lines(), + writer, + factory, + sessions: HashMap::new(), + next_session_id: 1, + }; + server.run().await +} + +struct SessionState { + cwd: Option, + messages: Vec, +} + +struct Server { + lines: Lines>, + writer: W, + factory: F, + sessions: HashMap, + next_session_id: u64, +} + +impl Server +where + R: AsyncRead + Unpin, + W: AsyncWrite + Unpin, + F: FnMut(Option) -> Result, +{ + async fn run(&mut self) -> Result<()> { + while let Some(line) = self.lines.next_line().await? { + if line.trim().is_empty() { + continue; + } + + if self.handle_line(&line).await? { + break; + } + } + Ok(()) + } + + async fn handle_line(&mut self, line: &str) -> Result { + let req: RpcRequest = match serde_json::from_str(line) { + Ok(req) => req, + + Err(err) => { + self.write_error(None, ERR_PARSE, format!("parse error: {err}")) + .await?; + return Ok(false); + } + }; + + if req.jsonrpc != JSONRPC_VERSION { + self.write_error( + req.id, + ERR_INVALID_REQUEST, + format!("unsupported jsonrpc version `{}`", req.jsonrpc), + ) + .await?; + return Ok(false); + } + + match req.method.as_str() { + "initialize" => { + self.handle_initialize(req.id).await?; + Ok(false) + } + + "session/new" => { + self.handle_session_new(req.id, req.params).await?; + Ok(false) + } + + "session/prompt" => { + self.handle_session_prompt(req.id, req.params).await?; + Ok(false) + } + + "session/cancel" => { + self.handle_session_cancel(req.id, req.params).await?; + Ok(false) + } + + "shutdown" => { + if let Some(id) = req.id { + self.write_result(id, json!({})).await?; + } + Ok(true) + } + + other => { + if req.id.is_some() { + self.write_error( + req.id, + ERR_METHOD_NOT_FOUND, + format!("method not found: {other}"), + ) + .await?; + } + Ok(false) + } + } + } + + async fn handle_initialize(&mut self, id: Option) -> Result<()> { + if let Some(id) = id { + let result = json!({ + "protocolVersion": ACP_PROTOCOL_VERSION, + "serverInfo": { + "name": "ox", + "version": env!("CARGO_PKG_VERSION"), + }, + "capabilities": { + "promptCapabilities": { + "embeddedContext": false, + "image": false, + "audio": false, + }, + }, + }); + self.write_result(id, result).await?; + } + Ok(()) + } + + async fn handle_session_new(&mut self, id: Option, params: Option) -> Result<()> { + let parsed: SessionNewParams = match params { + Some(value) => match serde_json::from_value(value) { + Ok(parsed) => parsed, + + Err(err) => { + self.write_error(id, ERR_INVALID_PARAMS, format!("invalid params: {err}")) + .await?; + return Ok(()); + } + }, + + None => SessionNewParams::default(), + }; + + let session_id = format!("session-{}", self.next_session_id); + self.next_session_id += 1; + self.sessions.insert( + session_id.clone(), + SessionState { + cwd: parsed.cwd, + messages: Vec::new(), + }, + ); + + if let Some(id) = id { + self.write_result(id, json!({ "sessionId": session_id })) + .await?; + } + Ok(()) + } + + async fn handle_session_prompt( + &mut self, + id: Option, + params: Option, + ) -> Result<()> { + let Some(parsed) = self + .parse_params::(id.as_ref(), params) + .await? + else { + return Ok(()); + }; + + let Some(session) = self.sessions.get(&parsed.session_id) else { + self.write_error( + id, + ERR_INVALID_PARAMS, + format!("unknown session `{}`", parsed.session_id), + ) + .await?; + return Ok(()); + }; + + let mut messages = session.messages.clone(); + messages.push(Message::user(parsed.prompt.into_text())); + let cwd = session.cwd.clone(); + + let agent = match (self.factory)(cwd) { + Ok(agent) => agent, + + Err(err) => { + self.write_error(id, ERR_INTERNAL, format!("failed to create agent: {err}")) + .await?; + return Ok(()); + } + }; + + let mut stream = agent.run(messages); + let mut stop_reason = "end_turn"; + let mut final_messages = None; + + loop { + tokio::select! { + event = stream.next() => { + let Some(event) = event else { + break; + }; + + match self.handle_agent_event(&parsed.session_id, event).await? { + EventOutcome::Continue => {} + + EventOutcome::Done { reason, messages } => { + stop_reason = reason; + final_messages = Some(messages); + break; + } + + EventOutcome::Error(err) => { + self.write_error(id, ERR_INTERNAL, err).await?; + return Ok(()); + } + } + } + + line = self.lines.next_line() => { + let Some(line) = line? else { + stop_reason = "cancelled"; + break; + }; + + if let Ok(req) = serde_json::from_str::(&line) + && req.method == "session/cancel" + && is_cancel_for(req.params.as_ref(), &parsed.session_id) + { + if let Some(cancel_id) = req.id { + self.write_result(cancel_id, json!({})).await?; + } + stop_reason = "cancelled"; + break; + } + } + } + } + + if let Some(updated) = final_messages + && let Some(session) = self.sessions.get_mut(&parsed.session_id) + { + session.messages = updated; + } + + if let Some(id) = id { + self.write_result(id, json!({ "stopReason": stop_reason })) + .await?; + } + Ok(()) + } + + async fn handle_session_cancel( + &mut self, + id: Option, + params: Option, + ) -> Result<()> { + let Some(parsed) = self + .parse_params::(id.as_ref(), params) + .await? + else { + return Ok(()); + }; + + if !self.sessions.contains_key(&parsed.session_id) { + self.write_error( + id, + ERR_INVALID_PARAMS, + format!("unknown session `{}`", parsed.session_id), + ) + .await?; + return Ok(()); + } + + if let Some(id) = id { + self.write_result(id, json!({})).await?; + } + Ok(()) + } + + async fn handle_agent_event( + &mut self, + session_id: &str, + event: AgentEvent, + ) -> Result { + match event { + AgentEvent::TextDelta(text) => { + if !text.is_empty() { + self.write_session_update( + session_id, + json!({ + "sessionUpdate": "agent_message_chunk", + "content": { "type": "text", "text": text }, + }), + ) + .await?; + } + Ok(EventOutcome::Continue) + } + + AgentEvent::ThinkingDelta(text) => { + if !text.is_empty() { + self.write_session_update( + session_id, + json!({ + "sessionUpdate": "agent_thought_chunk", + "content": { "type": "text", "text": text }, + }), + ) + .await?; + } + Ok(EventOutcome::Continue) + } + + AgentEvent::ToolCallStart { + id: call_id, + name, + arguments, + } => { + self.write_session_update( + session_id, + json!({ + "sessionUpdate": "tool_call", + "toolCallId": call_id, + "title": name, + "status": "in_progress", + "rawInput": arguments, + }), + ) + .await?; + Ok(EventOutcome::Continue) + } + + AgentEvent::ToolResult { + call_id, + name, + content, + is_error, + } => { + let status = if is_error { "failed" } else { "completed" }; + self.write_session_update( + session_id, + json!({ + "sessionUpdate": "tool_call_update", + "toolCallId": call_id, + "title": name, + "status": status, + "rawOutput": content, + }), + ) + .await?; + Ok(EventOutcome::Continue) + } + + AgentEvent::Done { + reason, messages, .. + } => Ok(EventOutcome::Done { + reason: map_stop_reason(&reason), + messages, + }), + + AgentEvent::Error(err) => Ok(EventOutcome::Error(err)), + + AgentEvent::TurnUsage(_) => Ok(EventOutcome::Continue), + } + } + + async fn parse_params Deserialize<'de>>( + &mut self, + id: Option<&Value>, + params: Option, + ) -> Result> { + let Some(value) = params else { + self.write_error(id.cloned(), ERR_INVALID_PARAMS, "missing params".to_owned()) + .await?; + return Ok(None); + }; + + match serde_json::from_value(value) { + Ok(parsed) => Ok(Some(parsed)), + + Err(err) => { + self.write_error( + id.cloned(), + ERR_INVALID_PARAMS, + format!("invalid params: {err}"), + ) + .await?; + Ok(None) + } + } + } + + async fn write_session_update(&mut self, session_id: &str, update: Value) -> Result<()> { + let notification = json!({ + "jsonrpc": JSONRPC_VERSION, + "method": "session/update", + "params": { + "sessionId": session_id, + "update": update, + }, + }); + self.write_json(¬ification).await + } + + async fn write_result(&mut self, id: Value, result: Value) -> Result<()> { + let response = RpcResponse { + jsonrpc: JSONRPC_VERSION, + id, + result: Some(result), + error: None, + }; + self.write_json(&response).await + } + + async fn write_error(&mut self, id: Option, code: i64, message: String) -> Result<()> { + let response = RpcResponse { + jsonrpc: JSONRPC_VERSION, + id: id.unwrap_or(Value::Null), + result: None, + error: Some(RpcError { code, message }), + }; + self.write_json(&response).await + } + + async fn write_json(&mut self, payload: &T) -> Result<()> { + let encoded = serde_json::to_string(payload)?; + self.writer.write_all(encoded.as_bytes()).await?; + self.writer.write_all(b"\n").await?; + self.writer.flush().await?; + Ok(()) + } +} + +enum EventOutcome { + Continue, + Done { + reason: &'static str, + messages: Vec, + }, + Error(String), +} + +fn map_stop_reason(reason: &AgentStopReason) -> &'static str { + match reason { + AgentStopReason::Completed(StopReason::MaxTokens) => "max_tokens", + AgentStopReason::Completed(_) => "end_turn", + AgentStopReason::MaxTurnsReached => "max_turn_requests", + } +} + +fn is_cancel_for(params: Option<&Value>, session_id: &str) -> bool { + params + .and_then(|value| serde_json::from_value::(value.clone()).ok()) + .is_some_and(|cancel| cancel.session_id == session_id) +} + +#[derive(Debug, Deserialize)] +struct RpcRequest { + jsonrpc: String, + #[serde(default)] + id: Option, + method: String, + #[serde(default)] + params: Option, +} + +#[derive(Debug, Serialize)] +struct RpcResponse { + jsonrpc: &'static str, + id: Value, + #[serde(skip_serializing_if = "Option::is_none")] + result: Option, + #[serde(skip_serializing_if = "Option::is_none")] + error: Option, +} + +#[derive(Debug, Serialize)] +struct RpcError { + code: i64, + message: String, +} + +#[derive(Debug, Default, Deserialize)] +#[serde(rename_all = "camelCase")] +struct SessionNewParams { + #[serde(default)] + cwd: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +struct SessionPromptParams { + session_id: String, + prompt: PromptInput, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +struct SessionCancelParams { + session_id: String, +} + +#[derive(Debug, Deserialize)] +#[serde(untagged)] +enum PromptInput { + Text(String), + Blocks(Vec), +} + +impl PromptInput { + fn into_text(self) -> String { + match self { + Self::Text(text) => text, + + Self::Blocks(blocks) => blocks + .into_iter() + .filter_map(|block| (block.kind == "text").then_some(block.text)) + .flatten() + .collect::>() + .join("\n"), + } + } +} + +#[derive(Debug, Deserialize)] +struct PromptBlock { + #[serde(rename = "type")] + kind: String, + #[serde(default)] + text: Option, +} + +#[cfg(test)] +mod tests { + use std::collections::VecDeque; + use std::path::PathBuf; + use std::sync::{Arc, Mutex}; + + use anyhow::{Result, anyhow}; + use async_trait::async_trait; + use futures_util::stream; + use serde_json::{Value, json}; + use tempfile::TempDir; + use tokio::io::{BufReader, duplex}; + + use ox_core::agent::{Agent, AgentConfig}; + use ox_core::client::{ClientError, EventStream, Request, ResponseEvent, StopReason, Wire}; + use ox_core::tools::{ToolContext, ToolRegistry}; + + use super::*; + + type TurnOutcome = std::result::Result, ClientError>; + + struct ScriptedWire { + turns: Mutex>, + } + + impl ScriptedWire { + fn new(turns: Vec) -> Arc { + Arc::new(Self { + turns: Mutex::new(turns.into()), + }) + } + } + + #[async_trait] + impl Wire for ScriptedWire { + async fn stream(&self, _req: Request) -> std::result::Result { + let outcome = self + .turns + .lock() + .expect("lock poisoned") + .pop_front() + .expect("unexpected extra turn"); + let events = outcome?; + Ok(Box::pin(stream::iter(events.into_iter().map(Ok)))) + } + } + + struct BlockingWire; + + #[async_trait] + impl Wire for BlockingWire { + async fn stream(&self, _req: Request) -> std::result::Result { + let pending = stream::pending(); + Ok(Box::pin(pending)) + } + } + + fn make_agent(wire: Arc, cwd: PathBuf) -> Agent { + Agent::new( + wire, + Arc::new(ToolRegistry::with_defaults()), + ToolContext::new(cwd), + AgentConfig::new("gemini-4-neon"), + ) + } + + async fn read_json_line( + lines: &mut tokio::io::Lines>, + ) -> Result { + let line = lines + .next_line() + .await? + .ok_or_else(|| anyhow!("unexpected EOF from server"))?; + Ok(serde_json::from_str(&line)?) + } + + async fn send_json_line(writer: &mut tokio::io::DuplexStream, value: &Value) -> Result<()> { + let encoded = serde_json::to_string(value)?; + writer.write_all(encoded.as_bytes()).await?; + writer.write_all(b"\n").await?; + writer.flush().await?; + Ok(()) + } + + #[tokio::test] + async fn initialize_session_prompt_and_shutdown_over_duplex() -> Result<()> { + let dir = TempDir::new()?; + let default_cwd = dir.path().to_path_buf(); + let wire = ScriptedWire::new(vec![Ok(vec![ + ResponseEvent::ReasoningDelta { + text: "plan".to_owned(), + signature: None, + }, + ResponseEvent::TextDelta("hello ".to_owned()), + ResponseEvent::TextDelta("world".to_owned()), + ResponseEvent::Done(StopReason::EndTurn), + ])]); + + let (mut client_tx, server_rx) = duplex(8192); + let (server_tx, client_rx) = duplex(8192); + + let server_task = tokio::spawn(async move { + serve_stdio(server_rx, server_tx, move |cwd| { + Ok(make_agent( + Arc::clone(&wire) as Arc, + cwd.unwrap_or_else(|| default_cwd.clone()), + )) + }) + .await + }); + + let mut lines = BufReader::new(client_rx).lines(); + + send_json_line( + &mut client_tx, + &json!({ "jsonrpc": "2.0", "id": 1, "method": "initialize" }), + ) + .await?; + let init = read_json_line(&mut lines).await?; + assert_eq!(init["id"], 1); + assert_eq!(init["result"]["protocolVersion"], 1); + assert_eq!(init["result"]["serverInfo"]["name"], "ox"); + + send_json_line( + &mut client_tx, + &json!({ "jsonrpc": "2.0", "id": 2, "method": "session/new", "params": {} }), + ) + .await?; + let created = read_json_line(&mut lines).await?; + assert_eq!(created["result"]["sessionId"], "session-1"); + + send_json_line( + &mut client_tx, + &json!({ + "jsonrpc": "2.0", + "id": 3, + "method": "session/prompt", + "params": { + "sessionId": "session-1", + "prompt": [{ "type": "text", "text": "say hi" }], + }, + }), + ) + .await?; + + let thought = read_json_line(&mut lines).await?; + assert_eq!(thought["method"], "session/update"); + assert_eq!( + thought["params"]["update"]["sessionUpdate"], + "agent_thought_chunk" + ); + assert_eq!(thought["params"]["update"]["content"]["text"], "plan"); + + let chunk1 = read_json_line(&mut lines).await?; + assert_eq!( + chunk1["params"]["update"]["sessionUpdate"], + "agent_message_chunk" + ); + assert_eq!(chunk1["params"]["update"]["content"]["text"], "hello "); + + let chunk2 = read_json_line(&mut lines).await?; + assert_eq!(chunk2["params"]["update"]["content"]["text"], "world"); + + let prompt_resp = read_json_line(&mut lines).await?; + assert_eq!(prompt_resp["id"], 3); + assert_eq!(prompt_resp["result"]["stopReason"], "end_turn"); + + send_json_line( + &mut client_tx, + &json!({ "jsonrpc": "2.0", "id": 4, "method": "shutdown" }), + ) + .await?; + let shutdown = read_json_line(&mut lines).await?; + assert_eq!(shutdown["id"], 4); + assert_eq!(shutdown["result"], json!({})); + + server_task.await??; + Ok(()) + } + + #[tokio::test] + async fn streams_tool_call_and_tool_result_updates() -> Result<()> { + let dir = TempDir::new()?; + let file = dir.path().join("note.txt"); + std::fs::write(&file, "hello from disk\n")?; + let default_cwd = dir.path().to_path_buf(); + + let wire = ScriptedWire::new(vec![ + Ok(vec![ + ResponseEvent::ToolCall { + id: "call_1".to_owned(), + name: "read".to_owned(), + arguments: json!({ "path": "note.txt" }), + thought_signature: None, + }, + ResponseEvent::Done(StopReason::ToolUse), + ]), + Ok(vec![ + ResponseEvent::TextDelta("read it".to_owned()), + ResponseEvent::Done(StopReason::MaxTokens), + ]), + ]); + + let (mut client_tx, server_rx) = duplex(8192); + let (server_tx, client_rx) = duplex(8192); + + let server_task = tokio::spawn(async move { + serve_stdio(server_rx, server_tx, move |cwd| { + Ok(make_agent( + Arc::clone(&wire) as Arc, + cwd.unwrap_or_else(|| default_cwd.clone()), + )) + }) + .await + }); + + let mut lines = BufReader::new(client_rx).lines(); + send_json_line( + &mut client_tx, + &json!({ "jsonrpc": "2.0", "id": 1, "method": "session/new" }), + ) + .await?; + let _created = read_json_line(&mut lines).await?; + + send_json_line( + &mut client_tx, + &json!({ + "jsonrpc": "2.0", + "id": 2, + "method": "session/prompt", + "params": { "sessionId": "session-1", "prompt": "read note.txt" }, + }), + ) + .await?; + + let start = read_json_line(&mut lines).await?; + assert_eq!(start["params"]["update"]["sessionUpdate"], "tool_call"); + assert_eq!(start["params"]["update"]["toolCallId"], "call_1"); + assert_eq!(start["params"]["update"]["status"], "in_progress"); + + let result = read_json_line(&mut lines).await?; + assert_eq!( + result["params"]["update"]["sessionUpdate"], + "tool_call_update" + ); + assert_eq!(result["params"]["update"]["status"], "completed"); + + let text = read_json_line(&mut lines).await?; + assert_eq!(text["params"]["update"]["content"]["text"], "read it"); + + let done = read_json_line(&mut lines).await?; + assert_eq!(done["result"]["stopReason"], "max_tokens"); + + drop(client_tx); + server_task.await??; + Ok(()) + } + + #[tokio::test] + async fn session_cancel_aborts_in_flight_prompt() -> Result<()> { + let dir = TempDir::new()?; + let default_cwd = dir.path().to_path_buf(); + + let (mut client_tx, server_rx) = duplex(8192); + let (server_tx, client_rx) = duplex(8192); + + let server_task = tokio::spawn(async move { + serve_stdio(server_rx, server_tx, move |cwd| { + Ok(make_agent( + Arc::new(BlockingWire), + cwd.unwrap_or_else(|| default_cwd.clone()), + )) + }) + .await + }); + + let mut lines = BufReader::new(client_rx).lines(); + send_json_line( + &mut client_tx, + &json!({ "jsonrpc": "2.0", "id": 1, "method": "session/new" }), + ) + .await?; + let _created = read_json_line(&mut lines).await?; + + send_json_line( + &mut client_tx, + &json!({ + "jsonrpc": "2.0", + "id": 2, + "method": "session/prompt", + "params": { "sessionId": "session-1", "prompt": "hang" }, + }), + ) + .await?; + send_json_line( + &mut client_tx, + &json!({ + "jsonrpc": "2.0", + "id": 3, + "method": "session/cancel", + "params": { "sessionId": "session-1" }, + }), + ) + .await?; + + let cancel_resp = read_json_line(&mut lines).await?; + assert_eq!(cancel_resp["id"], 3); + assert_eq!(cancel_resp["result"], json!({})); + + let prompt_resp = read_json_line(&mut lines).await?; + assert_eq!(prompt_resp["id"], 2); + assert_eq!(prompt_resp["result"]["stopReason"], "cancelled"); + + drop(client_tx); + server_task.await??; + Ok(()) + } + + #[tokio::test] + async fn handles_jsonrpc_and_agent_errors() -> Result<()> { + let (mut client_tx, server_rx) = duplex(8192); + let (server_tx, client_rx) = duplex(8192); + + let server_task = tokio::spawn(async move { + serve_stdio(server_rx, server_tx, |_cwd| Err(anyhow!("boom"))).await + }); + + let mut lines = BufReader::new(client_rx).lines(); + + // Parse error + client_tx.write_all(b"not json\n\n").await?; + client_tx.flush().await?; + let parse_err = read_json_line(&mut lines).await?; + assert_eq!(parse_err["error"]["code"], ERR_PARSE); + + // Invalid jsonrpc version + send_json_line( + &mut client_tx, + &json!({ "jsonrpc": "1.0", "id": 1, "method": "initialize" }), + ) + .await?; + let ver_err = read_json_line(&mut lines).await?; + assert_eq!(ver_err["error"]["code"], ERR_INVALID_REQUEST); + + // Unknown method + send_json_line( + &mut client_tx, + &json!({ "jsonrpc": "2.0", "id": 2, "method": "unknown/method" }), + ) + .await?; + let method_err = read_json_line(&mut lines).await?; + assert_eq!(method_err["error"]["code"], ERR_METHOD_NOT_FOUND); + + // Unknown session on cancel + send_json_line( + &mut client_tx, + &json!({ + "jsonrpc": "2.0", + "id": 3, + "method": "session/cancel", + "params": { "sessionId": "missing" }, + }), + ) + .await?; + let cancel_err = read_json_line(&mut lines).await?; + assert_eq!(cancel_err["error"]["code"], ERR_INVALID_PARAMS); + + send_json_line( + &mut client_tx, + &json!({ "jsonrpc": "2.0", "id": 4, "method": "session/new" }), + ) + .await?; + let _created = read_json_line(&mut lines).await?; + + // Idle cancel succeeds. + send_json_line( + &mut client_tx, + &json!({ + "jsonrpc": "2.0", + "id": 5, + "method": "session/cancel", + "params": { "sessionId": "session-1" }, + }), + ) + .await?; + let idle_cancel = read_json_line(&mut lines).await?; + assert_eq!(idle_cancel["result"], json!({})); + + // Factory error becomes internal error. + send_json_line( + &mut client_tx, + &json!({ + "jsonrpc": "2.0", + "id": 6, + "method": "session/prompt", + "params": { "sessionId": "session-1", "prompt": "hi" }, + }), + ) + .await?; + let internal_err = read_json_line(&mut lines).await?; + assert_eq!(internal_err["error"]["code"], ERR_INTERNAL); + + drop(client_tx); + server_task.await??; + Ok(()) + } + + #[tokio::test] + async fn rejects_invalid_params_and_unknown_sessions() -> Result<()> { + let (mut client_tx, server_rx) = duplex(8192); + let (server_tx, client_rx) = duplex(8192); + + let server_task = tokio::spawn(async move { + serve_stdio(server_rx, server_tx, |_cwd| Err(anyhow!("unused"))).await + }); + + let mut lines = BufReader::new(client_rx).lines(); + + send_json_line( + &mut client_tx, + &json!({ "jsonrpc": "2.0", "id": 1, "method": "session/new", "params": "bad" }), + ) + .await?; + assert_eq!( + read_json_line(&mut lines).await?["error"]["code"], + ERR_INVALID_PARAMS + ); + + send_json_line( + &mut client_tx, + &json!({ "jsonrpc": "2.0", "id": 2, "method": "session/prompt" }), + ) + .await?; + assert_eq!( + read_json_line(&mut lines).await?["error"]["code"], + ERR_INVALID_PARAMS + ); + + send_json_line( + &mut client_tx, + &json!({ + "jsonrpc": "2.0", + "id": 3, + "method": "session/prompt", + "params": { "wrong": true }, + }), + ) + .await?; + assert_eq!( + read_json_line(&mut lines).await?["error"]["code"], + ERR_INVALID_PARAMS + ); + + send_json_line( + &mut client_tx, + &json!({ + "jsonrpc": "2.0", + "id": 4, + "method": "session/prompt", + "params": { "sessionId": "missing", "prompt": "hi" }, + }), + ) + .await?; + assert_eq!( + read_json_line(&mut lines).await?["error"]["code"], + ERR_INVALID_PARAMS + ); + + drop(client_tx); + server_task.await??; + Ok(()) + } +} diff --git a/crates/ox/Cargo.toml b/crates/ox/Cargo.toml index 375b9aec6..3b2082241 100644 --- a/crates/ox/Cargo.toml +++ b/crates/ox/Cargo.toml @@ -14,6 +14,7 @@ workspace = true anyhow.workspace = true clap.workspace = true futures-util.workspace = true +ox-acp.workspace = true ox-core.workspace = true ox-tui.workspace = true serde_json.workspace = true diff --git a/crates/ox/src/lib.rs b/crates/ox/src/lib.rs index b520fb727..2985a57db 100644 --- a/crates/ox/src/lib.rs +++ b/crates/ox/src/lib.rs @@ -99,6 +99,8 @@ struct ChatArgs { #[derive(Debug, Subcommand)] enum Command { + /// Serve Agent Client Protocol (ACP) clients over stdio. + Acp(ChatArgs), /// Launch the interactive terminal UI. Chat(ChatArgs), /// Send a single prompt to a configured provider and stream the response. @@ -187,6 +189,8 @@ pub async fn run() -> Result<()> { async fn dispatch(cli: Cli) -> Result<()> { match cli.command { + Some(Command::Acp(acp)) => run_acp(acp).await, + Some(Command::Chat(chat)) => run_chat(chat).await, Some(Command::Complete { common }) => { @@ -327,6 +331,45 @@ fn resolve_session_mode( } } +async fn run_acp(acp: ChatArgs) -> Result<()> { + let default_workdir = resolve_workdir(acp.cwd)?; + let runtime = resolve_provider( + acp.provider.config, + acp.provider.model.as_deref(), + acp.provider.base_url, + acp.provider.api_key, + ) + .await?; + let wire = build_wire(runtime.provider)?; + let agent_cfg = AgentConfig { + model: runtime.wire_model, + system: acp.provider.system, + max_output_tokens: runtime.max_output_tokens, + reasoning_effort: acp.provider.reasoning_effort.or(runtime.reasoning_effort), + max_turns: acp.max_turns, + }; + let (tools, plugins) = build_tools_and_plugins(&runtime.plugins).await?; + let hooks = runtime.hooks; + + let result = ox_acp::run_stdio(move |session_cwd| { + let workdir = match session_cwd { + Some(dir) => resolve_workdir(Some(dir))?, + None => default_workdir.clone(), + }; + Ok(Agent::new( + Arc::clone(&wire), + Arc::clone(&tools), + ToolContext::new(workdir), + agent_cfg.clone(), + ) + .with_hooks(HookRunner::new(hooks.clone()))) + }) + .await; + + shutdown_plugins(&plugins).await; + result +} + async fn run_chat(chat: ChatArgs) -> Result<()> { let (agent, wire_model, theme, plugins) = build_chat_agent(chat).await?; let result = ox_tui::run_tui_with_theme(agent, wire_model, theme).await; @@ -844,6 +887,30 @@ mod tests { } } + #[test] + fn cli_parses_acp_subcommand() { + let cli = Cli::try_parse_from([ + "ox", + "acp", + "-m", + "gemini-4-neon", + "-C", + "/tmp", + "--max-turns", + "8", + ]) + .expect("parse ox acp"); + match cli.command { + Some(Command::Acp(acp)) => { + assert_eq!(acp.provider.model.as_deref(), Some("gemini-4-neon")); + assert_eq!(acp.cwd, Some(PathBuf::from("/tmp"))); + assert_eq!(acp.max_turns, 8); + } + + other => panic!("expected Acp command, got {other:?}"), + } + } + #[test] fn cli_parses_chat_subcommand() { let cli = Cli::try_parse_from([ diff --git a/crates/ox/tests/cli.rs b/crates/ox/tests/cli.rs index a139b7a31..046f45052 100644 --- a/crates/ox/tests/cli.rs +++ b/crates/ox/tests/cli.rs @@ -1,8 +1,10 @@ //! End-to-end CLI integration tests exercising the compiled `ox` binary. -use std::process::Command; +use std::io::Write as _; +use std::process::{Command, Stdio}; use indoc::indoc; +use serde_json::Value; use tempfile::{NamedTempFile, TempDir}; use wiremock::matchers::{method, path}; use wiremock::{Mock, MockServer, ResponseTemplate}; @@ -19,6 +21,7 @@ fn help_lists_subcommands() { assert!(output.status.success(), "expected exit 0"); let stdout = String::from_utf8(output.stdout).expect("utf8 stdout"); + assert!(stdout.contains("acp")); assert!(stdout.contains("chat")); assert!(stdout.contains("complete")); assert!(stdout.contains("run")); @@ -193,3 +196,68 @@ async fn complete_and_run_stream_from_mock_server() { "Hello from mock!\n" ); } + +#[test] +fn acp_serves_initialize_and_shutdown_over_stdio() { + let workdir = TempDir::new().expect("create temp workdir"); + let config_file = NamedTempFile::new().expect("create temp config"); + std::fs::write( + config_file.path(), + indoc! {r#" + default_model = "mock" + + [providers.google_mock] + wire = "google" + api_key = "test-key" + no_proxy = true + + [models.mock] + provider = "google_mock" + model = "gemini-4-neon" + "#}, + ) + .expect("write temp config"); + + let mut child = ox_bin() + .args(["acp", "--config"]) + .arg(config_file.path()) + .arg("-C") + .arg(workdir.path()) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("spawn ox acp"); + + { + let mut stdin = child.stdin.take().expect("open child stdin"); + stdin + .write_all( + indoc! {r#" + {"jsonrpc":"2.0","id":1,"method":"initialize"} + {"jsonrpc":"2.0","id":2,"method":"shutdown"} + "#} + .as_bytes(), + ) + .expect("write ACP requests"); + } + + let output = child.wait_with_output().expect("wait for ox acp"); + assert!( + output.status.success(), + "ox acp failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + + let stdout = String::from_utf8(output.stdout).expect("utf8 stdout"); + let responses: Vec = stdout + .lines() + .map(|line| serde_json::from_str(line).expect("parse JSON-RPC line")) + .collect(); + assert_eq!(responses.len(), 2); + assert_eq!(responses[0]["id"], 1); + assert_eq!(responses[0]["result"]["protocolVersion"], 1); + assert_eq!(responses[0]["result"]["serverInfo"]["name"], "ox"); + assert_eq!(responses[1]["id"], 2); + assert_eq!(responses[1]["result"], serde_json::json!({})); +} diff --git a/docs/README.md b/docs/README.md index df9433b2b..df8ae3ad0 100644 --- a/docs/README.md +++ b/docs/README.md @@ -17,6 +17,7 @@ Documentation for `oxide-code` (`ox`) is organized into three user-facing bucket | Document | Topic | | ------------------------------------------- | ------------------------------------------------------------------ | +| [ACP](reference/acp.md) | `ox acp` stdio JSON-RPC 2.0 server methods and streaming updates | | [CLI](reference/cli.md) | Shipped subcommands, flags, session storage, and TUI keybindings | | [Configuration](reference/configuration.md) | `config.toml` schema for providers, credentials, and model entries | | [Hooks](reference/hooks.md) | Out-of-process command hooks, lifecycle events, and error policy | diff --git a/docs/reference/acp.md b/docs/reference/acp.md new file mode 100644 index 000000000..ab461dc05 --- /dev/null +++ b/docs/reference/acp.md @@ -0,0 +1,41 @@ +# Agent Client Protocol (ACP) + +`ox acp` exposes `oxide-code` as an Agent Client Protocol server over newline-delimited JSON-RPC 2.0 on stdin and stdout. The server lives in the `crates/ox-acp` frontend crate and depends only on `ox-core`. + +## Usage + +```bash +ox acp --model gemini-4-neon +ox acp --config ~/.config/ox/config.toml -C /path/to/repo +``` + +`ox acp` accepts the same provider, model, system prompt, working directory (`-C` / `--cwd`), and `--max-turns` flags as `ox chat`. + +## Supported Methods + +| Method | Direction | Description | +| ---------------- | --------- | ------------------------------------------------------------------------- | +| `initialize` | Request | Returns `protocolVersion`, `serverInfo`, and `capabilities`. | +| `session/new` | Request | Creates a session with an optional `cwd` and returns `{ sessionId }`. | +| `session/prompt` | Request | Runs a prompt turn, streams `session/update`, and returns `stopReason`. | +| `session/cancel` | Request | Cancels an active prompt turn or acknowledges an idle session. | +| `shutdown` | Request | Acknowledges shutdown and exits the stdio server loop. | +| `session/update` | Notify | Streams `agent_message_chunk`, `agent_thought_chunk`, and tool lifecycle. | + +## Streaming Updates + +During `session/prompt`, `ox acp` emits `session/update` notifications: + +- `agent_message_chunk`: incremental assistant text (`content.type = "text"`). +- `agent_thought_chunk`: incremental reasoning text (`content.type = "text"`). +- `tool_call`: tool invocation start with `toolCallId`, `title`, `status = "in_progress"`, and `rawInput`. +- `tool_call_update`: tool completion with `toolCallId`, `title`, `status = "completed"` or `"failed"`, and `rawOutput`. + +## Stop Reasons + +`session/prompt` resolves with `{ "stopReason": "..." }`: + +- `end_turn`: model finished the turn normally. +- `max_tokens`: model hit the configured output token limit. +- `max_turn_requests`: agent reached `--max-turns`. +- `cancelled`: cancelled by `session/cancel` or client EOF.