rho-coding-agent 3.13.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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
//! WebSocket ↔ local daemon NDJSON relay for `rho daemon serve --http`.
//!
//! Wire contract over WebSocket:
//! - Every WebSocket **text frame** carries one complete JSON-RPC 2.0 object
//!   (no trailing newline required; compact JSON emitted toward the client).
//! - Maximum message/frame size matches [`rho_protocol::MAX_LINE_BYTES`]
//!   (16 MiB); a larger message closes with `Size` (1009).
//! - Binary frames from the client are refused with Close code
//!   `Unsupported` (1003).
//! - Once the daemon answers a `rho/hello` naming a codec, which it does only
//!   for a hello that offered one, everything it sends after that answer
//!   reaches the client as
//!   **binary frames**: its compressed stream, split wherever a read ends.
//!   The client joins the payloads back into the stream. The daemon keeps
//!   its cap on compressed connections and its separate frames for
//!   messages that may carry secrets; the bridge never decodes the stream.
//! - A single incoming text frame is compacted to a single line before reaching
//!   the local daemon socket so pretty-printed JSON works cleanly and malformed
//!   input containing raw newlines can never smuggle a second JSON-RPC line.
//! - For the protocol methods that accept a `ClientEnvironment`, the bridge
//!   overlays the client's variables on top of the server host's environment
//!   (captured when the server starts), so remote clients on another OS can
//!   send `{}` or omit `environment` and still get the host's `PATH`/`HOME`.
//!
//! Closing has one owner: the relay decides the close frame once, after the
//! daemon has answered what it already read when that matters, and the writer
//! sends it last.

use std::{
    borrow::Cow,
    collections::VecDeque,
    future::Future,
    io,
    pin::Pin,
    sync::{Mutex, PoisonError},
    task::{Context, Poll},
    time::Duration,
};

use bytes::{BufMut, BytesMut};
use futures_util::{
    stream::{SplitSink, SplitStream},
    SinkExt, StreamExt,
};
use rho_protocol::{
    methods::{
        AUTH_CHOOSE_STORE, AUTH_KEY, AUTH_LIST, AUTH_LOGIN, AUTH_LOGOUT, HELLO, HOOKS_LIST,
        MCP_LIST, MCP_PROBE, MODEL_LIST, MODEL_REFRESH, PLUGINS_INSTALL, PLUGINS_LIST,
        PLUGINS_SET_ENABLED, PLUGINS_UPDATE, RUNTIME_LIST, SESSION_ATTACH, SESSION_FORK,
        SESSION_NEW, SESSION_PROMPT,
    },
    FrameError, Message, MessageReader, RequestId, Response, MAX_LINE_BYTES,
};
use serde_json::{Map, Value};
use tokio::{
    io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, ReadBuf},
    sync::mpsc,
    time::{Instant, Sleep},
};
use tokio_tungstenite::{
    tungstenite::{
        protocol::{
            frame::{coding::CloseCode, CloseFrame},
            Role, WebSocketConfig,
        },
        Error as WsError, Message as WsMessage,
    },
    WebSocketStream,
};

/// Frames queued toward one WebSocket client before the bridge stops reading
/// the daemon, so a slow client slows its own daemon connection instead of
/// growing bridge memory.
//
// Backpressure, not buffering: the daemon's connection writer queues its own
// output, so this only smooths bursts. 16 frames bound one stalled client at
// 16 × `MAX_LINE_BYTES` in the worst case, where 128 allowed 2 GiB.
const OUTGOING_QUEUE: usize = 16;

/// Most bytes of the daemon's compressed stream one binary frame carries.
//
// A read returns what the daemon flushed, one message or a few, so most
// frames are far smaller. 64 KiB bounds a stalled client's queue at
// 16 × 64 KiB = 1 MiB, where text frames allow 16 × `MAX_LINE_BYTES`, and
// keeps the 2–10 byte frame header under 0.02% of a full frame.
const STREAM_FRAME_BYTES: usize = 64 * 1024;

/// Keepalive ping interval, so reverse proxies and tunnels do not drop idle
/// attached connections.
//
// Half the 60 s idle timeout common proxies default to (nginx
// `proxy_read_timeout`, AWS ALB `idle_timeout`).
const PING_INTERVAL: Duration = Duration::from_secs(30);

