rho-coding-agent 3.10.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
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
//! Foreground ACP driver. All terminal writes remain in session::settle.

use super::{
    agent_tools::{self, AgentTools, Served},
    asks::{self, Asker, PendingAsk},
    elicitation::AgentForm,
    handshake::{self, bounded, error, AgentFeatures, HANDSHAKE_STEP_BUDGET},
    permission::{choose_option, is_allowed, PermissionDecision},
    person::{Attendance, Person},
    policy::{AcpAgentPolicy, AgentToolCallRef},
    steering,
    turn::{classify_stop, TurnClassification},
    ExtensionAnswer,
};
use crate::cli_runtime::{
    agent_event::{render::EventRenderer, AgentEvent},
    parent_messages::{Delivered, ParentMessage, ParentMessageInbox},
    status_sink::StatusSink,
    stream_effect::{StatusPatch, StreamEffect},
};
use agent_client_protocol::util::MatchDispatch;
use agent_client_protocol::{
    v1::schema::{
        CancelNotification, CreateElicitationRequest, CreateElicitationResponse, ElicitationAction,
        NewSessionRequest, NewSessionResponse, RequestPermissionOutcome, RequestPermissionRequest,
        RequestPermissionResponse, ResumeSessionRequest, ResumeSessionResponse,
        SessionNotification, SessionUpdate, ToolCallContent, ToolCallId, ToolCallStatus,
    },
    v1::{ActiveSession, SessionMessage, SessionSetup},
    Agent, Client, ConnectTo, Dispatch, Error, Handled, Protocol, Responder, UntypedMessage,
};
use futures_util::{stream::FuturesUnordered, StreamExt};
use rho_tools::cancellation::RunCancellation;
use serde_json::Value;
use std::{
    collections::HashSet,
    future::Future,
    path::Path,
    pin::Pin,
    sync::{Arc, Mutex},
    time::Duration,
};
use tokio::sync::mpsc;

// Receipt: OwnedChild's 200 ms termination grace. A recorded ACP agent
// answered `session/cancel` with `stopReason: cancelled` in 4 ms (see the
// commit that removed the cursor runtime); share the existing shutdown budget
// before forcing termination, rather than leave a hung agent immortal after
// cancel.
pub(super) const CANCEL_DRAIN_BUDGET: Duration = Duration::from_millis(200);

pub(super) struct DriverOutcome {
    pub(super) classification: TurnClassification,
    pub(super) session_id: Option<String>,
    pub(super) result_text: String,
    pub(super) turns: u64,
}

impl DriverOutcome {
    fn stopped(renderer: &EventRenderer, session_id: Option<String>) -> Self {
        Self {
            classification: TurnClassification::Stopped,
            session_id,
            result_text: renderer.result_text().to_owned(),
            turns: renderer.turns(),
        }
    }
}

pub(super) fn render(renderer: &mut EventRenderer, sink: &mut StatusSink, event: AgentEvent) {
    for effect in renderer.render(event) {
        sink.apply_effect(effect);
    }
}

/// Generic over the responder's protocol marker: the connection's catch-all
/// hands over a v1 responder, a session's dispatch a raw one.
fn answer_extension<P: AcpAgentPolicy, Marker: Protocol>(
    policy: &Mutex<P>,
    request: UntypedMessage,
    responder: Responder<serde_json::Value, Marker>,
    events: &mpsc::UnboundedSender<AgentEvent>,
) -> Result<(), Error> {
    let answer = policy
        .lock()
        .expect("ACP policy")
        .answer_extension(&request.method, &request.params);
    match answer {
        Some(ExtensionAnswer {
            reply,
            events: presentation,
        }) => {
            responder.respond(reply)?;
            for event in presentation {
                let _ = events.send(event);
            }
            Ok(())
        }
        None => responder.respond_with_error(Error::method_not_found()),
    }
}

