use agent_client_protocol::{
v2::{schema as v2, ActiveSession, SentRequest},
Agent, Error,
};
use std::collections::VecDeque;
use tokio::sync::{mpsc, oneshot};
use super::error;
pub(super) enum Inbound {
Update(Box<v2::UpdateSessionNotification>),
Took(Result<v2::PromptResponse, Error>),
Answered,
}
pub(super) struct Updates {
tx: mpsc::UnboundedSender<Inbound>,
rx: mpsc::UnboundedReceiver<Inbound>,
queued: VecDeque<Inbound>,
}
impl Updates {
pub(super) fn new() -> (Self, mpsc::UnboundedSender<Inbound>) {
let (tx, rx) = mpsc::unbounded_channel();
let updates = Self {
tx: tx.clone(),
rx,
queued: VecDeque::new(),
};
(updates, tx)
}
pub(super) async fn ask<T: Send + 'static>(
&mut self,
sent: SentRequest<T>,
) -> Result<T, Error> {
let (answer_tx, answer_rx) = oneshot::channel();
let tx = self.tx.clone();
sent.on_receiving_result(async move |answer| {
let _ = answer_tx.send(answer);
let _ = tx.send(Inbound::Answered);
Ok(())
})?;
self.answer(answer_rx).await
}
async fn answer<T>(&mut self, answer: oneshot::Receiver<Result<T, Error>>) -> Result<T, Error> {
loop {
let Some(inbound) = self.rx.recv().await else {
unreachable!("`self` holds a sender");
};
match inbound {
Inbound::Answered => break,
Inbound::Update(notification) if is_config(¬ification) => {}
other => self.queued.push_back(other),
}
}
answer
.await
.unwrap_or_else(|_| Err(error("acp: a setup answer was lost")))
}
pub(super) fn latest_options(&mut self, session: &str) -> Option<Vec<v2::SessionConfigOption>> {
let mut latest = None;
while let Ok(inbound) = self.rx.try_recv() {
match inbound {
Inbound::Update(notification)
if is_config(¬ification)
&& notification.session_id.to_string() == session =>
{
if let v2::SessionUpdate::ConfigOptionUpdate(update) = notification.update {
latest = Some(update.config_options);
}
}
other => self.queued.push_back(other),
}
}
latest
}
pub(super) fn prompting(&mut self) {
while let Ok(inbound) = self.rx.try_recv() {
self.queued.push_back(inbound);
}
self.queued.retain(|inbound| {
!matches!(
inbound,
Inbound::Update(notification)
if matches!(notification.update, v2::SessionUpdate::StateUpdate(_))
)
});
}
pub(super) fn prompt(
&self,
session: &ActiveSession<Agent>,
prompt: Vec<v2::ContentBlock>,
) -> Result<(), Error> {
let tx = self.tx.clone();
session
.send_prompt_blocks(prompt)
.on_receiving_result(async move |took| {
let _ = tx.send(Inbound::Took(took));
Ok(())
})
}
pub(super) async fn next(&mut self) -> Option<Inbound> {
match self.queued.pop_front() {
Some(inbound) => Some(inbound),
None => self.rx.recv().await,
}
}
}
fn is_config(notification: &v2::UpdateSessionNotification) -> bool {
matches!(
notification.update,
v2::SessionUpdate::ConfigOptionUpdate(_)
)
}
#[cfg(test)]
#[path = "inbound_tests.rs"]
mod tests;