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
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
//! A session's pump: the one task that relays its attachments' events to
//! the host, in order, with the [`Control`]s its requests hand it.
//!
//! The pump owns the session's place in the stream ([`StreamPosition`]),
//! so it alone attaches again: when a request finds the session stale
//! ([`Control::Resume`]), and at once when the daemon drops an attachment
//! that fell behind (`Lagged`).
//!
//! A prompt of this host's is matched to its turn by the turn's id, which
//! the daemon answers the prompt with ([`Armed`]): the pump reads nothing
//! past [`Control::Arm`] until it has that id, so it never guesses whose
//! turn an event is of. Until the host prompts, the pump follows the turn
//! the host was told is running when it attached ([`Following::Announced`]).
//!
//! The pump also keeps the session's background work for the host
//! ([`Shared`]'s): each attach's, once its replay is through, and each
//! change the daemon sends, which it tells the host through
//! [`AcpClientPort::background_changed`].

use std::sync::{Arc, PoisonError};

use agent_client_protocol::{
    v1::schema::{MessageId, SessionInfoUpdate, SessionUpdate},
    Error as AcpError,
};
use rho_protocol::{
    BackgroundWork, DetachReason, InputRequest, JobState, Replay, Seq, SessionAttachResponse,
    SessionEvent, SessionOptions, SessionSetup, TurnId, TurnOutcome,
};
use tokio::{
    sync::{mpsc, oneshot},
    task::JoinHandle,
};

use super::{
    busy, lock, Attacher, Attachment, Control, Inbound, Opening, Replayed, Shared, Show, Waiter,
};
use crate::{
    app::{
        acp::{
            daemon,
            inputs::{InputContext, Inputs},
            prompt,
            updates::{self, Delivery, Updates},
            AcpClientPort, BackgroundChanged, Foreground, TurnEnd,
        },
        daemon_client::{HerdrStatus, Part, Routed, StreamPosition},
    },
    herdr::HerdrReporter,
};

/// Starts the pump of session `context.session` on the attach that opened
/// it, before it reads anything else from `inbound`.
pub(super) fn spawn(
    context: InputContext,
    attacher: Arc<dyn Attacher>,
    inbound: mpsc::UnboundedReceiver<Inbound>,
    shared: Arc<Shared>,
    setup: SessionSetup,
    herdr: &HerdrReporter,
    opening: Opening,
) -> JoinHandle<()> {
    let pump = Pump {
        updates: Updates::new(context.features),
        herdr: HerdrStatus::new(herdr, &context.session),
        position: StreamPosition::attached(&opening.response),
        context,
        attacher,
        inbound,
        shared,
        setup,
        turn: None,
        following: busy(opening.response.state)
            .then(|| opening.response.turn.clone())
            .flatten()
            .map(Following::Announced),
        inputs: Inputs::default(),
        replaying: None,
    };
    tokio::spawn(pump.run(opening))
}

/// An attachment's replay in progress.
struct Replaying {
    show: Show,
    /// The title to send a host shown history once it is through; cleared
    /// when the history carried one.
    title: Option<String>,
    /// The input requests open when the attachment began.
    inputs: Vec<InputRequest>,
    /// The background work the replay ends with, as the attach answered.
    background: Vec<BackgroundWork>,
    /// The job state the replay ends in, and the turn it is of, as the
    /// attach answered.
    state: JobState,
    turn: Option<TurnId>,
    done: Replayed,
    /// Released once the host has the response that names the session;
    /// only the attach that opened it has one.
    gate: Option<oneshot::Receiver<()>>,
}

/// The turn the pump follows for the host, whose end it must report.
enum Following {
    /// The prompt of this host's that the pump waits on.
    Prompt(Armed),
    /// A turn the host was told is running that no prompt of its own runs:
    /// the one under way when the opening attach began, as ACP v2
    /// `session/resume` reports `running` from the same attach state
    /// (`v2::state`), or one that began while the pump followed none.
    /// A prompt of this host's replaces it unreported, since that prompt's
    /// own updates then give the session's state.
    Announced(TurnId),
}

impl Following {
    fn turn(&self) -> &TurnId {
        match self {
            Self::Prompt(armed) => &armed.turn,
            Self::Announced(turn) => turn,
        }
    }
}

