rho-coding-agent 3.7.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
use std::{
    collections::BTreeMap,
    time::{Duration, UNIX_EPOCH},
};

use pretty_assertions::assert_eq;
use rho_protocol::{
    self as wire, ErrorCode, InputAnswer, InputRequestId, QuestionAnswer, Resolution,
};
use rho_sdk::{ApprovalDecision, HostInputRefusal, HostInputResponse, HostInputSource};
use tokio::sync::mpsc;

use super::{Asker, Inputs};
use crate::{
    app::{
        daemon_host::sessions::test_events::{
            approval, approval_withdrawn, elicitation, plan, question, question_id,
            question_with_fallback, question_withdrawn,
        },
        session_runtime::{ApprovalId, PlanApprovalId, SessionEvent, TurnControl},
    },
    permission::PermissionMode,
    tools::plan_exit::PlanExitDecision,
};

/// Opens the request `event` asks in `inputs`, returning its id and the
/// channel its answer reaches.
fn open(
    inputs: &mut Inputs,
    event: &SessionEvent,
) -> (InputRequestId, mpsc::UnboundedReceiver<TurnControl>) {
    let (control, answers) = mpsc::unbounded_channel();
    inputs.note(Asker::Turn, &control, event, UNIX_EPOCH);
    (opened(inputs).id, answers)
}

/// The request the last change opened, its only one.
fn opened(inputs: &mut Inputs) -> wire::InputRequest {
    match inputs.take_events().as_slice() {
        [wire::SessionEvent::InputRequested { request }] => (**request).clone(),
        _ => panic!("the event opens a request"),
    }
}

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

fn answers(pairs: &[(&str, &[&str])]) -> InputAnswer {
    InputAnswer::Answers {
        answers: pairs
            .iter()
            .map(|(question, values)| {
                (
                    (*question).to_owned(),
                    values.iter().map(|value| (*value).to_owned()).collect(),
                )
            })
            .collect::<BTreeMap<_, _>>(),
    }
}

/// What the turn got for an answer, or the error code the client did.
#[derive(Debug, PartialEq)]
enum Outcome {
    Turn(TurnControl),
    Refused(ErrorCode),
}