/// How long the bridge waits to hear from the client, before treating the
/// connection as dead: any byte it sends (part of a frame, or the pong to a
/// keepalive ping), or room it makes by taking what the bridge sends it.
//
// Silence on a live, lossy link is TCP's retransmission backoff: a pong
// lost k times in a row lands about 2^k - 1 RTOs late (RTO about 1 s at a
// 760 ms RTT). Measured on plane-geo, 2026-12-03 (netem, 760 ms RTT, one
// flow per network namespace, a ping every 30 s and its echo, 60 min):
// the longest silence was 34.0 s over 4 flows at `loss 3.1%`, and 91.6 s
// over 8 at `loss gemodel 0.8% 25% 100% 0%` (one pong 62.3 s late, 6
// losses). 300 s covers 8 losses in a row (about 255 s) after a 30 s ping
// gap; past that, the client should reconnect.
const IDLE_TIMEOUT: Duration = Duration::from_secs(300);

/// Protocol methods whose `params` include `environment: ClientEnvironment`.
/// A test holds this to the protocol schema.
const ENVIRONMENT_METHODS: [&str; 19] = [
    SESSION_NEW,
    SESSION_FORK,
    SESSION_PROMPT,
    SESSION_ATTACH,
    AUTH_LIST,
    AUTH_KEY,
    AUTH_LOGOUT,
    AUTH_LOGIN,
    AUTH_CHOOSE_STORE,
    MODEL_LIST,
    MODEL_REFRESH,
    RUNTIME_LIST,
    MCP_LIST,
    MCP_PROBE,
    HOOKS_LIST,
    PLUGINS_LIST,
    PLUGINS_INSTALL,
    PLUGINS_UPDATE,
    PLUGINS_SET_ENABLED,
];

/// WebSocket configuration sized to match `rho-protocol`'s 16 MiB message cap.
fn websocket_config() -> WebSocketConfig {
    WebSocketConfig::default()
        .max_message_size(Some(MAX_LINE_BYTES))
        .max_frame_size(Some(MAX_LINE_BYTES))
}

/// Relays one authenticated WebSocket connection, upgraded on `socket`, to
/// `daemon` until either side closes, the client falls silent for
/// [`IDLE_TIMEOUT`], `draining` resolves, or `cut_off` does. Draining stops
/// reading the client, delivers every answer the daemon still sends for
/// requests it already read, then closes with `Away` so the client
/// reconnects. `cut_off` resolves with a close, as when the connection's
/// token was revoked: relaying stops at once and the client gets that
/// close.
pub(super) async fn relay_websocket<S, D>(
    socket: S,
    daemon: D,
    relayed: &Relayed<'_>,
    draining: impl Future<Output = ()>,
    cut_off: impl Future<Output = CloseFrame>,
) where
    S: AsyncRead + AsyncWrite + Unpin,
    D: AsyncRead + AsyncWrite + Unpin,
{
    let ws = WebSocketStream::from_raw_socket(
        ClientSocket::new(socket),
        Role::Server,
        Some(websocket_config()),
    )
    .await;
    let (ws_sink, ws_stream) = ws.split();
    let (daemon_read, daemon_write) = tokio::io::split(daemon);
    let (frames, outgoing) = mpsc::channel::<WsMessage>(OUTGOING_QUEUE);
    let hello = PendingHellos::default();
    let hello = &hello;
    let relay = async move {
        let outbound = daemon_to_client(daemon_read, frames.clone(), hello);
        tokio::pin!(outbound);
        let inbound = client_to_daemon(ws_stream, daemon_write, relayed, hello, draining, cut_off);
        let first = tokio::select! {
            ended = inbound => First::Client(ended),
            close = &mut outbound => First::Daemon(close),
        };
        let close = match first {
            First::Client(Inbound::ClientGone) => None,
            First::Client(Inbound::Refused(close)) => Some(close),
            First::Client(Inbound::Draining) => {
                (&mut outbound).await;
                Some(close_frame(CloseCode::Away, "server going away".to_owned()))
            }
            First::Client(Inbound::DaemonGone) => Some(outbound.await),
            First::Daemon(close) => Some(close),
        };
        if let Some(close) = close {
            let _ = frames.send(WsMessage::Close(Some(close))).await;
        }
    };
    tokio::join!(write_frames(ws_sink, outgoing), relay);
}

/// Which direction of the relay ended first.
enum First {
    Client(Inbound),
    Daemon(CloseFrame),
}

