rho-coding-agent 3.12.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
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
//! Deterministic ACP peer shared by Channel tests and the debug-only
//! `rho __acp-fixture-agent` subcommand. Blocking client requests run in
//! spawned foreground-independent tasks; callbacks never await an outgoing
//! request on the dispatch loop.

use agent_client_protocol::{
    schema::ProtocolVersion,
    v1::schema::{
        AgentCapabilities, AuthenticateRequest, AuthenticateResponse, CancelNotification,
        InitializeRequest, InitializeResponse, McpCapabilities, NewSessionRequest,
        NewSessionResponse, PermissionOption, PromptCapabilities, PromptRequest, PromptResponse,
        RequestPermissionRequest, ResumeSessionRequest, ResumeSessionResponse, SessionCapabilities,
        SessionConfigOption, SessionMode, SessionModeState, SessionNotification,
        SessionResumeCapabilities, SessionUpdate, SetSessionConfigOptionRequest,
        SetSessionConfigOptionResponse, SetSessionModeRequest, SetSessionModeResponse, StopReason,
        ToolCallUpdate,
    },
    v1::{ConnectionTo, Responder},
    Agent, Client, ConnectTo, Error, Handled, UntypedMessage,
};
use rho_tools::cancellation::RunCancellation;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::{
    collections::VecDeque,
    fs::File,
    io::Write,
    sync::{
        atomic::{AtomicBool, Ordering},
        Arc, Mutex,
    },
};
use tokio::sync::{mpsc, Notify};

mod stdio_mcp;
mod v2;
use stdio_mcp::SharedStdio;
#[cfg(test)]
pub(crate) use stdio_mcp::StdioMcp;
pub(crate) use stdio_mcp::StdioMcpScript;
pub(crate) use v2::V2Script;
#[cfg(test)]
pub(crate) use v2::V2Step;

#[derive(Clone, Default, Serialize, Deserialize)]
pub(crate) struct Script {
    #[serde(default)]
    pub(crate) initialize_error: Option<String>,
    #[serde(default)]
    pub(crate) authenticate_error: Option<String>,
    #[serde(default)]
    pub(crate) new_session_error: Option<String>,
    #[serde(default)]
    pub(crate) set_mode_error: Option<String>,
    #[serde(default)]
    pub(crate) modes: Vec<String>,
    /// Advertised by `session/new`, and echoed by `session/set_config_option`
    /// unless `config_options_after_set` is nonempty.
    #[serde(default)]
    pub(crate) config_options: Vec<SessionConfigOption>,
    /// The full option set `session/set_config_option` answers with, for
    /// agents where one change moves other options.
    #[serde(default)]
    pub(crate) config_options_after_set: Vec<SessionConfigOption>,
    /// Advertise `_session/steering` in `initialize`.
    #[serde(default)]
    pub(crate) steering: bool,
    /// The `_session/steering` reply: `injected` when unset. Ignored when
    /// `steer_error` is set.
    #[serde(default)]
    pub(crate) steer_reply: Option<Value>,
    #[serde(default)]
    pub(crate) steer_error: Option<String>,
    pub(crate) turns: Vec<Vec<Step>>,
    /// Advertise `sessionCapabilities.resume`, and play these turns, instead
    /// of `turns`, in a process that resumed its session.
    #[serde(default)]
    pub(crate) resumed_turns: Option<Vec<Vec<Step>>>,
    /// Advertise `mcpCapabilities.acp`: take MCP servers carried over the
    /// connection, as claude-agent-acp does.
    #[serde(default)]
    pub(crate) mcp_over_acp: bool,
    /// Advertise `promptCapabilities.image`: take image blocks in
    /// `session/prompt`, as `claude-agent-acp` and `agy` do.
    #[serde(default)]
    pub(crate) image_prompts: bool,
    /// `mcp/message` envelopes sent, in order, before `session/new` is
    /// answered, as claude-agent-acp discovers and lists a server while it
    /// sets the session up; `"$server"` as in [`Step::Mcp`].
    #[serde(default)]
    pub(crate) setup_mcp: Vec<Value>,
    /// A file, relative to the agent's working directory, that marks a
    /// process that stalled on `session/resume`: the first process to
    /// resume its session, finding no such file, makes it and never
    /// answers, as an agent that hangs before it takes its prompt does,
    /// until Rho ends it (within the setup step's budget); later processes
    /// resume as usual.
    #[serde(default)]
    pub(crate) stall_resume_once: Option<String>,
    /// A file, relative to the agent's working directory, that marks a
    /// process whose `session/resume` was refused: the first process to
    /// resume its session, finding no such file, makes it and answers with
    /// an error, as an agent that cannot restore the conversation does;
    /// later processes resume as usual.
    #[serde(default)]
    pub(crate) refuse_resume_once: Option<String>,
    /// Start the stdio MCP server `session/new` or `session/resume`
    /// declared, and speak MCP to it over its stdio, as agy does with rho's
    /// stdio bridge.
    #[serde(default)]
    pub(crate) stdio_mcp: Option<StdioMcpScript>,
    /// Speak ACP v2 only, as this script says, instead of v1: everything
    /// above is the v1 dialect's.
    #[serde(default)]
    pub(crate) v2: Option<V2Script>,
}