// Covers: each kind of request hands the turn the answer a client gave in
// the runtime's terms (a deny without a reason says the user denied it, a
// plan approval only into a mode it offers, answers only when they fit the
// questions), and refuses an answer meant for another kind, leaving the
// request open.
// Owner: daemon input requests.
#[test]
fn a_request_hands_the_turn_only_the_answers_it_takes() {
    let question_answered = HostInputResponse::new().answer("answer", ["yes"]);
    let cases = [
        (
            approval(0),
            InputAnswer::AllowOnce,
            Outcome::Turn(TurnControl::RespondApproval {
                id: ApprovalId::nth_for_tests(0),
                decision: ApprovalDecision::AllowOnce,
            }),
        ),
        (
            approval(0),
            InputAnswer::Deny { reason: None },
            Outcome::Turn(TurnControl::RespondApproval {
                id: ApprovalId::nth_for_tests(0),
                decision: ApprovalDecision::Deny {
                    reason: "denied by user".into(),
                },
            }),
        ),
        (
            approval(0),
            InputAnswer::KeepPlanning { feedback: None },
            Outcome::Refused(ErrorCode::InvalidParams),
        ),
        (
            plan(0),
            InputAnswer::ApprovePlan {
                mode: wire::PermissionMode::Auto,
                feedback: None,
            },
            Outcome::Turn(TurnControl::AnswerPlan {
                id: PlanApprovalId::nth_for_tests(0),
                answer: PlanExitDecision::approve(PermissionMode::Auto),
            }),
        ),
        (
            plan(0),
            InputAnswer::KeepPlanning {
                feedback: Some("smaller steps".into()),
            },
            Outcome::Turn(TurnControl::AnswerPlan {
                id: PlanApprovalId::nth_for_tests(0),
                answer: PlanExitDecision::keep_planning()
                    .with_feedback(Some("smaller steps".into())),
            }),
        ),
        (
            plan(0),
            InputAnswer::ApprovePlan {
                mode: wire::PermissionMode::Bypass,
                feedback: None,
            },
            Outcome::Refused(ErrorCode::InvalidParams),
        ),
        (
            plan(0),
            InputAnswer::AllowOnce,
            Outcome::Refused(ErrorCode::InvalidParams),
        ),
        (
            question("q"),
            answers(&[("answer", &["yes"])]),
            Outcome::Turn(TurnControl::AnswerQuestion {
                id: question_id("q"),
                answer: Ok(question_answered),
            }),
        ),
        (
            question("q"),
            InputAnswer::Decline,
            Outcome::Turn(TurnControl::AnswerQuestion {
                id: question_id("q"),
                answer: Err(HostInputRefusal::Declined),
            }),
        ),
        (
            question("q"),
            answers(&[("answer", &["no"])]),
            Outcome::Refused(ErrorCode::InvalidParams),
        ),
        (
            question("q"),
            answers(&[("other", &["yes"])]),
            Outcome::Refused(ErrorCode::InvalidParams),
        ),
        (
            question("q"),
            InputAnswer::AllowOnce,
            Outcome::Refused(ErrorCode::InvalidParams),
        ),
    ];
    for (index, (event, answer, expected)) in cases.into_iter().enumerate() {
        let mut inputs = Inputs::new(/*question_timeout*/ None);
        let (id, mut turn) = open(&mut inputs, &event);
        let refused = matches!(expected, Outcome::Refused(_));

        let outcome = match inputs.answer(id, answer.clone()) {
            Ok(()) => {
                inputs.send_answers();
                Outcome::Turn(turn.try_recv().expect("the turn got the answer"))
            }
            Err(error) => Outcome::Refused(error.error_code().expect("a known code")),
        };

        assert_eq!(outcome, expected, "case {index}: answered {answer:?}");
        // A refused answer leaves the request open; an accepted one tells
        // clients it was answered.
        let told = if refused {
            Vec::new()
        } else {
            vec![resolved(id, Resolution::Answered)]
        };
        assert_eq!(
            (inputs.waiting(), inputs.take_events()),
            (refused, told),
            "case {index}"
        );
    }
}

/// A subagent's asker: run `run-1`, writing session `child-1`.
fn subagent() -> Asker {
    Asker::Subagent(wire::SubagentRef::new(
        "run-1",
        Some(wire::SessionId::new("child-1")),
    ))
}

/// One answer a session gives through `answer_question`, and what it gets.
struct SessionAnswerRow {
    case: &'static str,
    asker: Asker,
    event: SessionEvent,
    answer: QuestionAnswer,
    /// What the asker's turn gets, or the code that refuses the answer.
    expected: Result<TurnControl, ErrorCode>,
}

