rho-coding-agent 3.13.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
//! Rho's subagents as ACP v2 child sessions.
//!
//! A subagent the `agent` tool starts is background work of its parent
//! session, which [`super::background`] announces with a `subagent_update`
//! on the parent before the first `state_update` that lists it. A subagent
//! on Rho's runtime writes its own session, and the daemon streams a run's
//! session while it runs (`rho/session/observe`), so this module relays
//! that stream to the host as the child's own updates, under the child's
//! session id:
//!
//! - the child's `cwd` and `additionalDirectories`, which the observe
//!   answers with, on the parent's `subagent_update` before anything of
//!   the child's, and its options (its model among them) as its
//!   `config_option_update`, each `select` limited to its current value,
//!   since a host may not set a child's options;
//! - the task the parent gave it as a `session_message` from the parent,
//!   not a user message;
//! - its messages, thoughts and tool calls as any session's;
//! - its state as its own `state_update`, each one mirrored as the `state`
//!   of the parent's `subagent_update` before the next.
//!
//! The relay owns a child's state: the background list's finalization of a
//! child with a session only withdraws its `cancel` capability
//! ([`super::background::changes`]). A run that ends before the relay
//! could observe it, or whose stream ends without saying how, ends as the
//! parent's background list says it did ([`Subagents::ended`]). A relay
//! that loses the daemon reports the child `unknown`.
//!
//! A session the parent started with the `sessions` tool is a child too,
//! announced when the call that started it links it, and relayed the same
//! way ([`ChildKind::Started`]). It is no background work: it is titled as
//! its own session is, and it outlives its turns, so the relay reports
//! the state its session is in rather than how a run ended. It waits for a
//! person, so its approvals and questions are put to the host under it
//! ([`super::child_inputs`]).
//!
//! The registry also records which children each parent announced on this
//! connection: the methods a host may not send for a child are refused for
//! them, and a subagent's question is put to the host under the child
//! ([`AcpClientPort::child_session`]). Closing or resuming the parent
//! forgets its children and stops their relays; a resume announces them
//! again and follows each one that still runs ([`Subagents::resume`]).
//!
//! [`AcpClientPort::child_session`]: crate::app::acp::AcpClientPort::child_session

use std::{
    collections::HashMap,
    sync::{atomic::AtomicU64, Arc, Mutex, MutexGuard, PoisonError},
};

use agent_client_protocol::v2::schema as v2;
use agent_client_protocol::{v2::ConnectionTo as V2ConnectionTo, Client, Error as AcpError};
use rho_protocol::{
    methods::JobList, BackgroundItem, BackgroundStatus, BackgroundWork, JobListParams, SessionId,
    SessionOptions,
};
use tokio::{sync::oneshot, task::JoinHandle};

use super::{
    background::subagent_idle,
    child_inputs::ChildInputs,
    child_jobs::{started_by, StartedChild},
    child_kind::ChildKind,
    port::V2Port,
    relay::{Relay, Show},
    requests,
};
use crate::app::{
    acp::{
        host_features::{HostFeatures, Toggles},
        inputs::{AskGate, Asking},
        updates::Updates,
    },
    daemon_client::Daemon,
};

/// The id a child session has on ACP: its own session's, or its run's
/// when the daemon gave it none.
pub(super) fn child_id(run: &str, session: Option<&SessionId>) -> String {
    session.map_or_else(|| run.to_owned(), |session| session.as_str().to_owned())
}

/// One connection's children, by their ACP id.
pub(super) struct Subagents {
    daemon: Arc<Daemon>,
    /// What the host accepts, which a child's updates are mapped for.
    features: Mutex<HostFeatures>,
    children: Mutex<HashMap<String, Child>>,
    /// Numbers the placeholder cards of calls the host never saw, shared
    /// with the connection's sessions (`sessions::Sessions::placeholders`).
    placeholders: Arc<AtomicU64>,
}

/// A child announced on this connection.
struct Child {
    /// The ACP id of the session that announced it.
    parent: String,
    kind: ChildKind,
    /// The relay of its session's stream, while one runs.
    relay: Option<JoinHandle<()>>,
    state: Arc<Mutex<ChildState>>,
}