/// The prompt of this host's that the pump waits on, by its turn.
struct Armed {
    /// The turn the daemon answered the prompt with.
    turn: TurnId,
    waiter: Waiter,
    /// Whether the turn's user message, the prompt's own, went by.
    shown: bool,
    /// Whether a background change went unrepeated in a `state_update`
    /// before the prompt was acknowledged (see [`Pump::told_foreground`]).
    withheld: bool,
}

struct Pump {
    context: InputContext,
    attacher: Arc<dyn Attacher>,
    inbound: mpsc::UnboundedReceiver<Inbound>,
    updates: Updates,
    shared: Arc<Shared>,
    setup: SessionSetup,
    herdr: HerdrStatus,
    /// The turn the session's job is in or last ran, as its last state
    /// said.
    turn: Option<TurnId>,
    following: Option<Following>,
    inputs: Inputs,
    position: StreamPosition,
    replaying: Option<Replaying>,
}

impl Pump {
    async fn run(mut self, opening: Opening) {
        let Opening {
            response,
            show,
            replayed,
            gate,
        } = opening;
        self.begin(response, show, replayed, Some(gate)).await;
        while let Some(next) = self.inbound.recv().await {
            match next {
                Inbound::Routed(routed) => self.routed(routed).await,
                Inbound::Control(control) => self.control(control).await,
            }
        }
    }

    /// Whether the attachment delivers; what the router reads for an ended
    /// one is dropped.
    fn attached(&self) -> bool {
        matches!(*self.shared.attachment.borrow(), Attachment::Attached(_))
    }

    async fn routed(&mut self, routed: Routed) {
        if !self.attached() {
            return;
        }
        match routed {
            Routed::Event { seq, event } => self.event(seq, event).await,
            Routed::Detached(reason) => self.detached(reason).await,
            Routed::Lost => self.end(Attachment::Stale, daemon::lost()),
        }
    }

    async fn control(&mut self, control: Control) {
        match control {
            Control::Resume(replayed) => match self.reattach().await {
                Ok((response, show)) => self.begin(response, show, replayed, /*gate*/ None).await,
                Err(error) => {
                    let _ = replayed.send(Err(error));
                }
            },
            // Waits for the daemon's answer to the prompt before it reads
            // on: the turn's events, which queue behind this, are then told
            // from every other turn's by its id. A prompt the daemon
            // refused, or one that ended before it began, has no turn to
            // wait on.
            Control::Arm { waiter, turn } if self.attached() => {
                if let Ok(turn) = turn.await {
                    self.following = Some(Following::Prompt(Armed {
                        turn,
                        waiter,
                        shown: false,
                        withheld: false,
                    }));
                }
            }
            // The attachment ended between the prompt's reattach and now.
            Control::Arm { waiter, .. } => {
                let _ = waiter.outcome.send(Err(daemon::lost()));
            }
            Control::Options(options, told) => {
                self.options_changed(*options).await;
                let _ = told.send(());
            }
            Control::Flush(done) => {
                let _ = done.send(());
            }
        }
    }

    /// Attaches again after the cursor. Returns the response with what its
    /// replay shows: the events the host missed show as live, and a reset's
    /// history, which the host has, is skipped.
    async fn reattach(&self) -> Result<(SessionAttachResponse, Show), AcpError> {
        let response = self
            .attacher
            .attach(&self.context.session, self.position.cursor(), &self.setup)
            .await?;
        let show = Show::resumed(response.replay);
        Ok((response, show))
    }

    /// Starts relaying the attachment `response` began.
    async fn begin(
        &mut self,
        response: SessionAttachResponse,
        show: Show,
        done: Replayed,
        gate: Option<oneshot::Receiver<()>>,
    ) {
        self.position.reattached(&response);
        self.options_changed(response.options).await;
        self.shared
            .attachment
            .send_replace(Attachment::Attached(response.state));
        self.herdr.report(response.state).await;
        // A reset starts over with the saved conversation, whose messages
        // are of turns its states have yet to name.
        if response.replay == Replay::Reset {
            self.turn = None;
        }
        self.replaying = Some(Replaying {
            show,
            title: response.title,
            inputs: response.inputs,
            background: response.background,
            state: response.state,
            turn: response.turn,
            done,
            gate,
        });
        if !self.position.replaying() {
            self.end_replay().await;
        }
    }