// Covers: the path a session answers through takes only a question anyone
// but the user may answer: an approval, a plan approval, and an MCP
// server's elicitation (user-only), the turn's own or one a subagent
// forwards, are refused, stay open for a person, and reach no turn; a
// question hands its turn the answers as a session's and tells clients a
// session answered it.
// Owner: daemon input requests.
#[test]
fn only_a_question_takes_a_sessions_answer() {
    let yes = || QuestionAnswer::Answers {
        answers: [("answer".to_owned(), vec!["yes".to_owned()])].into(),
    };
    let rows = [
        // A person alone answers either kind of approval; both stay, since
        // each is its own request kind that a change could let through alone.
        SessionAnswerRow {
            case: "approval",
            asker: Asker::Turn,
            event: approval(0),
            answer: QuestionAnswer::Decline,
            expected: Err(ErrorCode::InvalidParams),
        },
        SessionAnswerRow {
            case: "plan approval",
            asker: Asker::Turn,
            event: plan(0),
            answer: yes(),
            expected: Err(ErrorCode::InvalidParams),
        },
        SessionAnswerRow {
            case: "elicitation",
            asker: Asker::Turn,
            event: elicitation("q"),
            answer: yes(),
            expected: Err(ErrorCode::InvalidParams),
        },
        SessionAnswerRow {
            case: "a subagent's elicitation",
            asker: subagent(),
            event: elicitation("q"),
            answer: QuestionAnswer::Decline,
            expected: Err(ErrorCode::InvalidParams),
        },
        SessionAnswerRow {
            case: "question",
            asker: Asker::Turn,
            event: question("q"),
            answer: yes(),
            expected: Ok(TurnControl::AnswerQuestion {
                id: question_id("q"),
                answer: Ok(HostInputResponse::new()
                    .answer("answer", ["yes"])
                    .with_source(HostInputSource::Session)),
            }),
        },
    ];
    for row in rows {
        let mut inputs = Inputs::new(/*question_timeout*/ None);
        let (control, mut turn) = mpsc::unbounded_channel();
        inputs.note(row.asker, &control, &row.event, UNIX_EPOCH);
        let id = opened(&mut inputs).id;

        let result = inputs
            .answer_question(id, row.answer)
            .map_err(|error| error.error_code());
        inputs.send_answers();

        let expected = match row.expected {
            Ok(delivered) => (
                Ok(()),
                Some(delivered),
                vec![resolved(id, Resolution::AnsweredBySession)],
                false,
            ),
            Err(code) => (Err(Some(code)), None, Vec::new(), true),
        };
        assert_eq!(
            (
                result,
                turn.try_recv().ok(),
                inputs.take_events(),
                inputs.open.contains_key(&id),
            ),
            expected,
            "{}",
            row.case
        );
    }
}

// Covers: a subagent's question is not the turn's: clients are told whose
// it is, down to the subagent's run and session, the turn's end leaves it
// open, and no turn waits on it, so the job does not wait for input.
// Owner: daemon input requests.
#[test]
fn a_subagents_question_outlives_the_turn() {
    let mut inputs = Inputs::new(/*question_timeout*/ None);
    let (turns, _turn) = open(&mut inputs, &approval(0));
    let (control, _answers) = mpsc::unbounded_channel();
    inputs.note(subagent(), &control, &question("q"), UNIX_EPOCH);
    let asked = opened(&mut inputs);
    let subagents = asked.id;

    inputs.withdraw_turn();

    assert_eq!(
        (
            asked.asker,
            asked.subagent,
            inputs.take_events(),
            inputs.waiting(),
            inputs.answer(subagents, InputAnswer::Decline).is_ok(),
        ),
        (
            wire::InputAsker::Subagent,
            Some(wire::SubagentRef::new(
                "run-1",
                Some(wire::SessionId::new("child-1"))
            )),
            vec![wire::SessionEvent::InputResolved {
                id: turns,
                resolution: Resolution::Withdrawn,
            }],
            false,
            true,
        )
    );
}