pub(super) struct DriverContext<'a> {
    pub(super) prompt: &'a str,
    pub(super) cwd: &'a Path,
    /// The agent's session to resume instead of starting one.
    pub(super) resume: Option<&'a str>,
    pub(super) cancellation: &'a RunCancellation,
    pub(super) inbox: &'a mut Option<ParentMessageInbox>,
    pub(super) renderer: &'a mut EventRenderer,
    pub(super) sink: &'a mut StatusSink,
    /// Who answers what the agent asks a person; `None` when nobody
    /// attends the run.
    pub(super) person: Option<&'a Person>,
    /// Background results the first prompt carries, as a content block
    /// ahead of `prompt`, delivered once it is sent
    /// ([`crate::cli_runtime::CliSessionOverrides::prompt_results`]).
    pub(super) prompt_results: Option<ParentMessage>,
}

/// Runs one agent process's session to its end. `tools`, when set, are
/// served to the agent over the connection or a stdio bridge
/// ([`agent_tools`]).
pub(super) async fn run<P: AcpAgentPolicy>(
    transport: impl ConnectTo<Client> + 'static,
    policy: P,
    context: DriverContext<'_>,
    tools: Option<Arc<dyn AgentTools>>,
) -> Result<DriverOutcome, String> {
    let DriverContext {
        prompt,
        cwd,
        resume,
        cancellation,
        inbox,
        renderer,
        sink,
        person,
        prompt_results,
    } = context;
    let attendance = Attendance::of(person);
    let (events_tx, mut events_rx) = mpsc::unbounded_channel();
    // The guard ends the server's calls however the run ends. Its calls
    // draw their cards through the run's events.
    let (served, _ends_calls) = tools
        .map(|tools| Served::new(tools, events_tx.clone()))
        .unzip();
    let mcp = served.clone();
    // Reborrow so a post-connection cancel outcome can still render.
    let (session_renderer, session_sink) = (&mut *renderer, &mut *sink);
    let policy = Arc::new(Mutex::new(policy));
    let extension_policy = Arc::clone(&policy);
    let extension_tx = events_tx.clone();
    let outcome = Client.v1()
        .name("rho")
        .on_receive_request(async move |request: UntypedMessage, responder, cx| {
            if request.method == agent_tools::MCP_MESSAGE {
                agent_tools::answer(mcp.as_ref(), request, responder, &cx)?;
                return Ok(Handled::Yes);
            }
            // Static handlers run BEFORE ActiveSession's dynamic handler.
            // Decline all session-scoped requests so permissions and scoped
            // extensions arrive through read_update, never this catch-all.
            if request.params.get("sessionId").and_then(serde_json::Value::as_str).is_some() {
                return Ok(Handled::No { message: (request, responder), retry: false });
            }
            answer_extension(&extension_policy, request, responder, &extension_tx)?;
            Ok(Handled::Yes)
        }, agent_client_protocol::on_receive_request!())
        .connect_with(transport, async move |cx| {
            let (renderer, sink) = (session_renderer, session_sink);
            let features = tokio::select! {
                biased;
                _ = cancellation.cancelled() => return Ok(DriverOutcome::stopped(renderer, None)),
                result = handshake::initialize(&cx, &policy, attendance) => result?,
            };
            let session_meta = policy.lock().expect("ACP policy").session_meta();
            // Declared over the connection to an agent that takes it there,
            // else over a stdio bridge; one no bridge opens for is told
            // nothing of it, and the run says so.
            let served = match (served.as_deref(), features.mcp_over_acp) {
                (Some(served), true) => Some(served),
                (Some(served), false) => match served.open_bridge() {
                    Ok(()) => Some(served),
                    Err(why) => {
                        render(renderer, sink, AgentEvent::Notice(format!("acp: the agent takes no MCP server over its connection (mcpCapabilities.acp), and rho could not serve it one over stdio, so it gets none of rho's tools: {why}")));
                        None
                    }
                },
                (None, _) => None,
            };
            let mcp_servers: Vec<_> = served.iter().map(|served| served.declaration()).collect();
            // Only startup is bounded: once the session exists, turns have
            // no deadline.
            let (session, response) = match resume {
                None => {
                    let SessionSetup { session, response, .. } = tokio::select! {
                        biased;
                        _ = cancellation.cancelled() => return Ok(DriverOutcome::stopped(renderer, None)),
                        setup = handshake::new_session(&cx, NewSessionRequest::new(cwd.to_path_buf()).meta(session_meta).mcp_servers(mcp_servers), &policy) => setup?,
                    };
                    (session, SetUpBy::New(response))
                }
                Some(_) if !features.resume => {
                    sink.conversation_not_restored();
                    return Err(error("acp: the agent cannot resume its session: it does not advertise sessionCapabilities.resume"));
                }
                Some(id) => {
                    let SessionSetup { session, response, .. } = tokio::select! {
                        biased;
                        _ = cancellation.cancelled() => return Ok(DriverOutcome::stopped(renderer, None)),
                        // The agent's own refusal, not a timeout or sign-in,
                        // says the conversation is not there to resume.
                        setup = bounded("session/resume", async {
                            Ok(cx.resume_session_from(ResumeSessionRequest::new(id.to_owned(), cwd.to_path_buf()).meta(session_meta).mcp_servers(mcp_servers))
                                .block_task()
                                .start_session()
                                .await)
                        }) => match setup? {
                            Ok(setup) => setup,
                            Err(refused) => {
                                if refused.code != agent_client_protocol::ErrorCode::AUTH_REQUIRED {
                                    sink.conversation_not_restored();
                                }
                                return Err(error(format!("acp: session/resume: {refused}")));
                            }
                        },
                    };
                    (session, SetUpBy::Resume(response))
                }
            };
            if let Some(served) = served {
                served.set_up(session.session_id().clone());
            }
            tokio::select! {
                biased;
                // Before its prompt: nothing resumes a session that never
                // took one (see `turns`).
                _ = cancellation.cancelled() => return Ok(DriverOutcome::stopped(renderer, None)),
                result = async {
                    handshake::require_mode(&session, response.set_up(), &policy).await?;
                    handshake::require_config(&session, response.set_up(), &policy).await
                } => result?,
            }
            turns(session, &policy, features, served, DriverContext { prompt, cwd, resume, cancellation, inbox, renderer, sink, person, prompt_results }, &events_tx, &mut events_rx).await
        }).await;
    match outcome {
        Ok(outcome) => Ok(outcome),
        // Local cancellation is authoritative on every path, not only when a
        // stop reason arrives: an agent that closes stdio, or a failed
        // session/cancel send, still settles as Stopped. Keep the diagnostic.
        Err(source) if cancellation.is_cancelled() => {
            render(
                renderer,
                sink,
                AgentEvent::Notice(format!("acp: after cancellation: {source}")),
            );
            Ok(DriverOutcome::stopped(renderer, None))
        }
        Err(source) => Err(format!("acp: {source}")),
    }
}