/// What the host was told of a child's state, and what would tell it how
/// the child's work ended. Locked while a state is sent, so the child's
/// own copy and the parent's mirror go out together.
#[derive(Default)]
pub(super) struct ChildState {
    pub(super) told: Option<Told>,
    /// How its run ended, as the parent's background list or the daemon's
    /// job list says.
    pub(super) ended: Option<BackgroundStatus>,
    /// Whether its relay stopped, so no `turn_ended` of its stream is to
    /// come.
    pub(super) unrelayed: bool,
    /// Whether its parent forgot it, after which the host hears nothing
    /// more of it: an aborted relay may still be handling an event.
    pub(super) released: bool,
}

impl ChildState {
    /// The `idle` a child is due once both its relay stopped and its
    /// parent's list said how its run ended, unless it was told already.
    pub(super) fn settled(&self) -> Option<v2::StateUpdate> {
        match (self.told, self.unrelayed, self.ended) {
            (Some(Told::Idle), _, _) => None,
            (_, true, Some(status)) => Some(subagent_idle(status)),
            (_, _, _) => None,
        }
    }
}

impl Drop for Child {
    fn drop(&mut self) {
        if let Some(relay) = self.relay.take() {
            relay.abort();
        }
    }
}

/// Whether a resume replayed its session's history.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Resumed {
    /// `replayFrom: start`: each child replays its own, too.
    Replayed,
    /// No replay: the host hears what is current only.
    Current,
}

/// Whether a child's relay port sends history (see [`V2Port::child`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum ChildReplay {
    History,
    Live,
}

impl Subagents {
    pub(super) fn new(daemon: Arc<Daemon>, placeholders: Arc<AtomicU64>) -> Self {
        Self {
            daemon,
            features: Mutex::default(),
            children: Mutex::default(),
            placeholders,
        }
    }

    /// Takes what the host accepts, as `initialize` negotiated it.
    pub(super) fn negotiated(&self, features: HostFeatures) {
        *lock(&self.features) = features;
    }

    /// Records that `parent` announced `child`, a child of `kind`; a child
    /// keeps its first parent and kind.
    pub(super) fn announced(&self, parent: &v2::SessionId, child: &v2::SessionId, kind: ChildKind) {
        lock(&self.children)
            .entry(child.0.to_string())
            .or_insert_with(|| Child {
                parent: parent.0.to_string(),
                kind,
                relay: None,
                state: Arc::default(),
            });
    }

    /// Whether `session` is a child announced on this connection, which
    /// the host may not prompt, configure, resume, close, or delete.
    pub(super) fn is_child(&self, session: &str) -> bool {
        lock(&self.children).contains_key(session)
    }

    /// Whether `parent` announced `child`.
    pub(super) fn is_child_of(&self, parent: &str, child: &str) -> bool {
        lock(&self.children)
            .get(child)
            .is_some_and(|known| known.parent == parent)
    }

    /// Relays each running subagent of `work` that has a session and is not
    /// relayed yet, once `parent` announced it.
    pub(super) fn follow(
        &self,
        cx: &V2ConnectionTo<Client>,
        parent: &v2::SessionId,
        work: &[BackgroundWork],
    ) {
        for (child, session) in sessions(work) {
            self.relay(cx, parent, child, session, Show::Live, Asking::now());
        }
    }

    /// Relays `child`, which `parent` linked, unless it was relayed before.
    pub(super) fn linked(
        &self,
        cx: &V2ConnectionTo<Client>,
        parent: &v2::SessionId,
        child: String,
        session: SessionId,
    ) {
        let relayed = lock(&self.children).get(&child).is_some_and(|known| {
            known
                .relay
                .as_ref()
                .is_some_and(|relay| !relay.is_finished() || !known.kind.follows_again())
        });
        if !relayed {
            self.relay(cx, parent, child, session, Show::Live, Asking::now());
        }
    }

    /// Announces `child`, a child of `kind`, on `parent`, titled `title`
    /// when known, recording it first.
    pub(super) fn announce(
        &self,
        cx: &V2ConnectionTo<Client>,
        parent: &v2::SessionId,
        child: &v2::SessionId,
        kind: ChildKind,
        title: Option<String>,
    ) {
        self.announced(parent, child, kind);
        let announced = v2::SubagentUpdate::new(child.clone());
        let announced = match title {
            Some(title) => announced.title(title),
            None => announced,
        };
        send(cx, parent, v2::SessionUpdate::SubagentUpdate(announced));
    }

