Skip to main content

mcpmesh_local_api/
client.rs

1//! A no-iroh mcpmesh-local/1 client: connect the UDS, read the server's `Hello`
2//! first frame, assert the api name, then issue typed request/response frames. Distinct
3//! from the CLI crate (`cli/`)'s ControlClient (which uses mcpmesh_net::framing) — this one links no
4//! iroh, so kb and the host shell can use it. kb calls this to self-register
5//! its `[services.kb]` socket backend with the running mcpmesh daemon.
6use std::path::Path;
7
8use serde_json::Value;
9
10use crate::codec::{FrameReader, Inbound, MAX_FRAME_BYTES, write_frame};
11use crate::protocol::{
12    AuditSummaryResult, BackendSpec, BlobFetchParams, BlobFetchResult, BlobGrantParams,
13    BlobPublishParams, BlobPublishResult, BlobScopeList, Hello, InviteParams, InviteResult,
14    OpenSessionParams, OrgJoinParams, OrgJoinResult, PairParams, PairResult, PeerRemoveParams,
15    PeerRenameParams, RegisterServiceParams, Request, RosterInstallParams, RosterInstallResult,
16    ServiceAllowParams, SetAppMetadataParams, SetNicknameParams, SetRosterUrlParams, StatusResult,
17    StreamFrame,
18};
19use crate::transport::{connect_local, split_local};
20
21/// The client's read half — boxed so ONE `ControlClient` serves every transport (the
22/// platform socket/pipe via [`connect_control`], or an embedder's in-memory duplex via
23/// [`connect_control_io`]).
24pub type ControlRead = Box<dyn tokio::io::AsyncRead + Send + Unpin>;
25/// The client's write half — see [`ControlRead`].
26pub type ControlWrite = Box<dyn tokio::io::AsyncWrite + Send + Unpin>;
27
28/// A connected mcpmesh-local/1 client: the framed stream + the server's `Hello`.
29pub struct ControlClient {
30    hello: Hello,
31    reader: FrameReader<ControlRead>,
32    writer: ControlWrite,
33}
34
35/// Hand-rolled (the boxed transport halves are not `Debug`): the `Hello` is the one
36/// diagnostic a `{:?}` needs — tests format `Result<ControlClient, _>` this way.
37impl std::fmt::Debug for ControlClient {
38    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
39        f.debug_struct("ControlClient")
40            .field("hello", &self.hello)
41            .finish_non_exhaustive()
42    }
43}
44
45/// The error surface of the client — thin, so callers can `anyhow`-wrap it.
46///
47/// The `Display`/`Error`/`From` impls below are hand-rolled rather than derived: the
48/// `client` feature deliberately pulls ONLY tokio (no `thiserror`), and the hand-rolled
49/// impls are behavior-identical (same messages, same `?`-conversion from `io::Error`)
50/// with zero extra dependencies.
51#[derive(Debug)]
52pub enum ClientError {
53    Io(std::io::Error),
54    Closed(&'static str),
55    Malformed(&'static str),
56    WrongApi { got: String, want: &'static str },
57    Api(Value),
58}
59
60impl std::fmt::Display for ClientError {
61    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
62        match self {
63            ClientError::Io(err) => write!(f, "io: {err}"),
64            ClientError::Closed(what) => write!(f, "connection closed before {what}"),
65            ClientError::Malformed(what) => write!(f, "malformed {what} frame"),
66            ClientError::WrongApi { got, want } => {
67                write!(f, "unexpected api: got {got:?}, want {want:?}")
68            }
69            ClientError::Api(err) => write!(f, "control API error: {err}"),
70        }
71    }
72}
73
74impl std::error::Error for ClientError {}
75
76impl From<std::io::Error> for ClientError {
77    fn from(err: std::io::Error) -> Self {
78        ClientError::Io(err)
79    }
80}
81
82impl ControlClient {
83    pub fn hello(&self) -> &Hello {
84        &self.hello
85    }
86
87    /// Issue a typed request; return the JSON-RPC `result` (or `ClientError::Api` on a
88    /// JSON-RPC `error`).
89    pub async fn request(&mut self, request: Request) -> Result<Value, ClientError> {
90        let frame = serde_json::to_value(&request).expect("Request serializes");
91        self.request_value(&frame).await
92    }
93
94    /// Issue a RAW request frame — the escape hatch for methods outside the typed
95    /// [`Request`] surface (the daemon-internal `shutdown`, third-party
96    /// `{"method":..,"params":{}}` shapes the dispatcher tolerates). Returns the JSON-RPC
97    /// `result` value (or `ClientError::Api` on a JSON-RPC `error`).
98    pub async fn request_value(&mut self, request: &Value) -> Result<Value, ClientError> {
99        write_frame(&mut self.writer, request).await?;
100        match self.reader.next().await? {
101            Some(Inbound::Frame(resp)) => {
102                if let Some(err) = resp.get("error") {
103                    return Err(ClientError::Api(err.clone()));
104                }
105                Ok(resp.get("result").cloned().unwrap_or(Value::Null))
106            }
107            Some(Inbound::Violation(_)) => Err(ClientError::Malformed("response")),
108            None => Err(ClientError::Closed("response")),
109        }
110    }
111
112    /// Send a request WITHOUT reading a response — for `OpenSession`, after which the
113    /// socket stops being JSON-RPC and becomes a raw MCP byte pipe (protocol.rs). Returns
114    /// the framed halves so the caller can pump the session — the SAME `FrameReader` that
115    /// read the Hello, so bytes the daemon pipelined behind it are never lost. A caller
116    /// that must re-box the read half calls `FrameReader::into_inner`, which returns the
117    /// BUFFERED reader (its read-ahead travels with it — see the pipelining test below).
118    pub async fn open_session(
119        mut self,
120        peer: String,
121        service: String,
122    ) -> Result<(FrameReader<ControlRead>, ControlWrite), ClientError> {
123        let frame = serde_json::to_value(Request::OpenSession(OpenSessionParams { peer, service }))
124            .expect("Request serializes");
125        write_frame(&mut self.writer, &frame).await?;
126        Ok((self.reader, self.writer))
127    }
128
129    /// Send a parameterless stream-upgrade request WITHOUT reading a response — like
130    /// [`open_session`](Self::open_session), but generic on the `method`: after this call the
131    /// socket stops being request/response and becomes a one-way push stream of frames the caller
132    /// READS (the `subscribe` telemetry surface). Returns the framed halves — the SAME
133    /// `FrameReader` that read the Hello, so any frame the daemon pipelined behind it is never
134    /// lost. The write half is handed back so the caller can hold the connection open (a watcher
135    /// only reads, but dropping the writer would half-close the socket).
136    pub async fn open_stream(
137        mut self,
138        method: &str,
139    ) -> Result<(FrameReader<ControlRead>, ControlWrite), ClientError> {
140        let frame = serde_json::json!({ "method": method });
141        write_frame(&mut self.writer, &frame).await?;
142        Ok((self.reader, self.writer))
143    }
144
145    /// Issue `request` and deserialize the JSON-RPC `result` into `T` — the shared core of every
146    /// typed helper below. `what` names the result in the [`ClientError::Malformed`] surface. The
147    /// wrong-type hazard the raw [`request`](Self::request) leaves to the caller is closed here:
148    /// each helper pairs its Request variant with its result type once, in this crate.
149    async fn request_typed<T: serde::de::DeserializeOwned>(
150        &mut self,
151        request: Request,
152        what: &'static str,
153    ) -> Result<T, ClientError> {
154        let v = self.request(request).await?;
155        serde_json::from_value(v).map_err(|_| ClientError::Malformed(what))
156    }
157
158    /// Issue `request` and discard the ack body (the daemon answers `{}` for verbs with no result
159    /// vocabulary). A JSON-RPC error still surfaces as [`ClientError::Api`].
160    async fn request_ack(&mut self, request: Request) -> Result<(), ClientError> {
161        self.request(request).await.map(|_| ())
162    }
163
164    /// The daemon's `status` picture: services served, known peers, roster/presence state,
165    /// self identity, recent pairings, and advisory reachability.
166    pub async fn status(&mut self) -> Result<StatusResult, ClientError> {
167        self.request_typed(Request::Status, "status result").await
168    }
169
170    /// Register/update a `[services.*]` entry idempotently (the daemon persists it and hot-reloads
171    /// serving). The daemon acks; the ack body is discarded.
172    pub async fn register_service(
173        &mut self,
174        name: &str,
175        backend: BackendSpec,
176        allow: Vec<String>,
177    ) -> Result<(), ClientError> {
178        self.register_service_with(name, backend, allow, false)
179            .await
180    }
181
182    /// [`register_service`](Self::register_service) with an explicit `ephemeral` flag (#36). When
183    /// `ephemeral` is true the registration lives only in daemon memory and is unregistered
184    /// automatically when THIS control connection closes — no config write, nothing to clean up.
185    /// Ideal for an embedder serving a `socket` backend from a fresh path each run.
186    pub async fn register_service_with(
187        &mut self,
188        name: &str,
189        backend: BackendSpec,
190        allow: Vec<String>,
191        ephemeral: bool,
192    ) -> Result<(), ClientError> {
193        self.request_ack(Request::RegisterService(RegisterServiceParams {
194            name: name.to_string(),
195            backend,
196            allow,
197            ephemeral,
198        }))
199        .await
200    }
201
202    /// Mint a one-time pairing invite granting `services`; return the copyable
203    /// `mcpmesh-invite:` line + its expiry.
204    pub async fn invite(&mut self, services: Vec<String>) -> Result<InviteResult, ClientError> {
205        self.invite_with(services, None).await
206    }
207
208    /// [`invite`](Self::invite) with an opaque `app_label` (#31) carried through to the redeemer's
209    /// `pair` result. mcpmesh never interprets the label; the embedder does (e.g. its own URN).
210    pub async fn invite_with(
211        &mut self,
212        services: Vec<String>,
213        app_label: Option<String>,
214    ) -> Result<InviteResult, ClientError> {
215        self.request_typed(
216            Request::Invite(InviteParams {
217                services,
218                app_label,
219            }),
220            "invite result",
221        )
222        .await
223    }
224
225    /// Redeem a pairing invite; return the inviter's suggested nickname, the display-only SAS
226    /// code, and the granted services.
227    pub async fn pair(&mut self, invite_line: &str) -> Result<PairResult, ClientError> {
228        self.request_typed(
229            Request::Pair(PairParams {
230                invite_line: invite_line.to_string(),
231            }),
232            "pair result",
233        )
234        .await
235    }
236
237    /// Unpair a peer by nickname: drops its identity row AND its every-`allow` membership
238    /// (idempotent; live sessions are not severed). The daemon acks; the ack body is discarded.
239    pub async fn peer_remove(&mut self, nickname: &str) -> Result<(), ClientError> {
240        self.request_ack(Request::PeerRemove(PeerRemoveParams {
241            nickname: nickname.to_string(),
242        }))
243        .await
244    }
245
246    /// Rename a contact's nickname to `to` — every device sharing `user_id` when given, else the
247    /// single provisional `nickname` entry — carrying its grants along. The daemon refuses (a
248    /// [`ClientError::Api`]) when `to` is empty or already names a different identity. The daemon
249    /// acks; the ack body is discarded.
250    pub async fn peer_rename(
251        &mut self,
252        user_id: Option<String>,
253        nickname: Option<String>,
254        to: &str,
255    ) -> Result<(), ClientError> {
256        self.request_ack(Request::PeerRename(PeerRenameParams {
257            user_id,
258            nickname,
259            to: to.to_string(),
260        }))
261        .await
262    }
263
264    /// Install a signed roster from the LOCAL file at `path` (`org_root_pk` pins the org root on
265    /// FIRST install); return the installed org id + serial + severed-session count.
266    pub async fn roster_install(
267        &mut self,
268        path: &str,
269        org_root_pk: Option<String>,
270    ) -> Result<RosterInstallResult, ClientError> {
271        self.request_typed(
272            Request::RosterInstall(RosterInstallParams {
273                path: path.to_string(),
274                org_root_pk,
275            }),
276            "roster_install result",
277        )
278        .await
279    }
280
281    /// Pin the org root on a JOINER (no roster yet). `user_key` is a LOCAL path — the key never
282    /// crosses the API. Returns the pinned org id.
283    pub async fn org_join(
284        &mut self,
285        org_id: &str,
286        org_root_pk: &str,
287        user_id: &str,
288        user_key: &str,
289    ) -> Result<OrgJoinResult, ClientError> {
290        self.request_typed(
291            Request::OrgJoin(OrgJoinParams {
292                org_id: org_id.to_string(),
293                org_root_pk: org_root_pk.to_string(),
294                user_id: user_id.to_string(),
295                user_key: user_key.to_string(),
296            }),
297            "org_join result",
298        )
299        .await
300    }
301
302    /// Pin the HTTPS roster URL (`[roster].url`) in the daemon's config. The daemon acks; the
303    /// ack body is discarded.
304    pub async fn set_roster_url(&mut self, url: &str) -> Result<(), ClientError> {
305        self.request_ack(Request::SetRosterUrl(SetRosterUrlParams {
306            url: url.to_string(),
307        }))
308        .await
309    }
310
311    /// Grant a stable `principal` (`b64u:`/`eid:`) access to `service` WITHOUT (re)pairing (#44)
312    /// — the per-peer "sharing on" toggle. Idempotent; an unknown service is a clean no-op.
313    pub async fn service_allow_grant(
314        &mut self,
315        service: &str,
316        principal: &str,
317    ) -> Result<(), ClientError> {
318        self.request_ack(Request::ServiceAllowGrant(ServiceAllowParams {
319            service: service.to_string(),
320            principal: principal.to_string(),
321        }))
322        .await
323    }
324
325    /// Revoke a stable `principal` from `service`'s allow WITHOUT unpairing (#44) — the
326    /// "sharing off" toggle. The peer's identity row is untouched; it just cannot open NEW
327    /// sessions (in-flight ones run to completion). Idempotent.
328    pub async fn service_allow_revoke(
329        &mut self,
330        service: &str,
331        principal: &str,
332    ) -> Result<(), ClientError> {
333        self.request_ack(Request::ServiceAllowRevoke(ServiceAllowParams {
334            service: service.to_string(),
335            principal: principal.to_string(),
336        }))
337        .await
338    }
339
340    /// Set this node's opaque app-metadata blob (#39, roster mode): ≤256 bytes, folded
341    /// signed into each presence heartbeat so paired peers read it in `status` presence —
342    /// no per-peer session. `""` clears it; in-memory (re-set on startup).
343    pub async fn set_app_metadata(&mut self, metadata: &str) -> Result<(), ClientError> {
344        self.request_ack(Request::SetAppMetadata(SetAppMetadataParams {
345            metadata: metadata.to_string(),
346        }))
347        .await
348    }
349
350    /// Rename this node LIVE (#37): the daemon validates + persists `[identity].nickname`
351    /// under its own config lock and updates the name future invites present — no restart.
352    /// Peers keep their stored pairing-time nickname until a re-invite (display-only).
353    pub async fn set_nickname(&mut self, nickname: &str) -> Result<(), ClientError> {
354        self.request_ack(Request::SetNickname(SetNicknameParams {
355            nickname: nickname.to_string(),
356        }))
357        .await
358    }
359
360    /// Summarize the daemon's LOCAL audit log into per-peer / per-service session counts
361    /// (local-only — nothing is transmitted).
362    pub async fn audit_summary(&mut self) -> Result<AuditSummaryResult, ClientError> {
363        self.request_typed(Request::AuditSummary, "audit_summary result")
364            .await
365    }
366
367    /// Publish a local file into `scope`; return the minted `mcpmesh/blob/1` ticket + hash.
368    pub async fn blob_publish(
369        &mut self,
370        scope: &str,
371        path: &str,
372    ) -> Result<BlobPublishResult, ClientError> {
373        self.request_typed(
374            Request::BlobPublish(BlobPublishParams {
375                scope: scope.to_string(),
376                path: path.to_string(),
377            }),
378            "blob_publish result",
379        )
380        .await
381    }
382
383    /// List the daemon's blob scopes (name → hashes + grants).
384    pub async fn blob_list(&mut self) -> Result<BlobScopeList, ClientError> {
385        self.request_typed(Request::BlobList, "blob_list result")
386            .await
387    }
388
389    /// Fetch a `mcpmesh/blob/1` ticket THROUGH the daemon (BLAKE3-verified), export to
390    /// `dest_path`; return the verified hash + byte length.
391    pub async fn blob_fetch(
392        &mut self,
393        ticket: &str,
394        dest_path: &str,
395    ) -> Result<BlobFetchResult, ClientError> {
396        self.request_typed(
397            Request::BlobFetch(BlobFetchParams {
398                ticket: ticket.to_string(),
399                dest_path: dest_path.to_string(),
400            }),
401            "blob_fetch result",
402        )
403        .await
404    }
405
406    /// Grant a scope to a principal — any flat-namespace entry: a group name, a user_id,
407    /// or a nickname (the shared `principal_set` expansion).
408    /// The daemon acks; the ack body is discarded (a JSON-RPC error surfaces as
409    /// `ClientError::Api`). Granting a scope to your own user_id reaches ALL of that
410    /// person's devices.
411    pub async fn blob_grant(&mut self, scope: &str, principal: &str) -> Result<(), ClientError> {
412        self.request_ack(Request::BlobGrant(BlobGrantParams {
413            scope: scope.to_string(),
414            principal: principal.to_string(),
415        }))
416        .await
417    }
418
419    /// The TYPED `subscribe` upgrade: send [`Request::Subscribe`] (after which the connection
420    /// stops being request/response — see [`open_stream`](Self::open_stream)) and return a
421    /// [`StreamSubscription`] yielding [`StreamFrame`]s. For raw frames (e.g. to tolerate frame
422    /// types newer than this crate), use `open_stream("subscribe")` instead.
423    pub async fn subscribe(self) -> Result<StreamSubscription, ClientError> {
424        let (reader, writer) = self.open_stream("subscribe").await?;
425        Ok(StreamSubscription {
426            reader,
427            _writer: writer,
428        })
429    }
430}
431
432/// A live [`Request::Subscribe`] stream yielding typed [`StreamFrame`]s (snapshot, then
433/// events/lagged notices) until the daemon side closes. Holds the connection's write half for its
434/// lifetime — a subscriber only reads, but dropping the writer would half-close the socket. Drop
435/// the subscription to disconnect (there is no request channel back).
436pub struct StreamSubscription {
437    reader: FrameReader<ControlRead>,
438    _writer: ControlWrite,
439}
440
441/// Hand-rolled like [`ControlClient`]'s: the boxed transport halves are not `Debug`.
442impl std::fmt::Debug for StreamSubscription {
443    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
444        f.debug_struct("StreamSubscription").finish_non_exhaustive()
445    }
446}
447
448impl StreamSubscription {
449    /// The next frame, or `None` when the daemon closed the stream. A frame this crate's
450    /// [`StreamFrame`] does not model (a NEWER daemon's frame type) surfaces as
451    /// [`ClientError::Malformed`] — a forward-compatible consumer reads raw frames via
452    /// [`ControlClient::open_stream`] instead.
453    pub async fn next(&mut self) -> Result<Option<StreamFrame>, ClientError> {
454        match self.reader.next().await? {
455            Some(Inbound::Frame(v)) => serde_json::from_value(v)
456                .map(Some)
457                .map_err(|_| ClientError::Malformed("stream frame")),
458            Some(Inbound::Violation(_)) => Err(ClientError::Malformed("stream frame")),
459            None => Ok(None),
460        }
461    }
462}
463
464/// Complete the mcpmesh-local/1 hello handshake over ALREADY-CONNECTED byte halves —
465/// the transport-agnostic core of [`connect_control`], and the front door for in-process
466/// embedding (`mcpmesh-node`'s `Node::control` dials a tokio duplex through here).
467pub async fn connect_control_io(
468    reader: impl tokio::io::AsyncRead + Send + Unpin + 'static,
469    writer: impl tokio::io::AsyncWrite + Send + Unpin + 'static,
470) -> Result<ControlClient, ClientError> {
471    let mut reader = FrameReader::new(Box::new(reader) as ControlRead, MAX_FRAME_BYTES);
472    let hello: Hello = match reader.next().await? {
473        Some(Inbound::Frame(v)) => {
474            serde_json::from_value(v).map_err(|_| ClientError::Malformed("hello"))?
475        }
476        Some(Inbound::Violation(_)) => return Err(ClientError::Malformed("hello")),
477        None => return Err(ClientError::Closed("hello")),
478    };
479    if hello.api != crate::protocol::API_NAME {
480        return Err(ClientError::WrongApi {
481            got: hello.api,
482            want: crate::protocol::API_NAME,
483        });
484    }
485    Ok(ControlClient {
486        hello,
487        reader,
488        writer: Box::new(writer) as ControlWrite,
489    })
490}
491
492/// Connect + complete the hello handshake, asserting the api name is `mcpmesh-local/1`.
493pub async fn connect_control(path: &Path) -> Result<ControlClient, ClientError> {
494    let stream = connect_local(path).await?;
495    let (read_half, write_half) = split_local(stream);
496    connect_control_io(read_half, write_half).await
497}
498
499/// [`connect_control`] at the platform default endpoint ([`crate::paths::default_endpoint`]):
500/// the quickstart front door — a consumer dials the running daemon without reimplementing
501/// the platform endpoint rule. Resolution failure surfaces as [`ClientError::Io`]
502/// (`NotFound`), same as a daemon that is not running.
503pub async fn connect_control_default() -> Result<ControlClient, ClientError> {
504    connect_control(&crate::paths::default_endpoint()?).await
505}
506
507// Seam-ported (Task 6): every stub daemon binds via the platform seam
508// (`transport::bind_local` + `LocalListener::accept`) rather than a raw `UnixListener`,
509// so these exercise the platform-identical `ControlClient` on BOTH unix (UDS) and windows
510// (named pipe). Gated on `feature = "service"` (bind needs it) rather than `unix`: under
511// `cargo test --workspace` feature unification turns `service` on for this crate (cli
512// depends on local-api with features=["service"]), so the module compiles and RUNS on the
513// windows CI leg. `test_endpoint` yields a platform-appropriate unique endpoint.
514#[cfg(all(test, feature = "service"))]
515mod tests {
516    use super::*;
517    use crate::protocol::{API_NAME, API_VERSION, BackendKind, ServiceInfo, StatusResult};
518    use crate::transport::{LocalListener, bind_local, split_local};
519    use tokio::io::AsyncWriteExt;
520
521    /// A unique local endpoint for a stub daemon, platform-appropriate: a tempdir socket
522    /// path on unix, a per-process-unique `\\.\pipe\…` name on windows. Returns the
523    /// endpoint plus a guard that MUST outlive the listener (the `TempDir` on unix; unit
524    /// on windows, whose pipe namespace needs no filesystem cleanup).
525    #[cfg(unix)]
526    fn test_endpoint(tag: &str) -> (std::path::PathBuf, tempfile::TempDir) {
527        let dir = tempfile::tempdir().unwrap();
528        let path = dir.path().join(format!("{tag}.sock"));
529        (path, dir)
530    }
531    #[cfg(windows)]
532    fn test_endpoint(tag: &str) -> (std::path::PathBuf, ()) {
533        use std::sync::atomic::{AtomicU64, Ordering};
534        static SEQ: AtomicU64 = AtomicU64::new(0);
535        let n = SEQ.fetch_add(1, Ordering::Relaxed);
536        let path = std::path::PathBuf::from(format!(
537            r"\\.\pipe\mcpmesh-client-test-{}-{tag}-{n}",
538            std::process::id()
539        ));
540        (path, ())
541    }
542
543    /// A stub mcpmesh daemon: send Hello, then answer one `status` with a StatusResult.
544    async fn stub_daemon(mut listener: LocalListener) {
545        let stream = listener.accept().await.unwrap();
546        let (read_half, mut writer) = split_local(stream);
547        write_frame(
548            &mut writer,
549            &serde_json::to_value(Hello {
550                api: API_NAME.into(),
551                api_version: API_VERSION.into(),
552                api_minor: 0,
553                stack_version: "0.1.0".into(),
554            })
555            .unwrap(),
556        )
557        .await
558        .unwrap();
559        let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
560        let req = match reader.next().await.unwrap().unwrap() {
561            Inbound::Frame(v) => v,
562            Inbound::Violation(_) => panic!("violation"),
563        };
564        assert_eq!(req["method"], "status");
565        let result = StatusResult {
566            stack_version: "0.1.0".into(),
567            services: vec![ServiceInfo {
568                name: "kb".into(),
569                allow: vec![],
570                allow_display: vec![],
571                backend: BackendKind::Socket,
572                ephemeral: false,
573            }],
574            peers: vec![],
575            roster: None,
576            presence: vec![],
577            self_user_id: None,
578            recent_pairings: vec![],
579            reachability: vec![],
580            self_nickname: String::new(),
581        };
582        write_frame(
583            &mut writer,
584            &serde_json::json!({ "jsonrpc": "2.0", "id": 1, "result": result }),
585        )
586        .await
587        .unwrap();
588        writer.flush().await.unwrap();
589    }
590
591    /// The transport-agnostic front door: the same hello handshake over a plain in-memory
592    /// duplex — what an embedded node's `Node::control` dials through.
593    #[tokio::test]
594    async fn connect_control_io_handshakes_over_a_duplex() {
595        let (client_io, mut server_io) = tokio::io::duplex(4096);
596        tokio::spawn(async move {
597            write_frame(
598                &mut server_io,
599                &serde_json::to_value(Hello {
600                    api: API_NAME.into(),
601                    api_version: API_VERSION.into(),
602                    api_minor: 0,
603                    stack_version: "in-proc".into(),
604                })
605                .unwrap(),
606            )
607            .await
608            .unwrap();
609        });
610        let (r, w) = tokio::io::split(client_io);
611        let client = connect_control_io(r, w).await.expect("handshake");
612        assert_eq!(client.hello().stack_version, "in-proc");
613    }
614
615    #[tokio::test]
616    async fn connect_reads_hello_asserts_api_and_requests() {
617        let (sock, _guard) = test_endpoint("status");
618        let listener = bind_local(&sock).unwrap();
619        let server = tokio::spawn(stub_daemon(listener));
620
621        let mut client = connect_control(&sock).await.unwrap();
622        assert_eq!(client.hello().api, API_NAME);
623        let result = client.request(Request::Status).await.unwrap();
624        assert_eq!(result["services"][0]["name"], "kb");
625        assert_eq!(result["services"][0]["backend"], "socket");
626        server.await.unwrap();
627    }
628
629    #[tokio::test]
630    async fn wrong_api_hello_is_rejected() {
631        let (sock, _guard) = test_endpoint("wrongapi");
632        let listener = bind_local(&sock).unwrap();
633        tokio::spawn(async move {
634            let mut listener = listener;
635            let stream = listener.accept().await.unwrap();
636            let (_r, mut w) = split_local(stream);
637            write_frame(
638                &mut w,
639                &serde_json::json!({"api":"other/1","api_version":"1.0","stack_version":"0"}),
640            )
641            .await
642            .unwrap();
643            w.flush().await.unwrap();
644        });
645        match connect_control(&sock).await {
646            Err(ClientError::WrongApi { got, want }) => {
647                assert_eq!(got, "other/1");
648                assert_eq!(want, API_NAME);
649            }
650            other => panic!("expected WrongApi, got {other:?}"),
651        }
652    }
653
654    #[tokio::test]
655    async fn blob_fetch_and_publish_deserialize_typed_results() {
656        use crate::protocol::{BlobFetchResult, BlobPublishResult};
657        let (sock, _guard) = test_endpoint("blob");
658        let listener = bind_local(&sock).unwrap();
659        let server = tokio::spawn(async move {
660            let mut listener = listener;
661            let stream = listener.accept().await.unwrap();
662            let (read_half, mut writer) = split_local(stream);
663            write_frame(
664                &mut writer,
665                &serde_json::to_value(Hello {
666                    api: API_NAME.into(),
667                    api_version: API_VERSION.into(),
668                    api_minor: 0,
669                    stack_version: "0.1.0".into(),
670                })
671                .unwrap(),
672            )
673            .await
674            .unwrap();
675            let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
676            // First request: blob_publish -> a ticket + hash.
677            let req = match reader.next().await.unwrap().unwrap() {
678                Inbound::Frame(v) => v,
679                Inbound::Violation(_) => panic!("violation"),
680            };
681            assert_eq!(req["method"], "blob_publish");
682            assert_eq!(req["params"]["scope"], "eng");
683            write_frame(
684                &mut writer,
685                &serde_json::json!({"jsonrpc":"2.0","id":1,"result":{"ticket":"blobT","hash":"ab"}}),
686            )
687            .await
688            .unwrap();
689            // Second request: blob_fetch -> a verified hash + length.
690            let req = match reader.next().await.unwrap().unwrap() {
691                Inbound::Frame(v) => v,
692                Inbound::Violation(_) => panic!("violation"),
693            };
694            assert_eq!(req["method"], "blob_fetch");
695            assert_eq!(req["params"]["ticket"], "blobT");
696            assert_eq!(req["params"]["dest_path"], "/tmp/out.bin");
697            write_frame(
698                &mut writer,
699                &serde_json::json!({"jsonrpc":"2.0","id":2,"result":{"hash":"cd","bytes_len":7}}),
700            )
701            .await
702            .unwrap();
703            let _ = (
704                BlobFetchResult {
705                    hash: "cd".into(),
706                    bytes_len: 7,
707                },
708                BlobPublishResult {
709                    ticket: "blobT".into(),
710                    hash: "ab".into(),
711                },
712            );
713        });
714
715        let mut client = connect_control(&sock).await.unwrap();
716        let pub_res = client.blob_publish("eng", "/tmp/a.bin").await.unwrap();
717        assert_eq!(pub_res.ticket, "blobT");
718        assert_eq!(pub_res.hash, "ab");
719        let fetch_res = client.blob_fetch("blobT", "/tmp/out.bin").await.unwrap();
720        assert_eq!(fetch_res.hash, "cd");
721        assert_eq!(fetch_res.bytes_len, 7);
722        server.await.unwrap();
723    }
724
725    /// Regression (lossless rebox): a frame the server PIPELINES in the same write as
726    /// the Hello must survive `open_session` + kb's production re-box shape
727    /// (`FrameReader::new(Box::new(reader.into_inner()), …)`, bridge/session.rs). Against
728    /// the old `into_inner -> R` — which unwrapped the internal `BufReader` and DROPPED
729    /// its read-ahead — the pipelined frame vanished and this test failed (EOF instead of
730    /// the frame). `into_inner -> BufReader<R>` carries the read-ahead across the rebox.
731    #[tokio::test]
732    async fn frame_pipelined_behind_hello_survives_open_session_rebox() {
733        use tokio::io::AsyncRead;
734
735        let (sock, _guard) = test_endpoint("pipelined");
736        let listener = bind_local(&sock).unwrap();
737        let server = tokio::spawn(async move {
738            let mut listener = listener;
739            let stream = listener.accept().await.unwrap();
740            let (read_half, mut writer) = split_local(stream);
741            // ONE write carrying the Hello AND a session frame → both land in the
742            // client's first BufReader fill (the read-ahead under test).
743            let mut bytes = serde_json::to_vec(
744                &serde_json::to_value(Hello {
745                    api: API_NAME.into(),
746                    api_version: API_VERSION.into(),
747                    api_minor: 0,
748                    stack_version: "0.1.0".into(),
749                })
750                .unwrap(),
751            )
752            .unwrap();
753            bytes.push(b'\n');
754            bytes.extend_from_slice(b"{\"jsonrpc\":\"2.0\",\"id\":42,\"result\":{}}\n");
755            writer.write_all(&bytes).await.unwrap();
756            writer.flush().await.unwrap();
757            // Absorb the client's open_session frame so its write never sees EPIPE.
758            let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
759            let req = match reader.next().await.unwrap().unwrap() {
760                Inbound::Frame(v) => v,
761                Inbound::Violation(_) => panic!("violation"),
762            };
763            assert_eq!(req["method"], "open_session");
764        });
765
766        let client = connect_control(&sock).await.unwrap();
767        let (reader, _writer) = client
768            .open_session("peer".into(), "kb".into())
769            .await
770            .unwrap();
771        // kb's production shape: erase the half type behind a boxed pipe, then re-frame.
772        let boxed: Box<dyn AsyncRead + Unpin + Send> = Box::new(reader.into_inner());
773        let mut reframed = FrameReader::new(boxed, MAX_FRAME_BYTES);
774        match reframed.next().await.unwrap() {
775            Some(Inbound::Frame(v)) => assert_eq!(v["id"], 42),
776            other => panic!("pipelined frame was lost across the rebox: {other:?}"),
777        }
778        server.await.unwrap();
779    }
780
781    #[tokio::test]
782    async fn blob_grant_issues_request_and_acks() {
783        let (sock, _guard) = test_endpoint("grant");
784        let listener = bind_local(&sock).unwrap();
785        let server = tokio::spawn(async move {
786            let mut listener = listener;
787            let stream = listener.accept().await.unwrap();
788            let (read_half, mut writer) = split_local(stream);
789            write_frame(
790                &mut writer,
791                &serde_json::to_value(Hello {
792                    api: API_NAME.into(),
793                    api_version: API_VERSION.into(),
794                    api_minor: 0,
795                    stack_version: "0.1.0".into(),
796                })
797                .unwrap(),
798            )
799            .await
800            .unwrap();
801            let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
802            let req = match reader.next().await.unwrap().unwrap() {
803                Inbound::Frame(v) => v,
804                Inbound::Violation(_) => panic!("violation"),
805            };
806            assert_eq!(req["method"], "blob_grant");
807            assert_eq!(req["params"]["scope"], "kb-sync");
808            assert_eq!(req["params"]["principal"], "alice");
809            write_frame(
810                &mut writer,
811                &serde_json::json!({"jsonrpc":"2.0","id":1,"result":{"ok":true}}),
812            )
813            .await
814            .unwrap();
815        });
816        let mut client = connect_control(&sock).await.unwrap();
817        client.blob_grant("kb-sync", "alice").await.unwrap();
818        server.await.unwrap();
819    }
820
821    /// The typed `status()` helper pairs `Request::Status` with `StatusResult` — the caller gets
822    /// the struct, not a `Value` to hand-deserialize (and a malformed result surfaces as
823    /// `ClientError::Malformed`, never a silently-wrong type).
824    #[tokio::test]
825    async fn typed_status_helper_deserializes_the_result() {
826        let (sock, _guard) = test_endpoint("typedstatus");
827        let listener = bind_local(&sock).unwrap();
828        let server = tokio::spawn(stub_daemon(listener));
829
830        let mut client = connect_control(&sock).await.unwrap();
831        let status = client.status().await.unwrap();
832        assert_eq!(status.stack_version, "0.1.0");
833        assert_eq!(status.services[0].name, "kb");
834        assert_eq!(status.services[0].backend, BackendKind::Socket);
835        assert!(status.peers.is_empty());
836        server.await.unwrap();
837    }
838
839    /// The ack-shaped typed helpers issue the right wire method and discard the `{}` ack; a
840    /// JSON-RPC error frame surfaces as `ClientError::Api`.
841    #[tokio::test]
842    async fn typed_ack_helpers_issue_requests_and_surface_api_errors() {
843        let (sock, _guard) = test_endpoint("typedack");
844        let listener = bind_local(&sock).unwrap();
845        let server = tokio::spawn(async move {
846            let mut listener = listener;
847            let stream = listener.accept().await.unwrap();
848            let (read_half, mut writer) = split_local(stream);
849            write_frame(
850                &mut writer,
851                &serde_json::to_value(Hello {
852                    api: API_NAME.into(),
853                    api_version: API_VERSION.into(),
854                    api_minor: 0,
855                    stack_version: "0.1.0".into(),
856                })
857                .unwrap(),
858            )
859            .await
860            .unwrap();
861            let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
862            // peer_remove → ack.
863            let req = match reader.next().await.unwrap().unwrap() {
864                Inbound::Frame(v) => v,
865                Inbound::Violation(_) => panic!("violation"),
866            };
867            assert_eq!(req["method"], "peer_remove");
868            assert_eq!(req["params"]["nickname"], "bob");
869            write_frame(
870                &mut writer,
871                &serde_json::json!({"jsonrpc":"2.0","id":1,"result":{}}),
872            )
873            .await
874            .unwrap();
875            // peer_rename → an error frame (collision refusal).
876            let req = match reader.next().await.unwrap().unwrap() {
877                Inbound::Frame(v) => v,
878                Inbound::Violation(_) => panic!("violation"),
879            };
880            assert_eq!(req["method"], "peer_rename");
881            assert_eq!(req["params"]["to"], "Bobby");
882            write_frame(
883                &mut writer,
884                &serde_json::json!({"jsonrpc":"2.0","id":2,"error":{"code":-32000,"message":"taken"}}),
885            )
886            .await
887            .unwrap();
888        });
889
890        let mut client = connect_control(&sock).await.unwrap();
891        client.peer_remove("bob").await.unwrap();
892        match client.peer_rename(None, Some("bob".into()), "Bobby").await {
893            Err(ClientError::Api(e)) => assert_eq!(e["message"], "taken"),
894            other => panic!("expected Api error, got {other:?}"),
895        }
896        server.await.unwrap();
897    }
898
899    /// The typed `subscribe()` upgrade yields `StreamFrame`s — snapshot, event, lagged — then
900    /// `None` when the daemon side closes.
901    #[tokio::test]
902    async fn typed_subscribe_yields_frames_then_end() {
903        use crate::protocol::{ActiveSession, AuditRecord, PeerReachability};
904
905        let (sock, _guard) = test_endpoint("subscribe");
906        let listener = bind_local(&sock).unwrap();
907        let server = tokio::spawn(async move {
908            let mut listener = listener;
909            let stream = listener.accept().await.unwrap();
910            let (read_half, mut writer) = split_local(stream);
911            write_frame(
912                &mut writer,
913                &serde_json::to_value(Hello {
914                    api: API_NAME.into(),
915                    api_version: API_VERSION.into(),
916                    api_minor: 0,
917                    stack_version: "0.1.0".into(),
918                })
919                .unwrap(),
920            )
921            .await
922            .unwrap();
923            let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
924            let req = match reader.next().await.unwrap().unwrap() {
925                Inbound::Frame(v) => v,
926                Inbound::Violation(_) => panic!("violation"),
927            };
928            assert_eq!(req["method"], "subscribe");
929            for frame in [
930                StreamFrame::Snapshot {
931                    active_sessions: vec![ActiveSession {
932                        peer: "bob".into(),
933                        service: "notes".into(),
934                        opened_at: 7,
935                    }],
936                    reachability: vec![PeerReachability {
937                        name: "bob".into(),
938                        reachable: true,
939                        rtt_ms: Some(42),
940                        age_secs: Some(3),
941                        meta: String::new(),
942                        principal: None,
943                    }],
944                },
945                StreamFrame::Event {
946                    record: Box::new(AuditRecord::session_open(
947                        "2026-07-03T14:02:11.480Z".into(),
948                        Some("bob".into()),
949                        "notes".into(),
950                    )),
951                },
952                StreamFrame::Lagged { dropped: 12 },
953            ] {
954                write_frame(&mut writer, &serde_json::to_value(&frame).unwrap())
955                    .await
956                    .unwrap();
957            }
958            writer.flush().await.unwrap();
959            // Drop the connection: the client must see the stream END (Ok(None)), not an error.
960        });
961
962        let client = connect_control(&sock).await.unwrap();
963        let mut sub = client.subscribe().await.unwrap();
964        match sub.next().await.unwrap().unwrap() {
965            StreamFrame::Snapshot {
966                active_sessions,
967                reachability,
968            } => {
969                assert_eq!(active_sessions[0].peer, "bob");
970                assert_eq!(reachability[0].rtt_ms, Some(42));
971            }
972            other => panic!("expected the snapshot first, got {other:?}"),
973        }
974        match sub.next().await.unwrap().unwrap() {
975            StreamFrame::Event { record } => {
976                assert_eq!(record.peer.as_deref(), Some("bob"));
977                assert_eq!(record.service.as_deref(), Some("notes"));
978            }
979            other => panic!("expected the event, got {other:?}"),
980        }
981        assert_eq!(
982            sub.next().await.unwrap(),
983            Some(StreamFrame::Lagged { dropped: 12 })
984        );
985        assert_eq!(sub.next().await.unwrap(), None, "clean end of stream");
986        server.await.unwrap();
987    }
988}