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, BlobFetchCancelParams, BlobFetchCancelResult, BlobFetchParams,
13    BlobFetchResult, BlobGrantParams, BlobPublishParams, BlobPublishResult, BlobScopeList, Hello,
14    InviteParams, InviteResult, OpenSessionParams, OrgJoinParams, OrgJoinResult, PairParams,
15    PairResult, PeerDiagnosticsParams, PeerDiagnosticsResult, PeerEndorseParams, PeerEndorseResult,
16    PeerHintClearParams, PeerHintClearResult, PeerIntroduceParams, PeerRemoveParams,
17    PeerRenameParams, PeerServicesParams, PeerServicesResult, RegisterServiceParams, Request,
18    RosterInstallParams, RosterInstallResult, ServiceAllowParams, SetAppMetadataParams,
19    SetNicknameParams, SetRelaysParams, SetRelaysResult, SetRosterUrlParams, StatusResult,
20    StreamFrame, UnregisterServiceParams,
21};
22use crate::transport::{connect_local, split_local};
23
24/// The client's read half — boxed so ONE `ControlClient` serves every transport (the
25/// platform socket/pipe via [`connect_control`], or an embedder's in-memory duplex via
26/// [`connect_control_io`]).
27pub type ControlRead = Box<dyn tokio::io::AsyncRead + Send + Unpin>;
28/// The client's write half — see [`ControlRead`].
29pub type ControlWrite = Box<dyn tokio::io::AsyncWrite + Send + Unpin>;
30
31/// A connected mcpmesh-local/1 client: the framed stream + the server's `Hello`.
32pub struct ControlClient {
33    hello: Hello,
34    reader: FrameReader<ControlRead>,
35    writer: ControlWrite,
36}
37
38/// Hand-rolled (the boxed transport halves are not `Debug`): the `Hello` is the one
39/// diagnostic a `{:?}` needs — tests format `Result<ControlClient, _>` this way.
40impl std::fmt::Debug for ControlClient {
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        f.debug_struct("ControlClient")
43            .field("hello", &self.hello)
44            .finish_non_exhaustive()
45    }
46}
47
48/// The error surface of the client — thin, so callers can `anyhow`-wrap it.
49///
50/// The `Display`/`Error`/`From` impls below are hand-rolled rather than derived: the
51/// `client` feature deliberately pulls ONLY tokio (no `thiserror`), and the hand-rolled
52/// impls are behavior-identical (same messages, same `?`-conversion from `io::Error`)
53/// with zero extra dependencies.
54#[derive(Debug)]
55pub enum ClientError {
56    Io(std::io::Error),
57    Closed(&'static str),
58    Malformed(&'static str),
59    WrongApi { got: String, want: &'static str },
60    Api(Value),
61}
62
63impl std::fmt::Display for ClientError {
64    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
65        match self {
66            ClientError::Io(err) => write!(f, "io: {err}"),
67            ClientError::Closed(what) => write!(f, "connection closed before {what}"),
68            ClientError::Malformed(what) => write!(f, "malformed {what} frame"),
69            ClientError::WrongApi { got, want } => {
70                write!(f, "unexpected api: got {got:?}, want {want:?}")
71            }
72            ClientError::Api(err) => write!(f, "control API error: {err}"),
73        }
74    }
75}
76
77impl std::error::Error for ClientError {}
78
79impl From<std::io::Error> for ClientError {
80    fn from(err: std::io::Error) -> Self {
81        ClientError::Io(err)
82    }
83}
84
85impl ControlClient {
86    pub fn hello(&self) -> &Hello {
87        &self.hello
88    }
89
90    /// Issue a typed request; return the JSON-RPC `result` (or `ClientError::Api` on a
91    /// JSON-RPC `error`).
92    pub async fn request(&mut self, request: Request) -> Result<Value, ClientError> {
93        let frame = serde_json::to_value(&request).expect("Request serializes");
94        self.request_value(&frame).await
95    }
96
97    /// Issue a RAW request frame — the escape hatch for methods outside the typed
98    /// [`Request`] surface (the daemon-internal `shutdown`, third-party
99    /// `{"method":..,"params":{}}` shapes the dispatcher tolerates). Returns the JSON-RPC
100    /// `result` value (or `ClientError::Api` on a JSON-RPC `error`).
101    pub async fn request_value(&mut self, request: &Value) -> Result<Value, ClientError> {
102        write_frame(&mut self.writer, request).await?;
103        match self.reader.next().await? {
104            Some(Inbound::Frame(resp)) => {
105                if let Some(err) = resp.get("error") {
106                    return Err(ClientError::Api(err.clone()));
107                }
108                Ok(resp.get("result").cloned().unwrap_or(Value::Null))
109            }
110            Some(Inbound::Violation(_)) => Err(ClientError::Malformed("response")),
111            None => Err(ClientError::Closed("response")),
112        }
113    }
114
115    /// Send a request WITHOUT reading a response — for `OpenSession`, after which the
116    /// socket stops being JSON-RPC and becomes a raw MCP byte pipe (protocol.rs). Returns
117    /// the framed halves so the caller can pump the session — the SAME `FrameReader` that
118    /// read the Hello, so bytes the daemon pipelined behind it are never lost. A caller
119    /// that must re-box the read half calls `FrameReader::into_inner`, which returns the
120    /// BUFFERED reader (its read-ahead travels with it — see the pipelining test below).
121    pub async fn open_session(
122        self,
123        peer: String,
124        service: String,
125    ) -> Result<(FrameReader<ControlRead>, ControlWrite), ClientError> {
126        self.open_session_with_idle_timeout(peer, service, None)
127            .await
128    }
129
130    /// [`open_session`](Self::open_session) with a per-session QUIC idle timeout (#166).
131    ///
132    /// See [`OpenSessionParams::idle_timeout_secs`] for what it can and cannot do — in short, it
133    /// can always make this session die sooner when it goes quiet, and can never make it outlive
134    /// what the peer allows.
135    ///
136    /// [`OpenSessionParams::idle_timeout_secs`]: crate::protocol::OpenSessionParams::idle_timeout_secs
137    pub async fn open_session_with_idle_timeout(
138        mut self,
139        peer: String,
140        service: String,
141        idle_timeout_secs: Option<u64>,
142    ) -> Result<(FrameReader<ControlRead>, ControlWrite), ClientError> {
143        let frame = serde_json::to_value(Request::OpenSession(OpenSessionParams {
144            peer,
145            service,
146            idle_timeout_secs,
147        }))
148        .expect("Request serializes");
149        write_frame(&mut self.writer, &frame).await?;
150        Ok((self.reader, self.writer))
151    }
152
153    /// Send a parameterless stream-upgrade request WITHOUT reading a response — like
154    /// [`open_session`](Self::open_session), but generic on the `method`: after this call the
155    /// socket stops being request/response and becomes a one-way push stream of frames the caller
156    /// READS (the `subscribe` telemetry surface). Returns the framed halves — the SAME
157    /// `FrameReader` that read the Hello, so any frame the daemon pipelined behind it is never
158    /// lost. The write half is handed back so the caller can hold the connection open (a watcher
159    /// only reads, but dropping the writer would half-close the socket).
160    pub async fn open_stream(
161        mut self,
162        method: &str,
163    ) -> Result<(FrameReader<ControlRead>, ControlWrite), ClientError> {
164        let frame = serde_json::json!({ "method": method });
165        write_frame(&mut self.writer, &frame).await?;
166        Ok((self.reader, self.writer))
167    }
168
169    /// Issue `request` and deserialize the JSON-RPC `result` into `T` — the shared core of every
170    /// typed helper below. `what` names the result in the [`ClientError::Malformed`] surface. The
171    /// wrong-type hazard the raw [`request`](Self::request) leaves to the caller is closed here:
172    /// each helper pairs its Request variant with its result type once, in this crate.
173    async fn request_typed<T: serde::de::DeserializeOwned>(
174        &mut self,
175        request: Request,
176        what: &'static str,
177    ) -> Result<T, ClientError> {
178        let v = self.request(request).await?;
179        serde_json::from_value(v).map_err(|_| ClientError::Malformed(what))
180    }
181
182    /// Issue `request` and discard the ack body (the daemon answers `{}` for verbs with no result
183    /// vocabulary). A JSON-RPC error still surfaces as [`ClientError::Api`].
184    async fn request_ack(&mut self, request: Request) -> Result<(), ClientError> {
185        self.request(request).await.map(|_| ())
186    }
187
188    /// The daemon's `status` picture: services served, known peers, roster/presence state,
189    /// self identity, recent pairings, and advisory reachability.
190    pub async fn status(&mut self) -> Result<StatusResult, ClientError> {
191        self.request_typed(Request::Status, "status result").await
192    }
193
194    /// Register/update a `[services.*]` entry idempotently (the daemon persists it and hot-reloads
195    /// serving). The daemon acks; the ack body is discarded.
196    pub async fn register_service(
197        &mut self,
198        name: &str,
199        backend: BackendSpec,
200        allow: Vec<String>,
201    ) -> Result<(), ClientError> {
202        self.register_service_with(name, backend, allow, false)
203            .await
204    }
205
206    /// [`register_service`](Self::register_service) with an explicit `ephemeral` flag (#36). When
207    /// `ephemeral` is true the registration lives only in daemon memory and is unregistered
208    /// automatically when THIS control connection closes — no config write, nothing to clean up.
209    /// Ideal for an embedder serving a `socket` backend from a fresh path each run.
210    pub async fn register_service_with(
211        &mut self,
212        name: &str,
213        backend: BackendSpec,
214        allow: Vec<String>,
215        ephemeral: bool,
216    ) -> Result<(), ClientError> {
217        self.request_ack(Request::RegisterService(RegisterServiceParams {
218            name: name.to_string(),
219            backend,
220            allow,
221            ephemeral,
222            rate_limit_per_min: None,
223        }))
224        .await
225    }
226
227    /// Mint a single-use pairing invite granting `services` (see `invite_multi` for more than
228    /// one); return the copyable
229    /// `mcpmesh-invite:` line + its expiry.
230    pub async fn invite(&mut self, services: Vec<String>) -> Result<InviteResult, ClientError> {
231        self.invite_with(services, None).await
232    }
233
234    /// [`invite`](Self::invite) with an opaque `app_label` (#31) carried through to the redeemer's
235    /// `pair` result. mcpmesh never interprets the label; the embedder does (e.g. its own URN).
236    pub async fn invite_with(
237        &mut self,
238        services: Vec<String>,
239        app_label: Option<String>,
240    ) -> Result<InviteResult, ClientError> {
241        self.invite_multi(services, app_label, None).await
242    }
243
244    /// `invite_with`, plus `max_uses` (#87): an invite redeemable up to that many times, each
245    /// redemption running its own SAS ceremony and writing its own peer rows.
246    ///
247    /// `None` = 1, the single-use default. The value is clamped daemon-side to
248    /// [`MAX_INVITE_USES`](crate::MAX_INVITE_USES) — read
249    /// [`InviteResult::uses_remaining`](crate::InviteResult::uses_remaining) for what you actually
250    /// got rather than assuming the request was honoured verbatim.
251    pub async fn invite_multi(
252        &mut self,
253        services: Vec<String>,
254        app_label: Option<String>,
255        max_uses: Option<u32>,
256    ) -> Result<InviteResult, ClientError> {
257        self.invite_named(services, app_label, max_uses, None).await
258    }
259
260    /// Mint an invite, optionally under YOUR OWN local name for whoever redeems it (#87).
261    ///
262    /// `peer_nickname` overrides the name they claim for themselves — the fix for two same-model
263    /// machines that does not require the other person to rename theirs. Never sent to them, and
264    /// rejected alongside `max_uses > 1` (one name for every redeemer collides on the second).
265    pub async fn invite_named(
266        &mut self,
267        services: Vec<String>,
268        app_label: Option<String>,
269        max_uses: Option<u32>,
270        peer_nickname: Option<String>,
271    ) -> Result<InviteResult, ClientError> {
272        self.invite_full(services, app_label, max_uses, peer_nickname, false)
273            .await
274    }
275
276    /// Mint an invite, optionally as a SELF-ENROLLMENT (#86): the redeemer becomes another device
277    /// of YOU rather than a peer, so both present one identity.
278    ///
279    /// `as_self` requires an empty `services` and `max_uses` of 1 — it grants nothing, and a
280    /// multi-use identity invite is a standing offer to become you.
281    pub async fn invite_full(
282        &mut self,
283        services: Vec<String>,
284        app_label: Option<String>,
285        max_uses: Option<u32>,
286        peer_nickname: Option<String>,
287        as_self: bool,
288    ) -> Result<InviteResult, ClientError> {
289        self.request_typed(
290            Request::Invite(InviteParams {
291                services,
292                app_label,
293                max_uses,
294                peer_nickname,
295                as_self,
296            }),
297            "invite result",
298        )
299        .await
300    }
301
302    /// Produce an endorsement of `subject` for someone else to redeem (#65).
303    ///
304    /// Signs with THIS node's user key. It is a statement for the recipient — it changes nothing
305    /// about your own trust in the subject, and only resolves for someone paired with you.
306    pub async fn endorse_peer(
307        &mut self,
308        subject: &str,
309        subject_user_id: Option<String>,
310    ) -> Result<PeerEndorseResult, ClientError> {
311        self.request_typed(
312            Request::PeerEndorse(PeerEndorseParams {
313                subject: subject.to_string(),
314                subject_user_id,
315            }),
316            "peer endorse result",
317        )
318        .await
319    }
320
321    /// Dump the durable per-peer state this node carries for `peer` (#140), `api_minor >= 33`.
322    ///
323    /// The persisted dial hint verbatim, whether the DIAL actually uses it, the addresses inside it,
324    /// iroh's own view (`api_minor >= 56`), the pairing stamp and the live reachability row — one
325    /// capture, intended to be run on BOTH ends of a stuck pairing and compared.
326    ///
327    /// **Read-only, but NOT inert.** It probes nothing, dials nothing and writes nothing — but
328    /// reading iroh's view delivers a message to that remote's actor, which resets its ~60s idle
329    /// timer. Polling this keeps remote state alive (a selected path included) that would otherwise
330    /// be reaped.
331    ///
332    /// That matters for the one experiment this method exists to support: #140's step A is "close
333    /// every session, **wait >60s**, then probe". Poll during the wait and you preserve the very
334    /// state you are trying to clear, and get a false negative.
335    ///
336    /// Existed as a verb since 0.35.0 with no typed method here, so an embedder had to hand-build
337    /// the request — which the one embedder who needs it most (a node embedder debugging #140)
338    /// would have to do at exactly the wrong moment.
339    pub async fn peer_diagnostics(
340        &mut self,
341        peer: &str,
342    ) -> Result<PeerDiagnosticsResult, ClientError> {
343        self.request_typed(
344            Request::PeerDiagnostics(PeerDiagnosticsParams {
345                peer: peer.to_string(),
346            }),
347            "peer diagnostics result",
348        )
349        .await
350    }
351
352    /// Forget this node's stored dial hint for `peer` (#140), `api_minor >= 59`.
353    ///
354    /// The hint is the only durable per-peer state on this node's disk that the dial path reads, and
355    /// the only thing a long-lived pairing carries that a freshly paired identity does not — so
356    /// clearing it makes the pairing address like a fresh one. Advisory, never authorization: the
357    /// peer row, its `user_id`, its services and its pairing stamp are untouched, and an absent hint
358    /// is a supported state (the dial degrades to id-only). Errors for an unknown peer; `cleared`
359    /// is `false` for a known peer that had no hint.
360    pub async fn peer_hint_clear(
361        &mut self,
362        peer: &str,
363    ) -> Result<PeerHintClearResult, ClientError> {
364        self.request_typed(
365            Request::PeerHintClear(PeerHintClearParams {
366                peer: peer.to_string(),
367            }),
368            "peer hint clear result",
369        )
370        .await
371    }
372
373    /// Install a peer from an endorsement by someone you are already paired with (#65).
374    ///
375    /// Installs IDENTITY, not authorization — the peer becomes resolvable and is granted nothing.
376    /// `subject_user_id` requires `subject_binding`, the subject's OWN device→user binding: a
377    /// `user_id` is authorization-bearing and public, so an endorser alone must not attach one.
378    pub async fn introduce_peer(&mut self, params: PeerIntroduceParams) -> Result<(), ClientError> {
379        self.request_ack(Request::PeerIntroduce(params)).await
380    }
381
382    /// Redeem a pairing invite; return the inviter's suggested nickname, the display-only SAS
383    /// code, and the granted services.
384    pub async fn pair(&mut self, invite_line: &str) -> Result<PairResult, ClientError> {
385        self.pair_as(invite_line, None).await
386    }
387
388    /// Redeem an invite, optionally under YOUR OWN local name for the inviter (#87).
389    ///
390    /// `as_nickname` overrides the name the invite suggests. Use it when that name is already
391    /// taken locally — otherwise the pairing is refused and the only other fixes are asking the
392    /// inviter to re-mint or renaming your existing peer. It does not bypass the collision check:
393    /// an alias that itself collides is refused the same way.
394    pub async fn pair_as(
395        &mut self,
396        invite_line: &str,
397        as_nickname: Option<String>,
398    ) -> Result<PairResult, ClientError> {
399        self.pair_opts(invite_line, as_nickname, false).await
400    }
401
402    /// Redeem an invite, stating whether a SELF-ENROLLMENT is a ceremony you offered (#178).
403    ///
404    /// [`pair`](Self::pair) and [`pair_as`](Self::pair_as) pass `false`, so a `mcpmesh-enroll:` line
405    /// pasted into an ordinary "join" field is refused with
406    /// [`ERR_SELF_ENROLL_NOT_OFFERED`](crate::ERR_SELF_ENROLL_NOT_OFFERED) before anything is
407    /// dialled — the invite survives, so the same line still works once the person is offered the
408    /// real choice. Pass `true` only from a path that actually means "add another of my own
409    /// devices": the ceremony writes a device→user binding that is irrevocable short of rotating
410    /// the user key.
411    ///
412    /// `mcpmesh_node::pairing::is_enrollment_line` answers which kind of line you are holding without
413    /// dialling, for a UI that wants to PROMPT rather than recover from a refusal.
414    pub async fn pair_opts(
415        &mut self,
416        invite_line: &str,
417        as_nickname: Option<String>,
418        allow_self_enroll: bool,
419    ) -> Result<PairResult, ClientError> {
420        self.request_typed(
421            Request::Pair(PairParams {
422                invite_line: invite_line.to_string(),
423                as_nickname,
424                allow_self_enroll,
425            }),
426            "pair result",
427        )
428        .await
429    }
430
431    /// Unpair a peer by nickname: drops its identity row AND its every-`allow` membership
432    /// (idempotent; live sessions are not severed). The daemon acks; the ack body is discarded.
433    pub async fn peer_remove(&mut self, nickname: &str) -> Result<(), ClientError> {
434        self.request_ack(Request::PeerRemove(PeerRemoveParams {
435            nickname: nickname.to_string(),
436        }))
437        .await
438    }
439
440    /// Rename a contact's nickname to `to` — every device sharing `user_id` when given, else the
441    /// single provisional `nickname` entry — carrying its grants along. The daemon refuses (a
442    /// [`ClientError::Api`]) when `to` is empty or already names a different identity. The daemon
443    /// acks; the ack body is discarded.
444    pub async fn peer_rename(
445        &mut self,
446        user_id: Option<String>,
447        nickname: Option<String>,
448        to: &str,
449    ) -> Result<(), ClientError> {
450        self.request_ack(Request::PeerRename(PeerRenameParams {
451            user_id,
452            nickname,
453            to: to.to_string(),
454        }))
455        .await
456    }
457
458    /// Install a signed roster from the LOCAL file at `path` (`org_root_pk` pins the org root on
459    /// FIRST install); return the installed org id + serial + severed-session count.
460    pub async fn roster_install(
461        &mut self,
462        path: &str,
463        org_root_pk: Option<String>,
464    ) -> Result<RosterInstallResult, ClientError> {
465        self.request_typed(
466            Request::RosterInstall(RosterInstallParams {
467                path: path.to_string(),
468                org_root_pk,
469            }),
470            "roster_install result",
471        )
472        .await
473    }
474
475    /// Read the installed roster's MEMBERSHIP (#93): the declared groups, and every person with
476    /// their display name, groups, and devices.
477    ///
478    /// Distinct from [`status`](Self::status)'s `presence`, which enumerates reachable DEVICES and
479    /// omits a person entirely when none of theirs is up. This is the member list — everyone the
480    /// roster carries, with `online` per device, so one read serves both questions.
481    ///
482    /// Advisory: display and authoring input, never an authorization answer. Empty in a
483    /// pure-pairing daemon and before the first roster is installed. `api_minor >= 46`.
484    pub async fn roster_members(
485        &mut self,
486    ) -> Result<crate::protocol::RosterMembersResult, ClientError> {
487        self.request_typed(Request::RosterMembers, "roster_members result")
488            .await
489    }
490
491    /// AUTHOR an org (#66): mint this node's org root key, sign an empty roster, install it (which
492    /// pins the root), and return the copyable invite plus the root's fingerprint.
493    ///
494    /// **One-time per node** — a second call is refused rather than replacing the key, which would
495    /// orphan every roster already signed with it.
496    ///
497    /// Show `org_root_fingerprint` to the operator: it is what every joiner reads back
498    /// out-of-band, and it is the only thing anchoring their trust in the org. `api_minor >= 46`.
499    pub async fn org_create(
500        &mut self,
501        name: &str,
502        expires_secs: Option<i64>,
503        roster_url: Option<String>,
504    ) -> Result<crate::protocol::OrgCreateResult, ClientError> {
505        self.request_typed(
506            Request::OrgCreate(crate::protocol::OrgCreateParams {
507                name: name.to_string(),
508                expires_secs,
509                roster_url,
510            }),
511            "org_create result",
512        )
513        .await
514    }
515
516    /// APPROVE a join code into the roster (#66): verify its device→user-key binding, add the
517    /// member with `groups`, re-sign, install.
518    ///
519    /// **The result's `join_code_fingerprint` is not decoration.** Nothing in a join code binds it
520    /// to a human, so a substituted code is caught by the two people comparing that fingerprint
521    /// out-of-band, or it is not caught at all. Show it and have the operator confirm it.
522    ///
523    /// Each group must already be declared in the roster; an undeclared one is refused. `user_id`
524    /// overrides the id the joiner requested — worth using, since that id is chosen by the person
525    /// being approved and is what every `allow` entry will name. `api_minor >= 46`.
526    pub async fn org_approve(
527        &mut self,
528        join_code: &str,
529        groups: Vec<String>,
530        user_id: Option<String>,
531    ) -> Result<crate::protocol::OrgApproveResult, ClientError> {
532        self.request_typed(
533            Request::OrgApprove(crate::protocol::OrgApproveParams {
534                join_code: join_code.to_string(),
535                groups,
536                user_id,
537            }),
538            "org_approve result",
539        )
540        .await
541    }
542
543    /// Rotate the org root (#93 ask c), publishing a bridge members adopt as they receive it.
544    pub async fn org_rotate(
545        &mut self,
546        new_key_path: Option<String>,
547    ) -> Result<crate::protocol::OrgRotateResult, ClientError> {
548        self.request_typed(
549            Request::OrgRotate(crate::protocol::OrgRotateParams { new_key_path }),
550            "org_rotate result",
551        )
552        .await
553    }
554
555    /// Mint an attestation offer (#85 ask 3) — where another of this person's devices should dial.
556    pub async fn attest_offer(
557        &mut self,
558    ) -> Result<crate::protocol::AttestOfferResult, ClientError> {
559        self.request_typed(Request::AttestOffer, "attest_offer result")
560            .await
561    }
562
563    /// Present this device's identity to a peer, using their `mcpmesh-attest:` line (#85 ask 3).
564    pub async fn attest_to(
565        &mut self,
566        offer: impl Into<String>,
567    ) -> Result<crate::protocol::PairResult, ClientError> {
568        self.request_typed(
569            Request::AttestTo(crate::protocol::AttestToParams {
570                offer: offer.into(),
571            }),
572            "attest_to result",
573        )
574        .await
575    }
576
577    /// Refuse a peer's device on this node (#85 ask 4). Immediate: live sessions are severed.
578    pub async fn peer_revoke(
579        &mut self,
580        peer: impl Into<String>,
581        reason: Option<String>,
582    ) -> Result<crate::protocol::PeerRevokeResult, ClientError> {
583        self.request_typed(
584            Request::PeerRevoke(crate::protocol::PeerRevokeParams {
585                peer: peer.into(),
586                reason,
587            }),
588            "peer_revoke result",
589        )
590        .await
591    }
592
593    /// Lift a local revocation (#85 ask 4). Idempotent.
594    pub async fn peer_unrevoke(
595        &mut self,
596        peer: impl Into<String>,
597    ) -> Result<crate::protocol::PeerUnrevokeResult, ClientError> {
598        self.request_typed(
599            Request::PeerUnrevoke(crate::protocol::PeerUnrevokeParams { peer: peer.into() }),
600            "peer_unrevoke result",
601        )
602        .await
603    }
604
605    /// Sign a portable revocation of one of THIS person's own devices (#85 ask 4).
606    pub async fn device_revoke(
607        &mut self,
608        endpoint: impl Into<String>,
609        reason: Option<String>,
610    ) -> Result<crate::protocol::DeviceRevokeResult, ClientError> {
611        self.request_typed(
612            Request::DeviceRevoke(crate::protocol::DeviceRevokeParams {
613                endpoint: endpoint.into(),
614                reason,
615            }),
616            "device_revoke result",
617        )
618        .await
619    }
620
621    /// Apply a peer's signed device revocation (#85 ask 4).
622    pub async fn device_revocation_import(
623        &mut self,
624        token: impl Into<String>,
625    ) -> Result<crate::protocol::DeviceRevocationImportResult, ClientError> {
626        self.request_typed(
627            Request::DeviceRevocationImport(crate::protocol::DeviceRevocationImportParams {
628                token: token.into(),
629            }),
630            "device_revocation_import result",
631        )
632        .await
633    }
634
635    /// EXPORT this node's user key as a RECOVERY PHRASE (#85 ask 2).
636    ///
637    /// **The phrase is the private key**, in a form a person can write down. Anyone who reads it
638    /// can present this identity. Show it once, to the person who owns it, and do not persist it
639    /// anywhere you would not persist the key file. It is deliberately not logged or audited by the
640    /// daemon; this response is the only place it exists.
641    ///
642    /// `user_id` is safe to display and record — compare it after an import to confirm the right
643    /// identity came back. `api_minor >= 48`.
644    pub async fn user_key_export(
645        &mut self,
646    ) -> Result<crate::protocol::UserKeyExportResult, ClientError> {
647        self.request_typed(Request::UserKeyExport, "user_key_export result")
648            .await
649    }
650
651    /// IMPORT a user key from a recovery phrase (#85 ask 2), so a person's `b64u:` survives the
652    /// hardware.
653    ///
654    /// Refuses to overwrite an existing key unless `replace` is set: importing over a live key
655    /// discards the identity this node presents, irreversibly without that key's own phrase.
656    ///
657    /// **Check the returned `user_id` against the one you are recovering.** The phrase's checksum
658    /// catches most transcription errors, but the `user_id` is the definitive answer, and the only
659    /// thing that distinguishes "restored the wrong key" from "my peers have not seen me yet".
660    ///
661    /// It does NOT get this device admitted by anyone: peers authorize per DEVICE, and a restored
662    /// user key does not put this endpoint in anybody's allowlist. That is #85 ask 3, not shipped.
663    /// `api_minor >= 48`.
664    pub async fn user_key_import(
665        &mut self,
666        recovery_phrase: &str,
667        replace: bool,
668    ) -> Result<crate::protocol::UserKeyImportResult, ClientError> {
669        self.request_typed(
670            Request::UserKeyImport(crate::protocol::UserKeyImportParams {
671                recovery_phrase: recovery_phrase.to_string(),
672                replace,
673            }),
674            "user_key_import result",
675        )
676        .await
677    }
678
679    /// INSPECT a join code without approving it (#66): what it claims, and the fingerprint that
680    /// decides whether to believe it. Read-only — nothing is signed or installed.
681    ///
682    /// **Call this before [`org_approve`](Self::org_approve), show
683    /// `join_code_fingerprint`, and have the operator confirm it out-of-band.** Nothing in a join
684    /// code binds it to a person; a substituted one carries a different key and diverges here. The
685    /// fingerprint on the approval RESULT is the same words, but by then the member is in the
686    /// signed roster — too late to decline.
687    ///
688    /// The claims (`display_name`, `requested_user_id`, `device_label`) are chosen by the sender.
689    /// Render them; do not trust them. A forged binding is refused rather than described.
690    /// `api_minor >= 46`.
691    pub async fn org_join_code(
692        &mut self,
693        join_code: &str,
694    ) -> Result<crate::protocol::OrgJoinCodeResult, ClientError> {
695        self.request_typed(
696            Request::OrgJoinCode(crate::protocol::OrgJoinCodeParams {
697                join_code: join_code.to_string(),
698            }),
699            "org_join_code result",
700        )
701        .await
702    }
703
704    /// REVOKE from the roster (#66) — and sever the cut devices' live sessions, immediately.
705    ///
706    /// Three readings, and picking the wrong one is destructive, so the result reports which
707    /// `mode` was applied: `"<user_id>/<label>"` cuts ONE device; a bare `user_id` removes the
708    /// person and revokes ALL their devices; `user_key = true` is a key ROTATION — the person is
709    /// removed but their devices stay un-revoked so the same hardware re-enrolls under a fresh
710    /// user key. `api_minor >= 46`.
711    pub async fn org_revoke(
712        &mut self,
713        target: &str,
714        user_key: bool,
715    ) -> Result<crate::protocol::OrgRevokeResult, ClientError> {
716        self.request_typed(
717            Request::OrgRevoke(crate::protocol::OrgRevokeParams {
718                target: target.to_string(),
719                user_key,
720            }),
721            "org_revoke result",
722        )
723        .await
724    }
725
726    /// Pin the org root on a JOINER (no roster yet). `user_key` is a LOCAL path — the key never
727    /// crosses the API. Returns the pinned org id.
728    pub async fn org_join(
729        &mut self,
730        org_id: &str,
731        org_root_pk: &str,
732        user_id: &str,
733        user_key: &str,
734    ) -> Result<OrgJoinResult, ClientError> {
735        self.request_typed(
736            Request::OrgJoin(OrgJoinParams {
737                org_id: org_id.to_string(),
738                org_root_pk: org_root_pk.to_string(),
739                user_id: user_id.to_string(),
740                user_key: user_key.to_string(),
741            }),
742            "org_join result",
743        )
744        .await
745    }
746
747    /// Pin the HTTPS roster URL (`[roster].url`) in the daemon's config. The daemon acks; the
748    /// ack body is discarded.
749    pub async fn set_roster_url(&mut self, url: &str) -> Result<(), ClientError> {
750        self.request_ack(Request::SetRosterUrl(SetRosterUrlParams {
751            url: url.to_string(),
752        }))
753        .await
754    }
755
756    /// Discover which services a paired `peer` (a nickname, `eid:`, or `b64u:`) CURRENTLY grants
757    /// the caller (#52) — dials the peer and returns the service names its allow admits for the
758    /// caller's principal (only your own admitted services, never the peer's full registry).
759    pub async fn peer_services(&mut self, peer: &str) -> Result<Vec<String>, ClientError> {
760        self.request_typed::<PeerServicesResult>(
761            Request::PeerServices(PeerServicesParams {
762                peer: peer.to_string(),
763            }),
764            "peer_services",
765        )
766        .await
767        .map(|r| r.services)
768    }
769
770    /// Remove a service registration (#50) — the deregistration mirror of `register_service`.
771    /// Removes the whole entry (allow included) + any ephemeral registration of the name, then
772    /// hot-reloads. Idempotent: an unknown name is a clean no-op.
773    pub async fn unregister_service(&mut self, name: &str) -> Result<(), ClientError> {
774        self.request_ack(Request::UnregisterService(UnregisterServiceParams {
775            name: name.to_string(),
776        }))
777        .await
778    }
779
780    /// Grant a stable `principal` (`b64u:`/`eid:`) access to `service` WITHOUT (re)pairing (#44)
781    /// — the per-peer "sharing on" toggle. Idempotent; an unknown service is a clean no-op.
782    pub async fn service_allow_grant(
783        &mut self,
784        service: &str,
785        principal: &str,
786    ) -> Result<(), ClientError> {
787        self.request_ack(Request::ServiceAllowGrant(ServiceAllowParams {
788            service: service.to_string(),
789            principal: principal.to_string(),
790        }))
791        .await
792    }
793
794    /// Revoke a stable `principal` from `service`'s allow WITHOUT unpairing (#44) — the
795    /// "sharing off" toggle. The peer's identity row is untouched; it just cannot open NEW
796    /// sessions (in-flight ones run to completion). Idempotent.
797    pub async fn service_allow_revoke(
798        &mut self,
799        service: &str,
800        principal: &str,
801    ) -> Result<(), ClientError> {
802        self.request_ack(Request::ServiceAllowRevoke(ServiceAllowParams {
803            service: service.to_string(),
804            principal: principal.to_string(),
805        }))
806        .await
807    }
808
809    /// Set this node's opaque app-metadata blob (#39, roster mode): ≤256 bytes, folded
810    /// signed into each presence heartbeat so paired peers read it in `status` presence —
811    /// no per-peer session. `""` clears it; in-memory (re-set on startup).
812    pub async fn set_app_metadata(&mut self, metadata: &str) -> Result<(), ClientError> {
813        self.request_ack(Request::SetAppMetadata(SetAppMetadataParams {
814            metadata: metadata.to_string(),
815        }))
816        .await
817    }
818
819    /// Set this node's CUSTOM relay set LIVE (#53). `relay_urls` is the desired set (each must
820    /// parse as an iroh `RelayUrl`; empty is rejected). When the node is already in
821    /// `relay_mode = "custom"`, the daemon diffs against the running endpoint and applies the
822    /// delta live (iroh `insert_relay`/`remove_relay`) — no restart, no dropped sessions — then
823    /// persists `[network]`. When the node is currently `default`/`disabled`, the config is
824    /// persisted but the live mode transition isn't possible: the returned
825    /// [`SetRelaysResult::restart_required`] is `true`. Idempotent (an unchanged set → `changed:
826    /// false`, no writes).
827    pub async fn set_relays(
828        &mut self,
829        relay_urls: &[String],
830    ) -> Result<SetRelaysResult, ClientError> {
831        self.request_typed::<SetRelaysResult>(
832            Request::SetRelays(SetRelaysParams {
833                relay_urls: relay_urls.to_vec(),
834            }),
835            "set_relays",
836        )
837        .await
838    }
839
840    /// Rename this node LIVE (#37): the daemon validates + persists `[identity].nickname`
841    /// under its own config lock and updates the name future invites present — no restart.
842    /// Peers keep their stored pairing-time nickname until a re-invite (display-only).
843    pub async fn set_nickname(&mut self, nickname: &str) -> Result<(), ClientError> {
844        self.request_ack(Request::SetNickname(SetNicknameParams {
845            nickname: nickname.to_string(),
846        }))
847        .await
848    }
849
850    /// Summarize the daemon's LOCAL audit log into per-peer / per-service session counts
851    /// (local-only — nothing is transmitted).
852    pub async fn audit_summary(&mut self) -> Result<AuditSummaryResult, ClientError> {
853        self.request_typed(Request::AuditSummary, "audit_summary result")
854            .await
855    }
856
857    /// Publish a local file into `scope`; return the minted `mcpmesh/blob/1` ticket + hash.
858    pub async fn blob_publish(
859        &mut self,
860        scope: &str,
861        path: &str,
862    ) -> Result<BlobPublishResult, ClientError> {
863        self.request_typed(
864            Request::BlobPublish(BlobPublishParams {
865                scope: scope.to_string(),
866                path: path.to_string(),
867            }),
868            "blob_publish result",
869        )
870        .await
871    }
872
873    /// List the daemon's blob scopes (name → hashes + grants + withdrawn).
874    ///
875    /// A DEFAULT LIMIT applies (#84b) — check `truncated` and page with
876    /// [`blob_list_paged`](Self::blob_list_paged) rather than assuming you saw everything.
877    pub async fn blob_list(&mut self) -> Result<BlobScopeList, ClientError> {
878        self.blob_list_paged(Default::default()).await
879    }
880
881    /// List blob scopes with filters + paging (#84b, `api_minor >= 20`).
882    pub async fn blob_list_paged(
883        &mut self,
884        params: crate::BlobListParams,
885    ) -> Result<BlobScopeList, ClientError> {
886        self.request_typed(Request::BlobList(params), "blob_list result")
887            .await
888    }
889
890    /// Fetch a `mcpmesh/blob/1` ticket THROUGH the daemon (BLAKE3-verified), export to
891    /// `dest_path`; return the verified hash + byte length.
892    pub async fn blob_fetch(
893        &mut self,
894        ticket: &str,
895        dest_path: &str,
896    ) -> Result<BlobFetchResult, ClientError> {
897        self.blob_fetch_from(ticket, dest_path, Vec::new()).await
898    }
899
900    /// [`blob_fetch`](Self::blob_fetch) with ADDITIONAL sources to try when the ticket's publisher
901    /// does not answer (#83).
902    ///
903    /// Content addressing makes every recipient a potential source; a single-address ticket made
904    /// that unusable, so a file shared with a room became unfetchable the moment the sender closed
905    /// their laptop — even though others in the room already held the identical verified bytes.
906    ///
907    /// `from` takes stable principals (`eid:`, `b64u:`) or paired nicknames — the same vocabulary
908    /// `open_session` takes, and naming a PERSON offers every device of theirs. They are tried in
909    /// order, **after** the publisher, so a live publisher costs nothing and an offline one costs
910    /// one dial timeout.
911    ///
912    /// **The bytes are BLAKE3-verified against the ticket's hash whoever serves them**, so an
913    /// alternate cannot substitute content. It can refuse: an alternate serves only hashes it has
914    /// republished into a scope that grants you (see `blob_republish`), and an ungranted one
915    /// answers a permission error and the fetch moves on. Every failure mode falls through, not
916    /// only an unreachable dial — a refusal, a missing hash, a reset, and a stalled transfer all
917    /// move to the next source. `api_minor >= 47`.
918    pub async fn blob_fetch_from(
919        &mut self,
920        ticket: &str,
921        dest_path: &str,
922        from: Vec<String>,
923    ) -> Result<BlobFetchResult, ClientError> {
924        self.request_typed(
925            Request::BlobFetch(BlobFetchParams {
926                ticket: ticket.to_string(),
927                dest_path: dest_path.to_string(),
928                from,
929            }),
930            "blob_fetch result",
931        )
932        .await
933    }
934
935    /// Stop every in-flight [`blob_fetch`](Self::blob_fetch) of `hash` (#172).
936    ///
937    /// **Send this on a DIFFERENT connection than the fetch it cancels.** This client is one
938    /// request at a time — `&mut self` is borrowed until the fetch answers — so a cancel issued on
939    /// the same client can only run after the thing it would cancel is already over. The cancelled
940    /// fetch answers [`ERR_CANCELLED`](crate::ERR_CANCELLED) on its own connection.
941    ///
942    /// `cancelled: false` means nothing was fetching that blob here. That is the honest answer to a
943    /// cancel that raced a fetch to completion, not an error.
944    ///
945    /// Needs `api_minor >= 44`; below it the method is unknown.
946    pub async fn blob_fetch_cancel(
947        &mut self,
948        hash: &str,
949    ) -> Result<BlobFetchCancelResult, ClientError> {
950        self.request_typed(
951            Request::BlobFetchCancel(BlobFetchCancelParams {
952                hash: hash.to_string(),
953            }),
954            "blob_fetch_cancel result",
955        )
956        .await
957    }
958
959    /// Grant a scope to a principal — any flat-namespace entry: a group name, a user_id,
960    /// or a nickname (the shared `principal_set` expansion).
961    /// The daemon acks; the ack body is discarded (a JSON-RPC error surfaces as
962    /// `ClientError::Api`). Granting a scope to your own user_id reaches ALL of that
963    /// person's devices.
964    pub async fn blob_grant(&mut self, scope: &str, principal: &str) -> Result<(), ClientError> {
965        self.request_ack(Request::BlobGrant(BlobGrantParams {
966            scope: scope.to_string(),
967            principal: principal.to_string(),
968        }))
969        .await
970    }
971
972    /// The TYPED `subscribe` upgrade: send [`Request::Subscribe`] (after which the connection
973    /// stops being request/response — see [`open_stream`](Self::open_stream)) and return a
974    /// [`StreamSubscription`] yielding [`StreamFrame`]s. For raw frames (e.g. to tolerate frame
975    /// types newer than this crate), use `open_stream("subscribe")` instead.
976    pub async fn subscribe(self) -> Result<StreamSubscription, ClientError> {
977        let (reader, writer) = self.open_stream("subscribe").await?;
978        Ok(StreamSubscription {
979            reader,
980            _writer: writer,
981        })
982    }
983}
984
985/// A live [`Request::Subscribe`] stream yielding typed [`StreamFrame`]s (snapshot, then
986/// events/lagged notices) until the daemon side closes. Holds the connection's write half for its
987/// lifetime — a subscriber only reads, but dropping the writer would half-close the socket. Drop
988/// the subscription to disconnect (there is no request channel back).
989pub struct StreamSubscription {
990    reader: FrameReader<ControlRead>,
991    _writer: ControlWrite,
992}
993
994/// Hand-rolled like [`ControlClient`]'s: the boxed transport halves are not `Debug`.
995impl std::fmt::Debug for StreamSubscription {
996    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
997        f.debug_struct("StreamSubscription").finish_non_exhaustive()
998    }
999}
1000
1001impl StreamSubscription {
1002    /// The next frame, or `None` when the daemon closed the stream. A frame this crate's
1003    /// [`StreamFrame`] does not model (a NEWER daemon's frame type) surfaces as
1004    /// [`ClientError::Malformed`] — a forward-compatible consumer reads raw frames via
1005    /// [`ControlClient::open_stream`] instead.
1006    pub async fn next(&mut self) -> Result<Option<StreamFrame>, ClientError> {
1007        match self.reader.next().await? {
1008            Some(Inbound::Frame(v)) => serde_json::from_value(v)
1009                .map(Some)
1010                .map_err(|_| ClientError::Malformed("stream frame")),
1011            Some(Inbound::Violation(_)) => Err(ClientError::Malformed("stream frame")),
1012            None => Ok(None),
1013        }
1014    }
1015}
1016
1017/// Complete the mcpmesh-local/1 hello handshake over ALREADY-CONNECTED byte halves —
1018/// the transport-agnostic core of [`connect_control`], and the front door for in-process
1019/// embedding (`mcpmesh-node`'s `Node::control` dials a tokio duplex through here).
1020pub async fn connect_control_io(
1021    reader: impl tokio::io::AsyncRead + Send + Unpin + 'static,
1022    writer: impl tokio::io::AsyncWrite + Send + Unpin + 'static,
1023) -> Result<ControlClient, ClientError> {
1024    let mut reader = FrameReader::new(Box::new(reader) as ControlRead, MAX_FRAME_BYTES);
1025    let hello: Hello = match reader.next().await? {
1026        Some(Inbound::Frame(v)) => {
1027            serde_json::from_value(v).map_err(|_| ClientError::Malformed("hello"))?
1028        }
1029        Some(Inbound::Violation(_)) => return Err(ClientError::Malformed("hello")),
1030        None => return Err(ClientError::Closed("hello")),
1031    };
1032    if hello.api != crate::protocol::API_NAME {
1033        return Err(ClientError::WrongApi {
1034            got: hello.api,
1035            want: crate::protocol::API_NAME,
1036        });
1037    }
1038    Ok(ControlClient {
1039        hello,
1040        reader,
1041        writer: Box::new(writer) as ControlWrite,
1042    })
1043}
1044
1045/// Connect + complete the hello handshake, asserting the api name is `mcpmesh-local/1`.
1046pub async fn connect_control(path: &Path) -> Result<ControlClient, ClientError> {
1047    let stream = connect_local(path).await?;
1048    let (read_half, write_half) = split_local(stream);
1049    connect_control_io(read_half, write_half).await
1050}
1051
1052/// [`connect_control`] at the platform default endpoint ([`crate::paths::default_endpoint`]):
1053/// the quickstart front door — a consumer dials the running daemon without reimplementing
1054/// the platform endpoint rule. Resolution failure surfaces as [`ClientError::Io`]
1055/// (`NotFound`), same as a daemon that is not running.
1056pub async fn connect_control_default() -> Result<ControlClient, ClientError> {
1057    connect_control(&crate::paths::default_endpoint()?).await
1058}
1059
1060// Seam-ported (Task 6): every stub daemon binds via the platform seam
1061// (`transport::bind_local` + `LocalListener::accept`) rather than a raw `UnixListener`,
1062// so these exercise the platform-identical `ControlClient` on BOTH unix (UDS) and windows
1063// (named pipe). Gated on `feature = "service"` (bind needs it) rather than `unix`: under
1064// `cargo test --workspace` feature unification turns `service` on for this crate (cli
1065// depends on local-api with features=["service"]), so the module compiles and RUNS on the
1066// windows CI leg. `test_endpoint` yields a platform-appropriate unique endpoint.
1067#[cfg(all(test, feature = "service"))]
1068mod tests {
1069    use super::*;
1070    use crate::protocol::{API_NAME, API_VERSION, BackendKind, ServiceInfo, StatusResult};
1071    use crate::transport::{LocalListener, bind_local, split_local};
1072    use tokio::io::AsyncWriteExt;
1073
1074    /// A unique local endpoint for a stub daemon, platform-appropriate: a tempdir socket
1075    /// path on unix, a per-process-unique `\\.\pipe\…` name on windows. Returns the
1076    /// endpoint plus a guard that MUST outlive the listener (the `TempDir` on unix; unit
1077    /// on windows, whose pipe namespace needs no filesystem cleanup).
1078    #[cfg(unix)]
1079    fn test_endpoint(tag: &str) -> (std::path::PathBuf, tempfile::TempDir) {
1080        let dir = tempfile::tempdir().unwrap();
1081        let path = dir.path().join(format!("{tag}.sock"));
1082        (path, dir)
1083    }
1084    #[cfg(windows)]
1085    fn test_endpoint(tag: &str) -> (std::path::PathBuf, ()) {
1086        use std::sync::atomic::{AtomicU64, Ordering};
1087        static SEQ: AtomicU64 = AtomicU64::new(0);
1088        let n = SEQ.fetch_add(1, Ordering::Relaxed);
1089        let path = std::path::PathBuf::from(format!(
1090            r"\\.\pipe\mcpmesh-client-test-{}-{tag}-{n}",
1091            std::process::id()
1092        ));
1093        (path, ())
1094    }
1095
1096    /// A stub mcpmesh daemon: send Hello, then answer one `status` with a StatusResult.
1097    async fn stub_daemon(mut listener: LocalListener) {
1098        let stream = listener.accept().await.unwrap();
1099        let (read_half, mut writer) = split_local(stream);
1100        write_frame(
1101            &mut writer,
1102            &serde_json::to_value(Hello {
1103                api: API_NAME.into(),
1104                api_version: API_VERSION.into(),
1105                api_minor: 0,
1106                stack_version: "0.1.0".into(),
1107            })
1108            .unwrap(),
1109        )
1110        .await
1111        .unwrap();
1112        let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
1113        let req = match reader.next().await.unwrap().unwrap() {
1114            Inbound::Frame(v) => v,
1115            Inbound::Violation(_) => panic!("violation"),
1116        };
1117        assert_eq!(req["method"], "status");
1118        let result = StatusResult {
1119            stack_version: "0.1.0".into(),
1120            services: vec![ServiceInfo {
1121                name: "kb".into(),
1122                allow: vec![],
1123                allow_display: vec![],
1124                backend: BackendKind::Socket,
1125                ephemeral: false,
1126            }],
1127            peers: vec![],
1128            roster: None,
1129            presence: vec![],
1130            self_user_id: None,
1131            recent_pairings: vec![],
1132            reachability: vec![],
1133            self_nickname: String::new(),
1134            storage: None,
1135            revoked: Vec::new(),
1136            self_network: None,
1137        };
1138        write_frame(
1139            &mut writer,
1140            &serde_json::json!({ "jsonrpc": "2.0", "id": 1, "result": result }),
1141        )
1142        .await
1143        .unwrap();
1144        writer.flush().await.unwrap();
1145    }
1146
1147    /// The transport-agnostic front door: the same hello handshake over a plain in-memory
1148    /// duplex — what an embedded node's `Node::control` dials through.
1149    #[tokio::test]
1150    async fn connect_control_io_handshakes_over_a_duplex() {
1151        let (client_io, mut server_io) = tokio::io::duplex(4096);
1152        tokio::spawn(async move {
1153            write_frame(
1154                &mut server_io,
1155                &serde_json::to_value(Hello {
1156                    api: API_NAME.into(),
1157                    api_version: API_VERSION.into(),
1158                    api_minor: 0,
1159                    stack_version: "in-proc".into(),
1160                })
1161                .unwrap(),
1162            )
1163            .await
1164            .unwrap();
1165        });
1166        let (r, w) = tokio::io::split(client_io);
1167        let client = connect_control_io(r, w).await.expect("handshake");
1168        assert_eq!(client.hello().stack_version, "in-proc");
1169    }
1170
1171    #[tokio::test]
1172    async fn connect_reads_hello_asserts_api_and_requests() {
1173        let (sock, _guard) = test_endpoint("status");
1174        let listener = bind_local(&sock).unwrap();
1175        let server = tokio::spawn(stub_daemon(listener));
1176
1177        let mut client = connect_control(&sock).await.unwrap();
1178        assert_eq!(client.hello().api, API_NAME);
1179        let result = client.request(Request::Status).await.unwrap();
1180        assert_eq!(result["services"][0]["name"], "kb");
1181        assert_eq!(result["services"][0]["backend"], "socket");
1182        server.await.unwrap();
1183    }
1184
1185    #[tokio::test]
1186    async fn wrong_api_hello_is_rejected() {
1187        let (sock, _guard) = test_endpoint("wrongapi");
1188        let listener = bind_local(&sock).unwrap();
1189        tokio::spawn(async move {
1190            let mut listener = listener;
1191            let stream = listener.accept().await.unwrap();
1192            let (_r, mut w) = split_local(stream);
1193            write_frame(
1194                &mut w,
1195                &serde_json::json!({"api":"other/1","api_version":"1.0","stack_version":"0"}),
1196            )
1197            .await
1198            .unwrap();
1199            w.flush().await.unwrap();
1200        });
1201        match connect_control(&sock).await {
1202            Err(ClientError::WrongApi { got, want }) => {
1203                assert_eq!(got, "other/1");
1204                assert_eq!(want, API_NAME);
1205            }
1206            other => panic!("expected WrongApi, got {other:?}"),
1207        }
1208    }
1209
1210    #[tokio::test]
1211    async fn blob_fetch_and_publish_deserialize_typed_results() {
1212        use crate::protocol::{BlobFetchResult, BlobPublishResult};
1213        let (sock, _guard) = test_endpoint("blob");
1214        let listener = bind_local(&sock).unwrap();
1215        let server = tokio::spawn(async move {
1216            let mut listener = listener;
1217            let stream = listener.accept().await.unwrap();
1218            let (read_half, mut writer) = split_local(stream);
1219            write_frame(
1220                &mut writer,
1221                &serde_json::to_value(Hello {
1222                    api: API_NAME.into(),
1223                    api_version: API_VERSION.into(),
1224                    api_minor: 0,
1225                    stack_version: "0.1.0".into(),
1226                })
1227                .unwrap(),
1228            )
1229            .await
1230            .unwrap();
1231            let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
1232            // First request: blob_publish -> a ticket + hash.
1233            let req = match reader.next().await.unwrap().unwrap() {
1234                Inbound::Frame(v) => v,
1235                Inbound::Violation(_) => panic!("violation"),
1236            };
1237            assert_eq!(req["method"], "blob_publish");
1238            assert_eq!(req["params"]["scope"], "eng");
1239            write_frame(
1240                &mut writer,
1241                &serde_json::json!({"jsonrpc":"2.0","id":1,"result":{"ticket":"blobT","hash":"ab"}}),
1242            )
1243            .await
1244            .unwrap();
1245            // Second request: blob_fetch -> a verified hash + length.
1246            let req = match reader.next().await.unwrap().unwrap() {
1247                Inbound::Frame(v) => v,
1248                Inbound::Violation(_) => panic!("violation"),
1249            };
1250            assert_eq!(req["method"], "blob_fetch");
1251            assert_eq!(req["params"]["ticket"], "blobT");
1252            assert_eq!(req["params"]["dest_path"], "/tmp/out.bin");
1253            write_frame(
1254                &mut writer,
1255                &serde_json::json!({"jsonrpc":"2.0","id":2,"result":{"hash":"cd","bytes_len":7}}),
1256            )
1257            .await
1258            .unwrap();
1259            let _ = (
1260                BlobFetchResult {
1261                    hash: "cd".into(),
1262                    bytes_len: 7,
1263                },
1264                BlobPublishResult {
1265                    ticket: "blobT".into(),
1266                    hash: "ab".into(),
1267                },
1268            );
1269        });
1270
1271        let mut client = connect_control(&sock).await.unwrap();
1272        let pub_res = client.blob_publish("eng", "/tmp/a.bin").await.unwrap();
1273        assert_eq!(pub_res.ticket, "blobT");
1274        assert_eq!(pub_res.hash, "ab");
1275        let fetch_res = client.blob_fetch("blobT", "/tmp/out.bin").await.unwrap();
1276        assert_eq!(fetch_res.hash, "cd");
1277        assert_eq!(fetch_res.bytes_len, 7);
1278        server.await.unwrap();
1279    }
1280
1281    /// Regression (lossless rebox): a frame the server PIPELINES in the same write as
1282    /// the Hello must survive `open_session` + kb's production re-box shape
1283    /// (`FrameReader::new(Box::new(reader.into_inner()), …)`, bridge/session.rs). Against
1284    /// the old `into_inner -> R` — which unwrapped the internal `BufReader` and DROPPED
1285    /// its read-ahead — the pipelined frame vanished and this test failed (EOF instead of
1286    /// the frame). `into_inner -> BufReader<R>` carries the read-ahead across the rebox.
1287    #[tokio::test]
1288    async fn frame_pipelined_behind_hello_survives_open_session_rebox() {
1289        use tokio::io::AsyncRead;
1290
1291        let (sock, _guard) = test_endpoint("pipelined");
1292        let listener = bind_local(&sock).unwrap();
1293        let server = tokio::spawn(async move {
1294            let mut listener = listener;
1295            let stream = listener.accept().await.unwrap();
1296            let (read_half, mut writer) = split_local(stream);
1297            // ONE write carrying the Hello AND a session frame → both land in the
1298            // client's first BufReader fill (the read-ahead under test).
1299            let mut bytes = serde_json::to_vec(
1300                &serde_json::to_value(Hello {
1301                    api: API_NAME.into(),
1302                    api_version: API_VERSION.into(),
1303                    api_minor: 0,
1304                    stack_version: "0.1.0".into(),
1305                })
1306                .unwrap(),
1307            )
1308            .unwrap();
1309            bytes.push(b'\n');
1310            bytes.extend_from_slice(b"{\"jsonrpc\":\"2.0\",\"id\":42,\"result\":{}}\n");
1311            writer.write_all(&bytes).await.unwrap();
1312            writer.flush().await.unwrap();
1313            // Absorb the client's open_session frame so its write never sees EPIPE.
1314            let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
1315            let req = match reader.next().await.unwrap().unwrap() {
1316                Inbound::Frame(v) => v,
1317                Inbound::Violation(_) => panic!("violation"),
1318            };
1319            assert_eq!(req["method"], "open_session");
1320        });
1321
1322        let client = connect_control(&sock).await.unwrap();
1323        let (reader, _writer) = client
1324            .open_session("peer".into(), "kb".into())
1325            .await
1326            .unwrap();
1327        // kb's production shape: erase the half type behind a boxed pipe, then re-frame.
1328        let boxed: Box<dyn AsyncRead + Unpin + Send> = Box::new(reader.into_inner());
1329        let mut reframed = FrameReader::new(boxed, MAX_FRAME_BYTES);
1330        match reframed.next().await.unwrap() {
1331            Some(Inbound::Frame(v)) => assert_eq!(v["id"], 42),
1332            other => panic!("pipelined frame was lost across the rebox: {other:?}"),
1333        }
1334        server.await.unwrap();
1335    }
1336
1337    #[tokio::test]
1338    async fn blob_grant_issues_request_and_acks() {
1339        let (sock, _guard) = test_endpoint("grant");
1340        let listener = bind_local(&sock).unwrap();
1341        let server = tokio::spawn(async move {
1342            let mut listener = listener;
1343            let stream = listener.accept().await.unwrap();
1344            let (read_half, mut writer) = split_local(stream);
1345            write_frame(
1346                &mut writer,
1347                &serde_json::to_value(Hello {
1348                    api: API_NAME.into(),
1349                    api_version: API_VERSION.into(),
1350                    api_minor: 0,
1351                    stack_version: "0.1.0".into(),
1352                })
1353                .unwrap(),
1354            )
1355            .await
1356            .unwrap();
1357            let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
1358            let req = match reader.next().await.unwrap().unwrap() {
1359                Inbound::Frame(v) => v,
1360                Inbound::Violation(_) => panic!("violation"),
1361            };
1362            assert_eq!(req["method"], "blob_grant");
1363            assert_eq!(req["params"]["scope"], "kb-sync");
1364            assert_eq!(req["params"]["principal"], "alice");
1365            write_frame(
1366                &mut writer,
1367                &serde_json::json!({"jsonrpc":"2.0","id":1,"result":{"ok":true}}),
1368            )
1369            .await
1370            .unwrap();
1371        });
1372        let mut client = connect_control(&sock).await.unwrap();
1373        client.blob_grant("kb-sync", "alice").await.unwrap();
1374        server.await.unwrap();
1375    }
1376
1377    /// The typed `status()` helper pairs `Request::Status` with `StatusResult` — the caller gets
1378    /// the struct, not a `Value` to hand-deserialize (and a malformed result surfaces as
1379    /// `ClientError::Malformed`, never a silently-wrong type).
1380    #[tokio::test]
1381    async fn typed_status_helper_deserializes_the_result() {
1382        let (sock, _guard) = test_endpoint("typedstatus");
1383        let listener = bind_local(&sock).unwrap();
1384        let server = tokio::spawn(stub_daemon(listener));
1385
1386        let mut client = connect_control(&sock).await.unwrap();
1387        let status = client.status().await.unwrap();
1388        assert_eq!(status.stack_version, "0.1.0");
1389        assert_eq!(status.services[0].name, "kb");
1390        assert_eq!(status.services[0].backend, BackendKind::Socket);
1391        assert!(status.peers.is_empty());
1392        server.await.unwrap();
1393    }
1394
1395    /// The ack-shaped typed helpers issue the right wire method and discard the `{}` ack; a
1396    /// JSON-RPC error frame surfaces as `ClientError::Api`.
1397    #[tokio::test]
1398    async fn typed_ack_helpers_issue_requests_and_surface_api_errors() {
1399        let (sock, _guard) = test_endpoint("typedack");
1400        let listener = bind_local(&sock).unwrap();
1401        let server = tokio::spawn(async move {
1402            let mut listener = listener;
1403            let stream = listener.accept().await.unwrap();
1404            let (read_half, mut writer) = split_local(stream);
1405            write_frame(
1406                &mut writer,
1407                &serde_json::to_value(Hello {
1408                    api: API_NAME.into(),
1409                    api_version: API_VERSION.into(),
1410                    api_minor: 0,
1411                    stack_version: "0.1.0".into(),
1412                })
1413                .unwrap(),
1414            )
1415            .await
1416            .unwrap();
1417            let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
1418            // peer_remove → ack.
1419            let req = match reader.next().await.unwrap().unwrap() {
1420                Inbound::Frame(v) => v,
1421                Inbound::Violation(_) => panic!("violation"),
1422            };
1423            assert_eq!(req["method"], "peer_remove");
1424            assert_eq!(req["params"]["nickname"], "bob");
1425            write_frame(
1426                &mut writer,
1427                &serde_json::json!({"jsonrpc":"2.0","id":1,"result":{}}),
1428            )
1429            .await
1430            .unwrap();
1431            // peer_rename → an error frame (collision refusal).
1432            let req = match reader.next().await.unwrap().unwrap() {
1433                Inbound::Frame(v) => v,
1434                Inbound::Violation(_) => panic!("violation"),
1435            };
1436            assert_eq!(req["method"], "peer_rename");
1437            assert_eq!(req["params"]["to"], "Bobby");
1438            write_frame(
1439                &mut writer,
1440                &serde_json::json!({"jsonrpc":"2.0","id":2,"error":{"code":-32000,"message":"taken"}}),
1441            )
1442            .await
1443            .unwrap();
1444        });
1445
1446        let mut client = connect_control(&sock).await.unwrap();
1447        client.peer_remove("bob").await.unwrap();
1448        match client.peer_rename(None, Some("bob".into()), "Bobby").await {
1449            Err(ClientError::Api(e)) => assert_eq!(e["message"], "taken"),
1450            other => panic!("expected Api error, got {other:?}"),
1451        }
1452        server.await.unwrap();
1453    }
1454
1455    /// The typed `subscribe()` upgrade yields `StreamFrame`s — snapshot, event, lagged — then
1456    /// `None` when the daemon side closes.
1457    #[tokio::test]
1458    async fn typed_subscribe_yields_frames_then_end() {
1459        use crate::protocol::{ActiveSession, AuditRecord, PeerReachability};
1460
1461        let (sock, _guard) = test_endpoint("subscribe");
1462        let listener = bind_local(&sock).unwrap();
1463        let server = tokio::spawn(async move {
1464            let mut listener = listener;
1465            let stream = listener.accept().await.unwrap();
1466            let (read_half, mut writer) = split_local(stream);
1467            write_frame(
1468                &mut writer,
1469                &serde_json::to_value(Hello {
1470                    api: API_NAME.into(),
1471                    api_version: API_VERSION.into(),
1472                    api_minor: 0,
1473                    stack_version: "0.1.0".into(),
1474                })
1475                .unwrap(),
1476            )
1477            .await
1478            .unwrap();
1479            let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
1480            let req = match reader.next().await.unwrap().unwrap() {
1481                Inbound::Frame(v) => v,
1482                Inbound::Violation(_) => panic!("violation"),
1483            };
1484            assert_eq!(req["method"], "subscribe");
1485            for frame in [
1486                StreamFrame::Snapshot {
1487                    self_network: None,
1488                    active_sessions: vec![ActiveSession {
1489                        peer: "bob".into(),
1490                        service: "notes".into(),
1491                        opened_at: 7,
1492                        principal: Some("eid:bob".into()),
1493                    }],
1494                    reachability: vec![PeerReachability {
1495                        name: "bob".into(),
1496                        reachable: true,
1497                        rtt_ms: Some(42),
1498                        age_secs: Some(3),
1499                        meta: String::new(),
1500                        principal: None,
1501                        path: Default::default(),
1502                    }],
1503                },
1504                StreamFrame::Event {
1505                    record: Box::new(AuditRecord::session_open(
1506                        "2026-07-03T14:02:11.480Z".into(),
1507                        Some("bob".into()),
1508                        "notes".into(),
1509                        None,
1510                    )),
1511                },
1512                StreamFrame::Lagged { dropped: 12 },
1513            ] {
1514                write_frame(&mut writer, &serde_json::to_value(&frame).unwrap())
1515                    .await
1516                    .unwrap();
1517            }
1518            writer.flush().await.unwrap();
1519            // Drop the connection: the client must see the stream END (Ok(None)), not an error.
1520        });
1521
1522        let client = connect_control(&sock).await.unwrap();
1523        let mut sub = client.subscribe().await.unwrap();
1524        match sub.next().await.unwrap().unwrap() {
1525            StreamFrame::Snapshot {
1526                active_sessions,
1527                reachability,
1528                ..
1529            } => {
1530                assert_eq!(active_sessions[0].peer, "bob");
1531                assert_eq!(reachability[0].rtt_ms, Some(42));
1532            }
1533            other => panic!("expected the snapshot first, got {other:?}"),
1534        }
1535        match sub.next().await.unwrap().unwrap() {
1536            StreamFrame::Event { record } => {
1537                assert_eq!(record.peer.as_deref(), Some("bob"));
1538                assert_eq!(record.service.as_deref(), Some("notes"));
1539            }
1540            other => panic!("expected the event, got {other:?}"),
1541        }
1542        assert_eq!(
1543            sub.next().await.unwrap(),
1544            Some(StreamFrame::Lagged { dropped: 12 })
1545        );
1546        assert_eq!(sub.next().await.unwrap(), None, "clean end of stream");
1547        server.await.unwrap();
1548    }
1549}