#[derive(Clone, Serialize, Deserialize)]
#[serde(tag = "step", rename_all = "snake_case")]
pub(crate) enum Step {
    Update {
        #[serde(deserialize_with = "update_from_value")]
        update: Box<SessionUpdate>,
    },
    Permission {
        call: Box<ToolCallUpdate>,
        options: Vec<PermissionOption>,
    },
    Extension {
        method: String,
        params: Value,
    },
    /// An `mcp/message` request, as the agent's MCP client sends one to a
    /// server the client declared over ACP: `envelope` is its params, with
    /// `"$server"` standing for the id of the `acp` server the session's
    /// setup declared, `"$session"` for the session's id, `"$cwd"` for the
    /// agent's working directory, and `"$reply:<pointer>"` for what the
    /// JSON pointer finds in the JSON that opens the text of the last
    /// `mcp/message` reply, as an agent passes on what a tool returned,
    /// such as the id of a session it started.
    Mcp {
        envelope: Value,
    },
    /// A JSON-RPC message to the stdio MCP server the session started
    /// ([`Script::stdio_mcp`]); a request's reply is recorded.
    StdioMcp {
        message: Value,
    },
    Stop {
        reason: StopReason,
    },
    /// Signal readiness, then await a real session/cancel notification.
    Hang,
    /// [`Self::Hang`], in the first process to play it, which makes
    /// `marker`, a file relative to the agent's working directory; nothing
    /// in a process that finds it made, which plays on.
    HangOnce {
        marker: String,
    },
    /// Close the transport while the prompt is still pending.
    Disconnect,
    /// Signal readiness, await session/cancel, then close the transport
    /// instead of answering the prompt.
    DisconnectOnCancel,
    /// Signal readiness, then await a `_session/steering` request.
    AwaitSteer,
    /// Send an update before the turn is queued, as claude-agent-acp does
    /// with an open task plan, then wait for the steer it declines.
    BeforeQueued {
        update: Box<SessionUpdate>,
    },
}

/// Parse an update the way the wire does. Inside the internally tagged
/// [`Step`], serde buffers the nested internally tagged `SessionUpdate`, and
/// the schema's default-on-error fields (such as `usage_update.cost`) then
/// silently drop.
fn update_from_value<'de, D: serde::Deserializer<'de>>(
    deserializer: D,
) -> Result<Box<SessionUpdate>, D::Error> {
    let value = Value::deserialize(deserializer)?;
    serde_json::from_value(value).map_err(serde::de::Error::custom)
}

/// Whole wire requests/replies, without assertions embedded in the fake.
#[derive(Debug, Default, Serialize)]
pub(crate) struct Record {
    pub(crate) requests: Vec<Value>,
    pub(crate) replies: Vec<Value>,
    /// Each entry is also appended here as one JSON line. The debug fixture
    /// needs this because Rho terminates the agent rather than letting it exit.
    #[serde(skip)]
    journal: Option<File>,
}