/// Why the client-to-daemon direction ended.
enum Inbound {
    /// The client closed or vanished; nothing more can reach it.
    ClientGone,
    /// Close at once with this frame: the client broke the wire contract, or
    /// the connection was cut off, as when its token was revoked.
    Refused(CloseFrame),
    /// The server is draining; deliver the daemon's remaining answers first.
    Draining,
    /// The daemon stopped accepting requests; its side decides the close.
    DaemonGone,
}

/// Sends every queued frame, plus keepalive pings, until the queue closes or
/// the client stops accepting frames. Owning `outgoing` means returning
/// early closes the queue, which stops the daemon-to-client direction.
async fn write_frames<S>(
    mut sink: SplitSink<WebSocketStream<S>, WsMessage>,
    mut outgoing: mpsc::Receiver<WsMessage>,
) where
    S: AsyncRead + AsyncWrite + Unpin,
{
    let mut ping = tokio::time::interval_at(Instant::now() + PING_INTERVAL, PING_INTERVAL);
    ping.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
    loop {
        let message = tokio::select! {
            message = outgoing.recv() => match message {
                Some(message) => message,
                None => break,
            },
            _ = ping.tick() => WsMessage::Ping(Default::default()),
        };
        if sink.send(message).await.is_err() {
            return;
        }
    }
    let _ = sink.close().await;
}

/// Which daemon output the relay is in, as far as the `rho/hello`s it
/// forwarded decide it. Both relay directions run in one task, so the lock
/// never waits; it is there for the relay to be `Send`.
#[derive(Default)]
struct PendingHellos(Mutex<DaemonOutput>);

enum DaemonOutput {
    /// Lines, with the ids of the hellos the daemon has not answered yet,
    /// oldest first, as it answers them. An answer naming a codec
    /// switches what follows to the daemon's compressed stream; the daemon
    /// names one only for a hello that offered it.
    Lines(VecDeque<RequestId>),
    /// The compressed stream, which no later hello's answer changes.
    Compressed,
}

impl Default for DaemonOutput {
    fn default() -> Self {
        Self::Lines(VecDeque::new())
    }
}

impl PendingHellos {
    fn forwarded(&self, id: RequestId) {
        match &mut *self.lock() {
            DaemonOutput::Lines(pending) => pending.push_back(id),
            DaemonOutput::Compressed => {}
        }
    }

    /// Whether the daemon's `line` answers the oldest pending hello naming
    /// a codec. Parses a line only while a hello is pending.
    fn switched_by(&self, line: &[u8]) -> bool {
        let mut output = self.lock();
        let DaemonOutput::Lines(pending) = &mut *output else {
            return false;
        };
        let Some(oldest) = pending.front() else {
            return false;
        };
        let Ok(Message::Response(Response {
            id: Some(id),
            outcome,
        })) = Message::parse(line)
        else {
            return false;
        };
        if id != *oldest {
            return false;
        }
        pending.pop_front();
        let switched = outcome.is_ok_and(|result| result.get("compression").is_some());
        if switched {
            *output = DaemonOutput::Compressed;
        }
        switched
    }

    fn lock(&self) -> std::sync::MutexGuard<'_, DaemonOutput> {
        self.0.lock().unwrap_or_else(PoisonError::into_inner)
    }
}