    async fn event(&mut self, seq: Seq, event: SessionEvent) {
        let left = match self.position.observe(seq) {
            Part::Live => return self.live(event).await,
            Part::Replayed { left, .. } => left,
        };
        let Some(replaying) = self.replaying.as_mut() else {
            return;
        };
        match replaying.show.clone() {
            Show::History(port) => {
                if matches!(event, SessionEvent::TitleChanged { .. }) {
                    replaying.title = None;
                }
                for update in self.updates.map(&event) {
                    self.send(&*port, update, Delivery::Replay).await;
                }
            }
            Show::Missed => self.live(event).await,
            // The host has the history; only the followed turn reads it.
            Show::Skip => {
                self.follow_turn(&event);
            }
        }
        if left == 0 {
            self.end_replay().await;
        }
    }

    /// Sends the title a history may lack, fails a prompt whose turn's
    /// end a skipped replay no longer held, takes the attach's background
    /// work, answers whoever waits for the replay, waits for the host's
    /// response, then puts the open input requests to the host.
    async fn end_replay(&mut self) {
        let Some(Replaying {
            show,
            title,
            inputs,
            background,
            state,
            turn,
            done,
            gate,
        }) = self.replaying.take()
        else {
            return;
        };
        self.turn = turn;
        match (show, title) {
            (Show::History(port), Some(title)) => {
                let update =
                    SessionUpdate::SessionInfoUpdate(SessionInfoUpdate::new().title(title));
                self.send(&*port, update, Delivery::Replay).await;
            }
            (Show::Skip, _) => self.fail_unreplayed(state),
            (Show::History(_) | Show::Missed, _) => {}
        }
        // A reattach tells the host what changed meanwhile; the attach that
        // opened the session already holds this work.
        self.background_changed(background);
        let _ = done.send(Ok(()));
        if let Some(gate) = gate {
            // A request that failed to respond drops the gate; the events
            // still belong to the session.
            let _ = gate.await;
        }
        for request in inputs {
            self.inputs.open(request, &self.context);
        }
    }

    /// A skipped reset replay is over, ending with the job in `state`, of
    /// the turn the attach named, now `self.turn`. It held the followed
    /// turn's end unless another turn saved since: a followed turn that is
    /// no longer the one under way ended unseen, and fails.
    fn fail_unreplayed(&mut self, state: JobState) {
        let under_way = busy(state).then_some(self.turn.as_ref()).flatten();
        if self
            .following
            .as_ref()
            .is_some_and(|following| under_way != Some(following.turn()))
        {
            self.fail(AcpError::internal_error().data(
                "the prompt's turn ended while this client was behind, and the rho daemon no longer replays how",
            ));
        }
    }

    async fn live(&mut self, event: SessionEvent) {
        let own = self.follow_turn(&event);
        match event {
            // The host already shows its own prompt.
            SessionEvent::UserMessage { .. } if own => {}
            // The followed turn's, which `follow_turn` settled, or one the
            // host follows no other way.
            SessionEvent::TurnEnded { .. } => {}
            SessionEvent::State { state, turn } => {
                let before = self
                    .shared
                    .attachment
                    .send_replace(Attachment::Attached(state))
                    .foreground();
                self.foreground_changed(before, Foreground::of(state), turn);
                self.herdr.report(state).await;
            }
            SessionEvent::InputRequested { request } => self.inputs.open(*request, &self.context),
            SessionEvent::InputResolved { id, .. } => self.inputs.resolve(id),
            SessionEvent::OptionsChanged { options } => self.options_changed(*options).await,
            SessionEvent::Background { work } => self.background_changed(work),
            // Another client's prompt, or a steer.
            event => self.send_mapped(&event).await,
        }
    }

