rho-coding-agent 3.11.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
//! The background work a daemon session's served tools start (see
//! `acp_tools`), delivered to the agent of another runtime that runs the
//! session: a subagent's result or notice, a process's exit, a workflow
//! run's end, and what a client did on a surface no `ui` call waited on.
//!
//! The work outlives the turn that started it, as a Rho session's does, and
//! its results reach the agent by the same rules a Rho session's turns
//! follow (see [`crate::app::background_delivery`]), rendered by the same
//! renderer:
//!
//! - As a turn starts, what waits rides ahead of its prompt, as a content
//!   block of its own ([`TurnMailbox`]), the children's informational
//!   notices with it.
//! - While the turn runs, each result is sent into it as it arrives, through
//!   the run's message inbox, which steers it into the turn in flight, or
//!   sends it as the agent's next turn once the turn ends (see
//!   `acp_runtime::driver`). A child's informational notice alone waits for
//!   a result, a request for the parent to act, or the next turn's prompt.
//! - Between turns, what arrives wakes the session where its client takes
//!   the turns the daemon starts (`idle_wake: turn`, see `idle_wake`), as a
//!   Rho session's does: the daemon starts a turn of its own whose prompt
//!   carries it (see `acp_turns/daemon_turn.rs`). Elsewhere it waits for
//!   the next prompt. No prompt waits for running work either way.
//!
//! A delivery is committed only once the run delivered it: its prompt sent,
//! its steer injected, or its follow-up turn sent. One the run never
//! delivered, as when the turn ended first, is put back for the next turn.
//! The run records the delivery's cards as it delivers it, so clients see
//! them once, where the agent got the results, and a reopen replays them
//! from the agent's journal. A card loses the typed side a Rho session's
//! card keeps (the subagent's session to open), which the journal does not
//! record. Nothing is sent into a turn while a served call runs, a parked
//! one included, or while one of the agent's requests to the served tools
//! has yet to get its answer
//! ([`super::agent_activity::Activity::served_tools_busy`]): `process`
//! `poll` or `agents` `status` may hand the agent the result itself, which a
//! delivery would then send again, and a delivery sent while a call's
//! answer waits to go back, as for a slot in the agent budget, would reach
//! the agent ahead of it.
//!
//! How the session waits follows from whether the daemon wakes it
//! ([`IdleDelivery`], decided as it opens; see [`idle_delivery`]):
//!
//! - Woken ([`IdleDelivery::WakeTurn`]), its `SessionBackground` waits as a
//!   Rho session whose client takes the daemon's turns does
//!   ([`BackgroundWait::HostTurns`]): the work it waits on keeps it active
//!   (see `settle`), its finished results keep it loaded and a daemon
//!   upgrade waiting, as a wake will deliver them
//!   ([`CountedWork::Results`]) until the wake gives up on them (then only
//!   [`CountedWork::Live`], see `unload`), and it takes the news of the pull
//!   requests it watches and the notices of the turns it started in other
//!   sessions too.
//! - Otherwise it waits as [`BackgroundWait::HoldPrompt`], which no daemon
//!   waker wakes: it settles as its turn ends, whatever runs, and its live
//!   work keeps it loaded, but no result does ([`CountedWork::Live`]).

use std::future::Future;

use crate::{
    app::{
        background_delivery::{
            self, BackgroundDelivery, BackgroundSources, Batch, CountedWork, HeldNotices, Notices,
        },
        notification_delivery,
        peer_sessions::PeerInbox,
        session_runtime::BackgroundWait,
    },
    cli_runtime::parent_messages::{
        message_channel, DeliveryReceipt, ParentMessage, ParentMessageHandle, ParentMessageInbox,
    },
    display_transcript::{DisplayRow, DisplayTranscript},
    run_artifacts::AttachmentEvent,
    tools::{
        sdk_registry::{AppToolSet, IdleDelivery},
        workflow_tracker::WorkflowRunTracker,
    },
};

