rho-coding-agent 3.9.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
//! The event pump for one turn: SDK run events, approval requests, plan
//! approvals, secret asks, questions for the user, the session's
//! subagents' questions among them, and applied background results,
//! reported to the host in arrival order as [`SessionEvent`]s, with the
//! host's [`TurnControl`] answers routed back to whatever asked.
//!
//! The pump never waits on the host. Requests stay pending until the host
//! answers or the turn withdraws them: a cancel answers open approvals as
//! cancelled and withdraws plan approvals, secret asks, and questions, and the end of the
//! run withdraws its questions, which wait on the user rather than the run.
//!
//! Every run event also feeds the session's compaction follow-up (see
//! [`crate::compaction_metrics`]) before the host sees it.

use std::{
    collections::{BTreeMap, BTreeSet},
    future::Future,
    pin::Pin,
};

use futures_util::stream::{FuturesUnordered, StreamExt};
use rho_sdk::{
    hooks::HookDispatcher, ApprovalRequestReceiver, CancellationToken, HostInputId,
    HostInputRefusal, HostInputResponse, PendingApproval, RunEvent, SessionId, UserInput,
};
use tokio::sync::{mpsc, oneshot};

use super::{
    delegation::OfferedDisplays,
    events::{
        cancelled_approval, ApprovalId, PlanApprovalId, PlanApprovalRequest, SecretAskId,
        SessionEvent, TurnControl,
    },
    persist::TurnCheckpoint,
    turn::TurnIo,
    QuestionSupport,
};
use crate::{
    app::subagent_host_input::{OpenChildQuestions, SubagentHostInputRequest},
    diagnostics::RuntimeDiagnostics,
    display_transcript::DisplayTranscript,
    tools::{
        mcp::secret_tool::{PendingSecret, SecretOutcome, SecretRequestReceiver},
        plan_exit::{PlanExitDecision, PlanPermissionReceiver, PlanPermissionRequest},
    },
};

pub(super) enum EventSource<'a> {
    Run(&'a mut rho_sdk::Run),
    #[cfg(test)]
    Channel(&'a mut tokio::sync::mpsc::UnboundedReceiver<RunEvent>),
}

impl EventSource<'_> {
    async fn next(&mut self) -> Option<RunEvent> {
        match self {
            Self::Run(run) => run.next_event().await,
            #[cfg(test)]
            Self::Channel(events) => events.recv().await,
        }
    }

    fn cancel_run(&mut self) {
        match self {
            Self::Run(run) => run.cancel(),
            #[cfg(test)]
            Self::Channel(_) => {}
        }
    }

    /// Answers a host input request. The run acknowledges asynchronously;
    /// nothing waits for it, because a request the run no longer holds
    /// (its tool finished or was cancelled) has nobody left to tell.
    fn answer(&mut self, id: HostInputId, answer: HostInputAnswer) {
        match self {
            Self::Run(run) => {
                let queued = match answer {
                    Ok(response) => run.request_respond(id, response).map(drop),
                    Err(refusal) => run.request_refuse(id, refusal).map(drop),
                };
                if let Err(error) = queued {
                    tracing::warn!(%error, "could not answer a host input request");
                }
            }
            #[cfg(test)]
            Self::Channel(_) => {}
        }
    }
}

type HostInputAnswer = Result<HostInputResponse, HostInputRefusal>;

pub(super) enum ApprovalSource<'a> {
    Receiver(Option<&'a mut ApprovalRequestReceiver>),
    #[cfg(test)]
    Channel(&'a mut tokio::sync::mpsc::UnboundedReceiver<PendingApproval>),
}

impl ApprovalSource<'_> {
    async fn next(&mut self) -> Option<PendingApproval> {
        match self {
            Self::Receiver(None) => std::future::pending().await,
            Self::Receiver(Some(receiver)) => receiver.recv().await,
            #[cfg(test)]
            Self::Channel(approvals) => approvals.recv().await,
        }
    }
}

