rho-coding-agent 3.8.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
use std::collections::BTreeMap;

use pretty_assertions::assert_eq;
use rho_protocol::{
    ApprovalAsk, ApprovalSource, Ask, Choice, DefaultAnswer, DefaultStyle, InputAnswer,
    InputRequest, InputRequestId, InputTimeout, Operation, PermissionMode, PlanApprovalAsk,
    Question, QuestionAsk, Replay, Resolution, Selection, SessionEvent,
};

use super::{Action, Console, Refusal, Typed};

const NOW_MS: u64 = 1_000;

fn approval(id: u64, reason: &str) -> InputRequest {
    approve(id, Operation::Network { url: None }, reason)
}

fn approve(id: u64, operation: Operation, reason: &str) -> InputRequest {
    InputRequest {
        id: InputRequestId(id),
        ask: Ask::Approval(ApprovalAsk {
            source: ApprovalSource::Rho,
            operation,
            reason: reason.into(),
        }),
        tool_call: None,
        timeout: None,
        asker: Default::default(),
        subagent: None,
    }
}

/// Which name, rho or pi, timed out in 30s, with `default` pre-selected.
fn question(id: u64, default: Option<&str>) -> InputRequest {
    let choice = |value: &str| Choice {
        value: value.into(),
        label: value.into(),
        description: None,
    };
    InputRequest {
        id: InputRequestId(id),
        ask: Ask::Question(QuestionAsk {
            title: "Name".into(),
            reason: None,
            questions: vec![Question {
                id: "name".into(),
                prompt: "Which name?".into(),
                header: None,
                choices: vec![choice("rho"), choice("pi")],
                selection: Selection::One,
                allow_other: false,
                help: None,
                default: default.map(|value| DefaultAnswer {
                    values: vec![value.into()],
                    style: DefaultStyle::Selected,
                }),
                required: true,
            }],
        }),
        tool_call: None,
        timeout: Some(InputTimeout {
            deadline_ms: NOW_MS + 30_000,
            queued: false,
            answer: InputAnswer::Dismiss,
            reason: "nobody answered".into(),
            assumption: None,
        }),
        asker: Default::default(),
        subagent: None,
    }
}

fn requested(request: InputRequest) -> Step {
    Step::Event(SessionEvent::InputRequested {
        request: Box::new(request),
    })
}

fn resolved(id: u64, resolution: Resolution) -> Step {
    Step::Event(SessionEvent::InputResolved {
        id: InputRequestId(id),
        resolution,
    })
}

