rho-coding-agent 3.11.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
//! The stdio bridge's own envelope: who may connect, and calls that outlast
//! one MCP call. Each test speaks to `serve` over an in-memory stream, as
//! the relay would over the endpoint.

use std::{
    path::{Path, PathBuf},
    sync::Arc,
    time::Duration,
};

use agent_client_protocol::v1::schema::ToolCallId;
use futures_util::future::BoxFuture;
use pretty_assertions::assert_eq;
use rho_tools::cancellation::RunCancellation;
use rmcp::{
    model::{CallToolRequestParams, CallToolResult, ContentBlock, Tool},
    service::RunningService,
    RoleClient, ServiceExt,
};
use serde_json::{json, Map, Value};
use tokio::{
    io::{AsyncReadExt, AsyncWriteExt, DuplexStream},
    sync::{mpsc, Notify},
};

use super::{relay_program, serve, Announced, BridgeCalls, Parked, ToolCalls};
use crate::{
    acp_runtime::agent_tools::{
        parked::{AGENT_CALL_LIMIT, ANSWER_BY, CALL_WAIT},
        AgentRequest, AgentToolCall, AgentTools,
    },
    cli_runtime::agent_event::AgentEvent,
};

const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";

/// One tool, `slow`, whose call ends once the test lets it, answering the
/// key its card is drawn under; it tells `requests` of each request of the
/// agent's and each answer readied, which it readies as `readies` says.
struct Slow {
    release: Arc<Notify>,
    requests: mpsc::UnboundedSender<Heard>,
    readies: Readies,
}

/// How [`Slow`] readies the answers to the agent's requests.
#[derive(Clone, Copy)]
enum Readies {
    AtOnce,
    /// Never, as a turn whose slot no run frees waits in line for good.
    Never,
}

/// What [`Slow`] hears of the agent's requests.
#[derive(Debug, PartialEq)]
enum Heard {
    /// A request is outstanding: the agent is blocked on it.
    Request,
    /// A request's answer is readied, to go back.
    Answer,
    /// A request's answer went back before it was readied.
    Overdue,
}

/// The notice `Slow` has the run show of an answer that went back
/// unreadied.
const OVERDUE_NOTICE: &str = "went back unreadied";

impl AgentTools for Slow {
    fn list(&self) -> Vec<Tool> {
        vec![Tool::new("slow", "Ends when let", Arc::new(Map::new()))]
    }

    fn call(&self, call: AgentToolCall) -> BoxFuture<'static, CallToolResult> {
        let release = Arc::clone(&self.release);
        let key = call.cards.key().to_string();
        Box::pin(async move {
            release.notified().await;
            CallToolResult::success(vec![ContentBlock::text(key)])
        })
    }

    fn request(&self) -> AgentRequest {
        let requests = self.requests.clone();
        let _ = requests.send(Heard::Request);
        let overdue = requests.clone();
        let readies = self.readies;
        AgentRequest::new(
            Box::pin(async move {
                match readies {
                    Readies::AtOnce => {}
                    Readies::Never => std::future::pending().await,
                }
                let _ = requests.send(Heard::Answer);
            }),
            Box::new(move || {
                let _ = overdue.send(Heard::Overdue);
                Some(OVERDUE_NOTICE.to_owned())
            }),
        )
    }
}

/// The calls of `Slow` the bridge serves, the events their cards draw, and
/// what `Slow` hears of the agent's requests.
type SlowBridge = (
    Arc<BridgeCalls>,
    mpsc::UnboundedReceiver<AgentEvent>,
    mpsc::UnboundedReceiver<Heard>,
);

/// The bridge's calls of `Slow`, which `release` lets end, readying its
/// answers as `readies` says.
fn bridge_calls(release: &Arc<Notify>, readies: Readies) -> SlowBridge {
    let (events, drawn) = mpsc::unbounded_channel();
    let (requests, heard) = mpsc::unbounded_channel();
    let calls = BridgeCalls {
        calls: ToolCalls {
            tools: Arc::new(Slow {
                release: Arc::clone(release),
                requests,
                readies,
            }),
            over: RunCancellation::new(),
            events,
        },
        announced: Announced::default(),
        parked: Parked::default(),
    };
    (Arc::new(calls), drawn, heard)
}

/// The bridge serving one connection, and the relay's end of it.
fn connection(calls: Arc<BridgeCalls>) -> (DuplexStream, tokio::task::JoinHandle<()>) {
    let (relay, bridge) = tokio::io::duplex(64 * 1024);
    let served = tokio::spawn(async move { serve(bridge, TOKEN, calls).await });
    (relay, served)
}

