---
url: https://clusto.app/docs/protocol.md
description: >-
  Reference for Clusto client, daemon, cluster, session, task, team, and
  streaming WebSocket messages.
---

# Wire Protocol

Clusto uses two WebSocket-based protocols:

1. **Client protocol** - between `clusto` client and `clustod` daemon (port 9178)
2. **Peer protocol** - between `clustod` cluster nodes (port 9179)

All messages are JSON text frames using serde tagged enums (`"type"` field,
`snake_case`) - **except terminal traffic**: the daemon sends terminal output as
a raw **binary** WebSocket frame and a client sends PTY input the same way (see
[Binary frames](#binary-frames)). Terminal bytes are escape-dense, so
JSON-encoding them dominated CPU on the session's busy owner node under load;
the binary frame ships the payload verbatim. Every client decodes output back
into the same logical `Output` message. A JSON message over 16 KiB is also cut
into binary Chunk v1 pieces so a keystroke echo never waits behind it.

This page covers the core message families: connection, sessions, terminals,
project files, chats, teams, and cluster replication. Feature areas
with their own pages (tasks, notes, SSH, agent docs, reports, updates, and
others) add further messages that follow the same tagged-JSON conventions.

## Client Protocol

Endpoint: `/ws` on the client port (default 9178), over one of:

* **Raw-key TLS** (`wss://`): TLS 1.3 where the node authenticates with its
  Ed25519 identity key (RFC 7250 raw public key) instead of a certificate. The
  desktop and mobile apps, the CLI and adopting daemons use it and pin the key.
* **Browser certificate** (`wss://`): the operator certificate (`tls_cert` and
  `tls_key`) for TLS clients that offer no raw key, such as browsers.
* **Plaintext** (`ws://`): only from loopback, Tailscale or a network listed in
  `[transport] plaintext_networks`. Any other plaintext request for `/ws` (or
  `/notifications`, `/metrics`, `/clients/...`) gets `403` at the HTTP upgrade,
  before a token is sent. See [Node Identity & Pairing](/node-identity).
* **Clusto Tunnel** or the web relay: the same messages over an iroh stream, see
  [Clusto Tunnel](/clusto-tunnel).

A browser WebSocket upgrade is refused with `403` unless its `Origin` is the
app's own, `https://web.clusto.app`, or listed in `allowed_origins`. Requests
with no `Origin` header (CLI, app, peers) are not affected.

### Connection Lifecycle

```
Client                           Server
  |                                |
  |---- ClientMessage::Auth ----->|
  |                                |
  |<--- ServerMessage::AuthResult-|  (success: true/false)
  |                                |
  |---- ClientMessage::* -------->|  (commands)
  |<--- ServerMessage::* --------|  (responses/output)
  |        ...                     |
  |---- WS Close ---------------->|
```

The first message **must** be `Auth`, `ProveIdentity` or `PairStart` (see
[Pre-auth handshakes](#pre-auth-handshakes)), sent within 10 s; every later
pre-auth read has the same 10 s limit. Any other message before auth results in
an error and disconnect. `Auth` accepts the node token or the cluster's shared
cluster token (full access), or a limited [session credential](/session-credentials)
(`cst1....`) presented by a helper running inside a session on the same machine.
An agent credential may also send `get_cluster_config` (the cluster token is
masked in the reply), `list_github_accounts`, `get_github_snapshot`,
`list_azure_devops_accounts`, `get_azure_devops_snapshot`, `get_daemon_log`,
`delete_note`, `rename_note`, `save_time_project`, `remove_time_project` and
`move_factory_card`, so `clusto mcp` can serve its tools.
Repeated failures from one IP address are rate-limited: 10 failures in 60 s block
that address for 5 minutes (configured cluster peers are never blocked).

### Pre-auth handshakes

Exactly one of three sequences runs before any other message. A late
`prove_identity`, `pair_start` or `pair_proof` after auth gets an
`already authenticated` error.

```
Auth                       -> AuthResult
ProveIdentity -> IdentityProof, then Auth -> AuthResult
PairStart -> PairChallenge, PairProof -> PairResult -> AuthResult
```

All nonces are 32 random bytes as 64 lowercase hex characters. An identity is the
node's 32-byte Ed25519 public key as 64 lowercase hex. Every proof is
HMAC-SHA256, hex-encoded (64 characters), over a label, a `0x00` byte, then
fixed-length binary fields. Labels end in a version, for example
`clusto/identity-proof/v1`.

**Identity proof.** A client that has no pin for the node, or whose pin did not
match, asks the node to prove it holds the token before the token is sent:

```json
{"type": "prove_identity", "nonce": "<64 hex>"}

// node_proof = HMAC(key = node token UTF-8, "clusto/identity-proof/v1" 0x00
//   || the identity key the node presented in TLS (32 bytes) || nonce (32 bytes));
// cluster_proof is the same keyed with the cluster token (absent outside a cluster)
{"type": "identity_proof", "node_id": "a1b2c3d4-...", "node_proof": "<64 hex>", "cluster_proof": "<64 hex>"}
```

The proof is bound to the key from the TLS handshake (or the tunnel endpoint id),
so a node cannot replay it for a different key. A token is only sent after it
checks out. Tokens are 256-bit, so the proofs are of no use for guessing; a
hand-set token under 32 characters is the exception, and the daemon warns about it
at startup.

**Pairing.** The client proves it knows the pairing code or password first, so an
unauthenticated caller never gets an offline guessing oracle, and the secret never
crosses the wire:

```json
{"type": "pair_start", "client_nonce": "<64 hex>", "client_name": "Laptop", "client_kind": {"kind": "app", "platform": "linux-x64", "app_version": "1.15.0"}}

// kind is "generated" or "custom". salt is 16 bytes (32 hex). iterations is at
// least 600000. Sent only when a pairing secret is active and not locked;
// otherwise a pair_result with a failure is sent.
{"type": "pair_challenge", "kind": "generated", "salt": "<32 hex>", "iterations": 600000, "server_nonce": "<64 hex>"}

// K = PBKDF2-HMAC-SHA256(secret, salt, iterations, 32 bytes). A generated code is
// canonicalised first (uppercase, no dashes or spaces, O read as 0, I and L as 1);
// a custom password is trimmed.
// client_proof = HMAC(K, "clusto/pair-client/v1" 0x00 || server identity (32)
//   || client_nonce (32) || server_nonce (32))
{"type": "pair_proof", "client_proof": "<64 hex>"}

// server_proof is the same with the label "clusto/pair-server/v1"; the client must
// verify it and discard the reply if it does not match. On success token and
// cluster_token grant full access and a normal auth_result follows, with the
// message "authenticated (pairing)". On failure the daemon closes the connection.
{"type": "pair_result", "success": true, "server_proof": "<64 hex>", "node_id": "a1b2c3d4-...", "token": "...", "cluster_token": "..."}
{"type": "pair_result", "success": false, "failure": {"kind": "invalid_proof"}}
```

`failure.kind` is `not_enabled`, `weak`, `expired`, `locked` (with `until_ms`),
`invalid_proof` or `malformed`. Wrong proofs count against one node-wide budget:
ten within 15 minutes lock pairing for 15 minutes, doubling per consecutive
lockout up to 24 hours; a success or a newly set secret clears it. A client
refuses a challenge asking for fewer than 600000 or more than 10,000,000
iterations.

### ClientMessage (client -> daemon)

```json
// Authenticate. client_name (the saved profile name) and client_kind
// ({"kind": "app", platform, app_version} or {"kind": "cli", platform}) are
// optional self-identification.
{"type": "auth", "token": "abc123", "client_name": "Laptop", "client_kind": {"kind": "app", "platform": "linux-x64", "app_version": "1.14.51"}}

// Create a new session
// command names the program (a registry name, a program, or a command line;
// null = the node default) and arguments overrides its args (legacy alias
// extra_args). Optional run_as_user runs the session as that OS user (takes
// precedence over any run-as user derived from project_id); optional node_id
// targets a peer. cols/rows set the initial PTY size (default 80x24). provider
// selects the SDK agent CLI (default "claude") and resume_id resumes a prior
// provider conversation; hidden keeps the session out of the terminals listing
// (internal agent chats). tags assigns free-form tags at creation - a session
// tagged "dev-server" is launched hidden as a Run-panel dev server whose bound
// port is detected from output.
{"type": "new_session", "working_dir": "/path", "mode": "pty", "name": "my-session", "command": null, "arguments": null, "project_id": null, "run_as_user": "alice", "node_id": null, "cols": 120, "rows": 36, "provider": "claude", "resume_id": null, "hidden": false, "tags": []}

// Attach to session output stream
{"type": "attach", "session_id": "550e8400-e29b-41d4-a716-446655440000"}

// Detach from a session's output stream
{"type": "detach", "session_id": "550e8400-..."}

// Subscribe to a session's output stream. from_seq (optional) resumes after a
// reconnect: the owner replays buffered frames with seq > from_seq, or answers
// resync_required when the gap is too old or, on a terminal, larger than
// 64 KiB (see [Transport & Resume](/transport)).
{"type": "subscribe_output", "session_id": "550e8400-...", "from_seq": 42}

// Cancel an output subscription; acknowledged with detached.
{"type": "unsubscribe_output", "session_id": "550e8400-..."}

// Fetch a session's history snapshot. request_id correlates the reply chunks.
// Optional: limit (raw line cap), client_cols (reflow PTY history to the
// viewer's width), and tail_rows (return only the last rows, with paging
// metadata for get_session_history_page).
{"type": "get_session_history", "session_id": "550e8400-...", "request_id": "uuid-h1", "limit": null, "client_cols": 120, "tail_rows": 2000}

// Page older rows of the snapshot cached by a tail-limited history fetch.
// generation is that snapshot's last_seq; the reply is session_history_page.
{"type": "get_session_history_page", "session_id": "550e8400-...", "client_cols": 120, "generation": 42, "before_row": 8000, "max_rows": 2000}

// Ask the session's owning node which programs run inside it, so a client can
// warn before closing it. Admin principals only (session credentials are
// refused). The reply is session_activity or session_activity_error, and the
// request is forwarded to the owner like other session requests.
{"type": "get_session_activity", "session_id": "550e8400-...", "request_id": "uuid-a1"}

// Send a prompt to an SDK-mode session. PTY sessions ignore it; their input
// goes through the binary Input v1 frame (see Binary frames).
{"type": "send_input", "session_id": "550e8400-...", "input": "explain this code"}

// List all sessions
{"type": "list_sessions"}

// Kill a session
{"type": "kill_session", "session_id": "550e8400-..."}

// Claim exclusive input control of a session (see Session Exclusivity). force
// is true only for an explicit Take over / Adopt; automatic reclaims send
// false and may replace only an unclaimed session, this connection's own claim,
// one of reclaim_connection_ids, or an orphaned claim past the input lease.
// holder is the device and account shown to other viewers. The reply is
// session_updated (current holder) followed by claim_result.
{"type": "claim_session", "session_id": "550e8400-...", "client_name": "laptop",
 "connection_id": "uuid-connection", "reclaim_connection_ids": [], "force": true,
 "holder": {"device": "laptop", "account": "..."}}

// Get cluster status. The daemon already pushes cluster_status once after
// authentication and again whenever the cluster changes (a node joins, leaves,
// updates or changes its settings); it does not push it on a timer.
{"type": "cluster_status"}

// Turn the live node metrics feed of this connection on or off. While it is on,
// the connection also gets a cluster_status on every metrics tick with fresh
// CPU, memory, network, storage and heartbeat readings. Off by default and
// dropped when the connection closes. The app turns it on only while the
// cluster view or the Settings cluster card is open.
{"type": "watch_cluster_metrics", "enabled": true}

// Adopt a running Claude process
{"type": "adopt_session", "pid": 12345, "name": "my-session", "working_dir": "/path/to/project"}

// Rename a session
{"type": "rename_session", "session_id": "550e8400-...", "name": "new-name"}

// Rename a cluster node
{"type": "rename_node", "node_id": "a1b2c3d4-...", "name": "production-1"}

// List directory contents
{"type": "list_directory", "path": "/home/user"}

// Browse a project's working directory (M1 file explorer).
// path is interpreted relative to project.working_dir; null/empty = root.
// Path traversal (".." or absolute) is rejected with project_file_error.
{"type": "list_project_files", "project_id": "550e8400-...", "path": "src"}

// Read a UTF-8 text file inside a project's working directory.
// Returns project_file_content on success, project_file_error on missing /
// binary / oversized (>1 MB) / non-UTF-8 / path-traversal failures.
{"type": "read_project_file", "project_id": "550e8400-...", "path": "README.md"}

// Read one window of a binary file inside a project's working directory for
// streaming download (file explorer "Download"). Stateless: each request seeks
// to offset and returns up to len bytes (daemon caps len to its 8 MiB per-frame
// bound). No total-size cap - the client loops windows until eof, so a file of
// any size streams without buffering a whole copy in memory. Answered with
// project_file_chunk (data base64, plus offset / total_size / eof) or
// project_file_chunk_error, correlated by request_id.
{"type": "read_project_file_chunk", "request_id": "d1", "project_id": "550e8400-...",
 "path": "build/artifact.bin", "offset": 0, "len": 8388608}

// Working-tree git status (M2 git changes panel).
// Daemon shells out to `git status --porcelain=v2 --branch -z` inside
// project.working_dir and parses the result. "Not a git repo" is NOT an
// error - git_status_result returns is_repo=false. git_error is reserved
// for transport / spawn failures (git missing, project unknown, peer down).
{"type": "git_status", "project_id": "550e8400-..."}

// Unified diff for a single project file.
// staged=false returns `git diff`; staged=true returns `git diff --cached`.
{"type": "git_diff", "project_id": "550e8400-...", "path": "src/lib.rs", "staged": false}

// Write a UTF-8 text file inside a project's working directory (M3 editor).
// base_sha256: the digest the editor last observed (from project_file_content).
// Daemon refuses with project_file_write_conflict when on-disk digest differs.
// Pass null to force-write (creating a new file or overwriting after conflict).
// 1 MiB cap; atomic temp+rename; preserves existing file mode on Unix.
{"type": "write_project_file", "project_id": "550e8400-...",
 "path": "src/lib.rs", "content": "fn main() {}\n", "base_sha256": "abc..."}

// Project filesystem mutations (file explorer: create / rename / move / copy /
// delete). Each carries a client-generated request_id echoed back on
// project_fs_action_result / project_fs_action_error so the client can match
// the reply. All paths are project-relative; traversal is rejected. create /
// move / copy refuse to overwrite an existing destination (no clobber).

// Create a new empty file (exclusive; fails if the path already exists).
{"type": "create_project_file", "project_id": "550e8400-...", "path": "src/new.rs", "request_id": "r1"}

// Create a new directory (parent must already exist).
{"type": "create_project_directory", "project_id": "550e8400-...", "path": "src/sub", "request_id": "r2"}

// Move or rename an entry (one message serves both). from must exist; to must not.
{"type": "move_project_entry", "project_id": "550e8400-...", "from": "a.txt", "to": "b.txt", "request_id": "r3"}

// Copy an entry (directories copy recursively). from must exist; to must not.
{"type": "copy_project_entry", "project_id": "550e8400-...", "from": "src", "to": "src-copy", "request_id": "r4"}

// Delete an entry (directories delete recursively). The project root can't be deleted.
{"type": "delete_project_entry", "project_id": "550e8400-...", "path": "old.txt", "request_id": "r5"}

// Upload a host file one window at a time (no size cap). data is a base64 window
// of at most 8 MiB; offset must equal the bytes already written (start at 0).
// The daemon grows a hidden .clusto-upload-<uuid>.part file next to the target
// (created exclusively) and replies project_fs_action_result or
// project_fs_action_error for every window; a failed window deletes the part
// file. last: true moves it into place and chowns it to the project's run-as user.
{"type": "upload_project_file_chunk", "request_id": "r6", "project_id": "550e8400-...", "upload_id": "9b2f...", "path": "assets/logo.png", "offset": 0, "data": "<base64>", "last": true}

// Subscribe to filesystem changes under a project's working directory. While
// subscribed the daemon pushes a debounced project_files_changed whenever
// anything under the root changes on disk (terminals, git, builds, peers).
// The watch is per-connection; re-subscribing replaces the prior watch and it
// is dropped on unwatch_project_files or disconnect. In cluster mode the watch
// is routed to the project owner and change events stream back over the peer
// transport, so remote-owned projects auto-refresh too.
{"type": "watch_project_files", "project_id": "550e8400-..."}

// Cancel a watch_project_files subscription (no-op if not watching).
{"type": "unwatch_project_files", "project_id": "550e8400-..."}

// Application-level keepalive. Sent periodically by clients that cannot
// observe WS protocol pongs (the browser shim - browsers auto-pong
// invisibly); the daemon replies keepalive_ack so the client has guaranteed
// inbound traffic to drive its connection-staleness indicator. Liveness is
// observational on both sides: a widening gap only flips a UI indicator and
// a daemon log line, never a teardown - connection death is detected by the
// kernel (TCP keepalive / TCP_USER_TIMEOUT), not by application timers.
{"type": "keepalive"}

// Start an anti-entropy exchange with every connected peer (manual;
// reconnects already do this). Answered with cluster_action_ack,
// or an error when the node is not clustered.
{"type": "trigger_sync"}

// Get cluster configuration
{"type": "get_cluster_config"}

// Update this node's cluster configuration (persisted to config.toml). Only
// provided fields change; an empty string clears default_pty_shell or
// default_session_user. tunnel_enabled takes effect after a daemon restart.
// The pairing code is set with set_pairing_secret, not here.
{"type": "update_cluster_config", "peers": ["10.0.0.2:9179"], "advertise_addresses": null, "default_pty_shell": "bash", "default_session_user": null, "keyboard_shortcuts": null, "tunnel_enabled": null}

// Set, replace or remove the connected node's pairing secret (admin only,
// answered by this node, never forwarded). mode is generate (code created by the
// node), custom (a password of 16 to 256 characters) or clear. expires_in_secs
// null means no expiry. The answer is pairing_secret_set, or an error naming the
// validation problem.
{"type": "set_pairing_secret", "request": {"mode": "generate", "expires_in_secs": 86400, "single_use": true}}
{"type": "set_pairing_secret", "request": {"mode": "custom", "secret": "a long password", "expires_in_secs": null, "single_use": false}}
{"type": "set_pairing_secret", "request": {"mode": "clear"}}

// Accept the identity key a peer now presents (after a reinstall) as its new pin
// and clear the recorded conflict. identity is 64 lowercase hex. The new pin
// spreads to the other nodes. Answered with cluster_action_ack
// (action: "trust_peer_identity").
{"type": "trust_peer_identity", "node_id": "b2c3d4e5-...", "identity": "<64 hex>"}

// Ask the connected daemon to adopt a remote node into this cluster. The daemon
// dials the remote node over raw-key TLS itself and never sends a credential or
// its cluster token to a node it has not verified. credential is a pairing code
// ({"kind": "pairing_code", "code": ...}) redeemed with the pairing proof, or the
// remote token ({"kind": "token", "token": ...}) sent only after the remote node
// passes prove_identity. expected_identity (64 hex) pins the dial, for example
// from a pairing link. The result is a cluster_action_ack.
{"type": "adopt_node", "remote_ip": "10.0.0.2", "remote_port": 9178, "credential": {"kind": "pairing_code", "code": "XXXXX-XXXXX-XXXXX-XXXXX"}, "expected_identity": null, "our_advertise_address": "10.0.0.1:9178", "display_name": "node-b"}

// Sent by the adopting daemon to the adopted node: the shared cluster token and
// the full roster of nodes with their pinned identities.
{"type": "init_cluster", "cluster_token": "...", "peer_nodes": [{"node_id": "a1b2c3d4-...", "identity": "<64 hex>", "...": "..."}], "advertise_address": "10.0.0.2:9178", "peer_port": 9179, "display_name": "node-b", "restart": true}

// Ask a node to sign a node-link claim with its tunnel key, so a signed-in
// account can register the node for the web relay. account is the cloud user id,
// or "*" for an unbound claim that `clusto daemon link` hands to a browser.
// node_id names a peer to sign instead of the connected node. Admin only.
// Answered with node_claim, or an error when the tunnel is off.
{"type": "sign_node_claim", "account": "*", "node_id": null}

// Update any node's session defaults (Node settings > Session Defaults): the
// default shell, the default session user, the folder chats without a
// workspace run in (default_chat_dir) and the folder named and replicated chat
// workspaces live in (chat_workspaces_dir). null leaves a field unchanged, an
// empty string clears it. A peer target is relayed as peer_update_node_defaults;
// the target persists the values and announces them with
// peer_node_defaults_announce. Answered with cluster_action_ack.
{"type": "update_node_defaults", "node_id": "a1b2c3d4-...", "default_pty_shell": null, "default_session_user": "ubuntu", "default_chat_dir": "", "chat_workspaces_dir": "/srv/chat-workspaces"}

// -- Durable chats --

// List first-class Claude, Codex, OpenCode, and OpenRouter chats.
{"type": "list_chats"}

// Create a dedicated-workspace chat. workspace_kind is dedicated, common,
// notes, or assistant; workspace_dir is required for every kind except notes.
// There is one chat type: design is not a kind. Optional: pinned_node_id,
// project_id, permission_mode, effort, mcp_servers, run_as_user, design (start
// in design mode; needs a replicated workspace), and
// attachments (context linked before the agent starts). New chats are never
// created as notes: notes are linked as attachments instead, and the notes kind
// only describes older chats that run inside the vault.
{"type": "create_chat", "title": "Research", "provider": "claude",
 "model": null, "workspace_kind": "dedicated", "workspace_dir": "/home/user/research"}

// Create a Notes chat. The receiving node resolves its configured vault path,
// so workspace_dir is omitted.
{"type": "create_chat", "title": "Notes research", "provider": "codex",
 "model": null, "workspace_kind": "notes", "workspace_dir": null}

// Link files, folders and notes - on any cluster node - into a chat as context.
// The daemon answers with chat_updated, then chat_attachment_statuses. With
// workspace_default=true the items become the chat's workspace defaults: they
// are stored in the workspace folder at .clusto/context.json (so they replicate
// with it) and every chat in that workspace sees them on every turn, including
// chats created earlier. workspace_default defaults to false.
{"type": "add_chat_attachments", "chat_id": "550e8400-...",
 "items": [{"node_id": null, "node_label": null, "path": "/home/u/notes/brand", "kind": "dir"}],
 "workspace_default": true}

// Unlink attachments from a chat. An id that names a workspace default removes
// it from the workspace, and so from every chat in it.
{"type": "remove_chat_attachments", "chat_id": "550e8400-...",
 "attachment_ids": ["7c1e..."]}

{"type": "open_chat", "chat_id": "550e8400-..."}
// open_chat also starts the live reply feed for this connection: it gets
// chat_delta and every transcript append of the chat until close_chat. A
// connection that does not have the chat open gets chat_updated at most once a
// second while the transcript grows (a change of working state is always sent).
// It never moves the chat's running turn to another node; take-over happens on
// send_chat_message or a retry, after a 20 s grace for the node running it.
// close_chat stops the feed for this connection and has no reply.
{"type": "close_chat", "chat_id": "550e8400-..."}
{"type": "rename_chat", "chat_id": "550e8400-...", "title": "New title"}
{"type": "delete_chat", "chat_id": "550e8400-..."}
{"type": "stop_chat", "chat_id": "550e8400-..."}

// linked_notes contains validated vault-relative paths and is accepted only
// when the chat has workspace_kind "notes". files (required, may be empty)
// carries client-local files pasted into this turn; they are copied into the
// chat workspace. view_context (optional) is the app view the user had open,
// used only by Assistant chats.
{"type": "send_chat_message", "chat_id": "550e8400-...",
 "text": "Update the summary", "linked_notes": ["projects/clusto.md"], "files": []}

// ── Remote Terminals ───────────────────────────────────────────────────────

// Open a new PTY terminal running an arbitrary shell or command
// command: the shell/binary to launch (e.g. "bash", "powershell.exe", "zsh")
// args: optional extra arguments; name: optional display name
{"type": "open_terminal", "working_dir": "/home/user", "command": "bash", "args": null, "name": "my-shell"}

// Send exact bytes to a PTY. A client sends no JSON for this: PTY input is a
// binary Input v1 frame, [0x03][16-byte session id][raw bytes] (see Binary
// frames), so UTF-8 input and binary terminal mouse reports survive unchanged
// at about a quarter of the size of a JSON byte array. The daemon fills in the
// connection id from the connection itself, and the live session owner accepts
// the bytes only when that connection holds the claim. A JSON send_pty_input
// on the client link is refused ("PTY input is sent as a binary input frame");
// the JSON form {"type": "send_pty_input", "session_id": ..., "data": [27, 91],
// "connection_id": ...} exists only for a node forwarding the request.

// Request an owner-authoritative PTY resize. request_id is echoed by
// pty_resize_result after the session owner handles the request, including when
// the live PTY is on another cluster node.
{"type": "resize_pty", "session_id": "550e8400-...", "request_id": "uuid-r1", "rows": 36, "cols": 120, "connection_id": "uuid-connection"}

// ── Projects ───────────────────────────────────────────────────────────────

// Clone a git repository onto a node as a new project. The node clones as the
// OS user run_as_user (default: its session user) with that user's own git
// credentials; no Clusto token is used. name defaults to the repository name,
// repo_link records the project's repository link. Answered by that node with
// project_cloned or project_clone_error, both carrying request_id.
{"type": "clone_project", "request_id": "550e8400-...", "node_id": "a1b2c3d4-...", "url": "https://github.com/owner/name.git", "path": "/home/me/name", "name": null, "run_as_user": null, "repo_link": null}

// ── Reports ────────────────────────────────────────────────────────────────

// post_report carries an optional agent ({"provider": "claude",
// "conversation_id": "...", "working_dir": "..."}), the agent conversation
// that posted it; the receiving node fills in its run_as_user, and the stored
// report returns it as agent.
// continue_report_in_chat continues that conversation (Claude only) in a new
// chat on the report's node, as the run's OS account, with text as the first
// message. The report is linked to the chat and marked read; clients receive
// chat_created.
{"type": "continue_report_in_chat", "report_id": "550e8400-...", "title": "Nightly stats", "settings": {"...": "..."}, "text": "Why did step 3 fail?", "node_id": "a1b2c3d4-..."}

// ── Agent Teams ────────────────────────────────────────────────────────────

// Create a new team (daemon creates a leader session and returns the Team).
// agent is a TeamAgent tagged by "kind" (claude, codex, opencode, openrouter,
// copilot, llama, custom) with optional model and args (custom takes a
// command instead of a model); omitted means Claude.
// headless=true creates no leader session. permission_mode is bypass
// (default), accept_edits, or plan. node_id routes creation to that cluster
// node, as in new_session; omitted or null means the receiving node.
// origin ({"kind": "chat", "chat_id": ...} or {"kind": "session",
// "session_id": ...}) records the conversation that started the team so the
// app can show a Team tab beside it. The daemon takes it from the caller's
// credential when that credential is bound to a chat or session.
{"type": "create_team", "name": "research-team", "working_dir": "/path", "arguments": null, "project_id": null, "agent": {"kind": "claude", "model": null, "args": null}, "headless": false, "permission_mode": null, "node_id": null}

// Spawn a worker session under an existing team. tier (fast, balanced, deep)
// picks a model of the worker's provider when agent carries none.
{"type": "spawn_worker", "team_id": "550e8400-...", "working_dir": "/path", "arguments": null, "name": "worker-1", "agent": {"kind": "codex", "model": null, "args": null}, "role": "reviewer", "tier": "balanced", "permission_mode": null}

// Relay a message between team members
// to_session_id omitted: sends to leader (from worker) or broadcasts to all workers (from leader)
// The receiving daemon forwards this request through the cluster node that
// owns a target team member, which performs persistence and agent delivery.
{"type": "relay_team_message", "team_id": "550e8400-...", "from_session_id": "uuid-a", "to_session_id": "uuid-b", "payload": "{\"task\":\"analyse\"}"}

// List all teams
{"type": "list_teams"}

// Get a specific team by ID
{"type": "get_team", "team_id": "550e8400-..."}

// Fetch the daemon-persisted operator-visible conversation for a team. In a
// cluster, the connected node routes this read to a member-owning daemon.
{"type": "get_team_messages", "team_id": "550e8400-..."}

// Delete a team and kill all its sessions
{"type": "delete_team", "team_id": "550e8400-..."}

// ── Team autopilot ─────────────────────────────────────────────────────────

// Spawn a worker and block until it reports (or the timeout fires).
// On timeout, the daemon returns wait_id so the caller can resume via team_wait.
// Optional: working_dir (omitted = a fresh worktree from the leader's cwd),
// agent, role, tier, and permission_mode (can only narrow the team's mode).
{"type": "handoff", "team_id": "550e8400-...", "prompt": "audit auth.rs", "worker_name": "explorer", "timeout_ms": 60000}

// Spawn a worker asynchronously; daemon replies with worker_assigned. Takes the
// same optional fields as handoff except timeout_ms.
{"type": "assign", "team_id": "550e8400-...", "prompt": "fan-out task"}

// Bounded block on pending workers. Pass wait_id (from a prior timeout) to resume.
{"type": "team_wait", "team_id": "550e8400-...", "for_session_ids": null, "timeout_ms": 60000, "wait_id": null}

// At-least-once inbox replay for relayed messages. since_seq=null returns everything.
{"type": "get_team_inbox", "team_id": "550e8400-...", "session_id": "uuid-worker", "since_seq": 7}
```

### ServerMessage (daemon -> client)

```json
// Auth result. connection_id identifies this connection for session claims;
// cluster_token lets the app authenticate to other cluster nodes (never sent to a
// session credential). The message is "authenticated", "authenticated (pairing)"
// after a pairing, "authenticated (session credential)", "invalid token",
// "session credential expired: its session ended", "session credential was not
// issued by this node's daemon (...); restart the agent session" (a well-formed
// credential signed with another key), or "session credential refused: it works
// only from the node that issued it".
{"type": "auth_result", "success": true, "message": "authenticated", "daemon_version": "1.15.0", "platform": "linux-x64", "cluster_token": "...", "node_name": "node-a", "build_date": "2026-10-08T09:00:00Z", "connection_id": "uuid-connection"}

// Reply to a client keepalive (see ClientMessage::keepalive) - gives clients
// without WS-pong visibility guaranteed inbound traffic for their staleness
// indicator.
{"type": "keepalive_ack"}

// Session created (session is a SessionInfo, see below)
{"type": "session_created", "session": {"id": "550e8400-...", "name": null, "mode": "sdk", "working_dir": "/path", "model": "opus", "created_at": "2025-01-01T00:00:00Z", "last_active": "2025-01-01T00:00:00Z", "attached_clients": 0, "...": "..."}}

// Durable chat metadata (ChatInfo). workspace_kind is "dedicated" | "common" |
// "notes" | "assistant". design is true while design mode is on (the agent
// gets the HTML mock-screen instructions and the chat shows the design preview).
// pinned_node_id is the node the chat is pinned to; runtime_node_id is the node
// currently running its agent. permission_mode, effort, mcp_servers,
// run_as_user and attachments are also carried when set.
{"type": "chat_list", "chats": [{
  "id": "550e8400-...", "title": "Notes research", "provider": "codex",
  "model": null, "pinned_node_id": null, "runtime_node_id": null,
  "design": false,
  "workspace_kind": "notes", "workspace_dir": "/home/user/.clusto/notes",
  "session_id": null, "is_working": false, "last_answer_at": null,
  "created_at": "2025-01-01T00:00:00Z", "updated_at": "2025-01-01T00:00:00Z"
}]}

// Creation and metadata/session changes send the same ChatInfo shape.
{"type": "chat_created", "chat": {"id": "550e8400-...", "...": "..."}}
{"type": "chat_updated", "chat": {"id": "550e8400-...", "...": "..."}}
{"type": "chat_deleted", "chat_id": "550e8400-..."}

// append=false replaces the client transcript; append=true adds new entries
// in order. Each entry wraps one raw provider JSONL line with a stable id, so
// clients merge a history response with concurrent appends without
// duplicating or dropping a line. Linked-note metadata is stored in the user
// transcript entry so clients can render the paths as openable chips.
{"type": "chat_history", "chat": {"id": "550e8400-...", "...": "..."},
 "entries": [{"id": "7c1e...", "recorded_at": "2025-01-01T00:00:00Z",
   "line": "{\"type\":\"clusto_user\",\"text\":\"Update the summary\",\"linked_notes\":[\"projects/clusto.md\"],\"at\":1735689600000}"}],
 "append": false}
// open_chat may carry the cursor of a cached transcript ("since": {"seq": 812,
// "entry_id": "7c1e..."}); the node then sends only the entries written after
// it, and chat_history echoes a new "cursor" to cache. A cursor the node cannot
// match gets the full history.

// One step of a reply that is still forming, sent only to connections that
// have the chat open (open_chat until close_chat). line is a provider stream
// line the daemon coalesced over a 75 ms window (consecutive text or thinking
// deltas of one content block joined, a Codex item's newer state replacing its
// older one), about 12 times fewer bytes per token than one line each. It never
// enters the transcript; the complete event that follows repeats it. reset is
// true on the catch-up sent when the chat is opened mid-reply: it replaces the
// in-flight lines the client holds for the reply.
{"type": "chat_delta", "chat_id": "550e8400-...", "entry_id": "7c1e...",
 "recorded_at": "2025-01-01T00:00:00Z", "line": "{\"type\":\"stream_event\",...}", "reset": false}

// Session list
{"type": "session_list", "sessions": [{"id": "...", ...}]}

// Attached to session
{"type": "attached", "session_id": "550e8400-..."}

// Detached from session
{"type": "detached", "session_id": "550e8400-..."}

// Streamed output. `seq` is the per-session monotonic chunk counter assigned by
// the session owner; clients dedupe against `SessionHistory.last_seq` (drop any
// Output with seq <= last_seq). NOTE: on the wire this is NOT the JSON shown
// below - it is a binary frame (see "Binary output frame"). The JSON form is the
// logical message every client reconstructs after decoding.
{"type": "output", "session_id": "550e8400-...", "seq": 42, "data": "..."}

// Collapsed PTY history. A long snapshot is split across frames; more=true means
// further frames of the same fetch follow. terminal_modes is required and
// nullable. On the final frame it contains the terminal state active at
// last_seq. Clients apply it after the snapshot and before any newer Output
// frames. The captured state covers the alternate screen of a running
// full-screen program, application cursor keys/keypad, origin, line wrap,
// cursor visibility, insert/newline, focus, mouse, bracketed paste, a pending
// line wrap, and the prefix of an escape sequence split by the snapshot
// boundary. Synchronized output is deliberately excluded.
// request_id echoes the fetch; snapshot_cols/snapshot_rows are the owner
// geometry the snapshot was captured at; total_rows/start_row/generation are
// paging metadata for a tail-limited fetch.
{"type": "session_history", "session_id": "550e8400-...", "request_id": "uuid-h1",
 "snapshot_cols": 120, "snapshot_rows": 36, "last_seq": 42,
 "lines": ["collapsed terminal rows"], "more": false,
 "total_rows": 8000, "start_row": 6000, "generation": 42,
 "terminal_modes": "\u001b[?1h\u001b[?1002h\u001b[?1006h\u001b[?2004h"}

// Reply to get_session_activity: the programs running inside the session on
// its owning node, excluding the session's own shell, agent and command.
// agent_started marks shell commands the agent launched. The list is empty when
// only the shell or agent runs, and always empty for non-PTY sessions.
{"type": "session_activity", "session_id": "550e8400-...", "request_id": "uuid-a1",
 "processes": [{"command": "npm run dev", "agent_started": false}]}

// get_session_activity failed (session gone, owner unreachable).
{"type": "session_activity_error", "session_id": "550e8400-...", "request_id": "uuid-a1",
 "message": "session not found"}

// The requested from_seq is older than the owner's replay ring, or the gap on
// a terminal is larger than 64 KiB. Also sent for a live stream when this
// connection fell about two seconds of link capacity behind: the daemon
// dropped the queued output instead of delivering it late and halted the
// stream. The client fetches a fresh history snapshot and resumes from its
// final boundary.
{"type": "resync_required", "session_id": "550e8400-...", "last_seq": 42}

// Ordered PTY geometry boundary. All Output frames before seq were generated
// at the prior geometry; clients resize their terminal grid here before
// parsing subsequent output. request_id is present for a client-requested
// boundary and absent for an internal or compensating boundary.
{"type": "pty_resize_boundary", "session_id": "550e8400-...", "seq": 43, "cols": 120, "rows": 36, "request_id": "uuid-r1"}

// Correlated owner-generated result for resize_pty.
// status: applied | unchanged | not_owner | not_found | failed
{"type": "pty_resize_result", "session_id": "550e8400-...", "request_id": "uuid-r1", "status": "applied", "cols": 120, "rows": 36, "message": null}

// Session metadata changed (name, tags, claim, PTY size, terminal title,
// agent_working, waiting-for-input state, ...). Carries the full SessionInfo.
{"type": "session_updated", "session": {"id": "...", ...}}

// Session killed
{"type": "session_killed", "session_id": "550e8400-..."}

// An SDK session's agent process finished a turn. The session stays alive for
// new prompts.
{"type": "session_completed", "session_id": "550e8400-...", "exit_code": 0}

// The owner answered an output subscription or keystroke with "no such
// session". Unlike session_unknown this is not a kill: the client keeps the
// session listed and lets the user reconnect or start a new one. node_id is the
// owner that answered (null on a standalone daemon).
{"type": "session_lost", "session_id": "550e8400-...", "node_id": "b2c3d4e5-..."}

// Session unknown - the addressed node has no live process for this session and
// cannot resolve an owner for it. In a cluster this is the owner's authoritative
// disclaim: a node that forwarded a request to the recorded owner treats this as
// proof the session is dead, prunes its stale local routing, and reports
// session_killed to its client. A client receiving it directly treats the
// session as ended.
{"type": "session_unknown", "session_id": "550e8400-..."}

// Cluster status: the connected node's identity, version, addresses, defaults,
// command registry, metrics, storage, and TLS/tunnel state, plus one NodeInfo
// per known peer. Offline peers stay listed with connected: false. A peer's
// `role` is vestigial under leaderless clustering (always "leader"); clients
// treat every node as a co-equal authority.
{"type": "cluster_status", "cluster": {"node_id": "a1b2c3d4-...", "display_name": "node-a", "version": "1.14.41", "addresses": ["10.0.0.1:9178"], "web_tls": false, "identity": "<64 hex>", "peers": [{"id": "b2c3d4e5-...", "display_name": "node-b", "role": "leader", "address": "10.0.0.2:9178", "peer_address": "10.0.0.2:9179", "connected": true, "web_tls": false, "identity": "<64 hex>", "identity_conflict": null, "...": "..."}], "...": "..."}}
// web_tls means the node also serves a CA-issued certificate to browsers; native
// clients always get raw-key TLS. identity is the node's pinned public key.
// identity_conflict on a peer is the key it presented that did not match its pin
// (the link is refused until trust_peer_identity or re-adoption).

// Outcome of claim_session, sent to the requesting connection as soon as the
// session's owner decided or could not be reached. A granted or refused claim
// is preceded by the session_updated that carries the current holder. error is
// set (and granted false) only when the claim could not be decided - the owner
// is unreachable or the session is gone; it is absent when the owner answered.
{"type": "claim_result", "session_id": "550e8400-...", "granted": true}
{"type": "claim_result", "session_id": "550e8400-...", "granted": false, "error": "the session owner did not answer"}

// Cluster config response. pairing reports the state of the pairing secret
// (state none, active, weak, expired or locked, plus kind, single_use and times
// in unix ms) without exposing it; identity is this node's public key;
// cluster_token is returned to admin clients so they can join another node to
// this cluster (a session credential never receives it).
{"type": "cluster_config", "node_id": "a1b2c3d4-...", "identity": "<64 hex>", "peer_port": 9179, "peers": ["10.0.0.2:9179"], "advertise_addresses": ["10.0.0.1:9178"], "pairing": {"state": "active", "kind": "generated", "single_use": true, "created_at": 1760000000000, "expires_at": 1760086400000, "locked_until": null}, "default_pty_shell": "bash", "cluster_token": "...", "commands": [], "default_session_user": null, "keyboard_shortcuts": {}, "tunnel_enabled": false, "tunnel_endpoint_id": null, "tunnel_relay_url": null}

// Reply to set_pairing_secret. code is the generated code, shown once and never
// retrievable again (absent for a custom password or a clear). link is the
// pairing link clusto://pair?v=1&node=<uuid>&id=<identity>&name=<name>&addr=<host:port>
// (repeated)&relay=<relay url when the tunnel listens>&code=<canonical code,
// omitted for a custom password>.
{"type": "pairing_secret_set", "code": "XXXXX-XXXXX-XXXXX-XXXXX", "link": "clusto://pair?v=1&...", "status": {"state": "active", "kind": "generated", "single_use": true, "created_at": 1760000000000, "expires_at": 1760086400000, "locked_until": null}}

// Reply to sign_node_claim: the node's tunnel endpoint id and a signature, made
// with the node's identity key, over
// "clusto-node-claim/1\naccount:<account>\nendpoint:<endpoint id>\nissued:<unix seconds>".
// signature is standard base64. The cloud accepts a claim for 10 minutes.
{"type": "node_claim", "node_id": "a1b2c3d4-...", "node_name": "node-a", "endpoint_id": "<64 hex>", "account": "*", "issued_at": 1760000000, "signature": "<base64>"}

// Cluster action acknowledgement
{"type": "cluster_action_ack", "action": "rename_node", "ok": true, "message": "Node renamed"}

// Non-fatal operational notice for the current client
{"type": "client_notice", "notice": {
  "level": "warning",
  "code": "output_lagged",
  "message": "This client is falling behind on live session output.",
  "detail": "Clusto skipped 12 buffered output chunks while catching up.",
  "session_id": "550e8400-e29b-41d4-a716-446655440000"
}}

// Directory listing response
{"type": "directory_listing", "path": "/home/user", "parent": "/home", "entries": ["projects/", "documents/", "file.txt"]}

// Project directory listing (response to list_project_files).
// Paths are project-relative; entries are sorted dirs-first then alphabetical.
// kind is "dir" | "file" | "symlink"; size is bytes (0 for directories).
{"type": "project_file_list", "project_id": "550e8400-...", "path": "src",
 "entries": [
   {"name": "components", "path": "src/components", "kind": "dir", "size": 0},
   {"name": "lib.rs", "path": "src/lib.rs", "kind": "file", "size": 4096}
 ]}

// Project file content (response to read_project_file).
// sha256 is lowercase hex of the raw bytes (used by M3 for write conflicts).
{"type": "project_file_content", "project_id": "550e8400-...", "path": "README.md",
 "content": "# Hi", "sha256": "abc..."}

// Project file error (list_project_files or read_project_file failed).
{"type": "project_file_error", "project_id": "550e8400-...", "path": "../etc/passwd",
 "message": "path escapes project root"}

// One window of a streaming download (response to read_project_file_chunk).
// data is base64-encoded; offset echoes the window start; total_size is the
// file's full size; eof is true once this window reaches the end. A failed
// window answers with project_file_chunk_error { request_id, message }.
{"type": "project_file_chunk", "request_id": "d1", "data": "...",
 "offset": 0, "total_size": 134217728, "eof": false}

// Git status result (response to git_status).
// is_repo=false means the working dir is not a git repository - empty change
// lists, no branch, not an error. status letters: M A D R C T U.
{"type": "git_status_result", "project_id": "550e8400-...",
 "is_repo": true, "branch": "main", "upstream": "origin/main",
 "ahead": 1, "behind": 0,
 "staged":   [{"path": "src/lib.rs", "status": "M"}],
 "unstaged": [{"path": "README.md",  "status": "M"}],
 "untracked": ["new.txt"]}

// Git diff result (response to git_diff). patch is raw unified-diff text.
{"type": "git_diff_result", "project_id": "550e8400-...",
 "path": "src/lib.rs", "staged": false,
 "patch": "diff --git a/src/lib.rs b/src/lib.rs\n@@ -1 +1 @@\n-old\n+new\n"}

// Git error (git_status / git_diff failed for a transport / spawn reason).
{"type": "git_error", "project_id": "550e8400-...", "message": "git not on PATH"}

// Project file saved (response to write_project_file). sha256 is the new base.
{"type": "project_file_saved", "project_id": "550e8400-...",
 "path": "src/lib.rs", "sha256": "def456..."}

// Write conflict: on-disk sha256 differs from base_sha256 (or file is gone).
// The client typically prompts the user to reload, overwrite, or merge.
{"type": "project_file_write_conflict", "project_id": "550e8400-...",
 "path": "src/lib.rs", "current_sha256": "ff00ff00..."}

// Project filesystem mutation succeeded (create / move / copy / delete).
// request_id echoes the originating request; path is the affected
// project-relative path (the new location for move/copy, the created path for
// create, the removed path for delete).
{"type": "project_fs_action_result", "project_id": "550e8400-...",
 "request_id": "r3", "path": "b.txt"}

// Project filesystem mutation failed (path escapes root, destination exists,
// source missing, IO error, peer unreachable). request_id echoes the request.
{"type": "project_fs_action_error", "project_id": "550e8400-...",
 "request_id": "r3", "message": "a file or directory with that name already exists"}

// Files changed under a watched project's working directory (pushed to clients
// with an active watch_project_files subscription). Debounced and coarse - no
// path detail; the client re-lists the directories it cares about (root plus
// expanded subfolders) in response.
{"type": "project_files_changed", "project_id": "550e8400-..."}

// Error
{"type": "error", "message": "session not found"}

// ── Remote Terminals ───────────────────────────────────────────────────────

// A new shell terminal was opened (response to open_terminal)
// The session uses mode "pty" and kind {"type": "shell", "command": "bash"}
{"type": "terminal_opened", "session": {"id": "550e8400-...", "mode": "pty", "kind": {"type": "shell", "command": "bash", "args": null}, ...}}

// ── Projects ───────────────────────────────────────────────────────────────

// Reply to clone_project: the repository was cloned and the project created.
// Projects carry an optional repo_link ({"host": ..., "repo": "owner/name"}
// for GitHub, "org/project/repo" for Azure DevOps); create_project and
// update_project accept it, and on update null clears it.
{"type": "project_cloned", "request_id": "550e8400-...", "node_id": "a1b2c3d4-...", "project": {"id": "...", "name": "Clusto", "working_dir": "/home/me/Clusto", "repo_link": {"host": "...", "repo": "owner/name"}}}

// clone_project failed on that node; nothing was left behind
{"type": "project_clone_error", "request_id": "550e8400-...", "node_id": "a1b2c3d4-...", "message": "..."}

// ── Agent Teams ────────────────────────────────────────────────────────────

// A new team was created (response to create_team)
{"type": "team_created", "team": {"id": "...", "name": "research-team", "leader_session_id": "...", "worker_session_ids": [], "status": "active", "created_at": "...", "last_active": "...", "project_id": null}, "leader_session": {"id": "...", ...}}

// A worker was spawned and added to the team (response to spawn_worker)
{"type": "worker_spawned", "team": {"id": "...", "worker_session_ids": ["worker-uuid"], ...}, "worker_session": {"id": "worker-uuid", ...}}

// A newly persisted operator-visible message. The same stable message.id is
// returned by team_message_history so clients can merge live and history data.
{"type": "team_message", "team_id": "550e8400-...", "message": {"id": "uuid-message", "from_session_id": "uuid-a", "to_session_id": "uuid-b", "payload": "{\"result\":\"done\"}", "sent_at": "2026-07-25T12:00:00Z"}}

// Per-recipient result for relay_team_message. delivered only includes members
// whose live session accepted the input. Unavailable sessions and agent-process
// input failures appear in undelivered for the app to surface.
{"type": "team_message_delivery", "team_id": "550e8400-...", "message_id": "uuid-message", "delivered": ["uuid-b"], "undelivered": []}

// Response to list_teams or get_team
{"type": "team_list", "teams": [{"id": "...", "name": "research-team", "status": "active", ...}]}

// Response to get_team_messages. The daemon returns the durable conversation in
// display order, allowing desktop and mobile clients to load the same chat.
{"type": "team_message_history", "team_id": "550e8400-...", "messages": [{"id": "uuid-message", "from_session_id": "uuid-a", "to_session_id": "uuid-b", "payload": "{\"result\":\"done\"}", "sent_at": "2026-07-25T12:00:00Z"}]}

// A team was updated
{"type": "team_updated", "team": {"id": "...", ...}}

// A team was deleted
{"type": "team_deleted", "team_id": "550e8400-..."}

// ── Team autopilot ─────────────────────────────────────────────────────────

// Response to handoff. completed=true means the worker reported within the
// timeout. success is null when the worker finished without asserting an
// outcome; reported_via is "explicit" or "stop_hook_fallback". completed=false
// with wait_id set means the handoff timed out and may be resumed via team_wait.
{"type": "handoff_result", "team_id": "550e8400-...", "worker_session_id": "uuid-w", "success": true, "result": "done", "reported_via": "explicit", "completed": true, "wait_id": null}

// Response to assign. Either the worker started (worker_session_id set) or the
// team was at its worker cap and the assignment was queued (queued=true, with a
// 1-based queue_position and an assignment_id that correlates with the
// worker_spawned that eventually runs it). Collect results via team_wait.
{"type": "worker_assigned", "team_id": "550e8400-...", "worker_session_id": "uuid-w", "queued": false, "queue_position": null, "assignment_id": null}

// Response to team_wait. completed_workers reported within the window;
// pending_workers are still working. timed_out + wait_id signal resumption.
{"type": "team_wait_result", "team_id": "550e8400-...", "completed_workers": ["uuid-w"], "pending_workers": [], "timed_out": false, "wait_id": null}

// Response to get_team_inbox. messages are seq-ordered; next_seq is the cursor
// the caller stores and re-presents as since_seq on the next call.
{"type": "team_inbox", "team_id": "550e8400-...", "session_id": "uuid-w", "messages": [{"seq": 1, "from_session_id": "uuid-leader", "payload": "...", "delivered_at": "..."}], "next_seq": 1}
```

`TeamMessage` and `TeamMessageHistory` describe the operator-visible Messages
panel. Each `TeamChatMessage.id` is generated before persistence and live
delivery, so clients merge history and concurrent live events by ID rather than
relying on arrival order. In a cluster, `GetTeamMessages` uses a team member as
an ownership anchor and is forwarded to that member's daemon, which holds the
durable conversation. This lets a client connected through any node load the
same history. `GetTeamInbox` is separate recipient-specific at-least-once
delivery state used by agents for crash recovery.

`RelayTeamMessage` is owner-authoritative in a cluster. The connected daemon
selects a team member as the delivery anchor and forwards the entire request to
that member's owning node. That node persists the message, writes the outbox,
injects the session input, and returns the stable `TeamMessage` plus
`TeamMessageDelivery`. It does not acknowledge a recipient until the live
session accepts the input. An unavailable member or failed agent process is
returned in `undelivered` for the app to surface. Agent-process input failures
also include a `ServerMessage::Error` with the underlying reason.

`client_notice` is deliberately non-fatal. It exists for "something important
is happening, but your request still worked" cases, and clients should surface
it to the user without treating it like an error. Current notice codes are:

* `cluster_owner_lookup` - Clusto is still converging on the session owner, so the attach is being routed to the owning node
* `output_lagged` - the client fell behind on output and Clusto skipped buffered chunks while catching up
* `output_backpressure` - the client could not keep up for an extended period, so Clusto dropped that output stream to protect the rest of the connection

### GitHub messages

The [GitHub view](/github) uses a family of `Github*` messages. The account list
is cluster-shared config. Everything that talks to GitHub runs on the account's
**host node**; the node a client is connected to forwards each request there, so
no message carries a `node_id` except `get_project_repos`. The GitHub token never
appears in any reply, only its status. Repositories are always spelled
`owner/name`.

```json
// The cluster-shared account list. Answered with github_accounts.
{"type": "list_github_accounts"}

// Create or replace one account (matched by id) and replicate the list.
// Answered with github_accounts; every client also receives github_accounts.
{"type": "save_github_account", "account": {"id": "5d2f8a40-...", "name": "Personal", "host_node_id": "a1b2c3d4-...", "poll_interval_secs": 60, "merge_method": "squash", "pinned": [], "hidden": []}}

// Remove an account and replicate the list. Its host drops the token.
{"type": "delete_github_account", "id": "5d2f8a40-..."}

// Store the token on the host node. Write-only; "" clears it. The host checks
// the account with GET /user. Answered with github_token_saved or github_error.
{"type": "set_github_token", "account_id": "5d2f8a40-...", "token": "github_pat_..."}

// Run `gh auth token` on the host node (as run_as_user, else the node's default
// session user) and store the result. Answered like set_github_token.
{"type": "import_github_token_from_gh", "account_id": "5d2f8a40-...", "run_as_user": null}

// The host's latest snapshot / poll now. Both answered with github_snapshot.
{"type": "get_github_snapshot", "account_id": "5d2f8a40-..."}
{"type": "refresh_github", "account_id": "5d2f8a40-..."}

// One pull request with checks, reviews, comments and files. Answered with
// github_pull_detail or github_error.
{"type": "get_github_pull", "account_id": "5d2f8a40-...", "repo": "acme/api", "number": 12}

// Act as the token's account. Answered with github_action_result. action is
// tagged by kind: approve {body?}, request_changes {body}, comment {body},
// merge {method?} (omitted = the account's method), close, reopen, mark_ready,
// rerun_failed_checks. Bodies are limited to 64 KiB.
{"type": "github_pull_action", "account_id": "5d2f8a40-...", "repo": "acme/api", "number": 12, "action": {"kind": "merge", "method": "squash"}, "request_id": "g1"}

// The tail (at most 64 KiB) of a GitHub Actions job log. check_run_id is the
// job id. Answered with github_check_log or github_error.
{"type": "get_github_check_log", "account_id": "5d2f8a40-...", "repo": "acme/api", "check_run_id": 4421}

// Which of a node's projects are checkouts of a GitHub repository, read from
// each project's git remote. Answered with project_repos or github_error.
{"type": "get_project_repos", "node_id": "a1b2c3d4-..."}

// Fetch the pull request head from the project's origin and check it out in
// worktrees/pr-<number> on branch wt/pr-<number>, on the project's node.
// Answered with worktree_created or worktree_error.
{"type": "create_pull_worktree", "project_id": "0b6f6c0e-...", "number": 12}

// One issue with its body and comments. Answered with github_issue_detail or
// github_error.
{"type": "get_github_issue", "account_id": "5d2f8a40-...", "repo": "acme/api", "number": 7}

// Act on an issue as the token's account. Answered with github_action_result
// (number is the issue number). action is tagged by kind: comment {body}, close,
// reopen, assign_me (adds the token's login to the assignees). Bodies are
// limited to 64 KiB.
{"type": "github_issue_action", "account_id": "5d2f8a40-...", "repo": "acme/api", "number": 7, "action": {"kind": "assign_me"}, "request_id": "g2"}

// One workflow run with its jobs. Answered with github_run_detail or github_error.
{"type": "get_github_run", "account_id": "5d2f8a40-...", "repo": "acme/api", "run_id": 9981}

// Re-run or cancel a workflow run. Answered with github_action_result (number is
// the run id). action is tagged by kind: rerun_failed (only the failed jobs),
// rerun (every job), cancel.
{"type": "github_run_action", "account_id": "5d2f8a40-...", "repo": "acme/api", "run_id": 9981, "action": {"kind": "rerun_failed"}, "request_id": "g3"}
```

Replies:

```json
// The account list. Reply to list/save/delete and pushed to every client.
{"type": "github_accounts", "accounts": [{"id": "5d2f8a40-...", "name": "Personal", ...}]}

// Token status on the host. login is the account the token authenticates as.
{"type": "github_token_saved", "account_id": "5d2f8a40-...", "auth": {"token_set": true, "login": "your-github-login"}}

// Reply to get_github_snapshot / refresh_github, and pushed to every client
// whenever the host's snapshot changes. repos holds visible repositories
// (hidden ones left out; open_pulls, default_checks), pulls the open pull
// requests (draft, labels, requested_reviewers, assignees, checks, review_decision).
// Each pull request also carries author_id and requested_reviewer_ids (numeric
// GitHub user ids, in the order of requested_reviewers), which the Team bucket
// matches teammates on. issues holds the open issues (repo, number, title,
// author, author_id, labels, assignees, comments, created_at, updated_at,
// html_url) and runs the latest workflow runs (id, name, display_title,
// head_branch, head_sha, event, status, conclusion, actor, run_attempt,
// pull_numbers) of the visible, active repositories; both default to [].
// checks is none / pending / success / failure; review_decision is approved /
// changes_requested / null. rate is GitHub's rate-limit state; fast is true
// while polling at 15 s.
{"type": "github_snapshot", "snapshot": {"account_id": "5d2f8a40-...", "auth": {"token_set": true, "login": "your-github-login"}, "repos": [], "pulls": [], "fetched_at": "2026-10-08T09:14:03Z", "rate": {"limit": 5000, "remaining": 4810, "reset_at": "2026-10-08T10:00:00Z"}, "last_error": null, "fast": false}}

// One pull request with body, state, merged, mergeable_state, checks, reviews,
// comments and files (patch text is size-capped; files_truncated says so).
// The body and comments are untrusted markdown: render them through an
// escaping renderer.
{"type": "github_pull_detail", "detail": {"account_id": "5d2f8a40-...", "pull": {"repo": "acme/api", "number": 12, ...}, "state": "open", "merged": false, "checks": [], "reviews": [], "comments": [], "files": [], "files_truncated": false, ...}}

// One issue with its body (untrusted markdown), state (open or closed) and
// comments.
{"type": "github_issue_detail", "detail": {"account_id": "5d2f8a40-...", "issue": {"repo": "acme/api", "number": 7, ...}, "body": "...", "state": "open", "comments": []}}

// One workflow run with its jobs. A job id is also the check_run_id that
// get_github_check_log takes.
{"type": "github_run_detail", "detail": {"account_id": "5d2f8a40-...", "run": {"repo": "acme/api", "id": 9981, ...}, "jobs": [{"id": 4421, "name": "test", "status": "completed", "conclusion": "failure", "html_url": "..."}]}}

// Reply to github_pull_action, github_issue_action and github_run_action. number
// is the pull request or issue number, or the workflow run id.
{"type": "github_action_result", "request_id": "g1", "account_id": "5d2f8a40-...", "repo": "acme/api", "number": 12, "ok": true, "message": "#12 merged"}

// Reply to get_github_check_log. truncated is true when more came before the tail.
{"type": "github_check_log", "account_id": "5d2f8a40-...", "repo": "acme/api", "check_run_id": 4421, "log": "...", "truncated": false}

// Reply to get_project_repos; repo is lowercased owner/name.
{"type": "project_repos", "node_id": "a1b2c3d4-...", "projects": [{"project_id": "0b6f6c0e-...", "repo": "acme/api"}]}

// A GitHub request failed. request_id echoes the request when it had one.
{"type": "github_error", "account_id": "5d2f8a40-...", "request_id": "g1", "message": "GitHub rejected the token"}
```

Every `Github*` request except `list_github_accounts`, `save_github_account` and
`delete_github_account` may wait on GitHub or a peer, so the daemon answers it off
the connection's ordered request worker. `github_pull_action` carries a
`request_id`; match its reply by it (the issue and run actions carry one too).
Each action is written to the host node's audit log as `github_action`; the
detail names the account, repository, number (the run id for a run), action kind
and whether it succeeded. Kinds: `approve`, `request_changes`, `comment`, `merge`,
`close`, `reopen`, `mark_ready`, `rerun_failed_checks` (pull requests),
`issue_comment`, `issue_close`, `issue_reopen`, `issue_assign_me` (issues) and
`run_rerun_failed`, `run_rerun`, `run_cancel` (workflow runs).

`create_worktree` with a `base_ref` of `origin/<branch>` (the default when none is
given is `origin/master`) first runs `git fetch --no-tags origin <branch>` on the
project's node. A failed fetch is answered with `worktree_error` and no worktree is
created. A `base_ref` that is not under `origin/` fetches nothing.

### Time tracking messages

The [Time view](/time-tracking) uses a small family of messages. Session credentials (`cst1.`) may
send `list_time_data`, `save_time_entry`, `remove_time_entry`, `save_time_project`,
`remove_time_project`, `start_timer` and `stop_timer`; time connectors and imports
need an admin client. Each
entry carries the
`owner` identity of the client that created it. The daemon returns every
account's entries, and the app shows only those of the signed-in clusto.app
account.

```json
// Every live project, the live entries that overlap [from, to), and every
// running timer. Answered with time_data.
{"type": "list_time_data", "from": "2026-10-19T00:00:00Z", "to": "2026-10-26T00:00:00Z"}

// Create or replace one project (matched by id). Answered with
// time_project_saved; the change replicates to every node.
{"type": "save_time_project", "project": {"id": "550e8400-...", "name": "Docs", "client": "Clusto", "color": "#2a78d6", "archived": false, "created_at": "...", "updated_at": "..."}}

// Delete a project. Its entries are kept and show without a project.
{"type": "remove_time_project", "id": "550e8400-..."}

// Create or replace one entry (manual booking or edit). A new entry needs an
// end: timers start through start_timer. The owner is kept from the first save.
// Answered with time_entry_saved.
{"type": "save_time_entry", "entry": {"id": "7c9e6679-...", "description": "Write docs", "project_id": "550e8400-...", "tags": ["docs"], "start": "...", "end": "...", "created_at": "...", "updated_at": "..."}}

// Delete an entry (leaves a tombstone).
{"type": "remove_time_entry", "id": "7c9e6679-..."}

// Start a timer now for `owner` (the client's identity). First stops any
// running timer of the same owner.account; one time_entry_saved per change.
{"type": "start_timer", "description": "Write docs", "project_id": "550e8400-...", "tags": ["docs"],
 "owner": {"device": "laptop", "account": "<account key>", "user": "Daniel"}}

// start_timer also takes optional "links": a list of work item or connector
// task links (see below).

// Stop the timer entry with this id.
{"type": "stop_timer", "id": "7c9e6679-..."}

// Reply to list_time_data. syncs holds the per-entry sync records.
{"type": "time_data", "from": "...", "to": "...", "projects": [...], "entries": [...], "syncs": [...]}

// Reply to save_time_project and remove_time_project (removed: true there).
// Also pushed to every connected client.
{"type": "time_project_saved", "project": {...}}

// Reply to a save, remove, start or stop (removed: true after a remove). Also pushed to every connected client so
// each device shows a started, stopped or edited entry live.
{"type": "time_entry_saved", "entry": {...}}

// A time request failed (flag off, credential refused, bad input). request_id
// is set when the failed request carried one (search_time_tasks).
{"type": "time_error", "message": "...", "request_id": "..."}
```

An entry's `links` are `{"kind": "azure_devops", "account_id", "org", "id", "title"?}`
or `{"kind": "connector", "plugin_id", "connector_id", "id", "title"?, "url"?}`.

#### Time connectors and Toggl import

[Time connectors](/plugins#time-connectors) sync entries to another system. Client
messages:

```json
// The saved connector configs and the connectors the plugins provide.
{"type": "list_time_connectors"}

// Create or replace the config of one connector.
{"type": "save_time_connector", "config": {"plugin_id": "taskrequest", "connector_id": "taskrequest",
 "enabled": true, "node_id": "...", "interval_minutes": 15, "lookback_days": 30, "account": "<account key>", "updated_at": "..."}}

// Run a sync now. target is {plugin_id, connector_id}.
{"type": "sync_time_connector", "target": {"plugin_id": "taskrequest", "connector_id": "taskrequest"}}

// Search the connector's tasks. request_id comes back in the reply.
{"type": "search_time_tasks", "target": {...}, "query": "login", "request_id": "..."}

// The last sync runs and failures of a connector.
{"type": "list_time_sync_log", "target": {...}, "limit": 100}

// Import entries from Toggl. The token is used for this request only.
{"type": "import_toggl", "api_token": "...", "from": "2026-10-01", "to": "2026-10-23",
 "owner": {...}, "work_item_account": "...", "work_item_org": "...", "connector": {...}}
```

`owner`, `work_item_account`, `work_item_org` and `connector` are optional; the last
three say where `B#` and `TR#` references link. Server messages:

```json
// A sync record for one entry changed. Pushed to every connected client.
{"type": "time_sync_saved", "record": {...}}

// Reply to list_time_connectors. available lists what the plugins provide.
{"type": "time_connectors", "configs": [...],
 "available": [{"plugin_id": "...", "connector_id": "...", "name": "...", "search": true, "pull": false, "node_ids": ["..."]}]}

// A connector config was saved. Also pushed to every connected client.
{"type": "time_connector_saved", "config": {...}}

// Reply to sync_time_connector. pulled counts entries a two-way connector merged in.
{"type": "time_sync_run", "target": {...}, "summary": {"synced": 3, "failed": 0, "skipped": 1, "pulled": 2}}

// Reply to search_time_tasks.
{"type": "time_tasks", "target": {...}, "request_id": "...", "tasks": [{"id": "...", "title": "..."}]}

// Reply to list_time_sync_log.
{"type": "time_sync_log", "target": {...}, "rows": [{"at": "...", "target": {...}, "level": "info", "entry_id": "...", "message": "..."}]}

// Reply to import_toggl. skipped counts entries that were already imported.
{"type": "toggl_imported", "entries": [...], "projects": [...], "skipped": 2}
```

Connector requests (sync and search) run on the node the connector is configured
for; the daemon forwards them there. The `time_sync_log` is node-local.

Between nodes, projects and entries travel as `time_project_upserted` and
`time_entry_upserted` peer messages with Critical delivery (see
[State Replication](#state-replication)). They are stored in the `time_projects`
and `time_entries` tables, added in database schema v63. Sync records and
connector configs travel as `time_sync_upserted` and `time_connector_upserted`.
Schema v64 adds the `time_syncs` and `time_connectors` tables and the node-local
`time_sync_log`.

### Binary frames

Terminal traffic is the only part of the client protocol sent as binary
WebSocket frames instead of JSON. Terminal bytes are dense with control/ESC
sequences; JSON-escaping every one of them (`ESC` becomes \`\`) is a per-byte
scan plus a large size inflation, on the highest-volume traffic and on the
session's busy owner node - so it dominated CPU under load. A binary frame
ships the payload verbatim. Every frame starts with a one-byte tag; control and
lifecycle messages stay JSON text.

| Tag | Name | Direction | Layout after the tag |
|-----|------|-----------|----------------------|
| `0x01` | Output v1 | daemon to client | session id (16-byte UUID), `seq` (u64, big-endian), raw UTF-8 terminal payload |
| `0x03` | Input v1 | client to daemon | session id (16-byte UUID), raw PTY bytes |
| `0x04` | Chunk v1 | both | stream id (u32, big-endian), flags (1 byte, bit 0 = last piece), piece of a JSON message |
| `0x05` | Output-Part v1 | daemon to client | same as Output v1; a leading piece of a terminal chunk too large for one frame |

**Output v1.** The daemon's reader splits PTY output on UTF-8 boundaries, so
each frame's payload is valid UTF-8. Every client (CLI, the app's native layer,
and the browser/PWA shim) decodes the frame back into the logical `Output`
message; nothing else in the protocol changes.

**Input v1.** A client sends PTY input (every keystroke, paste chunk and mouse
report) as one Input v1 frame: 17 bytes of header plus the exact bytes, about
25 bytes for a keystroke against 99 for the old JSON `send_pty_input` array. The
daemon supplies the connection id from the connection itself, so a client cannot
name another connection's claim. JSON `send_pty_input` on the client link is
refused with "PTY input is sent as a binary input frame"; that form exists only
between nodes. Input is still accepted only from the connection that holds the
session's claim.

**Chunk v1.** A JSON message over 16 KiB (a history snapshot, a file listing,
a large reply) is cut into Chunk v1 pieces of 4 KiB to 256 KiB, sized to the
link, instead of one text frame. A WebSocket message cannot be interleaved once
it has started, so the cut lets the daemon put a keystroke echo, a ping or a
pong between two pieces. Pieces of one message share a stream id and arrive in
order; the frame with bit 0 set ends it, and the receiver rebuilds the original
JSON text (a client rebuilds up to 64 MiB; the daemon applies its own
WebSocket message limit). The app sends a request over 16 KiB the same way, in
16 KiB pieces.

**Output-Part v1.** A terminal output chunk larger than the current output
frame size (2 KiB to 256 KiB, a quarter of the pacing window) is sent as
Output-Part v1 frames followed by a plain Output v1 frame. All pieces share the
chunk's `seq`, and the receiver joins them into one logical `Output`.

**Writer lanes and pacing.** Each connection has one writer that serves, in
order: priority frames (pings, pongs, the resync notice); the interactive lane
(a session whose whole backlog is 4 KiB or less, such as a keystroke echo or a
prompt, up to a burst of 32 KiB that refills at 16 KiB/s); and the bulk lane,
round robin between the JSON control stream and every session with a backlog,
one bounded frame per turn. Bulk frames are followed by a WebSocket ping whose
payload is `0xC1` plus an 8-byte counter (a marker); the client's pong, which is
cumulative, tells the daemon how many bulk bytes arrived. The daemon keeps the
bytes sent but not confirmed near what the link carries in one round trip plus
about 150 ms of queue, so a keystroke echo does not wait behind megabytes
already accepted by a slow link. On an idle link a ping with payload `0xC2` and
a probe id measures the round trip. A client that never answers a ping is not
paced.

A session whose backlog exceeds about two seconds of link capacity (between
128 KiB and 4 MiB; 1 MiB before the rate is known) has its queued output
dropped whole. The daemon stops that stream and sends one `resync_required`
(see below); the client fetches a screen snapshot and subscribes again from its
boundary. This is what makes `Ctrl+C` on a flooding terminal stop stale output
within a second. JSON control frames keep their order in one FIFO, and a
session's output, resize boundaries and history snapshots keep theirs.

Per the no-backward-compatibility policy the whole fleet upgrades together, so
there is no JSON-output or JSON-input fallback.

> Cluster note: forwarded output between nodes (`PeerMessage::SessionOutput`)
> does not use these tags. On the peer link it travels as a `0xC0` frame whose
> UUID field carries the subscription's `subscriber_id`; see
> [Peer link framing](#peer-link-framing).

### Write Handling in a Cluster

Leaderless clustering has no leader and no redirect. Every connected node
serves writes locally: it applies the mutation to its own replicated state,
gossips it to all peers (`PeerMessage::SessionUpserted` / `SessionRemoved` /
`ProjectUpserted` / `TeamUpserted`, etc.), and answers the client directly.

A non-owning node forwards requests that must reach a specific session's live
process - interactive input, resize, and output subscription - to the recorded
owner via `PeerMessage::ForwardedRequest`, `PeerSendPtyInput`, or
`SubscribeOutput` (see [Request Forwarding](#request-forwarding) below). It also routes
`GetTeamMessages` through a member owner because operator-visible Team chat is
durable on that daemon rather than replicated cluster state. State mutations are
never forwarded; the receiving node is its own authority.

A PTY resize request uses this correlated request/response route rather than a
separate fire-and-forget peer message. The owner inserts `PtyResizeBoundary`
into the ordered session output stream before output from the new geometry, so
clients on every node apply the same rows and columns at the same stream
position. The owner then announces the resulting authoritative size to every
peer with `peer_session_resized`, so their session mirrors and clients update.

PTY input is also owner-authoritative, but rides the fire-and-forget
`peer_send_pty_input` message instead of the request/response route, so
keystrokes pipeline rather than waiting one node-to-node round trip each. On
the peer link it is a binary `0xC1` frame on the interactive lane, the same
lane as requests, so ordering holds. If the owner
no longer has the session it answers `session_not_found`, which the client's
node reports as `session_lost`. `SendPtyInput.data` remains a byte array through
the client, daemon, and peer messages. This is required for
terminal protocols such as X10 mouse reporting, whose bytes are not always
valid standalone UTF-8. A read-only viewer cannot use PTY mouse input as a
claim bypass because the owner applies the same claim check to every byte. The
owner submits accepted input to a bounded, nonblocking PTY writer queue. A full
queue returns an error instead of blocking the WebSocket worker or growing
without limit.

### SessionInfo Object

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "name": "my-session",
  "mode": "pty",
  "working_dir": "/home/user/project",
  "model": null,
  "created_at": "2025-01-15T10:30:00Z",
  "last_active": "2025-01-15T10:35:00Z",
  "attached_clients": 1,
  "project_id": null,
  "run_as_user": null,
  "command": "Zsh",
  "node_id": null,
  "kind": {"type": "shell", "command": "/bin/zsh", "args": null},
  "provider": "claude",
  "hidden": false,
  "team_id": null,
  "is_team_leader": false,
  "project_root": "/home/user/project",
  "tags": ["backend"],
  "claimed_by": "Desktop (laptop)",
  "claim_id": "uuid-connection",
  "pty_cols": 120,
  "pty_rows": 36,
  "terminal_title": "Refactor parser",
  "agent_working": false,
  "awaiting_input": false,
  "progress": {"state": "normal", "percent": 40}
}
```

Optional fields are omitted when unset: `adopted_pid`, `project_id`,
`run_as_user`, `command`, `node_id`, `team_id`, `project_root`, `tags`,
`dev_server`, `claimed_by`, `claim_id`, `claim_holder`, `pty_cols`, `pty_rows`,
`terminal_title`, `attention_reason`, `attention_prompt`, and `progress`.

**mode**: `"sdk"` | `"pty"` | `"adopted"`

* `"pty"` - interactive terminal session; output is raw terminal data.
* `"sdk"` - headless agent driven turn-by-turn. Each prompt (sent via
  `send_input`) spawns the provider CLI in stream-json mode; `Output` frames
  carry newline-delimited JSON the client parses into a chat transcript. The
  daemon threads the provider's own conversation id (`--resume`) across turns so
  context is preserved.
* `"adopted"` - an external Claude process registered with the daemon.

**provider**: which runtime backend backs an SDK-mode session - `"claude"`,
`"codex"`, `"opencode"`, or `"openrouter"`. OpenRouter uses Clusto's native HTTP backend.
Ignored for PTY/adopted sessions.

**hidden**: when `true`, the session is kept out of the terminals/sessions
listings. Used for durable Chats and other headless agent runtimes that have
their own UI. Absent/`false` for normal sessions.

**node_id**: UUID of the cluster node that owns the session, stamped by the daemon when the session list/created message is built for an app client. Absent when running standalone (no cluster). Lets the app label a session's node even when it has no explicit project.

There is no session status field. `agent_working` and `awaiting_input` carry
live activity. When a PTY session's process exits, attached clients receive
`session_killed` and the daemon removes the session; an SDK session stays and
reports each finished agent process with `session_completed`.

**kind**: describes what process the session runs.

* `{"type": "claude"}` - a Claude Code CLI session (SDK or PTY mode)
* `{"type": "shell", "command": "bash", "args": null}` - an arbitrary shell or command process

**claimed_by** / **claim_id** / **claim_holder**: the client holding exclusive
input control, and its device and account (see
[Session Exclusivity](/session-exclusivity)). **pty_cols** / **pty_rows**: the
owner's authoritative PTY size. **terminal_title**: the latest useful OSC
window title, cleaned of spinner glyphs. **awaiting_input** with
**attention_reason** and **attention_prompt**: the agent is blocked on the user
(see [Agent Waiting Marker](/agent-attention)).

**progress**: terminal progress reported by the program with `OSC 9;4`.
`state` is `normal`, `error`, `indeterminate` or `paused`; `percent` is 0 to 100
and is omitted for `indeterminate`. The daemon clears it after 15 seconds
without an update and pushes changes at most every 500 ms through
`session_updated`. See [Terminal Notifications](/terminal-notifications).

**team_id**: UUID of the team this session belongs to, or `null`.

**is_team_leader**: `true` if this session is the leader/coordinator of its team.

**agent_working**: `true` while the owning daemon detects an agent working
spinner in the terminal title. The daemon publishes changes with the session
metadata so terminal sidebar spinners stay consistent across clients and cluster
nodes, including clients that are not attached to the terminal output stream.

### Team Object

```json
{
  "id": "660f9500-f30c-52e5-b827-557766551111",
  "name": "research-team",
  "leader_session_id": "550e8400-...",
  "worker_session_ids": ["worker-uuid-1", "worker-uuid-2"],
  "status": "active",
  "created_at": "2025-01-15T10:30:00Z",
  "last_active": "2025-01-15T10:35:00Z",
  "updated_at": "2025-01-15T10:35:00Z",
  "project_id": null,
  "worker_results": {"worker-uuid-1": {"success": true, "result": "done", "...": "..."}},
  "final_result": null,
  "leader_agent": {"kind": "claude", "model": null, "args": null},
  "worker_agents": {"worker-uuid-1": {"kind": "codex", "model": null, "args": null}},
  "headless": false,
  "origin": {"kind": "chat", "chat_id": "770a1600-..."},
  "root_dir": null,
  "permission_mode": "bypass",
  "worker_roles": {"worker-uuid-1": "reviewer"},
  "leader_instructions": null,
  "worker_instructions": null,
  "worker_meta": {},
  "queued_assignments": []
}
```

**status**: `"active"` | `"inactive"`. `worker_results` entries carry
`success` (`null` when the outcome is unknown), `result`, `reported_at`, and
`reported_via` (an explicit report or the Stop-hook fallback).

> **Note**: teams work in both standalone and cluster modes and are persisted in SQLite either way. In cluster mode they are also replicated to all nodes via `PeerMessage::TeamUpserted` / `TeamRemoved`.

## Peer Protocol

Endpoint: `wss://<host>:<peer_port>/peer`, always TLS 1.3 with **mutual raw
public key authentication**: both nodes present their [identity key](/node-identity)
and the TLS session must negotiate the ALPN protocol `clusto/peer/2`. There is no
plaintext peer port; a plain HTTP request to it is answered with
`HTTP/1.1 426 Upgrade Required`, which is also how a node on an older release
fails to link. A node can also dial a peer through [Clusto Tunnel](/clusto-tunnel)
when the peer's address is a tunnel endpoint; that route uses the same ALPN and the
same handshake.

Used for inter-node cluster communication. Messages are `PeerMessage` JSON text
frames, except forwarded session output and forwarded PTY input, which use
binary frames, and a message over 64 kB, which is cut into chunk frames (see
[Peer link framing](#peer-link-framing)).

### Peer Connection Lifecycle

```
Connecting Node                    Accepting Node
  |                                  |
  |---- PeerHello ------------------>|
  |                                  |  (check TLS identity vs pin,
  |                                  |   verify membership_proof)
  |<--- PeerHelloAck ---------------|  (carries its own membership_proof)
  |                                  |
  |---- StateSummary -------------->|  (anti-entropy: both sides send one
  |<--- StateSummary ---------------|   fingerprint per record class)
  |<--- StateDigest ----------------|  (only for classes that differ:
  |---- missing records ----------->|   id -> version, answered with the
  |        ...                       |   records the sender lacks)
```

### Handshake

```json
// Connecting node identifies itself. The cluster token is never sent: instead
// membership_proof = HMAC-SHA256(key = cluster token UTF-8,
//   "clusto/peer-hello/v1" 0x00 || dialer identity (32 bytes)
//   || responder identity (32 bytes) || dialer node id (16 bytes)), as 64 hex.
// Both identities are the keys from the TLS handshake, so the proof cannot be
// replayed to another node. The node's metadata (display_name, version,
// platform, addresses, peer_port, default shell and session user, command
// registry, build and artifact info, web_tls, ...) is flattened into the message.
// It includes `instance_id`, a per-process id: a reconnect from a new instance_id
// fails the requests still pending on that peer's previous process at once.
{"type": "peer_hello", "node_id": "a1b2c3d4-...", "membership_proof": "<64 hex>", "display_name": "node-a", "version": "1.15.0", "peer_port": 9179, "...": "..."}

// Accepting node responds with its own proof (label "clusto/peer-ack/v1", same
// fields but the responder's node id) and metadata
{"type": "peer_hello_ack", "node_id": "b2c3d4e5-...", "success": true, "message": null, "membership_proof": "<64 hex>", "display_name": "node-b", "...": "..."}

// Rejected: bad proof (token mismatch) or a key that does not match its pin
{"type": "peer_hello_ack", "node_id": "b2c3d4e5-...", "success": false, "message": "invalid cluster token"}
{"type": "peer_hello_ack", "node_id": "b2c3d4e5-...", "success": false, "message": "identity mismatch"}
```

Each node pins its peers' identities in `peer_nodes` (`identity` and
`identity_updated_at`, last-writer-wins) and shares them in the roster. A pin
comes from adoption, from roster gossip (which only fills a missing pin and never
replaces an existing one), from the first contact that proves cluster
membership, or from `trust_peer_identity`, which changes the pin only on the
node that receives it. The `sync_cluster_config` message never carries the
cluster token. An identity mismatch is
refused, recorded as a conflict on the peer and never counts as a token
mismatch, so the node does not drop out of the cluster over it.

The old leader-based variants (`heartbeat`, `request_vote`, `leader_announce`,
and the rest) and the `term` field are gone from `PeerMessage`; there is no
election and no leader-push catch-up.

### State Replication

There is no leader push. Each node applies a local write to its own state and
gossips it once to all peers (a full mesh means one hop reaches everyone);
recipients apply it locally and never re-broadcast. Sessions carry a
`generation` and projects/teams carry an `updated_at` so a recipient resolves
conflicts last-writer-wins and rejects stale or reordered upserts. Removed
sessions leave a time-bounded tombstone so a late upsert cannot resurrect them
(a higher `generation` from the live owner can punch through - this self-heals
an erroneous removal during cluster churn).

```json
// Anti-entropy, sent by both sides on connect: one fingerprint per record
// class. Equal fingerprints end the exchange for that class, so an unchanged
// reconnect costs this one small frame each way.
{"type": "state_summary", "summary": {"classes": {"projects": 1234567890, "knowledge": 987654321}}}

// For the classes whose fingerprint differs: id -> version of what this node
// holds (updated_at in microseconds, a session's generation, a chat tombstone's
// removed_at, or a hash of a chat's content-free form). The receiver answers
// with every record the sender lacks or holds older, one per frame, as the
// incremental messages below; they are applied like live writes.
{"type": "state_digest", "digest": {"classes": {"projects": {"550e8400-...": 1794300000000000}}}}

// Flow control of that answer: after a batch of records the sender waits for
// the ack before it sends more.
{"type": "state_sync_mark", "mark": 7}
{"type": "state_sync_ack", "mark": 7}

// Incremental: session created/updated (gossiped on local mutation)
{"type": "session_update", "session": {"info": {...}, "output_history": [...]}}

// Incremental: session removed (records a tombstone on every node)
{"type": "session_removed", "session_id": "550e8400-..."}

// Incremental: project created/updated
{"type": "project_upserted", "project": {"id": "550e8400-...", "updated_at": "...", ...}}

// Incremental: project deleted
{"type": "project_deleted", "project_id": "550e8400-..."}
```

The digest also covers teams, chats (sent without their content, which the
receiver pulls with `chat_content_request`), chat tombstones, SSH connections
and credentials, agent docs, assets and variables, plugins, time tracking, read
marks, factory records and knowledge entries, each with its own
incremental messages (`team_upserted` / `team_removed`, `chat_upserted`, and so
on; time tracking uses `time_project_upserted` / `time_entry_upserted`). Tasks (`peer_task_*`), reports (`peer_report_changed`), and node settings
(`sync_*`) have their own messages outside the digest.

### Peer link framing

A message of at most 64 kB is one frame: JSON text, or a binary frame for
terminal output (`0xC0`, subscriber id, sequence, UTF-8 bytes) and forwarded
terminal input (`0xC1`, session id, 2-byte connection id length, connection id,
raw bytes). A larger message is cut into chunk frames of at most 64 kB (`0xC2`,
lane, flags, piece; flag bit 0 marks the last piece, bit 1 a JSON text body) and
reassembled per lane.

The writer sends one frame at a time from the highest lane that has one:

1. interactive - forwarded input, resize announcements and requests someone is
   waiting on;
2. output - forwarded terminal output (droppable);
3. transfer - replies too large for one frame, so a big download never freezes
   a terminal;
4. replication - live writes and periodic announces;
5. bulk - anti-entropy digests and chat content pulls.

A keystroke therefore waits behind at most one 64 kB frame of bulk traffic.

Each end pings the other every 5 s (`0xC3` ping, `0xC4` pong, 8-byte nonce).
Any received frame counts as a sign of life, not only a pong. A peer silent for
30 s (20 round trips on a slower link, at most 120 s) is disconnected and
redialed; a healthy link under load is no longer reset.

### Node Management

```json
// Request a peer to rename itself
{"type": "peer_rename_node", "name": "new-name"}

// Broadcast own display name change to all peers
{"type": "peer_display_name_update", "name": "new-name"}
```

Other node-management messages follow the same request/ack pattern and are
driven from the app's cluster screens: `peer_forget_node` (remove a node from
the cluster; the removal is also carried last-writer-wins in the
`node_removals` list of `sync_cluster_config`, so peers that miss the forget
converge), `update_daemon` / `self_update_from_url` (update a peer's
binaries; with `defer_restart` the peer stages the update and waits for a
`commit_staged_update`, which `cluster_self_update_from_url` with its optional
`node_ids` list uses to restart the selected nodes together, discarding a
staged update after 15 minutes without the commit), `restart_node`, `enable_tls`, and `set_tunnel_enabled`, each
answered by its `*_ack`. Nodes also broadcast `peer_metrics_announce`,
`peer_cli_version_announce`, `peer_node_commands_announce` and
`peer_node_defaults_announce` (default shell, session user, chat folder and
chat workspaces folder) so peers show live values on node cards, and
`peer_agent_idle` so clients on every node get the agent-idle popup.
The `agent_idle` notification and its `peer_agent_idle` relay carry an optional
`title`. When set it replaces the default `<name> finished` title and the
`detail` text is the body. The daemon sets it for notifications that programs
raise from the terminal with `OSC 9`, `OSC 777`, `OSC 99` or `OSC 7501` (see
[Terminal Notifications](/terminal-notifications)).

### Request Forwarding

State writes are never forwarded - every node applies them locally. Forwarding
exists only to reach a session's live process on its owning node (interactive
input, resize, output subscription). The originating node sends a
`forwarded_request` to the recorded owner; the owner runs it and replies with
`forwarded_response`. A `hops` budget bounds re-forwarding so a misrouted or
phantom-owner request cannot bounce around the mesh forever.

```json
// Originating node -> session owner
{"type": "forwarded_request", "request_id": "uuid-...", "payload": "{\"type\":\"send_input\",...}", "hops": 4}

// Owner -> originating node
{"type": "forwarded_response", "request_id": "uuid-...", "payload": "{\"type\":\"...\",...}"}
```

Session streams and input use dedicated peer messages instead of the
request/response pair:

```json
// Subscriber -> Owner: stream a session's output. from_seq (optional) resumes
// from the owner's replay ring.
{"type": "subscribe_output", "subscriber_id": "uuid-...", "session_id": "550e8400-...", "from_seq": 42}

// Subscriber -> Owner: stop streaming
{"type": "unsubscribe_output", "subscriber_id": "uuid-..."}

// Owner -> Subscriber: output chunk with the owner's seq (sent as a binary
// frame on the wire, see Binary output frame)
{"type": "session_output", "subscriber_id": "uuid-...", "seq": 43, "data": "..."}

// Owner -> Subscriber: from_seq predates the ring; surfaced to the client as
// resync_required
{"type": "session_resync_required", "subscriber_id": "uuid-...", "session_id": "550e8400-...", "last_seq": 42}

// Owner -> Subscriber: the owner has no such session (client sees session_lost)
{"type": "session_not_found", "session_id": "550e8400-..."}

// Client's node -> Owner: PTY input bytes, fire-and-forget. Shown as JSON for
// reference; on the wire it is a 0xC1 frame (session id, connection id, bytes).
{"type": "peer_send_pty_input", "session_id": "550e8400-...", "data": [104, 105], "connection_id": "uuid-connection"}

// Owner -> all peers: authoritative PTY size after a resize
{"type": "peer_session_resized", "session_id": "550e8400-...", "cols": 120, "rows": 36}

// A claim change, sent directly to peers so their clients update without
// waiting for replication. On release claimed_by is null and claim_id and
// claim_holder are omitted.
{"type": "peer_session_claimed", "session_id": "550e8400-...", "claimed_by": "Desktop (laptop)", "claim_id": "uuid-connection"}

// Sent when a peer joins and every 30 s: the exact set of sessions this node
// owns, so peers drop stale entries attributed to it
{"type": "session_ownership_announce", "sessions": ["550e8400-..."]}
```

### Project File Watching

Mirrors the session-output subscription model. A node that has a client
watching a remote-owned project asks the owner to watch the working directory;
the owner streams coarse, debounced change ticks back keyed by `subscriber_id`.

```json
// Subscriber -> Owner: start watching a project's working directory
{"type": "subscribe_project_files", "subscriber_id": "uuid-...", "project_id": "550e8400-..."}

// Subscriber -> Owner: stop watching
{"type": "unsubscribe_project_files", "subscriber_id": "uuid-..."}

// Owner -> Subscriber: files changed (Lossy - idempotent, debounced)
{"type": "project_files_changed", "subscriber_id": "uuid-..."}
```

## Tunnel and Web Relay Transports

[Clusto Tunnel](/clusto-tunnel) carries the same messages over iroh (QUIC)
connections. A node accepts three ALPN protocols on its tunnel endpoint:

| ALPN | Who may use it | Carries |
|------|----------------|---------|
| `hive/tunnel/1` | Native clients (apps, CLI) | The client protocol, with the same pre-auth handshakes |
| `clusto/peer/2` | Other cluster nodes | The peer protocol, authenticated as on the peer port |
| `clusto/web-relay/1` | Only the pinned web relay endpoint ids (`[tunnel] trusted_web_relays`, default the clusto.app relay) | The client protocol for a browser the relay forwards |

A web relay that dials a node on the web relay ALPN first sends a `WebRelayHello`
on a QUIC unidirectional stream, then opens the bidirectional stream that carries
the browser's `Auth` (or `PairStart`). The hello is JSON, at most 1024 bytes:

```json
{"client_id": "<1 to 64 lowercase hex characters>"}
```

`client_id` is an opaque identifier the relay derives for the signed-in account,
stable per account and relay. It contains no email address. The node keys its
pre-auth caps, its auth rate limiter and its audit log by it, so one relay user
cannot lock out the others. Anything that is not a trusted relay is refused on
this ALPN, and a trusted relay presenting the client or peer ALPN is closed.

The browser reaches the relay with `wss://web.clusto.app/relay/connect?node=<endpoint id>`,
offering the WebSocket subprotocols `clusto-relay` and `clusto-bearer.<hex of the
account token>`; the relay answers with `clusto-relay`. A request without a bearer
gets `401`, too many connects from one client get `429`, and a node that is not
linked to the signed-in account is refused with WebSocket close code **4403**
(`node-not-linked`) before the relay dials anything. See
[The web relay](/clusto-tunnel#the-web-relay).

## HTTP Endpoints

Besides `/ws`, the client port serves a few plain HTTP routes:

| Route | Auth | Returns |
|-------|------|---------|
| `GET /health` | none | `ok` (200) |
| `GET /identify` | none | `{"name": "<display name>", "version": "<daemon version>", "identity": "<64 hex>"}`, used by discovery. The identity is only a hint until a client verifies it with a TLS pin and `prove_identity` or pairing |
| `GET /metrics` | `Authorization: Bearer <token or cluster token>` | Prometheus text format: session, peer, and version metrics |
| `GET /notifications` | `Authorization: Bearer <token or cluster token>` | Cluster-wide notification feed polled by backgrounded mobile apps |
| `GET /clients/{kind}/{platform}` | `Authorization: Bearer <token or cluster token>` (no `?token=` query) | A staged client artifact as a download |

`/health` and `/identify` are served on every transport. Every other route
(`/ws`, `/metrics`, `/notifications`, `/clients/...`) carries a credential, so
over plaintext it is refused with `403` unless the source is loopback, Tailscale
or a `[transport] plaintext_networks` network; see
[Node Identity & Pairing](/node-identity#unencrypted-connections). Browsers also
need an allowed `Origin` for `/identify`, `/notifications` and the `/ws` upgrade.

```
GET http://<host>:<port>/health
Response: "ok" (200)
```
