mod pump;
use std::{
collections::HashMap,
future::Future,
pin::Pin,
sync::{
atomic::{AtomicBool, AtomicU64, Ordering},
Arc, Mutex, PoisonError,
},
};
use agent_client_protocol::{
v1::schema::{
CloseSessionRequest, CloseSessionResponse, DeleteSessionRequest, DeleteSessionResponse,
LoadSessionRequest, McpServer, MessageId, NewSessionRequest, ResumeSessionRequest,
SessionId as AcpSessionId, SetSessionConfigOptionRequest, SetSessionConfigOptionResponse,
SetSessionModeRequest, SetSessionModeResponse,
},
Error as AcpError,
};
use rho_protocol::{
methods::{
SessionAttach, SessionBackgroundStop, SessionCancel, SessionConfigure, SessionDelete,
SessionDetach, SessionNew,
},
BackgroundItem, BackgroundWork, ClientEnvironment, Cursor, ErrorCode, JobState, Replay,
SessionAttachParams, SessionAttachResponse, SessionBackgroundStopParams, SessionCancelParams,
SessionChange, SessionConfigureParams, SessionDeleteParams, SessionDetachParams, SessionId,
SessionNewParams, SessionOptions, SessionSetup, TurnId, TurnOutcome,
};
use tokio::{
sync::{mpsc, oneshot, watch},
task::JoinHandle,
};
use super::{daemon, inputs::InputContext, options, requests, AcpClientPort, Adapter, Foreground};
use crate::app::daemon_client::{Daemon, Link, Routed, SessionRoute};
enum Inbound {
Routed(Routed),
Control(Control),
}
pub(super) enum Control {
Resume(Replayed),
Arm {
waiter: Waiter,
turn: oneshot::Receiver<TurnId>,
},
Options(Box<SessionOptions>, oneshot::Sender<()>),
Flush(oneshot::Sender<()>),
}
pub(super) type Replayed = oneshot::Sender<Result<(), AcpError>>;
struct Opening {
response: SessionAttachResponse,
show: Show,
replayed: Replayed,
gate: oneshot::Receiver<()>,
}
#[derive(Clone)]
pub(super) enum Show {
History(Arc<dyn AcpClientPort>),
Missed,
Skip,
}
impl Show {
fn resumed(replay: Replay) -> Self {
match replay {
Replay::Tail => Self::Missed,
Replay::Reset => Self::Skip,
}
}
}
pub(super) type Accept = Box<dyn FnOnce(MessageId) + Send>;
pub(super) struct Waiter {
pub(super) outcome: oneshot::Sender<Result<TurnOutcome, AcpError>>,
pub(super) accept: Arc<Mutex<Option<Accept>>>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Attachment {
Attached(JobState),
Stale,
Deleted,
}
impl Attachment {
fn busy(self) -> bool {
matches!(self, Self::Attached(state) if busy(state))
}
fn foreground(self) -> Foreground {
match self {
Self::Attached(state) => Foreground::of(state),
Self::Stale | Self::Deleted => Foreground::Idle,
}
}
}
struct Shared {
options: Mutex<SessionOptions>,
background: Mutex<Vec<BackgroundWork>>,
attachment: watch::Sender<Attachment>,
}
pub(super) trait Attacher: Send + Sync {
fn attach<'a>(
&'a self,
session: &'a SessionId,
after: Option<&'a Cursor>,
setup: &'a SessionSetup,
) -> Pin<Box<dyn Future<Output = Result<SessionAttachResponse, AcpError>> + Send + 'a>>;
}
impl Attacher for Daemon {
fn attach<'a>(
&'a self,
session: &'a SessionId,
after: Option<&'a Cursor>,
setup: &'a SessionSetup,
) -> Pin<Box<dyn Future<Output = Result<SessionAttachResponse, AcpError>> + Send + 'a>> {
Box::pin(async move {
let params = SessionAttachParams {
session: session.clone(),
after: after.cloned(),
environment: ClientEnvironment::of_this_process(),
setup: setup.clone(),
};
self.request::<SessionAttach>(¶ms)
.await
.map_err(AcpError::from)
})
}
}
pub(super) struct Live {
pub(super) id: SessionId,
inbound: mpsc::UnboundedSender<Inbound>,
shared: Arc<Shared>,
pub(super) prompt: tokio::sync::Mutex<()>,
pub(super) cancelling: AtomicBool,
pub(super) closing: AtomicBool,
attaching: tokio::sync::Mutex<()>,
pump: JoinHandle<()>,
}
impl Live {
pub(super) async fn deliver(&self, link: &Link, control: Control) -> Result<(), AcpError> {
link.fence().await;
self.inbound
.send(Inbound::Control(control))
.map_err(|_| super::resource_not_found(Some(self.id.as_str().to_owned())))
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Wait {
Prompt,
Job,
}
#[derive(Default)]
pub(super) struct Sessions {
live: Mutex<HashMap<String, Arc<Live>>>,
placeholders: Arc<AtomicU64>,
}
pub(super) struct Started {
pub(super) session_id: AcpSessionId,
pub(super) options: SessionOptions,
pub(super) state: JobState,
pub(super) background: Vec<BackgroundWork>,
gate: oneshot::Sender<()>,
}
impl Started {
pub(super) fn open(self) {
let _ = self.gate.send(());
}
}
impl Sessions {
fn get(&self, id: &str) -> Option<Arc<Live>> {
lock(&self.live).get(id).cloned()
}
fn remove(&self, id: &str) -> Option<Arc<Live>> {
lock(&self.live).remove(id)
}
fn take_all(&self) -> Vec<Arc<Live>> {
lock(&self.live).drain().map(|(_, live)| live).collect()
}
}
impl Adapter {
fn port(&self) -> Result<Arc<dyn AcpClientPort>, AcpError> {
self.negotiated
.client()
.ok_or_else(|| AcpError::internal_error().data("ACP connection not initialized"))
}
pub(super) fn with_background<T>(
&self,
id: &AcpSessionId,
report: impl FnOnce(&[BackgroundWork]) -> T,
) -> T {
match self.sessions.get(&id.0) {
Some(live) => report(&lock(&live.shared.background)),
None => report(&[]),
}
}
pub(super) fn is_open(&self, id: &AcpSessionId) -> bool {
self.sessions.get(&id.0).is_some()
}
pub(super) async fn stop_background(
&self,
id: &AcpSessionId,
find: impl FnOnce(&[BackgroundWork]) -> Option<BackgroundItem>,
) -> Result<(), AcpError> {
let live = self.live(id).await?;
let work = find(&lock(&live.shared.background)).ok_or_else(|| {
AcpError::invalid_params().data("no such running background work in this session")
})?;
self.stop_work(&live, work).await
}
pub(super) async fn stop_any_background(
&self,
find: impl Fn(&[BackgroundWork]) -> Option<BackgroundItem>,
) -> bool {
let lives: Vec<_> = lock(&self.sessions.live).values().cloned().collect();
for live in lives {
let Some(work) = find(&lock(&live.shared.background)) else {
continue;
};
if let Err(error) = self.stop_work(&live, work).await {
tracing::warn!(%error, "could not stop an ACP session's background work");
}
return true;
}
false
}
async fn stop_work(&self, live: &Live, work: BackgroundItem) -> Result<(), AcpError> {
let link = self.daemon.link().await?;
let params = SessionBackgroundStopParams {
session: live.id.clone(),
work,
};
link.request::<SessionBackgroundStop>(¶ms)
.await
.map_err(|error| daemon::daemon_error(&error))?;
Ok(())
}
pub(super) async fn live(&self, id: &AcpSessionId) -> Result<Arc<Live>, AcpError> {
let live = self
.sessions
.get(&id.0)
.ok_or_else(|| super::resource_not_found(Some(id.0.to_string())))?;
{
let _attaching = live.attaching.lock().await;
let attachment = *live.shared.attachment.borrow();
match attachment {
Attachment::Attached(_) => {}
Attachment::Stale => self.resume(&live).await?,
Attachment::Deleted => {
self.sessions.remove(&id.0);
self.forget(&live);
return Err(super::resource_not_found(Some(id.0.to_string())));
}
}
}
Ok(live)
}
pub(super) async fn new_session(
&self,
request: &NewSessionRequest,
) -> Result<Started, AcpError> {
let cwd = requests::session_cwd(&request.cwd)?;
let setup = self.launch.setup(
&request.additional_directories,
&request.mcp_servers,
self.negotiated.get(),
);
let created = self
.daemon
.request::<SessionNew>(&SessionNewParams {
cwd,
environment: ClientEnvironment::of_this_process(),
agent: self.launch.agent.clone(),
setup: setup.clone(),
parent: None,
grant: None,
worktree: false,
})
.await?;
self.open(created.session, setup, Show::Skip).await
}
pub(super) async fn load_session(
&self,
request: &LoadSessionRequest,
port: Arc<dyn AcpClientPort>,
) -> Result<Started, AcpError> {
self.reopen(
&request.session_id,
&request.additional_directories,
&request.mcp_servers,
Show::History(port),
)
.await
}
pub(super) async fn resume_session(
&self,
request: &ResumeSessionRequest,
) -> Result<Started, AcpError> {
self.reopen(
&request.session_id,
&request.additional_directories,
&request.mcp_servers,
Show::Skip,
)
.await
}
async fn reopen(
&self,
session_id: &AcpSessionId,
additional_directories: &[std::path::PathBuf],
servers: &[McpServer],
show: Show,
) -> Result<Started, AcpError> {
if let Some(live) = self.sessions.remove(&session_id.0) {
self.detach(&live, Wait::Prompt).await;
if let Some(link) = self.daemon.current().await {
link.fence().await;
}
}
let setup = self
.launch
.setup(additional_directories, servers, self.negotiated.get());
self.open(SessionId::new(session_id.0.as_ref()), setup, show)
.await
}
async fn open(
&self,
id: SessionId,
setup: SessionSetup,
show: Show,
) -> Result<Started, AcpError> {
let port = self.port()?;
let acp_id = AcpSessionId::new(id.as_str());
let (inbound, receiver) = mpsc::unbounded_channel();
self.daemon.route(&id, route(&inbound));
let response = match self.daemon.attach(&id, None, &setup).await {
Ok(response) => response,
Err(error) => {
self.daemon.unroute(&id);
return Err(error);
}
};
let options = response.options.clone();
let state = response.state;
let background = response.background.clone();
let shared = Arc::new(Shared {
options: Mutex::new(options.clone()),
background: Mutex::new(background.clone()),
attachment: watch::channel(Attachment::Stale).0,
});
let context = InputContext {
daemon: Arc::clone(&self.daemon),
session: id.clone(),
acp_id: acp_id.clone(),
port,
features: self.negotiated.get(),
placeholders: Arc::clone(&self.sessions.placeholders),
};
let (replayed, through) = oneshot::channel();
let (gate, gate_receiver) = oneshot::channel();
let attacher: Arc<dyn Attacher> = self.daemon.clone();
let pump = pump::spawn(
context,
attacher,
receiver,
Arc::clone(&shared),
setup,
&self.herdr,
Opening {
response,
show,
replayed,
gate: gate_receiver,
},
);
let live = Arc::new(Live {
id,
inbound,
shared,
prompt: tokio::sync::Mutex::new(()),
cancelling: AtomicBool::new(false),
closing: AtomicBool::new(false),
attaching: tokio::sync::Mutex::new(()),
pump,
});
lock(&self.sessions.live).insert(acp_id.0.to_string(), Arc::clone(&live));
if let Err(error) = through.await.unwrap_or_else(|_| Err(daemon::lost())) {
self.sessions.remove(&acp_id.0);
self.detach(&live, Wait::Prompt).await;
return Err(error);
}
Ok(Started {
session_id: acp_id,
options,
state,
background,
gate,
})
}
async fn resume(&self, live: &Live) -> Result<(), AcpError> {
self.daemon.route(&live.id, route(&live.inbound));
let (replayed, through) = oneshot::channel();
live.inbound
.send(Inbound::Control(Control::Resume(replayed)))
.map_err(|_| daemon::lost())?;
through.await.unwrap_or_else(|_| Err(daemon::lost()))
}
async fn detach(&self, live: &Live, wait: Wait) {
live.closing.store(true, Ordering::Release);
if live.prompt.try_lock().is_err() {
self.cancel_live(live).await;
drop(live.prompt.lock().await);
if wait == Wait::Job {
let mut attachment = live.shared.attachment.subscribe();
let _ = attachment.wait_for(|attachment| !attachment.busy()).await;
}
}
let attachment = *live.shared.attachment.borrow();
self.forget(live);
if !matches!(attachment, Attachment::Attached(_)) {
return;
}
if let Some(link) = self.daemon.current().await {
let params = SessionDetachParams {
session: live.id.clone(),
};
if let Err(error) = link.request::<SessionDetach>(¶ms).await {
tracing::debug!(%error, "could not detach an ACP session");
}
}
}
fn forget(&self, live: &Live) {
self.daemon.unroute(&live.id);
live.pump.abort();
}
pub(super) async fn close_session(
&self,
request: &CloseSessionRequest,
) -> Result<CloseSessionResponse, AcpError> {
if let Some(live) = self.sessions.remove(&request.session_id.0) {
self.detach(&live, Wait::Prompt).await;
}
Ok(CloseSessionResponse::new())
}
pub(super) async fn close_all(&self) {
for live in self.sessions.take_all() {
self.detach(&live, Wait::Prompt).await;
}
let _ = self.herdr.release().await;
}
pub(super) async fn delete_session(
&self,
request: &DeleteSessionRequest,
) -> Result<DeleteSessionResponse, AcpError> {
if let Some(live) = self.sessions.remove(&request.session_id.0) {
self.detach(&live, Wait::Job).await;
}
let params = SessionDeleteParams {
session: SessionId::new(request.session_id.0.as_ref()),
unless_attached: false,
};
let link = self.daemon.link().await?;
match link.request::<SessionDelete>(¶ms).await {
Ok(_) => {}
Err(error) if error.error_code() == Some(ErrorCode::SessionNotFound) => {}
Err(error) => return Err(daemon::daemon_error(&error)),
}
Ok(DeleteSessionResponse::new())
}
pub(super) async fn set_config_option(
&self,
request: &SetSessionConfigOptionRequest,
) -> Result<SetSessionConfigOptionResponse, AcpError> {
let live = self.live(&request.session_id).await?;
let toggles = self.negotiated.get().toggles;
let current = lock(&live.shared.options).clone();
let change = options::change(request, ¤t, toggles)?;
let options = self.configure(&live, change).await?;
Ok(SetSessionConfigOptionResponse::new(
options::config_options(&options, toggles),
))
}
pub(super) async fn set_session_mode(
&self,
request: &SetSessionModeRequest,
) -> Result<SetSessionModeResponse, AcpError> {
let live = self.live(&request.session_id).await?;
let change = options::mode_change(&request.mode_id.0)?;
self.configure(&live, change).await?;
Ok(SetSessionModeResponse::new())
}
async fn configure(
&self,
live: &Live,
change: SessionChange,
) -> Result<SessionOptions, AcpError> {
let link = self.daemon.link().await?;
let params = SessionConfigureParams {
session: live.id.clone(),
change,
};
let response = link
.request::<SessionConfigure>(¶ms)
.await
.map_err(|error| daemon::daemon_error(&error))?;
let (told, heard) = oneshot::channel();
let control = Control::Options(Box::new(response.options.clone()), told);
if live.deliver(&link, control).await.is_ok() {
let _ = heard.await;
}
Ok(response.options)
}
pub(super) async fn cancel(&self, session_id: &AcpSessionId) {
if let Some(live) = self.sessions.get(&session_id.0) {
self.cancel_live(&live).await;
}
}
async fn cancel_live(&self, live: &Live) {
live.cancelling.store(true, Ordering::Release);
let Some(link) = self.daemon.current().await else {
return;
};
let params = SessionCancelParams {
session: live.id.clone(),
};
if let Err(error) = link.request::<SessionCancel>(¶ms).await {
tracing::warn!(%error, "could not cancel an ACP session's turn");
}
}
}
fn route(inbound: &mpsc::UnboundedSender<Inbound>) -> SessionRoute {
let inbound = inbound.clone();
Box::new(move |routed| {
let _ = inbound.send(Inbound::Routed(routed));
})
}
fn busy(state: JobState) -> bool {
matches!(
state,
JobState::Running | JobState::Queued | JobState::WaitingForInput
)
}
fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
mutex.lock().unwrap_or_else(PoisonError::into_inner)
}