/// The answer to the request that set the session up.
enum SetUpBy {
    New(NewSessionResponse),
    Resume(ResumeSessionResponse),
}

impl SetUpBy {
    fn set_up(&self) -> handshake::SetUp<'_> {
        match self {
            Self::New(response) => response.into(),
            Self::Resume(response) => response.into(),
        }
    }
}

/// How long a turn that has ended waits on a steer still in flight. Same
/// 10 s as each ACP setup request; claude-agent-acp answers a steer after one
/// queue check, without waiting on the model.
const STEER_REPLY_BUDGET: std::time::Duration = HANDSHAKE_STEP_BUDGET;

type SteerReply = Pin<Box<dyn Future<Output = Result<Value, Error>> + Send>>;

/// Steering for one session. It takes one parent message at a time from the
/// inbox while a turn runs. A message the agent does not inject waits for the
/// next turn, ahead of anything still queued, and pauses steering to keep the
/// order.
enum Steering {
    /// The agent does not steer, or the inbox closed.
    Off,
    /// Ready for the next parent message.
    Idle,
    /// A `_session/steering` request in flight, with the message it carries.
    InFlight(ParentMessage, SteerReply),
    /// Declined while Rho's prompt was still running, so the agent had not
    /// queued its turn yet. Steered again on the turn's next output, or sent
    /// as the next turn if the turn ends first.
    Held(ParentMessage),
    /// The steer failed; sent as the next turn.
    Declined(ParentMessage),
}

