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
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
//! A v2 session's turns: each prompt, from its send to the `idle` state
//! that ends the foreground work it started, then the next turn the parent's
//! inbox holds.
//!
//! The prompt response only says the agent took the prompt. Work starts
//! with the session's `running` (or `requires_action`) state and ends with
//! its next `idle`; an `idle` before any work since the prompt, such as the
//! snapshot a session sends as it sets up, ends nothing. Updates of other
//! sessions, such as the agent's own subagents, are not followed here.
//!
//! The agent's answers to prompts are read in order with its updates
//! ([`Inbound`]), so a turn knows which `idle` came before an answer.
//!
//! A parent message that arrives while the turn works is steered into it
//! as another `session/prompt`: the agent inserts a prompt into the turn it
//! is busy with, answers once it did, and ends both with the turn's one
//! `idle` (claude-agent-acp 0.114.0, recorded in the attended wire check).
//! A steer the agent took only after that `idle` starts a turn of its own,
//! so an `idle` while a prompt is unanswered ends only the turn before it,
//! and the steer counts as the next turn however its answer and the new
//! turn's `running` are ordered. A steer the agent refuses goes as the next
//! turn.
//!
//! Once the prompted work is done, the run keeps the agent while its
//! background work may still report ([`Background`]): the turns the agent
//! starts on its own are the run's turns too, and the last one's reply is
//! the run's answer. A parent message meanwhile goes as the next turn.

use super::{
    ask_bridge::{self, AgentAsk},
    background::Background,
    setup,
    tool_calls::ToolCalls,
    updates,
    updates::TurnEnd,
    v1_options, Inbound, Updates,
};
use crate::acp_runtime::{
    agent_tools::Served,
    asks::{settle, Asker},
    connection,
    deciders::Deciders,
    driver::{render, DriverOutcome, CANCEL_DRAIN_BUDGET},
    handshake::error,
    person::Person,
    policy::AcpAgentPolicy,
    turn::TurnClassification,
};
use crate::cli_runtime::{
    agent_event::{render::EventRenderer, AgentEvent},
    parent_messages::{Delivered, ParentMessage, ParentMessageInbox},
    status_sink::StatusSink,
    BackgroundWork, CliPrompt,
};
use agent_client_protocol::{
    v2::{schema as v2, ActiveSession},
    Agent, Error,
};
use futures_util::{stream::FuturesUnordered, StreamExt};
use rho_tools::cancellation::RunCancellation;
use std::{collections::HashSet, sync::Mutex};
use tokio::sync::mpsc;

/// Steering for one session: at most one parent message is with the agent
/// or waiting on it, so messages keep their order.
enum Steer {
    /// No inbox, or it closed.
    Off,
    /// Ready for the next parent message.
    Ready,
    /// Sent into the turn as a `session/prompt`, until the agent answers
    /// it. `late` once the turn it was sent into ended.
    InFlight { text: ParentMessage, late: bool },
    /// The agent refused it; it goes as the next turn.
    Refused(ParentMessage),
}

impl Steer {
    fn take_refused(&mut self) -> Option<ParentMessage> {
        match std::mem::replace(self, Self::Ready) {
            Self::Refused(text) => Some(text),
            other => {
                *self = other;
                None
            }
        }
    }

    /// Tells the parent of the message the agent has not taken, which no
    /// turn will carry now the run ends.
    fn drop_undelivered(&mut self, renderer: &mut EventRenderer, sink: &mut StatusSink) {
        match std::mem::replace(self, Self::Off) {
            Self::InFlight { text, .. } | Self::Refused(text) => {
                render(
                    renderer,
                    sink,
                    AgentEvent::Notice(text.undelivered_notice().into()),
                );
            }
            Self::Off | Self::Ready => {}
        }
    }
}

/// What a v2 session's turns read and write: the parts of a
/// [`DriverContext`] that outlive the session's setup.
///
/// [`DriverContext`]: crate::acp_runtime::driver::DriverContext
pub(super) struct Turns<'a> {
    pub(super) prompt: &'a CliPrompt,
    pub(super) cancellation: &'a RunCancellation,
    pub(super) inbox: &'a mut Option<ParentMessageInbox>,
    pub(super) renderer: &'a mut EventRenderer,
    pub(super) sink: &'a mut StatusSink,
    pub(super) prompt_results: &'a mut Option<ParentMessage>,
    /// The tools the run serves the agent, if it gets any.
    pub(super) served: Option<&'a Served>,
    /// Who answers what the agent asks a person; `None` when nobody
    /// attends the run.
    pub(super) person: Option<&'a Person>,
    pub(super) background_work: BackgroundWork,
}