impl Record {
    fn push_request(&mut self, request: Value) {
        self.write_journal(&json!({"request": request}));
        self.requests.push(request);
    }

    fn push_reply(&mut self, reply: Value) {
        self.write_journal(&json!({"reply": reply}));
        self.replies.push(reply);
    }

    /// Each session setup request's method and the `mcpServers` it
    /// declared, in order.
    pub(crate) fn declared_servers(&self) -> Vec<(String, Vec<Value>)> {
        self.requests
            .iter()
            .filter_map(|request| {
                let method = request["method"].as_str()?;
                matches!(method, "session/new" | "session/resume").then(|| {
                    let servers = request["params"]["mcpServers"].as_array();
                    (method.to_owned(), servers.cloned().unwrap_or_default())
                })
            })
            .collect()
    }

    /// The id of the `acp` MCP server the last session setup declared.
    fn declared_server(&self) -> String {
        let (_, servers) = self.declared_servers().pop().unwrap_or_default();
        servers
            .iter()
            .find(|server| server["type"] == "acp")
            .and_then(|server| server["serverId"].as_str().map(str::to_owned))
            .unwrap_or_default()
    }

    fn write_journal(&mut self, entry: &Value) {
        if let Some(journal) = self.journal.as_mut() {
            // One append per line: `writeln!` would write a JSON value in
            // pieces, which a reader of the journal can see half done, and
            // which another turn's agent could append between.
            journal
                .write_all(format!("{entry}\n").as_bytes())
                .expect("write scripted agent journal");
        }
    }
}

#[derive(Debug, PartialEq, Eq)]
pub(crate) enum Signal {
    Prompt,
    Waiting,
    Cancel,
}

pub(crate) struct ScriptedAgent {
    script: Script,
    record: Arc<Mutex<Record>>,
    signals: mpsc::UnboundedSender<Signal>,
}

impl ScriptedAgent {
    pub(crate) fn new(
        script: Script,
    ) -> (Self, Arc<Mutex<Record>>, mpsc::UnboundedReceiver<Signal>) {
        let record = Arc::new(Mutex::new(Record::default()));
        let (signals, receiver) = mpsc::unbounded_channel();
        (
            Self {
                script,
                record: Arc::clone(&record),
                signals,
            },
            record,
            receiver,
        )
    }

    /// Also append every recorded request and reply to `journal` as JSONL.
    #[cfg(debug_assertions)]
    pub(crate) fn with_journal(self, journal: File) -> Self {
        self.record.lock().expect("script record").journal = Some(journal);
        self
    }

