//! The wire: one JSON object per line, in both directions. //! //! `PROTOCOL.md` beside this file is the prose; this module is the only //! implementation, and `tests/protocol_vectors.rs` pins every message shape to //! `tests/fixtures/protocol-vectors.jsonl` so a rename is a red test rather //! than a client that silently stops understanding a field. //! //! WHY LINE-DELIMITED JSON AND NOT A BINARY FRAMING. Terminal bytes are the //! bulk of this traffic and base64 costs a third more of them. It is still the //! right phase-2 shape: ONE parser, one log format a person can read with //! `nc`, and vectors that are literally the file the tests compare. The place //! a binary framing belongs is the phone's own hop (design: the attach //! WebSocket carries binary frames), which is phase 3 and encodes nothing //! twice — the helper's socket is a loopback hop between two processes on one //! Mac. use std::collections::BTreeMap; use serde::{Deserialize, Serialize}; /// The refusal a line can earn. #[derive(Debug, thiserror::Error)] pub enum WireError { /// The line was longer than [`MAX_LINE_BYTES`]. Named rather than /// truncated: a client that sends a megabyte of JSON has a bug, and half a /// message parsed is worse than none. #[error("a protocol line was longer than {MAX_LINE_BYTES} bytes and was refused rather than truncated")] LineTooLong, /// The line was not the JSON this protocol speaks. #[error("a protocol line was not a message this host understands — {0}")] NotAMessage(#[from] serde_json::Error), /// The socket itself. #[error("the host socket: {0}")] Io(#[from] std::io::Error), } /// The ceiling on one line. /// /// A `data` line carries at most [`crate::pty::READ_CHUNK_BYTES`] of terminal /// output base64-encoded (a third larger), and every other message is small. /// One megabyte is far above the first and far below anything that could /// exhaust the reader. pub const MAX_LINE_BYTES: usize = 1024 * 1024; /// Which agent a session runs. /// /// Two, and no generalisation for a third until a third is in use. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum Tool { /// Anthropic's `claude`. Claude, /// OpenAI's `codex`. Codex, } impl Tool { /// The provider whose account this tool signs in with. pub fn provider(self) -> Provider { match self { Self::Claude => Provider::Anthropic, Self::Codex => Provider::Openai, } } /// The tool's name as `sample`'s `agents` map spells it. pub fn agent_key(self) -> &'static str { match self { Self::Claude => "claude-code", Self::Codex => "codex", } } } /// Whose subscription an account belongs to. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum Provider { /// `claude`'s login. Anthropic, /// `codex`'s login. Openai, } /// Whether the agent asks before it acts. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum PermissionMode { /// The default. The agent never raises a permission prompt, so no /// `PermissionRequest` hook fires and nothing blocks on the phone. Bypass, /// The agent asks, and the question travels to the phone. Ask, } /// What the person answered a permission request with. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum Decision { /// This once. Allow, /// No. Deny, /// This, and anything like it for the rest of the session. AllowSession, } /// What a session is doing. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum SessionState { /// Spawned; the agent has not said `SessionStart` yet. Starting, /// Working. Running, /// A turn finished and nothing is pending. Idle, /// Blocked on the person — see `waiting_kind`. Waiting, /// The process is gone. Ended, } /// What a waiting session is waiting for. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum WaitingKind { /// A `PermissionRequest` hook is blocked on an answer. Permission, /// The agent asked something. Question, /// The agent wants input and said so without asking anything. Input, } /// Who said a turn. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum TurnRole { /// The person. User, /// The agent. Assistant, } /// A turn, as an adapter read it out of the agent's own transcript. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct Turn { /// Who said it. pub role: TurnRole, /// What they said, joined from the transcript's content blocks. pub text: String, } /// Where one task on a session's list has got to. /// /// **Cotton's three words, not the agent's.** Claude Code says /// `pending|in_progress|completed`; Codex's plan tool says something else /// again. The translation happens once, in [`crate::tasks`], so the phone /// reads one vocabulary whatever wrote the list. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum TaskStatus { /// Not started. Open, /// The one the session is on. Active, /// Finished. Done, } /// One task of a session's list, as the agent's own task tool last wrote it. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct Task { /// Its place in the list — the index the agent wrote it at, so the phone /// renders the list in the order the session sees it. pub seq: u32, /// What it says. pub text: String, /// Where it has got to. pub status: TaskStatus, } /// An account's usage windows, as an adapter read them out of a forwarded /// event. /// /// Every field is optional because every one of them is genuinely absent /// sometimes — Claude reports no `rate_limits` until the first API response of /// a session, and a Codex `token_count` record carries a secondary window only /// for a plan that has one. An absent window is `null` and NEVER zero: a zero /// would read on the phone as "no usage at all", which is the opposite of "we /// have not been told". #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Usage { /// Whose account. pub provider: Provider, /// The signed-in address, when the forwarded event names one. pub email: Option, /// Percent of the five-hour window used. pub five_hour_pct: Option, /// When the five-hour window resets, RFC 3339. pub five_hour_resets_at: Option, /// Percent of the weekly window used. pub weekly_pct: Option, /// When the weekly window resets, RFC 3339. pub weekly_resets_at: Option, } /// Who an agent on this Mac is signed in as — the agent's OWN answer. /// /// Read by asking the agent (`claude auth status`), never by opening a file /// it keeps or a keychain item it owns: Cotton never touches a credential, /// and an address the agent prints about itself is not one. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct SignedIn { /// Whose account. pub provider: Provider, /// The signed-in address. Never empty: an agent that names no address is /// absent from [`MachineSample::accounts`]. pub email: String, /// The subscription as the agent words it (`max`, `pro`), when it says. #[serde(default)] pub plan: Option, } /// One session, as `list` reports it. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct SessionSummary { /// The host's own id for the session. pub session_id: String, /// The launch this session answered. /// /// EMPTY for an adopted session: nobody launched it, and a made-up launch /// id would be a row pointing at a queue entry that does not exist. pub launch_id: String, /// Which agent. pub tool: Tool, /// The agent's own session id, when it differs from the host's. /// /// `claude` takes ours (`--session-id`); `codex` mints its own and the /// host learns it from the `SessionStart` hook, which is what /// `codex resume ` later needs. pub agent_session_id: Option, /// Where it runs. pub cwd: String, /// RFC 3339. pub started_at: String, /// RFC 3339, once it has ended. pub ended_at: Option, /// What it is doing. pub state: SessionState, /// What it is waiting for, when it is waiting. pub waiting_kind: Option, /// The pending permission request, when one is blocked. pub request_id: Option, /// The exit code, when the process exited with one. pub exit_code: Option, /// The signal that ended it, when one did. pub exit_signal: Option, /// Whether this host still owns the pseudo-terminal. /// /// False for a session `index.json` remembers across a restart of the /// daemon: the scrollback is still readable, the agent is not. pub host_owned: bool, } /// What this machine looked like when it was sampled. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct MachineSample { /// Stable Mac hardware identity; absent on other platforms. #[serde(default)] pub hardware_id: Option, /// RFC 3339. pub sampled_at: String, /// One-minute load average. pub load1: f64, /// Free memory as a percentage, 0–100. pub mem_free_pct: u8, /// Total memory, gigabytes. pub mem_total_gb: f64, /// Free space on the data directory's volume, gigabytes. pub disk_free_gb: f64, /// Logical CPUs. pub cpu_count: u32, /// **WHAT THIS MACHINE IS** — the three constants /// ([`crate::machine::Facts`]): the chip's name (`Apple M4 Pro`), the /// operating system's version (`26.0.1`), and the size of the volume the /// data directory is on, gigabytes. Read once at `serve` start and carried /// on every sample so the app that connects late still learns them; the /// mirror writes them onto the device row ONCE — in their own op, apart /// from the reading — and again only when one changes. /// /// `None` is "would not say", never an empty string or a zero. Defaulted on /// the way IN, like every field added after the first release: a new app /// reads samples from an older helper that carries none. And LEFT OUT on /// the way out when `None`, so a sample from such a helper round-trips /// byte-for-byte — which is what the protocol vectors hold. #[serde(default, skip_serializing_if = "Option::is_none")] pub chip: Option, /// See [`Self::chip`]. #[serde(default, skip_serializing_if = "Option::is_none")] pub os_version: Option, /// See [`Self::chip`]. #[serde(default, skip_serializing_if = "Option::is_none")] pub disk_total_gb: Option, /// Sessions this host currently owns a pseudo-terminal for. pub sessions_running: u32, /// Whether `/tmp/tinmen-build.lock` is held by a process that is alive. /// /// REPORTED, no longer a throttle: the lock says somebody is building and /// says nothing about how big the build is. What admits work is /// [`Self::mem_committed_gb`]. pub build_lock_held: bool, /// **THE MEMORY THIS MAC HAS ALREADY PROMISED**, gigabytes — every coding /// session at its measured peak, plus what the heavy things Cotton did not /// start are holding right now, with nothing counted twice /// ([`crate::processes::committed_gb`]). /// /// Zero when the process table could not be read at all, which is the same /// number as an idle Mac: a reading that failed costs headroom, never a /// session its memory. /// /// Defaulted on the way IN, like every field added after the first /// release: a new app reads samples from an older helper that carries /// none. #[serde(default)] pub mem_committed_gb: f64, /// The largest ONE coding session's process tree has been measured at on /// this Mac, gigabytes — `None` while no session has been measured. /// /// This is what a dispatcher subtracts before admitting the next session, /// because a session that is reading a file this second still holds the /// build it will want back. #[serde(default)] pub session_peak_gb: Option, /// How many readings [`Self::session_peak_gb`] is drawn from. /// /// The peaks live in the helper's memory and a restart begins the count /// again, so a peak is only worth what its sample count says: one reading /// of an idle session is not a budget. #[serde(default)] pub session_peak_samples: u32, /// Installed agents, `claude-code` / `codex` to version. **An agent that /// is not installed is ABSENT from the map** — never a zero, never an /// empty string. Beside them, by their own keys: `npm`, and `developer-id` /// to the team of this Mac's Developer ID signing identity when it holds /// one (`machine::with_signing_identity`). pub agents: BTreeMap, /// **WHO EACH INSTALLED AGENT IS SIGNED IN AS**, `claude-code` / `codex` /// to a [`SignedIn`]. An agent that is signed out, or that will not say /// who it is signed in as, is ABSENT from the map. /// /// This is what lets a dispatcher place a session at all: a Mac with the /// agent installed and nobody signed in starts a session that stops at a /// login screen. Until 27 Sep 2026 nothing reported it, every Mac read as /// signed out, and every session asked for from the phone waited for a /// free Mac that was never going to be one. /// /// Defaulted on the way IN, like every field added after the first /// release: a new app reads samples from an older helper that carries /// none, and reads that Mac as signed out. /// /// And LEFT OUT on the way out when there is none, so a sample from a Mac /// nobody is signed in on is byte-for-byte the message it was before this /// field existed — which is what the protocol vectors hold. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub accounts: BTreeMap, /// This host's own version. /// /// The APP's version on a shipped helper — `crate::HOST_VERSION`, stamped /// from `CFBundleShortVersionString` by the packaging lane — and the /// crate's own with a `-dev` suffix on anything else. pub host_version: String, /// **WHICH EXECUTABLE THIS HOST IS RUNNING**, as /// [`crate::binary::Fingerprint::short`] spells it: the size and /// modification time of its own binary, read once at `serve` start. /// /// The version alone cannot tell a rebuild at the same version from the /// same build, and that is the whole of a development loop. Empty when the /// binary could not be stat'ed at all. /// /// Defaulted on the way IN, like every field added after the first /// release: the helper outlives the app, so a new app reads samples from /// an older helper that carries none. #[serde(default)] pub binary_fingerprint: String, /// **WHETHER THIS HOST IS WAITING TO RESTART ONTO A NEW BINARY.** /// /// True when the executable underneath it has been replaced — a Sparkle /// update — and host-owned sessions are still alive. It exits as soon as /// the last one ends; until then it says so in every sample rather than /// ending somebody's turn. `crate::binary`. #[serde(default)] pub update_pending: bool, } /// Client → daemon. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(tag = "t", rename_all = "snake_case")] pub enum Request { /// Start an agent in a new pseudo-terminal. Spawn { /// The launch row this answers. launch_id: String, /// The session id to use. Absent means the host mints one. #[serde(default, skip_serializing_if = "Option::is_none")] session_id: Option, /// Which agent. tool: Tool, /// Arguments appended after the ones the adapter owns. #[serde(default)] argv_extras: Vec, /// The working directory. cwd: String, /// Environment for the child, on top of the adapter's own. #[serde(default)] env: BTreeMap, /// Terminal width. cols: u16, /// Terminal height. rows: u16, /// Whether the agent asks before it acts. permission_mode: PermissionMode, /// **CONTINUE AN AGENT SESSION THAT ALREADY EXISTS**, rather than /// starting a new one. /// /// The AGENT's own session id, as this host recorded it — `claude` /// takes ours, `codex` mints its own and the host learns it from the /// `SessionStart` hook. The adapter turns it into `claude --resume /// ` or `codex resume `; with `--session-id` and `--resume` /// being contradictory, a resuming Claude launch carries only the /// second. Absent is an ordinary first start. /// /// The transcript lives on THIS Mac and nowhere else, so a resume is /// placed on the Mac the session ran on or it is not placed at all /// (`crates/cotton-ffi/src/phone/session_queue.rs`). #[serde(default, skip_serializing_if = "Option::is_none")] resume_from: Option, }, /// **Run a COMMAND in a pseudo-terminal, and nothing else.** /// /// A utility terminal is how the Mac app gets this machine ready without /// anybody opening Terminal.app: installing an agent, signing one in, /// asking Apple for the command line tools, cloning a repository. It is /// the person's own login environment, a real terminal and the bytes on /// the screen — and **no hooks, no session row, no index entry and no /// transcript adoption**, because none of those is true of it: nobody /// launched a coding session, and a card for one would be a card nothing /// could answer. /// /// It is attached to, written to, resized and stopped exactly as a session /// is — the id is simply namespaced (`util:…`) so nothing downstream can /// mistake one for a session. /// /// **One at a time per purpose.** A second `install-claude` while the /// first is running is refused by name rather than started beside it: /// two installers writing one directory is the failure nobody would be /// able to read afterwards. SpawnUtility { /// What this terminal is FOR, in one word a person could read — /// `install-claude`, `sign-in-codex`, `command-line-tools`, /// `clone-cottondb`. It is the key the one-at-a-time rule is kept on, /// and the name of the scrollback file, so it is held to letters, /// digits, `-` and `_`. purpose: String, /// The program and its arguments. `argv[0]` is resolved against the /// PERSON'S PATH, the same one a session runs on, so a utility that /// starts is a command they could have typed. argv: Vec, /// Where to run it. The person's home when absent. #[serde(default, skip_serializing_if = "Option::is_none")] cwd: Option, /// Environment for the child, on top of the login environment. #[serde(default)] env: BTreeMap, /// The viewer's width, if it has one yet. #[serde(default, skip_serializing_if = "Option::is_none")] cols: Option, /// The viewer's height, if it has one yet. #[serde(default, skip_serializing_if = "Option::is_none")] rows: Option, }, /// Take this connection over as a terminal stream. Attach { /// Which session. session_id: String, /// The viewer's width. cols: u16, /// The viewer's height. rows: u16, /// Resume from this scrollback offset rather than from the tail. #[serde(default, skip_serializing_if = "Option::is_none")] from_offset: Option, }, /// Keystrokes, base64. Write { /// Which session. session_id: String, /// The bytes. b: String, }, /// The viewer resized. Resize { /// Which session. session_id: String, /// New width. cols: u16, /// New height. rows: u16, }, /// Stop streaming on this connection. The session keeps running. Detach, /// End the session: SIGINT, SIGTERM, SIGKILL, on the schedule in /// [`crate::pty::StopSchedule`]. Stop { /// Which session. session_id: String, }, /// Answer a blocked permission request. Decide { /// Which session. session_id: String, /// Which request. request_id: String, /// The answer. decision: Decision, }, /// Every session this host knows about, running or remembered. List, /// Turn this connection into an event stream. Subscribe, /// Sample this machine now. Sample, /// **RESTART ONTO THE EXECUTABLE THAT IS THERE NOW.** /// /// The helper exits 0 and launchd's `KeepAlive` starts whatever is at its /// path — which after a Sparkle update is the new bundle's binary. It is /// asked by the BUNDLED binary at app launch /// (`cotton-session-host restart`), never by a phone: which helper a Mac /// runs is that Mac's business. /// /// **A live session outranks it.** With host-owned sessions running the /// helper answers `restarting: false`, marks `update_pending` and exits /// when the last one ends — restarting the daemon ends its children, and /// an update is not a reason to end somebody's turn. Restart, /// A hook's JSON, forwarded by `cotton-session-host hook `. Hook { /// The event name the agent fired. event: String, /// The session the hook belongs to, as the agent named it. #[serde(default, skip_serializing_if = "Option::is_none")] session_id: Option, /// What arrived on the hook's stdin, verbatim. payload: serde_json::Value, }, /// A status line's JSON, forwarded by `cotton-session-host statusline`. Statusline { /// The session it belongs to. #[serde(default, skip_serializing_if = "Option::is_none")] session_id: Option, /// What arrived on stdin, verbatim. payload: serde_json::Value, }, } /// Daemon → client. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(tag = "t", rename_all = "snake_case")] pub enum Event { /// A `spawn` succeeded. Spawned { /// The host's id for the new session. session_id: String, /// The launch it answered. launch_id: String, /// The agent's pid. pid: Option, }, /// A `spawn_utility` succeeded. /// /// Deliberately NOT a `spawned`: a utility is not a session, and the one /// thing that must never happen is a client writing a `cotton_sessions` /// row for a `curl | bash`. UtilityStarted { /// The id to attach on — `util::`. id: String, /// What it is for, as the request named it. purpose: String, /// The process. pid: Option, }, /// A utility's process is gone, and this host has reaped it. /// /// **A fresh `sample` follows it**, because a utility is the one thing on /// this Mac that CHANGES what a sample says — an install that just /// finished is an agent that is now installed, and the panel would /// otherwise show *not installed* until the fifteen-minute timer came /// round. UtilityEnded { /// Which utility. id: String, /// What it was for. purpose: String, /// Its exit code, when it had one. code: Option, /// The signal that ended it, when one did. signal: Option, /// When, RFC 3339 — this host's own reading, the same one `exited` /// carries. at: String, }, /// An `attach` succeeded; `data` lines follow. Attached { /// Which session. session_id: String, /// The scrollback offset the first `data` line starts at. offset: u64, }, /// Terminal output, base64. Data { /// Which session. session_id: String, /// The bytes. b: String, }, /// The answer to `list`. Sessions { /// Every session, newest last. sessions: Vec, }, /// A session this host did NOT spawn, found in an agent's own transcript. /// /// The registration an adopted session gets in place of a `spawned`: /// nobody launched it, so there is no launch id and no pseudo-terminal — /// what the client needs to write a `host_owned = 0` row is which agent, /// where it runs and when it started. `state`, `turn` and `exited` follow /// for it exactly as they do for a hosted session. /// `crates/cotton-session-host/src/adopted.rs`. Adopted { /// The agent's own session id, which is also the row's `external_id`. session_id: String, /// Which agent. tool: Tool, /// Where it runs, when the transcript says. #[serde(default, skip_serializing_if = "Option::is_none")] cwd: Option, /// RFC 3339 — the transcript's own first stamp, else when this host /// first saw the file. started_at: String, }, /// A session changed what it is doing. State { /// Which session. session_id: String, /// What it is doing now. state: SessionState, /// What it is waiting for, when it is waiting. #[serde(default, skip_serializing_if = "Option::is_none")] waiting_kind: Option, /// The pending permission request, when one is blocked. #[serde(default, skip_serializing_if = "Option::is_none")] request_id: Option, }, /// A turn finished. Turn { /// Which session. session_id: String, /// Who said it. role: TurnRole, /// What they said. text: String, /// The turn's position in this session, from 1. seq: u64, }, /// A turn finished in a session whose turns the agent's own `Stop` hook /// logs (the session-log hook script, through `log_session`). /// /// **The hook is that session's ONE source of turns.** It numbers a turn /// by its line in the transcript and this host by what it sampled, and /// both numberings land on one `(session, seq)` prompt row — so a `turn` /// from here would overwrite an unrelated turn of the hook's. What this /// carries instead is what only this host reads: the card's last line /// and that the session was active. No prompt row, no seq. Spoke { /// Which session. session_id: String, /// Who said it. role: TurnRole, /// What they said. text: String, }, /// The session's WHOLE task list, as the agent's own task tool just wrote /// it. /// /// Never a delta: the agent rewrites the list every time it touches one /// task, so this event replaces whatever the row held. An empty `tasks` is /// therefore a real message — the session cleared its list — and not a /// reading that failed, which is why it is sent rather than skipped. Tasks { /// Which session. session_id: String, /// The list, in the agent's own order. tasks: Vec, }, /// An account's windows, as a forwarded event reported them. Usage { /// The reading. #[serde(flatten)] usage: Usage, }, /// A machine sample. Sample { /// The reading. #[serde(flatten)] sample: MachineSample, }, /// A session's process is gone. Exited { /// Which session. session_id: String, /// Its exit code, when it had one. code: Option, /// The signal that ended it, when one did. signal: Option, /// WHEN it ended, RFC 3339 — the host's own answer, never the /// mirror's. /// /// A hosted session carries the instant the host reaped it, which is /// the same stamp its index wrote. An ADOPTED one carries the /// TRANSCRIPT'S last write: the host learns a file went quiet hours /// after the last line was written, and stamping `ended_at` with the /// moment of the discovery would put a session that stopped at /// lunchtime on the card as having ended at midnight (`adopted.rs`). /// /// Optional on the wire for the reason every other added field is: the /// helper outlives the app and an older one sends none, which reads as /// "now" exactly as it always did. #[serde(default, skip_serializing_if = "Option::is_none")] at: Option, /// Why it ended, when that was a failure: its terminal's last line /// ([`crate::exit_reason`]) — what the session row's `error` says. #[serde(default, skip_serializing_if = "Option::is_none")] error: Option, }, /// The answer to a blocked `hook PermissionRequest` connection: the exact /// JSON that hook must print on its stdout. /// /// Encoded HERE, by the session's own adapter, so the `hook` subcommand /// knows nothing about either agent's decision dialect. Decision { /// Which session. session_id: String, /// Which request. request_id: String, /// What to print. stdout: serde_json::Value, }, /// What a `restart` decided. /// /// Answered on the connection that asked, BEFORE the process goes, so the /// asker learns which of the two happened rather than inferring it from a /// socket that closed. Restarting { /// Whether the helper is exiting now. False means it is waiting for /// its sessions. restarting: bool, /// How many host-owned sessions are holding it. sessions_running: u32, }, /// The request was accepted and has no answer of its own. Ok, /// The request was refused, with the reason a person reads. Error { /// The sentence. message: String, }, } /// Encode one message as the line that carries it, newline included. pub fn line(message: &T) -> Result { let mut text = serde_json::to_string(message)?; text.push('\n'); Ok(text) } /// Decode one line, newline optional. pub fn parse Deserialize<'de>>(text: &str) -> Result { if text.len() > MAX_LINE_BYTES { return Err(WireError::LineTooLong); } Ok(serde_json::from_str(text.trim_end_matches(['\r', '\n']))?) } #[cfg(test)] #[path = "protocol_tests.rs"] mod protocol_tests;