pub(super) struct PumpSources<'a> {
    pub(super) cancel: CancellationToken,
    /// Whether the session's host can put the run's questions to a person.
    pub(super) questions: QuestionSupport,
    pub(super) events: EventSource<'a>,
    pub(super) approvals: ApprovalSource<'a>,
    /// Plan approvals from `exit_plan_mode`; `None` when the session has no
    /// plan handoff.
    pub(super) plan_approvals: Option<&'a mut PlanPermissionReceiver>,
    /// Secret asks from `mcp_request_secret`; `None` when the session's
    /// host cannot take them.
    pub(super) secret_asks: Option<&'a mut SecretRequestReceiver>,
    /// Background results offered to the run; tests of the event and
    /// approval plumbing pass `None`.
    pub(super) displays: Option<AppliedDisplays<'a>>,
    /// The session's hooks, told whenever the turn waits for a person, so a
    /// user away from every client can learn of it (#1660). They are told
    /// after the host has the request, so a hook that reacts by attaching a
    /// client finds it open.
    pub(super) hooks: HookDispatcher,
    pub(super) session: &'a SessionId,
    /// Questions the session's subagents ask, which wait for the same
    /// person; `None` when the session runs no subagents of its own.
    pub(super) child_questions: Option<&'a mut mpsc::Receiver<SubagentHostInputRequest>>,
    /// The session's diagnostics, whose latest compaction counts what
    /// follows its commit.
    pub(super) diagnostics: &'a RuntimeDiagnostics,
}

/// Background results handed to the model during one turn. Each is shown
/// where the run applied it and saved with the turn so a reload replays it.
pub(super) struct AppliedDisplays<'a> {
    pub(super) offered: OfferedDisplays,
    pub(super) checkpoint: &'a TurnCheckpoint,
}

impl AppliedDisplays<'_> {
    /// Records the rows for an applied boundary input and returns them to
    /// show.
    fn record(&mut self, input: &UserInput) -> Option<DisplayTranscript> {
        let transcript = self.offered.applied(input)?;
        self.checkpoint
            .record_display(input, transcript.display_message());
        Some(transcript)
    }
}

/// A plan approval or secret ask the host may still answer. It ends with
/// the answer passed on, or withdrawn when the tool stops waiting first.
type ToolWait = Pin<Box<dyn Future<Output = Settled> + Send>>;

enum Settled {
    Answered,
    PlanWithdrawn(PlanApprovalId),
    SecretWithdrawn(SecretAskId),
}

/// Requests the host has not answered yet.
#[derive(Default)]
struct Pending {
    approvals: BTreeMap<ApprovalId, PendingApproval>,
    plans: BTreeMap<PlanApprovalId, oneshot::Sender<PlanExitDecision>>,
    secrets: BTreeMap<SecretAskId, oneshot::Sender<SecretOutcome>>,
    questions: BTreeSet<HostInputId>,
    child_questions: OpenChildQuestions,
    next_approval: u64,
    next_plan: u64,
    next_secret: u64,
}