/// An MCP client on `relay`, once it presented the token.
async fn client(mut relay: DuplexStream) -> RunningService<RoleClient, ()> {
    relay
        .write_all(format!("{TOKEN}\n").as_bytes())
        .await
        .unwrap();
    ().serve(relay).await.unwrap()
}

// Covers: a connection is served only once it presents the run's token as
// its first line: one presenting another token, a prefix of it, or none
// before it closes is closed at once, unserved; the token opens MCP, whose
// listing is the run's tools and `await`. Kills: the token check dropped
// or loosened to a prefix (any local process of the user's could call the
// session's tools), `await` left unlisted (agy cannot wait on a parked
// call).
// Owner: stdio bridge (admission).
#[tokio::test]
async fn only_the_runs_token_opens_its_tools() {
    let release = Arc::new(Notify::new());
    let mut refused = Vec::new();
    for presented in [
        format!("{}\n", "f".repeat(64)),
        format!("{}\n", &TOKEN[..32]),
        String::new(),
    ] {
        let (calls, _drawn, _heard) = bridge_calls(&release, Readies::AtOnce);
        let (mut relay, served) = connection(calls);
        relay.write_all(presented.as_bytes()).await.unwrap();
        // A request a served connection answers, refused or not.
        relay.write_all(LIST_REQUEST.as_bytes()).await.unwrap();
        relay.shutdown().await.unwrap();
        // Unserved: the bridge drops the connection without a byte.
        let mut heard = Vec::new();
        relay.read_to_end(&mut heard).await.unwrap();
        served.await.unwrap();
        refused.push(heard);
    }
    let (calls, _drawn, _heard) = bridge_calls(&release, Readies::AtOnce);
    let (relay, _served) = connection(calls);
    let listed: Vec<String> = client(relay)
        .await
        .list_all_tools()
        .await
        .unwrap()
        .into_iter()
        .map(|tool| tool.name.into_owned())
        .collect();

    assert_eq!(
        (refused, listed),
        (
            vec![Vec::new(); 3],
            vec!["slow".to_owned(), "await".to_owned()]
        )
    );
}

/// A `tools/list` request as agy sends one, which a connection the bridge
/// served answers.
const LIST_REQUEST: &str = concat!(
    r#"{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{"_meta":{"#,
    r#""io.modelcontextprotocol/protocolVersion":"2026-07-28"}}}"#,
    "\n"
);

/// The text of `result`, and whether it is an error.
fn text_of(result: &CallToolResult) -> (String, bool) {
    let text = result
        .content
        .iter()
        .filter_map(|block| block.as_text().map(|text| text.text.clone()))
        .collect();
    (text, result.is_error == Some(true))
}

/// The parked call's id a still-running answer gives, in its structured
/// content.
fn parked_id(result: &CallToolResult) -> String {
    let id = result
        .structured_content
        .as_ref()
        .map(|content| &content["id"]);
    id.and_then(Value::as_str)
        .expect("a still-running answer names its id")
        .to_owned()
}

fn call(name: &str, arguments: Value) -> CallToolRequestParams {
    let Value::Object(arguments) = arguments else {
        unreachable!("arguments are an object");
    };
    CallToolRequestParams::new(name.to_owned()).with_arguments(arguments)
}

