rho-coding-agent 3.7.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! Closing and deleting the sessions this process has open, as the host
//! asks or as its connection ends.
//!
//! ACP v1 closes by detaching ([`Close::Detach`]): this host's prompt is
//! cancelled and the rest of the session's work runs on in the daemon. ACP
//! v2 closes by stopping that work ([`Close::Stop`]) before it answers:
//! held prompts, the turn under way, whoever's, the background work, and
//! the input requests open on the host. Both end with [`Adapter::release`],
//! after which the host hears nothing more of the session. The
//! connection's end only detaches, on either version.

use std::sync::atomic::Ordering;

use agent_client_protocol::{
    v1::schema::{
        CloseSessionRequest, CloseSessionResponse, DeleteSessionRequest, DeleteSessionResponse,
        SessionId as AcpSessionId,
    },
    Error as AcpError,
};
use rho_protocol::{
    methods::{SessionBackgroundHold, SessionBackgroundStop, SessionDelete, SessionDetach},
    BackgroundItem, DeleteWork, ErrorCode, SessionBackgroundHoldParams,
    SessionBackgroundStopParams, SessionDeleteParams, SessionDetachParams, SessionId,
};

use super::{lock, Attachment, Live};
use crate::app::acp::{daemon, Adapter};

/// What closing a session does with its work.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(in crate::app::acp) enum Close {
    /// Stops relaying it, as ACP v1 does: this host's prompt is cancelled,
    /// and the rest, another client's turn and the background work, runs
    /// on in the daemon.
    Detach,
    /// Stops it, as ACP v2 requires: its held prompts and its turn,
    /// whoever's, are cancelled, its background work is stopped, and its
    /// open input requests are withdrawn from the host, before the host is
    /// answered, and the host hears nothing of it after.
    Stop,
}

impl Close {
    /// What deleting the session does with the work the daemon still has
    /// once it is closed so: a turn another client runs, and background
    /// work.
    fn delete_work(self) -> DeleteWork {
        match self {
            Self::Detach => DeleteWork::Refuse,
            Self::Stop => DeleteWork::Stop,
        }
    }
}

/// What closing a session waits for once it cancelled this host's prompt.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Wait {
    /// The prompt's end.
    Prompt,
    /// The prompt's end, then the cancelled turn's job's, so the session
    /// can be deleted.
    Job,
}

