use std::{
collections::HashMap,
path::PathBuf,
sync::{Arc, Mutex, MutexGuard, PoisonError},
};
use rho_protocol::{AnswerStop, DetachReason, TurnError, TurnErrorKind, TurnOutcome};
use rho_sdk::CancellationToken;
use tokio::sync::{oneshot, watch};
use super::{
jobs::{
JobAgent, JobEvent, JobId, JobRecord, JobRegistry, JobState, Moved, RegisterError,
TransitionError, TurnEnd,
},
sessions::{ChildFeeds, ChildStream},
};
use crate::{
app::{
agent_binding::CapacityClass,
agent_concurrency::{AgentConcurrency, QueuePlace, QueueWatch, QueuedRun},
subagent_pool::{
ChildEvent, ChildEvents, ChildObserver, HostedWorkflow, StartedSubagent,
StartedWorkflow, SubagentPool, WorkflowEnd,
},
},
config::DEFAULT_AGENT_CONCURRENCY,
subagent::{RunState, RunStatus},
};
pub(super) struct Subagents {
concurrency: AgentConcurrency,
jobs: Arc<JobRegistry>,
queues: Queues,
feeds: ChildFeeds,
stopping: CancellationToken,
}
type Queues = Arc<Mutex<HashMap<JobId, QueueWatch>>>;
impl Subagents {
pub(super) fn new(jobs: Arc<JobRegistry>, stopping: CancellationToken) -> Self {
Self {
concurrency: AgentConcurrency::from_config(DEFAULT_AGENT_CONCURRENCY),
jobs,
queues: Queues::default(),
feeds: ChildFeeds::default(),
stopping,
}
}
pub(super) fn feeds(&self) -> &ChildFeeds {
&self.feeds
}
pub(super) fn concurrency(&self) -> AgentConcurrency {
self.concurrency.clone()
}
pub(super) fn pool_for(&self, parent: JobId) -> SubagentPool {
SubagentPool::Shared {
concurrency: self.concurrency.clone(),
observer: Arc::new(ChildJobs {
parent,
jobs: Arc::clone(&self.jobs),
queues: Arc::clone(&self.queues),
feeds: self.feeds.clone(),
stopping: self.stopping.clone(),
}),
}
}
pub(super) fn queue_turn(&self, job: &JobId) -> TurnBudget {
let line = TurnLine {
job: job.clone(),
concurrency: self.concurrency.clone(),
queues: Arc::clone(&self.queues),
};
let (queued, listing) = line.join();
TurnBudget {
queued,
line,
listing,
}
}
pub(super) fn queue_place(&self, job: &JobId) -> Option<QueuePlace> {
lock(&self.queues).get(job)?.place()
}
}
pub(super) struct TurnBudget {
pub(super) queued: QueuedRun,
pub(super) line: TurnLine,
pub(super) listing: Listing,
}
#[derive(Clone)]
pub(super) struct TurnLine {
job: JobId,
concurrency: AgentConcurrency,
queues: Queues,
}
impl TurnLine {
pub(super) fn join(&self) -> (QueuedRun, Listing) {
let queued = self.concurrency.join(CapacityClass::Rho);
lock(&self.queues).insert(self.job.clone(), queued.watch());
let listing = Listing {
job: self.job.clone(),
queues: Arc::clone(&self.queues),
};
(queued, listing)
}
pub(super) fn limit(&self) -> usize {
self.concurrency.total_limit()
}
}
pub(super) struct Listing {
job: JobId,
queues: Queues,
}
impl Drop for Listing {
fn drop(&mut self) {
lock(&self.queues).remove(&self.job);
}
}
fn listed_workspace(workspace: PathBuf) -> PathBuf {
crate::paths::without_verbatim_prefix(workspace)
}
#[derive(Clone)]
struct ChildJobs {
parent: JobId,
jobs: Arc<JobRegistry>,
queues: Queues,
feeds: ChildFeeds,
stopping: CancellationToken,
}
impl ChildObserver for ChildJobs {
fn workflow_started(&self, run: StartedWorkflow) -> HostedWorkflow {
let StartedWorkflow { run_id, workspace } = run;
let workspace = listed_workspace(workspace);
let (end, ended) = oneshot::channel();
let record = JobRecord::new_workflow(self.parent.clone(), workspace, run_id);
let job = record.id.clone();
if let Err(error) = self.jobs.register(record) {
unlisted(&error, &self.parent, &run_id.to_string(), "workflow");
return HostedWorkflow {
observer: Arc::new(self.clone()),
end,
};
}
tracing::info!(parent = %self.parent, %job, run = %run_id, "workflow run started");
tokio::spawn(follow_workflow(
job.clone(),
ended,
Arc::clone(&self.jobs),
self.stopping.clone(),
));
HostedWorkflow {
observer: Arc::new(Self {
parent: job,
..self.clone()
}),
end,
}
}
fn subagent_started(&self, run: StartedSubagent) {
let StartedSubagent {
run_id,
session,
workspace,
status,
queue,
events,
task,
} = run;
let workspace = listed_workspace(workspace);
let (worktree, agent, title) = {
let status = status.borrow();
(
status.worktree.clone(),
run_agent(&status),
status.title.clone().or(task),
)
};
let record = JobRecord {
agent,
title,
..JobRecord::new_subagent(
self.parent.clone(),
workspace.clone(),
session.as_ref().map(|session| session.id().clone()),
run_id.clone(),
worktree,
)
};
let job = record.id.clone();
let followed = session.zip(events).map(|(session, events)| Followed {
events: Some(events),
stream: self
.feeds
.list(session.id().clone(), workspace, &record.state),
});
if let Err(error) = self.jobs.register(record) {
unlisted(&error, &self.parent, &run_id, "subagent");
return;
}
tracing::info!(parent = %self.parent, %job, run = %run_id, "subagent run started");
lock(&self.queues).insert(job.clone(), queue);
tokio::spawn(record_title(
job.clone(),
status.clone(),
Arc::clone(&self.jobs),
self.stopping.clone(),
));
tokio::spawn(follow(
job,
status,
followed,
Arc::clone(&self.jobs),
Arc::clone(&self.queues),
self.stopping.clone(),
));
}
}
fn unlisted(error: &RegisterError, parent: &JobId, run: &str, kind: &str) {
match error {
RegisterError::Closed => {
tracing::info!(%parent, run, kind, "daemon stopping; a run started during the stop goes on unlisted");
}
RegisterError::Io(error) => {
tracing::error!(%parent, run, kind, %error, "could not record a run's job; the run goes on unlisted");
}
}
}
struct Followed {
events: Option<ChildEvents>,
stream: ChildStream,
}
impl Followed {
async fn next(&mut self) -> ChildEvent {
loop {
match &mut self.events {
Some(events) => match events.recv().await {
Some(event) => return event,
None => self.events = None,
},
None => return std::future::pending().await,
}
}
}
fn show_status(&self, status: &RunStatus) {
if let Some(title) = &status.title {
self.stream.titled(title);
}
}
fn show(&self, event: ChildEvent, status: &RunStatus) {
match event {
ChildEvent::Opened { options, agent } => {
self.stream.open(*options, agent);
self.show_status(status);
}
ChildEvent::Session(event) => self.stream.publish([event]),
}
}
fn show_rest(&mut self, status: &RunStatus) {
while let Some(event) = self
.events
.as_mut()
.and_then(|events| events.try_recv().ok())
{
self.show(event, status);
}
}
}
fn record_and_tell(
jobs: &JobRegistry,
job: &JobId,
event: JobEvent,
followed: &mut Option<Followed>,
run: &RunStatus,
) -> Result<Moved, TransitionError> {
let Some(followed) = followed else {
return jobs.record(job, event);
};
let ended = if let JobEvent::TurnEnded(end) = &event {
followed.show_rest(run);
outcome(end, run)
} else {
None
};
followed.stream.record(|| jobs.record(job, event), ended)
}
pub(in crate::app::daemon_host) fn outcome(end: &TurnEnd, run: &RunStatus) -> Option<TurnOutcome> {
match end {
TurnEnd::Completed => Some(TurnOutcome::Answered {
text: run.result.clone().unwrap_or_default(),
stop: AnswerStop::EndTurn,
}),
TurnEnd::Cancelled => Some(TurnOutcome::Cancelled),
TurnEnd::Failed(message) => Some(TurnOutcome::Failed {
error: TurnError {
kind: TurnErrorKind::Other,
message: message.clone(),
},
}),
TurnEnd::Interrupted => None,
TurnEnd::TimedOut { .. } => None,
}
}
async fn record_title(
job: JobId,
mut status: watch::Receiver<RunStatus>,
jobs: Arc<JobRegistry>,
stopping: CancellationToken,
) {
let titled = tokio::select! {
titled = status.wait_for(|status| status.title.is_some()) => {
titled.ok().and_then(|status| status.title.clone())
}
() = stopping.cancelled() => None,
};
if let Some(title) = titled {
jobs.set_title(&job, &title);
}
}
async fn follow(
job: JobId,
mut status: watch::Receiver<RunStatus>,
mut followed: Option<Followed>,
jobs: Arc<JobRegistry>,
queues: Queues,
stopping: CancellationToken,
) {
let mut state = JobState::Queued;
loop {
let run = status.borrow_and_update().clone();
if let Some(followed) = &followed {
followed.show_status(&run);
}
if let Some(event) = next_event(&state, &run, stopping.is_cancelled()) {
match record_and_tell(&jobs, &job, event, &mut followed, &run) {
Ok(next) => state = next.state,
Err(error) => {
tracing::debug!(%job, %error, "subagent job already ended");
break;
}
}
}
if run.state.is_terminal() {
break;
}
let changed = loop {
tokio::select! {
changed = status.changed() => break changed,
event = next_child_event(&mut followed) => {
if let Some(followed) = &followed {
followed.show(event, &status.borrow());
}
}
}
};
if changed.is_err() {
let end = if stopping.is_cancelled() {
TurnEnd::Interrupted
} else {
TurnEnd::Failed("the subagent run ended without a status".into())
};
if let Err(error) =
record_and_tell(&jobs, &job, JobEvent::TurnEnded(end), &mut followed, &run)
{
tracing::debug!(%job, %error, "subagent job already ended");
}
break;
}
}
if let Some(followed) = followed.filter(|_| stopping.is_cancelled()) {
followed.stream.close(DetachReason::DaemonStopping);
}
lock(&queues).remove(&job);
}
async fn next_child_event(followed: &mut Option<Followed>) -> ChildEvent {
match followed {
Some(followed) => followed.next().await,
None => std::future::pending().await,
}
}
async fn follow_workflow(
job: JobId,
ended: oneshot::Receiver<WorkflowEnd>,
jobs: Arc<JobRegistry>,
stopping: CancellationToken,
) {
let end = workflow_end(ended.await.ok(), stopping.is_cancelled());
if let Err(error) = jobs.record(&job, JobEvent::TurnEnded(end)) {
tracing::debug!(%job, %error, "workflow job already ended");
}
}
fn workflow_end(ended: Option<WorkflowEnd>, stopping: bool) -> TurnEnd {
match ended {
Some(WorkflowEnd::Completed) => TurnEnd::Completed,
Some(WorkflowEnd::Cancelled) => TurnEnd::Cancelled,
Some(WorkflowEnd::Failed(error)) => TurnEnd::Failed(error),
None if stopping => TurnEnd::Interrupted,
None => TurnEnd::Failed("the workflow run stopped without an end".into()),
}
}
fn next_event(state: &JobState, run: &RunStatus, stopping: bool) -> Option<JobEvent> {
match run.state {
RunState::Queued => match state {
JobState::Running => Some(JobEvent::SlotWanted),
JobState::Idle
| JobState::Queued
| JobState::Requeued
| JobState::WaitingForInput
| JobState::Ended(_) => None,
},
RunState::Starting | RunState::Running => match state {
JobState::Queued | JobState::Requeued => Some(JobEvent::Admitted),
JobState::Idle | JobState::Running | JobState::WaitingForInput | JobState::Ended(_) => {
None
}
},
RunState::Ok | RunState::Error | RunState::Stopped => run_end(run, stopping)
.filter(|_| state.in_progress())
.map(JobEvent::TurnEnded),
}
}
pub(in crate::app::daemon_host) fn run_end(run: &RunStatus, stopping: bool) -> Option<TurnEnd> {
match run.state {
RunState::Queued | RunState::Starting | RunState::Running => None,
RunState::Ok => Some(TurnEnd::Completed),
RunState::Error => Some(TurnEnd::Failed(
run.error
.clone()
.unwrap_or_else(|| "the subagent run failed".into()),
)),
RunState::Stopped if stopping => Some(TurnEnd::Interrupted),
RunState::Stopped => Some(TurnEnd::Cancelled),
}
}
fn lock(queues: &Queues) -> MutexGuard<'_, HashMap<JobId, QueueWatch>> {
queues.lock().unwrap_or_else(PoisonError::into_inner)
}
fn run_agent(status: &crate::subagent::RunStatus) -> Option<JobAgent> {
let engine = match status.runtime? {
crate::subagent::RecordedRuntime::Known(runtime) => runtime.into(),
crate::subagent::RecordedRuntime::Retired(_) => rho_protocol::AgentRuntime::Unknown,
};
Some(JobAgent {
id: status.agent_id.clone()?,
engine,
})
}
#[cfg(test)]
#[path = "subagents_tests.rs"]
mod tests;