impl Steering {
    fn take_in_flight(&mut self) -> Option<(ParentMessage, SteerReply)> {
        match std::mem::replace(self, Self::Idle) {
            Self::InFlight(text, reply) => Some((text, reply)),
            other => {
                *self = other;
                None
            }
        }
    }

    fn take_held(&mut self) -> Option<ParentMessage> {
        match std::mem::replace(self, Self::Idle) {
            Self::Held(text) => Some(text),
            other => {
                *self = other;
                None
            }
        }
    }

    fn take_declined(&mut self) -> Option<ParentMessage> {
        match std::mem::replace(self, Self::Idle) {
            Self::Held(text) | Self::Declined(text) => Some(text),
            other => {
                *self = other;
                None
            }
        }
    }
}

async fn turns<P: AcpAgentPolicy>(
    mut session: ActiveSession<'_, Agent>,
    policy: &Mutex<P>,
    features: AgentFeatures,
    served: Option<&Served>,
    context: DriverContext<'_>,
    events_tx: &mpsc::UnboundedSender<AgentEvent>,
    events_rx: &mut mpsc::UnboundedReceiver<AgentEvent>,
) -> Result<DriverOutcome, Error> {
    let DriverContext {
        prompt,
        cancellation,
        inbox,
        renderer,
        sink,
        person,
        prompt_results,
        ..
    } = context;
    let session_id = session.session_id().to_string();
    sink.mark_running();
    match &prompt_results {
        // A block of their own, ahead of the prompt, so the agent reads
        // where they end and the person's text begins.
        Some(results) => {
            session.send_prompt_blocks(vec![results.framed().into(), prompt.to_owned().into()])?
        }
        None => session.send_prompt(prompt)?,
    }
    // The prompt carried them.
    for event in prompt_results
        .into_iter()
        .flat_map(|results| results.settle(Delivered::NextTurn))
    {
        sink.apply_effect(StreamEffect::Attachment(event));
    }
    // Recorded once the prompt is out, never before: a later turn resumes the
    // session this names, and one that never took a prompt holds no
    // conversation to resume.
    sink.apply_effect(StreamEffect::Status(StatusPatch {
        runtime_session_id: Some(session_id.clone()),
        ..StatusPatch::default()
    }));
    let connection = session.connection().clone();
    let mut cancelled_by_us = false;
    let mut cancel_deadline = None;
    let mut tracking = UpdateTracking::default();
    // What the agent asked the person and waits on, answered as each settles.
    let mut asks = FuturesUnordered::new();
    let mut steering = if features.steering && inbox.is_some() {
        Steering::Idle
    } else {
        Steering::Off
    };
    loop {
        tokio::select! {
            biased;
            _ = cancellation.cancelled(), if !cancelled_by_us => {
                connection.send_notification(CancelNotification::new(session.session_id().clone()))?;
                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 } } => {
                render(renderer, sink, AgentEvent::Notice("acp: session/cancel response exceeded shutdown grace budget 200 ms; terminating agent".into()));
                return Ok(DriverOutcome::stopped(renderer, Some(session_id)));
            }
            reply = async { match &mut steering { Steering::InFlight(_, reply) => reply.as_mut().await, _ => std::future::pending().await } }, if matches!(steering, Steering::InFlight(..)) => {
                if let Some((text, _)) = steering.take_in_flight() {
                    steering = settle_steer(text, reply, renderer, sink);
                    if matches!(steering, Steering::Held(_)) {
                        // Retry only after output that follows the decline.
                        tracking.turn_live = false;
                    }
                }
            }
            text = async { inbox.as_mut().expect("steering needs an inbox").recv().await }, if matches!(steering, Steering::Idle) && tracking.turn_live && !cancelled_by_us => match text {
                Some(text) => {
                    let request = steering::request(session.session_id(), &text.framed())?;
                    steering = Steering::InFlight(text, Box::pin(connection.send_request(request).block_task()));
                }
                None => steering = Steering::Off,
            },
            message = session.read_update() => match message? {
                SessionMessage::Message(dispatch) => {
                    // What a served call drew before the agent heard its
                    // result goes first, so the agent's end of the call
                    // finds the call's card drawn. A call draws before it
                    // answers, and the agent ends the call only after the
                    // answer, so its cards are queued by the time this
                    // message is read.
                    while let Ok(event) = events_rx.try_recv() { render(renderer, sink, event); }
                    let asking = Asker { person, cancellation, cancelled_by_us };
                    asks.extend(dispatch_update(dispatch.into_raw(), Deciders { policy, served }, renderer, sink, &mut tracking, asking, events_tx).await?);
                    if tracking.turn_live && !cancelled_by_us {
                        if let Some(text) = steering.take_held() {
                            let request = steering::request(session.session_id(), &text.framed())?;
                            steering = Steering::InFlight(text, Box::pin(connection.send_request(request).block_task()));
                        }
                    }
                }
                SessionMessage::PromptResponse(response) => {
                    let stop = response?.stop_reason;
                    let classification = classify_stop(&stop, cancelled_by_us);
                    // A steer racing the end of a successful turn is settled
                    // first, so a declined message still becomes the next
                    // turn. Any other ending sends no next turn, so it does not
                    // wait. A cancel during the wait stops the run instead.
                    let mut cancelled_while_settling = false;
                    if let Some((text, reply)) = steering.take_in_flight() {
                        if classification == TurnClassification::Success {
                            tokio::select! {
                                biased;
                                _ = cancellation.cancelled() => cancelled_while_settling = true,
                                reply = tokio::time::timeout(STEER_REPLY_BUDGET, reply) => {
                                    let reply = reply.unwrap_or_else(|_| Err(error(format!("{} reply exceeded budget {} s", steering::METHOD, STEER_REPLY_BUDGET.as_secs()))));
                                    steering = settle_steer(text, reply, renderer, sink);
                                }
                            }
                        }
                    }
                    while let Ok(event) = events_rx.try_recv() { render(renderer, sink, event); }
                    render(renderer, sink, AgentEvent::TurnEnded(stop));
                    if cancelled_while_settling {
                        if let Some(inbox) = inbox.as_ref() { inbox.seal(); }
                        return Ok(DriverOutcome::stopped(renderer, Some(session_id)));
                    }
                    // classify_stop already reports Stopped once we cancelled.
                    if classification == TurnClassification::Success {
                        // Atomic with sends: a racing message either becomes
                        // the next turn (port stays open) or is rejected.
                        if let Some(text) = steering.take_declined().or_else(|| inbox.as_mut().and_then(ParentMessageInbox::take_next_or_close)) {
                            // The run's answer is the last turn's reply; the host keeps this one too.
                            sink.turn_replied(renderer.result_text());
                            session.send_prompt(text.framed())?;
                            tracking.turn_live = false;
                            for event in text.settle(Delivered::NextTurn) { sink.apply_effect(StreamEffect::Attachment(event)); }
                            continue;
                        }
                    } else if let Some(text) = steering.take_declined() {
                        // It was waiting for a next turn that will not come.
                        render(renderer, sink, AgentEvent::Notice(text.undelivered_notice().into()));
                    }
                    if let Some(inbox) = inbox.as_ref() { inbox.seal(); }
                    return Ok(DriverOutcome { classification, session_id: Some(session_id), result_text: renderer.result_text().to_owned(), turns: renderer.turns() });
                }
                _ => return Err(error("acp: unhandled session message")),
            },
            Some(settled) = asks.next() => asks::settle(settled, policy, &mut tracking.rejected)?,
            Some(event) = events_rx.recv() => render(renderer, sink, event),
            _ = connection.incoming_closed() => return Err(error("acp: connection closed before session/prompt response")),
        }
    }
}