use super::{
    acp_tools::ServedTools,
    agent_activity::AgentActivity,
    background::{SessionBackground, Sources},
};

/// Whether the daemon wakes the idle session a client opens so that a Rho
/// session opened alike would wait as `rho_wait` ([`BackgroundWait::of`]),
/// for its results: only where the daemon starts a Rho session's turns for
/// them. A host that runs a session's children as its own threads wakes a
/// Rho session through itself (`t3_wake`), which no session an agent of
/// another runtime runs has.
pub(super) fn idle_delivery(rho_wait: BackgroundWait) -> IdleDelivery {
    match rho_wait {
        BackgroundWait::HostTurns => IdleDelivery::WakeTurn,
        // T3 Code's own wake is no daemon wake.
        BackgroundWait::HostWakes | BackgroundWait::HoldPrompt => IdleDelivery::NextPrompt,
    }
}

/// How the background work of a session woken as `idle` says waits: for a
/// turn the daemon starts (see `awaited`), or for the next prompt, which no
/// daemon waker wakes. Rho's boundaries never run the session's turns, so
/// neither holds a prompt open. Not the Rho session's wait it came from: a
/// T3 Code client's `HostWakes` names a waker no such session has.
fn wait(idle: IdleDelivery) -> BackgroundWait {
    match idle {
        IdleDelivery::WakeTurn => BackgroundWait::HostTurns,
        IdleDelivery::NextPrompt => BackgroundWait::HoldPrompt,
    }
}

/// The work the session delivers, from the tools it is `served`.
fn sources(served: &ServedTools) -> BackgroundSources<'_> {
    sources_of(served.set(), served.idle(), served.peers())
}

/// The work a session woken as `idle` says delivers, from its tools `set`
/// and the inbox of the turns it starts in other sessions, `peers`. Pull
/// request news and those notices only where the daemon wakes it: only a
/// wake could deliver them, and only then is `watch_pull_request` served.
pub(super) fn sources_of<'a>(
    set: &'a AppToolSet,
    idle: IdleDelivery,
    peers: Option<&'a PeerInbox>,
) -> BackgroundSources<'a> {
    let of = BackgroundSources::of(set);
    match idle {
        IdleDelivery::WakeTurn => BackgroundSources {
            peer_sessions: peers,
            ..of
        },
        IdleDelivery::NextPrompt => BackgroundSources {
            pull_requests: None,
            ..of
        },
    }
}

/// The background work of session `session_id`, from the tools it is
/// `served`: none without them.
pub(super) fn background(session_id: String, served: Option<&ServedTools>) -> SessionBackground {
    match served {
        Some(served) => of_sources(session_id, served.idle(), sources(served)),
        None => SessionBackground::of_sources(
            session_id,
            wait(IdleDelivery::NextPrompt),
            Sources::default(),
            WorkflowRunTracker::new(),
        ),
    }
}

/// The background work of session `session_id`, woken as `idle` says, from
/// `sources`.
fn of_sources(
    session_id: String,
    idle: IdleDelivery,
    sources: BackgroundSources<'_>,
) -> SessionBackground {
    SessionBackground::of_sources(
        session_id,
        wait(idle),
        Sources {
            processes: sources.processes.cloned(),
            subagents: sources.subagents.cloned(),
            surfaces: sources.surfaces.cloned(),
            pull_requests: sources.pull_requests.cloned(),
            peers: sources.peer_sessions.cloned(),
        },
        sources.workflows.clone(),
    )
}

/// Whether work of the tools session `session_id` is `served`, counted as
/// the session's host says (`counted`), keeps it loaded and a daemon
/// upgrade waiting: what a teardown would stop or drop. Where the daemon
/// wakes the session, as for a Rho session, a result counts as the host
/// says, since a wake will deliver it. Otherwise only what still runs: a
/// result there waits for a turn nothing starts, so counting it would keep
/// the session loaded, and a daemon upgrade waiting, for good.
pub(super) fn has_work(session_id: &str, served: &ServedTools, counted: CountedWork) -> bool {
    let counted = match served.idle() {
        IdleDelivery::WakeTurn => counted,
        IdleDelivery::NextPrompt => CountedWork::Live,
    };
    background_delivery::has_work(session_id, &sources(served), served.held_notices(), counted)
}