// Covers: a call still running when one MCP call has waited `CALL_WAIT`
// answers that it is still running, with an id, and runs on; `await` with
// the id answers the same while the call runs, then the call's result once
// it ends, the call's card drawn under the agent's announcement of it all
// along; an `await` draws no card of its own, only hides the agent's for
// it; an id awaited to its end is no longer parked. Time is paused, so the
// waits pass at once. Kills: the call cut off at the wait (the result lost
// or the call cancelled), the await drawing a card (two cards for one
// call), a parked call never forgotten, the call drawn under its own key.
// Owner: stdio bridge (calls past agy's MCP call limit).
#[tokio::test(start_paused = true)]
async fn a_call_past_one_mcp_calls_wait_is_awaited_to_its_end() {
    let release = Arc::new(Notify::new());
    let (calls, mut drawn, _heard) = bridge_calls(&release, Readies::AtOnce);
    for (tool, id) in [
        ("slow", "agent-slow"),
        ("await", "agent-await-1"),
        ("await", "agent-await-2"),
        ("await", "agent-await-3"),
    ] {
        calls
            .announced
            .announce(tool, ToolCallId::new(id), /*input*/ None);
    }
    let (relay, _served) = connection(Arc::clone(&calls));
    let client = client(relay).await;

    let started = tokio::time::Instant::now();
    let first = client.call_tool(call("slow", json!({}))).await.unwrap();
    // Paused time moves exactly to the wait's end.
    let waited = started.elapsed().as_secs();
    let id = parked_id(&first);
    let again = client
        .call_tool(call("await", json!({"id": id})))
        .await
        .unwrap();
    release.notify_one();
    let ended = client
        .call_tool(call("await", json!({"id": id})))
        .await
        .unwrap();
    let gone = client
        .call_tool(call("await", json!({"id": id})))
        .await
        .unwrap();
    let mut cards = Vec::new();
    while let Ok(event) = drawn.try_recv() {
        match event {
            AgentEvent::Served { call, .. } => cards.push((call.to_string(), false)),
            AgentEvent::ServedHidden(call) => cards.push((call.to_string(), true)),
            _ => {}
        }
    }

    assert_eq!(
        (
            waited,
            text_of(&first).1,
            parked_id(&again),
            text_of(&ended),
            text_of(&gone).1,
            cards,
        ),
        (
            CALL_WAIT.as_secs(),
            false,
            id,
            ("agent-slow".to_owned(), false),
            true,
            vec![
                ("agent-await-1".to_owned(), true),
                ("agent-await-2".to_owned(), true),
                ("agent-await-3".to_owned(), true),
            ],
        )
    );
}

/// What `Slow` heard of the agent's requests so far.
fn heard(requests: &mut mpsc::UnboundedReceiver<Heard>) -> Vec<Heard> {
    std::iter::from_fn(|| requests.try_recv().ok()).collect()
}

// Covers: agy counts as blocked on rho's tools exactly while one of its MCP
// calls over the bridge is outstanding: a call still running past
// `CALL_WAIT` readies its answer before agy hears that it is still
// running, and runs on, parked, no longer blocking agy; an `await` of it is
// a request of its own, outstanding until it readies its answer, the
// call's result, before agy hears it. Time is paused, so the waits pass at
// once. The daemon's tools lend a budgeted turn's slot while a request is
// outstanding and take it back as it readies (`budget_tests`).
// Kills: the request held across the call's own future rather than the MCP
// call (no answer readied before "still running": a parked call keeps
// agy's turn lending its slot while agy makes model requests); `await`
// served outside `ToolCalls::serve_blocking` (no request while agy waits
// in it, so the turn neither lends nor takes its slot back before the
// result); the answer dropped rather than readied (`request.answer_by` in
// `serve_blocking` replaced by a drop: no `Answer`, so the daemon never
// takes its slot back before agy goes on).
// Owner: stdio bridge (calls past agy's MCP call limit), the agent's
// requests (`AgentTools::request`).
#[tokio::test(start_paused = true)]
async fn agy_is_blocked_only_while_its_mcp_call_is_outstanding() {
    let release = Arc::new(Notify::new());
    let (calls, _drawn, mut requests) = bridge_calls(&release, Readies::AtOnce);
    for (tool, id) in [("slow", "agent-slow"), ("await", "agent-await")] {
        calls
            .announced
            .announce(tool, ToolCallId::new(id), /*input*/ None);
    }
    let (relay, _served) = connection(Arc::clone(&calls));
    let client = client(relay).await;

    let first = client.call_tool(call("slow", json!({}))).await.unwrap();
    let before_still_running = heard(&mut requests);
    let id = parked_id(&first);
    let awaiting = client.call_tool(call("await", json!({"id": id})));
    tokio::pin!(awaiting);
    // The call runs on until let, so the `await` waits in it: its request
    // comes first, unless it is none.
    let awaited = tokio::select! {
        biased;
        heard = requests.recv() => heard,
        _ = &mut awaiting => None,
    };
    release.notify_one();
    let ended = awaiting.await.unwrap();
    let before_the_result = heard(&mut requests);

    assert_eq!(
        (
            before_still_running,
            awaited,
            text_of(&ended),
            before_the_result
        ),
        (
            vec![Heard::Request, Heard::Answer],
            Some(Heard::Request),
            ("agent-slow".to_owned(), false),
            vec![Heard::Answer],
        )
    );
}

