# The session host's socket protocol > The wire between CottonDB for Mac and the process that owns the coding > agents' terminals. Phase 2 of the Code tool. The one implementation is > `src/protocol.rs`; every message below is pinned by > `tests/fixtures/protocol-vectors.jsonl` and > `tests/fixtures/protocol-events.jsonl`, round-tripped in > `tests/protocol_vectors.rs`. ## The socket `~/Library/Application Support/Cotton/session-host.sock` (Cotton Dev: `…/CottonDev`), its log `session-host.log` beside it, mode **0600** — anything that can write it can run a process as the person and read their terminal, so there is no group and no other on it. `~/CottonDB` is retired on every Mac, so nothing of the host's is under it. With `$COTTON_MAC_DATA_DIR` set (a lane's synthetic folder) the socket and log are in that folder instead (`src/data_dir.rs`, `Layout`). **One host per data directory.** A second daemon finds the socket, connects to it, and refuses by name when somebody answers. A socket node a crash left behind — nothing listening, so the connect is refused — is unlinked and rebound. Anything at that path that is *not* a socket is a named refusal and is never deleted: a host does not remove a file it does not understand out of the person's data directory. ## Framing **One JSON object per line, UTF-8, newline-terminated, in both directions.** Terminal bytes travel base64 in a `data` message. A line is refused past 1 MiB (`MAX_LINE_BYTES`) rather than truncated. Why not a binary framing for the bytes: this hop is two processes on one Mac, and one parser with one readable log is worth the third more that base64 costs. The framing that matters for the phone is the attach WebSocket in phase 3, which carries binary frames and does not re-encode anything. A connection is a request/answer channel until `attach` or `subscribe` turns it into a stream; `detach` turns it back. **Both of those ANSWER FIRST.** `attach` answers `attached`, `subscribe` answers `ok`, and the answer is the first line on the connection whatever the broadcast is doing. A stream that opened with nothing on it could not be told from a socket nobody answered, and the client waits for that line before it believes it is subscribed (`SUBSCRIBE_ANSWER_MS`). **And both REPLAY what the subscriber missed.** `attach` replays the scrollback tail; `subscribe` replays an `adopted` and a `state` for every session this host FOUND, because that announcement goes out once and this host outlives the app — without the replay, an app restarted by a Sparkle update would never hear about a single session the person opened in a terminal. Re-announcing is safe by construction: the mirror dedupes on `(tool, external_id)` and keeps the row's own history. ## Client → daemon | Message | Fields | |---|---| | `spawn` | `launch_id`, `session_id?`, `tool` (`claude`\|`codex`), `argv_extras[]`, `cwd`, `env{}`, `cols`, `rows`, `permission_mode` (`bypass`\|`ask`) | | `spawn_utility` | `purpose`, `argv[]`, `cwd?`, `env{}`, `cols?`, `rows?` | | `attach` | `session_id`, `cols`, `rows`, `from_offset?` | | `write` | `session_id`, `b` (base64) | | `resize` | `session_id`, `cols`, `rows` | | `detach` | — | | `stop` | `session_id` | | `decide` | `session_id`, `request_id`, `decision` (`allow`\|`deny`\|`allow_session`) | | `list` | — | | `subscribe` | — | | `sample` | — | | `restart` | — | | `hook` | `event`, `session_id?`, `payload` (the hook's stdin, verbatim) | | `statusline` | `session_id?`, `payload` (the status line's stdin, verbatim) | `spawn` without a `session_id` has the host mint one. `env` is merged into the child's environment on top of the adapter's own; `argv_extras` are appended after the arguments the adapter owns. ## Daemon → client | Message | Fields | |---|---| | `spawned` | `session_id`, `launch_id`, `pid` | | `utility_started` | `id`, `purpose`, `pid` | | `utility_ended` | `id`, `purpose`, `code`, `signal`, `at` | | `adopted` | `session_id`, `tool`, `cwd?`, `started_at` — a session this host FOUND, not one it spawned | | `attached` | `session_id`, `offset` | | `data` | `session_id`, `b` (base64) | | `sessions` | `sessions[]` — see below | | `state` | `session_id`, `state` (`starting`\|`running`\|`idle`\|`waiting`\|`ended`), `waiting_kind?` (`permission`\|`question`\|`input`), `request_id?` | | `turn` | `session_id`, `role` (`user`\|`assistant`), `text`, `seq` | | `spoke` | `session_id`, `role`, `text` — a turn of a session whose turns the agent's own `Stop` hook logs: the card's last line, never a prompt row | | `tasks` | `session_id`, `tasks[]` — `seq`, `text`, `status` (`open`\|`active`\|`done`). The WHOLE list, never a delta; an empty one clears it | | `usage` | `provider` (`anthropic`\|`openai`), `email`, `five_hour_pct`, `five_hour_resets_at`, `weekly_pct`, `weekly_resets_at` | | `sample` | `sampled_at`, `load1`, `mem_free_pct`, `mem_total_gb`, `disk_free_gb`, `cpu_count`, `chip?`, `os_version?`, `disk_total_gb?` (what the machine IS — read once at `serve` start, left out when unknown; the mirror writes them onto the device row once, apart from the reading), `sessions_running`, `build_lock_held`, `mem_committed_gb`, `session_peak_gb?`, `session_peak_samples`, `agents{}`, `accounts{}`, `host_version`, `binary_fingerprint`, `update_pending` | | `restarting` | `restarting`, `sessions_running` — the answer to a `restart` | | `exited` | `session_id`, `code`, `signal` | | `decision` | `session_id`, `request_id`, `stdout` (the JSON the hook must print) | | `ok` | — | | `error` | `message` | A session in `sessions[]`: `session_id`, `launch_id`, `tool`, `agent_session_id`, `cwd`, `started_at`, `ended_at`, `state`, `waiting_kind`, `request_id`, `exit_code`, `exit_signal`, `host_owned`. An ADOPTED session's `launch_id` is the empty string and its `host_owned` is false: nobody launched it and nothing here holds it. **An unknown number is `null`, never `0`.** A usage window nobody has reported, an exit nobody reaped, a reset instant that could not be computed: all null. Zero would read on the phone as "none used" and "exited cleanly", which is the opposite of "we have not been told". ## Utility terminals **A `spawn_utility` runs a COMMAND in a pseudo-terminal, and nothing else.** It is how the Mac app gets a machine ready without anybody opening Terminal.app: installing an agent, signing one in, asking Apple for the command line tools, cloning a repository into a working folder. It is **not a session**, and every way it differs is deliberate: * no adapter, so **no hook file is written and no hook can fire**; * **no `sessions/index.json` entry**, so `list` never answers for one and a restart of the daemon does not stamp one as an ended session; * **not counted in `sessions_running`**, which is the number the dispatcher places work by; * **no transcript adoption** — it writes none; * and an id that says so: `util::-`. A client keys rows on a session id, and the one thing that makes a utility safe to run through this socket is that its id can never be one. What it SHARES with a session is the terminal: `attach`, `write`, `resize` and `stop` take a utility id exactly as they take a session id, through the same lookup, so a view drawing one behaves identically. Signing an agent in needs the write half as much as the read half — a view that could show the bytes but not answer them would be a screenshot. **One at a time per purpose.** A second `install-claude` while the first is running is refused by name. The purpose is also the scrollback's directory — `/utilities//scrollback.log`, written from the start on every run — so the same string is the key, the folder and the sentence, and the set of directories is bounded by what the app can ask for rather than growing by one per button press. A finished utility is KEPT until a new one of its purpose replaces it, so the view that watched an install can still replay how it went. `argv[0]` is resolved against the person's captured PATH before anything is opened, and a program that is not on it is a **named refusal** rather than a terminal that opens and dies with a shell's own wording. **`utility_ended` is followed by a fresh `sample`.** A utility is the one thing running on this Mac that changes what a sample says — an install that just finished is an agent that is now installed — and the panel reads the sample, not the helper. Without it a person who watched `claude` install would keep reading *not installed* for up to five minutes. **Cotton still never touches a credential.** A sign-in utility runs the agent's own binary, whose browser flow is between the person and their provider; what crosses this process is the pseudo-terminal's bytes on their way to a screen. ## Attaching, and the offset `attach` answers `attached` with the offset its first `data` line starts at, then streams. `from_offset` asks to resume from a point; when the ring has already dropped that point the replay is the tail and **the answered `offset` says so** — a viewer that trusted its own number would render a gap as continuity. A replay is capped at 256 KiB. The scrollback is `/sessions//scrollback.log`, a ring capped at **8 MiB per session**. The bound is a post-condition of every append: the file is rewritten to 7 MiB whenever it passes 8, so a compaction costs one rewrite per megabyte written rather than one per write. A viewer that stops reading is dropped from the live broadcast and told, by name, how much it missed. ## Hooks Every hook an adapter registers is `cotton-session-host hook `, and the status line is `cotton-session-host statusline`. Both read the agent's JSON on stdin and send it here. **No state is ever inferred from screen bytes.** | Event | What the host does | |---|---| | `SessionStart` | learns the agent's own session id; state → `running` | | `UserPromptSubmit` | a turn began — the opening prompt or a typed reply; state → `running`. The hook prints nothing | | `Stop` | reads the transcript named on stdin, emits `turn` — or `spoke` when the user's own `cotton-session-log` Stop hook logs the session's turns; state → `idle` | | `SessionEnd` | state → `ended` | | `PostToolUse` (matcher `TodoWrite`) | reads the task list out of `tool_input.todos`, emits `tasks`; the state does not move | | `Notification` | state → `waiting`, with the kind | | `PermissionRequest` | **blocks** until `decide` or the timeout | **Only Claude registers `PostToolUse`**, and only for one tool name: Codex has no task-list tool, and an unmatched `PostToolUse` there would be a socket round trip after every command it ran. The list arrives WHOLE every time the agent rewrites it, so `tasks` replaces what the row held — an empty list included. A status word this host does not know skips that task with a line on stderr, never a guess, and a payload with no list at all emits nothing rather than clearing the row. `PermissionRequest` is the only blocking one. The host answers it with `decision`, whose `stdout` is the exact JSON that hook must print — encoded by the SESSION's own adapter, so the `hook` subcommand knows neither agent's decision dialect. After **10 minutes** (`PERMISSION_TIMEOUT_SECONDS`, or `COTTON_SESSION_HOST_PERMISSION_TIMEOUT_SECONDS`) the host answers `ok` instead, the hook prints **nothing** and exits 0, and the agent falls back to its own prompt in the TUI. A hook whose session this host does not hold is still answered, because it is blocking on us. `allow_session` travels to both agents as `allow`: neither hook's answer has a session-wide form, and remembering not to ask again is Cotton's own record. ## The two agents Everything that differs lives in `src/agents/{claude,codex}.rs`; nothing else in the crate branches on which agent a session runs. **Claude** takes `--settings `, whose hooks MERGE with the person's own `settings.json` in `~/.claude`. The file is written into the session's own directory, so a crashed host leaves nothing behind that a later hand-run `claude` would try to reach. Also `--session-id ` (so one id names the session everywhere), `--dangerously-skip-permissions` in bypass mode, and the environment `DISABLE_AUTOUPDATER=1` and `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1`. **Codex** takes its hooks as `-c hooks=` on the command line, with `--dangerously-bypass-hook-trust`, plus `-C `, `-c check_for_update_on_startup=false` and, in bypass mode, `--dangerously-bypass-approvals-and-sandbox`. It writes **no file at all**. The three routes that were refused, and why, are written out at the top of `src/agents/codex.rs`; the short form is that `~/.codex/config.toml` is the person's file, `/.codex/hooks.json` is the person's repository and is trust-gated, and a `CODEX_HOME` overlay would either copy the person's credential or break the moment Codex refreshes its token. **Cotton never touches a credential.** Codex mints its own session id; the host learns it from `SessionStart` and reports it as `agent_session_id`, which is what `codex resume ` takes. ## Sampling `sample` reads this machine: one-minute load, free memory percent and total, free disk on the data directory's volume, CPU count, sessions running, whether `/tmp/tinmen-build.lock` is held by a process that is still alive, the installed agents, and this host's version. `serve` samples itself every **5 minutes** and broadcasts it — the report interval `cotton-core` declares (`engine::machines::REPORT_INTERVAL_MINUTES`). It also carries WHICH BINARY the helper is running (`binary_fingerprint`) and whether that helper is waiting to restart onto a new one (`update_pending`) — see *Restarting onto a new binary*. `agents` maps `claude-code` / `codex` to a version, and **an agent that is not installed is absent from the map** — the dispatcher acts differently on "not installed" and "installed, version unknown", so they are different answers. The same map says whether this Mac can sign a release: `developer-id` maps to the team of the valid Developer ID Application identity in its keychain (`security find-identity -v -p codesigning`, asked on every sample), and is absent on a Mac that holds none. Every Mac may build; a scheduler reads this key to know which of them can sign. **The agents are looked for on the PERSON'S PATH, and looked for again on every sample.** The helper is started by launchd, which gives it `PATH=/usr/bin:/bin:/usr/sbin:/sbin`; the PATH it actually resolves against is the one its login-shell capture settled on (`src/login_env.rs`), which is also the environment a spawned session runs in — so an agent that is detected is an agent that can be launched. And because this daemon runs for weeks under `KeepAlive`, a `sample` re-runs the detection rather than answering a map read once at boot. The message's SHAPE is unchanged: still a name to a version, and nothing says where it was found. That is the log's job. `accounts` maps the same agent names to who that agent is signed in as — `{provider, email, plan}` — and **an agent that is signed out, or that will not say as whom, is absent from the map**. It is read by ASKING the agent (`claude auth status`), in the login environment and against the binary the detection found, with ten seconds to answer; never by opening a file the agent keeps or a keychain item it owns. `codex login status` names no address, so Codex is not asked and a Mac with only Codex signed in reads as signed out. A status line that carries usage windows and no address is filed under the login its agent reported on the last sample. The host's LOG names the agent and the plan when the answer changes, never the address. `sessions_running` counts the sessions this host still owns a terminal for. An ended session stays in the host's map so its scrollback keeps answering, and is not counted. **The map also carries `npm`**, which is not an agent. Codex installs with `npm install -g @openai/codex`, so a Mac with no Node is a Mac where that button would fail, and the panel needs the answer before it offers the button — it says *Codex needs Node.js* instead. Cotton never installs Node itself. Every reader asks this map BY KEY for the reason that implies: one that listed whatever was in it would draw `npm` as a coding agent. ## Restarting onto a new binary `restart` asks the helper to exit so launchd's `KeepAlive` starts whatever is at its path — which after a Sparkle update is the new bundle's binary. **With no host-owned session alive it answers `{restarting: true, sessions_running: 0}` and goes; with sessions alive it answers `{restarting: false, sessions_running: N}`, marks `update_pending` and goes when the last one ends.** A restart of this daemon ends its children, and an update is not a reason to end somebody's turn. The answer is written on the asking connection BEFORE the process exits, so the asker learns which of the two happened rather than inferring it from a socket that closed. **The helper also asks itself.** At `serve` start it records the size and modification time of its own executable — the absolute path `current_exe()` resolves, even though the launchd plist's `ProgramArguments[0]` is bundle-relative — and re-reads it every **60 seconds**, applying the same rule. `sample` carries that fingerprint as `binary_fingerprint` and the deferral as `update_pending`, so "which helper is this Mac actually running" is a question anything reading a sample can answer. Both fields DEFAULT on the way in: the helper outlives the app, so a newly started app reads samples from helpers that predate them. **`host_version` is the APP's version** — `CFBundleShortVersionString`, stamped into the binary at package time — and `0.1.0-dev` on a `cargo build`. The crate's own version identified the component rather than the build, which is how a three-day-old helper reported the same number as a fresh one on every Mac (`docs/subsystems/repo-landmines.md`, *`KeepAlive` keeps a STALE helper alive too*). ## Adopted sessions The host also watches the two agents' own transcript directories — `~/.claude/projects` and `~/.codex/sessions`, or `$CLAUDE_CONFIG_DIR` / `$CODEX_HOME` when either is set — on a **15-second mtime poll**, and registers what it finds there that it did not spawn. Each one is announced with `adopted`, then reports `state`, `turn` and `exited` exactly as a hosted session does, and appears in `list` with `host_owned: false`. **One source of turns per session.** When Claude's user settings (`settings.json` beside `projects`) register the `cotton-session-log` Stop hook, that hook logs every Claude session's turns through `log_session`, numbered by transcript line. The host then says `spoke` instead of `turn` for those sessions — the card's last line, no prompt row — so the two numberings never share a `(session, seq)` row. A session with no such hook keeps `turn`, and the client files those turns in a seq space above any transcript line index. Identity comes out of the transcript's HEAD, never out of its path; the last turn and the end marker come out of its TAIL, bounded so a multi-megabyte transcript is not re-read whole every fifteen seconds. A file whose head names no session is skipped and counted, never adopted under an invented name, and a session this host SPAWNED is never adopted from its own transcript — its own events are the truth about it. **Quiet is `idle`; only a marker is `ended`.** No write for 90 seconds makes a session `idle`. `ended` needs the agent's own end marker AND a file that has stopped changing, and the `exited` that follows carries `code: null, signal: null` — this host did not reap that process and will not say it knows how it went. **A session whose agent writes no end marker stays `idle` for as long as it stays quiet.** That is deliberate: an invented exit code would read on the phone as "it finished cleanly". **`attach`, `write`, `resize`, `stop` and `decide` on an adopted session are refused**, with a sentence naming the session and saying to start it from Cotton to get all five — distinct from the refusal for an id this host has never heard of, because the two are different things to fix. A restart of the daemon does not end an adopted session either: nothing was taken away from it, and the first scan of the new run reads its state straight back out of its file. ## A restart ends the children The pseudo-terminals are owned by this process and nothing re-parents them, so **restarting the daemon ends every session it was running.** `/sessions/index.json` survives: on the way up the host stamps every session the previous run left open as ended, at the current instant, with `exit: {code: null, signal: null}` — nobody reaped them, so the exit is genuinely unknown. `list` keeps answering for those sessions with `host_owned: false`, and their scrollback is still readable. A card on the phone shows an ended session, never one waiting for a process that no longer exists. ## Stopping `stop` is SIGINT, SIGTERM after 10 seconds, SIGKILL after 10 more. Every step is bounded, and the step it took is the answer — a stop that had to reach SIGKILL is a fact, not a detail.