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