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
//! The stdio bridge: the run's tools served to an agent that takes no MCP
//! server over its ACP connection, as agy (Antigravity's ACP server 1.5.21,
//! which advertises no `mcpCapabilities`) takes only stdio servers.
//!
//! The run declares a stdio server, [`super::SERVER_NAME`], on `session/new`
//! and on `session/resume`, whose command is rho itself, as
//! `rho __session-tools <endpoint>`; agy starts it as the session sets up.
//! rho goes by the path the process was started from, the one the daemon
//! watches for upgrades ([`relay_program`]), so the relay still starts once
//! an upgrade or rebuild replaced the binary the daemon runs.
//! That process only relays its stdio to the run's endpoint ([`relay`]),
//! where the run serves MCP with rmcp, from the same tools as over the
//! connection.
//!
//! Only the agent's own relay may connect:
//! - The endpoint is private to the user (see
//!   [`crate::daemon::LocalListener`]), at a fresh address for each run, and
//!   gone once the run's calls end.
//! - A connection must first present the run's token, 256 random bits the
//!   declaration hands the relay in its environment ([`TOKEN_ENV`]), as one
//!   line; the run closes any other at once.
//!
//! Calls run as the run's calls over the connection do: in the session, its
//! mode, approvals and workspace being the tools' own. What differs is the
//! envelope: no MCP call names the agent's tool call, so each claims the
//! agent's announcement of it (`announced`), and one that runs past agy's
//! limit on an MCP call is parked for [`AWAIT_TOOL`] (`parked`).

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

use agent_client_protocol::v1::schema::{EnvVariable, McpServerStdio, SessionUpdate};
use rmcp::{
    model::{
        CallToolRequestParams, CallToolResponse, CallToolResult, ListToolsResult,
        PaginatedRequestParams, ServerConfig, Tool,
    },
    service::RequestContext,
    ErrorData, RoleServer, ServerHandler, ServiceExt,
};
use tokio::{
    io::{AsyncBufReadExt, AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, BufReader},
    time::Instant,
};

pub(crate) use super::parked::AWAIT_TOOL;
use super::{
    announced::Announced,
    parked::{Parked, ANSWER_BY},
    ToolCalls, SERVER_NAME,
};
use crate::daemon::{LocalConnected, LocalListener};

/// The hidden subcommand that relays the agent's stdio to the run.
pub(crate) const RELAY_COMMAND: &str = "__session-tools";

/// The variable the declaration sets for the relay, holding the run's
/// token.
pub(crate) const TOKEN_ENV: &str = "RHO_SESSION_TOOLS_TOKEN";

/// Bytes of randomness in a run's token: 256 bits, sent as hex.
const TOKEN_BYTES: usize = 32;

/// The token's line: its hex digits and a newline. A connection gets no
/// further than this many bytes without one.
const TOKEN_FRAME_BYTES: usize = TOKEN_BYTES * 2 + 1;

/// How long a connection has to present the token. A tripwire, not a
/// wait anyone sees: the relay writes the token as its first bytes as soon
/// as it connects ([`connect`]), one short write to an endpoint on the same
/// machine, of the same user, so it lands at once. 10 s is room many times
/// over for a relay the host is slow to schedule; past it, the connection
/// is closed, so one that never speaks holds no task until the run ends.
const TOKEN_WAIT: Duration = Duration::from_secs(10);

/// What names the endpoint's directory or pipe.
const ENDPOINT_PREFIX: &str = "rho-tools";

/// One run's bridge: what its declaration says, and what its calls share.
/// The endpoint lives on the task that listens on it, which ends with the
/// run's calls, or as the bridge drops.
pub(super) struct Bridge {
    declaration: McpServerStdio,
    calls: Arc<BridgeCalls>,
    _listening: AbortOnDrop,
}