/// Journal an injected message, or keep it for the next turn.
fn settle_steer(
    text: ParentMessage,
    reply: Result<Value, Error>,
    renderer: &mut EventRenderer,
    sink: &mut StatusSink,
) -> Steering {
    match reply.as_ref().map(steering::delivery) {
        Ok(steering::Delivery::Injected) => {
            for event in text.settle(Delivered::Steered) {
                sink.apply_effect(StreamEffect::Attachment(event));
            }
            Steering::Idle
        }
        Ok(steering::Delivery::NextTurn) => Steering::Held(text),
        Err(source) => {
            render(
                renderer,
                sink,
                AgentEvent::Notice(format!(
                    "acp: {}: {source}; sending the message as the next turn",
                    steering::METHOD
                )),
            );
            Steering::Declined(text)
        }
    }
}

/// What the driver keeps from one session's updates.
#[derive(Default)]
struct UpdateTracking {
    /// Ids only, for the session lifetime: duplicate completed snapshots must
    /// not turn a previously rejected tool back into a successful card.
    rejected: HashSet<ToolCallId>,
    /// The current prompt's turn has produced output since it was sent, or
    /// since the last too-early steer. An agent queues a turn only after its
    /// own setup, which can itself send updates (claude-agent-acp publishes an
    /// open task plan first), and declines a steer that arrives before with
    /// `promptRequired`; [`Steering::Held`] retries it.
    turn_live: bool,
}

