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
//! A run a person attends: the driver puts what its policy leaves to a
//! person to them, answers the agent as they do, and advertises forms; a
//! run nobody attends fails those asks closed.

use super::{
    permission::{Asking, PermissionDecision},
    person::{Heard, Person, PersonAnswer, PersonAsk},
    policy::AcpProtocol,
    scripted_agent::{Record, Script, ScriptedAgent, Step, V2Script, V2Step},
    session::run_on_channel,
    test_support::*,
    AcpSessionRequest,
};
use crate::{permission::PermissionMode, subagent::RunState};
use agent_client_protocol::{
    v1::schema::{
        ContentChunk, CurrentModeUpdate, PermissionOption, PermissionOptionKind, SessionUpdate,
        StopReason, ToolCall, ToolCallUpdate, ToolCallUpdateFields, ToolKind,
    },
    v2::schema as v2,
    Channel,
};
use pretty_assertions::assert_eq;
use rho_sdk::{HostInputResponse, HostInputSource};
use serde_json::{json, Value};
use std::sync::{Arc, Mutex};

/// What the person heard, in order: each ask's kind and what it shows, and
/// the mode the agent left plan mode for.
type Noted = Arc<Mutex<Vec<(String, String)>>>;

/// A person who approves every plan and tool call and picks `Blue` for
/// each form's `question_0`, noting what they heard.
fn approving_person() -> (Person, Noted) {
    let (person, mut heard) = Person::channel();
    let noted = Noted::default();
    let noting = Arc::clone(&noted);
    tokio::spawn(async move {
        while let Some(heard) = heard.recv().await {
            let asked = match heard {
                Heard::Asked(asked) => asked,
                Heard::LeftPlan(mode) => {
                    let left = ("left".to_owned(), mode.as_str().to_owned());
                    noting.lock().unwrap().push(left);
                    continue;
                }
            };
            let (note, answer) = match asked.ask {
                PersonAsk::Tool { title, .. } => {
                    (("tool", title.unwrap_or_default()), PersonAnswer::Allow)
                }
                PersonAsk::PlanExit { plan, to, .. } => (
                    ("plan", format!("{plan} -> {}", to.as_str())),
                    PersonAnswer::Allow,
                ),
                PersonAsk::Form { request, .. } => {
                    let questions = request
                        .questions()
                        .iter()
                        .map(|question| question.id().to_owned())
                        .collect::<Vec<_>>()
                        .join(",");
                    let answers = HostInputResponse::new()
                        .with_source(HostInputSource::User)
                        .answer("question_0", vec!["Blue".to_owned()]);
                    (("form", questions), PersonAnswer::Form(Ok(answers)))
                }
            };
            noting
                .lock()
                .unwrap()
                .push((note.0.to_owned(), note.1.to_owned()));
            let _ = asked.reply.send(answer);
        }
    });
    (person, noted)
}

/// What the agent heard: its requests and its replies to Rho's answers.
struct AgentHeard {
    requests: Vec<Value>,
    replies: Vec<Value>,
}

async fn exercise(request: AcpSessionRequest, policy: TestPolicy, script: Script) -> AgentHeard {
    let (client, agent) = Channel::duplex();
    let (fake, record, _signals) = ScriptedAgent::new(script);
    tokio::time::timeout(TEST_BUDGET, async {
        let (client, agent) =
            tokio::join!(run_on_channel(request, policy, client), fake.run(agent));
        client.unwrap();
        agent.unwrap();
    })
    .await
    .expect("ACP runtime/agent finished");
    let record: std::sync::MutexGuard<'_, Record> = record.lock().unwrap();
    AgentHeard {
        requests: record.requests.clone(),
        replies: record.replies.clone(),
    }
}

/// Claude's `ExitPlanMode` ask: approving it (`allow_once`) moves Claude
/// to `default`.
fn plan_exit() -> Vec<Step> {
    plan_exit_offering(vec![
        PermissionOption::new(
            "exit-plan-default",
            "Yes, manually approve edits",
            PermissionOptionKind::AllowOnce,
        ),
        PermissionOption::new("plan-no", "No", PermissionOptionKind::RejectOnce),
    ])
}

fn plan_exit_offering(options: Vec<PermissionOption>) -> Vec<Step> {
    vec![
        Step::Update {
            update: Box::new(SessionUpdate::ToolCall(
                ToolCall::new("plan-1", "Approve Plan").kind(ToolKind::SwitchMode),
            )),
        },
        Step::Permission {
            call: Box::new(ToolCallUpdate::new(
                "plan-1",
                ToolCallUpdateFields::new()
                    .kind(ToolKind::SwitchMode)
                    .raw_input(json!({"plan": "ship it"})),
            )),
            options,
        },
    ]
}

