Cotton code
378 lines · 20.8 KB · MarkdownRaw
# 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** — anythingthat can write it can run a process as the person and read their terminal, sothere is no group and no other on it. `~/CottonDB` is retired on every Mac, sonothing of the host's is under it. With `$COTTON_MAC_DATA_DIR` set (a lane'ssynthetic 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 toit, and refuses by name when somebody answers. A socket node a crash leftbehind — nothing listening, so the connect is refused — is unlinked andrebound. Anything at that path that is *not* a socket is a named refusal and isnever deleted: a host does not remove a file it does not understand out of theperson'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 itinto 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 thebroadcast is doing. A stream that opened with nothing on it could not be toldfrom a socket nobody answered, and the client waits for that line before itbelieves it is subscribed (`SUBSCRIBE_ANSWER_MS`).**And both REPLAY what the subscriber missed.** `attach` replays the scrollbacktail; `subscribe` replays an `adopted` and a `state` for every session this hostFOUND, 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 abouta single session the person opened in a terminal. Re-announcing is safe byconstruction: the mirror dedupes on `(tool, external_id)` and keeps the row'sown 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 thechild's environment on top of the adapter's own; `argv_extras` are appendedafter 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 launchedit 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 theopposite 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 openingTerminal.app: installing an agent, signing one in, asking Apple for the commandline 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:<purpose>:<pid>-<n>`. 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 samelookup, so a view drawing one behaves identically. Signing an agent in needsthe write half as much as the read half — a view that could show the bytes butnot answer them would be a screenshot.**One at a time per purpose.** A second `install-claude` while the first isrunning is refused by name. The purpose is also the scrollback's directory —`<dataDir>/utilities/<purpose>/scrollback.log`, written from the start on everyrun — so the same string is the key, the folder and the sentence, and the setof directories is bounded by what the app can ask for rather than growing byone per button press. A finished utility is KEPT until a new one of its purposereplaces 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 isopened, and a program that is not on it is a **named refusal** rather than aterminal that opens and dies with a shell's own wording.**`utility_ended` is followed by a fresh `sample`.** A utility is the one thingrunning on this Mac that changes what a sample says — an install that justfinished 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 keepreading *not installed* for up to five minutes.**Cotton still never touches a credential.** A sign-in utility runs the agent'sown binary, whose browser flow is between the person and their provider; whatcrosses 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 hasalready 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 ascontinuity. A replay is capped at 256 KiB.The scrollback is `<dataDir>/sessions/<id>/scrollback.log`, a ring capped at**8 MiB per session**. The bound is a post-condition of every append: the fileis rewritten to 7 MiB whenever it passes 8, so a compaction costs one rewriteper megabyte written rather than one per write.A viewer that stops reading is dropped from the live broadcast and told, byname, how much it missed.## HooksEvery hook an adapter registers is `cotton-session-host hook <event>`, and thestatus line is `cotton-session-host statusline`. Both read the agent's JSON onstdin 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 hasno task-list tool, and an unmatched `PostToolUse` there would be a socket roundtrip after every command it ran. The list arrives WHOLE every time the agentrewrites it, so `tasks` replaces what the row held — an empty list included. Astatus 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 thanclearing 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 bythe SESSION's own adapter, so the `hook` subcommand knows neither agent'sdecision 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 toits own prompt in the TUI. A hook whose session this host does not hold isstill answered, because it is blocking on us.`allow_session` travels to both agents as `allow`: neither hook's answer has asession-wide form, and remembering not to ask again is Cotton's own record.## The two agentsEverything that differs lives in `src/agents/{claude,codex}.rs`; nothing elsein the crate branches on which agent a session runs.**Claude** takes `--settings <file>`, whose hooks MERGE with the person'sown `settings.json` in `~/.claude`. The file is written into the session's owndirectory, so a crashed host leaves nothing behind that a later hand-run`claude` would try to reach. Also `--session-id <uuid>` (so one id names thesession everywhere), `--dangerously-skip-permissions` in bypass mode, and theenvironment `DISABLE_AUTOUPDATER=1` and`CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1`.**Codex** takes its hooks as `-c hooks=<inline TOML table>` on the commandline, with `--dangerously-bypass-hook-trust`, plus `-C <cwd>`,`-c check_for_update_on_startup=false` and, in bypass mode,`--dangerously-bypass-approvals-and-sandbox`. It writes **no file at all**. Thethree 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 theperson's file, `<repo>/.codex/hooks.json` is the person's repository and istrust-gated, and a `CODEX_HOME` overlay would either copy the person'scredential or break the moment Codex refreshes its token. **Cotton nevertouches a credential.**Codex mints its own session id; the host learns it from `SessionStart` andreports it as `agent_session_id`, which is what `codex resume <id>` 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, theinstalled agents, and this host's version. `serve` samples itself every **5minutes** 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`) andwhether 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 notinstalled is absent from the map** — the dispatcher acts differently on "notinstalled" and "installed, version unknown", so they are different answers.The same map says whether this Mac can sign a release: `developer-id` maps tothe team of the valid Developer ID Application identity in its keychain(`security find-identity -v -p codesigning`, asked on every sample), and isabsent on a Mac that holds none. Every Mac may build; a scheduler reads thiskey to know which of them can sign.**The agents are looked for on the PERSON'S PATH, and looked for again on everysample.** The helper is started by launchd, which gives it`PATH=/usr/bin:/bin:/usr/sbin:/sbin`; the PATH it actually resolves against isthe one its login-shell capture settled on (`src/login_env.rs`), which is alsothe environment a spawned session runs in — so an agent that is detected is anagent that can be launched. And because this daemon runs for weeks under`KeepAlive`, a `sample` re-runs the detection rather than answering a map readonce at boot. The message's SHAPE is unchanged: still a name to a version, andnothing 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 notsay 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 thedetection found, with ten seconds to answer; never by opening a file the agentkeeps or a keychain item it owns. `codex login status` names no address, soCodex is not asked and a Mac with only Codex signed in reads as signed out. Astatus line that carries usage windows and no address is filed under the loginits agent reported on the last sample. The host's LOG names the agent and theplan when the answer changes, never the address.`sessions_running` counts the sessions this host still owns a terminal for. Anended session stays in the host's map so its scrollback keeps answering, and isnot 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 thatbutton 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. Everyreader asks this map BY KEY for the reason that implies: one that listedwhatever 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 atits path — which after a Sparkle update is the new bundle's binary. **With nohost-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 endsomebody's turn.The answer is written on the asking connection BEFORE the process exits, so theasker learns which of the two happened rather than inferring it from a socketthat closed.**The helper also asks itself.** At `serve` start it records the size andmodification time of its own executable — the absolute path `current_exe()`resolves, even though the launchd plist's `ProgramArguments[0]` isbundle-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 questionanything reading a sample can answer. Both fields DEFAULT on the way in: thehelper outlives the app, so a newly started app reads samples from helpers thatpredate them.**`host_version` is the APP's version** — `CFBundleShortVersionString`, stampedinto the binary at package time — and `0.1.0-dev` on a `cargo build`. Thecrate's own version identified the component rather than the build, which ishow 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 alivetoo*).## Adopted sessionsThe host also watches the two agents' own transcript directories — `~/.claude/projects` and `~/.codex/sessions`, or `$CLAUDE_CONFIG_DIR` / `$CODEX_HOME` wheneither is set — on a **15-second mtime poll**, and registers what it finds therethat 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 bytranscript line. The host then says `spoke` instead of `turn` for thosesessions — the card's last line, no prompt row — so the two numberings nevershare a `(session, seq)` row. A session with no such hook keeps `turn`, and theclient 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 lastturn and the end marker come out of its TAIL, bounded so a multi-megabytetranscript is not re-read whole every fifteen seconds. A file whose head namesno session is skipped and counted, never adopted under an invented name, and asession this host SPAWNED is never adopted from its own transcript — its ownevents are the truth about it.**Quiet is `idle`; only a marker is `ended`.** No write for 90 seconds makes asession `idle`. `ended` needs the agent's own end marker AND a file that hasstopped changing, and the `exited` that follows carries `code: null,signal: null` — this host did not reap that process and will not say it knowshow it went. **A session whose agent writes no end marker stays `idle` for aslong as it stays quiet.** That is deliberate: an invented exit code would readon the phone as "it finished cleanly".**`attach`, `write`, `resize`, `stop` and `decide` on an adopted session arerefused**, with a sentence naming the session and saying to start it from Cottonto get all five — distinct from the refusal for an id this host has never heardof, because the two are different things to fix. A restart of the daemon doesnot end an adopted session either: nothing was taken away from it, and the firstscan of the new run reads its state straight back out of its file.## A restart ends the childrenThe pseudo-terminals are owned by this process and nothing re-parents them, so**restarting the daemon ends every session it was running.**`<dataDir>/sessions/index.json` survives: on the way up the host stamps everysession the previous run left open as ended, at the current instant, with`exit: {code: null, signal: null}` — nobody reaped them, so the exit isgenuinely unknown. `list` keeps answering for those sessions with`host_owned: false`, and their scrollback is still readable. A card on thephone shows an ended session, never one waiting for a process that no longerexists.## Stopping`stop` is SIGINT, SIGTERM after 10 seconds, SIGKILL after 10 more. Every stepis bounded, and the step it took is the answer — a stop that had to reachSIGKILL is a fact, not a detail.