/// The channels the connection's handlers feed a session's turns.
pub(super) struct Incoming<'a> {
    pub(super) updates: &'a mut Updates,
    pub(super) asks: &'a mut mpsc::UnboundedReceiver<AgentAsk>,
    pub(super) events: &'a mut mpsc::UnboundedReceiver<AgentEvent>,
}

pub(super) async fn run<P: AcpAgentPolicy>(
    session: &ActiveSession<Agent>,
    policy: &Mutex<P>,
    context: Turns<'_>,
    incoming: Incoming<'_>,
) -> Result<DriverOutcome, Error> {
    let Turns {
        prompt,
        cancellation,
        inbox,
        renderer,
        sink,
        prompt_results,
        served,
        person,
        background_work,
    } = context;
    let Incoming {
        updates,
        asks: asks_rx,
        events: events_rx,
    } = incoming;
    let deciders = Deciders::new(policy, served);
    let mut tool_calls = ToolCalls::default();
    // Ids only, for the session lifetime, as on v1.
    let mut rejected = HashSet::new();
    // What the agent asked the person and waits on, answered as each settles.
    let mut pending_asks = FuturesUnordered::new();
    let session_id = session.session_id().to_string();
    sink.mark_running();
    updates.prompting();
    let prompt_results = prompt_results.take();
    let first = connection::v2_blocks(connection::first_prompt(prompt, prompt_results.as_ref()));
    updates.prompt(session, first)?;
    connection::prompt_sent(sink, prompt_results, &session_id);
    // A turn's own prompt is unanswered. At most one prompt is: a steer
    // goes only once the turn's prompt was answered, and the next turn's
    // only once no steer is in flight.
    let mut awaiting = true;
    let mut cancelled_by_us = false;
    let mut cancel_deadline = None;
    // Foreground work started since the last prompt was sent.
    let mut working = false;
    let mut background = Background::default();
    // The last turn's reply while a turn the agent started on its own runs:
    // the run's answer if that turn does not end well.
    let mut kept_reply: Option<String> = None;
    let mut steer = if inbox.is_some() {
        Steer::Ready
    } else {
        Steer::Off
    };
    loop {
        tokio::select! {
            biased;
            _ = cancellation.cancelled(), if !cancelled_by_us => {
                session.cancel_active_work()?;
                cancelled_by_us = true;
                cancel_deadline = Some(tokio::time::Instant::now() + CANCEL_DRAIN_BUDGET);
                if let Some(inbox) = inbox.as_ref() { inbox.seal(); }
            }
            _ = async { match cancel_deadline { Some(deadline) => tokio::time::sleep_until(deadline).await, None => std::future::pending().await } } => {
                // With no work running, no `idle` is owed (the SDK's
                // `cancel_active_work`), so only work left running is news.
                if working {
                    render(renderer, sink, AgentEvent::Notice("acp: session/cancel did not end the turn within shutdown grace budget 200 ms; terminating agent".into()));
                }
                steer.drop_undelivered(renderer, sink);
                return Ok(DriverOutcome::stopped(renderer, Some(session_id)));
            }
            _ = async { match background.deadline() { Some(deadline) => tokio::time::sleep_until(deadline).await, None => std::future::pending().await } }, if background.keeping() && !cancelled_by_us => {
                if let Some(notice) = background.expired(tokio::time::Instant::now()) {
                    render(renderer, sink, AgentEvent::Notice(notice));
                }
                match finish(inbox, &mut steer, renderer, sink) {
                    // A message that came meanwhile goes as the next turn.
                    Some(text) if !working => {
                        next_turn(session, updates, sink, renderer, &mut background, text)?;
                        awaiting = true;
                    }
                    // Only the budget expires while the agent works: it is
                    // stopped mid-turn, and the message goes nowhere.
                    Some(text) => {
                        render(renderer, sink, AgentEvent::Notice(text.undelivered_notice().into()));
                        return Ok(kept(kept_reply, renderer, session_id));
                    }
                    None => return Ok(kept(kept_reply, renderer, session_id)),
                }
            }
            text = async { inbox.as_mut().expect("steering needs an inbox").recv().await }, if matches!(steer, Steer::Ready) && (working || background.keeping()) && !awaiting && !cancelled_by_us => match text {
                // While the agent works on its own, it is steered as in any turn.
                Some(text) if working => {
                    updates.prompt(session, connection::v2_blocks(text.content()))?;
                    steer = Steer::InFlight { text, late: false };
                }
                Some(text) => {
                    next_turn(session, updates, sink, renderer, &mut background, text)?;
                    awaiting = true;
                }
                None => steer = Steer::Off,
            },
            Some(ask) = asks_rx.recv() => {
                let asker = Asker { person, cancellation, cancelled_by_us };
                pending_asks.extend(ask_bridge::answer(ask, &deciders, asker, &mut rejected)?);
            }
            Some(settled) = pending_asks.next() => settle(settled, policy, &mut rejected)?,
            Some(inbound) = updates.next() => {
                let notification = match inbound {
                    Inbound::Update(notification) => *notification,
                    // Never reaches a turn: setup reads every answer it
                    // asked for ([`Updates::ask`]).
                    Inbound::Answered => continue,
                    Inbound::Took(took) => {
                        if let Steer::InFlight { .. } = steer {
                            let Steer::InFlight { text, late } = std::mem::replace(&mut steer, Steer::Ready) else { unreachable!() };
                            match took {
                                Ok(_) if !late => connection::delivered(sink, text, Delivered::Steered),
                                // Taken after the turn it was sent into
                                // ended, it started a turn of its own.
                                Ok(_) => connection::delivered(sink, text, Delivered::NextTurn),
                                Err(_) if cancelled_by_us => render(renderer, sink, AgentEvent::Notice(text.undelivered_notice().into())),
                                Err(source) => {
                                    render(renderer, sink, AgentEvent::Notice(format!("acp: the agent refused a steering session/prompt: {source}; sending the message as the next turn")));
                                    if !late {
                                        steer = Steer::Refused(text);
                                    } else {
                                        // The turn it was sent into ended
                                        // waiting for it: it goes now.
                                        updates.prompt(session, connection::v2_blocks(text.content()))?;
                                        awaiting = true;
                                        connection::delivered(sink, text, Delivered::NextTurn);
                                    }
                                }
                            }
                            continue;
                        }
                        awaiting = false;
                        match took {
                            Ok(_) => {}
                            // A cancel can drop a prompt the agent had not taken yet.
                            Err(_) if cancelled_by_us => {
                                steer.drop_undelivered(renderer, sink);
                                return Ok(DriverOutcome::stopped(renderer, Some(session_id)));
                            }
                            Err(refused) => return Err(error(format!("acp: session/prompt: {refused}"))),
                        }
                        continue;
                    }
                };
                if notification.session_id.to_string() != session_id {
                    continue;
                }
                // What a served call drew goes first, as on v1.
                while let Ok(event) = events_rx.try_recv() { render(renderer, sink, event); }
                match &notification.update {
                    v2::SessionUpdate::StateUpdate(state) => background.observe(state),
                    v2::SessionUpdate::ToolCallUpdate(call) => background.tool_call(call),
                    _ => {}
                }
                let idle = match notification.update {
                    v2::SessionUpdate::StateUpdate(v2::StateUpdate::Running(_) | v2::StateUpdate::RequiresAction(_)) => {
                        // A turn the agent started on its own follows the last.
                        if background.keeping() && !working {
                            sink.turn_replied(renderer.result_text());
                            kept_reply = Some(renderer.result_text().to_owned());
                        }
                        working = true;
                        continue;
                    }
                    v2::SessionUpdate::StateUpdate(v2::StateUpdate::Idle(idle)) if working => idle,
                    // Its background work changed while the run waits on it.
                    v2::SessionUpdate::StateUpdate(v2::StateUpdate::Idle(_)) if background.keeping() && !awaiting => {
                        match after_idle(background_work, &mut background, inbox, &mut steer, renderer, sink) {
                            AfterIdle::Keep => {}
                            AfterIdle::Next(text) => {
                                next_turn(session, updates, sink, renderer, &mut background, text)?;
                                awaiting = true;
                            }
                            AfterIdle::End => return Ok(DriverOutcome::ended(TurnClassification::Success, renderer, session_id)),
                        }
                        continue;
                    }
                    v2::SessionUpdate::ConfigOptionUpdate(update) => {
                        let required = policy.lock().expect("ACP policy").session_mode();
                        setup::check_mode(&v1_options(&update.config_options), required.as_ref())?;
                        continue;
                    }
                    update => {
                        match updates::rendered(&update, &mut tool_calls) {
                            None => {}
                            Some(Ok(update)) => deciders.show(update, &rejected, renderer, sink),
                            Some(Err(source)) => render(renderer, sink, AgentEvent::Notice(source.to_string())),
                        }
                        continue;
                    }
                };
                let end = TurnEnd::of(idle.stop_reason.as_ref(), cancelled_by_us);
                while let Ok(event) = events_rx.try_recv() { render(renderer, sink, event); }
                render(renderer, sink, AgentEvent::TurnEnded(end.reason));
                working = false;
                // A turn the agent started on its own that did not end well
                // ends what the run kept it for, on the reply before it.
                if let (Some(reply), false) = (&kept_reply, end.classification == TurnClassification::Success || cancelled_by_us) {
                    render(renderer, sink, AgentEvent::Notice(format!("acp: a turn the agent started on its own ended {:?}; the run keeps the reply before it", end.classification)));
                    let reply = reply.clone();
                    steer.drop_undelivered(renderer, sink);
                    if let Some(inbox) = inbox.as_ref() { inbox.seal(); }
                    return Ok(kept(Some(reply), renderer, session_id));
                }
                kept_reply = None;
                if end.classification == TurnClassification::Success {
                    // A prompt still unanswered starts the next turn, as one
                    // the agent holds while a turn it started on its own runs.
                    if awaiting {
                        sink.turn_replied(renderer.result_text());
                        continue;
                    }
                    // A steer still unanswered starts the next turn: the
                    // run prompted the agent again.
                    if let Steer::InFlight { late, .. } = &mut steer {
                        *late = true;
                        sink.turn_replied(renderer.result_text());
                        background.prompted();
                        continue;
                    }
                    let next = match steer.take_refused() {
                        Some(text) => AfterIdle::Next(text),
                        None => after_idle(background_work, &mut background, inbox, &mut steer, renderer, sink),
                    };
                    match next {
                        AfterIdle::Keep => {}
                        AfterIdle::Next(text) => {
                            next_turn(session, updates, sink, renderer, &mut background, text)?;
                            awaiting = true;
                        }
                        AfterIdle::End => return Ok(DriverOutcome::ended(end.classification, renderer, session_id)),
                    }
                    continue;
                }
                // It was waiting for a turn that will not come.
                steer.drop_undelivered(renderer, sink);
                if let Some(inbox) = inbox.as_ref() { inbox.seal(); }
                return Ok(DriverOutcome::ended(end.classification, renderer, session_id));
            }
            Some(event) = events_rx.recv() => render(renderer, sink, event),
            _ = session.connection().incoming_closed() => {
                steer.drop_undelivered(renderer, sink);
                // What the run kept the agent for is lost, not its answer.
                if background.keeping() && !awaiting {
                    render(renderer, sink, AgentEvent::Notice("acp: the agent closed the connection while the run waited on its background work".into()));
                    return Ok(kept(kept_reply, renderer, session_id));
                }
                return Err(error("acp: connection closed before the turn ended"));
            }
        }
    }
}