/// Output only a running turn produces. Session-level updates (commands,
/// modes, config, session info) can arrive before the agent has queued it.
fn is_turn_content(update: &SessionUpdate) -> bool {
    match update {
        SessionUpdate::UserMessageChunk(_)
        | SessionUpdate::AgentMessageChunk(_)
        | SessionUpdate::AgentThoughtChunk(_)
        | SessionUpdate::ToolCall(_)
        | SessionUpdate::ToolCallUpdate(_)
        | SessionUpdate::Plan(_)
        | SessionUpdate::UsageUpdate(_) => true,
        SessionUpdate::AvailableCommandsUpdate(_)
        | SessionUpdate::CurrentModeUpdate(_)
        | SessionUpdate::ConfigOptionUpdate(_)
        | SessionUpdate::SessionInfoUpdate(_) => false,
        _ => false,
    }
}

/// Who decides the agent's permission asks: the tools' owner, as each call
/// runs, for a tool the run serves; the policy for the rest.
struct Deciders<'p, P> {
    policy: &'p Mutex<P>,
    served: Option<&'p Served>,
}

impl<P: AcpAgentPolicy> Deciders<'_, P> {
    /// The tool the run serves that the agent's tool call `call` runs, if
    /// it runs one.
    fn served_tool<'c>(&self, call: AgentToolCallRef<'c>) -> Option<&'c str> {
        // The tools are asked outside the policy's lock.
        let named = self.policy.lock().expect("ACP policy").agent_tool(call);
        named.filter(|name| self.served.is_some_and(|served| served.serves(name)))
    }

    /// Tells the run's server of `update` (see [`Served::heard`]), and
    /// whether it announces a call of a tool the run serves.
    fn hear(&self, update: &SessionUpdate) -> bool {
        let tool = match update {
            SessionUpdate::ToolCall(call) => self.served_tool(call.into()),
            _ => None,
        };
        if let Some(served) = self.served {
            served.heard(update, tool);
        }
        tool.is_some()
    }

    fn decide(&self, request: &RequestPermissionRequest) -> PermissionDecision {
        if self.served_tool((&request.tool_call).into()).is_some() {
            return PermissionDecision::AllowOnce;
        }
        self.policy
            .lock()
            .expect("ACP policy")
            .decide_permission(request)
    }
}