impl Bridge {
    /// Listens on a new private endpoint for the calls of `calls`'s run.
    /// `Err` says why it could not.
    pub(super) fn open(calls: ToolCalls) -> Result<Self, String> {
        let program = relay_program(
            crate::daemon::started_path(),
            std::env::consts::EXE_SUFFIX,
            std::env::current_exe(),
            Path::is_file,
        )?;
        let (listener, address) = LocalListener::bind_private(ENDPOINT_PREFIX)
            .map_err(|error| format!("could not listen on a private endpoint: {error}"))?;
        let address = address
            .into_string()
            .map_err(|address| format!("the endpoint {} is not UTF-8", address.display()))?;
        let token = crate::secrets::random_hex::<TOKEN_BYTES>();
        let declaration = declare(program, address, token.clone());
        let calls = Arc::new(BridgeCalls {
            calls,
            announced: Announced::default(),
            parked: Parked::default(),
        });
        let listening = tokio::spawn(listen(listener, token.into(), Arc::clone(&calls)));
        Ok(Self {
            declaration,
            calls,
            _listening: AbortOnDrop(listening),
        })
    }

    pub(super) fn declaration(&self) -> McpServerStdio {
        self.declaration.clone()
    }

    /// Whether the bridge serves `name` besides the run's tools.
    pub(super) fn serves(&self, name: &str) -> bool {
        name == AWAIT_TOOL
    }

    /// The agent's `update`, `tool` being the served tool it announces a
    /// call of, if any: an MCP call claims the announcement, and the
    /// agent's end of a call withdraws it (see [`Announced::hear`]).
    pub(super) fn heard(&self, update: &SessionUpdate, tool: Option<&str>) {
        self.calls.announced.hear(update, tool);
    }
}

/// The stdio server that runs `program` as the relay to the endpoint at
/// `address`, handing it `token`; [`relay_target`] reads them back.
fn declare(program: PathBuf, address: String, token: String) -> McpServerStdio {
    McpServerStdio::new(SERVER_NAME, program)
        .args(vec![RELAY_COMMAND.to_owned(), address])
        .env(vec![EnvVariable::new(TOKEN_ENV, token)])
}

/// The endpoint and token of a relay [`declare`] declared, as the relay
/// gets them from its arguments and environment; `None` for another
/// server. For an agent that connects in process (the scripted agent).
#[cfg(any(test, debug_assertions))]
pub(crate) fn relay_target(server: &McpServerStdio) -> Option<(&str, &str)> {
    let [command, address] = server.args.as_slice() else {
        return None;
    };
    let token = server.env.iter().find(|var| var.name == TOKEN_ENV)?;
    (command == RELAY_COMMAND).then_some((address.as_str(), token.value.as_str()))
}

/// The program the declaration runs as the relay, the first of these that
/// `is_file` finds a file at:
/// - rho by `started`, the path this process was started from
///   ([`crate::daemon::started_path`]), which an upgrade or rebuild writes
///   the new binary over;
/// - that path with the platform's executable `suffix`, which `argv[0]` may
///   leave out on Windows, as `.\rho daemon` does;
/// - `current`, the file the process runs ([`std::env::current_exe`]),
///   which on Linux reads `/…/rho (deleted)` once an upgrade replaced it.
///
/// `Err`, which the run reports, when none is.
fn relay_program(
    started: std::io::Result<PathBuf>,
    suffix: &str,
    current: std::io::Result<PathBuf>,
    is_file: impl Fn(&Path) -> bool,
) -> Result<PathBuf, String> {
    let mut tried = Vec::new();
    if let Ok(started) = &started {
        tried.push(started.clone());
        if !suffix.is_empty() {
            let mut suffixed = started.clone().into_os_string();
            suffixed.push(suffix);
            tried.push(PathBuf::from(suffixed));
        }
    }
    if let Ok(current) = current {
        if !tried.contains(&current) {
            tried.push(current);
        }
    }
    if let Some(program) = tried.iter().find(|path| is_file(path.as_path())) {
        return Ok(program.clone());
    }
    match (started, tried.is_empty()) {
        (Err(error), true) => Err(format!("could not find rho's own executable: {error}")),
        _ => {
            let tried: Vec<_> = tried
                .iter()
                .map(|path| path.display().to_string())
                .collect();
            Err(format!(
                "rho's executable is at none of {}",
                tried.join(", ")
            ))
        }
    }
}