    pub(crate) async fn run(self, transport: impl ConnectTo<Agent> + 'static) -> Result<(), Error> {
        let Self {
            script,
            record,
            signals,
        } = self;
        if let Some(v2) = script.v2 {
            return v2::run(v2, record, signals, transport).await;
        }
        let closed = RunCancellation::new();
        let cancelled = RunCancellation::new();
        let initialize_record = Arc::clone(&record);
        let initialize_error = script.initialize_error;
        let authenticate_error = script.authenticate_error;
        let authenticate_record = Arc::clone(&record);
        let new_record = Arc::clone(&record);
        let new_error = script.new_session_error;
        let setup_mcp = script.setup_mcp;
        let modes = script.modes;
        let mode_record = Arc::clone(&record);
        let mode_error = script.set_mode_error;
        let new_config_options = script.config_options.clone();
        let config_options = if script.config_options_after_set.is_empty() {
            script.config_options
        } else {
            script.config_options_after_set
        };
        let config_record = Arc::clone(&record);
        let prompt_record = Arc::clone(&record);
        let turns = Arc::new(Mutex::new(VecDeque::from(script.turns)));
        let resume_turns = Arc::clone(&turns);
        let resume_record = Arc::clone(&record);
        let resumes = script.resumed_turns.is_some();
        let resumed_turns = script.resumed_turns.unwrap_or_default();
        let resume_modes = modes.clone();
        let resume_config_options = new_config_options.clone();
        let stall_resume_once = script.stall_resume_once;
        let refuse_resume_once = script.refuse_resume_once;
        let prompt_closed = closed.clone();
        let prompt_cancelled = cancelled.clone();
        let prompt_signals = signals.clone();
        let steered = Arc::new(Notify::new());
        let prompt_steered = Arc::clone(&steered);
        let declined = Arc::new(Notify::new());
        let prompt_declined = Arc::clone(&declined);
        // Like claude-agent-acp, a turn exists for steering only once it is
        // queued, which the fake marks with the turn's first update; until
        // then a steer is declined with `promptRequired`.
        let turn_live = Arc::new(AtomicBool::new(false));
        let prompt_turn_live = Arc::clone(&turn_live);
        let steer_record = Arc::clone(&record);
        let advertise_steering = script.steering;
        let mcp_over_acp = script.mcp_over_acp;
        let image_prompts = script.image_prompts;
        let new_stdio_script = script.stdio_mcp;
        let resume_stdio_script = new_stdio_script.clone();
        let stdio: SharedStdio = Arc::default();
        let new_stdio = Arc::clone(&stdio);
        let resume_stdio = Arc::clone(&stdio);
        let prompt_stdio = Arc::clone(&stdio);
        let steer_reply = match script.steer_error {
            Some(message) => Err(message),
            None => Ok(script
                .steer_reply
                .unwrap_or_else(|| json!({"outcome": "injected"}))),
        };
        Agent
            .v1()
            .name("rho-scripted-agent")
            .on_receive_request(
                async move |request: InitializeRequest, responder, _cx| {
                    record_request(&initialize_record, "initialize", &request);
                    match &initialize_error {
                        Some(message) => responder.respond_with_error(fake_error(message)),
                        None => responder.respond(
                            InitializeResponse::new(ProtocolVersion::V1)
                                .agent_capabilities(
                                    AgentCapabilities::new()
                                        .session_capabilities(
                                            SessionCapabilities::new().resume(
                                                resumes.then(SessionResumeCapabilities::new),
                                            ),
                                        )
                                        .mcp_capabilities(McpCapabilities::new().acp(mcp_over_acp))
                                        .prompt_capabilities(
                                            PromptCapabilities::new().image(image_prompts),
                                        ),
                                )
                                .meta(
                                    advertise_steering
                                        .then(|| json!({"steering": {"supported": true}}))
                                        .and_then(|meta| meta.as_object().cloned()),
                                ),
                        ),
                    }
                },
                agent_client_protocol::on_receive_request!(),
            )
            .on_receive_request(
                async move |request: AuthenticateRequest, responder, _cx| {
                    record_request(&authenticate_record, "authenticate", &request);
                    match &authenticate_error {
                        Some(message) => responder.respond_with_error(fake_error(message)),
                        None => responder.respond(AuthenticateResponse::new()),
                    }
                },
                agent_client_protocol::on_receive_request!(),
            )
            .on_receive_request(
                async move |request: NewSessionRequest, responder, cx| {
                    record_request(&new_record, "session/new", &request);
                    if let Some(message) = &new_error {
                        return responder.respond_with_error(fake_error(message));
                    }
                    let response = NewSessionResponse::new("scripted-session")
                        .modes(SessionModeState::new(
                            "agent",
                            modes
                                .iter()
                                .map(|mode| SessionMode::new(mode.clone(), mode.clone()))
                                .collect(),
                        ))
                        .config_options(
                            (!new_config_options.is_empty()).then(|| new_config_options.clone()),
                        );
                    // Off the dispatch loop, which must stay free to take
                    // Rho's answers.
                    let (record, setup_mcp) = (Arc::clone(&new_record), setup_mcp.clone());
                    let (stdio, stdio_script) = (Arc::clone(&new_stdio), new_stdio_script.clone());
                    let servers = request.mcp_servers.clone();
                    let connection = cx.clone();
                    cx.spawn(async move {
                        if let Some(script) = stdio_script {
                            stdio_mcp::start(&stdio, &record, &servers, script).await?;
                        }
                        send_mcp(
                            &connection.clone().into_raw(),
                            &record,
                            setup_mcp,
                            "scripted-session",
                        )
                        .await?;
                        responder.respond(response)
                    })
                },
                agent_client_protocol::on_receive_request!(),
            )
            .on_receive_request(
                async move |request: ResumeSessionRequest, responder, cx| {
                    record_request(&resume_record, "session/resume", &request);
                    if refuse_resume_once.as_deref().is_some_and(first_to_mark) {
                        return responder
                            .respond_with_error(fake_error("could not restore the conversation"));
                    }
                    if stall_resume_once.as_deref().is_some_and(first_to_mark) {
                        // Held unanswered, off the dispatch loop, until Rho
                        // ends the process.
                        return cx.spawn(async move {
                            let _unanswered = responder;
                            std::future::pending::<Result<(), Error>>().await
                        });
                    }
                    *resume_turns.lock().expect("script turns") =
                        VecDeque::from(resumed_turns.clone());
                    let response = ResumeSessionResponse::new()
                        .modes(SessionModeState::new(
                            "agent",
                            resume_modes
                                .iter()
                                .map(|mode| SessionMode::new(mode.clone(), mode.clone()))
                                .collect(),
                        ))
                        .config_options(
                            (!resume_config_options.is_empty())
                                .then(|| resume_config_options.clone()),
                        );
                    let Some(script) = resume_stdio_script.clone() else {
                        return responder.respond(response);
                    };
                    // As agy starts a resumed session's stdio server too,
                    // off the dispatch loop.
                    let (stdio, record) = (Arc::clone(&resume_stdio), Arc::clone(&resume_record));
                    let servers = request.mcp_servers.clone();
                    cx.spawn(async move {
                        stdio_mcp::start(&stdio, &record, &servers, script).await?;
                        responder.respond(response)
                    })
                },
                agent_client_protocol::on_receive_request!(),
            )
            .on_receive_request(
                async move |request: SetSessionModeRequest, responder, _cx| {
                    record_request(&mode_record, "session/set_mode", &request);
                    match &mode_error {
                        Some(message) => responder.respond_with_error(fake_error(message)),
                        None => responder.respond(SetSessionModeResponse::new()),
                    }
                },
                agent_client_protocol::on_receive_request!(),
            )
            .on_receive_request(
                async move |request: SetSessionConfigOptionRequest, responder, _cx| {
                    record_request(&config_record, "session/set_config_option", &request);
                    responder.respond(SetSessionConfigOptionResponse::new(config_options.clone()))
                },
                agent_client_protocol::on_receive_request!(),
            )
            .on_receive_request(
                async move |request: PromptRequest, responder, cx| {
                    record_request(&prompt_record, "session/prompt", &request);
                    let _ = prompt_signals.send(Signal::Prompt);
                    let steps = turns
                        .lock()
                        .expect("script turns")
                        .pop_front()
                        .ok_or_else(|| fake_error("unexpected prompt"))?;
                    let record = Arc::clone(&prompt_record);
                    let signals = prompt_signals.clone();
                    let cancelled = prompt_cancelled.clone();
                    let closed = prompt_closed.clone();
                    let steered = Arc::clone(&prompt_steered);
                    let turn_live = Arc::clone(&prompt_turn_live);
                    let declined = Arc::clone(&prompt_declined);
                    let stdio = Arc::clone(&prompt_stdio);
                    cx.clone().spawn(async move {
                        play_turn(
                            cx,
                            request,
                            responder,
                            steps,
                            TurnControls {
                                record,
                                signals,
                                cancelled,
                                closed,
                                steered,
                                turn_live,
                                declined,
                                stdio,
                            },
                        )
                        .await
                    })
                },
                agent_client_protocol::on_receive_request!(),
            )
            .on_receive_notification(
                async move |request: CancelNotification, _cx| {
                    record_request(&record, "session/cancel", &request);
                    let _ = signals.send(Signal::Cancel);
                    cancelled.cancel();
                    Ok(())
                },
                agent_client_protocol::on_receive_notification!(),
            )
            .on_receive_request(
                async move |request: UntypedMessage, responder: Responder<Value>, _cx| {
                    if request.method != "_session/steering" {
                        return Ok(Handled::No {
                            message: (request, responder),
                            retry: false,
                        });
                    }
                    record_request(&steer_record, &request.method, &request.params);
                    if !turn_live.load(Ordering::SeqCst) {
                        responder.respond(
                            json!({"outcome": "promptRequired", "reason": "noRunningTurn"}),
                        )?;
                        declined.notify_one();
                        return Ok(Handled::Yes);
                    }
                    steered.notify_one();
                    match &steer_reply {
                        Ok(reply) => responder.respond(reply.clone())?,
                        Err(message) => responder.respond_with_error(fake_error(message))?,
                    }
                    Ok(Handled::Yes)
                },
                agent_client_protocol::on_receive_request!(),
            )
            .connect_with(transport, async move |cx| {
                tokio::select! { _ = cx.incoming_closed() => {}, _ = closed.cancelled() => {} }
                Ok(())
            })
            .await
    }
}

