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
420
421
422
423
424
425
426
427
428
429
430
//! A session's open input requests, put to the host.
//!
//! The daemon asks every attached client (`SessionEvent::InputRequested`);
//! the first answer wins and every client hears `InputResolved`. Each open
//! request is one task here that asks the host and sends its answer back;
//! a resolution, from this host or another client, aborts the task, which
//! drops the host request (the connection then cancels it).
//!
//! - An approval is `session/request_permission` on the call's card, or on
//!   a placeholder card for a call the host never saw.
//! - A plan approval is `session/request_permission` offering the modes,
//!   with the plan shown while it is asked ([`AcpClientPort::plan_proposed`]).
//! - A question is a form-mode `elicitation/create` on hosts that draw
//!   forms. A host without forms leaves it to the other clients: sessions
//!   it opens ask none (the daemon declines an MCP server's question
//!   itself), but a session another client opened may.
//!
//! Closing a session on ACP v2 withdraws its open requests from the host
//! before it answers ([`Asks::withdrawn`]).

use std::{
    collections::HashMap,
    future::Future,
    sync::{
        atomic::{AtomicU64, Ordering},
        Arc,
    },
};

use agent_client_protocol::{v1::schema::SessionId as AcpSessionId, Error as AcpError};
use rho_protocol::{
    methods::{SessionAnswer, SessionHold},
    Ask, ClientError, ErrorCode, InputAnswer, InputAsker, InputRequest, InputRequestId,
    SessionAnswerParams, SessionHoldParams, SessionId,
};
use tokio::{sync::watch, task::JoinHandle};

use super::{
    elicitation,
    host_features::{Forms, HostFeatures},
    permission::{self, Card},
    AcpClientPort,
};
use crate::app::daemon_client::Daemon;

/// What every input task of a session shares.
#[derive(Clone)]
pub(super) struct InputContext {
    pub(super) daemon: Arc<Daemon>,
    pub(super) session: SessionId,
    pub(super) acp_id: AcpSessionId,
    pub(super) port: Arc<dyn AcpClientPort>,
    pub(super) features: HostFeatures,
    /// Numbers the placeholder cards of calls the host never saw, across
    /// this process's sessions.
    pub(super) placeholders: Arc<AtomicU64>,
    /// The session's input tasks, each of which may have a request open on
    /// the host.
    pub(super) asks: Asks,
    pub(super) cancels: TurnCancels,
    pub(super) timeouts: QuestionTimeouts,
    pub(super) asking: Asking,
}

/// When a session's requests may be put to the host: at once, or once an
/// [`AskGate`] opens, as a resumed parent's started children wait for the
/// host to have the resume's response. A request resolved meanwhile is
/// never asked.
#[derive(Clone)]
pub(super) struct Asking(Option<watch::Receiver<bool>>);

/// Lets the requests of an [`Asking::after`] through.
pub(super) struct AskGate(watch::Sender<bool>);

impl Asking {
    pub(super) fn now() -> Self {
        Self(None)
    }

    /// Asking once the returned gate opens, or is dropped, as by a resume
    /// that failed before it answered.
    pub(super) fn after() -> (AskGate, Self) {
        let (gate, asking) = watch::channel(false);
        (AskGate(gate), Self(Some(asking)))
    }

    async fn ready(&self) {
        if let Some(asking) = &self.0 {
            let _ = asking.clone().wait_for(|open| *open).await;
        }
    }
}

impl AskGate {
    pub(super) fn open(self) {
        self.0.send_replace(true);
    }
}

/// What asking the host a question does to its timeout.
#[derive(Clone, Copy)]
pub(super) enum QuestionTimeouts {
    /// Stops it for good: a person may take longer to fill a form than the
    /// timeout allows, in a session the host opened.
    Hold,
    /// Leaves it running: the question falls back to its default answers
    /// on time, whether the host's person answers or not.
    Keep,
}

/// Counts a session's input tasks until each is gone. A task that is
/// aborted drops its host request, which withdraws the request from the
/// host with `$/cancel_request` as it drops, so once none is left, none of
/// the session's requests is open on the host.
#[derive(Clone, Default)]
pub(super) struct Asks(Arc<watch::Sender<usize>>);

impl Asks {
    fn spawn(&self, ask: impl Future<Output = ()> + Send + 'static) -> JoinHandle<()> {
        self.0.send_modify(|tasks| *tasks += 1);
        // Moved into the task, so it drops with the task's future, even one
        // aborted before it first ran.
        let counted = Counted(Arc::clone(&self.0));
        tokio::spawn(async move {
            let _counted = counted;
            ask.await;
        })
    }

    /// Waits until every input task is gone: answered, or aborted, as when
    /// the session's pump stops.
    pub(super) async fn withdrawn(&self) {
        // The sender lives as long as `self`.
        let _ = self.0.subscribe().wait_for(|tasks| *tasks == 0).await;
    }
}

