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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
//! A relay of one child session's stream to the host: it observes the
//! child's session on the daemon and sends what it does as the child's own
//! updates, as [`super::subagents`] describes, until the stream ends, the
//! daemon is lost, or the parent forgets the child.
use std::{
sync::{Arc, Mutex},
time::Duration,
};
use agent_client_protocol::{v1::schema as v1, v2::schema as v2};
use agent_client_protocol::{v2::ConnectionTo as V2ConnectionTo, Client};
use rho_protocol::{
methods::{JobList, SessionObserve},
ClientError, DetachReason, ErrorCode, JobListParams, JobState, Replay, SessionAttachResponse,
SessionEvent, SessionId, SessionObserveParams, SessionOptions,
};
use tokio::sync::{mpsc, oneshot};
use super::{
bridge,
child_inputs::ChildInputs,
child_jobs::run_ended,
child_kind::ChildKind,
port::V2Port,
requests,
subagents::{child_options, lock, replay_complete, send, tell, ChildState, Told},
};
use crate::app::{
acp::{
prompt,
sessions::Attacher,
updates::{self, Delivery, Updates},
Foreground, TurnEnd,
},
daemon_client::{Daemon, DaemonError, Part, Routed, StreamPosition},
};
/// How long a relay waits to ask again to observe a child whose run has
/// yet to open its session: the interval the session pump reads processes'
/// output at (`sessions::output::READ_EVERY`, whose cost is measured there).
const OBSERVE_AGAIN: Duration = Duration::from_millis(250);
/// What a relay shows of an observe's replay. The events after it are
/// live, and show as such.
pub(super) enum Show {
/// As live updates: the host has seen none of it, or missed it.
Live,
/// Nothing: the host has it, or a resume without replay reports what
/// is current only.
Skip,
/// As history, through `port`, which the child's `replay_complete`
/// ends, then its current options and state; `caught_up` then tells
/// the resume waiting for it.
History {
port: V2Port,
caught_up: oneshot::Sender<()>,
},
}
impl Show {
/// What an observe again after the cursor shows of its `replay`: a
/// tail holds the events the host missed, and a reset the history it
/// has.
fn resumed(replay: Replay) -> Self {
match replay {
Replay::Tail => Self::Live,
Replay::Reset => Self::Skip,
}
}
/// Ends a history no relay will show: `child`'s `replay_complete`, then
/// the resume hears it is through.
pub(super) fn over(self, cx: &V2ConnectionTo<Client>, child: &v2::SessionId) {
if let Self::History { caught_up, .. } = self {
send(cx, child, replay_complete());
let _ = caught_up.send(());
}
}
}
/// The task that relays one child's stream.
pub(super) struct Relay {
pub(super) daemon: Arc<Daemon>,
pub(super) kind: ChildKind,
pub(super) state: Arc<Mutex<ChildState>>,
pub(super) port: Arc<V2Port>,
/// What the current observe's replay shows.
pub(super) show: Show,
pub(super) parent: v2::SessionId,
pub(super) child: v2::SessionId,
pub(super) session: SessionId,
pub(super) updates: Updates,
/// Where the stream is, once observed.
pub(super) position: Option<StreamPosition>,
/// The child's options and state as the observe began, which a replay
/// reports once the child's history is over.
pub(super) pending: Option<(SessionOptions, JobState)>,
/// The requests a child that waits for a person has open on the host.
pub(super) inputs: Option<ChildInputs>,
}
/// What a relay does once its observe ends.
enum Next {
/// Observe again after the cursor: the daemon dropped the observe as
/// it fell behind.
Again,
Stop(Stopped),
}
/// Why a relay stopped.
#[derive(Clone, Copy)]
enum Stopped {
/// The run ended, or its session cannot be followed.
Ended,
/// The daemon is gone.
Lost,
/// Its parent forgot the child.
Released,
}
impl Relay {
pub(super) async fn run(mut self) {
// A relay of the child that a resume or close aborted may have left
// the daemon following it for this connection, and the events its
// forwarder queued would come ahead of this observe's replay.
if let Err(error) = Attacher::detach(&*self.daemon, &self.session).await {
tracing::debug!(%error, "could not stop following a subagent's session");
}
loop {
let routed = self.daemon.route_channel(&self.session);
let params = SessionObserveParams {
session: self.session.clone(),
after: self
.position
.as_ref()
.and_then(StreamPosition::cursor)
.cloned(),
};
let next = match self.daemon.request::<SessionObserve>(¶ms).await {
Ok(response) => {
self.begin(&response);
self.read(routed).await
}
// The run has yet to open its session, so it has no history
// a resume would wait for.
Err(DaemonError::Request(error))
if error.error_code() == Some(ErrorCode::SessionBusy) =>
{
self.daemon.unroute(&self.session);
self.history_over();
tokio::time::sleep(OBSERVE_AGAIN).await;
Next::Again
}
Err(
error @ (DaemonError::Unreachable(_)
| DaemonError::Request(ClientError::Closed | ClientError::Frame(_))),
) => {
tracing::debug!(%error, "could not observe a subagent's session");
Next::Stop(Stopped::Lost)
}
Err(DaemonError::Request(error)) => {
tracing::debug!(%error, "could not observe a subagent's session");
Next::Stop(Stopped::Ended)
}
};
match next {
Next::Again => {}
Next::Stop(Stopped::Released) => return,
Next::Stop(stopped) => {
self.daemon.unroute(&self.session);
self.history_over();
if matches!(stopped, Stopped::Ended) && self.kind.learns_end_from_jobs() {
self.learn_how_it_ended().await;
}
self.stopped(stopped);
return;
}
}
}
}
/// Asks the daemon how the child's run ended, unless the host was told
/// or the parent's background list said: a run that ended before its
/// session could be followed has a saved replay that does not say, and
/// one that started and ended between two of its parent's background
/// reports is never listed. A rare case, so the job list's size is
/// paid only then.
async fn learn_how_it_ended(&self) {
{
let state = lock(&self.state);
if state.told == Some(Told::Idle) || state.ended.is_some() {
return;
}
}
let jobs = match self.daemon.request::<JobList>(&JobListParams {}).await {
Ok(response) => response.jobs,
Err(error) => {
tracing::debug!(%error, "could not ask how a subagent's run ended");
return;
}
};
if let Some(status) = run_ended(&jobs, &self.session) {
lock(&self.state).ended.get_or_insert(status);
}
}
/// Ends the relay: a child whose work it did not see end ends as the
/// parent's background list says, now if it said so already, or else
/// once it does; one the daemon lost with it is `unknown`.
fn stopped(&self, stopped: Stopped) {
let mut state = lock(&self.state);
state.unrelayed = true;
let (told, update) = match (state.settled(), stopped) {
(Some(idle), _) => (Told::Idle, idle),
(None, Stopped::Lost) if state.told != Some(Told::Idle) => (
Told::Unknown,
v2::StateUpdate::Unknown(v2::UnknownStateUpdate::new()),
),
// A started session that could not be observed at all, as one
// since deleted: no background list will say how it is.
(None, Stopped::Ended) if state.told.is_none() && !self.kind.learns_end_from_jobs() => {
(
Told::Unknown,
v2::StateUpdate::Unknown(v2::UnknownStateUpdate::new()),
)
}
(None, Stopped::Lost | Stopped::Ended | Stopped::Released) => return,
};
self.tell_locked(&mut state, told, update);
}
/// Takes the observe's `response`: the child's directories go on the
/// parent's association at once, and its options and state once a
/// replay of its history is over. An observe again after the cursor
/// shows its replay as [`Show::resumed`] says.
fn begin(&mut self, response: &SessionAttachResponse) {
match &mut self.position {
Some(position) => {
position.reattached(response);
self.history_over();
self.show = Show::resumed(response.replay);
}
None => self.position = Some(StreamPosition::attached(response)),
}
let directories: Vec<v2::AbsolutePath> = response
.options
.added_dirs
.iter()
.cloned()
.map(v2::AbsolutePath::new)
.collect();
let placed = v2::SubagentUpdate::new(self.child.clone())
.cwd(v2::AbsolutePath::new(response.workspace.clone()))
.additional_directories(directories);
send(
self.port.cx(),
&self.parent,
v2::SessionUpdate::SubagentUpdate(placed),
);
self.pending = Some((response.options.clone(), response.state));
if let Some(inputs) = &mut self.inputs {
inputs.listed(response.inputs.clone());
}
if !matches!(self.show, Show::History { .. }) {
self.current();
}
}
/// Reports the child's options and state as the observe began.
fn current(&mut self) {
let Some((options, state)) = self.pending.take() else {
return;
};
self.options(&options);
match self.kind.idle_at_observe(state) {
Some(idle) => self.tell_locked(&mut lock(&self.state), Told::Idle, idle),
None => self.busy(Foreground::of(state)),
}
}
async fn read(&mut self, mut routed: mpsc::UnboundedReceiver<Routed>) -> Next {
if !self
.position
.as_ref()
.is_some_and(StreamPosition::replaying)
{
self.replay_over();
}
while let Some(next) = routed.recv().await {
match next {
Routed::Event { seq, event, .. } => {
if lock(&self.state).released {
return Next::Stop(Stopped::Released);
}
self.updates.observe(&event);
let Some(position) = self.position.as_mut() else {
return Next::Stop(Stopped::Ended);
};
match position.observe(seq) {
Part::Live => {
// A replay's requests are resolved, or among
// those the observe listed.
if let Some(inputs) = &mut self.inputs {
inputs.event(&event);
}
self.live(&event);
}
Part::Replayed { left, .. } => {
match &self.show {
Show::Live => self.live(&event),
Show::History { .. } => self.replayed(&event),
Show::Skip => {}
}
if left == 0 {
self.replay_over();
}
}
}
}
Routed::Detached(DetachReason::Lagged) => return Next::Again,
Routed::Detached(DetachReason::DaemonStopping | DetachReason::Restarting)
| Routed::Lost => return Next::Stop(Stopped::Lost),
// The run ended, or its session is gone.
Routed::Detached(_) => return Next::Stop(Stopped::Ended),
}
}
Next::Stop(Stopped::Ended)
}
/// Ends the observe's replay: a resume's history of the child, then
/// the requests it had open, asked once the host has seen the calls
/// they name.
fn replay_over(&mut self) {
self.history_over();
if let Some(inputs) = &mut self.inputs {
inputs.caught_up();
}
}
/// Ends a resume's replay of the child, if one is under way: its
/// `replay_complete`, then its current options and state, and then
/// the resume hears it is through. What follows shows live.
fn history_over(&mut self) {
let show = std::mem::replace(&mut self.show, Show::Live);
let Show::History { caught_up, .. } = show else {
self.show = show;
return;
};
send(self.port.cx(), &self.child, replay_complete());
// The resume answers as soon as it hears, so the current options
// and state go out first.
self.current();
let _ = caught_up.send(());
}
/// Relays `event` as it happens.
fn live(&mut self, event: &SessionEvent) {
match event {
SessionEvent::UserMessage { .. } => {
let message = self.task(event);
send(self.port.cx(), &self.child, message);
}
SessionEvent::State { state, .. } => self.busy(Foreground::of(*state)),
SessionEvent::TurnEnded { outcome, .. } => {
// The answer text no chunk showed comes before the idle.
self.mapped(event, Delivery::Live);
let end = TurnEnd::Ended(prompt::stop_reason(outcome.clone()));
let idle = v2::IdleStateUpdate::new().stop_reason(requests::stop_reason(&end));
self.tell_locked(
&mut lock(&self.state),
Told::Idle,
v2::StateUpdate::Idle(idle),
);
}
SessionEvent::OptionsChanged { options } => self.options(options),
// A started session's title is its parent's title for it too.
SessionEvent::TitleChanged { title } if self.kind.mirrors_title() => {
let titled = v2::SubagentUpdate::new(self.child.clone()).title(title.clone());
send(
self.port.cx(),
&self.parent,
v2::SessionUpdate::SubagentUpdate(titled),
);
self.mapped(event, Delivery::Live);
}
// A subagent's questions are its parent's requests; a started
// session's are asked as they come ([`Self::read`]). Its own
// background work is not shown.
SessionEvent::InputRequested { .. }
| SessionEvent::InputResolved { .. }
| SessionEvent::Background { .. } => {}
event => self.mapped(event, Delivery::Live),
}
}
/// Relays `event` of a resume's replay as history, which holds no
/// states.
fn replayed(&mut self, event: &SessionEvent) {
match event {
SessionEvent::UserMessage { .. } => {
let message = self.task(event);
if let Show::History { port, .. } = &self.show {
let replayed = v2::UpdateSessionNotification::new(self.child.clone(), message)
.meta(updates::replay_meta());
if let Err(error) = port.cx().send_notification(replayed) {
tracing::debug!(%error, "could not replay a subagent's task over ACP v2");
}
}
}
SessionEvent::State { .. }
| SessionEvent::OptionsChanged { .. }
| SessionEvent::InputRequested { .. }
| SessionEvent::InputResolved { .. }
| SessionEvent::Background { .. } => {}
// A turn's end holds no state, only the answer text no chunk
// showed.
event => self.mapped(event, Delivery::Replay),
}
}
/// Sends `event` as Rho's adapter maps it for any session, through the
/// history's port for a replay.
fn mapped(&mut self, event: &SessionEvent, delivery: Delivery) {
let child = v1::SessionId::new(self.child.0.clone());
let mapped = self.updates.map(event);
let port = match (&self.show, delivery) {
(Show::History { port, .. }, Delivery::Replay) => port,
_ => &self.port,
};
for update in mapped {
port.forward(updates::notification(&child, update, delivery));
}
}
/// The `session_message` a user message of the child's stream is: the
/// task its parent gave it.
fn task(&mut self, event: &SessionEvent) -> v2::SessionUpdate {
let mut id = None;
let mut content = Vec::new();
for update in self.updates.map(event) {
if let v1::SessionUpdate::UserMessageChunk(chunk) = update {
id = id.or(chunk.message_id);
match bridge::<_, v2::ContentBlock>(&chunk.content) {
Ok(block) => content.push(block),
Err(error) => tracing::warn!(%error, "could not report a subagent's task"),
}
}
}
let id = id.map_or_else(|| format!("{}-task", self.child.0), |id| id.0.to_string());
v2::SessionUpdate::SessionMessage(
v2::SessionMessage::new(id)
.sender_session_id(self.parent.clone())
.recipient_session_id(self.child.clone())
.content(content),
)
}
fn options(&self, options: &SessionOptions) {
match child_options(options) {
Ok(update) => send(self.port.cx(), &self.child, update),
Err(error) => tracing::warn!(%error, "could not report a subagent's options"),
}
}
/// Tells the host the child is busy as `foreground` says; the turn's
/// end says how its work stopped, so an idle state tells nothing.
fn busy(&self, foreground: Foreground) {
let (told, state) = match foreground {
Foreground::Running => (
Told::Running,
v2::StateUpdate::Running(v2::RunningStateUpdate::new()),
),
Foreground::RequiresAction => (
Told::RequiresAction,
v2::StateUpdate::RequiresAction(v2::RequiresActionStateUpdate::new()),
),
Foreground::Idle => return,
};
self.tell_locked(&mut lock(&self.state), told, state);
}
fn tell_locked(&self, state: &mut ChildState, told: Told, update: v2::StateUpdate) {
tell(
self.port.cx(),
&self.parent,
&self.child,
state,
told,
update,
);
}
}