/// Handles one session message, and returns what it asked the person,
/// which the turn waits on alongside its updates.
async fn dispatch_update<'a, P: AcpAgentPolicy>(
    dispatch: Dispatch,
    deciders: Deciders<'_, P>,
    renderer: &mut EventRenderer,
    sink: &mut StatusSink,
    tracking: &mut UpdateTracking,
    asker: Asker<'a>,
    events: &mpsc::UnboundedSender<AgentEvent>,
) -> Result<Option<PendingAsk<'a>>, Error> {
    let Deciders { policy, .. } = deciders;
    let cancelled_by_us = asker.cancelled_by_us;
    // At most one request per message; the closures below share it.
    let pending = Mutex::new(None);
    MatchDispatch::new(dispatch)
        .if_notification(async |notification: SessionNotification| {
            let (mut update, required_mode, status) = {
                let policy = policy.lock().expect("ACP policy");
                let status = policy.status_effects(&notification.update);
                (notification.update, policy.session_mode(), status)
            };
            for effect in status {
                sink.apply_effect(effect);
            }
            handshake::check_mode_update(&update, required_mode.as_ref())?;
            tracking.turn_live |= is_turn_content(&update);
            if let SessionUpdate::ToolCallUpdate(call) = &mut update {
                if call.fields.status == Some(ToolCallStatus::Completed)
                    && tracking.rejected.contains(&call.tool_call_id)
                {
                    call.fields.status = Some(ToolCallStatus::Failed);
                    call.fields.content = Some(vec![ToolCallContent::from(
                        "rejected by Rho permission policy",
                    )]);
                }
            }
            let served = deciders.hear(&update);
            let event = match update {
                // A served call draws its own card.
                SessionUpdate::ToolCall(call) if served => {
                    AgentEvent::ServedToolCall(Box::new(call))
                }
                update => AgentEvent::from(update),
            };
            render(renderer, sink, event);
            Ok(())
        })
        .await
        .if_request(async |request: RequestPermissionRequest, responder| {
            let decision = deciders.decide(&request);
            let outcome = match (decision, asker.attended()) {
                _ if cancelled_by_us => RequestPermissionOutcome::Cancelled,
                (PermissionDecision::AskPerson(asking), Some(attended)) => {
                    let ask = attended.permission(request, responder, asking);
                    *pending.lock().expect("pending ask") = Some(ask);
                    return Ok(());
                }
                // Nobody attends to ask: it fails closed.
                (
                    PermissionDecision::AskPerson(_)
                    | PermissionDecision::AllowOnce
                    | PermissionDecision::Reject,
                    _,
                ) => choose_option(decision, &request.options),
            };
            if !is_allowed(&outcome, &request.options) {
                tracking
                    .rejected
                    .insert(request.tool_call.tool_call_id.clone());
            }
            responder.respond(RequestPermissionResponse::new(outcome))
        })
        .await
        .if_request(async |request: CreateElicitationRequest, responder| {
            // Only a run a person attends advertised forms.
            let Some(attended) = asker.attended() else {
                return responder
                    .respond(CreateElicitationResponse::new(ElicitationAction::Cancel));
            };
            match AgentForm::of(&request) {
                Ok((form, ask)) => {
                    *pending.lock().expect("pending ask") =
                        Some(attended.form(form, ask, responder));
                    Ok(())
                }
                Err(declined) => responder.respond(declined),
            }
        })
        .await
        .if_request(async |request: UntypedMessage, responder| {
            answer_extension(policy, request, responder, events)
        })
        .await
        .otherwise_ignore()?;
    Ok(pending.into_inner().expect("pending ask"))
}