/// Claude's `AskUserQuestion` form, shaped as claude-agent-acp 0.114.0
/// sends it: one titled single select and its free-text companion.
fn ask_user_question() -> Step {
    Step::Extension {
        method: "elicitation/create".into(),
        params: json!({
            "mode": "form",
            "sessionId": "scripted-session",
            "toolCallId": "ask-1",
            "message": "Which color?",
            "requestedSchema": {
                "type": "object",
                "properties": {
                    "question_0": {
                        "type": "string",
                        "title": "Color",
                        "oneOf": [
                            {"const": "Red", "title": "Red"},
                            {"const": "Blue", "title": "Blue"}
                        ]
                    },
                    "question_0_custom": {
                        "type": "string",
                        "title": "Other",
                        "description": "Type your own answer (optional)."
                    }
                }
            }
        }),
    }
}

fn end(text: &str) -> Vec<Step> {
    vec![
        Step::Update {
            update: Box::new(SessionUpdate::AgentMessageChunk(ContentChunk::new(
                text.to_owned().into(),
            ))),
        },
        Step::Stop {
            reason: StopReason::EndTurn,
        },
    ]
}

/// The client capabilities `initialize` advertised.
fn capabilities(record: &AgentHeard) -> Value {
    record
        .requests
        .iter()
        .find(|request| request["method"] == "initialize")
        .map(|request| request["params"]["clientCapabilities"]["elicitation"].clone())
        .unwrap_or_default()
}

// Covers: in a run a person attends, `initialize` advertises forms; a plan
// exit the policy leaves to the person reaches them with its plan and the
// mode it leads to, and their approval selects the agent's `allow_once`,
// moves the policy to the mode the agent then switches to, so the switch
// keeps the run, and tells the person the agent left; a form reaches them
// as questions, and their answer goes back as the form's content.
// Owner: ACP driver (asks put to a person).
#[tokio::test]
async fn an_attended_run_puts_plan_exits_and_forms_to_the_person() {
    let dir = tempfile::tempdir().unwrap();
    let (person, heard) = approving_person();
    let mut request = request(dir.path(), None);
    request.overrides.person = Some(person);
    let mut policy = TestPolicy::new(dir.path());
    policy.decision = PermissionDecision::AskPerson(Asking::PlanExit {
        to: PermissionMode::Supervised,
    });
    policy.mode = Some("plan".into());
    policy.plan_exit_to = Some("default".into());
    let mut turn = plan_exit();
    turn.push(Step::Update {
        update: Box::new(SessionUpdate::CurrentModeUpdate(CurrentModeUpdate::new(
            "default",
        ))),
    });
    turn.push(ask_user_question());
    turn.extend(end("done"));
    let script = Script {
        modes: vec!["plan".into(), "default".into()],
        turns: vec![turn],
        ..Script::default()
    };

    let record = exercise(request, policy, script).await;
    let (status, _) = read_artifacts(dir.path());

    assert_eq!(
        (
            status.state,
            capabilities(&record),
            heard.lock().unwrap().clone(),
            record.replies,
        ),
        (
            RunState::Ok,
            json!({"form": {}}),
            vec![
                ("plan".to_owned(), "ship it -> supervised".to_owned()),
                ("left".to_owned(), "supervised".to_owned()),
                ("form".to_owned(), "question_0,question_0_custom".to_owned()),
            ],
            vec![
                json!({"method": "session/request_permission", "result": {
                    "outcome": {"outcome": "selected", "optionId": "exit-plan-default"}
                }}),
                json!({"method": "elicitation/create", "result": {
                    "action": "accept", "content": {"question_0": "Blue"}
                }}),
            ],
        )
    );
}

// Covers: in a run nobody attends, `initialize` advertises no forms, an
// ask the policy leaves to a person is rejected, and a form the agent
// sends anyway is cancelled rather than left waiting.
// Owner: ACP driver (asks put to a person).
#[tokio::test]
async fn an_unattended_run_fails_a_persons_asks_closed() {
    let dir = tempfile::tempdir().unwrap();
    let mut policy = TestPolicy::new(dir.path());
    policy.decision = PermissionDecision::AskPerson(Asking::Tool);
    let mut turn = plan_exit();
    turn.push(ask_user_question());
    turn.extend(end("done"));

    let record = exercise(request(dir.path(), None), policy, script_of(turn)).await;

    assert_eq!(
        (capabilities(&record), record.replies),
        (
            Value::Null,
            vec![
                json!({"method": "session/request_permission", "result": {
                    "outcome": {"outcome": "selected", "optionId": "plan-no"}
                }}),
                json!({"method": "elicitation/create", "result": {"action": "cancel"}}),
            ],
        )
    );
}

