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    /// DETACH this device from an identity it was enrolled into (#214) — the inverse of
680    /// `pair_opts(.., allow_self_enroll: true)`. Drops the adopted binding live and on disk; the
681    /// node goes back to presenting its own identity (imported, else boot-derived), returned as
682    /// `user_id`.
683    ///
684    /// Local only: peers who already learned this endpoint as that person's device are not told —
685    /// that is `device_revoke`, from the device holding the key. Refused with `ERR_NOT_ENROLLED`
686    /// when nothing is adopted. `api_minor >= 62`.
687    pub async fn self_enroll_detach(
688        &mut self,
689    ) -> Result<crate::protocol::SelfEnrollDetachResult, ClientError> {
690        self.request_typed(Request::SelfEnrollDetach, "self_enroll_detach result")
691            .await
692    }
693
694    /// INSPECT a join code without approving it (#66): what it claims, and the fingerprint that
695    /// decides whether to believe it. Read-only — nothing is signed or installed.
696    ///
697    /// **Call this before [`org_approve`](Self::org_approve), show
698    /// `join_code_fingerprint`, and have the operator confirm it out-of-band.** Nothing in a join
699    /// code binds it to a person; a substituted one carries a different key and diverges here. The
700    /// fingerprint on the approval RESULT is the same words, but by then the member is in the
701    /// signed roster — too late to decline.
702    ///
703    /// The claims (`display_name`, `requested_user_id`, `device_label`) are chosen by the sender.
704    /// Render them; do not trust them. A forged binding is refused rather than described.
705    /// `api_minor >= 46`.
706    pub async fn org_join_code(
707        &mut self,
708        join_code: &str,
709    ) -> Result<crate::protocol::OrgJoinCodeResult, ClientError> {
710        self.request_typed(
711            Request::OrgJoinCode(crate::protocol::OrgJoinCodeParams {
712                join_code: join_code.to_string(),
713            }),
714            "org_join_code result",
715        )
716        .await
717    }
718
719    /// REVOKE from the roster (#66) — and sever the cut devices' live sessions, immediately.
720    ///
721    /// Three readings, and picking the wrong one is destructive, so the result reports which
722    /// `mode` was applied: `"<user_id>/<label>"` cuts ONE device; a bare `user_id` removes the
723    /// person and revokes ALL their devices; `user_key = true` is a key ROTATION — the person is
724    /// removed but their devices stay un-revoked so the same hardware re-enrolls under a fresh
725    /// user key. `api_minor >= 46`.
726    pub async fn org_revoke(
727        &mut self,
728        target: &str,
729        user_key: bool,
730    ) -> Result<crate::protocol::OrgRevokeResult, ClientError> {
731        self.request_typed(
732            Request::OrgRevoke(crate::protocol::OrgRevokeParams {
733                target: target.to_string(),
734                user_key,
735            }),
736            "org_revoke result",
737        )
738        .await
739    }
740
741    /// Pin the org root on a JOINER (no roster yet). `user_key` is a LOCAL path — the key never
742    /// crosses the API. Returns the pinned org id.
743    pub async fn org_join(
744        &mut self,
745        org_id: &str,
746        org_root_pk: &str,
747        user_id: &str,
748        user_key: &str,
749    ) -> Result<OrgJoinResult, ClientError> {
750        self.request_typed(
751            Request::OrgJoin(OrgJoinParams {
752                org_id: org_id.to_string(),
753                org_root_pk: org_root_pk.to_string(),
754                user_id: user_id.to_string(),
755                user_key: user_key.to_string(),
756            }),
757            "org_join result",
758        )
759        .await
760    }
761
762    /// Pin the HTTPS roster URL (`[roster].url`) in the daemon's config. The daemon acks; the
763    /// ack body is discarded.
764    pub async fn set_roster_url(&mut self, url: &str) -> Result<(), ClientError> {
765        self.request_ack(Request::SetRosterUrl(SetRosterUrlParams {
766            url: url.to_string(),
767        }))
768        .await
769    }
770
771    /// Discover which services a paired `peer` (a nickname, `eid:`, or `b64u:`) CURRENTLY grants
772    /// the caller (#52) — dials the peer and returns the service names its allow admits for the
773    /// caller's principal (only your own admitted services, never the peer's full registry).
774    pub async fn peer_services(&mut self, peer: &str) -> Result<Vec<String>, ClientError> {
775        self.request_typed::<PeerServicesResult>(
776            Request::PeerServices(PeerServicesParams {
777                peer: peer.to_string(),
778            }),
779            "peer_services",
780        )
781        .await
782        .map(|r| r.services)
783    }
784
785    /// Remove a service registration (#50) — the deregistration mirror of `register_service`.
786    /// Removes the whole entry (allow included) + any ephemeral registration of the name, then
787    /// hot-reloads. Idempotent: an unknown name is a clean no-op.
788    pub async fn unregister_service(&mut self, name: &str) -> Result<(), ClientError> {
789        self.request_ack(Request::UnregisterService(UnregisterServiceParams {
790            name: name.to_string(),
791        }))
792        .await
793    }
794
795    /// Grant a stable `principal` (`b64u:`/`eid:`) access to `service` WITHOUT (re)pairing (#44)
796    /// — the per-peer "sharing on" toggle. Idempotent; an unknown service is a clean no-op.
797    pub async fn service_allow_grant(
798        &mut self,
799        service: &str,
800        principal: &str,
801    ) -> Result<(), ClientError> {
802        self.request_ack(Request::ServiceAllowGrant(ServiceAllowParams {
803            service: service.to_string(),
804            principal: principal.to_string(),
805        }))
806        .await
807    }
808
809    /// Revoke a stable `principal` from `service`'s allow WITHOUT unpairing (#44) — the
810    /// "sharing off" toggle. The peer's identity row is untouched; it just cannot open NEW
811    /// sessions (in-flight ones run to completion). Idempotent.
812    pub async fn service_allow_revoke(
813        &mut self,
814        service: &str,
815        principal: &str,
816    ) -> Result<(), ClientError> {
817        self.request_ack(Request::ServiceAllowRevoke(ServiceAllowParams {
818            service: service.to_string(),
819            principal: principal.to_string(),
820        }))
821        .await
822    }
823
824    /// Set this node's opaque app-metadata blob (#39, roster mode): ≤256 bytes, folded
825    /// signed into each presence heartbeat so paired peers read it in `status` presence —
826    /// no per-peer session. `""` clears it; in-memory (re-set on startup).
827    pub async fn set_app_metadata(&mut self, metadata: &str) -> Result<(), ClientError> {
828        self.request_ack(Request::SetAppMetadata(SetAppMetadataParams {
829            metadata: metadata.to_string(),
830        }))
831        .await
832    }
833
834    /// Set this node's CUSTOM relay set LIVE (#53). `relay_urls` is the desired set (each must
835    /// parse as an iroh `RelayUrl`; empty is rejected). When the node is already in
836    /// `relay_mode = "custom"`, the daemon diffs against the running endpoint and applies the
837    /// delta live (iroh `insert_relay`/`remove_relay`) — no restart, no dropped sessions — then
838    /// persists `[network]`. When the node is currently `default`/`disabled`, the config is
839    /// persisted but the live mode transition isn't possible: the returned
840    /// [`SetRelaysResult::restart_required`] is `true`. Idempotent (an unchanged set → `changed:
841    /// false`, no writes).
842    pub async fn set_relays(
843        &mut self,
844        relay_urls: &[String],
845    ) -> Result<SetRelaysResult, ClientError> {
846        self.request_typed::<SetRelaysResult>(
847            Request::SetRelays(SetRelaysParams {
848                relay_urls: relay_urls.to_vec(),
849            }),
850            "set_relays",
851        )
852        .await
853    }
854
855    /// Rename this node LIVE (#37): the daemon validates + persists `[identity].nickname`
856    /// under its own config lock and updates the name future invites present — no restart.
857    /// Peers keep their stored pairing-time nickname until a re-invite (display-only).
858    pub async fn set_nickname(&mut self, nickname: &str) -> Result<(), ClientError> {
859        self.request_ack(Request::SetNickname(SetNicknameParams {
860            nickname: nickname.to_string(),
861        }))
862        .await
863    }
864
865    /// Summarize the daemon's LOCAL audit log into per-peer / per-service session counts
866    /// (local-only — nothing is transmitted).
867    pub async fn audit_summary(&mut self) -> Result<AuditSummaryResult, ClientError> {
868        self.request_typed(Request::AuditSummary, "audit_summary result")
869            .await
870    }
871
872    /// Publish a local file into `scope`; return the minted `mcpmesh/blob/1` ticket + hash.
873    pub async fn blob_publish(
874        &mut self,
875        scope: &str,
876        path: &str,
877    ) -> Result<BlobPublishResult, ClientError> {
878        self.request_typed(
879            Request::BlobPublish(BlobPublishParams {
880                scope: scope.to_string(),
881                path: path.to_string(),
882            }),
883            "blob_publish result",
884        )
885        .await
886    }
887
888    /// List the daemon's blob scopes (name → hashes + grants + withdrawn).
889    ///
890    /// A DEFAULT LIMIT applies (#84b) — check `truncated` and page with
891    /// [`blob_list_paged`](Self::blob_list_paged) rather than assuming you saw everything.
892    pub async fn blob_list(&mut self) -> Result<BlobScopeList, ClientError> {
893        self.blob_list_paged(Default::default()).await
894    }
895
896    /// List blob scopes with filters + paging (#84b, `api_minor >= 20`).
897    pub async fn blob_list_paged(
898        &mut self,
899        params: crate::BlobListParams,
900    ) -> Result<BlobScopeList, ClientError> {
901        self.request_typed(Request::BlobList(params), "blob_list result")
902            .await
903    }
904
905    /// Fetch a `mcpmesh/blob/1` ticket THROUGH the daemon (BLAKE3-verified), export to
906    /// `dest_path`; return the verified hash + byte length.
907    pub async fn blob_fetch(
908        &mut self,
909        ticket: &str,
910        dest_path: &str,
911    ) -> Result<BlobFetchResult, ClientError> {
912        self.blob_fetch_from(ticket, dest_path, Vec::new()).await
913    }
914
915    /// [`blob_fetch`](Self::blob_fetch) with ADDITIONAL sources to try when the ticket's publisher
916    /// does not answer (#83).
917    ///
918    /// Content addressing makes every recipient a potential source; a single-address ticket made
919    /// that unusable, so a file shared with a room became unfetchable the moment the sender closed
920    /// their laptop — even though others in the room already held the identical verified bytes.
921    ///
922    /// `from` takes stable principals (`eid:`, `b64u:`) or paired nicknames — the same vocabulary
923    /// `open_session` takes, and naming a PERSON offers every device of theirs. They are tried in
924    /// order, **after** the publisher, so a live publisher costs nothing and an offline one costs
925    /// one dial timeout.
926    ///
927    /// **The bytes are BLAKE3-verified against the ticket's hash whoever serves them**, so an
928    /// alternate cannot substitute content. It can refuse: an alternate serves only hashes it has
929    /// republished into a scope that grants you (see `blob_republish`), and an ungranted one
930    /// answers a permission error and the fetch moves on. Every failure mode falls through, not
931    /// only an unreachable dial — a refusal, a missing hash, a reset, and a stalled transfer all
932    /// move to the next source. `api_minor >= 47`.
933    pub async fn blob_fetch_from(
934        &mut self,
935        ticket: &str,
936        dest_path: &str,
937        from: Vec<String>,
938    ) -> Result<BlobFetchResult, ClientError> {
939        self.request_typed(
940            Request::BlobFetch(BlobFetchParams {
941                ticket: ticket.to_string(),
942                dest_path: dest_path.to_string(),
943                from,
944            }),
945            "blob_fetch result",
946        )
947        .await
948    }
949
950    /// Stop every in-flight [`blob_fetch`](Self::blob_fetch) of `hash` (#172).
951    ///
952    /// **Send this on a DIFFERENT connection than the fetch it cancels.** This client is one
953    /// request at a time — `&mut self` is borrowed until the fetch answers — so a cancel issued on
954    /// the same client can only run after the thing it would cancel is already over. The cancelled
955    /// fetch answers [`ERR_CANCELLED`](crate::ERR_CANCELLED) on its own connection.
956    ///
957    /// `cancelled: false` means nothing was fetching that blob here. That is the honest answer to a
958    /// cancel that raced a fetch to completion, not an error.
959    ///
960    /// Needs `api_minor >= 44`; below it the method is unknown.
961    pub async fn blob_fetch_cancel(
962        &mut self,
963        hash: &str,
964    ) -> Result<BlobFetchCancelResult, ClientError> {
965        self.request_typed(
966            Request::BlobFetchCancel(BlobFetchCancelParams {
967                hash: hash.to_string(),
968            }),
969            "blob_fetch_cancel result",
970        )
971        .await
972    }
973
974    /// Grant a scope to a principal — any flat-namespace entry: a group name, a user_id,
975    /// or a nickname (the shared `principal_set` expansion).
976    /// The daemon acks; the ack body is discarded (a JSON-RPC error surfaces as
977    /// `ClientError::Api`). Granting a scope to your own user_id reaches ALL of that
978    /// person's devices.
979    pub async fn blob_grant(&mut self, scope: &str, principal: &str) -> Result<(), ClientError> {
980        self.request_ack(Request::BlobGrant(BlobGrantParams {
981            scope: scope.to_string(),
982            principal: principal.to_string(),
983        }))
984        .await
985    }
986
987    /// The TYPED `subscribe` upgrade: send [`Request::Subscribe`] (after which the connection
988    /// stops being request/response — see [`open_stream`](Self::open_stream)) and return a
989    /// [`StreamSubscription`] yielding [`StreamFrame`]s. For raw frames (e.g. to tolerate frame
990    /// types newer than this crate), use `open_stream("subscribe")` instead.
991    pub async fn subscribe(self) -> Result<StreamSubscription, ClientError> {
992        let (reader, writer) = self.open_stream("subscribe").await?;
993        Ok(StreamSubscription {
994            reader,
995            _writer: writer,
996        })
997    }
998}
999
1000/// A live [`Request::Subscribe`] stream yielding typed [`StreamFrame`]s (snapshot, then
1001/// events/lagged notices) until the daemon side closes. Holds the connection's write half for its
1002/// lifetime — a subscriber only reads, but dropping the writer would half-close the socket. Drop
1003/// the subscription to disconnect (there is no request channel back).
1004pub struct StreamSubscription {
1005    reader: FrameReader<ControlRead>,
1006    _writer: ControlWrite,
1007}
1008
1009/// Hand-rolled like [`ControlClient`]'s: the boxed transport halves are not `Debug`.
1010impl std::fmt::Debug for StreamSubscription {
1011    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1012        f.debug_struct("StreamSubscription").finish_non_exhaustive()
1013    }
1014}
1015
1016impl StreamSubscription {
1017    /// The next frame, or `None` when the daemon closed the stream. A frame this crate's
1018    /// [`StreamFrame`] does not model (a NEWER daemon's frame type) surfaces as
1019    /// [`ClientError::Malformed`] — a forward-compatible consumer reads raw frames via
1020    /// [`ControlClient::open_stream`] instead.
1021    pub async fn next(&mut self) -> Result<Option<StreamFrame>, ClientError> {
1022        match self.reader.next().await? {
1023            Some(Inbound::Frame(v)) => serde_json::from_value(v)
1024                .map(Some)
1025                .map_err(|_| ClientError::Malformed("stream frame")),
1026            Some(Inbound::Violation(_)) => Err(ClientError::Malformed("stream frame")),
1027            None => Ok(None),
1028        }
1029    }
1030}
1031
1032/// Complete the mcpmesh-local/1 hello handshake over ALREADY-CONNECTED byte halves —
1033/// the transport-agnostic core of [`connect_control`], and the front door for in-process
1034/// embedding (`mcpmesh-node`'s `Node::control` dials a tokio duplex through here).
1035pub async fn connect_control_io(
1036    reader: impl tokio::io::AsyncRead + Send + Unpin + 'static,
1037    writer: impl tokio::io::AsyncWrite + Send + Unpin + 'static,
1038) -> Result<ControlClient, ClientError> {
1039    let mut reader = FrameReader::new(Box::new(reader) as ControlRead, MAX_FRAME_BYTES);
1040    let hello: Hello = match reader.next().await? {
1041        Some(Inbound::Frame(v)) => {
1042            serde_json::from_value(v).map_err(|_| ClientError::Malformed("hello"))?
1043        }
1044        Some(Inbound::Violation(_)) => return Err(ClientError::Malformed("hello")),
1045        None => return Err(ClientError::Closed("hello")),
1046    };
1047    if hello.api != crate::protocol::API_NAME {
1048        return Err(ClientError::WrongApi {
1049            got: hello.api,
1050            want: crate::protocol::API_NAME,
1051        });
1052    }
1053    Ok(ControlClient {
1054        hello,
1055        reader,
1056        writer: Box::new(writer) as ControlWrite,
1057    })
1058}
1059
1060/// Connect + complete the hello handshake, asserting the api name is `mcpmesh-local/1`.
1061pub async fn connect_control(path: &Path) -> Result<ControlClient, ClientError> {
1062    let stream = connect_local(path).await?;
1063    let (read_half, write_half) = split_local(stream);
1064    connect_control_io(read_half, write_half).await
1065}
1066
1067/// [`connect_control`] at the platform default endpoint ([`crate::paths::default_endpoint`]):
1068/// the quickstart front door — a consumer dials the running daemon without reimplementing
1069/// the platform endpoint rule. Resolution failure surfaces as [`ClientError::Io`]
1070/// (`NotFound`), same as a daemon that is not running.
1071pub async fn connect_control_default() -> Result<ControlClient, ClientError> {
1072    connect_control(&crate::paths::default_endpoint()?).await
1073}
1074
1075// Seam-ported (Task 6): every stub daemon binds via the platform seam
1076// (`transport::bind_local` + `LocalListener::accept`) rather than a raw `UnixListener`,
1077// so these exercise the platform-identical `ControlClient` on BOTH unix (UDS) and windows
1078// (named pipe). Gated on `feature = "service"` (bind needs it) rather than `unix`: under
1079// `cargo test --workspace` feature unification turns `service` on for this crate (cli
1080// depends on local-api with features=["service"]), so the module compiles and RUNS on the
1081// windows CI leg. `test_endpoint` yields a platform-appropriate unique endpoint.
1082#[cfg(all(test, feature = "service"))]
1083mod tests {
1084    use super::*;
1085    use crate::protocol::{API_NAME, API_VERSION, BackendKind, ServiceInfo, StatusResult};
1086    use crate::transport::{LocalListener, bind_local, split_local};
1087    use tokio::io::AsyncWriteExt;
1088
1089    /// A unique local endpoint for a stub daemon, platform-appropriate: a tempdir socket
1090    /// path on unix, a per-process-unique `\\.\pipe\…` name on windows. Returns the
1091    /// endpoint plus a guard that MUST outlive the listener (the `TempDir` on unix; unit
1092    /// on windows, whose pipe namespace needs no filesystem cleanup).
1093    #[cfg(unix)]
1094    fn test_endpoint(tag: &str) -> (std::path::PathBuf, tempfile::TempDir) {
1095        let dir = tempfile::tempdir().unwrap();
1096        let path = dir.path().join(format!("{tag}.sock"));
1097        (path, dir)
1098    }
1099    #[cfg(windows)]
1100    fn test_endpoint(tag: &str) -> (std::path::PathBuf, ()) {
1101        use std::sync::atomic::{AtomicU64, Ordering};
1102        static SEQ: AtomicU64 = AtomicU64::new(0);
1103        let n = SEQ.fetch_add(1, Ordering::Relaxed);
1104        let path = std::path::PathBuf::from(format!(
1105            r"\\.\pipe\mcpmesh-client-test-{}-{tag}-{n}",
1106            std::process::id()
1107        ));
1108        (path, ())
1109    }
1110
1111    /// A stub mcpmesh daemon: send Hello, then answer one `status` with a StatusResult.
1112    async fn stub_daemon(mut listener: LocalListener) {
1113        let stream = listener.accept().await.unwrap();
1114        let (read_half, mut writer) = split_local(stream);
1115        write_frame(
1116            &mut writer,
1117            &serde_json::to_value(Hello {
1118                api: API_NAME.into(),
1119                api_version: API_VERSION.into(),
1120                api_minor: 0,
1121                stack_version: "0.1.0".into(),
1122            })
1123            .unwrap(),
1124        )
1125        .await
1126        .unwrap();
1127        let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
1128        let req = match reader.next().await.unwrap().unwrap() {
1129            Inbound::Frame(v) => v,
1130            Inbound::Violation(_) => panic!("violation"),
1131        };
1132        assert_eq!(req["method"], "status");
1133        let result = StatusResult {
1134            stack_version: "0.1.0".into(),
1135            services: vec![ServiceInfo {
1136                name: "kb".into(),
1137                allow: vec![],
1138                allow_display: vec![],
1139                backend: BackendKind::Socket,
1140                ephemeral: false,
1141            }],
1142            peers: vec![],
1143            roster: None,
1144            presence: vec![],
1145            self_user_id: None,
1146            self_user_key_held: false,
1147            recent_pairings: vec![],
1148            reachability: vec![],
1149            self_nickname: String::new(),
1150            storage: None,
1151            revoked: Vec::new(),
1152            self_network: None,
1153        };
1154        write_frame(
1155            &mut writer,
1156            &serde_json::json!({ "jsonrpc": "2.0", "id": 1, "result": result }),
1157        )
1158        .await
1159        .unwrap();
1160        writer.flush().await.unwrap();
1161    }
1162
1163    /// The transport-agnostic front door: the same hello handshake over a plain in-memory
1164    /// duplex — what an embedded node's `Node::control` dials through.
1165    #[tokio::test]
1166    async fn connect_control_io_handshakes_over_a_duplex() {
1167        let (client_io, mut server_io) = tokio::io::duplex(4096);
1168        tokio::spawn(async move {
1169            write_frame(
1170                &mut server_io,
1171                &serde_json::to_value(Hello {
1172                    api: API_NAME.into(),
1173                    api_version: API_VERSION.into(),
1174                    api_minor: 0,
1175                    stack_version: "in-proc".into(),
1176                })
1177                .unwrap(),
1178            )
1179            .await
1180            .unwrap();
1181        });
1182        let (r, w) = tokio::io::split(client_io);
1183        let client = connect_control_io(r, w).await.expect("handshake");
1184        assert_eq!(client.hello().stack_version, "in-proc");
1185    }
1186
1187    #[tokio::test]
1188    async fn connect_reads_hello_asserts_api_and_requests() {
1189        let (sock, _guard) = test_endpoint("status");
1190        let listener = bind_local(&sock).unwrap();
1191        let server = tokio::spawn(stub_daemon(listener));
1192
1193        let mut client = connect_control(&sock).await.unwrap();
1194        assert_eq!(client.hello().api, API_NAME);
1195        let result = client.request(Request::Status).await.unwrap();
1196        assert_eq!(result["services"][0]["name"], "kb");
1197        assert_eq!(result["services"][0]["backend"], "socket");
1198        server.await.unwrap();
1199    }
1200
1201    #[tokio::test]
1202    async fn wrong_api_hello_is_rejected() {
1203        let (sock, _guard) = test_endpoint("wrongapi");
1204        let listener = bind_local(&sock).unwrap();
1205        tokio::spawn(async move {
1206            let mut listener = listener;
1207            let stream = listener.accept().await.unwrap();
1208            let (_r, mut w) = split_local(stream);
1209            write_frame(
1210                &mut w,
1211                &serde_json::json!({"api":"other/1","api_version":"1.0","stack_version":"0"}),
1212            )
1213            .await
1214            .unwrap();
1215            w.flush().await.unwrap();
1216        });
1217        match connect_control(&sock).await {
1218            Err(ClientError::WrongApi { got, want }) => {
1219                assert_eq!(got, "other/1");
1220                assert_eq!(want, API_NAME);
1221            }
1222            other => panic!("expected WrongApi, got {other:?}"),
1223        }
1224    }
1225
1226    #[tokio::test]
1227    async fn blob_fetch_and_publish_deserialize_typed_results() {
1228        use crate::protocol::{BlobFetchResult, BlobPublishResult};
1229        let (sock, _guard) = test_endpoint("blob");
1230        let listener = bind_local(&sock).unwrap();
1231        let server = tokio::spawn(async move {
1232            let mut listener = listener;
1233            let stream = listener.accept().await.unwrap();
1234            let (read_half, mut writer) = split_local(stream);
1235            write_frame(
1236                &mut writer,
1237                &serde_json::to_value(Hello {
1238                    api: API_NAME.into(),
1239                    api_version: API_VERSION.into(),
1240                    api_minor: 0,
1241                    stack_version: "0.1.0".into(),
1242                })
1243                .unwrap(),
1244            )
1245            .await
1246            .unwrap();
1247            let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
1248            // First request: blob_publish -> a ticket + hash.
1249            let req = match reader.next().await.unwrap().unwrap() {
1250                Inbound::Frame(v) => v,
1251                Inbound::Violation(_) => panic!("violation"),
1252            };
1253            assert_eq!(req["method"], "blob_publish");
1254            assert_eq!(req["params"]["scope"], "eng");
1255            write_frame(
1256                &mut writer,
1257                &serde_json::json!({"jsonrpc":"2.0","id":1,"result":{"ticket":"blobT","hash":"ab"}}),
1258            )
1259            .await
1260            .unwrap();
1261            // Second request: blob_fetch -> a verified hash + length.
1262            let req = match reader.next().await.unwrap().unwrap() {
1263                Inbound::Frame(v) => v,
1264                Inbound::Violation(_) => panic!("violation"),
1265            };
1266            assert_eq!(req["method"], "blob_fetch");
1267            assert_eq!(req["params"]["ticket"], "blobT");
1268            assert_eq!(req["params"]["dest_path"], "/tmp/out.bin");
1269            write_frame(
1270                &mut writer,
1271                &serde_json::json!({"jsonrpc":"2.0","id":2,"result":{"hash":"cd","bytes_len":7}}),
1272            )
1273            .await
1274            .unwrap();
1275            let _ = (
1276                BlobFetchResult {
1277                    hash: "cd".into(),
1278                    bytes_len: 7,
1279                },
1280                BlobPublishResult {
1281                    ticket: "blobT".into(),
1282                    hash: "ab".into(),
1283                },
1284            );
1285        });
1286
1287        let mut client = connect_control(&sock).await.unwrap();
1288        let pub_res = client.blob_publish("eng", "/tmp/a.bin").await.unwrap();
1289        assert_eq!(pub_res.ticket, "blobT");
1290        assert_eq!(pub_res.hash, "ab");
1291        let fetch_res = client.blob_fetch("blobT", "/tmp/out.bin").await.unwrap();
1292        assert_eq!(fetch_res.hash, "cd");
1293        assert_eq!(fetch_res.bytes_len, 7);
1294        server.await.unwrap();
1295    }
1296
1297    /// Regression (lossless rebox): a frame the server PIPELINES in the same write as
1298    /// the Hello must survive `open_session` + kb's production re-box shape
1299    /// (`FrameReader::new(Box::new(reader.into_inner()), …)`, bridge/session.rs). Against
1300    /// the old `into_inner -> R` — which unwrapped the internal `BufReader` and DROPPED
1301    /// its read-ahead — the pipelined frame vanished and this test failed (EOF instead of
1302    /// the frame). `into_inner -> BufReader<R>` carries the read-ahead across the rebox.
1303    #[tokio::test]
1304    async fn frame_pipelined_behind_hello_survives_open_session_rebox() {
1305        use tokio::io::AsyncRead;
1306
1307        let (sock, _guard) = test_endpoint("pipelined");
1308        let listener = bind_local(&sock).unwrap();
1309        let server = tokio::spawn(async move {
1310            let mut listener = listener;
1311            let stream = listener.accept().await.unwrap();
1312            let (read_half, mut writer) = split_local(stream);
1313            // ONE write carrying the Hello AND a session frame → both land in the
1314            // client's first BufReader fill (the read-ahead under test).
1315            let mut bytes = serde_json::to_vec(
1316                &serde_json::to_value(Hello {
1317                    api: API_NAME.into(),
1318                    api_version: API_VERSION.into(),
1319                    api_minor: 0,
1320                    stack_version: "0.1.0".into(),
1321                })
1322                .unwrap(),
1323            )
1324            .unwrap();
1325            bytes.push(b'\n');
1326            bytes.extend_from_slice(b"{\"jsonrpc\":\"2.0\",\"id\":42,\"result\":{}}\n");
1327            writer.write_all(&bytes).await.unwrap();
1328            writer.flush().await.unwrap();
1329            // Absorb the client's open_session frame so its write never sees EPIPE.
1330            let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
1331            let req = match reader.next().await.unwrap().unwrap() {
1332                Inbound::Frame(v) => v,
1333                Inbound::Violation(_) => panic!("violation"),
1334            };
1335            assert_eq!(req["method"], "open_session");
1336        });
1337
1338        let client = connect_control(&sock).await.unwrap();
1339        let (reader, _writer) = client
1340            .open_session("peer".into(), "kb".into())
1341            .await
1342            .unwrap();
1343        // kb's production shape: erase the half type behind a boxed pipe, then re-frame.
1344        let boxed: Box<dyn AsyncRead + Unpin + Send> = Box::new(reader.into_inner());
1345        let mut reframed = FrameReader::new(boxed, MAX_FRAME_BYTES);
1346        match reframed.next().await.unwrap() {
1347            Some(Inbound::Frame(v)) => assert_eq!(v["id"], 42),
1348            other => panic!("pipelined frame was lost across the rebox: {other:?}"),
1349        }
1350        server.await.unwrap();
1351    }
1352
1353    #[tokio::test]
1354    async fn blob_grant_issues_request_and_acks() {
1355        let (sock, _guard) = test_endpoint("grant");
1356        let listener = bind_local(&sock).unwrap();
1357        let server = tokio::spawn(async move {
1358            let mut listener = listener;
1359            let stream = listener.accept().await.unwrap();
1360            let (read_half, mut writer) = split_local(stream);
1361            write_frame(
1362                &mut writer,
1363                &serde_json::to_value(Hello {
1364                    api: API_NAME.into(),
1365                    api_version: API_VERSION.into(),
1366                    api_minor: 0,
1367                    stack_version: "0.1.0".into(),
1368                })
1369                .unwrap(),
1370            )
1371            .await
1372            .unwrap();
1373            let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
1374            let req = match reader.next().await.unwrap().unwrap() {
1375                Inbound::Frame(v) => v,
1376                Inbound::Violation(_) => panic!("violation"),
1377            };
1378            assert_eq!(req["method"], "blob_grant");
1379            assert_eq!(req["params"]["scope"], "kb-sync");
1380            assert_eq!(req["params"]["principal"], "alice");
1381            write_frame(
1382                &mut writer,
1383                &serde_json::json!({"jsonrpc":"2.0","id":1,"result":{"ok":true}}),
1384            )
1385            .await
1386            .unwrap();
1387        });
1388        let mut client = connect_control(&sock).await.unwrap();
1389        client.blob_grant("kb-sync", "alice").await.unwrap();
1390        server.await.unwrap();
1391    }
1392
1393    /// The typed `status()` helper pairs `Request::Status` with `StatusResult` — the caller gets
1394    /// the struct, not a `Value` to hand-deserialize (and a malformed result surfaces as
1395    /// `ClientError::Malformed`, never a silently-wrong type).
1396    #[tokio::test]
1397    async fn typed_status_helper_deserializes_the_result() {
1398        let (sock, _guard) = test_endpoint("typedstatus");
1399        let listener = bind_local(&sock).unwrap();
1400        let server = tokio::spawn(stub_daemon(listener));
1401
1402        let mut client = connect_control(&sock).await.unwrap();
1403        let status = client.status().await.unwrap();
1404        assert_eq!(status.stack_version, "0.1.0");
1405        assert_eq!(status.services[0].name, "kb");
1406        assert_eq!(status.services[0].backend, BackendKind::Socket);
1407        assert!(status.peers.is_empty());
1408        server.await.unwrap();
1409    }
1410
1411    /// The ack-shaped typed helpers issue the right wire method and discard the `{}` ack; a
1412    /// JSON-RPC error frame surfaces as `ClientError::Api`.
1413    #[tokio::test]
1414    async fn typed_ack_helpers_issue_requests_and_surface_api_errors() {
1415        let (sock, _guard) = test_endpoint("typedack");
1416        let listener = bind_local(&sock).unwrap();
1417        let server = tokio::spawn(async move {
1418            let mut listener = listener;
1419            let stream = listener.accept().await.unwrap();
1420            let (read_half, mut writer) = split_local(stream);
1421            write_frame(
1422                &mut writer,
1423                &serde_json::to_value(Hello {
1424                    api: API_NAME.into(),
1425                    api_version: API_VERSION.into(),
1426                    api_minor: 0,
1427                    stack_version: "0.1.0".into(),
1428                })
1429                .unwrap(),
1430            )
1431            .await
1432            .unwrap();
1433            let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
1434            // peer_remove → ack.
1435            let req = match reader.next().await.unwrap().unwrap() {
1436                Inbound::Frame(v) => v,
1437                Inbound::Violation(_) => panic!("violation"),
1438            };
1439            assert_eq!(req["method"], "peer_remove");
1440            assert_eq!(req["params"]["nickname"], "bob");
1441            write_frame(
1442                &mut writer,
1443                &serde_json::json!({"jsonrpc":"2.0","id":1,"result":{}}),
1444            )
1445            .await
1446            .unwrap();
1447            // peer_rename → an error frame (collision refusal).
1448            let req = match reader.next().await.unwrap().unwrap() {
1449                Inbound::Frame(v) => v,
1450                Inbound::Violation(_) => panic!("violation"),
1451            };
1452            assert_eq!(req["method"], "peer_rename");
1453            assert_eq!(req["params"]["to"], "Bobby");
1454            write_frame(
1455                &mut writer,
1456                &serde_json::json!({"jsonrpc":"2.0","id":2,"error":{"code":-32000,"message":"taken"}}),
1457            )
1458            .await
1459            .unwrap();
1460        });
1461
1462        let mut client = connect_control(&sock).await.unwrap();
1463        client.peer_remove("bob").await.unwrap();
1464        match client.peer_rename(None, Some("bob".into()), "Bobby").await {
1465            Err(ClientError::Api(e)) => assert_eq!(e["message"], "taken"),
1466            other => panic!("expected Api error, got {other:?}"),
1467        }
1468        server.await.unwrap();
1469    }
1470
1471    /// The typed `subscribe()` upgrade yields `StreamFrame`s — snapshot, event, lagged — then
1472    /// `None` when the daemon side closes.
1473    #[tokio::test]
1474    async fn typed_subscribe_yields_frames_then_end() {
1475        use crate::protocol::{ActiveSession, AuditRecord, PeerReachability};
1476
1477        let (sock, _guard) = test_endpoint("subscribe");
1478        let listener = bind_local(&sock).unwrap();
1479        let server = tokio::spawn(async move {
1480            let mut listener = listener;
1481            let stream = listener.accept().await.unwrap();
1482            let (read_half, mut writer) = split_local(stream);
1483            write_frame(
1484                &mut writer,
1485                &serde_json::to_value(Hello {
1486                    api: API_NAME.into(),
1487                    api_version: API_VERSION.into(),
1488                    api_minor: 0,
1489                    stack_version: "0.1.0".into(),
1490                })
1491                .unwrap(),
1492            )
1493            .await
1494            .unwrap();
1495            let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
1496            let req = match reader.next().await.unwrap().unwrap() {
1497                Inbound::Frame(v) => v,
1498                Inbound::Violation(_) => panic!("violation"),
1499            };
1500            assert_eq!(req["method"], "subscribe");
1501            for frame in [
1502                StreamFrame::Snapshot {
1503                    self_network: None,
1504                    active_sessions: vec![ActiveSession {
1505                        peer: "bob".into(),
1506                        service: "notes".into(),
1507                        opened_at: 7,
1508                        principal: Some("eid:bob".into()),
1509                    }],
1510                    reachability: vec![PeerReachability {
1511                        name: "bob".into(),
1512                        reachable: true,
1513                        rtt_ms: Some(42),
1514                        age_secs: Some(3),
1515                        meta: String::new(),
1516                        principal: None,
1517                        path: Default::default(),
1518                    }],
1519                },
1520                StreamFrame::Event {
1521                    record: Box::new(AuditRecord::session_open(
1522                        "2026-07-03T14:02:11.480Z".into(),
1523                        Some("bob".into()),
1524                        "notes".into(),
1525                        None,
1526                    )),
1527                },
1528                StreamFrame::Lagged { dropped: 12 },
1529            ] {
1530                write_frame(&mut writer, &serde_json::to_value(&frame).unwrap())
1531                    .await
1532                    .unwrap();
1533            }
1534            writer.flush().await.unwrap();
1535            // Drop the connection: the client must see the stream END (Ok(None)), not an error.
1536        });
1537
1538        let client = connect_control(&sock).await.unwrap();
1539        let mut sub = client.subscribe().await.unwrap();
1540        match sub.next().await.unwrap().unwrap() {
1541            StreamFrame::Snapshot {
1542                active_sessions,
1543                reachability,
1544                ..
1545            } => {
1546                assert_eq!(active_sessions[0].peer, "bob");
1547                assert_eq!(reachability[0].rtt_ms, Some(42));
1548            }
1549            other => panic!("expected the snapshot first, got {other:?}"),
1550        }
1551        match sub.next().await.unwrap().unwrap() {
1552            StreamFrame::Event { record } => {
1553                assert_eq!(record.peer.as_deref(), Some("bob"));
1554                assert_eq!(record.service.as_deref(), Some("notes"));
1555            }
1556            other => panic!("expected the event, got {other:?}"),
1557        }
1558        assert_eq!(
1559            sub.next().await.unwrap(),
1560            Some(StreamFrame::Lagged { dropped: 12 })
1561        );
1562        assert_eq!(sub.next().await.unwrap(), None, "clean end of stream");
1563        server.await.unwrap();
1564    }
1565}