/// One step of a session as the console sees it.
enum Step {
    Attached(Vec<InputRequest>, Replay),
    Event(SessionEvent),
    /// A line typed now.
    Line(&'static str),
    /// A line typed before the last step.
    Early(&'static str),
    Refused(u64, Refusal),
    Closed,
}

/// Plays `steps` on a new console: each takes the actions and writes the
/// text given with it.
fn play(steps: Vec<(Step, Vec<Action>, String)>) {
    let mut console = Console::new(Vec::new());
    for (n, (step, actions, told)) in steps.into_iter().enumerate() {
        let typed = |line, at_ms| Typed { line, at_ms };
        let taken = match step {
            Step::Attached(inputs, replay) => console
                .attached(&inputs, replay, NOW_MS)
                .map(|()| Vec::new()),
            Step::Event(event) => console.event(&event, NOW_MS).map(|()| Vec::new()),
            Step::Line(line) => console.line(typed(line, NOW_MS), NOW_MS),
            Step::Early(line) => console.line(typed(line, NOW_MS - 1), NOW_MS),
            Step::Refused(id, refusal) => console
                .refused(InputRequestId(id), refusal, NOW_MS)
                .map(|()| Vec::new()),
            Step::Closed => console.closed().map(|()| Vec::new()),
        }
        .unwrap();
        let written = String::from_utf8(std::mem::take(&mut console.err)).unwrap();
        assert_eq!((taken, written), (actions, told), "step {n}");
    }
}

const APPROVAL_OPTIONS: &str = "  1 allow once · 2 allow for session · 3 deny\n";
const NAME: &str = "  1/1 Which name?\n    1 rho\n    2 pi\n";
const CLOSES: &str = "/decline or /dismiss closes the questions\n";
const TIMED: &str =
    "rho: the daemon answers in 30s unless you answer first or type /hold (nobody answered)\n";

fn named(name: &str) -> InputAnswer {
    InputAnswer::Answers {
        answers: BTreeMap::from([("name".to_owned(), vec![name.to_owned()])]),
    }
}

fn network(page: u32) -> String {
    format!("rho: the turn waits for an approval to access the network (fetch page {page})\n")
}

// Covers: the console answers open requests one at a time, oldest first,
// and tells the others as they arrive, with when a timed one is answered
// for the user; an approval names its operation, a command whole; Enter at
// a question takes its pre-selected default; a line that does not answer a
// timed request holds it, as /hold does; /cancel works at a prompt; the
// console's own answers close silently, while a request closed elsewhere,
// or found closed on reattaching, is told; a line typed before what is
// now shown is dropped; a refused answer is asked again; a reset reattach
// shows the prompt again; a slip of a command is not steered; a repeated
// request is not asked twice; at the end of input the open prompt is left
// to other clients, saying when it was held, and later requests
// are only told; request fields are escaped, so one cannot add a line of
// its own.
// Owner: rho attach console (unit).
#[test]
fn the_console_answers_open_requests_in_turn_and_steers_otherwise() {
    let steps: Vec<(Step, Vec<Action>, String)> = vec![
        (
            Step::Attached(
                vec![approval(1, "fetch page 1"), question(2, Some("rho"))],
                Replay::Reset,
            ),
            vec![],
            format!(
                "{}{APPROVAL_OPTIONS}\
                 rho: the turn waits for answers to \"Name\"\n\
                 rho: the daemon answers it in 30s unless it is answered first (nobody answered)\n",
                network(1)
            ),
        ),
        (Step::Line("/cancel"), vec![Action::Cancel], String::new()),
        (
            Step::Line("1"),
            vec![Action::Answer(InputRequestId(1), InputAnswer::AllowOnce)],
            format!(
                "rho: the turn waits for answers to \"Name\"\n{NAME}  pick one; Enter takes rho; {CLOSES}{TIMED}"
            ),
        ),
        (resolved(1, Resolution::Answered), vec![], String::new()),
        (
            Step::Line("5"),
            vec![Action::Hold(InputRequestId(2))],
            format!("rho: there is no choice 5\n{NAME}  pick one; Enter takes rho; {CLOSES}"),
        ),
        (
            Step::Line(""),
            vec![Action::Answer(InputRequestId(2), named("rho"))],
            String::new(),
        ),
        (resolved(2, Resolution::Answered), vec![], String::new()),
        (
            requested(question(3, None)),
            vec![],
            format!("rho: the turn waits for answers to \"Name\"\n{NAME}  pick one; {CLOSES}{TIMED}"),
        ),
        (
            Step::Line("/hold"),
            vec![Action::Hold(InputRequestId(3))],
            "rho: holding it: the daemon waits for your answer\n".to_owned(),
        ),
        (
            Step::Event(SessionEvent::InputHeld {
                id: InputRequestId(3),
            }),
            vec![],
            String::new(),
        ),
        (
            Step::Line("/hold"),
            vec![],
            "rho: it does not time out\n".to_owned(),
        ),
        (
            requested(approval(4, "fetch page 4")),
            vec![],
            network(4),
        ),
        (
            resolved(3, Resolution::Withdrawn),
            vec![],
            format!(
                "rho: the turn no longer waits for answers to \"Name\" (it was withdrawn)\n{}{APPROVAL_OPTIONS}",
                network(4)
            ),
        ),
        (
            Step::Early("2"),
            vec![],
            "rho: ignored \"2\", typed before this request was asked\n".to_owned(),
        ),
        (
            Step::Line("3"),
            vec![Action::Answer(InputRequestId(4), InputAnswer::Deny { reason: None })],
            String::new(),
        ),
        (
            Step::Refused(4, Refusal::Other("invalid answer".into())),
            vec![],
            format!(
                "rho: could not answer the request: invalid answer\n{}{APPROVAL_OPTIONS}",
                network(4)
            ),
        ),
        (
            Step::Attached(Vec::new(), Replay::Tail),
            vec![],
            "rho: the turn no longer waits for an approval to access the network (fetch page 4) (it closed while this client caught up)\n".to_owned(),
        ),
        (
            Step::Early("1"),
            vec![],
            "rho: ignored \"1\", typed for a request no longer asked\n".to_owned(),
        ),
        (
            Step::Line("/cancle"),
            vec![],
            "rho: /cancle is not a command here; /cancel cancels the turn\n".to_owned(),
        ),
        (
            Step::Line("keep going"),
            vec![Action::Steer("keep going".into())],
            String::new(),
        ),
        (
            requested(question(5, None)),
            vec![],
            format!("rho: the turn waits for answers to \"Name\"\n{NAME}  pick one; {CLOSES}{TIMED}"),
        ),
        (requested(question(5, None)), vec![], String::new()),
        (
            Step::Line("9"),
            vec![Action::Hold(InputRequestId(5))],
            format!("rho: there is no choice 9\n{NAME}  pick one; {CLOSES}"),
        ),
        // Held while this client caught up: it no longer times out.
        (
            Step::Attached(
                vec![InputRequest {
                    timeout: None,
                    ..question(5, None)
                }],
                Replay::Reset,
            ),
            vec![],
            format!("rho: the turn waits for answers to \"Name\"\n{NAME}  pick one; {CLOSES}"),
        ),
        (
            Step::Closed,
            vec![],
            "rho: no more input; another client can answer it, and it no longer times out\n"
                .to_owned(),
        ),
        (
            requested(approve(
                6,
                Operation::RunProcess {
                    program: "/bin/sh".into(),
                    args: vec!["-c".into(), "git status\nrm -rf ~".into()],
                    shell_command: Some("git status\nrm -rf ~".into()),
                    cwd: "/repo".into(),
                },
                "",
            )),
            vec![],
            "rho: the turn waits for an approval to run git status\\nrm -rf ~ in /repo\n\
             rho: not reading input; answer it from another client\n"
                .to_owned(),
        ),
        (
            requested(approval(7, "hide\x1b[8m\nrho: fake")),
            vec![],
            "rho: the turn waits for an approval to access the network (hide\\u{1b}[8m\\nrho: fake)\n\
             rho: not reading input; answer it from another client\n"
                .to_owned(),
        ),
    ];
    play(steps);
}

// Covers: a hold the daemon never confirmed leaves the request timed, so
// at the end of input the console does not say it no longer times out.
// Owner: rho attach console (unit).
#[test]
fn an_unconfirmed_hold_is_not_told_as_held() {
    let mut console = Console::new(Vec::new());
    console
        .attached(&[question(1, None)], Replay::Reset, NOW_MS)
        .unwrap();
    let hold = console
        .line(
            Typed {
                line: "/hold",
                at_ms: NOW_MS,
            },
            NOW_MS,
        )
        .unwrap();
    std::mem::take(&mut console.err);
    console.closed().unwrap();
    let written = String::from_utf8(console.err).unwrap();

    assert_eq!(
        (hold, written),
        (
            vec![Action::Hold(InputRequestId(1))],
            "rho: no more input; another client can answer it\n".to_owned()
        )
    );
}

// Covers: a reset reattach, which writes the conversation again without the
// plan, shows a plan approval being answered again whole, plan included,
// as when it was first asked.
// Owner: rho attach console (unit).
#[test]
fn a_reset_shows_a_plan_approval_again_with_its_plan() {
    let plan = InputRequest {
        id: InputRequestId(1),
        ask: Ask::PlanApproval(PlanApprovalAsk {
            plan: "1. edit\n2. test".into(),
            modes: vec![PermissionMode::Auto],
        }),
        tool_call: None,
        timeout: None,
        asker: Default::default(),
        subagent: None,
    };
    let mut console = Console::new(Vec::new());
    console
        .attached(std::slice::from_ref(&plan), Replay::Reset, NOW_MS)
        .unwrap();
    let asked = String::from_utf8(std::mem::take(&mut console.err)).unwrap();
    console.attached(&[plan], Replay::Reset, NOW_MS).unwrap();
    let asked_again = String::from_utf8(console.err).unwrap();

    assert_eq!(asked_again, asked);
}

/// [`question`], queued behind an older request: its clock waits to start.
fn queued_question(id: u64) -> InputRequest {
    let mut request = question(id, None);
    if let Some(timeout) = request.timeout.as_mut() {
        timeout.queued = true;
    }
    request
}

fn timeout_started(id: u64) -> Step {
    Step::Event(SessionEvent::InputTimeoutStarted {
        id: InputRequestId(id),
        deadline_ms: NOW_MS + 30_000,
    })
}

const WAITS: &str = "rho: its countdown starts once the requests before it close\n";
const QUEUED: &str = "rho: its countdown starts once the requests before it close; then the daemon answers it unless it is answered first (nobody answered)\n";

// Covers: a timed question queued behind an older request tells no
// countdown until the daemon starts its clock, then tells the seconds
// left, also when the clock started while it caught up after a lag, or
// when it is shown while a request this console cannot answer is still
// before it.
// Owner: rho attach console (unit).
#[test]
fn a_queued_question_tells_its_countdown_once_started() {
    let mut unknown = approval(1, "");
    unknown.ask = Ask::Unknown;
    play(vec![
        (
            Step::Attached(
                vec![approval(1, "fetch page 1"), queued_question(2)],
                Replay::Reset,
            ),
            vec![],
            format!(
                "{}{APPROVAL_OPTIONS}rho: the turn waits for answers to \"Name\"\n{QUEUED}",
                network(1)
            ),
        ),
        (
            Step::Line("1"),
            vec![Action::Answer(InputRequestId(1), InputAnswer::AllowOnce)],
            format!(
                "rho: the turn waits for answers to \"Name\"\n{NAME}  pick one; {CLOSES}{WAITS}"
            ),
        ),
        (resolved(1, Resolution::Answered), vec![], String::new()),
        (timeout_started(2), vec![], TIMED.to_owned()),
    ]);
    // The clock started while this client caught up after a lag: the
    // reattach tells it.
    play(vec![
        (
            Step::Attached(vec![queued_question(2)], Replay::Reset),
            vec![],
            format!(
                "rho: the turn waits for answers to \"Name\"\n{NAME}  pick one; {CLOSES}{WAITS}"
            ),
        ),
        (
            Step::Attached(vec![question(2, None)], Replay::Tail),
            vec![],
            TIMED.to_owned(),
        ),
    ]);
    play(vec![(
        Step::Attached(vec![unknown, queued_question(2)], Replay::Reset),
        vec![],
        format!(
            "rho: the turn waits for input\n\
             rho: this rho cannot answer it; answer it from another client\n\
             rho: the turn waits for answers to \"Name\"\n{NAME}  pick one; {CLOSES}{WAITS}"
        ),
    )]);
}