/// Sends `envelopes` as `mcp/message` requests to the server the last
/// session setup declared, in order, recording each reply.
async fn send_mcp(
    cx: &agent_client_protocol::ConnectionTo<Client>,
    record: &Mutex<Record>,
    envelopes: Vec<Value>,
    session: &str,
) -> Result<(), agent_client_protocol::Error> {
    for envelope in envelopes {
        let server = record.lock().expect("script record").declared_server();
        let envelope = substitute(envelope, &server, session, record);
        let response = cx
            .send_request(UntypedMessage::new("mcp/message", envelope)?)
            .block_task()
            .await;
        let reply = match response {
            Ok(result) => json!({"method": "mcp/message", "result": result}),
            Err(error) => json!({"method": "mcp/message", "error": error}),
        };
        record.lock().expect("script record").push_reply(reply);
    }
    Ok(())
}

/// `value` with each placeholder string replaced: `"$server"`,
/// `"$session"`, `"$cwd"`, and `"$reply:<pointer>"`, by what the JSON
/// pointer finds in the JSON that opens the text of the last `mcp/message`
/// reply `record` holds (see [`Step::Mcp`]). A placeholder that resolves to
/// nothing, or any other string that starts with `$`, as a misspelt
/// `"$sesion"` would, is a bug in the script, which panics.
fn substitute(value: Value, server: &str, session: &str, record: &Mutex<Record>) -> Value {
    // Read once, at the first `$reply:` placeholder.
    let returned = std::cell::OnceCell::new();
    replace_strings(value, &|text: &str| match text {
        "$server" => Some(Value::String(server.to_owned())),
        "$session" => Some(Value::String(session.to_owned())),
        "$cwd" => {
            let cwd = std::env::current_dir()
                .expect("the scripted agent's working directory, for the script's `$cwd`");
            Some(Value::String(cwd.display().to_string()))
        }
        _ => {
            let Some(pointer) = text.strip_prefix("$reply:") else {
                assert!(
                    !text.starts_with('$'),
                    "the script's `{text}` is no placeholder: use `$server`, `$session`, \
                     `$cwd`, or `$reply:<pointer>`"
                );
                return None;
            };
            let returned = returned.get_or_init(|| last_returned(record));
            let found = returned
                .as_ref()
                .and_then(|returned| returned.pointer(pointer));
            Some(found.cloned().unwrap_or_else(|| {
                panic!(
                    "the script's `{text}` finds nothing in the JSON the last `mcp/message` \
                     reply returned: {returned:?}"
                )
            }))
        }
    })
}