    /// Takes how child `child` of `parent` ended, as the parent's background
    /// list says: the child is told so unless its relay will tell it, or
    /// told it already.
    pub(super) fn ended(
        &self,
        cx: &V2ConnectionTo<Client>,
        parent: &v2::SessionId,
        child: &str,
        status: BackgroundStatus,
    ) {
        let Some(state) = lock(&self.children)
            .get(child)
            .map(|known| Arc::clone(&known.state))
        else {
            return;
        };
        let mut state = lock(&state);
        state.ended = Some(status);
        if let Some(idle) = state.settled() {
            let child = v2::SessionId::new(child);
            tell(cx, parent, &child, &mut state, Told::Idle, idle);
        }
    }

    /// Forgets `parent`'s children and stops their relays, as closing the
    /// parent or resuming it does: after a close the host may no longer
    /// name them, and a resume announces them again.
    pub(super) fn release(&self, parent: &str) {
        let released: Vec<Child> = {
            let mut children = lock(&self.children);
            let ids: Vec<String> = children
                .iter()
                .filter(|(_, child)| child.parent == parent)
                .map(|(id, _)| id.clone())
                .collect();
            ids.iter().filter_map(|id| children.remove(id)).collect()
        };
        for child in &released {
            lock(&child.state).released = true;
        }
        // Each stops its relay as it drops, outside the lock.
        drop(released);
    }

    /// The children of a resume of `parent`, which announced them again
    /// before this: relays each that runs in `work` again, and each session
    /// it started, which it announces again here with its title, from its
    /// start as history when the resume replayed, and otherwise from now.
    /// A replay waits for each child's history and gives every child it
    /// announced its own `replay_complete`, all before the response. The
    /// children's requests wait until the returned gate opens, once the
    /// host has the response.
    pub(super) async fn resume(
        &self,
        cx: &V2ConnectionTo<Client>,
        parent: &v2::SessionId,
        work: &[BackgroundWork],
        resumed: Resumed,
    ) -> AskGate {
        let (gate, asking) = Asking::after();
        let mut relayable: HashMap<String, SessionId> = sessions(work).collect();
        for started in self.started_by(parent).await {
            let id = v2::SessionId::new(started.session.as_str());
            self.announce(cx, parent, &id, ChildKind::Started, started.title);
            relayable.insert(id.0.to_string(), started.session);
        }
        let announced: Vec<String> = lock(&self.children)
            .iter()
            .filter(|(_, child)| child.parent == parent.0.as_ref())
            .map(|(id, _)| id.clone())
            .collect();
        let mut caught_up = Vec::new();
        for child in announced {
            match (relayable.get(&child), resumed) {
                (Some(session), Resumed::Replayed) => {
                    let (told, waited) = oneshot::channel();
                    let history = Show::History {
                        port: V2Port::child(cx.clone(), ChildReplay::History),
                        caught_up: told,
                    };
                    self.relay(cx, parent, child, session.clone(), history, asking.clone());
                    caught_up.push(waited);
                }
                (Some(session), Resumed::Current) => {
                    self.relay(
                        cx,
                        parent,
                        child,
                        session.clone(),
                        Show::Skip,
                        asking.clone(),
                    );
                }
                (None, Resumed::Replayed) => {
                    send(cx, &v2::SessionId::new(child), replay_complete());
                }
                (None, Resumed::Current) => {}
            }
        }
        for waited in caught_up {
            // A relay that stopped first ended its history as it did.
            let _ = waited.await;
        }
        gate
    }

    /// The sessions `parent` started, with their titles, as the daemon's
    /// job list says.
    async fn started_by(&self, parent: &v2::SessionId) -> Vec<StartedChild> {
        match self.daemon.request::<JobList>(&JobListParams {}).await {
            Ok(response) => started_by(&response.jobs, &SessionId::new(parent.0.as_ref())),
            Err(error) => {
                tracing::debug!(%error, "could not list the sessions a session started");
                Vec::new()
            }
        }
    }