// Covers: an answer the tools never ready still goes back to agy, by
// `ANSWER_BY` after its MCP call arrived, short of agy's cut-off: the tools
// hear it went back unreadied, and the run shows their notice of it. Time
// is paused, so the wait passes at once; the call's answer must come within
// agy's cut-off.
// Kills: no deadline race (`serve_blocking`'s deadline ignored, or `None`
// passed from the bridge: the answer waits on readying for good, past agy's
// cut-off, where agy loses it); the deadline measured from the call's end
// rather than its arrival (an answer past `ANSWER_BY`); the notice dropped
// (nothing shows the turn ran over its budget).
// Owner: stdio bridge (answers within agy's MCP call limit), the agent's
// requests (`AgentRequest::answer_by`).
#[tokio::test(start_paused = true)]
async fn an_answer_goes_back_unreadied_before_agys_cut_off() {
    let release = Arc::new(Notify::new());
    let (calls, mut drawn, mut requests) = bridge_calls(&release, Readies::Never);
    calls
        .announced
        .announce("slow", ToolCallId::new("agent-slow"), /*input*/ None);
    let (relay, _served) = connection(Arc::clone(&calls));
    let client = client(relay).await;

    // The call itself ends 10 s in; readying its answer never does.
    let started = tokio::time::Instant::now();
    let releasing = Arc::clone(&release);
    tokio::spawn(async move {
        tokio::time::sleep(Duration::from_secs(10)).await;
        releasing.notify_one();
    });
    let answered =
        tokio::time::timeout(AGENT_CALL_LIMIT, client.call_tool(call("slow", json!({}))))
            .await
            .map(|answer| (text_of(&answer.unwrap()), started.elapsed().as_secs()));
    let notices: Vec<String> = std::iter::from_fn(|| drawn.try_recv().ok())
        .filter_map(|event| match event {
            AgentEvent::Notice(notice) => Some(notice),
            _ => None,
        })
        .collect();

    assert_eq!(
        (answered, heard(&mut requests), notices),
        (
            Ok((("agent-slow".to_owned(), false), ANSWER_BY.as_secs())),
            vec![Heard::Request, Heard::Overdue],
            vec![OVERDUE_NOTICE.to_owned()],
        )
    );
}

// Covers: the relay the declaration runs is rho by the path the process
// was started from while a program is there; else that path with the
// platform's executable suffix, as a Windows `argv[0]` typed without
// `.exe` (`.\rho daemon`) needs; else the file the process runs; with none
// a file, as once an upgrade unlinked the running file (`/…/rho
// (deleted)`) and nothing is at the started path, or with no path at all,
// an `Err` the run reports, so agy is never declared a server it cannot
// start. Pure over the paths and which are files. Kills: the existence
// check dropped (agy fails to start the server, and the turn never says
// why), the suffixed path not tried (a Windows daemon started as `.\rho`
// serves agy no tools), the running file not tried, the started path
// tried after the running file (an upgrade's new binary passed over for
// the old). That the path is `argv[0]`'s is `daemon::started_path`'s,
// which the daemon's own upgrade watch shares.
// Owner: stdio bridge (relay program).
#[test]
fn the_relay_is_rho_by_the_path_it_was_started_from() {
    let started = || Ok(PathBuf::from("/opt/rho"));
    let running = || Ok(PathBuf::from("/nix/store/rho"));
    // Its name, the paths, which of them are files, and the program.
    type Case = (
        &'static str,
        std::io::Result<PathBuf>,
        std::io::Result<PathBuf>,
        &'static [&'static str],
        Result<PathBuf, String>,
    );
    let cases: [Case; 5] = [
        (
            "the started path is a file",
            started(),
            running(),
            &["/opt/rho", "/opt/rho.exe", "/nix/store/rho"],
            Ok(PathBuf::from("/opt/rho")),
        ),
        (
            "started without its suffix",
            started(),
            running(),
            &["/opt/rho.exe", "/nix/store/rho"],
            Ok(PathBuf::from("/opt/rho.exe")),
        ),
        (
            "only the running file",
            started(),
            running(),
            &["/nix/store/rho"],
            Ok(PathBuf::from("/nix/store/rho")),
        ),
        (
            "none is a file",
            started(),
            running(),
            &[],
            Err("rho's executable is at none of /opt/rho, /opt/rho.exe, /nix/store/rho".to_owned()),
        ),
        (
            "no path at all",
            Err(std::io::Error::other("no argv[0]")),
            Err(std::io::Error::other("no current_exe")),
            &[],
            Err("could not find rho's own executable: no argv[0]".to_owned()),
        ),
    ];
    for (name, started, current, files, expected) in cases {
        let is_file = |path: &Path| files.iter().any(|file| path == Path::new(file));
        let chosen = relay_program(started, ".exe", current, is_file);

        assert_eq!(chosen, expected, "{name}");
    }
}