rho-coding-agent 3.5.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
//! Background delivery at SDK input boundaries for hosts without an interactive
//! inbox (the daemon and `rho run`). Finished subagents, workflows, and
//! background processes reach the model at the next boundary. Natural
//! completion waits for every undelivered child of the session, whichever
//! prompt started it, and for workflows and process tasks started during
//! this prompt, standing in for the TUI's idle wake, unless the host wakes
//! the idle session (see below). Workflows and tasks from an earlier prompt,
//! such as a `/workflow:<name>` start, only deliver; a later prompt does not
//! wait for them. A process service (`kind: service`, such as a dev server)
//! never holds completion, whichever prompt started it; its exit result
//! still delivers at the next boundary of any prompt. The wait stays inside
//! the original run, so cancellation and the SDK step budget still govern
//! parent continuations.
//! Notices of turns the session started in other sessions through session
//! control (see `app::peer_sessions`) deliver like finished work and never
//! hold completion; only a session whose host starts its turns has them.
//! Hosts that show a transcript take [`Delegation::offered_displays`] to
//! render what the model was given. Children the host runs as its own threads
//! ([`super::ChildAgents::HostThreads`]) are not registered here: they
//! outlive the prompt and report through the host's next prompt instead.
//!
//! Children also outlive a cancelled prompt, so the session keeps their
//! notice binding between prompts with [`Delegation::hold_notices`]. `rho run`
//! drops it with the run.
//!
//! A session whose host runs its children as its own threads (T3 Code) is
//! woken through that host for background work too (see the daemon's
//! `sessions::t3_wake`), so it gets [`BackgroundWait::HostWakes`]: running
//! workflows and process tasks then never hold natural completion, and
//! finished ones still deliver at every boundary. So it is for a session
//! whose host starts a turn of its own when the work finishes, as the daemon
//! does for the TUI ([`BackgroundWait::HostTurns`], `sessions::idle_wake`).
//! There a prompt does not wait for its running subagents either, and a
//! child's informational notices alone buy no provider request: they wait
//! for the next one, in this prompt or a later turn.

use std::time::Instant;

use rho_sdk::{BoundaryInputRequest, InputBoundary, Session, UserInput};
use tokio::sync::mpsc;

use crate::{
    app::{
        boundary_results::BoundaryResults,
        peer_sessions::{PeerBatch, PeerInbox},
        pull_requests::{NewsBatch, PullRequestInbox},
        subagent_manager::{SubagentManager, SubagentNotification},
        subagent_messaging::{NoticePermits, SubagentNotice},
    },
    display_transcript::DisplayTranscript,
    session::SessionPersistence,
    tools::{
        process::{ProcessManager, ProcessNotification},
        sdk_registry::AppToolSet,
        ui::{SurfaceAction, SurfaceHost},
        workflow_tracker::{WorkflowNotification, WorkflowRunTracker},
    },
};

pub(super) struct Delegation {
    session_id: String,
    requests: mpsc::Receiver<BoundaryInputRequest>,
    subagents: Option<SubagentDelivery>,
    processes: Option<ProcessManager>,
    workflows: WorkflowRunTracker,
    /// The session's A2UI surfaces, whose actions no `ui` call waited for
    /// are delivered like finished work.
    surfaces: Option<SurfaceHost>,
    /// The session's watched pull requests, whose news is delivered like
    /// finished work.
    pull_requests: Option<PullRequestInbox>,
    /// Notices of turns the session started in other sessions, delivered
    /// like finished work.
    peer_sessions: Option<PeerInbox>,
    /// Workflows and process tasks started from here on hold natural
    /// completion; older ones, and services, only deliver.
    prompt_started: Instant,
    background_wait: BackgroundWait,
    /// Display rows for each delivery offered to the runtime, when a host asked.
    displays: Option<mpsc::UnboundedSender<(UserInput, DisplayTranscript)>>,
}

/// Whether running workflows and processes hold a prompt's natural completion.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum BackgroundWait {
    /// The prompt waits for the work it started, standing in for an idle wake.
    HoldPrompt,
    /// The host wakes the idle session when the work finishes.
    HostWakes,
    /// The host starts a turn on the idle session when the work finishes,
    /// a subagent included, or a child asks the parent to act. The turn
    /// delivers the result at its first boundary.
    HostTurns,
}

impl BackgroundWait {
    /// How a session whose children `children` runs waits: a host that runs
    /// them as its own threads wakes the session itself, whatever
    /// `idle_turns` says.
    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,
        }
    }
}

/// The parent's subagent notice binding for one prompt.
struct SubagentDelivery {
    manager: SubagentManager,
    notices: mpsc::Receiver<SubagentNotice>,
    permits: NoticePermits,
    pending: Vec<SubagentNotice>,
}