/// The JSON that opens the text of the last `mcp/message` reply `record`
/// holds, as a tool returns JSON ahead of any note it adds; `None` without
/// one.
fn last_returned(record: &Mutex<Record>) -> Option<Value> {
    let record = record.lock().expect("script record");
    let text = record
        .replies
        .iter()
        .rev()
        .find(|reply| reply["method"] == "mcp/message")
        // The envelope's result, around the MCP call's.
        .and_then(|reply| reply["result"]["result"]["content"][0]["text"].as_str())?;
    let mut values = serde_json::Deserializer::from_str(text).into_iter::<Value>();
    values.next()?.ok()
}

/// `value` with each string `replace` answers for replaced by its answer.
fn replace_strings(value: Value, replace: &impl Fn(&str) -> Option<Value>) -> Value {
    match value {
        Value::String(text) => replace(&text).unwrap_or(Value::String(text)),
        Value::Array(items) => Value::Array(
            items
                .into_iter()
                .map(|item| replace_strings(item, replace))
                .collect(),
        ),
        Value::Object(fields) => Value::Object(
            fields
                .into_iter()
                .map(|(key, item)| (key, replace_strings(item, replace)))
                .collect(),
        ),
        other => other,
    }
}

/// Whether this process is the first to reach a once-only step marked by
/// `marker`, a file relative to its working directory: it makes the file,
/// so no later process is.
fn first_to_mark(marker: &str) -> bool {
    std::fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(marker)
        .is_ok()
}