// Covers: the first answer takes the request, so a second client's answer,
// or one to a request the turn withdrew, is refused as not open and reaches
// no turn; the answer reaches its turn only once it is sent, after clients
// were told; a withdrawal closes only the request of the model turn that
// asked, and none an answer already closed; an answer to a model turn that
// ended without withdrawing its request is refused and tells clients the
// request was withdrawn; ids stay unique after requests close.
// Owner: daemon input requests.
#[test]
fn only_the_first_answer_to_an_open_request_wins() {
    let code = |error: rho_protocol::RpcError| error.error_code();
    let mut inputs = Inputs::new(/*question_timeout*/ None);
    let (approved, mut turn) = open(&mut inputs, &approval(0));
    let (asked, _asking) = open(&mut inputs, &question("q"));
    let (abandoned, ended) = open(&mut inputs, &approval(1));
    drop(ended);
    // The model turn that asked `asked` withdraws it; another model turn's
    // withdrawal of a request with the same runtime id closes nothing.
    let (other_turn, _) = mpsc::unbounded_channel();
    let (asking_turn, _) = mpsc::unbounded_channel();
    inputs.note(Asker::Turn, &asking_turn, &question("q"), UNIX_EPOCH);
    let reasked = opened(&mut inputs);

    let first = inputs
        .answer(approved, InputAnswer::AllowOnce)
        .map_err(code);
    let second = inputs
        .answer(approved, InputAnswer::Deny { reason: None })
        .map_err(code);
    inputs.note(Asker::Turn, &other_turn, &approval_withdrawn(0), UNIX_EPOCH);
    inputs.note(
        Asker::Turn,
        &other_turn,
        &question_withdrawn("q"),
        UNIX_EPOCH,
    );
    inputs.note(
        Asker::Turn,
        &asking_turn,
        &question_withdrawn("q"),
        UNIX_EPOCH,
    );
    let to_withdrawn = inputs
        .answer(reasked.id, InputAnswer::Decline)
        .map_err(code);
    let to_ended = inputs
        .answer(abandoned, InputAnswer::AllowOnce)
        .map_err(code);
    let before_sending = turn.try_recv().ok();
    inputs.send_answers();
    let delivered = [before_sending, turn.try_recv().ok(), turn.try_recv().ok()];

    assert_eq!(
        (
            first,
            second,
            to_withdrawn,
            to_ended,
            inputs.take_events(),
            delivered,
            inputs.waiting(),
            [approved, asked, abandoned, reasked.id],
        ),
        (
            Ok(()),
            Err(Some(ErrorCode::InputNotOpen)),
            Err(Some(ErrorCode::InputNotOpen)),
            Err(Some(ErrorCode::InputNotOpen)),
            vec![
                resolved(approved, Resolution::Answered),
                resolved(reasked.id, Resolution::Withdrawn),
                resolved(abandoned, Resolution::Withdrawn),
            ],
            [
                None,
                Some(TurnControl::RespondApproval {
                    id: ApprovalId::nth_for_tests(0),
                    decision: ApprovalDecision::AllowOnce,
                }),
                None,
            ],
            // `asked`, whose model turn withdrew nothing, is still open.
            true,
            [
                InputRequestId(0),
                InputRequestId(1),
                InputRequestId(2),
                InputRequestId(3)
            ],
        )
    );
}

/// A session's question timeout in these tests; every request opens at
/// `UNIX_EPOCH`, so one that times out has its deadline this far past it.
const QUESTION_TIMEOUT: Duration = Duration::from_secs(60);

// Covers: only a question whose agent offered fallback answers, in a
// session whose questions time out, gets a timeout: clients see when and
// with what the daemon answers it, and the agent's assumption only when it
// gave one, and the caller is handed the timeout to run.
// Owner: daemon input requests.
#[test]
fn only_a_question_with_fallback_answers_times_out() {
    let times_out = |reason: &str, assumption: Option<&str>| {
        (
            Some(wire::InputTimeout {
                deadline_ms: 60_000,
                answer: answers(&[("answer", &["yes"])]),
                reason: reason.into(),
                assumption: assumption.map(str::to_owned),
            }),
            vec![(InputRequestId(0), QUESTION_TIMEOUT)],
        )
    };
    let cases = [
        (
            "question with fallback answers and an assumption",
            Some(QUESTION_TIMEOUT),
            question_with_fallback("q", Some("safe default")),
            times_out("safe default", Some("safe default")),
        ),
        (
            "question with fallback answers and no assumption",
            Some(QUESTION_TIMEOUT),
            question_with_fallback("q", None),
            times_out("yes", None),
        ),
        (
            "question without",
            Some(QUESTION_TIMEOUT),
            question("q"),
            (None, Vec::new()),
        ),
        (
            "approval",
            Some(QUESTION_TIMEOUT),
            approval(0),
            (None, Vec::new()),
        ),
        (
            "questions do not time out",
            None,
            question_with_fallback("q", Some("safe default")),
            (None, Vec::new()),
        ),
    ];
    for (case, question_timeout, event, expected) in cases {
        let mut inputs = Inputs::new(question_timeout);
        let (control, _turn) = mpsc::unbounded_channel();
        inputs.note(Asker::Turn, &control, &event, UNIX_EPOCH);
        let request = opened(&mut inputs);

        assert_eq!(
            (request.timeout, inputs.take_timeouts()),
            expected,
            "{case}"
        );
    }
}

/// Something that happens to an open question with a timeout.
#[derive(Clone, Copy, Debug)]
enum Step {
    Answer,
    Hold,
    EndTurn,
    TimeOut,
}