/// Aborts the listening task as the bridge drops.
struct AbortOnDrop(tokio::task::JoinHandle<()>);

impl Drop for AbortOnDrop {
    fn drop(&mut self) {
        self.0.abort();
    }
}

/// Accepts connections on `listener` until the run's calls are over,
/// serving each that presents `token` the run's `calls`. The endpoint goes
/// with the listener, as this returns or is aborted.
async fn listen(mut listener: LocalListener, token: Arc<str>, calls: Arc<BridgeCalls>) {
    let over = calls.calls.over.clone();
    loop {
        let stream = tokio::select! {
            () = over.cancelled() => return,
            accepted = listener.accept() => match accepted {
                Ok(stream) => stream,
                Err(error) => {
                    tracing::warn!(%error, "rho's tools stopped taking the agent's connections");
                    return;
                }
            },
        };
        let (token, calls, over) = (Arc::clone(&token), Arc::clone(&calls), over.clone());
        tokio::spawn(async move {
            tokio::select! {
                () = over.cancelled() => {}
                () = serve(stream, &token, calls) => {}
            }
        });
    }
}

/// Serves MCP on `stream` once it presented `token`; closes it otherwise.
async fn serve<S>(stream: S, token: &str, calls: Arc<BridgeCalls>)
where
    S: AsyncRead + AsyncWrite + Send + 'static,
{
    let (read, write) = tokio::io::split(stream);
    let mut read = BufReader::new(read);
    let mut frame = Vec::with_capacity(TOKEN_FRAME_BYTES);
    let presented = tokio::time::timeout(
        TOKEN_WAIT,
        (&mut read)
            .take(TOKEN_FRAME_BYTES as u64)
            .read_until(b'\n', &mut frame),
    )
    .await;
    if !matches!(presented, Ok(Ok(_))) || !admits(&frame, token) {
        tracing::warn!(
            "refused a connection to rho's tools that did not present the run's token within \
             TOKEN_WAIT ({TOKEN_WAIT:?})"
        );
        return;
    }
    let server = BridgeServer { calls };
    match server.serve((read, write)).await {
        Ok(running) => {
            let _ = running.waiting().await;
        }
        Err(error) => tracing::debug!(%error, "the agent's MCP client left rho's tools"),
    }
}

/// Whether `frame` is `token`'s line, compared in constant time.
fn admits(frame: &[u8], token: &str) -> bool {
    frame
        .strip_suffix(b"\n")
        .is_some_and(|presented| crate::secrets::constant_time_eq(presented, token.as_bytes()))
}

/// What the bridge's connections share.
struct BridgeCalls {
    calls: ToolCalls,
    announced: Announced,
    parked: Parked,
}

impl BridgeCalls {
    /// The tools the bridge lists: the run's and [`AWAIT_TOOL`].
    fn list(&self) -> Vec<Tool> {
        let mut tools = self.calls.tools.list();
        tools.push(super::parked::await_tool());
        tools
    }

    /// The answer to one `tools/call` of `name` with `arguments`. The agent
    /// is blocked on it, `await` included, until its answer goes back, the
    /// call's result or that it is still running: a call parked past
    /// [`super::parked::CALL_WAIT`] runs on without blocking the agent (see
    /// [`ToolCalls::serve_blocking`]). The answer goes back by
    /// [`ANSWER_BY`] after the call arrived, readied or not, ahead of agy's
    /// cut-off.
    async fn call(
        &self,
        name: String,
        arguments: serde_json::Map<String, serde_json::Value>,
    ) -> Result<CallToolResult, ErrorData> {
        let deadline = Instant::now() + ANSWER_BY;
        self.calls
            .serve_blocking(Some(deadline), async {
                let key = self.announced.claim(&name, &arguments).await;
                if name == AWAIT_TOOL {
                    // The awaited call's card shows its wait; the agent's
                    // card for the `await` shows nothing.
                    if let Some(key) = key {
                        self.calls.hide(key);
                    }
                    return Ok(self.parked.wait(arguments).await);
                }
                let call = self
                    .calls
                    .start(name.clone(), arguments, key)
                    .map_err(|message| ErrorData::invalid_params(message, None))?;
                Ok::<_, ErrorData>(self.parked.run(&name, call).await)
            })
            .await
    }
}