/// Forwards client text frames to the daemon, one NDJSON line each, until
/// the client stops, breaks the wire contract, falls silent, `draining`
/// resolves, or `cut_off` does. Shuts the daemon write half on the way out,
/// so the daemon answers what it already read and then closes its side.
async fn client_to_daemon<S, W>(
    mut stream: SplitStream<WebSocketStream<S>>,
    mut daemon: W,
    relayed: &Relayed<'_>,
    hello: &PendingHellos,
    draining: impl Future<Output = ()>,
    cut_off: impl Future<Output = CloseFrame>,
) -> Inbound
where
    S: AsyncRead + AsyncWrite + Unpin,
    W: AsyncWrite + Unpin,
{
    tokio::pin!(draining);
    tokio::pin!(cut_off);
    let ended = loop {
        let next = tokio::select! {
            biased;
            close = &mut cut_off => break Inbound::Refused(close),
            () = &mut draining => break Inbound::Draining,
            next = stream.next() => next,
        };
        let message = match next {
            None => break Inbound::ClientGone,
            Some(Err(WsError::Capacity(error))) => {
                tracing::debug!(%error, "WebSocket client sent an oversized message");
                break Inbound::Refused(too_large("message"));
            }
            // Also how a silent client ends: its socket fails the read.
            Some(Err(error)) => {
                tracing::debug!(%error, "WebSocket read failed");
                break Inbound::ClientGone;
            }
            Some(Ok(message)) => message,
        };
        match message {
            WsMessage::Text(text) => match prepare_daemon_line(text.as_str(), relayed) {
                Ok(line) => {
                    // Before the write: the daemon's answer may be read
                    // while the write still waits.
                    if let Some(id) = line.hello {
                        hello.forwarded(id);
                    }
                    let bytes = &line.bytes;
                    if daemon.write_all(bytes).await.is_err() || daemon.flush().await.is_err() {
                        break Inbound::DaemonGone;
                    }
                }
                Err(TooLarge { bytes }) => {
                    break Inbound::Refused(too_large(&format!("message of {bytes} bytes")));
                }
            },
            WsMessage::Binary(_) => {
                break Inbound::Refused(close_frame(
                    CloseCode::Unsupported,
                    "rho-protocol requires UTF-8 JSON text frames".to_owned(),
                ));
            }
            WsMessage::Close(_) => break Inbound::ClientGone,
            // tungstenite answers pings itself; `ClientSocket` saw the bytes.
            WsMessage::Ping(_) | WsMessage::Pong(_) | WsMessage::Frame(_) => {}
        }
    };
    let _ = daemon.shutdown().await;
    ended
}

/// The client's socket, which fails a read once the client has been silent
/// for [`IDLE_TIMEOUT`]. Bytes count rather than frames: on a slow uplink
/// one large frame takes longer than that to arrive whole, and a client
/// mid-frame can send no pong. So does a write that waited for room, since
/// only the client taking bytes makes room: on a slow downlink the bridge
/// may send one large frame for longer than that, and a client mid-frame
/// gets no ping to answer. A write that never waits proves nothing; pings
/// to a dead client fit in the kernel's buffer.
struct ClientSocket<S> {
    socket: S,
    silence: Pin<Box<Sleep>>,
    /// The last write waited for room.
    write_waited: bool,
}

impl<S> ClientSocket<S> {
    fn new(socket: S) -> Self {
        Self {
            socket,
            silence: Box::pin(tokio::time::sleep(IDLE_TIMEOUT)),
            write_waited: false,
        }
    }

    fn heard(&mut self) {
        self.silence.as_mut().reset(Instant::now() + IDLE_TIMEOUT);
    }

    fn wrote(&mut self, written: &Poll<io::Result<usize>>) {
        match written {
            Poll::Pending => self.write_waited = true,
            Poll::Ready(Ok(bytes)) if *bytes > 0 && self.write_waited => {
                self.write_waited = false;
                self.heard();
            }
            Poll::Ready(_) => self.write_waited = false,
        }
    }
}

impl<S: AsyncRead + Unpin> AsyncRead for ClientSocket<S> {
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<io::Result<()>> {
        let this = self.get_mut();
        let before = buf.filled().len();
        let read = Pin::new(&mut this.socket).poll_read(cx, buf);
        if buf.filled().len() > before {
            this.heard();
        } else if read.is_pending() && this.silence.as_mut().poll(cx).is_ready() {
            return Poll::Ready(Err(io::Error::new(
                io::ErrorKind::TimedOut,
                format!("the client was silent for {IDLE_TIMEOUT:?} (IDLE_TIMEOUT)"),
            )));
        }
        read
    }
}

impl<S: AsyncWrite + Unpin> AsyncWrite for ClientSocket<S> {
    fn poll_write(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<io::Result<usize>> {
        let this = self.get_mut();
        let written = Pin::new(&mut this.socket).poll_write(cx, buf);
        this.wrote(&written);
        written
    }

    fn poll_write_vectored(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        bufs: &[io::IoSlice<'_>],
    ) -> Poll<io::Result<usize>> {
        let this = self.get_mut();
        let written = Pin::new(&mut this.socket).poll_write_vectored(cx, bufs);
        this.wrote(&written);
        written
    }

    fn is_write_vectored(&self) -> bool {
        self.socket.is_write_vectored()
    }

    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        Pin::new(&mut self.socket).poll_flush(cx)
    }

    fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        Pin::new(&mut self.socket).poll_shutdown(cx)
    }
}