/// A notice binding kept between prompts. The binding stays installed, so a
/// child can still queue `message_parent` text or an action request while no
/// prompt runs, and notices a cancelled prompt never delivered reach the next.
pub(super) struct HeldNotices(SubagentDelivery);

/// The background work a prompt delivers and waits for.
pub(super) struct BackgroundSources<'a> {
    pub(super) subagents: Option<&'a SubagentManager>,
    pub(super) processes: Option<&'a ProcessManager>,
    pub(super) workflows: &'a WorkflowRunTracker,
    pub(super) surfaces: Option<&'a SurfaceHost>,
    pub(super) pull_requests: Option<&'a PullRequestInbox>,
    pub(super) peer_sessions: Option<&'a PeerInbox>,
}

impl<'a> BackgroundSources<'a> {
    /// The work of the session's `tools`; a turn adds its host's notices of
    /// the turns it started in other sessions.
    pub(super) fn of(tools: &'a AppToolSet) -> Self {
        Self {
            subagents: tools.subagents(),
            processes: tools.processes(),
            workflows: tools.workflow_tracker(),
            surfaces: tools.surfaces(),
            pull_requests: tools.pull_requests(),
            peer_sessions: None,
        }
    }

    /// Whether work of session `session_id`'s still runs or holds a result
    /// no prompt delivered, whichever prompt started it: a subagent, a
    /// workflow run, a live background process, task or service, or a
    /// finished task's result. A finished service's result does not count:
    /// it waits only for a next prompt, so it must not keep an idle
    /// session loaded or a daemon upgrade waiting. Neither does pull request
    /// news: it is saved, so an unloaded session or a restarted daemon still
    /// delivers it.
    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_task_result())
            || self.surfaces.is_some_and(SurfaceHost::has_action)
    }
}

impl HeldNotices {
    /// Whether a child's notice waits for the next prompt.
    pub(super) fn has_undelivered(&self) -> bool {
        let Self(delivery) = self;
        !delivery.pending.is_empty() || !delivery.notices.is_empty()
    }
}

impl Delegation {
    /// Installs boundary delivery for one prompt on an idle session. A binding
    /// in `held` resumes the previous prompt's notices; without one the prompt
    /// binds afresh, retiring any earlier binding. `held` is taken only once
    /// attach succeeds, so a failed attach keeps it for the next prompt.
    /// Subagents keep their artifacts in `storage`'s folder when it has one,
    /// and save their sessions as `persistence` says the session does.
    /// Running workflows and processes hold natural completion as `wait`
    /// says.
    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,
            surfaces: sources.surfaces.cloned(),
            pull_requests: sources.pull_requests.cloned(),
            peer_sessions: sources.peer_sessions.cloned(),
            prompt_started: Instant::now(),
            background_wait: wait,
            displays: None,
        })
    }

    /// Display rows for every delivery offered from now on. The host claims
    /// them as the run reports each input applied.
    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,
        };
        // The SDK checkpoints input before acknowledging it. Reap any ready
        // acknowledgement before dropping reservations, including when the
        // event pump notices cancellation in that same scheduling turn.
        let _ = futures_util::poll!(&mut service);
        result
    }

    /// Ends this prompt but keeps its notice binding, with every notice not yet
    /// delivered, for the next [`Self::attach`].
    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 {
            // Subscribe before collecting so a finish between the snapshot
            // and the wait below still wakes it.
            let process_exit = self.processes.as_ref().map(ProcessManager::notified_owned);
            let workflow_finish = self.workflows.notified_owned();
            let surface_action = self.surfaces.as_ref().map(SurfaceHost::acted_owned);
            let news = self
                .pull_requests
                .as_ref()
                .map(PullRequestInbox::news_owned);
            let peers = self.peer_sessions.as_ref().map(PeerInbox::arrived_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() {
                    // With nothing due, the prompt is about to end. Where the
                    // host starts later turns, notices wait for one of them.
                    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 {
                            // Queued before the reply, so its rows wait for
                            // the applied event. A closed host shows nothing.
                            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,
                }
            };
            let surface_action = async move {
                match surface_action {
                    Some(acted) => acted.await,
                    None => std::future::pending().await,
                }
            };
            let news = async move {
                match news {
                    Some(news) => news.await,
                    None => std::future::pending().await,
                }
            };
            let peers = async move {
                match peers {
                    Some(arrived) => arrived.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 => {}
                    () = surface_action => {}
                    () = news => {}
                    () = peers => {}
                },
                None => tokio::select! {
                    () = process_exit => {}
                    () = workflow_finish => {}
                    () = surface_action => {}
                    () = news => {}
                    () = peers => {}
                },
            }
        };
        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(&notice);
                    }
                }
            }
        }
    }

    /// Drains finished work from every source. Call under the delivery lock.
    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(),
            surfaces: self.surfaces.clone(),
            surface_actions: self
                .surfaces
                .as_ref()
                .map(SurfaceHost::take_actions)
                .unwrap_or_default(),
            pull_requests: self.pull_requests.clone(),
            pull_request_news: self
                .pull_requests
                .as_ref()
                .map(PullRequestInbox::take_news)
                .unwrap_or_default(),
            peer_sessions: self.peer_sessions.clone(),
            peer_notices: self
                .peer_sessions
                .as_ref()
                .map(PeerInbox::take)
                .unwrap_or_default(),
        }
    }

    /// Model input and display rows for a batch, rendered as the TUI renders them.
    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,
            surface_actions: &batch.surface_actions,
            pull_requests: &batch.pull_request_news,
            peer_sessions: &batch.peer_notices,
        }
        .render(self.subagents.as_ref().map(|subagents| &subagents.manager))
        .finish()
    }

    /// Work whose result could still arrive and should hold natural completion.
    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)
            || self.surfaces.as_ref().is_some_and(SurfaceHost::has_action)
            || self
                .pull_requests
                .as_ref()
                .is_some_and(PullRequestInbox::has_news)
            || self
                .peer_sessions
                .as_ref()
                .is_some_and(PeerInbox::has_notices);
        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_task_started_since(self.prompt_started)
                    })
            }
            BackgroundWait::HostWakes | BackgroundWait::HostTurns => false,
        };
        subagents || finished || running
    }
}

