1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
//! What a session's in-process subagents share with the host that runs the
//! session.
//!
//! Most hosts run each session's subagents, and the agent nodes of the
//! workflow runs it starts, on a pool of their own sized by the config's
//! `agent_concurrency`. The daemon shares one pool across every session it
//! hosts, so the budget is daemon-wide, and hears of each subagent and
//! workflow run so it can list the run as a child job of its session's
//! (#1658).
use std::{path::PathBuf, sync::Arc};
use rho_protocol::{SessionEvent as WireEvent, SessionOptions};
use tokio::sync::mpsc::{self, UnboundedReceiver, UnboundedSender};
use super::{
agent_concurrency::{AgentConcurrency, QueueWatch},
agent_executor::AgentRunHandle,
};
use crate::{subagent::RunStatus, workflow::RunId};
/// Where a session's in-process agent runs take capacity, its subagents and
/// its workflow runs' agent nodes, and who else hears of them.
#[derive(Clone)]
pub(crate) enum SubagentPool {
/// The session's own pool, sized by its config's `agent_concurrency`;
/// nobody else hears of its runs.
Own,
/// A pool the host shares across its sessions, and the observer of the
/// runs started here.
Shared {
concurrency: AgentConcurrency,
observer: Arc<dyn ChildObserver>,
},
}
impl SubagentPool {
/// The pool runs take capacity from, an own one sized to
/// `agent_concurrency`, and the observer that hears of them, if any.
pub(crate) fn into_parts(
self,
agent_concurrency: usize,
) -> (AgentConcurrency, Option<Arc<dyn ChildObserver>>) {
match self {
Self::Own => (AgentConcurrency::from_config(agent_concurrency), None),
Self::Shared {
concurrency,
observer,
} => (concurrency, Some(observer)),
}
}
/// The pool workflow run `run`'s agent nodes take capacity from: this
/// one, whose observer hears of the run first and returns the observer
/// of its nodes, and where to report how the run ended, if anyone
/// follows it.
pub(crate) fn host_workflow(
self,
run: StartedWorkflow,
) -> (Self, Option<tokio::sync::oneshot::Sender<WorkflowEnd>>) {
match self {
Self::Own => (Self::Own, None),
Self::Shared {
concurrency,
observer,
} => {
let HostedWorkflow { observer, end } = observer.workflow_started(run);
(
Self::Shared {
concurrency,
observer,
},
Some(end),
)
}
}
}
}
impl std::fmt::Debug for SubagentPool {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Own => formatter.write_str("Own"),
Self::Shared { concurrency, .. } => formatter
.debug_struct("Shared")
.field("limit", &concurrency.total_limit())
.finish_non_exhaustive(),
}
}
}
/// Hears of the subagent and workflow runs a session starts, and of the
/// agent node runs of those workflow runs. The daemon implements it to
/// record each run as a child job of the job that started it.
///
/// Both methods are called on the task that starts the run and must return
/// promptly; implementors follow the run on a task of their own.
pub(crate) trait ChildObserver: Send + Sync {
/// Called right after the run is spawned, possibly before it has
/// capacity and possibly after it already ended.
fn subagent_started(&self, run: StartedSubagent);
/// Called before the run is driven. Returns the observer of the run's
/// agent node runs, and where the run reports how it ended. Workflow
/// agent nodes start no workflow runs, so the returned observer only
/// hears [`Self::subagent_started`].
fn workflow_started(&self, run: StartedWorkflow) -> HostedWorkflow;
}
/// What a Rho child run tells the observer that follows it (#1668).
pub(crate) enum ChildEvent {
/// The run opened its session, which runs with these options. Sent
/// once, before any [`Self::Session`].
Opened(Box<SessionOptions>),
/// One event of the run's session, as the daemon protocol's.
Session(WireEvent),
}
/// Where a Rho child run sends its [`ChildEvent`]s. Unbounded: the observer
/// drains it on a task of its own into a stream that bounds what it keeps.
pub(crate) type ChildEventSender = UnboundedSender<ChildEvent>;
/// The observer's end of a [`ChildEventSender`].
pub(crate) type ChildEvents = UnboundedReceiver<ChildEvent>;
/// The event channel of a run about to start: both ends when `observer`
/// will hear of the run, neither when nobody follows it.
pub(crate) fn child_events(
observer: Option<&Arc<dyn ChildObserver>>,
) -> (Option<ChildEventSender>, Option<ChildEvents>) {
observer.map(|_| mpsc::unbounded_channel()).unzip()
}
/// A subagent run that just started, as its observer follows it.
pub(crate) struct StartedSubagent {
/// The run's id among its parent session's runs.
pub(crate) run_id: String,
/// The Rho session the run writes; `None` for a run on another runtime
/// (Claude, Cursor, Antigravity), which keeps that runtime's own.
pub(crate) session: Option<rho_sdk::SessionId>,
/// The directory the run works in.
pub(crate) workspace: PathBuf,
/// The run's status, from `queued` until it is terminal.
pub(crate) status: tokio::sync::watch::Receiver<RunStatus>,
/// Where the run waits for capacity, while it does.
pub(crate) queue: QueueWatch,
/// What the run tells of the session it writes, from its opening;
/// `None` for a run launched without the sender. A run on another
/// runtime sends nothing.
pub(crate) events: Option<ChildEvents>,
}
impl StartedSubagent {
/// The run `handle` follows, started as `run_id` in `workspace`, which
/// sends its session's events to `events`.
pub(crate) fn of(
run_id: String,
workspace: PathBuf,
handle: &AgentRunHandle,
events: Option<ChildEvents>,
) -> Self {
Self {
run_id,
session: handle.session().cloned(),
workspace,
status: handle.clone_status_watch(),
queue: handle.queue(),
events,
}
}
}
/// A workflow run about to be driven in the background.
pub(crate) struct StartedWorkflow {
pub(crate) run_id: RunId,
/// The workspace the run was planned in, where its nodes work.
pub(crate) workspace: PathBuf,
}
/// How the host follows a workflow run it heard of.
pub(crate) struct HostedWorkflow {
/// Hears of each of the run's agent node runs.
pub(crate) observer: Arc<dyn ChildObserver>,
/// Takes how the run ended. Dropped unsent when the drive stops without
/// an end, such as when the host's runtime shuts down under it.
pub(crate) end: tokio::sync::oneshot::Sender<WorkflowEnd>,
}
/// How a workflow run's drive ended.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum WorkflowEnd {
/// Every node finished and the run succeeded.
Completed,
/// The run was cancelled.
Cancelled,
/// The run failed, was denied or blocked, or could not be driven.
Failed(String),
}