/// Forwards daemon NDJSON lines to the client, one text frame each, until
/// the daemon closes its side or the client stops accepting frames, and
/// the rest of the stream as binary frames once it answers `hello` naming
/// a codec. Returns the close frame that describes how the daemon side
/// ended.
async fn daemon_to_client<R>(
    daemon: R,
    frames: mpsc::Sender<WsMessage>,
    hello: &PendingHellos,
) -> CloseFrame
where
    R: AsyncRead + Unpin,
{
    let mut reader = MessageReader::new(daemon);
    loop {
        let line = match reader.read_line().await {
            Ok(Some(line)) => line,
            Ok(None) => return daemon_closed(),
            Err(FrameError::LineTooLong { .. }) => {
                return too_large("a daemon message");
            }
            Err(error) => return daemon_failed(&error),
        };
        let switched = hello.switched_by(&line);
        let text = match String::from_utf8(line) {
            Ok(text) => text,
            Err(error) => {
                tracing::debug!(%error, "daemon sent a non-UTF-8 line");
                return close_frame(CloseCode::Error, "daemon sent invalid UTF-8".to_owned());
            }
        };
        if frames.send(WsMessage::Text(text.into())).await.is_err() {
            return client_gone();
        }
        if switched {
            let (daemon, buffered) = reader.into_parts();
            return daemon_stream_to_client(daemon, buffered, frames).await;
        }
    }
}

/// Forwards the daemon's compressed stream, `buffered` first, as binary
/// frames of what each read returns, until the daemon closes its side or
/// the client stops accepting frames.
async fn daemon_stream_to_client<R>(
    mut daemon: R,
    buffered: Vec<u8>,
    frames: mpsc::Sender<WsMessage>,
) -> CloseFrame
where
    R: AsyncRead + Unpin,
{
    if !buffered.is_empty()
        && frames
            .send(WsMessage::Binary(buffered.into()))
            .await
            .is_err()
    {
        return client_gone();
    }
    let mut read = BytesMut::with_capacity(STREAM_FRAME_BYTES);
    loop {
        match daemon
            .read_buf(&mut (&mut read).limit(STREAM_FRAME_BYTES))
            .await
        {
            Ok(0) => return daemon_closed(),
            Ok(_) => {}
            Err(error) => return daemon_failed(&error),
        }
        if frames
            .send(WsMessage::Binary(read.split().freeze()))
            .await
            .is_err()
        {
            return client_gone();
        }
        read.reserve(STREAM_FRAME_BYTES);
    }
}

fn daemon_closed() -> CloseFrame {
    close_frame(CloseCode::Normal, "daemon closed the connection".to_owned())
}

fn daemon_failed(error: &dyn std::fmt::Display) -> CloseFrame {
    tracing::debug!(%error, "daemon read failed");
    close_frame(CloseCode::Error, "daemon stream failed".to_owned())
}

/// The writer is gone, so no close frame can reach the client.
fn client_gone() -> CloseFrame {
    close_frame(CloseCode::Normal, "client gone".to_owned())
}

pub(super) fn close_frame(code: CloseCode, reason: String) -> CloseFrame {
    CloseFrame {
        code,
        reason: reason.into(),
    }
}

/// The close for a message over [`MAX_LINE_BYTES`], naming the limit.
fn too_large(what: &str) -> CloseFrame {
    close_frame(
        CloseCode::Size,
        format!("{what} exceeds MAX_LINE_BYTES ({MAX_LINE_BYTES} bytes)"),
    )
}

/// What the bridge adds to what a WebSocket's client sends the daemon.
pub(super) struct Relayed<'a> {
    /// The server's environment, the base of the client's.
    pub(super) host_env: &'a Map<String, Value>,
    /// The name of the token that authenticated the WebSocket, which every
    /// `rho/hello` the client sends carries to the daemon as
    /// `bridge_device`, in place of any the client sent; `None` strips it.
    pub(super) device: Option<&'a str>,
}

/// One client frame, ready for the daemon.
#[derive(Debug, PartialEq, Eq)]
pub(super) struct DaemonLine {
    /// One compact NDJSON line, `\n` included.
    pub(super) bytes: Vec<u8>,
    /// The id of a `rho/hello`, whose answer may switch the daemon's side
    /// to a codec.
    pub(super) hello: Option<RequestId>,
}

/// A daemon line over [`MAX_LINE_BYTES`] once the host environment was
/// overlaid.
#[derive(Debug, PartialEq, Eq)]
pub(super) struct TooLarge {
    pub(super) bytes: usize,
}