/// Display rows for deliveries offered to the runtime. Each waits for the
/// [`rho_sdk::RunEvent::BoundaryInputApplied`] that confirms it, so a host
/// shows a result exactly where it entered the run and never shows one the
/// runtime rejected.
pub(super) struct OfferedDisplays {
    receiver: mpsc::UnboundedReceiver<(UserInput, DisplayTranscript)>,
}

impl OfferedDisplays {
    /// Rows for the `input` a run applied. A rejected offer can only precede
    /// it, so older offers that do not match are discarded.
    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();
        // Cancellation can leave queued notices behind. A host that drops the
        // binding instead of holding it retires their receipts with it.
        while let Ok(notice) = subagents.notices.try_recv() {
            subagents.pending.push(notice);
        }
        for notice in subagents.pending.drain(..) {
            subagents.permits.release_notice(&notice);
        }
    }
}

/// Results drained for one boundary. A cancelled boundary must not consume
/// results it never committed, so dropping an uncommitted batch restores them.
struct DeliveryReservation {
    subagents: Option<SubagentManager>,
    subagent_results: Vec<SubagentNotification>,
    workflows: WorkflowRunTracker,
    workflow_results: Vec<WorkflowNotification>,
    processes: Option<ProcessManager>,
    process_results: Vec<ProcessNotification>,
    surfaces: Option<SurfaceHost>,
    surface_actions: Vec<SurfaceAction>,
    pull_requests: Option<PullRequestInbox>,
    pull_request_news: NewsBatch,
    peer_sessions: Option<PeerInbox>,
    peer_notices: PeerBatch,
}

impl DeliveryReservation {
    fn has_results(&self) -> bool {
        !self.subagent_results.is_empty()
            || !self.workflow_results.is_empty()
            || !self.process_results.is_empty()
            || !self.surface_actions.is_empty()
            || !self.pull_request_news.is_empty()
            || !self.peer_notices.is_empty()
    }

    /// The SDK applied the input: the results are delivered. Pull request
    /// news is also removed from disk now, and only now, so a crash before
    /// this delivers it again rather than never.
    fn commit(&mut self) {
        if let Some(inbox) = &self.pull_requests {
            inbox.acknowledge(&self.pull_request_news);
        }
        self.pull_request_news = NewsBatch::default();
        self.peer_notices = PeerBatch::default();
        self.subagent_results.clear();
        self.workflow_results.clear();
        self.process_results.clear();
        self.surface_actions.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);
        }
        if let Some(surfaces) = &self.surfaces {
            surfaces.restore_actions(&self.surface_actions);
        }
        if let Some(inbox) = &self.pull_requests {
            inbox.restore_news(&self.pull_request_news);
        }
        if let Some(inbox) = &self.peer_sessions {
            inbox.restore(&self.peer_notices);
        }
    }
}

#[cfg(test)]
#[path = "delegation_tests.rs"]
mod tests;