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
//! The scripted agent's ACP v2 dialect ([`super::Script::v2`]): an agent
//! that speaks v2 only, as claude-agent-acp 0.114.0 does to a client that
//! asks for v2. Its session's mode is a select config option, and a turn is
//! the updates it plays between the prompt's acknowledgement and an `idle`
//! state.

use super::{fake_error, record_request, send_mcp, Record, Signal};
use agent_client_protocol::{
    schema::ProtocolVersion,
    v2::{schema as v2, ConnectionTo, Responder},
    Agent, Client, ConnectTo, Error,
};
use rho_tools::cancellation::RunCancellation;
use serde::{Deserialize, Serialize};
use std::{
    collections::VecDeque,
    sync::{Arc, Mutex},
};
use tokio::sync::mpsc;

/// The session every v2 setup answers with.
pub(crate) const SESSION: &str = "scripted-session";

#[derive(Clone, Default, Serialize, Deserialize)]
pub(crate) struct V2Script {
    /// The options `session/new` and `session/resume` offer, as the
    /// session's current options; `session/set_config_option` moves a
    /// select to the asked value unless `sticky_config` names it.
    #[serde(default)]
    pub(crate) config_options: Vec<v2::SessionConfigOption>,
    /// Options `session/set_config_option` answers for without moving
    /// them, as an agent that keeps a value it was asked to change.
    #[serde(default)]
    pub(crate) sticky_config: Vec<String>,
    /// Right after answering `session/set_config_option`, move the mode
    /// option to this value and report it, as an agent that changes its
    /// own mode.
    #[serde(default)]
    pub(crate) mode_after_set: Option<String>,
    /// Advertise `session.mcp.acp`.
    #[serde(default)]
    pub(crate) mcp_over_acp: bool,
    /// Advertise `session.prompt.image`.
    #[serde(default)]
    pub(crate) image_prompts: bool,
    /// Each prompt plays the next turn, after acknowledging the prompt. A
    /// prompt while a turn plays steers it instead ([`V2Step::AwaitSteer`]).
    pub(crate) turns: Vec<Vec<V2Step>>,
    /// Refuse a steering prompt, as an agent that takes none mid-turn.
    #[serde(default)]
    pub(crate) refuse_steers: bool,
    /// Hold a steering prompt until the turn ends, then play it as the next
    /// turn, as claude-agent-acp 0.114.0 does while an input request is
    /// open: `running` goes out before the prompt's answer.
    #[serde(default)]
    pub(crate) hold_steers: bool,
}

/// A turn's steering: whether a turn plays, so a prompt steers it, and the
/// steer a [`V2Step::AwaitSteer`] waits for.
#[derive(Default)]
struct Steering {
    playing: std::sync::atomic::AtomicBool,
    steered: tokio::sync::Notify,
    refuse: bool,
    hold: bool,
    /// A held steering prompt, answered as its turn starts.
    held: Mutex<Option<Responder<v2::PromptResponse>>>,
}

#[derive(Clone, Serialize, Deserialize)]
#[serde(tag = "step", rename_all = "snake_case")]
pub(crate) enum V2Step {
    /// An update of the session `session`, the root's when unset.
    Update {
        #[serde(default)]
        session: Option<String>,
        #[serde(deserialize_with = "update_from_value")]
        update: Box<v2::SessionUpdate>,
    },
    /// The root session's `running` state.
    Running,
    /// The root session's `idle` state, which ends the turn's play.
    Idle {
        #[serde(default)]
        stop_reason: Option<v2::StopReason>,
    },
    /// Signal readiness, await `session/cancel`, then report `idle` with
    /// `cancelled`.
    Hang,
    /// Let `millis` of the agent's time pass, on tokio's clock, which a
    /// test pauses so the time passes at once.
    Wait { millis: u64 },
    /// Signal readiness, then send nothing more, as an agent whose
    /// background work never ends.
    Rest,
    /// End the turn's play without a state of its own, as after a scripted
    /// `idle` update: a prompt then plays the next turn. Signals readiness.
    Done,
    /// Ask permission, to allow or reject once, for what `title` names,
    /// about the tool call `call` when set, recording the answer.
    Permission {
        title: String,
        #[serde(default)]
        call: Option<Box<v2::ToolCallUpdate>>,
    },
    /// Signal readiness, then await a steering prompt, taken or refused.
    AwaitSteer,
    /// Ask the form `request` (`elicitation/create`), recording the answer.
    Form {
        request: Box<v2::CreateElicitationRequest>,
    },
    /// Send `mcp/message` with `envelope`, its placeholders filled as the
    /// v1 dialect's [`super::Step::Mcp`], recording the reply.
    Mcp { envelope: serde_json::Value },
}

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