/// What came of a question with a timeout after some steps.
#[derive(Debug, PartialEq)]
struct Played {
    /// The codes of the steps refused.
    refused: Vec<ErrorCode>,
    events: Vec<wire::SessionEvent>,
    turn: Option<TurnControl>,
    open: bool,
}

/// Opens the question `event` asks in a session whose questions time out,
/// plays `steps` on it, and reports what came of it.
fn play(event: &SessionEvent, steps: &[Step]) -> Played {
    let mut inputs = Inputs::new(Some(QUESTION_TIMEOUT));
    let (id, mut turn) = open(&mut inputs, event);
    let mut refused = Vec::new();
    for step in steps {
        let result = match step {
            Step::Answer => inputs.answer(id, InputAnswer::Decline),
            Step::Hold => inputs.hold(id),
            Step::EndTurn => {
                turn.close();
                Ok(())
            }
            Step::TimeOut => {
                inputs.time_out(id);
                Ok(())
            }
        };
        refused.extend(result.err().and_then(|error| error.error_code()));
    }
    inputs.send_answers();
    Played {
        refused,
        events: inputs.take_events(),
        turn: turn.try_recv().ok(),
        open: inputs.waiting(),
    }
}

// Covers: a question still open and not held when its timeout fires hands
// the turn its fallback answers, marked as the fallback, and tells clients
// it timed out; one answered or held first, or whose model turn ended,
// does not time out.
// Owner: daemon input requests.
#[test]
fn a_question_times_out_only_while_open_and_not_held() {
    let id = InputRequestId(0);
    let cases = [
        (
            "nobody answered",
            &[Step::TimeOut][..],
            vec![resolved(id, Resolution::TimedOut)],
            Some(TurnControl::AnswerQuestion {
                id: question_id("q"),
                answer: Ok(HostInputResponse::new()
                    .answer("answer", ["yes"])
                    .with_source(HostInputSource::TimeoutFallback)),
            }),
            false,
        ),
        (
            "answered first",
            &[Step::Answer, Step::TimeOut],
            vec![resolved(id, Resolution::Answered)],
            Some(TurnControl::AnswerQuestion {
                id: question_id("q"),
                answer: Err(HostInputRefusal::Declined),
            }),
            false,
        ),
        (
            "held first",
            &[Step::Hold, Step::TimeOut],
            vec![wire::SessionEvent::InputHeld { id }],
            None,
            true,
        ),
        (
            "model turn ended",
            &[Step::EndTurn, Step::TimeOut],
            vec![resolved(id, Resolution::Withdrawn)],
            None,
            false,
        ),
    ];
    for (case, steps, events, turn, open) in cases {
        let expected = Played {
            refused: Vec::new(),
            events,
            turn,
            open,
        };
        let timed = question_with_fallback("q", Some("safe"));
        assert_eq!(play(&timed, steps), expected, "{case}");
    }
}

// Covers: holding a question stops its timeout once and tells clients;
// holding it again, or one without a timeout, tells nobody; a closed
// question cannot be held.
// Owner: daemon input requests.
#[test]
fn holding_tells_clients_only_when_it_stops_a_timeout() {
    let id = InputRequestId(0);
    let held = wire::SessionEvent::InputHeld { id };
    let timed = question_with_fallback("q", Some("safe"));
    let cases = [
        (
            "held",
            &timed,
            &[Step::Hold][..],
            Vec::new(),
            vec![held.clone()],
        ),
        (
            "held twice",
            &timed,
            &[Step::Hold, Step::Hold],
            Vec::new(),
            vec![held],
        ),
        (
            "without a timeout",
            &question("q"),
            &[Step::Hold],
            Vec::new(),
            Vec::new(),
        ),
        (
            "held after it timed out",
            &timed,
            &[Step::TimeOut, Step::Hold],
            vec![ErrorCode::InputNotOpen],
            vec![resolved(id, Resolution::TimedOut)],
        ),
    ];
    for (case, event, steps, refused, events) in cases {
        let played = play(event, steps);
        assert_eq!((played.refused, played.events), (refused, events), "{case}");
    }
}