    /// Reads what `event` says of the followed turn: the first user message
    /// of an armed prompt's turn that is no steer is the prompt's own, which
    /// accepts it, and the followed turn's end settles it. Returns whether
    /// `event` is that user message. A prompt that gave up (its receiver is
    /// gone) is dropped.
    fn follow_turn(&mut self, event: &SessionEvent) -> bool {
        if let SessionEvent::State { turn, .. } = event {
            self.turn.clone_from(turn);
        }
        if matches!(
            &self.following,
            Some(Following::Prompt(armed)) if armed.waiter.outcome.is_closed()
        ) {
            self.following = None;
        }
        if let SessionEvent::TurnEnded { turn, outcome } = event {
            if self
                .following
                .as_ref()
                .is_some_and(|following| following.turn() == turn)
            {
                self.settle(Ok(outcome.clone()));
            }
            return false;
        }
        let Some(Following::Prompt(armed)) = self.following.as_mut() else {
            return false;
        };
        match event {
            // A steer applies within the turn under way; it never starts
            // one.
            SessionEvent::UserMessage {
                message,
                steer: None,
                ..
            } if !armed.shown && self.turn.as_ref() == Some(&armed.turn) => {
                armed.shown = true;
                let accept = armed
                    .waiter
                    .accept
                    .lock()
                    .unwrap_or_else(PoisonError::into_inner)
                    .take();
                if let Some(accept) = accept {
                    accept(MessageId::new(message.as_str()));
                }
                true
            }
            _ => false,
        }
    }

    /// Settles the followed turn, if any. The host hears it end before
    /// anything the pump reads next, as this is the only place a turn's
    /// end is told: an announced turn with the outcome's stop reason, or
    /// unseen when the pump lost track of it (`end` is the error); an armed
    /// prompt's turn with the stop reason or error, once acknowledged,
    /// before the prompt hears `end`. A prompt whose turn ended before its
    /// user message went by is acknowledged here, as the daemon saved it.
    fn settle(&mut self, end: Result<TurnOutcome, AcpError>) {
        let told = match self.following.take() {
            Some(Following::Prompt(armed)) => {
                let told = match (&end, armed.shown) {
                    (Ok(_), shown) => {
                        if !shown {
                            let accept = armed
                                .waiter
                                .accept
                                .lock()
                                .unwrap_or_else(PoisonError::into_inner)
                                .take();
                            if let Some(accept) = accept {
                                accept(MessageId::new(format!(
                                    "rho-user-{}",
                                    uuid::Uuid::new_v4()
                                )));
                            }
                        }
                        Some(TurnEnd::Ended(end.clone().and_then(prompt::stop_reason)))
                    }
                    (Err(error), true) => Some(TurnEnd::Ended(Err(error.clone()))),
                    // The prompt fails unacknowledged; only the state its
                    // wait withheld is owed.
                    (Err(_), false) => armed.withheld.then_some(TurnEnd::Unseen),
                };
                self.tell_turn_ended(told);
                let _ = armed.waiter.outcome.send(end);
                return;
            }
            Some(Following::Announced(_)) => Some(match end {
                Ok(outcome) => TurnEnd::Ended(prompt::stop_reason(outcome)),
                Err(_) => TurnEnd::Unseen,
            }),
            None => None,
        };
        self.tell_turn_ended(told);
    }

    fn tell_turn_ended(&self, end: Option<TurnEnd>) {
        if let Some(end) = end {
            let background = lock(&self.shared.background);
            self.context
                .port
                .turn_ended(&self.context.acp_id, end, &background);
        }
    }

    /// Takes `work` as the session's background work and tells the host
    /// how it changed, if it did.
    fn background_changed(&mut self, work: Vec<BackgroundWork>) {
        let foreground = self.told_foreground();
        let mut background = lock(&self.shared.background);
        if *background == work {
            return;
        }
        if let Some(Following::Prompt(armed)) = &mut self.following {
            armed.withheld |= foreground.is_none();
        }
        let previous = std::mem::replace(&mut *background, work);
        self.context.port.background_changed(
            &self.context.acp_id,
            BackgroundChanged {
                previous: &previous,
                current: &background,
                foreground,
            },
        );
    }