/// Runs the turn's sources until the run's events end and no approval waits
/// on the host. Fails only when the host reports it could not deliver
/// ([`TurnControl::HostFailed`]) or stops answering altogether.
pub(super) async fn pump(sources: PumpSources<'_>, io: &mut TurnIo) -> anyhow::Result<()> {
    let PumpSources {
        cancel,
        questions,
        mut events,
        mut approvals,
        mut plan_approvals,
        mut secret_asks,
        mut displays,
        hooks,
        session,
        mut child_questions,
        diagnostics,
    } = sources;
    let mut cancelled = cancel.is_cancelled();
    let mut events_open = true;
    let mut approvals_open = true;
    let mut pending = Pending::default();
    let mut tool_waits: FuturesUnordered<ToolWait> = FuturesUnordered::new();
    loop {
        if !events_open && pending.approvals.is_empty() && tool_waits.is_empty() {
            return Ok(());
        }
        tokio::select! {
            biased;

            () = cancel.cancelled(), if !cancelled => {
                cancelled = true;
                events.cancel_run();
                for (id, mut approval) in std::mem::take(&mut pending.approvals) {
                    let _ = approval.respond(cancelled_approval());
                    io.emit(SessionEvent::ApprovalWithdrawn { id });
                }
                // Dropping a plan's or secret's reply reports its call as
                // cancelled.
                tool_waits.clear();
                for id in std::mem::take(&mut pending.plans).into_keys() {
                    io.emit(SessionEvent::PlanApprovalWithdrawn { id });
                }
                for id in std::mem::take(&mut pending.secrets).into_keys() {
                    io.emit(SessionEvent::SecretWithdrawn { id });
                }
                // The run's cancellation ends the questions themselves.
                withdraw_questions(&mut pending, io);
            }

            event = events.next(), if events_open => {
                let Some(event) = event else {
                    events_open = false;
                    withdraw_questions(&mut pending, io);
                    io.emit(SessionEvent::RunClosed);
                    continue;
                };
                if let (RunEvent::BoundaryInputApplied { input, .. }, Some(displays)) =
                    (&event, displays.as_mut())
                {
                    if let Some(transcript) = displays.record(input) {
                        io.emit(SessionEvent::BoundaryApplied { transcript });
                    }
                }
                diagnostics.observe_run_event(&event);
                let asked = match &event {
                    RunEvent::HostInputRequested { request } => Some((request.clone(), None)),
                    RunEvent::ToolHostInputRequested { call_id, request } => {
                        Some((request.clone(), Some(call_id.clone())))
                    }
                    _ => None,
                };
                io.emit(SessionEvent::Run(event));
                if let Some((request, call_id)) = asked {
                    match (questions, cancelled) {
                        (QuestionSupport::Available, false) => {
                            pending.questions.insert(request.id().clone());
                            io.emit(SessionEvent::QuestionAsked {
                                id: request.id().clone(),
                                call_id,
                                request: request.clone(),
                            });
                            hooks.question_requested(session, &request);
                        }
                        // The run's cancellation ends the request.
                        (QuestionSupport::Available, true) => {}
                        // Rho offers no asking tools to such hosts; anything
                        // that asks anyway must not wait forever.
                        (QuestionSupport::Unavailable, _) => {
                            events.answer(request.id().clone(), Err(HostInputRefusal::Declined));
                        }
                    }
                }
            }

            approval = approvals.next(), if events_open && approvals_open => {
                let Some(mut approval) = approval else {
                    approvals_open = false;
                    continue;
                };
                if cancelled {
                    let _ = approval.respond(cancelled_approval());
                    continue;
                }
                let id = ApprovalId(pending.next_approval);
                pending.next_approval += 1;
                io.emit(SessionEvent::ApprovalRequested {
                    id,
                    request: approval.request().clone(),
                });
                hooks.approval_requested(session, approval.request());
                pending.approvals.insert(id, approval);
            }

            asked = next_child_question(child_questions.as_deref_mut()), if events_open => {
                let Some(asked) = asked else {
                    child_questions = None;
                    continue;
                };
                // Dropping the reply tells the subagent nobody will answer:
                // the turn is ending.
                if cancelled {
                    continue;
                }
                let (notice, request) = pending.child_questions.open(asked);
                io.emit(SessionEvent::Notice { text: notice });
                io.emit(SessionEvent::QuestionAsked {
                    id: request.id().clone(),
                    call_id: None,
                    request: request.clone(),
                });
                hooks.question_requested(session, &request);
            }

            // Its subagent stopped waiting, as one the parent stopped does.
            id = pending.child_questions.abandoned() => {
                io.emit(SessionEvent::QuestionWithdrawn { id });
            }

            request = next_request(plan_approvals.as_deref_mut()), if events_open => {
                let Some(request) = request else {
                    plan_approvals = None;
                    continue;
                };
                if cancelled {
                    // Dropping the reply reports the call as cancelled.
                    continue;
                }
                let id = PlanApprovalId(pending.next_plan);
                pending.next_plan += 1;
                let (answer, answered) = oneshot::channel();
                io.emit(SessionEvent::PlanApprovalRequested {
                    id,
                    request: PlanApprovalRequest {
                        call_id: request.call_id.clone(),
                        plan: request.plan.clone(),
                        targets: request.targets.clone(),
                    },
                });
                hooks.plan_approval_requested(session, &request.plan);
                pending.plans.insert(id, answer);
                tool_waits.push(Box::pin(wait_for_plan(id, request, answered)));
            }

            asked = next_request(secret_asks.as_deref_mut()), if events_open => {
                let Some(PendingSecret { request, reply }) = asked else {
                    secret_asks = None;
                    continue;
                };
                if cancelled {
                    // Dropping the reply reports the call as cancelled.
                    continue;
                }
                let id = SecretAskId(pending.next_secret);
                pending.next_secret += 1;
                let (answer, answered) = oneshot::channel();
                io.emit(SessionEvent::SecretRequested { id, request });
                pending.secrets.insert(id, answer);
                tool_waits.push(Box::pin(wait_for_secret(id, reply, answered)));
            }

            control = io.control.recv() => match control {
                Some(TurnControl::RespondApproval { id, decision }) => {
                    if let Some(mut approval) = pending.approvals.remove(&id) {
                        let _ = approval.respond(decision);
                    }
                }
                Some(TurnControl::AnswerPlan { id, answer }) => {
                    if let Some(reply) = pending.plans.remove(&id) {
                        let _ = reply.send(answer);
                    }
                }
                Some(TurnControl::AnswerSecret { id, outcome }) => {
                    if let Some(reply) = pending.secrets.remove(&id) {
                        let _ = reply.send(outcome);
                    }
                }
                Some(TurnControl::AnswerQuestion { id, answer }) => {
                    if pending.questions.remove(&id) {
                        events.answer(id, answer);
                    } else if let Some(notice) = pending.child_questions.answer(&id, answer) {
                        io.emit(SessionEvent::Notice { text: notice });
                    }
                }
                Some(TurnControl::HostFailed { message }) => return Err(anyhow::Error::msg(message)),
                // Nothing could answer the requests still pending, or any
                // later one.
                None => anyhow::bail!("the host stopped answering the turn"),
            },

            Some(settled) = tool_waits.next(), if !tool_waits.is_empty() => match settled {
                Settled::Answered => {}
                Settled::PlanWithdrawn(id) => {
                    if pending.plans.remove(&id).is_some() {
                        io.emit(SessionEvent::PlanApprovalWithdrawn { id });
                    }
                }
                Settled::SecretWithdrawn(id) => {
                    if pending.secrets.remove(&id).is_some() {
                        io.emit(SessionEvent::SecretWithdrawn { id });
                    }
                }
            },
        }
    }
}