/// The MCP server one connection talks to.
#[derive(Clone)]
struct BridgeServer {
    calls: Arc<BridgeCalls>,
}

impl ServerHandler for BridgeServer {
    fn get_info(&self) -> ServerConfig {
        super::server_config()
    }

    async fn list_tools(
        &self,
        _request: Option<PaginatedRequestParams>,
        _context: RequestContext<RoleServer>,
    ) -> Result<ListToolsResult, ErrorData> {
        Ok(ListToolsResult::with_all_items(self.calls.list()))
    }

    async fn call_tool(
        &self,
        request: CallToolRequestParams,
        _context: RequestContext<RoleServer>,
    ) -> Result<CallToolResponse, ErrorData> {
        let result = self
            .calls
            .call(
                request.name.into_owned(),
                request.arguments.unwrap_or_default(),
            )
            .await?;
        Ok(result.into())
    }
}

/// Connects to the run's endpoint at `address`, presenting `token`: what
/// the relay does before it relays.
pub(crate) async fn connect(address: &OsStr, token: &str) -> std::io::Result<LocalConnected> {
    let mut stream = crate::daemon::connect_local(address).await?;
    stream.write_all(format!("{token}\n").as_bytes()).await?;
    Ok(stream)
}

/// `rho __session-tools <address>`: relays this process's stdio, which
/// the agent speaks MCP on, to the run's endpoint at `address`, after the
/// run's `token`, which the declaration put in [`TOKEN_ENV`]. Ends when
/// either side closes.
pub(crate) async fn relay(address: &OsStr, token: &str) -> anyhow::Result<()> {
    let stream = connect(address, token).await.map_err(|error| {
        anyhow::anyhow!(
            "could not reach rho's tools at {}: {error}",
            address.display()
        )
    })?;
    let (mut from_run, mut to_run) = tokio::io::split(stream);
    let mut stdin = stdin_chunks();
    let mut stdout = tokio::io::stdout();
    let to_run = async {
        while let Some(chunk) = stdin.recv().await {
            to_run.write_all(&chunk?).await?;
        }
        to_run.shutdown().await
    };
    let from_run = async {
        tokio::io::copy(&mut from_run, &mut stdout).await?;
        stdout.flush().await
    };
    // Either side closing ends the relay: the agent stopped its server, or
    // the run ended.
    tokio::select! {
        sent = to_run => sent?,
        heard = from_run => heard?,
    }
    Ok(())
}

/// This process's stdin, read on a thread of its own, chunk by chunk, until
/// it ends. Not tokio's stdin, whose blocking read the runtime would wait
/// for as the relay returns because the run ended, while the agent keeps
/// the pipe open: the thread dies with the process instead.
fn stdin_chunks() -> tokio::sync::mpsc::Receiver<std::io::Result<Vec<u8>>> {
    use std::io::Read;
    // A few chunks in flight: the relay writes each on as it comes.
    let (chunks, received) = tokio::sync::mpsc::channel(4);
    std::thread::spawn(move || {
        let mut stdin = std::io::stdin().lock();
        let mut buffer = vec![0_u8; 64 * 1024];
        loop {
            let chunk = match stdin.read(&mut buffer) {
                Ok(0) => return,
                Ok(read) => Ok(buffer[..read].to_vec()),
                Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
                Err(error) => Err(error),
            };
            let failed = chunk.is_err();
            if chunks.blocking_send(chunk).is_err() || failed {
                return;
            }
        }
    });
    received
}

#[cfg(test)]
#[path = "bridge_tests.rs"]
mod tests;