pub(super) async fn run(
    script: V2Script,
    record: Arc<Mutex<Record>>,
    signals: mpsc::UnboundedSender<Signal>,
    transport: impl ConnectTo<Agent> + 'static,
) -> Result<(), Error> {
    let options = Arc::new(Mutex::new(script.config_options));
    let turns = Arc::new(Mutex::new(VecDeque::from(script.turns)));
    let cancelled = RunCancellation::new();
    let sticky = script.sticky_config;
    let mode_after_set = script.mode_after_set;
    let mcp_over_acp = script.mcp_over_acp;
    let image_prompts = script.image_prompts;
    let steering = Arc::new(Steering {
        refuse: script.refuse_steers,
        hold: script.hold_steers,
        ..Steering::default()
    });
    let (initialize_record, new_record, resume_record, config_record, prompt_record) = (
        Arc::clone(&record),
        Arc::clone(&record),
        Arc::clone(&record),
        Arc::clone(&record),
        Arc::clone(&record),
    );
    let (new_options, resume_options, config_options) = (
        Arc::clone(&options),
        Arc::clone(&options),
        Arc::clone(&options),
    );
    let (prompt_signals, prompt_cancelled) = (signals.clone(), cancelled.clone());
    Agent
        .v2()
        .name("rho-scripted-agent")
        .on_receive_request(
            async move |request: v2::InitializeRequest, responder, _cx| {
                record_request(&initialize_record, "initialize", &request);
                let session = v2::SessionCapabilities::new()
                    .mcp(
                        mcp_over_acp
                            .then(|| v2::McpCapabilities::new().acp(v2::McpAcpCapabilities::new())),
                    )
                    .prompt(image_prompts.then(|| {
                        v2::PromptCapabilities::new().image(v2::PromptImageCapabilities::new())
                    }));
                responder.respond(
                    v2::InitializeResponse::new(
                        ProtocolVersion::V2,
                        v2::Implementation::new("rho-scripted-agent", "0"),
                    )
                    .capabilities(v2::AgentCapabilities::new().session(session)),
                )
            },
            agent_client_protocol::on_receive_request!(),
        )
        .on_receive_request(
            async move |request: v2::NewSessionRequest, responder, cx| {
                record_request(&new_record, "session/new", &request);
                let options = new_options.lock().expect("script options").clone();
                // Before its answer, as an agent that reports the options it
                // starts with does.
                cx.send_notification(options_changed(&options))?;
                responder.respond(v2::NewSessionResponse::new(SESSION).config_options(options))
            },
            agent_client_protocol::on_receive_request!(),
        )
        .on_receive_request(
            async move |request: v2::ResumeSessionRequest, responder, cx| {
                record_request(&resume_record, "session/resume", &request);
                // A resume sends the session's state before it answers.
                cx.send_notification(idle(None))?;
                let options = resume_options.lock().expect("script options").clone();
                responder.respond(v2::ResumeSessionResponse::new().config_options(options))
            },
            agent_client_protocol::on_receive_request!(),
        )
        .on_receive_request(
            async move |request: v2::SetSessionConfigOptionRequest, responder, cx| {
                record_request(&config_record, "session/set_config_option", &request);
                let mut options = config_options.lock().expect("script options");
                if !sticky.contains(&request.config_id.to_string()) {
                    set_option(&mut options, &request)?;
                    // A change is also reported before the answer, as
                    // claude-agent-acp 0.114.0 does.
                    cx.send_notification(options_changed(&options))?;
                }
                responder.respond(v2::SetSessionConfigOptionResponse::new(options.clone()))?;
                if let Some(mode) = &mode_after_set {
                    let moved = v2::SetSessionConfigOptionRequest::new(
                        SESSION.to_owned(),
                        "mode",
                        v2::SessionConfigOptionValue::Id {
                            value: mode.clone().into(),
                        },
                    );
                    set_option(&mut options, &moved)?;
                    cx.send_notification(options_changed(&options))?;
                }
                Ok(())
            },
            agent_client_protocol::on_receive_request!(),
        )
        .on_receive_request(
            async move |request: v2::PromptRequest, responder, cx| {
                record_request(&prompt_record, "session/prompt", &request);
                if steering.playing.load(std::sync::atomic::Ordering::SeqCst) {
                    // The turn plays on either way.
                    steering.steered.notify_one();
                    if steering.refuse {
                        return responder.respond_with_error(fake_error("no steering here"));
                    }
                    if steering.hold {
                        *steering.held.lock().expect("held steer") = Some(responder);
                        return Ok(());
                    }
                    return responder.respond(v2::PromptResponse::new("steered-message"));
                }
                let _ = prompt_signals.send(Signal::Prompt);
                let steps = next_turn(&turns)?;
                let controls = (
                    Arc::clone(&prompt_record),
                    prompt_signals.clone(),
                    prompt_cancelled.clone(),
                    Arc::clone(&steering),
                    Arc::clone(&turns),
                );
                cx.clone()
                    .spawn(async move { play_turn(cx, responder, steps, controls).await })
            },
            agent_client_protocol::on_receive_request!(),
        )
        .on_receive_notification(
            async move |notification: v2::CancelSessionNotification, _cx| {
                record_request(&record, "session/cancel", &notification);
                let _ = signals.send(Signal::Cancel);
                cancelled.cancel();
                Ok(())
            },
            agent_client_protocol::on_receive_notification!(),
        )
        .connect_with(transport, async move |cx: ConnectionTo<Client>| {
            cx.incoming_closed().await;
            Ok(())
        })
        .await
}