fn record_request(record: &Mutex<Record>, method: &str, request: &impl Serialize) {
    record
        .lock()
        .expect("script record")
        .push_request(json!({"method": method, "params": request}));
}

fn fake_error(message: &str) -> Error {
    let mut error = Error::internal_error();
    error.message = message.into();
    error
}

struct TurnControls {
    record: Arc<Mutex<Record>>,
    signals: mpsc::UnboundedSender<Signal>,
    cancelled: RunCancellation,
    closed: RunCancellation,
    steered: Arc<Notify>,
    turn_live: Arc<AtomicBool>,
    declined: Arc<Notify>,
    stdio: SharedStdio,
}

async fn play_turn(
    cx: ConnectionTo<Client>,
    request: PromptRequest,
    responder: Responder<PromptResponse>,
    steps: Vec<Step>,
    controls: TurnControls,
) -> Result<(), Error> {
    let TurnControls {
        record,
        signals,
        cancelled,
        closed,
        steered,
        turn_live,
        declined,
        stdio,
    } = controls;
    for step in steps {
        match step {
            Step::Update { update } => {
                turn_live.store(true, Ordering::SeqCst);
                cx.send_notification(SessionNotification::new(
                    request.session_id.clone(),
                    *update,
                ))?;
            }
            Step::Permission { call, options } => {
                let response = cx
                    .send_request(RequestPermissionRequest::new(
                        request.session_id.clone(),
                        *call,
                        options,
                    ))
                    .block_task()
                    .await?;
                record.lock().expect("script record").push_reply(
                    json!({"method": "session/request_permission", "result": response}),
                );
            }
            Step::Extension { method, params } => {
                let response = cx
                    .send_request(UntypedMessage::new(&method, params)?)
                    .block_task()
                    .await;
                let reply = match response {
                    Ok(result) => json!({"method": method, "result": result}),
                    Err(error) => json!({"method": method, "error": error}),
                };
                record.lock().expect("script record").push_reply(reply);
            }
            Step::Mcp { envelope } => {
                let session = request.session_id.to_string();
                send_mcp(&cx.clone().into_raw(), &record, vec![envelope], &session).await?;
            }
            Step::StdioMcp { message } => stdio_mcp::send(&stdio, &record, vec![message]).await,
            Step::Stop { reason } => {
                turn_live.store(false, Ordering::SeqCst);
                return responder.respond(PromptResponse::new(reason));
            }
            Step::Hang => {
                let _ = signals.send(Signal::Waiting);
                cancelled.cancelled().await;
                return responder.respond(PromptResponse::new(StopReason::Cancelled));
            }
            Step::HangOnce { marker } => {
                if first_to_mark(&marker) {
                    let _ = signals.send(Signal::Waiting);
                    cancelled.cancelled().await;
                    return responder.respond(PromptResponse::new(StopReason::Cancelled));
                }
            }
            Step::Disconnect => {
                closed.cancel();
                return std::future::pending().await;
            }
            Step::DisconnectOnCancel => {
                let _ = signals.send(Signal::Waiting);
                cancelled.cancelled().await;
                closed.cancel();
                return std::future::pending().await;
            }
            Step::BeforeQueued { update } => {
                cx.send_notification(SessionNotification::new(
                    request.session_id.clone(),
                    *update,
                ))?;
                declined.notified().await;
            }
            Step::AwaitSteer => {
                let _ = signals.send(Signal::Waiting);
                steered.notified().await;
            }
        }
    }
    Err(fake_error("script turn has no stop step"))
}