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
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
//! Foreground ACP driver. All terminal writes remain in session::settle.

use super::{
    agent_tools::{self, AgentTools, Served},
    asks::{self, Asker, PendingAsk},
    connection,
    deciders::Deciders,
    handshake::{self, bounded, error, AgentFeatures, HANDSHAKE_STEP_BUDGET},
    person::{Attendance, Person},
    policy::AcpAgentPolicy,
    steering,
    turn::{classify_stop, TurnClassification},
    ExtensionAnswer,
};
use crate::cli_runtime::{
    agent_event::{render::EventRenderer, AgentEvent},
    parent_messages::{Delivered, ParentMessage, ParentMessageInbox},
    status_sink::StatusSink,
    BackgroundWork, CliPrompt,
};
use agent_client_protocol::util::MatchDispatch;
use agent_client_protocol::{
    v1::schema::{
        CancelNotification, CreateElicitationRequest, NewSessionRequest, NewSessionResponse,
        RequestPermissionRequest, ResumeSessionRequest, ResumeSessionResponse, SessionNotification,
        SessionUpdate, ToolCallId,
    },
    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 {
    /// The run ended as its last turn did, with that turn's reply.
    pub(super) fn ended(
        classification: TurnClassification,
        renderer: &EventRenderer,
        session_id: String,
    ) -> Self {
        Self {
            classification,
            session_id: Some(session_id),
            result_text: renderer.result_text().to_owned(),
            turns: renderer.turns(),
        }
    }

    pub(super) 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 or v2 responder, a v1 session's dispatch a raw one.
pub(super) 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 CliPrompt,
    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`]).
    /// Taken by the prompt that carries them, so an agent process that
    /// never prompted leaves them for the next.
    pub(super) prompt_results: &'a mut Option<ParentMessage>,
    /// What the run does with work the agent leaves running (v2 only).
    pub(super) background_work: BackgroundWork,
    /// Where to tell what the agent's `initialize` said; `None` for an
    /// agent that is no executable, as a test's channel.
    pub(super) adapter: Option<super::adapters::Adapter<'a>>,
}

/// 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: Arc<Mutex<P>>,
    context: DriverContext<'_>,
    tools: Option<Arc<dyn AgentTools>>,
) -> Result<DriverOutcome, String> {
    let DriverContext {
        prompt,
        cwd,
        resume,
        cancellation,
        inbox,
        renderer,
        sink,
        person,
        prompt_results,
        background_work,
        adapter,
    } = 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 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.into_raw())?;
                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, adapter) => result?,
            };
            if prompt.has_images() && !features.image {
                return Err(error(
                    "acp: the agent does not take image prompts: it does not advertise promptCapabilities.image",
                ));
            }
            let session_meta = policy.lock().expect("ACP policy").session_meta();
            let served = connection::serve(served.as_deref(), features.mcp_over_acp, "mcpCapabilities.acp", renderer, sink);
            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)),
                        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) => return Err(connection::resume_refused(sink, 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, background_work, /* initialized already */ adapter: None }, &events_tx, &mut events_rx).await
        }).await;
    connection::ended(outcome, cancellation, renderer, sink, |stopped| stopped)
}

/// 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();
    let prompt_results = prompt_results.take();
    session.send_prompt_blocks(connection::v1_blocks(connection::first_prompt(
        prompt,
        prompt_results.as_ref(),
    )))?;
    connection::prompt_sent(sink, prompt_results, &session_id);
    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::new(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(Some(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;
                            connection::delivered(sink, text, Delivered::NextTurn);
                            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::ended(classification, renderer, session_id));
                }
                _ => 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) => {
            connection::delivered(sink, text, Delivered::Steered);
            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,
    }
}

/// 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 policy = deciders.policy();
    // 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 required_mode = policy.lock().expect("ACP policy").session_mode();
            handshake::check_mode_update(&notification.update, required_mode.as_ref())?;
            tracking.turn_live |= is_turn_content(&notification.update);
            deciders.show(notification.update, &tracking.rejected, renderer, sink);
            Ok(())
        })
        .await
        .if_request(async |request: RequestPermissionRequest, responder| {
            let reply = Box::new(move |response| responder.respond(response));
            *pending.lock().expect("pending ask") =
                asks::permission(request, reply, deciders, asker, &mut tracking.rejected)?;
            Ok(())
        })
        .await
        .if_request(async |request: CreateElicitationRequest, responder| {
            let reply = Box::new(move |response| responder.respond(response));
            *pending.lock().expect("pending ask") = asks::form(&request, reply, asker)?;
            Ok(())
        })
        .await
        .if_request(async |request: UntypedMessage, responder| {
            answer_extension(policy, request, responder, events)
        })
        .await
        .otherwise_ignore()?;
    Ok(pending.into_inner().expect("pending ask"))
}