/// Binds the delivery of session `session_id`'s work, from the tools it is
/// `served`, resuming the children's notices `held` the last turn kept.
pub(super) fn bind(
    session_id: String,
    served: &ServedTools,
    held: Option<HeldNotices>,
) -> BackgroundDelivery {
    BackgroundDelivery::bind(session_id, sources(served), held)
}

/// When a delivery is due.
#[derive(Clone, Copy)]
enum Moment {
    /// As the turn starts: its prompt goes anyway, so the children's
    /// informational notices ride along.
    TurnStart,
    /// While the turn runs: a result, or a child's request that the parent
    /// act.
    MidTurn,
}

/// What one turn's run takes for the session's background results: the
/// inbox the run reads them from, the port into it, which a person's steer
/// goes through too ([`super::acp_steer`]), and the results its first
/// prompt carries.
pub(super) struct TurnMailbox {
    inbox: ParentMessageInbox,
    messages: ParentMessageHandle,
    prompt_results: Option<ParentMessage>,
}

impl TurnMailbox {
    /// The mailbox of a turn no background results reach: steers alone.
    pub(super) fn steers_only() -> Self {
        let (messages, inbox) = message_channel();
        Self {
            inbox,
            messages,
            prompt_results: None,
        }
    }

    /// The port into the turn's run.
    pub(super) fn messages(&self) -> ParentMessageHandle {
        self.messages.clone()
    }

    /// The results that wait, which the turn's prompt carries, if any.
    pub(super) fn prompt_results(&self) -> Option<&ParentMessage> {
        self.prompt_results.as_ref()
    }

    /// Gives `launch` the inbox, and its prompt the results that wait.
    pub(super) fn install(self, launch: &mut crate::app::agent_binding::ExternalLaunch) {
        let Self {
            inbox,
            prompt_results,
            ..
        } = self;
        *launch.parent_messages_mut() = Some(inbox);
        launch.overrides_mut().prompt_results = prompt_results;
    }
}

/// A delivery the run was given and has yet to confirm.
struct InFlight {
    batch: Batch,
    delivered: DeliveryReceipt,
}

/// The session's background delivery for one turn.
pub(super) struct TurnDelivery {
    delivery: BackgroundDelivery,
    messages: ParentMessageHandle,
    in_flight: Option<InFlight>,
    /// What the agent does with the served tools, which holds back what is
    /// sent mid-turn.
    activity: AgentActivity,
}

impl TurnDelivery {
    /// Starts delivering `delivery` into a turn whose agent's use of the
    /// served tools `activity` tells: the turn's side, and what its run
    /// takes, with what waits rendered for its prompt.
    pub(super) fn start(
        delivery: BackgroundDelivery,
        activity: AgentActivity,
    ) -> (Self, TurnMailbox) {
        let (messages, inbox) = message_channel();
        let mut turn = Self {
            delivery,
            messages: messages.clone(),
            in_flight: None,
            activity,
        };
        let prompt_results = turn.due(Moment::TurnStart).map(|(message, in_flight)| {
            turn.in_flight = Some(in_flight);
            message
        });
        (
            turn,
            TurnMailbox {
                inbox,
                messages,
                prompt_results,
            },
        )
    }

