| 1 | use super::*; |
| 2 | use agent_client_protocol::v1::{ConnectionTo, Responder}; |
| 3 | use agent_client_protocol::{Agent, Client, Lines, UntypedMessage}; |
| 4 | use codewhale_util::bounded_lines::{BoundedLines, FrameRefusal, MAX_FRAME_BYTES}; |
| 5 | use futures_util::{Sink, Stream}; |
| 6 | use std::io; |
| 7 | use std::sync::{MutexGuard, PoisonError}; |
| 8 | use tokio::sync::{Notify, mpsc}; |
| 9 | |
| 10 | const PROMPT_BUSY: &str = "a session/prompt turn is already in progress"; |
| 11 | const OUTGOING_QUEUE_FRAMES: usize = 256; |
| 12 | const OVERSIZE_RESPONSE: &str = |
| 13 | "ACP response exceeds the 8 MiB transport limit; inspect canonical state without replay"; |
| 14 | type Cx = ConnectionTo<Client>; |
| 15 | |
| 16 | pub(super) struct Shared { |
| 17 | server: tokio::sync::Mutex<AcpServer>, |
| 18 | prompt: std::sync::Mutex<Option<mpsc::UnboundedSender<Inbound>>>, |
| 19 | idle: Notify, |
| 20 | ending: Notify, |
| 21 | failure: std::sync::Mutex<Option<anyhow::Error>>, |
| 22 | } |
| 23 | |
| 24 | struct PromptGuard(Arc<Shared>); |
| 25 | |
| 26 | impl Drop for PromptGuard { |
| 27 | fn drop(&mut self) { |
| 28 | self.0.release(); |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | impl PromptGuard { |
| 33 | fn finish(self, responder: Responder<Value>, result: std::result::Result<Value, SdkError>) { |
| 34 | let mut slot = self.0.slot(); |
| 35 | let _ = responder.respond_with_result(result); |
| 36 | *slot = None; |
| 37 | drop(slot); |
| 38 | self.0.idle.notify_waiters(); |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | impl Shared { |
| 43 | pub(super) fn new(server: AcpServer) -> Self { |
| 44 | Self { |
| 45 | server: tokio::sync::Mutex::new(server), |
| 46 | prompt: std::sync::Mutex::new(None), |
| 47 | idle: Notify::new(), |
| 48 | ending: Notify::new(), |
| 49 | failure: std::sync::Mutex::new(None), |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | pub(super) fn fail(&self, error: anyhow::Error) { |
| 54 | self.failure |
| 55 | .lock() |
| 56 | .unwrap_or_else(PoisonError::into_inner) |
| 57 | .get_or_insert(error); |
| 58 | self.tell_prompt(Inbound::Eof); |
| 59 | self.ending.notify_one(); |
| 60 | } |
| 61 | |
| 62 | pub(super) fn take_failure(&self) -> Option<anyhow::Error> { |
| 63 | self.failure |
| 64 | .lock() |
| 65 | .unwrap_or_else(PoisonError::into_inner) |
| 66 | .take() |
| 67 | } |
| 68 | |
| 69 | #[cfg(test)] |
| 70 | pub(super) fn into_server(self) -> AcpServer { |
| 71 | self.server.into_inner() |
| 72 | } |
| 73 | |
| 74 | fn slot(&self) -> MutexGuard<'_, Option<mpsc::UnboundedSender<Inbound>>> { |
| 75 | self.prompt.lock().unwrap_or_else(PoisonError::into_inner) |
| 76 | } |
| 77 | |
| 78 | fn prompt_active(&self) -> bool { |
| 79 | self.slot().is_some() |
| 80 | } |
| 81 | |
| 82 | fn tell_prompt(&self, message: Inbound) { |
| 83 | if let Some(inbox) = self.slot().as_ref() { |
| 84 | let _ = inbox.send(message); |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | fn release(&self) { |
| 89 | *self.slot() = None; |
| 90 | self.idle.notify_waiters(); |
| 91 | } |
| 92 | |
| 93 | async fn wait_idle(&self) { |
| 94 | loop { |
| 95 | let notified = self.idle.notified(); |
| 96 | if !self.prompt_active() { |
| 97 | return; |
| 98 | } |
| 99 | notified.await; |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | fn cancel(&self, params: &Value) { |
| 104 | if let Some(session) = params.get("sessionId").and_then(Value::as_str) { |
| 105 | self.tell_prompt(Inbound::Cancel { |
| 106 | session: session.to_string(), |
| 107 | }); |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | async fn request( |
| 112 | self: &Arc<Self>, |
| 113 | method: String, |
| 114 | params: Value, |
| 115 | responder: Responder<Value>, |
| 116 | cx: Cx, |
| 117 | ) { |
| 118 | match method.as_str() { |
| 119 | "session/cancel" => { |
| 120 | self.cancel(¶ms); |
| 121 | let _ = responder.respond(Value::Null); |
| 122 | } |
| 123 | "session/prompt" => self.start_prompt(params, responder, cx).await, |
| 124 | _ if self.prompt_active() => self.during_prompt(&cx, method, params, responder), |
| 125 | "shutdown" => { |
| 126 | let _ = responder.respond(Value::Null); |
| 127 | self.ending.notify_one(); |
| 128 | } |
| 129 | "session/load" => self.load(params, responder, cx).await, |
| 130 | _ => { |
| 131 | let result = Box::pin(AcpServer::handle_request_shared( |
| 132 | &self.server, |
| 133 | &method, |
| 134 | params, |
| 135 | )) |
| 136 | .await; |
| 137 | let _ = responder.respond_with_result(result); |
| 138 | } |
| 139 | } |
| 140 | } |
| 141 | |
| 142 | fn during_prompt( |
| 143 | self: &Arc<Self>, |
| 144 | cx: &Cx, |
| 145 | method: String, |
| 146 | params: Value, |
| 147 | responder: Responder<Value>, |
| 148 | ) { |
| 149 | let served = matches!( |
| 150 | method.as_str(), |
| 151 | "session/list" |
| 152 | | "session/set_config_option" |
| 153 | | "session/set_mode" |
| 154 | | "session/set_model" |
| 155 | | "session/listProviders" |
| 156 | | "session/currentModel" |
| 157 | | "session/selectModel" |
| 158 | ); |
| 159 | if !served { |
| 160 | let error = if matches!( |
| 161 | method.as_str(), |
| 162 | "initialize" | "session/new" | "session/load" | "shutdown" |
| 163 | ) { |
| 164 | SdkError::new(-32603, PROMPT_BUSY) |
| 165 | } else { |
| 166 | SdkError::method_not_found().data(Value::String(method)) |
| 167 | }; |
| 168 | let _ = responder.respond_with_error(error); |
| 169 | return; |
| 170 | } |
| 171 | let shared = Arc::clone(self); |
| 172 | let method_name = method.clone(); |
| 173 | if let Err(error) = cx.spawn(async move { |
| 174 | let result = Box::pin(AcpServer::handle_request_shared( |
| 175 | &shared.server, |
| 176 | &method, |
| 177 | params, |
| 178 | )) |
| 179 | .await; |
| 180 | let _ = responder.respond_with_result(result); |
| 181 | Ok(()) |
| 182 | }) { |
| 183 | tracing::warn!( |
| 184 | method = %method_name, |
| 185 | error = ?error, |
| 186 | "failed to spawn ACP request task" |
| 187 | ); |
| 188 | } |
| 189 | } |
| 190 | |
| 191 | async fn load(&self, params: Value, responder: Responder<Value>, cx: Cx) { |
| 192 | let result = async { |
| 193 | let loaded = Box::pin(AcpServer::load_session_shared(&self.server, params)) |
| 194 | .await |
| 195 | .map_err(SdkError::from)?; |
| 196 | if let Some(session) = loaded.get("sessionId").and_then(Value::as_str) { |
| 197 | let (sessions_dir, config) = { |
| 198 | let server = self.server.lock().await; |
| 199 | (server.sessions_dir.clone(), Arc::clone(&server.config)) |
| 200 | }; |
| 201 | let updates = Box::pin(history_updates_for( |
| 202 | sessions_dir, |
| 203 | config, |
| 204 | session.to_string(), |
| 205 | )) |
| 206 | .await |
| 207 | .map_err(|error| SdkError::new(-32603, error.to_string()))?; |
| 208 | for update in updates { |
| 209 | cx.send_notification(acp::SessionNotification::new( |
| 210 | session.to_string(), |
| 211 | update, |
| 212 | ))?; |
| 213 | } |
| 214 | } |
| 215 | Ok::<_, SdkError>(loaded) |
| 216 | } |
| 217 | .await; |
| 218 | let _ = responder.respond_with_result(result); |
| 219 | } |
| 220 | |
| 221 | async fn start_prompt(self: &Arc<Self>, params: Value, responder: Responder<Value>, cx: Cx) { |
| 222 | if self.prompt_active() { |
| 223 | let _ = responder.respond_with_error(SdkError::new(-32603, PROMPT_BUSY)); |
| 224 | return; |
| 225 | } |
| 226 | let admitted = { |
| 227 | let server = self.server.lock().await; |
| 228 | server.validate_prompt(¶ms).map(|(session, prompt)| { |
| 229 | let thread = server.sessions[&session].thread_id.clone(); |
| 230 | (session, thread, prompt, server.prompt_run()) |
| 231 | }) |
| 232 | }; |
| 233 | let (session, thread, prompt, run) = match admitted { |
| 234 | Ok(admitted) => admitted, |
| 235 | Err(error) => { |
| 236 | let _ = responder.respond_with_error(error.into()); |
| 237 | return; |
| 238 | } |
| 239 | }; |
| 240 | let (answers, mut inbox) = mpsc::unbounded_channel(); |
| 241 | *self.slot() = Some(answers.clone()); |
| 242 | let guard = PromptGuard(Arc::clone(self)); |
| 243 | let task_cx = cx.clone(); |
| 244 | let session_id = session.clone(); |
| 245 | if let Err(error) = cx.spawn(async move { |
| 246 | let result = { |
| 247 | let mut emit = |outgoing: Outgoing| -> Result<()> { |
| 248 | match outgoing { |
| 249 | Outgoing::Update(notification) => task_cx |
| 250 | .send_notification(notification) |
| 251 | .map_err(|error| anyhow!("ACP update was not sent: {}", error.message)), |
| 252 | Outgoing::Permission { key, request } => { |
| 253 | let answers = answers.clone(); |
| 254 | task_cx |
| 255 | .send_request(request) |
| 256 | .on_receiving_result(async move |reply| { |
| 257 | let gone = matches!( |
| 258 | &reply, |
| 259 | Err(error) |
| 260 | if agent_client_protocol::is_incoming_transport_closed(error) |
| 261 | || agent_client_protocol::is_connection_terminated(error) |
| 262 | ); |
| 263 | if !gone { |
| 264 | let _ = answers.send(Inbound::Permission { |
| 265 | key, |
| 266 | allow: permission_allowed(&reply), |
| 267 | }); |
| 268 | } |
| 269 | Ok(()) |
| 270 | }) |
| 271 | .map_err(|error| { |
| 272 | anyhow!("ACP permission request was not sent: {}", error.message) |
| 273 | }) |
| 274 | } |
| 275 | } |
| 276 | }; |
| 277 | run.drive_prompt(&session, &thread, prompt, &mut emit, &mut inbox) |
| 278 | .await |
| 279 | }; |
| 280 | let result = match result { |
| 281 | Ok(stop) => to_wire(&acp::PromptResponse::new(stop)).map_err(SdkError::from), |
| 282 | Err(error) => Err(SdkError::new( |
| 283 | -32603, |
| 284 | codewhale_engine::client::redact_model_bound_text(&error.to_string(), &[]), |
| 285 | )), |
| 286 | }; |
| 287 | guard.finish(responder, result); |
| 288 | Ok(()) |
| 289 | }) { |
| 290 | tracing::warn!( |
| 291 | session = %session_id, |
| 292 | error = ?error, |
| 293 | "failed to spawn ACP prompt task" |
| 294 | ); |
| 295 | } |
| 296 | } |
| 297 | } |
| 298 | |
| 299 | fn permission_allowed( |
| 300 | reply: &std::result::Result<acp::RequestPermissionResponse, SdkError>, |
| 301 | ) -> bool { |
| 302 | matches!( |
| 303 | reply, |
| 304 | Ok(response) if matches!( |
| 305 | &response.outcome, |
| 306 | acp::RequestPermissionOutcome::Selected(selected) |
| 307 | if &*selected.option_id.0 == "allow-once" |
| 308 | ) |
| 309 | ) |
| 310 | } |
| 311 | |
| 312 | fn closes_input(line: &str) -> bool { |
| 313 | line.len() <= 256 |
| 314 | && line.contains("daemon/input_closed") |
| 315 | && serde_json::from_str::<Value>(line) |
| 316 | .is_ok_and(|message| crate::is_control_input_closed(&message)) |
| 317 | } |
| 318 | |
| 319 | fn incoming_lines( |
| 320 | input: Box<dyn AsyncBufRead + Send + Unpin>, |
| 321 | shared: Arc<Shared>, |
| 322 | ) -> impl Stream<Item = io::Result<String>> + Send + 'static { |
| 323 | futures_util::stream::unfold( |
| 324 | (BoundedLines::new(input), shared), |
| 325 | |(mut lines, shared)| async move { |
| 326 | loop { |
| 327 | match lines.next_line().await { |
| 328 | Ok(Some(line)) if line.trim().is_empty() => continue, |
| 329 | Ok(Some(line)) if closes_input(&line) => return None, |
| 330 | Ok(Some(line)) => return Some((Ok(line), (lines, shared))), |
| 331 | Ok(None) => return None, |
| 332 | Err(error) if crate::stdio::is_frame_refusal(&error) => { |
| 333 | return Some((Ok(error.to_string()), (lines, shared))); |
| 334 | } |
| 335 | Err(error) => { |
| 336 | shared.fail(anyhow!("ACP input failed: {error}")); |
| 337 | return None; |
| 338 | } |
| 339 | } |
| 340 | } |
| 341 | }, |
| 342 | ) |
| 343 | } |
| 344 | |
| 345 | pub(super) fn bound_outgoing(line: String) -> io::Result<String> { |
| 346 | if line.len() <= MAX_FRAME_BYTES { |
| 347 | return Ok(line); |
| 348 | } |
| 349 | let refused = || io::Error::new(io::ErrorKind::InvalidData, FrameRefusal::TooLarge); |
| 350 | let Ok(Value::Object(frame)) = serde_json::from_str::<Value>(&line) else { |
| 351 | return Err(refused()); |
| 352 | }; |
| 353 | if frame.contains_key("method") || !frame.contains_key("id") { |
| 354 | return Err(refused()); |
| 355 | } |
| 356 | let failure = |id: Value| { |
| 357 | json!({"jsonrpc":"2.0","id":id,"error":{"code":-32603,"message":OVERSIZE_RESPONSE}}) |
| 358 | .to_string() |
| 359 | }; |
| 360 | let replaced = failure(frame["id"].clone()); |
| 361 | Ok(if replaced.len() <= MAX_FRAME_BYTES { |
| 362 | replaced |
| 363 | } else { |
| 364 | failure(Value::Null) |
| 365 | }) |
| 366 | } |
| 367 | |
| 368 | pub(super) fn outgoing_lines( |
| 369 | frames: mpsc::Sender<String>, |
| 370 | shared: Arc<Shared>, |
| 371 | ) -> impl Sink<String, Error = io::Error> + Send + 'static { |
| 372 | futures_util::sink::unfold( |
| 373 | (frames, shared), |
| 374 | |(frames, shared), line: String| async move { |
| 375 | let line = match bound_outgoing(line) { |
| 376 | Ok(line) => line, |
| 377 | Err(error) => { |
| 378 | shared.fail(anyhow!("ACP output refused: {error}")); |
| 379 | return Ok((frames, shared)); |
| 380 | } |
| 381 | }; |
| 382 | frames |
| 383 | .send(line) |
| 384 | .await |
| 385 | .map_err(|_| io::Error::new(io::ErrorKind::BrokenPipe, "ACP output closed"))?; |
| 386 | Ok::<_, io::Error>((frames, shared)) |
| 387 | }, |
| 388 | ) |
| 389 | } |
| 390 | |
| 391 | pub(super) async fn serve_connection<'a>( |
| 392 | server: AcpServer, |
| 393 | input: Box<dyn AsyncBufRead + Send + Unpin>, |
| 394 | mut output: Box<dyn AsyncWrite + Send + Unpin + 'a>, |
| 395 | ) -> Result<Arc<Shared>> { |
| 396 | let shared = Arc::new(Shared::new(server)); |
| 397 | let (frames, mut queued) = mpsc::channel::<String>(OUTGOING_QUEUE_FRAMES); |
| 398 | let transport = Lines::new( |
| 399 | outgoing_lines(frames, Arc::clone(&shared)), |
| 400 | incoming_lines(input, Arc::clone(&shared)), |
| 401 | ); |
| 402 | let requests = Arc::clone(&shared); |
| 403 | let notifications = Arc::clone(&shared); |
| 404 | let finishing = Arc::clone(&shared); |
| 405 | let connection = Agent |
| 406 | .v1() |
| 407 | .on_receive_request( |
| 408 | async move |request: UntypedMessage, responder, cx| { |
| 409 | let (method, params) = request.into_parts(); |
| 410 | requests.request(method, params, responder, cx).await; |
| 411 | Ok(()) |
| 412 | }, |
| 413 | agent_client_protocol::on_receive_request!(), |
| 414 | ) |
| 415 | .on_receive_notification( |
| 416 | async move |notification: UntypedMessage, _cx| { |
| 417 | let (method, params) = notification.into_parts(); |
| 418 | if method == "session/cancel" { |
| 419 | notifications.cancel(¶ms); |
| 420 | } |
| 421 | Ok(()) |
| 422 | }, |
| 423 | agent_client_protocol::on_receive_notification!(), |
| 424 | ) |
| 425 | .connect_with(transport, async move |cx| { |
| 426 | tokio::select! { |
| 427 | () = cx.incoming_closed() => {} |
| 428 | () = finishing.ending.notified() => {} |
| 429 | } |
| 430 | finishing.tell_prompt(Inbound::Eof); |
| 431 | finishing.wait_idle().await; |
| 432 | Ok(()) |
| 433 | }); |
| 434 | let connection = async { |
| 435 | match connection.await { |
| 436 | Err(error) if agent_client_protocol::is_incoming_transport_closed(&error) => Ok(()), |
| 437 | other => other.map_err(|error| anyhow!("ACP connection failed: {}", error.message)), |
| 438 | } |
| 439 | }; |
| 440 | let failing = Arc::clone(&shared); |
| 441 | let pump = async { |
| 442 | let mut broken = false; |
| 443 | while let Some(frame) = queued.recv().await { |
| 444 | if broken { |
| 445 | continue; |
| 446 | } |
| 447 | if let Err(error) = |
| 448 | crate::stdio::write_control_line(&mut output, frame.as_bytes()).await |
| 449 | { |
| 450 | broken = true; |
| 451 | failing.fail(error); |
| 452 | } |
| 453 | } |
| 454 | }; |
| 455 | let (ended, ()) = tokio::join!(connection, pump); |
| 456 | drop(failing); |
| 457 | if let Some(error) = shared.take_failure() { |
| 458 | return Err(error); |
| 459 | } |
| 460 | ended?; |
| 461 | Ok(shared) |
| 462 | } |
| 463 |