use std::time::Instant;
use rho_sdk::{BoundaryInputRequest, InputBoundary, Session, UserInput};
use tokio::sync::mpsc;
use crate::{
app::{
boundary_results::BoundaryResults,
subagent_manager::{SubagentManager, SubagentNotification},
subagent_messaging::{NoticePermits, SubagentNotice},
},
display_transcript::DisplayTranscript,
session::SessionPersistence,
tools::{
process::{ProcessManager, ProcessNotification},
sdk_registry::AppToolSet,
workflow_tracker::{WorkflowNotification, WorkflowRunTracker},
},
};
pub(super) struct Delegation {
session_id: String,
requests: mpsc::Receiver<BoundaryInputRequest>,
subagents: Option<SubagentDelivery>,
processes: Option<ProcessManager>,
workflows: WorkflowRunTracker,
prompt_started: Instant,
background_wait: BackgroundWait,
displays: Option<mpsc::UnboundedSender<(UserInput, DisplayTranscript)>>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum BackgroundWait {
HoldPrompt,
HostWakes,
HostTurns,
}
impl BackgroundWait {
pub(super) fn of(children: super::ChildAgents, idle_turns: super::IdleTurns) -> Self {
match (children, idle_turns) {
(super::ChildAgents::HostThreads, _) => Self::HostWakes,
(super::ChildAgents::InProcess, super::IdleTurns::Host) => Self::HostTurns,
(super::ChildAgents::InProcess, super::IdleTurns::Never) => Self::HoldPrompt,
}
}
}
struct SubagentDelivery {
manager: SubagentManager,
notices: mpsc::Receiver<SubagentNotice>,
permits: NoticePermits,
pending: Vec<SubagentNotice>,
}
pub(super) struct HeldNotices(SubagentDelivery);
pub(super) struct BackgroundSources<'a> {
pub(super) subagents: Option<&'a SubagentManager>,
pub(super) processes: Option<&'a ProcessManager>,
pub(super) workflows: &'a WorkflowRunTracker,
}
impl<'a> BackgroundSources<'a> {
pub(super) fn of(tools: &'a AppToolSet) -> Self {
Self {
subagents: tools.subagents(),
processes: tools.processes(),
workflows: tools.workflow_tracker(),
}
}
pub(super) fn has_work(&self, session_id: &str) -> bool {
self.subagents
.is_some_and(|manager| manager.has_active_or_pending_notification(session_id))
|| self
.workflows
.has_active_or_pending_notification(session_id)
|| self.processes.is_some_and(|processes| {
processes.has_live() || processes.has_pending_notification()
})
}
}
impl HeldNotices {
pub(super) fn has_undelivered(&self) -> bool {
let Self(delivery) = self;
!delivery.pending.is_empty() || !delivery.notices.is_empty()
}
}
impl Delegation {
pub(super) fn attach(
session: &Session,
sources: BackgroundSources<'_>,
wait: BackgroundWait,
storage: Option<&crate::session::Session>,
persistence: SessionPersistence,
held: &mut Option<HeldNotices>,
) -> Result<Self, rho_sdk::Error> {
let (source, requests) = rho_sdk::boundary_input_channel();
session.set_boundary_inputs(Some(source))?;
let session_id = session.id().to_string();
let mut held = held.take().map(|HeldNotices(delivery)| delivery);
let subagents = sources.subagents.map(|manager| {
manager.bind_parent_session(session_id.clone(), storage, persistence);
held.take().unwrap_or_else(|| {
let binding = manager.rebind_notices(None);
SubagentDelivery {
manager: manager.clone(),
notices: binding.receiver,
permits: binding.permits,
pending: binding.retained,
}
})
});
let workflows = sources.workflows.clone();
workflows.bind_parent_session(session_id.clone());
Ok(Self {
session_id,
requests,
subagents,
processes: sources.processes.cloned(),
workflows,
prompt_started: Instant::now(),
background_wait: wait,
displays: None,
})
}
pub(super) fn offered_displays(&mut self) -> OfferedDisplays {
let (sender, receiver) = mpsc::unbounded_channel();
self.displays = Some(sender);
OfferedDisplays { receiver }
}
pub(super) async fn drive<T>(host: &mut Self, run: impl std::future::Future<Output = T>) -> T {
let service = host.serve();
tokio::pin!(service);
let result = tokio::select! {
biased;
() = &mut service => unreachable!(),
result = run => result,
};
let _ = futures_util::poll!(&mut service);
result
}
pub(super) fn hold_notices(mut self) -> Option<HeldNotices> {
self.subagents.take().map(HeldNotices)
}
async fn serve(&mut self) {
while let Some(request) = self.requests.recv().await {
self.respond(request).await;
}
std::future::pending().await
}
async fn respond(&mut self, request: BoundaryInputRequest) {
let boundary = request.boundary();
let mut notices_open = true;
let (receipt, mut reservation, notices_offered) = loop {
let process_exit = self.processes.as_ref().map(ProcessManager::notified_owned);
let workflow_finish = self.workflows.notified_owned();
{
let _delivery = crate::app::notification_delivery::lock();
let batch = self.collect();
let due = batch.has_results()
|| self.subagents.as_ref().is_some_and(|subagents| {
subagents
.pending
.iter()
.any(|notice| notice.delivery.requires_parent_action())
})
|| boundary == InputBoundary::BeforeProvider;
if due || !self.has_outstanding_work() {
let notices_offered = due
|| match self.background_wait {
BackgroundWait::HoldPrompt | BackgroundWait::HostWakes => true,
BackgroundWait::HostTurns => false,
};
let rendered = if notices_offered {
self.render(&batch)
} else {
None
};
let input = rendered.map(|(model, display)| {
let input = UserInput::text(model);
if let Some(sink) = &self.displays {
let _ = sink.send((input.clone(), display));
}
input
});
break (request.respond(input), batch, notices_offered);
}
}
let process_exit = async move {
match process_exit {
Some(exit) => exit.await,
None => std::future::pending().await,
}
};
match &mut self.subagents {
Some(subagents) => tokio::select! {
notice = subagents.notices.recv(), if notices_open => {
if let Some(notice) = notice {
subagents.pending.push(notice);
} else {
notices_open = false;
}
}
() = subagents.manager.wait_for_notification(&self.session_id) => {}
() = process_exit => {}
() = workflow_finish => {}
},
None => tokio::select! {
() = process_exit => {}
() = workflow_finish => {}
},
}
};
if receipt.await {
reservation.commit();
if notices_offered {
if let Some(subagents) = &mut self.subagents {
for notice in subagents.pending.drain(..) {
notice.acknowledge();
subagents.permits.release_notice(¬ice);
}
}
}
}
}
fn collect(&mut self) -> DeliveryReservation {
let subagent_results = match &mut self.subagents {
Some(subagents) => {
while let Ok(notice) = subagents.notices.try_recv() {
subagents.pending.push(notice);
}
let permits = &subagents.permits;
subagents.pending.retain(|notice| {
if notice.is_acknowledged() {
permits.release_notice(notice);
false
} else {
true
}
});
subagents.manager.take_notifications(&self.session_id)
}
None => Vec::new(),
};
DeliveryReservation {
subagents: self
.subagents
.as_ref()
.map(|subagents| subagents.manager.clone()),
subagent_results,
workflows: self.workflows.clone(),
workflow_results: self.workflows.take_notifications(&self.session_id),
processes: self.processes.clone(),
process_results: self
.processes
.as_ref()
.map(ProcessManager::take_notifications)
.unwrap_or_default(),
}
}
fn render(&self, batch: &DeliveryReservation) -> Option<(String, DisplayTranscript)> {
BoundaryResults {
notices: self
.subagents
.as_ref()
.map(|subagents| subagents.pending.as_slice())
.unwrap_or_default(),
subagents: &batch.subagent_results,
workflows: &batch.workflow_results,
processes: &batch.process_results,
}
.render(self.subagents.as_ref().map(|subagents| &subagents.manager))
.finish()
}
fn has_outstanding_work(&self) -> bool {
let subagents = match self.background_wait {
BackgroundWait::HoldPrompt | BackgroundWait::HostWakes => {
self.subagents.as_ref().is_some_and(|subagents| {
subagents
.manager
.has_active_or_pending_notification(&self.session_id)
})
}
BackgroundWait::HostTurns => false,
};
let finished = self.workflows.has_pending_notification(&self.session_id)
|| self
.processes
.as_ref()
.is_some_and(ProcessManager::has_pending_notification);
let running = match self.background_wait {
BackgroundWait::HoldPrompt => {
self.workflows
.has_live_started_since(&self.session_id, self.prompt_started)
|| self.processes.as_ref().is_some_and(|processes| {
processes.has_live_started_since(self.prompt_started)
})
}
BackgroundWait::HostWakes | BackgroundWait::HostTurns => false,
};
subagents || finished || running
}
}
pub(super) struct OfferedDisplays {
receiver: mpsc::UnboundedReceiver<(UserInput, DisplayTranscript)>,
}
impl OfferedDisplays {
pub(super) fn applied(&mut self, input: &UserInput) -> Option<DisplayTranscript> {
while let Ok((offered, display)) = self.receiver.try_recv() {
if offered == *input {
return Some(display);
}
}
None
}
}
impl Drop for Delegation {
fn drop(&mut self) {
let Some(subagents) = &mut self.subagents else {
return;
};
let _delivery = crate::app::notification_delivery::lock();
subagents.manager.unbind_notices();
while let Ok(notice) = subagents.notices.try_recv() {
subagents.pending.push(notice);
}
for notice in subagents.pending.drain(..) {
subagents.permits.release_notice(¬ice);
}
}
}
struct DeliveryReservation {
subagents: Option<SubagentManager>,
subagent_results: Vec<SubagentNotification>,
workflows: WorkflowRunTracker,
workflow_results: Vec<WorkflowNotification>,
processes: Option<ProcessManager>,
process_results: Vec<ProcessNotification>,
}
impl DeliveryReservation {
fn has_results(&self) -> bool {
!self.subagent_results.is_empty()
|| !self.workflow_results.is_empty()
|| !self.process_results.is_empty()
}
fn commit(&mut self) {
self.subagent_results.clear();
self.workflow_results.clear();
self.process_results.clear();
}
}
impl Drop for DeliveryReservation {
fn drop(&mut self) {
if let Some(subagents) = &self.subagents {
subagents.restore_notifications(&self.subagent_results);
}
self.workflows.restore_notifications(&self.workflow_results);
if let Some(processes) = &self.processes {
processes.restore_notifications(&self.process_results);
}
}
}
#[cfg(test)]
#[path = "delegation_tests.rs"]
mod tests;