// Covers: a plan the person approves that the agent offers no `allow_once`
// for is rejected, and the person is not told the agent left plan mode.
// Owner: ACP driver (asks put to a person).
#[tokio::test]
async fn an_approved_plan_the_agent_cannot_take_keeps_the_run_in_plan() {
    let dir = tempfile::tempdir().unwrap();
    let (person, heard) = approving_person();
    let mut request = request(dir.path(), None);
    request.overrides.person = Some(person);
    let mut policy = TestPolicy::new(dir.path());
    policy.decision = PermissionDecision::AskPerson(Asking::PlanExit {
        to: PermissionMode::Supervised,
    });
    policy.mode = Some("plan".into());
    policy.plan_exit_to = Some("default".into());
    let mut turn = plan_exit_offering(vec![PermissionOption::new(
        "plan-no",
        "No",
        PermissionOptionKind::RejectOnce,
    )]);
    turn.extend(end("done"));
    let script = Script {
        modes: vec!["plan".into(), "default".into()],
        turns: vec![turn],
        ..Script::default()
    };

    let record = exercise(request, policy, script).await;

    assert_eq!(
        (heard.lock().unwrap().clone(), record.replies),
        (
            vec![("plan".to_owned(), "ship it -> supervised".to_owned())],
            vec![json!({"method": "session/request_permission", "result": {
                "outcome": {"outcome": "selected", "optionId": "plan-no"}
            }})],
        )
    );
}

fn script_of(turn: Vec<Step>) -> Script {
    Script {
        turns: vec![turn],
        ..Script::default()
    }
}

/// A v2 turn in which the agent asks to run its Write, as claude-agent-acp
/// 0.114.0 does in default mode, then asks a form.
fn v2_asking_script() -> Script {
    let write = v2::ToolCallUpdate::new("toolu_1")
        .name("Write".to_owned())
        .title("Write a.txt".to_owned())
        .kind(v2::ToolKind::Edit);
    let form = json!({
        "mode": "form",
        "sessionId": "scripted-session",
        "toolCallId": "toolu_2",
        "message": "Which color?",
        "requestedSchema": {
            "type": "object",
            "properties": {
                "question_0": {
                    "type": "string",
                    "title": "Color",
                    "oneOf": [{"const": "Red", "title": "Red"}, {"const": "Blue", "title": "Blue"}]
                },
                "question_0_custom": {"type": "string", "title": "Other"}
            }
        }
    });
    Script {
        v2: Some(V2Script {
            turns: vec![vec![
                V2Step::Running,
                V2Step::Update {
                    session: None,
                    update: Box::new(v2::SessionUpdate::ToolCallUpdate(write.clone())),
                },
                V2Step::Permission {
                    title: "Write a.txt".into(),
                    call: Some(Box::new(write)),
                },
                V2Step::Form {
                    request: Box::new(serde_json::from_value(form).unwrap()),
                },
                V2Step::Idle { stop_reason: None },
            ]],
            ..V2Script::default()
        }),
        ..Script::default()
    }
}

// Covers: on ACP v2 as on v1, a run a person attends advertises forms and
// puts the agent's tool ask and form to the person, answering as they do;
// a run nobody attends advertises none, rejects what its policy leaves to
// a person, and cancels a form the agent sends anyway.
// Owner: ACP v2 client (asks put to a person).
#[tokio::test]
async fn a_v2_run_puts_asks_to_the_person_who_attends_it() {
    let allowed = json!({"method": "session/request_permission", "result": {
        "outcome": {"outcome": "selected", "optionId": "allow"}
    }});
    let rejected = json!({"method": "session/request_permission", "result": {
        "outcome": {"outcome": "selected", "optionId": "reject"}
    }});
    let cases = [
        (
            true,
            json!({"form": {}}),
            vec![
                ("tool".to_owned(), "Write a.txt".to_owned()),
                ("form".to_owned(), "question_0,question_0_custom".to_owned()),
            ],
            vec![
                allowed,
                json!({"method": "elicitation/create", "result": {
                    "action": "accept", "content": {"question_0": "Blue"}
                }}),
            ],
        ),
        (
            false,
            Value::Null,
            vec![],
            vec![
                rejected,
                json!({"method": "elicitation/create", "result": {"action": "cancel"}}),
            ],
        ),
    ];
    for (attended, forms, expected_heard, replies) in cases {
        let dir = tempfile::tempdir().unwrap();
        let (person, heard) = approving_person();
        let mut request = request(dir.path(), None);
        request.overrides.person = attended.then_some(person);
        let mut policy = TestPolicy::new(dir.path());
        policy.protocol = AcpProtocol::V2;
        policy.decision = PermissionDecision::AskPerson(Asking::Tool);

        let record = exercise(request, policy, v2_asking_script()).await;
        let (status, _) = read_artifacts(dir.path());
        let advertised = record
            .requests
            .iter()
            .find(|request| request["method"] == "initialize")
            .map(|request| request["params"]["capabilities"]["elicitation"].clone())
            .unwrap_or_default();

        assert_eq!(
            (
                status.state,
                advertised,
                heard.lock().unwrap().clone(),
                record.replies
            ),
            (RunState::Ok, forms, expected_heard, replies),
            "attended: {attended}"
        );
    }
}