/// Moves the select `request` names to the value it asks for.
fn set_option(
    options: &mut [v2::SessionConfigOption],
    request: &v2::SetSessionConfigOptionRequest,
) -> Result<(), Error> {
    let v2::SessionConfigOptionValue::Id { value } = &request.value else {
        return Err(fake_error("the script sets select options only"));
    };
    let select = options
        .iter_mut()
        .find(|option| option.config_id == request.config_id)
        .and_then(|option| match &mut option.kind {
            v2::SessionConfigKind::Select(select) => Some(select),
            _ => None,
        })
        .ok_or_else(|| fake_error("no such select option"))?;
    select.current_value = value.clone();
    Ok(())
}

fn options_changed(options: &[v2::SessionConfigOption]) -> v2::UpdateSessionNotification {
    update(
        SESSION,
        v2::SessionUpdate::ConfigOptionUpdate(v2::ConfigOptionUpdate::new(options.to_vec())),
    )
}

fn update(session: &str, update: v2::SessionUpdate) -> v2::UpdateSessionNotification {
    v2::UpdateSessionNotification::new(session.to_owned(), update)
}

fn idle(stop_reason: Option<v2::StopReason>) -> v2::UpdateSessionNotification {
    update(
        SESSION,
        v2::SessionUpdate::StateUpdate(v2::StateUpdate::Idle(
            v2::IdleStateUpdate::new().stop_reason(stop_reason),
        )),
    )
}

type Turns = Arc<Mutex<VecDeque<Vec<V2Step>>>>;

fn next_turn(turns: &Turns) -> Result<Vec<V2Step>, Error> {
    turns
        .lock()
        .expect("script turns")
        .pop_front()
        .ok_or_else(|| fake_error("unexpected prompt"))
}

