Skip to main content

kintsugi_daemon/
ipc.rs

1//! Local IPC transport between interception and the daemon.
2//!
3//! Wire format: one newline-delimited JSON value per message. The interception
4//! side connects and sends a [`Request`]; the daemon replies with a [`Response`].
5//! A `Propose` carries a [`ProposedCommand`] and is answered with a [`Verdict`];
6//! a `Resolve` records a human's decision on a held command and is answered with
7//! `Ack`. Transport is a Unix domain socket (filesystem) or a Windows named pipe
8//! (namespaced), abstracted by the `interprocess` crate.
9
10use std::io::{BufRead, BufReader, Read, Write};
11use std::path::PathBuf;
12
13use anyhow::{Context, Result};
14use interprocess::local_socket::prelude::*;
15#[cfg(unix)]
16use interprocess::local_socket::GenericFilePath;
17#[cfg(not(unix))]
18use interprocess::local_socket::GenericNamespaced;
19use interprocess::local_socket::{ListenerOptions, Name, Stream};
20use kintsugi_core::{Decision, ProposedCommand, Verdict};
21use serde::{Deserialize, Serialize};
22
23/// A request from interception to the daemon.
24#[derive(Debug, Clone, Serialize, Deserialize)]
25#[serde(tag = "kind", rename_all = "lowercase")]
26pub enum Request {
27    /// "Here is a command I'm about to run — what's the verdict?"
28    Propose(ProposedCommand),
29    /// "A human resolved a held command; record it (and maybe remember it)."
30    Resolve(Resolution),
31    /// "I observed a filesystem change that bypassed interception — just record
32    /// it." The backstop sends these so the daemon's single writer keeps the hash
33    /// chain intact.
34    Observe(Observation),
35    /// "I observed an agent ingest untrusted content (a web fetch, a search, an MCP
36    /// result, an out-of-workspace read, a download)." Provenance taint input
37    /// (P6.2): the daemon labels the session; it never blocks on this — observation
38    /// only labels, the trifecta rule decides later.
39    Ingest(kintsugi_core::ObservedIngest),
40    /// "An agent session wrote this file." Provenance propagation input (V1.1):
41    /// a tainted session taints the path it writes, so a later reader inherits the
42    /// taint. `path` is an identifier — the write content never leaves the agent.
43    /// Observation only (never blocks), gated on the cwd's `[provenance]` policy
44    /// exactly like the trifecta floor.
45    WriteObserved {
46        session: String,
47        path: String,
48        cwd: PathBuf,
49    },
50    /// "An agent session read this file." The consumer half of the write
51    /// propagation: if an earlier tainted session labelled `path`, the reader now
52    /// inherits that taint (and its later egress sink trips the trifecta).
53    /// `path` is an identifier — the file content never leaves the agent, and this
54    /// never blocks, never enqueues, and never touches a command verdict.
55    ReadObserved {
56        session: String,
57        path: String,
58        cwd: PathBuf,
59    },
60    /// "Show me the provenance trail for this command" (P6.4). A read-only query for
61    /// the CLI/TUI: the daemon returns the session's untrusted reads plus this
62    /// command's sensitive-read → egress-sink → rule chain. Identifiers only.
63    Provenance(ProposedCommand),
64    /// "A human (no AI agent) already ran this shell command — record it for the
65    /// audit trail." Passive session recording: the daemon classifies it (so a
66    /// destructive command is flagged in the timeline) but never blocks or
67    /// snapshots, because by the time we hear about it the command has run.
68    Record(ProposedCommand),
69    /// "List the commands currently held for approval."
70    ListPending,
71    /// "What is the status of this queued command?" (`pending`/`approved`/`denied`).
72    // Struct variants (not newtype-of-String): serde's internally-tagged enums
73    // cannot represent a tagged newtype wrapping a primitive.
74    PendingStatus { id: String },
75    /// "A human approved this queued command id." Since Phase 7 (anchored
76    /// trust) this is a *privileged* op on a locked daemon: it carries the
77    /// nonce + proof from `AuthBegin { op: "approve:<id>" }`. A bare approve
78    /// (both fields absent) is refused loudly, audited, and throttled under the
79    /// default policy (`[security] require_approval_proof = true`); a daemon
80    /// with no vault accepts it bare (the shutdown mirror — there is no secret
81    /// to prove possession of).
82    Approve {
83        id: String,
84        /// The challenge nonce + proof (hex). `None` on the bare path —
85        /// modeled as absence, NOT an empty string, so no placeholder ever
86        /// flows into the proof-verification crypto sink.
87        nonce: Option<String>,
88        /// See `nonce`.
89        proof: Option<String>,
90    },
91    /// "A human denied this queued command id." Stays bare by design: an agent
92    /// denying its own held command is a nuisance, not a threat.
93    Deny { id: String },
94    /// "Drop every still-pending entry from the queue without recording an audit
95    /// row per one — the bulk recovery for orphaned holds."
96    PrunePending,
97    /// "What is the daemon's runtime status?" — currently the active scorer, so
98    /// callers can tell whether the local model loaded or it's on the heuristic
99    /// fallback.
100    Status,
101    /// "I want to perform a privileged operation `op` (e.g. shutdown) — give me a
102    /// challenge." The daemon replies with a [`Response::Challenge`]. Auth is
103    /// enforced by the *daemon*, against the vault IT loaded at startup, so the
104    /// caller's environment can't point the check at a different/empty vault.
105    AuthBegin { op: String },
106    /// "Here is the challenge proof for `op`; do it." Currently only shutdown.
107    Shutdown {
108        op: String,
109        /// The challenge nonce + proof (hex). `None` on the unauthenticated path
110        /// (no vault provisioned) — modeled as absence, NOT an empty string, so
111        /// no placeholder ever flows into the proof-verification crypto sink.
112        nonce: Option<String>,
113        proof: Option<String>,
114    },
115}
116
117/// A filesystem change observed by the backstop watcher.
118#[derive(Debug, Clone, Serialize, Deserialize)]
119pub struct Observation {
120    /// `created` | `modified` | `removed`. Serialized as `change` so it never
121    /// collides with the enum's internal `kind` tag.
122    #[serde(rename = "change")]
123    pub kind: String,
124    /// The path that changed.
125    pub path: String,
126}
127
128/// A human's resolution of a held command.
129#[derive(Debug, Clone, Serialize, Deserialize)]
130pub struct Resolution {
131    /// The original command being resolved.
132    pub command: ProposedCommand,
133    /// The human's decision — `Allow` or `Deny` (never `Hold`).
134    pub decision: Decision,
135    /// Whether to remember this decision for this exact command in this repo.
136    pub remember: bool,
137}
138
139/// The daemon's reply.
140#[derive(Debug, Clone, Serialize, Deserialize)]
141#[serde(tag = "kind", rename_all = "lowercase")]
142pub enum Response {
143    /// Verdict for a `Propose`.
144    Verdict(Verdict),
145    /// Acknowledgement of a `Resolve`/`Approve`/`Deny`/`Observe`.
146    Ack,
147    /// The approval queue (reply to `ListPending`). A struct variant because
148    /// serde's internally-tagged enums cannot wrap a bare sequence.
149    PendingList {
150        items: Vec<kintsugi_core::PendingItem>,
151    },
152    /// The status of a queued command (reply to `PendingStatus`): `pending` |
153    /// `approved` | `denied` | `gone` (not in the queue).
154    Pending { status: String },
155    /// The daemon's runtime status (reply to `Status`). `scorer` is the active
156    /// backend id, e.g. `heuristic` or `llama:Qwen3-4B-Instruct-2507-Q4_K_M`.
157    Status { scorer: String },
158    /// The provenance trail for a command (reply to `Provenance`). `tainted` is the
159    /// session's current taint state; `trail` is the ordered, identifier-only chain.
160    Provenance {
161        tainted: bool,
162        trail: Vec<kintsugi_core::ProvStep>,
163    },
164    /// Reply to `AuthBegin`: a fresh challenge. `locked` is false when the daemon
165    /// has no vault (then no proof is needed); otherwise the caller derives the
166    /// proof from `nonce` + `salt` + `params` and the admin password.
167    Challenge {
168        locked: bool,
169        nonce: String,
170        salt: String,
171        params: kintsugi_core::admin::KdfParams,
172    },
173    /// Something went wrong handling the request.
174    Error { message: String },
175}
176
177/// Resolve the socket path. Override with `KINTSUGI_SOCKET` (handy in tests).
178///
179/// On Unix this is a filesystem path under `$XDG_RUNTIME_DIR` (falling back to
180/// the temp dir). On Windows a namespaced pipe name is used instead.
181pub fn socket_path() -> PathBuf {
182    if let Ok(p) = std::env::var("KINTSUGI_SOCKET") {
183        return PathBuf::from(p);
184    }
185    #[cfg(unix)]
186    {
187        // $XDG_RUNTIME_DIR is already a per-user 0700 dir — the right home.
188        if let Ok(rt) = std::env::var("XDG_RUNTIME_DIR") {
189            if !rt.is_empty() {
190                return PathBuf::from(rt).join("kintsugi.sock");
191            }
192        }
193        // Otherwise use the per-user data dir (created 0700 at bind), never the
194        // world-writable temp dir, so another local user can't pre-create or
195        // connect to the socket.
196        if let Some(dirs) = directories::ProjectDirs::from("", "", "kintsugi") {
197            return dirs.data_dir().join("kintsugi.sock");
198        }
199        std::env::temp_dir().join("kintsugi.sock")
200    }
201    #[cfg(not(unix))]
202    {
203        PathBuf::from(r"\\.\pipe\kintsugi")
204    }
205}
206
207/// Best-effort chmod on Unix (no-op elsewhere). Used to keep the socket and its
208/// parent dir private to the owning user.
209#[cfg(unix)]
210pub(crate) fn set_mode(path: &std::path::Path, mode: u32) {
211    use std::os::unix::fs::PermissionsExt;
212    let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode));
213}
214
215/// Build the `interprocess` name for the current platform.
216fn make_name() -> Result<Name<'static>> {
217    let path = socket_path();
218    #[cfg(unix)]
219    {
220        path.clone()
221            .to_fs_name::<GenericFilePath>()
222            .with_context(|| format!("invalid socket path {}", path.display()))
223    }
224    #[cfg(not(unix))]
225    {
226        let _ = &path;
227        "kintsugi"
228            .to_ns_name::<GenericNamespaced>()
229            .context("invalid namespaced pipe name")
230    }
231}
232
233/// Write one JSON message followed by a newline.
234fn write_message<W: Write, T: Serialize>(w: &mut W, value: &T) -> Result<()> {
235    let mut line = serde_json::to_string(value).context("serialize IPC message")?;
236    line.push('\n');
237    w.write_all(line.as_bytes()).context("write IPC message")?;
238    w.flush().context("flush IPC message")?;
239    Ok(())
240}
241
242/// Maximum size of a single IPC message. Bounds memory so a misbehaving or
243/// hostile local peer can't OOM/stall the single-threaded daemon with a giant or
244/// newline-free stream.
245pub const MAX_FRAME: u64 = 16 * 1024 * 1024;
246
247/// Read one newline-delimited JSON message from a length-bounded reader.
248fn read_message<R: BufRead, T: serde::de::DeserializeOwned>(r: &mut R) -> Result<T> {
249    let mut line = String::new();
250    let n = r.read_line(&mut line).context("read IPC message")?;
251    if n == 0 {
252        anyhow::bail!("connection closed before a message was received");
253    }
254    if !line.ends_with('\n') && n as u64 >= MAX_FRAME {
255        anyhow::bail!("IPC message exceeds {MAX_FRAME} bytes");
256    }
257    serde_json::from_str(line.trim_end()).context("deserialize IPC message")
258}
259
260/// Wrap a stream in a length-bounded buffered reader (see [`MAX_FRAME`]).
261fn bounded(stream: &mut Stream) -> BufReader<std::io::Take<&mut Stream>> {
262    BufReader::new(stream.take(MAX_FRAME))
263}
264
265/// Expect an `Ack`, mapping anything else to an error.
266fn expect_ack(resp: Response) -> Result<()> {
267    match resp {
268        Response::Ack => Ok(()),
269        Response::Error { message } => anyhow::bail!("daemon error: {message}"),
270        _ => anyhow::bail!("unexpected response (wanted Ack)"),
271    }
272}
273
274/// Send a request and read the response on a fresh connection.
275fn round_trip(req: &Request) -> Result<Response> {
276    round_trip_within(req, None)
277}
278
279/// The same round-trip with an optional read deadline. A daemon that is alive but
280/// busy (the serve loop is single-threaded) would otherwise block the caller
281/// indefinitely — which, for the TUI, means freezing its event loop on the primary
282/// navigation key.
283fn round_trip_within(req: &Request, timeout: Option<std::time::Duration>) -> Result<Response> {
284    let name = make_name()?;
285    let mut stream =
286        Stream::connect(name).context("connect to kintsugi daemon (is it running?)")?;
287    // Unix only: a named-pipe stream on Windows does not honour a read timeout
288    // (setting one either errors or defeats the read), and propagating that turned a
289    // convenience bound into a hard failure for every Windows caller. The bound
290    // exists so the TUI's event loop cannot wedge on a wedged daemon — never as a
291    // security control — so Windows keeps the previous unbounded read.
292    #[cfg(unix)]
293    if let Some(t) = timeout {
294        stream.set_recv_timeout(Some(t))?;
295    }
296    #[cfg(not(unix))]
297    let _ = timeout;
298    write_message(&mut stream, req)?;
299    let mut reader = bounded(&mut stream);
300    read_message(&mut reader)
301}
302
303/// Client side: connect, send a request, and block for the response.
304pub struct Client;
305
306impl Client {
307    /// Propose a command and await its verdict.
308    pub fn send(cmd: &ProposedCommand) -> Result<Verdict> {
309        match round_trip(&Request::Propose(cmd.clone()))? {
310            Response::Verdict(v) => Ok(v),
311            Response::Error { message } => anyhow::bail!("daemon error: {message}"),
312            _ => anyhow::bail!("unexpected response to Propose"),
313        }
314    }
315
316    /// Record a human's resolution of a held command.
317    pub fn resolve(resolution: &Resolution) -> Result<()> {
318        expect_ack(round_trip(&Request::Resolve(resolution.clone()))?)
319    }
320
321    /// Record an observed filesystem change (backstop).
322    pub fn observe(observation: &Observation) -> Result<()> {
323        expect_ack(round_trip(&Request::Observe(observation.clone()))?)
324    }
325
326    /// Report an observed untrusted-content ingestion (provenance taint input).
327    pub fn ingest(observed: &kintsugi_core::ObservedIngest) -> Result<()> {
328        expect_ack(round_trip(&Request::Ingest(observed.clone()))?)
329    }
330
331    /// Report a file write by an agent session (provenance write propagation).
332    pub fn write_observed(session: &str, path: &str, cwd: &std::path::Path) -> Result<()> {
333        expect_ack(round_trip(&Request::WriteObserved {
334            session: session.to_string(),
335            path: path.to_string(),
336            cwd: cwd.to_path_buf(),
337        })?)
338    }
339
340    /// Report a file read by an agent session (provenance read propagation).
341    pub fn read_observed(session: &str, path: &str, cwd: &std::path::Path) -> Result<()> {
342        expect_ack(round_trip(&Request::ReadObserved {
343            session: session.to_string(),
344            path: path.to_string(),
345            cwd: cwd.to_path_buf(),
346        })?)
347    }
348
349    /// Fetch the provenance trail for a command: `(tainted, trail)`.
350    ///
351    /// Bounded: this is the call the TUI makes when you open a Detail view, and an
352    /// unbounded wait there freezes the whole interface for as long as the daemon
353    /// takes. The budget is deliberately generous — a cold local-socket connect plus
354    /// a single SQLite read measured multiple seconds on `windows-latest` CI, so a
355    /// tight bound would turn a slow machine into a false "daemon busy". Past it the
356    /// caller gets an error it can render honestly instead of a hung window.
357    pub const PROVENANCE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
358
359    pub fn provenance(cmd: &ProposedCommand) -> Result<(bool, Vec<kintsugi_core::ProvStep>)> {
360        let resp = round_trip_within(
361            &Request::Provenance(cmd.clone()),
362            Some(Self::PROVENANCE_TIMEOUT),
363        )?;
364        match resp {
365            Response::Provenance { tainted, trail } => Ok((tainted, trail)),
366            Response::Error { message } => anyhow::bail!("daemon error: {message}"),
367            _ => anyhow::bail!("unexpected response to Provenance"),
368        }
369    }
370
371    /// Record a shell command a human already ran (passive session recording).
372    pub fn record(cmd: &ProposedCommand) -> Result<()> {
373        expect_ack(round_trip(&Request::Record(cmd.clone()))?)
374    }
375
376    /// List the commands currently held for approval.
377    pub fn list_pending() -> Result<Vec<kintsugi_core::PendingItem>> {
378        match round_trip(&Request::ListPending)? {
379            Response::PendingList { items } => Ok(items),
380            Response::Error { message } => anyhow::bail!("daemon error: {message}"),
381            _ => anyhow::bail!("unexpected response to ListPending"),
382        }
383    }
384
385    /// The status of a queued command: `pending` | `approved` | `denied` | `gone`.
386    pub fn pending_status(id: &str) -> Result<String> {
387        match round_trip(&Request::PendingStatus { id: id.to_string() })? {
388            Response::Pending { status } => Ok(status),
389            Response::Error { message } => anyhow::bail!("daemon error: {message}"),
390            _ => anyhow::bail!("unexpected response to PendingStatus"),
391        }
392    }
393
394    /// Approve a queued command bare — no proof. Kept for callers that predate
395    /// approval auth (the TUI, the desktop app). A daemon with a provisioned
396    /// vault under the default policy refuses this with a loud, actionable
397    /// error ("approval requires proof — run `kintsugi approve <id>`"), which
398    /// those callers surface verbatim; the human then approves interactively.
399    pub fn approve(id: &str) -> Result<()> {
400        Self::approve_with_proof(id, None, None)
401    }
402
403    /// Approve a queued command with the nonce-bound proof from
404    /// [`auth_begin`](Self::auth_begin)`("approve:<id>")`. Pass
405    /// `Some(nonce_hex)` + `Some(proof_hex)` for the authenticated path; pass
406    /// `None`/`None` when the daemon reported no vault (`locked = false`) and
407    /// no proof is required. Absence is modeled as `None`, never an empty
408    /// string, so a placeholder can't be mistaken for a real nonce.
409    pub fn approve_with_proof(id: &str, nonce: Option<&str>, proof: Option<&str>) -> Result<()> {
410        expect_ack(round_trip(&Request::Approve {
411            id: id.to_string(),
412            nonce: nonce.map(str::to_string),
413            proof: proof.map(str::to_string),
414        })?)
415    }
416
417    /// Deny a queued command.
418    pub fn deny(id: &str) -> Result<()> {
419        expect_ack(round_trip(&Request::Deny { id: id.to_string() })?)
420    }
421
422    /// Prune every still-pending entry from the queue without recording a
423    /// human:deny per one — recovery for orphaned holds. Returns the count
424    /// pruned (reported by the daemon via a `Pending { status: "N" }` reply).
425    pub fn prune_pending() -> Result<u64> {
426        match round_trip(&Request::PrunePending)? {
427            Response::Pending { status } => status
428                .parse()
429                .map_err(|e| anyhow::anyhow!("bad count: {e}")),
430            Response::Error { message } => anyhow::bail!("daemon error: {message}"),
431            _ => anyhow::bail!("unexpected response to PrunePending"),
432        }
433    }
434
435    /// The daemon's active scorer backend id (e.g. `heuristic` or
436    /// `llama:<model>`). Lets callers report whether the local model is loaded.
437    pub fn status_scorer() -> Result<String> {
438        match round_trip(&Request::Status)? {
439            Response::Status { scorer } => Ok(scorer),
440            Response::Error { message } => anyhow::bail!("daemon error: {message}"),
441            _ => anyhow::bail!("unexpected response to Status"),
442        }
443    }
444
445    /// Begin authenticating a privileged op; returns (locked, nonce, salt, params).
446    pub fn auth_begin(op: &str) -> Result<(bool, String, String, kintsugi_core::admin::KdfParams)> {
447        match round_trip(&Request::AuthBegin { op: op.to_string() })? {
448            Response::Challenge {
449                locked,
450                nonce,
451                salt,
452                params,
453            } => Ok((locked, nonce, salt, params)),
454            Response::Error { message } => anyhow::bail!("daemon error: {message}"),
455            _ => anyhow::bail!("unexpected response to AuthBegin"),
456        }
457    }
458
459    /// Complete a shutdown. Pass `Some(nonce_hex)` + `Some(proof_hex)` for the
460    /// authenticated path (a provisioned vault); pass `None`/`None` when no vault
461    /// is set and no proof is required. Absence is modeled as `None`, never an
462    /// empty string, so a placeholder can't be mistaken for a real nonce.
463    pub fn shutdown(op: &str, nonce: Option<&str>, proof: Option<&str>) -> Result<()> {
464        expect_ack(round_trip(&Request::Shutdown {
465            op: op.to_string(),
466            nonce: nonce.map(str::to_string),
467            proof: proof.map(str::to_string),
468        })?)
469    }
470
471    /// Whether a daemon appears to be listening.
472    pub fn is_daemon_running() -> bool {
473        match make_name() {
474            Ok(name) => Stream::connect(name).is_ok(),
475            Err(_) => false,
476        }
477    }
478}
479
480/// Server side: a bound listener that dispatches each request to a handler.
481pub struct Server {
482    listener: interprocess::local_socket::Listener,
483}
484
485impl Server {
486    /// Bind the listener, clearing any stale Unix socket file first.
487    pub fn bind() -> Result<Self> {
488        // Refuse to start a second daemon: two writers would race on the event
489        // log's prev_hash and split the timeline. Clearing the stale socket below
490        // would otherwise let a second instance silently steal the endpoint.
491        if Client::is_daemon_running() {
492            anyhow::bail!(
493                "a kintsugi daemon is already running on {}",
494                socket_path().display()
495            );
496        }
497        #[cfg(unix)]
498        {
499            let path = socket_path();
500            // Ensure a private parent dir (0700) so peers can't pre-create the
501            // socket, then clear any stale socket file.
502            if let Some(parent) = path.parent() {
503                let _ = std::fs::create_dir_all(parent);
504                set_mode(parent, 0o700);
505            }
506            if path.exists() {
507                let _ = std::fs::remove_file(&path);
508            }
509        }
510        let name = make_name()?;
511        let listener = ListenerOptions::new()
512            .name(name)
513            .create_sync()
514            .context("bind kintsugi daemon socket")?;
515        // Restrict the socket to the owning user (no group/other access), so on a
516        // shared host another user can't connect and Approve/Deny/Resolve.
517        #[cfg(unix)]
518        set_mode(&socket_path(), 0o600);
519        Ok(Self { listener })
520    }
521
522    /// The path/name the server is listening on.
523    pub fn endpoint() -> PathBuf {
524        socket_path()
525    }
526
527    /// Serve connections sequentially, calling `handler` for each request.
528    pub fn serve<F>(self, mut handler: F) -> Result<()>
529    where
530        F: FnMut(Request) -> Response,
531    {
532        for incoming in self.listener.incoming() {
533            let stream = match incoming {
534                Ok(s) => s,
535                Err(e) => {
536                    eprintln!("kintsugi-daemon: accept error: {e}");
537                    continue;
538                }
539            };
540            if let Err(e) = Self::handle_one(stream, &mut handler) {
541                eprintln!("kintsugi-daemon: connection error: {e}");
542            }
543        }
544        Ok(())
545    }
546
547    /// Serve connections until `stop()` returns true (checked after each one).
548    /// Lets a handler request its own shutdown (e.g. an authenticated `Shutdown`).
549    pub fn serve_until<F, S>(self, mut handler: F, stop: S) -> Result<()>
550    where
551        F: FnMut(Request) -> Response,
552        S: Fn() -> bool,
553    {
554        for incoming in self.listener.incoming() {
555            let stream = match incoming {
556                Ok(s) => s,
557                Err(e) => {
558                    eprintln!("kintsugi-daemon: accept error: {e}");
559                    continue;
560                }
561            };
562            if let Err(e) = Self::handle_one(stream, &mut handler) {
563                eprintln!("kintsugi-daemon: connection error: {e}");
564            }
565            if stop() {
566                break;
567            }
568        }
569        Ok(())
570    }
571
572    /// Serve exactly `count` connections then stop. Used by tests.
573    pub fn serve_n<F>(self, count: usize, mut handler: F) -> Result<()>
574    where
575        F: FnMut(Request) -> Response,
576    {
577        if count == 0 {
578            return Ok(());
579        }
580        let mut served = 0;
581        for incoming in self.listener.incoming() {
582            let stream = incoming.context("accept connection")?;
583            Self::handle_one(stream, &mut handler)?;
584            served += 1;
585            if served >= count {
586                break;
587            }
588        }
589        Ok(())
590    }
591
592    fn handle_one<F>(mut stream: Stream, handler: &mut F) -> Result<()>
593    where
594        F: FnMut(Request) -> Response,
595    {
596        // Read the request line directly (rather than via `read_message`) so we can
597        // tell a *benign* zero-byte disconnect — a peer that connected and closed
598        // without sending, e.g. `is_daemon_running`'s liveness probe — apart from a
599        // real protocol error. A probe is not worth logging; treat it as a no-op.
600        let mut line = String::new();
601        let n = {
602            let mut reader = bounded(&mut stream);
603            reader.read_line(&mut line).context("read IPC message")?
604        };
605        if n == 0 {
606            return Ok(()); // connected then closed with no message — nothing to do
607        }
608        if !line.ends_with('\n') && n as u64 >= MAX_FRAME {
609            anyhow::bail!("IPC message exceeds {MAX_FRAME} bytes");
610        }
611        let req: Request =
612            serde_json::from_str(line.trim_end()).context("deserialize IPC message")?;
613        let resp = handler(req);
614        write_message(&mut stream, &resp)?;
615        Ok(())
616    }
617}