/// Stops waiting on every open question, the run's and its subagents'.
fn withdraw_questions(pending: &mut Pending, io: &TurnIo) {
    let children = pending.child_questions.drop_all();
    for id in std::mem::take(&mut pending.questions)
        .into_iter()
        .chain(children)
    {
        io.emit(SessionEvent::QuestionWithdrawn { id });
    }
}

async fn next_child_question(
    questions: Option<&mut mpsc::Receiver<SubagentHostInputRequest>>,
) -> Option<SubagentHostInputRequest> {
    match questions {
        Some(questions) => questions.recv().await,
        None => std::future::pending().await,
    }
}

/// The next request a tool puts to the host, or never without a channel.
async fn next_request<T>(requests: Option<&mut mpsc::UnboundedReceiver<T>>) -> Option<T> {
    match requests {
        Some(requests) => requests.recv().await,
        None => std::future::pending().await,
    }
}

/// Passes the host's answer to a plan approval to the waiting tool.
async fn wait_for_plan(
    id: PlanApprovalId,
    request: PlanPermissionRequest,
    answered: oneshot::Receiver<PlanExitDecision>,
) -> Settled {
    if relay(request.reply, answered).await {
        Settled::Answered
    } else {
        Settled::PlanWithdrawn(id)
    }
}

/// Passes how the host settled a secret ask to the waiting tool.
async fn wait_for_secret(
    id: SecretAskId,
    reply: oneshot::Sender<SecretOutcome>,
    answered: oneshot::Receiver<SecretOutcome>,
) -> Settled {
    if relay(reply, answered).await {
        Settled::Answered
    } else {
        Settled::SecretWithdrawn(id)
    }
}

/// Passes the host's answer on to `reply`, unless the tool stops waiting
/// first or the host drops the request. Whether it passed one on.
async fn relay<T>(mut reply: oneshot::Sender<T>, answered: oneshot::Receiver<T>) -> bool {
    tokio::select! {
        biased;
        () = reply.closed() => false,
        answer = answered => match answer {
            Ok(answer) => {
                let _ = reply.send(answer);
                true
            }
            Err(_) => false,
        },
    }
}

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