    /// Starts relaying `child`'s `session`, showing the replay of its first
    /// observe as `show` says, unless a relay of it still runs: that one
    /// shows the child live, so a history asked of it is over at once. A
    /// relay that takes over from one that stopped shows no live replay
    /// again.
    fn relay(
        &self,
        cx: &V2ConnectionTo<Client>,
        parent: &v2::SessionId,
        child: String,
        session: SessionId,
        show: Show,
        asking: Asking,
    ) {
        let mut children = lock(&self.children);
        let Some(known) = children.get_mut(&child) else {
            return;
        };
        let child = v2::SessionId::new(child);
        let show = match &known.relay {
            Some(relay) if !relay.is_finished() => {
                show.over(cx, &child);
                return;
            }
            // One that stopped, as when it lost the daemon, showed what the
            // child did until then.
            Some(_) => match show {
                Show::Live => Show::Skip,
                show @ (Show::Skip | Show::History { .. }) => show,
            },
            None => show,
        };
        let state = Arc::clone(&known.state);
        lock(&state).unrelayed = false;
        let features = *lock(&self.features);
        let port = Arc::new(V2Port::child(cx.clone(), ChildReplay::Live));
        let inputs = known.kind.asks_host().then(|| {
            ChildInputs::new(
                Arc::clone(&self.daemon),
                session.clone(),
                &child,
                Arc::clone(&port),
                features,
                Arc::clone(&self.placeholders),
                asking,
            )
        });
        let relay = Relay {
            daemon: Arc::clone(&self.daemon),
            kind: known.kind,
            state,
            port,
            show,
            parent: parent.clone(),
            child,
            session,
            updates: Updates::new(features),
            position: None,
            pending: None,
            inputs,
        };
        known.relay = Some(tokio::spawn(relay.run()));
    }
}

/// The running subagents of `work` that have a session, by ACP id.
fn sessions(work: &[BackgroundWork]) -> impl Iterator<Item = (String, SessionId)> + '_ {
    work.iter()
        .filter(|work| work.status.is_running())
        .filter_map(|work| match &work.item {
            BackgroundItem::Subagent {
                run,
                session: Some(session),
            } => Some((child_id(run, Some(session)), session.clone())),
            _ => None,
        })
}

/// A child's state, as its own `state_update` and the parent's mirror tell
/// it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Told {
    Running,
    RequiresAction,
    Idle,
    Unknown,
}

/// Tells the host child `child` of `parent` is in state `update`, which is
/// `told`, on the child and then as the parent's mirror, unless that is
/// what it was told last.
pub(super) fn tell(
    cx: &V2ConnectionTo<Client>,
    parent: &v2::SessionId,
    child: &v2::SessionId,
    state: &mut ChildState,
    told: Told,
    update: v2::StateUpdate,
) {
    if state.released || state.told == Some(told) {
        return;
    }
    state.told = Some(told);
    send(cx, child, v2::SessionUpdate::StateUpdate(update.clone()));
    let mirror = v2::SubagentUpdate::new(child.clone()).state(update);
    send(cx, parent, v2::SessionUpdate::SubagentUpdate(mirror));
}

/// A child's `config_option_update`: its options as any session's, each
/// `select` offering only its current value, as the host may not change
/// them.
pub(super) fn child_options(options: &SessionOptions) -> Result<v2::SessionUpdate, AcpError> {
    let options = requests::setup(options, Toggles::Select)?
        .config_options
        .into_iter()
        .map(|mut option| {
            if let v2::SessionConfigKind::Select(select) = &mut option.kind {
                let current = select.current_value.clone();
                let choices = match &select.options {
                    v2::SessionConfigSelectOptions::Grouped(groups) => {
                        groups.iter().flat_map(|group| &group.options).collect()
                    }
                    v2::SessionConfigSelectOptions::Ungrouped(choices) => choices.iter().collect(),
                    // A shape a newer schema adds.
                    _ => Vec::new(),
                };
                let kept: Vec<_> = choices
                    .into_iter()
                    .filter(|choice| choice.value == current)
                    .cloned()
                    .collect();
                if kept.is_empty() {
                    tracing::warn!(
                        option = %option.config_id.0,
                        "a subagent's option offers no choice for its current value"
                    );
                } else {
                    select.options = kept.into();
                }
            }
            option
        })
        .collect();
    Ok(v2::SessionUpdate::ConfigOptionUpdate(
        v2::ConfigOptionUpdate::new(options),
    ))
}

pub(super) fn replay_complete() -> v2::SessionUpdate {
    v2::SessionUpdate::ReplayComplete(v2::ReplayComplete::new())
}

/// Sends `update` on `session`; a host that is gone hears nothing more.
/// Nothing a relay sends announces a child, and [`Subagents::announce`]
/// records the child it announces first.
pub(super) fn send(
    cx: &V2ConnectionTo<Client>,
    session: &v2::SessionId,
    update: v2::SessionUpdate,
) {
    let notification = v2::UpdateSessionNotification::new(session.clone(), update);
    if let Err(error) = cx.send_notification(notification) {
        tracing::debug!(%error, "could not send a subagent's update over ACP v2");
    }
}

pub(super) fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
    mutex.lock().unwrap_or_else(PoisonError::into_inner)
}

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