fn running() -> v2::UpdateSessionNotification {
    update(
        SESSION,
        v2::SessionUpdate::StateUpdate(v2::StateUpdate::Running(v2::RunningStateUpdate::new())),
    )
}

async fn play_turn(
    cx: ConnectionTo<Client>,
    responder: Responder<v2::PromptResponse>,
    steps: Vec<V2Step>,
    (record, signals, cancelled, steering, turns): (
        Arc<Mutex<Record>>,
        mpsc::UnboundedSender<Signal>,
        RunCancellation,
        Arc<Steering>,
        Turns,
    ),
) -> Result<(), Error> {
    // The prompt is taken before its turn plays, as v2 acknowledges it.
    responder.respond(v2::PromptResponse::new("scripted-message"))?;
    steering
        .playing
        .store(true, std::sync::atomic::Ordering::SeqCst);
    let mut steps = VecDeque::from(steps);
    while let Some(step) = steps.pop_front() {
        match step {
            V2Step::Update {
                session,
                update: body,
            } => cx.send_notification(update(session.as_deref().unwrap_or(SESSION), *body))?,
            V2Step::Running => cx.send_notification(running())?,
            V2Step::Idle { stop_reason } => {
                steering
                    .playing
                    .store(false, std::sync::atomic::Ordering::SeqCst);
                cx.send_notification(idle(stop_reason))?;
                let held = steering.held.lock().expect("held steer").take();
                let Some(held) = held else {
                    return Ok(());
                };
                cx.send_notification(running())?;
                held.respond(v2::PromptResponse::new("held-message"))?;
                steering
                    .playing
                    .store(true, std::sync::atomic::Ordering::SeqCst);
                steps = VecDeque::from(next_turn(&turns)?);
            }
            V2Step::AwaitSteer => {
                let _ = signals.send(Signal::Waiting);
                steering.steered.notified().await;
            }
            V2Step::Wait { millis } => {
                tokio::time::sleep(std::time::Duration::from_millis(millis)).await;
            }
            V2Step::Done => {
                steering
                    .playing
                    .store(false, std::sync::atomic::Ordering::SeqCst);
                let _ = signals.send(Signal::Waiting);
                return Ok(());
            }
            V2Step::Rest => {
                let _ = signals.send(Signal::Waiting);
                std::future::pending::<()>().await;
            }
            V2Step::Hang => {
                let _ = signals.send(Signal::Waiting);
                cancelled.cancelled().await;
                return cx.send_notification(idle(Some(v2::StopReason::Cancelled)));
            }
            V2Step::Permission { title, call } => {
                let subject = call.map(|call| {
                    v2::RequestPermissionSubject::ToolCall(Box::new(
                        v2::ToolCallPermissionSubject::new(*call),
                    ))
                });
                let answer = cx
                    .send_request(
                        v2::RequestPermissionRequest::new(
                            SESSION.to_owned(),
                            title,
                            vec![
                                v2::PermissionOption::new(
                                    "allow",
                                    "Allow",
                                    v2::PermissionOptionKind::AllowOnce,
                                ),
                                v2::PermissionOption::new(
                                    "reject",
                                    "Reject",
                                    v2::PermissionOptionKind::RejectOnce,
                                ),
                            ],
                        )
                        .subject(subject),
                    )
                    .block_task()
                    .await?;
                record.lock().expect("script record").push_reply(
                    serde_json::json!({"method": "session/request_permission", "result": answer}),
                );
            }
            V2Step::Form { request } => {
                let answer = cx.send_request(*request).block_task().await?;
                record.lock().expect("script record").push_reply(
                    serde_json::json!({"method": "elicitation/create", "result": answer}),
                );
            }
            V2Step::Mcp { envelope } => {
                send_mcp(&cx.clone().into_raw(), &record, vec![envelope], SESSION).await?;
            }
        }
    }
    Err(fake_error("script turn has no idle step"))
}