/// One input task, counted in its session's [`Asks`] while it lives.
struct Counted(Arc<watch::Sender<usize>>);

impl Drop for Counted {
    fn drop(&mut self) {
        self.0.send_modify(|tasks| *tasks -= 1);
    }
}

/// Counts the host's `session/cancel`s of one session. A cancel withdraws
/// the turn's open requests, so an answer the host gives after one is not
/// sent: it would race the cancel, and could land first. ACP v2 hosts
/// answer `cancelled` to the prompts a cancel leaves open, which would
/// otherwise reject the call before the cancel stops it.
#[derive(Clone, Default)]
pub(super) struct TurnCancels(Arc<AtomicU64>);

impl TurnCancels {
    pub(super) fn cancel(&self) {
        self.0.fetch_add(1, Ordering::AcqRel);
    }

    /// The point a request was opened at, to tell later cancels by.
    fn mark(&self) -> CancelMark {
        CancelMark(self.0.load(Ordering::Acquire))
    }

    /// Whether the host cancelled since `mark`.
    fn cancelled_since(&self, mark: CancelMark) -> bool {
        self.0.load(Ordering::Acquire) != mark.0
    }
}

/// A point in a session's [`TurnCancels`].
#[derive(Clone, Copy)]
struct CancelMark(u64);

/// The input requests one session has open on the host.
#[derive(Default)]
pub(super) struct Inputs {
    open: HashMap<InputRequestId, JoinHandle<()>>,
}

impl Inputs {
    /// Puts `request` to the host, unless it is already open: an attach
    /// lists the open requests, and its replay may repeat them.
    pub(super) fn open(&mut self, request: InputRequest, context: &InputContext) {
        if self
            .open
            .get(&request.id)
            .is_some_and(|task| !task.is_finished())
        {
            return;
        }
        let id = request.id;
        // Marked here, not in the task, which first runs later: a cancel
        // that comes in between still withdraws the request.
        let asked = context.cancels.mark();
        let task = context.asks.spawn(ask(request, context.clone(), asked));
        self.open.insert(id, task);
    }

    /// Puts every request of `requests`, the ones open as an attach or
    /// observe began, to the host, and withdraws the rest: a skipped replay
    /// did not say how the others were resolved.
    pub(super) fn reconcile(&mut self, requests: Vec<InputRequest>, context: &InputContext) {
        self.retain(&requests);
        for request in requests {
            self.open(request, context);
        }
    }

    /// Withdraws every open request but those of `requests`.
    fn retain(&mut self, requests: &[InputRequest]) {
        self.open.retain(|id, task| {
            let open = requests.iter().any(|request| request.id == *id);
            if !open {
                task.abort();
            }
            open
        });
    }

    /// Withdraws request `id` from the host: answered, here or elsewhere,
    /// withdrawn, or timed out.
    pub(super) fn resolve(&mut self, id: InputRequestId) {
        if let Some(task) = self.open.remove(&id) {
            task.abort();
        }
    }

    /// Withdraws every request, as when the attachment ends.
    pub(super) fn abort_all(&mut self) {
        for (_, task) in self.open.drain() {
            task.abort();
        }
    }
}

impl Drop for Inputs {
    fn drop(&mut self) {
        self.abort_all();
    }
}

/// Puts `request`, opened at `asked`, to the host and sends its answer.
async fn ask(request: InputRequest, context: InputContext, asked: CancelMark) {
    context.asking.ready().await;
    let mut shown = match &request.ask {
        Ask::PlanApproval(ask) => Some(ShownPlan::new(
            context.port.as_ref(),
            &context.acp_id,
            &ask.plan,
        )),
        _ => None,
    };
    let answer = match host_answer(&request, &context).await {
        Ok(Some(answer)) => answer,
        // The host cannot answer, or cancelled: another client may answer,
        // or the turn's cancel withdraws the request.
        Ok(None) => return,
        Err(error) => {
            tracing::warn!(%error, "could not ask the ACP host for input");
            return;
        }
    };
    if request.asker == InputAsker::Turn && context.cancels.cancelled_since(asked) {
        return;
    }
    let retry = matches!(answer, InputAnswer::Answers { .. });
    if let Some(shown) = &mut shown {
        shown.approved = matches!(answer, InputAnswer::ApprovePlan { .. });
    }
    let sent = send(&context, request.id, answer).await;
    if let (Some(shown), false) = (&mut shown, matches!(sent, Ok(Sent::Taken))) {
        shown.approved = false;
    }
    match sent {
        // An answer the daemon finds invalid, such as a choice the question
        // does not offer, declines instead so the tool is not left waiting.
        Err(Unsent::Failed(error))
            if retry && error.error_code() == Some(ErrorCode::InvalidParams) =>
        {
            if let Err(unsent) = send(&context, request.id, InputAnswer::Decline).await {
                tracing::warn!(?unsent, "could not decline an input request");
            }
        }
        Ok(_) => {}
        Err(unsent) => tracing::warn!(?unsent, "could not answer an input request"),
    }
}