impl Adapter {
    /// Stops relaying `live`: cancels this host's prompt and waits as
    /// `wait` says, then detaches. The session stays in the daemon.
    pub(super) async fn detach(&self, live: &Live, wait: Wait) {
        // Before the cancel, so a prompt queued behind the cancelled one
        // sees it once it gets the lock.
        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;
            }
        }
        self.release(live).await;
    }

    /// Stops `live`'s work, then its relaying, as ACP v2 `session/close`
    /// requires; the session stays in the daemon. Its results are held for
    /// its next turn first, so neither the work's end nor the cancel has
    /// the daemon start a turn to deliver them. Its held prompts are
    /// dropped and its turn, whoever's, is cancelled, and the host hears
    /// that turn end before this returns. Then its running background work
    /// is stopped, and the relaying ends as [`Self::release`] says.
    async fn stop(&self, live: &Live) {
        // Before the cancel, so a prompt queued behind the cancelled one
        // sees it once it gets the lock.
        live.closing.store(true, Ordering::Release);
        self.hold_results(live).await;
        self.cancel_live(live).await;
        // This host's prompt, whose turn's end the pump reported first.
        drop(live.prompt.lock().await);
        // Any other turn, another client's or one the daemon started, which
        // the pump follows and reports the end of before the job's idle
        // state; an attachment that ended reports none busy.
        let mut attachment = live.shared.attachment.subscribe();
        let _ = attachment.wait_for(|attachment| !attachment.busy()).await;
        // Again, since a turn starting clears the hold, as a prompt of this
        // host's that reached the daemon after the first does; none can
        // start now, so the stops' results are held.
        self.hold_results(live).await;
        // A stale or deleted attachment's work list is out of date. A daemon
        // that is gone is not started again to hear the stops.
        let attached = matches!(*live.shared.attachment.borrow(), Attachment::Attached(_));
        if let (true, Some(link)) = (attached, self.daemon.current().await) {
            let running: Vec<BackgroundItem> = lock(&live.shared.background)
                .iter()
                .filter(|work| work.status.is_running())
                .map(|work| work.item.clone())
                .collect();
            for work in running {
                let params = SessionBackgroundStopParams {
                    session: live.id.clone(),
                    work,
                };
                if let Err(error) = link.request::<SessionBackgroundStop>(&params).await {
                    // Work that ended meanwhile.
                    tracing::debug!(%error, "could not stop an ACP session's background work");
                }
            }
        }
        self.release(live).await;
    }

    /// Has the daemon hold `live`'s background results for its next turn
    /// ([`rho_protocol::SESSION_BACKGROUND_HOLD`]). A daemon that has not
    /// loaded the session, or is gone, starts no turn for them either.
    async fn hold_results(&self, live: &Live) {
        let Some(link) = self.daemon.current().await else {
            return;
        };
        let params = SessionBackgroundHoldParams {
            session: live.id.clone(),
        };
        if let Err(error) = link.request::<SessionBackgroundHold>(&params).await {
            tracing::debug!(%error, "could not hold an ACP session's background results");
        }
    }

    /// Ends relaying `live` once its turn is done with: its routing and pump
    /// stop, the input requests the pump has open are withdrawn from the
    /// host, the child sessions the host was told of stop being relayed
    /// ([`AcpClientPort::released`]), and it is detached from the daemon.
    /// The host hears nothing more of it once this returns.
    ///
    /// [`AcpClientPort::released`]: crate::app::acp::AcpClientPort::released
    async fn release(&self, live: &Live) {
        let attachment = *live.shared.attachment.borrow();
        self.forget(live);
        // The pump is gone once its receiver is, after anything it was
        // sending; its input tasks, aborted with it, withdraw their host
        // requests as they go.
        live.inbound.closed().await;
        live.asks.withdrawn().await;
        // Its children with it: their relays stop, and the host may no
        // longer name them.
        if let Some(port) = self.negotiated.client() {
            port.released(&AcpSessionId::new(live.id.as_str()));
        }
        // A stale or deleted attachment has nothing left to detach.
        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>(&params).await {
                tracing::debug!(%error, "could not detach an ACP session");
            }
        }
    }

    /// Stops `live`'s routing and pump; what the daemon still sends for it
    /// is dropped.
    pub(super) fn forget(&self, live: &Live) {
        self.daemon.unroute(&live.id);
        live.pump.abort();
    }

    /// `session/close`: stops relaying the session, and its work as `close`
    /// says; it stays saved.
    pub(in crate::app::acp) async fn close_session(
        &self,
        request: &CloseSessionRequest,
        close: Close,
    ) -> Result<CloseSessionResponse, AcpError> {
        if let Some(live) = self.sessions.remove(&request.session_id.0) {
            match close {
                Close::Detach => self.detach(&live, Wait::Prompt).await,
                Close::Stop => self.stop(&live).await,
            }
        }
        Ok(CloseSessionResponse::new())
    }

    /// Detaches every session, as when the host disconnects or this
    /// process is told to stop: the connection's end leaves its sessions'
    /// work running, on ACP v2 too.
    pub(in crate::app::acp) async fn close_all(&self) {
        for live in self.sessions.take_all() {
            self.detach(&live, Wait::Prompt).await;
        }
        let _ = self.herdr.release().await;
    }

    /// `session/delete`. Hosts such as Zed delete from history without
    /// closing the thread, so a session open here is closed first, as
    /// `close` says: detached once its turn ends, or stopped. A stopped
    /// session's delete, open here or not, has the daemon cancel a turn
    /// another client runs and end the background work it still has, where
    /// a detached one's refuses while there is either. Deleting
    /// converges: a session that is already gone, or never was, is deleted.
    pub(in crate::app::acp) async fn delete_session(
        &self,
        request: &DeleteSessionRequest,
        close: Close,
    ) -> Result<DeleteSessionResponse, AcpError> {
        if let Some(live) = self.sessions.remove(&request.session_id.0) {
            match close {
                Close::Detach => self.detach(&live, Wait::Job).await,
                Close::Stop => self.stop(&live).await,
            }
        }
        let params = SessionDeleteParams {
            session: SessionId::new(request.session_id.0.as_ref()),
            unless_attached: false,
            work: close.delete_work(),
        };
        let link = self.daemon.link().await?;
        match link.request::<SessionDelete>(&params).await {
            Ok(_) => {}
            Err(error) if error.error_code() == Some(ErrorCode::SessionNotFound) => {}
            Err(error) => return Err(daemon::daemon_error(&error)),
        }
        Ok(DeleteSessionResponse::new())
    }
}