/// What the run does at an idle with nothing of its own outstanding.
enum AfterIdle {
    /// Keep the agent: its background work may still report.
    Keep,
    /// Send the parent's message as the next turn.
    Next(ParentMessage),
    /// The run ends.
    End,
}

fn after_idle(
    background_work: BackgroundWork,
    background: &mut Background,
    inbox: &mut Option<ParentMessageInbox>,
    steer: &mut Steer,
    renderer: &mut EventRenderer,
    sink: &mut StatusSink,
) -> AfterIdle {
    let keep = match background_work {
        BackgroundWork::Await => background.idle(tokio::time::Instant::now()).is_some(),
        BackgroundWork::Leave => false,
    };
    if keep {
        return AfterIdle::Keep;
    }
    match finish(inbox, steer, renderer, sink) {
        Some(text) => AfterIdle::Next(text),
        None => AfterIdle::End,
    }
}

/// Sends `text` as the next turn, which ends what the run kept the agent
/// for. The reply of the turn that ended is the host's too; the run's
/// answer will be the last turn's.
fn next_turn(
    session: &ActiveSession<Agent>,
    updates: &Updates,
    sink: &mut StatusSink,
    renderer: &EventRenderer,
    background: &mut Background,
    text: ParentMessage,
) -> Result<(), Error> {
    background.prompted();
    sink.turn_replied(renderer.result_text());
    updates.prompt(session, connection::v2_blocks(text.content()))?;
    connection::delivered(sink, text, Delivered::NextTurn);
    Ok(())
}

/// The run's work is done: the parent message that came meanwhile, which
/// goes as the next turn, or `None` once the inbox is closed and the run
/// ends. Atomic with sends: a racing message is taken or rejected.
fn finish(
    inbox: &mut Option<ParentMessageInbox>,
    steer: &mut Steer,
    renderer: &mut EventRenderer,
    sink: &mut StatusSink,
) -> Option<ParentMessage> {
    if let Some(text) = inbox
        .as_mut()
        .and_then(ParentMessageInbox::take_next_or_close)
    {
        return Some(text);
    }
    steer.drop_undelivered(renderer, sink);
    if let Some(inbox) = inbox.as_ref() {
        inbox.seal();
    }
    None
}

/// The run's outcome once it stops keeping the agent: the reply before a
/// turn the agent started on its own that is cut short, else the last.
fn kept(kept_reply: Option<String>, renderer: &EventRenderer, session_id: String) -> DriverOutcome {
    let mut outcome = DriverOutcome::ended(TurnClassification::Success, renderer, session_id);
    if let Some(reply) = kept_reply {
        outcome.result_text = reply;
    }
    outcome
}