/// What the host answered, or `None` when it cannot answer or cancelled
/// the prompt.
async fn host_answer(
    request: &InputRequest,
    context: &InputContext,
) -> Result<Option<InputAnswer>, AcpError> {
    let InputContext {
        port,
        features,
        placeholders,
        ..
    } = context;
    // A subagent's question goes to the child session the host was told
    // of; it is still answered on this session.
    let child = request
        .subagent
        .as_ref()
        .and_then(|child| port.child_session(&context.acp_id, child));
    let acp_id = child.as_ref().unwrap_or(&context.acp_id);
    match &request.ask {
        Ask::Approval(ask) => {
            let card = Card::of(request.tool_call.as_ref(), placeholders);
            let prompt = permission::permission_request(acp_id, ask, &card);
            let response = port.request_permission(prompt).await?;
            Ok(permission::approval_answer(&response.outcome))
        }
        Ask::PlanApproval(ask) => {
            let card = Card::of(request.tool_call.as_ref(), placeholders);
            let prompt = permission::plan_approval_request(acp_id, ask, &card);
            let response = port.request_permission(prompt).await?;
            Ok(permission::plan_answer(&response.outcome))
        }
        Ask::Question(ask) => {
            let Forms::Available(dialect) = features.forms else {
                return Ok(None);
            };
            let held = match context.timeouts {
                QuestionTimeouts::Hold => request.timeout.is_some(),
                QuestionTimeouts::Keep => false,
            };
            if held {
                if let Err(unsent) = hold(context, request.id).await {
                    tracing::debug!(?unsent, "could not hold an input request");
                }
            }
            let form =
                elicitation::elicitation_request(ask, acp_id, request.tool_call.as_ref(), dialect);
            let response = port.create_elicitation(form).await?;
            Ok(Some(elicitation::host_answer(ask, response, dialect)))
        }
        // ACP has no masked field, so an ACP client never declares
        // `secret_asks` and its sessions never ask; one that a client which
        // masks opened is that client's to answer.
        Ask::Secret(_) => Ok(None),
        // `Unknown`, or an ask a newer daemon sends: the host cannot answer
        // it, and another client may.
        _ => Ok(None),
    }
}

/// A plan shown to the host while its approval is asked. Dropped without
/// this host's approval on its way to the daemon, it is withdrawn: the host
/// kept planning, the request failed or a cancel withdrew it, or another
/// client resolved it first, when this host cannot tell whether it
/// approved. An approval counts once sent, since the resolution it causes
/// aborts the task before the send returns, unless the daemon answers that
/// the request was already resolved.
struct ShownPlan<'a> {
    port: &'a dyn AcpClientPort,
    session: &'a AcpSessionId,
    approved: bool,
}

impl<'a> ShownPlan<'a> {
    fn new(port: &'a dyn AcpClientPort, session: &'a AcpSessionId, plan: &str) -> Self {
        port.plan_proposed(session, plan);
        Self {
            port,
            session,
            approved: false,
        }
    }
}

impl Drop for ShownPlan<'_> {
    fn drop(&mut self) {
        if !self.approved {
            self.port.plan_withdrawn(self.session);
        }
    }
}

/// Why an answer or hold did not reach the daemon.
#[derive(Debug)]
enum Unsent {
    /// The connection the request came over is gone; a new daemon would
    /// not have it.
    Disconnected,
    /// The daemon refused it, or the connection failed under it.
    Failed(ClientError),
}

/// What became of an answer the daemon received.
enum Sent {
    /// It resolved the request.
    Taken,
    /// The request was already resolved elsewhere: the first answer wins.
    Resolved,
}

/// Answers request `id`. A request already resolved elsewhere is not an
/// error.
async fn send(
    context: &InputContext,
    id: InputRequestId,
    answer: InputAnswer,
) -> Result<Sent, Unsent> {
    let params = SessionAnswerParams {
        session: context.session.clone(),
        request: id,
        answer,
    };
    let link = context.daemon.current().await.ok_or(Unsent::Disconnected)?;
    match link.request::<SessionAnswer>(&params).await {
        Ok(_) => Ok(Sent::Taken),
        Err(error) if error.error_code() == Some(ErrorCode::InputNotOpen) => Ok(Sent::Resolved),
        Err(error) => Err(Unsent::Failed(error)),
    }
}

async fn hold(context: &InputContext, id: InputRequestId) -> Result<(), Unsent> {
    let params = SessionHoldParams {
        session: context.session.clone(),
        request: id,
    };
    let link = context.daemon.current().await.ok_or(Unsent::Disconnected)?;
    link.request::<SessionHold>(&params)
        .await
        .map(drop)
        .map_err(Unsent::Failed)
}