    /// Sends each result into the turn as it arrives, one at a time, each
    /// committed once the run delivered it, and none while the served tools
    /// are busy. Returns once the run takes no more; cancel-safe, since a
    /// delivery in flight stays for [`Self::finish`].
    async fn deliver(&mut self) {
        loop {
            if let Some(in_flight) = &mut self.in_flight {
                let delivered = (&mut in_flight.delivered).await.is_ok();
                match (delivered, self.in_flight.take()) {
                    (true, Some(in_flight)) => self.commit(in_flight),
                    // The run ended without it, so it takes no more: the
                    // batch goes back for the next turn.
                    (false, _) | (true, None) => return,
                }
                continue;
            }
            // A call that hands the agent a result runs first; what it left
            // is looked at once it, and every other call, ended, and every
            // answer went back.
            self.activity
                .until(|activity| !activity.served_tools_busy())
                .await;
            // Subscribed before the look, so a result in between still
            // wakes the wait.
            let arrived = self.delivery.arrivals();
            if let Some((message, in_flight)) = self.due(Moment::MidTurn) {
                match self.messages.send_message(message) {
                    Ok(()) => self.in_flight = Some(in_flight),
                    // The run closed its inbox as it ends: the batch goes
                    // back for the next turn.
                    Err(_) => return,
                }
                continue;
            }
            self.delivery.changed(arrived).await;
        }
    }

    /// The turn's run ended: a delivery it made is committed, one it did
    /// not is put back, and the children's notice binding is kept for the
    /// next turn.
    pub(super) fn finish(mut self) -> Option<HeldNotices> {
        if let Some(mut in_flight) = self.in_flight.take() {
            if in_flight.delivered.try_recv().is_ok() {
                self.commit(in_flight);
            }
        }
        let Self { delivery, .. } = self;
        delivery.hold()
    }

    /// The results due at `moment`, reserved and rendered as the message
    /// that delivers them; `None`, reserving nothing, when none are.
    fn due(&mut self, moment: Moment) -> Option<(ParentMessage, InFlight)> {
        let lock = notification_delivery::lock();
        let batch = self.delivery.collect(&lock);
        let due = batch.has_results()
            || match moment {
                Moment::TurnStart => self.delivery.has_notices(),
                Moment::MidTurn => self.delivery.action_requested(),
            };
        if !due {
            return None;
        }
        let (model, display) = self.delivery.render(&batch)?;
        let (message, delivered) =
            ParentMessage::hosted(framed(&model), shown(display), UNDELIVERED.to_owned());
        Some((message, InFlight { batch, delivered }))
    }

    /// The run delivered `in_flight`, with every notice that waited, since
    /// each delivery offers them all.
    fn commit(&mut self, in_flight: InFlight) {
        self.delivery.commit(in_flight.batch, Notices::Offered);
    }
}

/// Runs `run`, a turn's run, delivering `delivery` into it meanwhile, if
/// the turn has one; returns how the run ended, and the children's notice
/// binding for the next turn. Once the delivery returns, as the run takes
/// no more, the run goes on alone to its end.
pub(super) async fn alongside<T>(
    delivery: Option<TurnDelivery>,
    run: impl Future<Output = T>,
) -> (T, Option<HeldNotices>) {
    let Some(mut delivery) = delivery else {
        return (run.await, None);
    };
    tokio::pin!(run);
    let ended = tokio::select! {
        biased;
        ended = &mut run => ended,
        () = delivery.deliver() => run.await,
    };
    (ended, delivery.finish())
}

/// The results `model` rendered, as the agent reads them: what work it
/// started finished, not a request from anyone.
fn framed(model: &str) -> String {
    format!("rho delivered results of background work you started earlier with its tools (not a new task from the user - use them in your current work):\n\n{model}")
}

/// What the run says of results it never delivered.
const UNDELIVERED: &str = "acp: background results were not delivered: the run ended before its next turn; the session's next turn gets them";

/// What the run records of a delivery as it delivers it: the rows the
/// renderer gave its transcript, as the agent's journal holds them.
fn shown(display: DisplayTranscript) -> Vec<AttachmentEvent> {
    let DisplayTranscript(rows) = display;
    rows.into_iter()
        .filter_map(|row| match row {
            DisplayRow::Notification(row) => Some(AttachmentEvent::Message(Box::new(row.card))),
            DisplayRow::Notice(text) => Some(AttachmentEvent::Notice(text)),
            // A delivery renders none.
            DisplayRow::Compaction(_) => None,
        })
        .collect()
}

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