/// Converts one incoming WebSocket text frame into a single compact NDJSON
/// line, `\n` included, ready for the local daemon socket.
///
/// - Valid JSON is compacted to one line, so pretty-printed messages from
///   non-Rust clients work without breaking NDJSON framing.
/// - For methods that accept `ClientEnvironment`, `host_env` is used as the
///   base environment with any entries supplied by the client overlaid on top.
/// - Invalid JSON has raw `\r`/`\n` replaced by spaces so one WebSocket frame
///   can never smuggle multiple lines; the daemon still answers with a normal
///   JSON-RPC `ParseError`.
/// - A hello names its id, so the bridge knows the answer that may switch
///   the daemon's side to a codec, and carries the WebSocket's device as
///   `bridge_device`, which the client cannot set: one it sent is replaced,
///   or removed when the bridge names none. A hello that is not JSON the
///   daemon refuses anyway.
pub(super) fn prepare_daemon_line(
    frame: &str,
    relayed: &Relayed<'_>,
) -> Result<DaemonLine, TooLarge> {
    // Raw CR and LF are whitespace between JSON tokens and invalid inside
    // strings, so flattening them first changes no valid frame, and the
    // daemon parses exactly the line the bridge parsed.
    let frame = if frame.contains(['\r', '\n']) {
        Cow::Owned(frame.replace(['\r', '\n'], " "))
    } else {
        Cow::Borrowed(frame)
    };
    let mut hello = None;
    let mut bytes = match serde_json::from_str::<Value>(&frame) {
        Ok(mut value) => {
            apply_host_environment(&mut value, relayed.host_env);
            let is_hello = value.get("method").and_then(Value::as_str) == Some(HELLO);
            if is_hello {
                stamp_device(&mut value, relayed.device);
            }
            let bytes = serde_json::to_vec(&value).expect("a serde_json::Value always serializes");
            if is_hello {
                hello = hello_id(&bytes);
            }
            bytes
        }
        Err(_) => frame.into_owned().into_bytes(),
    };
    if bytes.len() > MAX_LINE_BYTES {
        return Err(TooLarge { bytes: bytes.len() });
    }
    bytes.push(b'\n');
    Ok(DaemonLine { bytes, hello })
}

/// Sets a hello's `params.bridge_device` to `device`, or removes it when
/// `device` is `None`, so the daemon hears only the bridge's word for which
/// device opened the connection. Params that are not an object get one
/// only to carry `device`; the daemon refuses such a hello either way.
fn stamp_device(hello: &mut Value, device: Option<&str>) {
    let Some(object) = hello.as_object_mut() else {
        return;
    };
    match (object.get_mut("params"), device) {
        (Some(Value::Object(params)), Some(device)) => {
            params.insert("bridge_device".to_owned(), Value::from(device));
        }
        (Some(Value::Object(params)), None) => {
            params.remove("bridge_device");
        }
        (_, None) => {}
        (_, Some(device)) => {
            object.insert(
                "params".to_owned(),
                serde_json::json!({ "bridge_device": device }),
            );
        }
    }
}

/// For environment-bearing protocol requests, overlays client-provided
/// `params.environment` entries onto `host_env` (or supplies `host_env` when
/// `environment` is omitted). A non-object `environment` is left alone so
/// the daemon still rejects it with `InvalidParams`.
fn apply_host_environment(message: &mut Value, host_env: &Map<String, Value>) {
    let Some(object) = message.as_object_mut() else {
        return;
    };
    let takes_environment = object
        .get("method")
        .and_then(Value::as_str)
        .is_some_and(|method| ENVIRONMENT_METHODS.contains(&method));
    if !takes_environment {
        return;
    }
    let Some(params) = object.get_mut("params").and_then(Value::as_object_mut) else {
        return;
    };
    let environment = match params.remove("environment") {
        None => Value::Object(host_env.clone()),
        Some(Value::Object(client)) => {
            let mut merged = host_env.clone();
            merged.extend(client);
            Value::Object(merged)
        }
        Some(malformed) => malformed,
    };
    params.insert("environment".to_owned(), environment);
}

/// The id of the hello `line` as the daemon reads it, which its answer
/// echoes; none when the daemon cannot read it as a request.
fn hello_id(line: &[u8]) -> Option<RequestId> {
    match Message::parse(line) {
        Ok(Message::Request(request)) => Some(request.id),
        _ => None,
    }
}

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