    /// What the host was told the session's foreground work is doing: a
    /// turn it follows, as the job's state has it, or else idle, since the
    /// host hears of no other turn. `None` while a prompt of the host's
    /// waits to be acknowledged: the host was told idle, but T3 Code ends
    /// its pending prompt on any `idle`, and the acknowledgement's
    /// `running` comes next.
    fn told_foreground(&self) -> Option<Foreground> {
        match &self.following {
            Some(Following::Announced(_) | Following::Prompt(Armed { shown: true, .. })) => {
                Some(self.shared.attachment.borrow().foreground())
            }
            Some(Following::Prompt(Armed { shown: false, .. })) => None,
            None => Some(Foreground::Idle),
        }
    }

    /// Tells the host of a change from `before` to `now` it hears no other
    /// way: a turn it does not follow beginning, as another client's prompt
    /// or a turn the daemon starts as background work finishes, which the
    /// pump follows from then on ([`Following::Announced`]); or the turn it
    /// follows starting or stopping to wait for a person. A prompt reports
    /// its own turn's start, and a followed turn's end is reported as it
    /// settles.
    fn foreground_changed(&mut self, before: Foreground, now: Foreground, turn: Option<TurnId>) {
        if before == Foreground::Idle && now != Foreground::Idle {
            let (None, Some(turn)) = (&self.following, turn) else {
                return;
            };
            self.following = Some(Following::Announced(turn));
        } else if before == now || now == Foreground::Idle {
            return;
        }
        if self
            .told_foreground()
            .is_none_or(|told| told == Foreground::Idle)
        {
            return;
        }
        let background = lock(&self.shared.background);
        self.context
            .port
            .foreground_changed(&self.context.acp_id, now, &background);
    }

    async fn options_changed(&mut self, options: SessionOptions) {
        let old = std::mem::replace(&mut *lock(&self.shared.options), options.clone());
        let port = Arc::clone(&self.context.port);
        for update in updates::options_changed(&old, &options, self.context.features) {
            self.send(&*port, update, Delivery::Live).await;
        }
    }

    async fn detached(&mut self, reason: DetachReason) {
        match reason {
            // Fell behind: resume after the cursor at once. Nobody waits
            // for this replay.
            DetachReason::Lagged => match self.reattach().await {
                Ok((response, show)) => {
                    let (replayed, _) = oneshot::channel();
                    self.begin(response, show, replayed, /*gate*/ None).await;
                }
                Err(error) => self.end(Attachment::Stale, error),
            },
            DetachReason::DaemonStopping => self.end(
                Attachment::Stale,
                AcpError::internal_error().data("rho daemon is stopping"),
            ),
            // Re-executing in place: the next request attaches again on a
            // new connection, which waits for the restarted daemon. Only a
            // prompt waiting on a turn the restart interrupted hears of it.
            DetachReason::Restarting => self.end(
                Attachment::Stale,
                AcpError::internal_error().data("rho daemon restarted"),
            ),
            DetachReason::Deleted => {
                let error =
                    crate::app::acp::resource_not_found(Some(self.context.acp_id.0.to_string()));
                self.end(Attachment::Deleted, error);
            }
            // `Unknown`, or a reason a newer daemon sends: attach again on
            // the next request.
            _ => self.end(Attachment::Stale, daemon::lost()),
        }
    }

    /// Ends the attachment as `attachment`: the prompt waiting on it fails
    /// with `error`, an announced turn ends unseen, and the host's input
    /// prompts are withdrawn.
    fn end(&mut self, attachment: Attachment, error: AcpError) {
        self.fail(error);
        self.inputs.abort_all();
        self.replaying = None;
        self.shared.attachment.send_replace(attachment);
    }

    /// Fails the followed turn, if any, with `error`.
    fn fail(&mut self, error: AcpError) {
        self.settle(Err(error));
    }

    async fn send_mapped(&mut self, event: &SessionEvent) {
        let port = Arc::clone(&self.context.port);
        for update in self.updates.map(event) {
            self.send(&*port, update, Delivery::Live).await;
        }
    }

    async fn send(&self, port: &dyn AcpClientPort, update: SessionUpdate, delivery: Delivery) {
        let notification = updates::notification(&self.context.acp_id, update, delivery);
        if let Err(error) = port.send_session_notification(notification).await {
            tracing::warn!(%error, "could not send an ACP session update");
        }
    }
}

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