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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
//! 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).
mod external_run_file;
use std::{path::PathBuf, sync::Arc};
use external_run_file::ExternalRunFile;
use rho_protocol::{SessionEvent as WireEvent, SessionOptions};
use tokio::sync::mpsc::{self, UnboundedReceiver, UnboundedSender};
use super::{
agent_concurrency::{AgentConcurrency, QueueWatch},
agent_executor::AgentRunHandle,
session_events::{external_options, ExternalEvents},
};
use crate::{
cli_runtime::status_sink::RunObserver,
permission::PermissionMode,
run_artifacts::{AttachmentEvent, RunArtifactIdentity},
session::{SessionPersistence, SessionProvenance},
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 {
/// What hears of the runs started here, if anyone does.
pub(crate) fn child_observer(&self) -> Option<Arc<dyn ChildObserver>> {
match self {
Self::Own => None,
Self::Shared { observer, .. } => Some(Arc::clone(observer)),
}
}
/// 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 child run tells the observer that follows it (#1668): the events
/// of a Rho child's session, or of the one a run on an external agent
/// runtime is recorded under ([`ExternalRun`]), and the children such a
/// run's agent starts on its own.
pub(crate) enum ChildEvent {
/// The run opened its session, which runs with `options` as the agent
/// whose id is `agent`, on `runtime`. Sent once, before any
/// [`Self::Session`].
Opened {
options: Box<SessionOptions>,
agent: String,
runtime: crate::agent::AgentRuntime,
},
/// One event of the run's session, as the daemon protocol's.
Session(WireEvent),
/// Not an event of the run's session: the run's agent started a child
/// on its own, a run of its own the observer lists as the run's child
/// (see `app::runtime_child_host`).
RuntimeChild(Box<StartedSubagent>),
}
/// Where a 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>;
/// A run on an external agent runtime that a host follows: where it sends
/// its session's events, and where it records that session.
pub(crate) struct ExternalRun {
pub(crate) events: ChildEventSender,
/// The session the run is recorded under.
pub(crate) session: rho_sdk::SessionId,
/// The workspace the run works in.
pub(crate) cwd: PathBuf,
pub(crate) provenance: SessionProvenance,
/// The run's id.
pub(crate) run: String,
/// The run's status file, beside which it keeps its attach journal.
pub(crate) status: PathBuf,
pub(crate) prompt: String,
/// Whether the run's session is saved: not when its parent's is not.
pub(crate) persistence: SessionPersistence,
}
impl ExternalRun {
/// What hears the run of the agent bound as `identity`, in permission
/// mode `mode`: it tells the host the run's session's events, and
/// records that session in a file, created now, which gets the run's
/// prompt and reply once it ends, beside the run's attach journal.
pub(crate) fn observer(
self,
identity: &RunArtifactIdentity,
mode: PermissionMode,
) -> Box<dyn RunObserver> {
let created = match self.persistence {
SessionPersistence::Saved => Some(ExternalRunFile::create(&self, identity, mode)),
SessionPersistence::Ephemeral => None,
};
let (file, pending) = match created.transpose() {
Ok(file) => (file, None),
// The run goes on; its session shows only while it runs.
Err(error) => {
tracing::warn!(
session = %self.session,
run = %self.run,
error = format!("{error:#}"),
"could not create an external run's session file"
);
let notice = "could not save this run's session: it shows only while it runs";
(None, Some(AttachmentEvent::Notice(notice.into())))
}
};
let mut feed = ExternalRunFeed::new(self.events, identity, mode, file);
feed.pending = pending;
Box::new(feed)
}
}
/// Tells a run's observer what a run on an external agent runtime records,
/// as the events of the session it is recorded under: opens that session
/// with the run's first recorded event, its prompt, once the run has
/// capacity and starts.
struct ExternalRunFeed {
events: ChildEventSender,
/// The session's opening, until it is sent.
opening: Option<ChildEvent>,
/// What the host is told once the session opens, besides what the run
/// records.
pending: Option<AttachmentEvent>,
mapped: ExternalEvents,
/// The session's file, until the run ends.
file: Option<ExternalRunFile>,
}
impl ExternalRunFeed {
/// Follows a run of the agent bound as `identity`, in permission mode
/// `mode`, telling the host on `events`, and saving to `file`, if any.
fn new(
events: ChildEventSender,
identity: &RunArtifactIdentity,
mode: PermissionMode,
file: Option<ExternalRunFile>,
) -> Self {
Self {
events,
opening: Some(ChildEvent::Opened {
options: Box::new(external_options(
&identity.provider,
identity.model.as_deref(),
mode.into(),
)),
agent: identity.agent_id.clone(),
runtime: identity.runtime,
}),
pending: None,
mapped: ExternalEvents::default(),
file,
}
}
}
impl RunObserver for ExternalRunFeed {
fn recorded(&mut self, event: &AttachmentEvent) {
let opening = self.opening.take();
let pending = opening.as_ref().and_then(|_| self.pending.take());
let mapped = &mut self.mapped;
let events = std::iter::once(event)
.chain(pending.as_ref())
.flat_map(|event| mapped.map(event))
.map(ChildEvent::Session);
for event in opening.into_iter().chain(events) {
// The observer went away: nobody follows the run any more.
let _ = self.events.send(event);
}
}
fn ended(&mut self, reply: Option<&str>) {
if let Some(file) = self.file.take() {
file.finish(reply);
}
}
}
/// 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 session the run shows its events under; `None` for a run on an
/// external runtime launched without the sender of `events`.
pub(crate) session: Option<RunSession>,
/// 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 its session, from its opening; `None` for a
/// run launched without the sender.
pub(crate) events: Option<ChildEvents>,
/// What the run shows as until it titles itself, from the moment it
/// queues: its task's [`crate::title::placeholder`].
pub(crate) task: Option<String>,
/// Who started the run: Rho, or its parent's agent runtime.
pub(crate) started_by: RunStarter,
}
/// What started a subagent run.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum RunStarter {
/// Rho: the `agent` tool of its parent, or the workflow run it is an
/// agent node of.
#[default]
Rho,
/// The agent runtime of its parent's session, on its own, as Claude
/// Code starts a subagent with its Task tool (see
/// `acp_runtime::runtime_children`). Nobody prompts or resumes it.
Runtime,
}
impl RunStarter {
/// Whether Rho started the run: what a job record that does not say
/// means.
pub(crate) fn is_rho(&self) -> bool {
*self == Self::Rho
}
}
/// The session a child run shows its events under, and what it holds.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum RunSession {
/// The session a Rho child writes: its conversation, which a follow-up
/// continues.
Rho(rho_sdk::SessionId),
/// The session a run on an external agent runtime is recorded under.
/// The runtime keeps its own conversation; the session's file holds the
/// run's prompt and reply, and the run's attach journal what it showed
/// (see [`crate::session::SessionEngine::Acp`]).
External(rho_sdk::SessionId),
}
impl RunSession {
pub(crate) fn id(&self) -> &rho_sdk::SessionId {
match self {
Self::Rho(id) | Self::External(id) => id,
}
}
}
impl StartedSubagent {
/// The run `handle` follows, started as `run_id` in `workspace` on
/// `task`, which sends its session's events to `events`.
pub(crate) fn of(
run_id: String,
workspace: PathBuf,
handle: &AgentRunHandle,
events: Option<ChildEvents>,
task: Option<String>,
) -> Self {
Self {
run_id,
session: handle.session().cloned(),
workspace,
status: handle.clone_status_watch(),
queue: handle.queue(),
events,
task,
started_by: RunStarter::Rho,
}
}
}
/// 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),
}
#[cfg(test)]
#[path = "subagent_pool_tests.rs"]
mod tests;