rho-coding-agent 2.33.1

A fast Rust agent harness with a small footprint and opinionated defaults
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
//! 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::{
        v1::{
            AuthenticateRequest, AuthenticateResponse, CancelNotification, InitializeRequest,
            InitializeResponse, NewSessionRequest, NewSessionResponse, PermissionOption,
            PromptRequest, PromptResponse, RequestPermissionRequest, SessionConfigOption,
            SessionMode, SessionModeState, SessionNotification, SessionUpdate,
            SetSessionConfigOptionRequest, SetSessionConfigOptionResponse, SetSessionModeRequest,
            SetSessionModeResponse, StopReason, ToolCallUpdate,
        },
        ProtocolVersion,
    },
    Agent, Client, ConnectTo, ConnectionTo, Error, Handled, Responder, 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};

#[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>>,
}

#[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,
    },
    Stop {
        reason: StopReason,
    },
    /// Signal readiness, then await a real session/cancel notification.
    Hang,
    /// 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);
    }

    fn write_journal(&mut self, entry: &Value) {
        if let Some(journal) = self.journal.as_mut() {
            writeln!(journal, "{entry}").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;
        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 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 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 steer_reply = match script.steer_error {
            Some(message) => Err(message),
            None => Ok(script
                .steer_reply
                .unwrap_or_else(|| json!({"outcome": "injected"}))),
        };
        Agent
            .builder()
            .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).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);
                    match &new_error {
                        Some(message) => responder.respond_with_error(fake_error(message)),
                        None => responder.respond(
                            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()),
                                ),
                        ),
                    }
                },
                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);
                    cx.clone().spawn(async move {
                        play_turn(
                            cx,
                            request,
                            responder,
                            steps,
                            TurnControls {
                                record,
                                signals,
                                cancelled,
                                closed,
                                steered,
                                turn_live,
                                declined,
                            },
                        )
                        .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
    }
}

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>,
}

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,
    } = 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::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::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"))
}