use std::{
collections::{BTreeMap, BTreeSet},
future::Future,
pin::Pin,
};
use futures_util::stream::{FuturesUnordered, StreamExt};
use rho_sdk::{
hooks::HookDispatcher, ApprovalRequestReceiver, CancellationToken, HostInputId,
HostInputRefusal, HostInputResponse, PendingApproval, RunEvent, SessionId, UserInput,
};
use tokio::sync::{mpsc, oneshot};
use super::{
delegation::OfferedDisplays,
events::{
cancelled_approval, ApprovalId, PlanApprovalId, PlanApprovalRequest, SecretAskId,
SessionEvent, TurnControl,
},
persist::TurnCheckpoint,
turn::TurnIo,
QuestionSupport,
};
use crate::{
diagnostics::RuntimeDiagnostics,
display_transcript::DisplayTranscript,
tools::{
mcp::secret_tool::{PendingSecret, SecretOutcome, SecretRequestReceiver},
plan_exit::{PlanExitDecision, PlanPermissionReceiver, PlanPermissionRequest},
},
};
pub(super) enum EventSource<'a> {
Run(&'a mut rho_sdk::Run),
#[cfg(test)]
Channel(&'a mut tokio::sync::mpsc::UnboundedReceiver<RunEvent>),
}
impl EventSource<'_> {
async fn next(&mut self) -> Option<RunEvent> {
match self {
Self::Run(run) => run.next_event().await,
#[cfg(test)]
Self::Channel(events) => events.recv().await,
}
}
fn cancel_run(&mut self) {
match self {
Self::Run(run) => run.cancel(),
#[cfg(test)]
Self::Channel(_) => {}
}
}
fn answer(&mut self, id: HostInputId, answer: HostInputAnswer) {
match self {
Self::Run(run) => {
let queued = match answer {
Ok(response) => run.request_respond(id, response).map(drop),
Err(refusal) => run.request_refuse(id, refusal).map(drop),
};
if let Err(error) = queued {
tracing::warn!(%error, "could not answer a host input request");
}
}
#[cfg(test)]
Self::Channel(_) => {}
}
}
}
type HostInputAnswer = Result<HostInputResponse, HostInputRefusal>;
pub(super) enum ApprovalSource<'a> {
Receiver(Option<&'a mut ApprovalRequestReceiver>),
#[cfg(test)]
Channel(&'a mut tokio::sync::mpsc::UnboundedReceiver<PendingApproval>),
}
impl ApprovalSource<'_> {
async fn next(&mut self) -> Option<PendingApproval> {
match self {
Self::Receiver(None) => std::future::pending().await,
Self::Receiver(Some(receiver)) => receiver.recv().await,
#[cfg(test)]
Self::Channel(approvals) => approvals.recv().await,
}
}
}
pub(super) struct PumpSources<'a> {
pub(super) cancel: CancellationToken,
pub(super) questions: QuestionSupport,
pub(super) events: EventSource<'a>,
pub(super) approvals: ApprovalSource<'a>,
pub(super) plan_approvals: Option<&'a mut PlanPermissionReceiver>,
pub(super) secret_asks: Option<&'a mut SecretRequestReceiver>,
pub(super) displays: Option<AppliedDisplays<'a>>,
pub(super) hooks: HookDispatcher,
pub(super) session: &'a SessionId,
pub(super) diagnostics: &'a RuntimeDiagnostics,
}
pub(super) struct AppliedDisplays<'a> {
pub(super) offered: OfferedDisplays,
pub(super) checkpoint: &'a TurnCheckpoint,
}
impl AppliedDisplays<'_> {
fn record(&mut self, input: &UserInput) -> Option<DisplayTranscript> {
let transcript = self.offered.applied(input)?;
self.checkpoint
.record_display(input, transcript.display_message());
Some(transcript)
}
}
type ToolWait = Pin<Box<dyn Future<Output = Settled> + Send>>;
enum Settled {
Answered,
PlanWithdrawn(PlanApprovalId),
SecretWithdrawn(SecretAskId),
}
#[derive(Default)]
struct Pending {
approvals: BTreeMap<ApprovalId, PendingApproval>,
plans: BTreeMap<PlanApprovalId, oneshot::Sender<PlanExitDecision>>,
secrets: BTreeMap<SecretAskId, oneshot::Sender<SecretOutcome>>,
questions: BTreeSet<HostInputId>,
next_approval: u64,
next_plan: u64,
next_secret: u64,
}
pub(super) async fn pump(sources: PumpSources<'_>, io: &mut TurnIo) -> anyhow::Result<()> {
let PumpSources {
cancel,
questions,
mut events,
mut approvals,
mut plan_approvals,
mut secret_asks,
mut displays,
hooks,
session,
diagnostics,
} = sources;
let mut cancelled = cancel.is_cancelled();
let mut events_open = true;
let mut approvals_open = true;
let mut pending = Pending::default();
let mut tool_waits: FuturesUnordered<ToolWait> = FuturesUnordered::new();
loop {
if !events_open && pending.approvals.is_empty() && tool_waits.is_empty() {
return Ok(());
}
tokio::select! {
biased;
() = cancel.cancelled(), if !cancelled => {
cancelled = true;
events.cancel_run();
for (id, mut approval) in std::mem::take(&mut pending.approvals) {
let _ = approval.respond(cancelled_approval());
io.emit(SessionEvent::ApprovalWithdrawn { id });
}
tool_waits.clear();
for id in std::mem::take(&mut pending.plans).into_keys() {
io.emit(SessionEvent::PlanApprovalWithdrawn { id });
}
for id in std::mem::take(&mut pending.secrets).into_keys() {
io.emit(SessionEvent::SecretWithdrawn { id });
}
withdraw_questions(&mut pending, io);
}
event = events.next(), if events_open => {
let Some(event) = event else {
events_open = false;
withdraw_questions(&mut pending, io);
io.emit(SessionEvent::RunClosed);
continue;
};
if let (RunEvent::BoundaryInputApplied { input, .. }, Some(displays)) =
(&event, displays.as_mut())
{
if let Some(transcript) = displays.record(input) {
io.emit(SessionEvent::BoundaryApplied { transcript });
}
}
diagnostics.observe_run_event(&event);
let asked = match &event {
RunEvent::HostInputRequested { request } => Some((request.clone(), None)),
RunEvent::ToolHostInputRequested { call_id, request } => {
Some((request.clone(), Some(call_id.clone())))
}
_ => None,
};
io.emit(SessionEvent::Run(event));
if let Some((request, call_id)) = asked {
match (questions, cancelled) {
(QuestionSupport::Available, false) => {
pending.questions.insert(request.id().clone());
io.emit(SessionEvent::QuestionAsked {
id: request.id().clone(),
call_id,
request: request.clone(),
});
hooks.question_requested(session, &request);
}
(QuestionSupport::Available, true) => {}
(QuestionSupport::Unavailable, _) => {
events.answer(request.id().clone(), Err(HostInputRefusal::Declined));
}
}
}
}
approval = approvals.next(), if events_open && approvals_open => {
let Some(mut approval) = approval else {
approvals_open = false;
continue;
};
if cancelled {
let _ = approval.respond(cancelled_approval());
continue;
}
let id = ApprovalId(pending.next_approval);
pending.next_approval += 1;
io.emit(SessionEvent::ApprovalRequested {
id,
request: approval.request().clone(),
});
hooks.approval_requested(session, approval.request());
pending.approvals.insert(id, approval);
}
request = next_request(plan_approvals.as_deref_mut()), if events_open => {
let Some(request) = request else {
plan_approvals = None;
continue;
};
if cancelled {
continue;
}
let id = PlanApprovalId(pending.next_plan);
pending.next_plan += 1;
let (answer, answered) = oneshot::channel();
io.emit(SessionEvent::PlanApprovalRequested {
id,
request: PlanApprovalRequest {
call_id: request.call_id.clone(),
plan: request.plan.clone(),
targets: request.targets.clone(),
},
});
hooks.plan_approval_requested(session, &request.plan);
pending.plans.insert(id, answer);
tool_waits.push(Box::pin(wait_for_plan(id, request, answered)));
}
asked = next_request(secret_asks.as_deref_mut()), if events_open => {
let Some(PendingSecret { request, reply }) = asked else {
secret_asks = None;
continue;
};
if cancelled {
continue;
}
let id = SecretAskId(pending.next_secret);
pending.next_secret += 1;
let (answer, answered) = oneshot::channel();
io.emit(SessionEvent::SecretRequested { id, request });
pending.secrets.insert(id, answer);
tool_waits.push(Box::pin(wait_for_secret(id, reply, answered)));
}
control = io.control.recv() => match control {
Some(TurnControl::RespondApproval { id, decision }) => {
if let Some(mut approval) = pending.approvals.remove(&id) {
let _ = approval.respond(decision);
}
}
Some(TurnControl::AnswerPlan { id, answer }) => {
if let Some(reply) = pending.plans.remove(&id) {
let _ = reply.send(answer);
}
}
Some(TurnControl::AnswerSecret { id, outcome }) => {
if let Some(reply) = pending.secrets.remove(&id) {
let _ = reply.send(outcome);
}
}
Some(TurnControl::AnswerQuestion { id, answer }) => {
if pending.questions.remove(&id) {
events.answer(id, answer);
}
}
Some(TurnControl::HostFailed { message }) => return Err(anyhow::Error::msg(message)),
None => anyhow::bail!("the host stopped answering the turn"),
},
Some(settled) = tool_waits.next(), if !tool_waits.is_empty() => match settled {
Settled::Answered => {}
Settled::PlanWithdrawn(id) => {
if pending.plans.remove(&id).is_some() {
io.emit(SessionEvent::PlanApprovalWithdrawn { id });
}
}
Settled::SecretWithdrawn(id) => {
if pending.secrets.remove(&id).is_some() {
io.emit(SessionEvent::SecretWithdrawn { id });
}
}
},
}
}
}
fn withdraw_questions(pending: &mut Pending, io: &TurnIo) {
for id in std::mem::take(&mut pending.questions) {
io.emit(SessionEvent::QuestionWithdrawn { id });
}
}
async fn next_request<T>(requests: Option<&mut mpsc::UnboundedReceiver<T>>) -> Option<T> {
match requests {
Some(requests) => requests.recv().await,
None => std::future::pending().await,
}
}
async fn wait_for_plan(
id: PlanApprovalId,
request: PlanPermissionRequest,
answered: oneshot::Receiver<PlanExitDecision>,
) -> Settled {
if relay(request.reply, answered).await {
Settled::Answered
} else {
Settled::PlanWithdrawn(id)
}
}
async fn wait_for_secret(
id: SecretAskId,
reply: oneshot::Sender<SecretOutcome>,
answered: oneshot::Receiver<SecretOutcome>,
) -> Settled {
if relay(reply, answered).await {
Settled::Answered
} else {
Settled::SecretWithdrawn(id)
}
}
async fn relay<T>(mut reply: oneshot::Sender<T>, answered: oneshot::Receiver<T>) -> bool {
tokio::select! {
biased;
() = reply.closed() => false,
answer = answered => match answer {
Ok(answer) => {
let _ = reply.send(answer);
true
}
Err(_) => false,
},
}
}
#[cfg(test)]
#[path = "pump_tests.rs"]
mod tests;