Relay

Wire protocol

The contract between a Viewport Daemon, a Viewport Relay and any viewer (Console, CLI, mobile, CI). Session stream, control, pairing and approvals.

Protocol id viewport.daemon/v1. This page is normative: the daemon, the relay and @viewportai/daemon/client implement exactly this, and the conformance vectors in spec/conformance/ pin it. The same file lives in viewportai/daemon and viewportai/relay; the daemon copy is the source.

1. Layers

L3  Session protocol    JSON messages: hello, sessions, events, control, approvals, pairing admin
L2  Channel             Noise_IK (paired peers) or Noise_IKpsk1 (pairing), framed messages
L1  Relay envelope      only when going through a relay: hub routing, connection multiplexing
L0  Transport           WebSocket

A viewer reaches a daemon in one of three ways. L3 is identical in all three.

PathURLLayersAuthFor
LocalWebSocket over the Unix domain socket ~/.viewport/daemon/daemon.sock (path /v1/ws; a named pipe with an owner-only ACL on Windows)L3 as WebSocket text framesBearer token from ~/.viewport/daemon/token (0600)The CLI and tools running as the same OS user
Directws://<host>:7070/v1/connect (or wss://)L2 + L3Noise, paired peer keyA viewer on the same machine or LAN. Browsers on HTTPS origins can use Direct only to loopback or a wss:// URL; use Relay otherwise
Relaywss://<relay>/v1/viewer?hub=<daemon_id>L1 + L2 + L3Relay token, then Noise, paired peer keyAnything anywhere

The relay never sees L3. It routes ciphertext. Authorization to watch or control a daemon is decided by the daemon, from the peer list it keeps, never by the relay.

Default ports: daemon 7070, Console 7071, relay 7072.

2. Encoding rules

  • JSON is UTF-8. Keys Viewport defines are snake_case. User data (tool args, results, environment) is never transformed.
  • Binary values in JSON (keys, output bytes) are base64url without padding (RFC 4648 section 5), named *_b64.
  • Timestamps are RFC 3339 UTC with millisecond precision. Durations are *_ms integers.
  • Ids: ses_<ulid> sessions, apr_<ulid> approvals, off_<ulid> pairing offers, msg_<ulid> messages. daemon_id and peer_id are key fingerprints (section 5.1).
  • Readers ignore unknown fields and unknown event types. Writers never send fields this page does not define, except inside attributes objects.
  • Limits: one L3 message is at most 60 KiB of UTF-8 (it must fit in one Noise message, 65535 bytes, with room for the frame tag and the AEAD tag). A peer that receives an oversize message closes the channel with channel.message_too_large.
  • Output framing: the daemon splits terminal output into output events. The 32 KiB limit applies to the encoded event. The daemon splits on UTF-8 boundaries and uses data_b64 for any chunk that is not valid UTF-8.

3. L3: session protocol

3.1 Requests and results

The viewer sends requests. Every request has a client-chosen id (string, at most 64 chars, unique per connection). The daemon answers each request exactly once with a result.

Ordering: the result of session.subscribe is sent before any event for that subscription. Requests may be pipelined; results may arrive out of order. Subscribing again replaces the cursor.

{ "type": "session.subscribe", "id": "7", "session_id": "ses_01JDQ7...", "after_seq": 120 }
{ "type": "result", "id": "7", "ok": true, "data": { "session": { "...": "SessionInfo" }, "earliest_seq": 1, "latest_seq": 130 } }
{ "type": "result", "id": "8", "ok": false, "error": { "code": "daemon.session_not_found", "message": "No session ses_01..." } }

Errors always have the shape { "code", "message", "details"? }. details is an object.

The daemon also pushes messages with no id: event, session.lagged, session.updated, bye.

3.2 Roles

A connection has one role, fixed when it is authenticated.

RoleGranted toMay
viewerPeers paired with --role viewerhello, sessions.list, session.subscribe, session.unsubscribe, session.events, approval.get, peer.leave, ping
controllerPeers paired with --role controller (default)Everything a viewer may, plus session.start, session.input, session.resize, session.interrupt, session.stop, approval.respond
ownerThe local token onlyEverything a controller may except approval.respond and peer.leave, plus pair.offer, pair.confirm, peers.list, peers.revoke

A request outside the role fails with daemon.forbidden. The connection stays open.

The local token does not answer approvals unless the daemon's config sets local_approvals: true. An agent running as the same OS user must not be able to approve its own tool calls; approvals come from paired peers, whose keys children cannot read (section 7). peer.leave is for peers only, since the local token is not a peer.

3.3 Requests

typeFieldsdata on successRole
helloprotocols: string[] (e.g. ["viewport.daemon/v1"]), client?: { name, version }{ protocol, daemon: { id, name, version }, role, runners: RunnerInfo[] }viewer
sessions.liststatus?: Status[], pending_approvals?: true, tenant?, limit? (default 50, max 500), before?: session_id{ sessions: SessionInfo[], more }, newest first, strictly older than before when given; pending_approvals: true keeps only sessions with open approvals, tenant only that tenant'sviewer
session.subscribesession_id, after_seq? (default 0){ session, earliest_seq, latest_seq }, then event pushes from after_seq + 1viewer
session.unsubscribesession_id{}viewer
session.eventssession_id, after_seq, limit? (default 500, max 5000){ events: Event[], earliest_seq, latest_seq, more }: stored events with seq > after_seq, in order (Event is the event push without type)viewer
session.startrunner, cwd, prompt?, command?, args?: string[], name?, model?, terminal?, cols?, rows?, env?: { [k]: string }, idempotency_key?, tenant?, resume?{ session: SessionInfo }controller
session.inputsession_id, and exactly one of text (a prompt or a line for an agent) or data_b64 (raw bytes for a terminal){}controller
session.resizesession_id, cols (1-1000), rows (1-1000){}controller
session.interruptsession_id{}controller
session.stopsession_id, grace_ms? (default 2000){ session: SessionInfo } once stoppedcontroller
approval.respondapproval_id, decision: "allow" | "deny", reason?, updated_input?, actor?, action_digest (required to allow){ approval_id, decision, resolved_by }controller
approval.getapproval_id, offset? (bytes, default 0){ approval_id, action_digest, total_bytes, offset, chunk_b64, more }: the full action, in chunks (3.8)viewer
pair.offerrole? (default controller), ttl_ms? (default 600000, 30000 to 3600000), relay_url?, direct_url?, name?, watch?, confirm?, console_home? (local socket only){ offer_id, link, expires_at }owner
pair.confirmoffer_id, peer_id, confirmed: boolean{}; fails with daemon.pair_offer_invalid when this connection has no such question openowner
peers.listnone{ peers: PeerInfo[] }owner
peers.revokepeer_id{} and every open channel of that peer is closedowner
peer.leavenone{}, then the daemon removes the caller's own peer and closes all of its channels, this one includedviewer
pingnone{ at }viewer

hello is optional: the Noise handshake payload already carries the client's name and version. Its result also carries child_isolation: "home" | "none" (section 7), so a viewer can warn when children could read the daemon's home, and, under "home" with a working sandbox, isolation?: string[]: the absolute, realpath-resolved read-deny roots that hold viewer and Console secrets (the daemon home, every known Console home, ~/.viewport/viewer). A Console can check that its own home is listed before it trusts the daemon with its key. A daemon picks the first entry of protocols it speaks and fails with daemon.invalid_request if there is none.

session.start: command and args are the program and its arguments for the command runner (args are extra CLI arguments for agent runners). terminal (default true) asks for a PTY. env is merged over the daemon's scrubbed child environment (section 7). Secrets should not be sent this way; configure them on the daemon. tenant (1 to 128 characters from A-Z a-z 0-9 . _ : -) labels the session for a multi-tenant viewer. The daemon stores it on SessionInfo, filters on it, and does not enforce isolation by it: every peer with a role still sees every session. It is part of the intent compared for idempotency_key.

idempotency_key (at most 128 chars): the same key with the same intent (every other field) returns the same session; the same key with a different intent fails with daemon.idempotency_conflict.

Byte budgets: every result fits in one L3 message (60 KiB). sessions.list and session.events return fewer items than limit when the next item would not fit, and set more: true whenever items remain after the last one returned (more: false means the page reached the end). Page on with before (the last session's id) or after_seq (the last event's seq). A single event never exceeds the budget: output events are split (section 2) approval actions are truncated (3.8), and large message and tool_call events are truncated (3.7).

pair.offer probes every target it is given (section 5.2), from the local socket as from the CLI, with the same 3 second budget, a loopback direct_url included. watch: true asks for a pair.paired push on this connection when the offer is redeemed. confirm: true (implies watch) makes this connection the operator of --confirm (5.3): the daemon pushes pair.pending and holds the viewer until this connection answers with pair.confirm; a closed connection counts as a refusal. Both are how the CLI's pair works over the local socket.

Retries (at-least-once delivery): a viewer that loses its channel cannot know whether a request ran, so requests are safe to repeat. session.start with an idempotency_key returns the same session. approval.respond that repeats the winning answer of the same caller (same decision, reason, updated_input, actor and action_digest) returns the original result; any other answer to a resolved approval, including the same caller with any field changed, gets daemon.approval_already_resolved with the winning decision in error.details. session.input has no deduplication: repeat it only after checking the session's events.

Daemon restarts: sessions that were running when the daemon stopped become failed with daemon.interrupted_by_restart. Their outcome is unknown, so the daemon never re-runs them by itself. A viewer continues an agent's conversation with a new session.start whose resume is the old session's agent_session_id (runners with capabilities.resume), using an idempotency_key so a retried start does not fork it twice. Events persist before they are sent, so a reconnecting viewer replays everything with session.subscribe.

3.4 Pushes

{ "type": "event", "session_id": "ses_01...", "seq": 131, "at": "2026-11-25T10:37:00.123Z", "event": { "type": "output", "stream": "pty", "data": "hello\r\n" } }
{ "type": "session.lagged", "session_id": "ses_01...", "skipped_from_seq": 132, "resume_from_seq": 190 }
{ "type": "session.updated", "session": { "...": "SessionInfo" } }
{ "type": "bye", "reason": { "code": "daemon.shutting_down", "message": "..." } }
{ "type": "pair.pending", "offer_id": "off_01...", "peer_id": "vpp_...", "daemon_id": "vpd_...", "role": "controller", "name": "Console", "deadline": "2026-11-25T10:39:00.000Z" }
{ "type": "pair.paired", "offer_id": "off_01...", "peer": { "...": "PeerInfo" } }
  • event is sent only for sessions the connection subscribed to.
  • session.lagged is sent only for subscribed sessions, see 3.5.
  • session.updated is sent to every authenticated connection whenever a session is created, changes status, or its pending_approvals change, so a session list stays live without subscribing to every stream.
  • bye precedes a deliberate close.
  • pair.pending and pair.paired go only to the local connection that made the offer with confirm or watch (3.3). Viewers ignore push types they do not know (section 9).

3.5 Session stream and replay

  • seq starts at 1 per session and increases by exactly 1. The daemon persists events before sending them.
  • session.subscribe with after_seq: n delivers every stored event with seq > n in order, then live events, with no gap and no duplicate. The result's latest_seq is the last seq that existed at subscribe time.
  • If n + 1 < earliest_seq (the store compacted older events), the daemon delivers from earliest_seq. The viewer detects the gap by comparing. output events are the only ones a store may compact.
  • Exactly-once processing is the viewer's job: drop any seq already present, not "any seq at or below the last one seen", because session.lagged gap fills deliver seqs below the newest one. Reconnecting viewers resume from the lowest seq they have not filled (after_seq = that seq - 1) and drop what they already hold.
  • Backpressure: if a connection's outbound queue exceeds 4 MiB, the daemon stops sending output events to it. Other events are never dropped. The daemon resumes output when the queue falls below 1 MiB and then sends one session.lagged push per affected session with skipped_from_seq (the first output seq it skipped) and resume_from_seq (the first seq it sends again). Fetch the gap with session.events. If the queue still exceeds 16 MiB the daemon closes the connection with daemon.slow_consumer; the viewer resubscribes from its last seq.

3.6 Shapes

type Status = "starting" | "running" | "waiting_input" | "waiting_approval" | "exited" | "failed" | "stopped";

interface SessionInfo {
  id: string;                 // ses_...
  runner: string;             // "command" | "claude-code" | "codex" | "gemini-cli" | custom
  name?: string;
  cwd: string;
  status: Status;
  created_at: string;
  ended_at?: string;
  exit_code?: number | null;
  signal?: string | null;
  last_seq: number;
  agent_session_id?: string;  // the agent's own id (Claude session id, Codex thread id), for resume
  tenant?: string;            // from session.start
  terminal?: boolean;         // true: runs in a PTY; false: pipes (asked for, or a fallback); absent: no terminal (agent runners) or an older record
  pending_approvals: PendingApproval[];   // at most 8, see "Size" below
  pending_approvals_count?: number;      // present when more than 8 are open
  attributes_truncated?: true;
  error?: ErrorShape;         // why the session failed, e.g. daemon.interrupted_by_restart
  attributes?: Record<string, unknown>;
}

interface PendingApproval {
  approval_id: string;
  action: Action;             // args may be truncated, see 3.8
  args_truncated?: true;
  action_digest: string;      // "sha256:" + hex of SHA-256 over the JCS (RFC 8785) encoding of the full action
  reason?: string;
  requested_at: string;
  expires_at: string;
}

interface Action { tool_name: string; args: Record<string, unknown>; call_id?: string }
interface ErrorShape { code: string; message: string; details?: Record<string, unknown> }

interface RunnerInfo {
  name: string;
  available: boolean;         // binary or SDK found
  reason?: string;            // why not available
  capabilities: { terminal: boolean; approvals: boolean; structured_events: boolean; resume: boolean; updated_input: boolean };
}

interface PeerInfo { peer_id: string; name?: string; role: "viewer" | "controller"; paired_at: string; last_seen_at?: string }

Size: an encoded SessionInfo is at most 24 KiB, so session.updated, sessions.list pages and session.subscribe results always fit. To get there the daemon shapes it, in order: pending_approvals keeps at most the 8 oldest entries, with pending_approvals_count giving the total when there are more; inside SessionInfo, an entry inlines action.args only up to 2 KiB of JCS (otherwise args: {} and args_truncated: true, the digest unchanged; action_digest is always present, and it is what an allow echoes) and cuts reason to 1024 code points; then error.message, name and cwd are cut to 1024 code points; then attributes is dropped with attributes_truncated: true. If it is still over 24 KiB, the remaining strings are cut to 128 code points, error.details is dropped, and pending_approvals keeps fewer entries (at least one while any is open), with pending_approvals_count giving the total. The full entries reach subscribers as approval_requested events (3.7 rules) and through approval.get.

Invariants: pending_approvals is non-empty if and only if status is waiting_approval. last_seq never decreases for a session, across session.updated pushes, sessions.list and session.subscribe results alike, so a viewer keeps the copy with the higher last_seq (on a tie, the later one received).

Terminal states are exited (process ended by itself, any exit code), failed (could not start, or the runner reported an error), and stopped (ended by session.stop or daemon shutdown).

3.7 Events

Every event has type. Message, tool and model events use the field names of Viewport trajectory v1 events, so a session's events convert to a trajectory without renaming.

typeFieldsNotes
statusstatus, previousEvery status change
outputstream: "pty" | "stdout" | "stderr", data (UTF-8 text) or data_b64Raw process output. pty for terminal sessions
messagemessage_id, role: "user" | "assistant" | "system", content (string), partial?: trueAgent text. partial chunks are deltas. A final message with the same message_id carries the full content and supersedes its partials
tool_callcall_id, tool_name, args, status: "started" | "completed" | "failed", result?, error?: { type, message }One event per status change, same call_id
model_callmodel?, usage: { input_tokens, output_tokens, cache_read_tokens?, cache_write_tokens?, cost_usd? }Emitted when the agent reports usage
approval_requestedapproval_id, action: { tool_name, args, call_id? }, args_truncated?, action_digest, reason?, expires_atStatus becomes waiting_approval. The event's at is the request time
approval_resolvedapproval_id, decision: "allow" | "deny", resolved_by, reason?, actor?resolved_by: peer:<peer_id>, local, handler, timeout, session_ended. actor echoes the responder's claim
exitexit_code: number | null, signal: string | nullLast event before the terminal status
errorerror: { code, message, details? }Runner errors. The session may continue

Large events: any event push other than output whose encoding exceeds 48 KiB is shortened, field by field in a fixed order, until it fits:

  1. The type's bulk fields: message.content; tool_call.result, then tool_call.args. A string keeps its longest code-point prefix that fits; args becomes {} and a non-string result becomes null.

  2. If it still does not fit, every other string anywhere in the event body except type, ids (*_id), status, previous, decision, resolved_by, role, stream and digests is cut to its first 1024 code points, in JCS key order, depth first. Examples: error.message, reason, tool_name.

  3. If it still does not fit, every object or array left under args, result, error.details and action.args becomes {} (or []).

  4. If it still does not fit (unbounded ids such as a runner's call_id), the remaining strings that step 2 skipped, ids included, are cut to 128 code points, except type, status, previous, decision, role, stream and digests.

After step 4 every event fits, because what remains is bounded. Each shortened field is listed in truncated_digests under its dotted path (content, result, args, error.message, reason, ...), with the digest of the JCS (RFC 8785) encoding of the original value (the action_digest form, 3.8), and the event carries truncated: true. The rule is deterministic, so the live push and session.events deliver identical events. Viewers show the field as truncated with its digest. A chunked fetch of the full field is planned for v1.1; until then the full value exists only in the daemon's store. output events are split instead (section 2), and approval args are handled in 3.8.

3.8 Approvals

The approvals hook is how a human (or a policy engine such as Viewport HITL) decides on an agent's tool call.

  1. A runner that supports approvals (Claude Code through the Agent SDK canUseTool, Codex approval requests) asks the supervisor.
  2. If the supervisor has an in-process approval handler, it runs first. A handler returns allow, deny or ask (or { effect, reason?, updated_input? }). ask means "ask the humans".
  3. Otherwise the daemon emits approval_requested, and any controller may answer with approval.respond.
  4. The first answer wins (compare and set). Later answers get daemon.approval_already_resolved with the winning decision in error.details.
  5. No answer by expires_at (default 5 minutes) denies it: resolved_by: "timeout". Fail closed. A session that ends first resolves its open approvals as deny with resolved_by: "session_ended".
  6. updated_input replaces the tool input when the runner supports it (capabilities.updated_input; Claude Code does). Runners that do not reject it with daemon.updated_input_unsupported and the approval stays open.
  7. action_digest binds a decision to one exact action, which catches answers sent to the wrong approval and actions that changed (races). Every allow must carry it: an allow without it, or with one that differs from the approval's digest, fails with daemon.approval_action_mismatch and the approval stays open. A deny may leave it out (when given, it must match). The viewer echoes the action_digest from pending_approvals, approval_requested or approval.get; it never needs to compute one. The digest is "sha256:" + lowercase hex of SHA-256 over the JCS (RFC 8785) encoding of the full action { tool_name, args, call_id? }. The daemon cannot know what a viewer displayed: a viewer that echoes the digest of args it showed as {} gets its allow accepted. Showing the full action is the viewer's duty (step 9).
  8. actor (at most 128 characters, the same character rules as peer names) is who the viewer says decided, for example the human behind a shared Console. The daemon records and echoes it but cannot verify it: the authenticated identity is resolved_by.
  9. Large actions: when the JCS encoding of action.args exceeds 16 KiB, approval_requested and pending_approvals carry args: {} and args_truncated: true, with the digest of the full action. approval.get returns the JCS encoding of the full action in chunks of at most 32 KiB (chunk_b64, from byte offset, more until offset + chunk length = total_bytes). The viewer joins the chunks, parses them, checks the digest, and shows and answers it like any other approval. A viewer must not allow an action whose args it showed truncated (over 16 KiB here, over 2 KiB inside a SessionInfo (3.6), or fields an event cut (3.7)) without first fetching the full action with approval.get and showing it. The daemon cannot enforce this; the reference client (RemoteSession.approve) does, by refusing to allow an action it has seen only truncated. approval.get works for open approvals and for resolved ones whose session is still stored; otherwise it fails with daemon.approval_not_found.

4. L2: channel

4.1 Frames

Every channel message is a byte string with a one-byte tag. On a direct WebSocket each channel message is one binary WebSocket message. Through a relay, each is the payload of one L1 data frame.

TagNameDirectionBody
0x01preambleviewer to daemon, first messageUTF-8 JSON { "v": 1, "mode": "session" } or { "v": 1, "mode": "pair", "offer_id": "off_..." }
0x02handshakebothA Noise handshake message
0x03transportbothA Noise transport message whose plaintext is one L3 JSON message
0x04rejectdaemon to viewer, before the handshake completesUTF-8 JSON { "code", "message" }, then the channel closes

Any other tag, a frame out of order, or a failed decryption closes the channel.

reject is not authenticated: anyone on the path, including a relay, can send one, and the same holds for close reasons (a relay close 4100 reason, a WebSocket close reason, daemon.pair_not_confirmed). Viewers treat all of them as advisory and report them under their own code (channel.rejected, with the claimed code in details), never as the daemon's error code. They show the code and may retry with backoff, but never act on it destructively: no forgetting the daemon, no deleting keys or pairings, no downgrade. Only a completed handshake tells the viewer anything about the daemon.

4.2 Noise

  • Suite: Noise_IK_25519_AESGCM_SHA256 for session mode, Noise_IKpsk1_25519_AESGCM_SHA256 for pair mode, exactly as specified in the Noise Protocol Framework revision 34. Standard names, standard test vectors. Every primitive is in WebCrypto (X25519, AES-256-GCM, SHA-256, HMAC), so browsers need no crypto library.
  • The viewer is the initiator and must already know the daemon's static public key (from pairing). The daemon is the responder.
  • Prologue: the exact bytes of the preamble frame body. A relay that alters the preamble breaks the handshake.
  • Through a relay, the viewer waits for relay.hub_online (6.2) before sending the preamble. When the daemon drops, the channel is dead: the viewer re-handshakes after the next hub_online.
  • Browsers: every primitive must be native. Viewers feature-detect X25519 in crypto.subtle and fail with daemon.crypto_unsupported when it is missing. Minimums: Chrome 133+, Safari 17+, Firefox 130+.
  • Handshake message 1 payload (viewer): UTF-8 JSON { "client": { "name", "version" } }. Message 2 payload (daemon): { "daemon": { "id", "name", "version" }, "role", "peer_id" }.
  • After Split(), each direction has its own key and its own 64-bit counter nonce. No random nonces.
  • A channel sends at most 2^32 transport messages per direction; then either side closes it and the viewer reconnects (a fresh handshake). Keys live only in memory.

4.3 Session mode

After message 1 the daemon knows the viewer's static key. If its fingerprint is not in the peer list, the daemon sends reject with daemon.peer_unknown and closes; revoked peers get the same. Otherwise it answers with message 2 and the channel carries L3 with the peer's role.

4.4 Pair mode

See section 5.3.

5. Pairing

No accounts and no hosted service. Identities are keys. The daemon is the root of trust for its own sessions.

5.1 Identities

  • Daemon: an X25519 static key pair in ~/.viewport/daemon/identity.json (0600, atomic write, created without ever replacing an existing file; the daemon refuses to load it when other users can read or write it). daemon_id = vpd_ + the first 26 characters of the lowercase base32 (RFC 4648, no padding) of SHA-256(public key), where the public key is the raw 32-byte X25519 public key. 130 bits. The relay hub id is this daemon_id, derived from k.
  • Public keys must be canonical: 32 bytes, little endian, u < 2^255 - 19 (bit 255 clear). X25519 ignores bit 255, so without this one key would have two fingerprints. Both sides refuse non-canonical keys in links, handshakes and fingerprints.
  • Viewer: an X25519 static key pair per device, generated and kept by the viewer (Console stores it in IndexedDB as a non-extractable key where the platform allows). peer_id = vpp_ + the same encoding of its public key.

viewport-daemon pair (or pair.offer over the local socket) creates a single-use offer:

  • offer_id (off_<ulid>), a 32-byte random secret, the role, an expiry (default 10 minutes), and the targets the daemon can be reached on.
  • The link carries everything a viewer needs, in the URL fragment so it never reaches a server log:
https://<console>/pair#v=1&k=<daemon_public_key_b64>&o=<offer_id>&s=<secret_b64>&r=<relay_ws_url>&t=<viewer_relay_token>&d=<direct_ws_url>&n=<daemon_name>
viewport://pair#v=1&k=...&o=...&s=...&r=...&t=...&d=...&n=...

k is the raw 32-byte X25519 public key, base64url. s is 32 bytes, base64url. Values are percent-encoded (encodeURIComponent). r and d are optional, but at least one is present, and neither carries credentials (user:pass@). n, like the handshake name, is at most 128 characters with no control, bidi or zero-width format characters. t is the relay token a viewer presents to the relay, present when r is (unless the relay is open); it is an operator credential and grants no access to the daemon. The console base URL comes from config (console_url). Without one the link is viewport://pair#..., never an http URL on the daemon's machine, where a sandboxed child could be listening; viewport:// is also the form for native apps. The CLI prints the link and a QR code of it.

  • Before printing, the CLI probes every target (relay reachable and hub admitted, direct URL answering) with a 3 second budget and prints only reachable ones. If none is reachable, no offer is created and the command fails with daemon.pair_target_unreachable.
  • Local pairing (Console's first run): a tool holding the local token calls pair.offer with a loopback direct_url, then pairs over the direct channel like any viewer, checking that k matches the daemon.id the local hello reported. This is safe because the local socket lives in the daemon home: only the same OS user can create or reach it, and children can neither read the token nor stand in for the socket (section 7). The daemon's config local_pairing: false makes pair.offer over the local socket fail with daemon.forbidden for operators who want pairing only from the CLI.
  • Console's home (section 7): the Console sends console_home, the absolute path of its home, in that local pair.offer. The daemon resolves it by realpath, requires an existing directory (never /, a home directory or an ancestor of one), adds it to the children's read-deny roots before the offer exists, and keeps it in <home>/console-homes.json (0600) so it stays denied after a restart. It only ever adds a deny root. Anything else fails with daemon.invalid_request and changes nothing. A channel peer (direct or relay) that sends console_home gets daemon.forbidden. Children already running keep the policy they started with.
  • Offers expire and are single use. There is no failed-attempt lockout: the secret is 256 bits, so guessing is hopeless, and the offer_id travels in the clear in the preamble, so a lockout would let anyone who sees it (a relay, a shoulder surfer) block pairing.

5.3 Pair handshake

  1. The viewer opens a channel (direct or relay) and sends preamble { "v": 1, "mode": "pair", "offer_id" }.
  2. Both sides derive psk = HKDF-SHA256(ikm = secret, salt = "viewport.daemon/v1 pair", info = offer_id, 32 bytes).
  3. The viewer runs Noise_IKpsk1 with the daemon key k from the link. Message 1 is encrypted under a key that mixes the psk, so only a holder of the secret can produce it, and it carries the viewer's static key and { "client": { "name", "version" }, "name": "<peer display name>" }.
  4. The daemon looks up the offer. Unknown, expired or used offers, and a message 1 that fails to decrypt, get reject (daemon.pair_offer_invalid). Otherwise the daemon sends message 2 with { daemon, role, peer_id }. Up to here nothing changes state: message 1 can be replayed by anyone who saw it, and a replay must not burn the offer or store anything.
  5. When the viewer's first transport message decrypts (which proves a live holder of the ephemeral key, not a replay), the daemon marks the offer used with a compare and set (so two racing redeems cannot both win) and stores the peer { peer_id, public_key, name, role }, before it processes that message. If the compare and set loses, the channel closes. Session mode follows the same rule: admission has no side effects until the first transport message decrypts.
  6. The channel is now an authenticated channel in that role, exactly as in session mode. Next time the viewer connects in session mode with the same key.

Why this is safe against a malicious relay: the viewer got the daemon's public key out of band (the link), so the relay cannot impersonate the daemon; and the relay never learns the secret, so it cannot pair itself.

Optional confirmation compares full fingerprints, never a short code. The viewer shows its own peer_id and the daemon_id of k; the daemon shows the peer_id it received and its own daemon_id. All 26 characters of each must match. Both sides show the 26 characters in groups of 4 and the operator confirms each group, because someone who substituted the link learns the viewer's peer_id and can grind a key that matches a prefix (8 characters take about 2^40 tries). viewport-daemon pair --confirm asks the operator to compare before the peer is stored (over the local socket: pair.offer with confirm, then pair.pending and pair.confirm, 3.3). The daemon asks when the viewer's first transport message decrypts (step 5) and holds that message, so the viewer's first request (usually hello) gets no result while the operator decides. The viewer shows "waiting for the operator" from message 2 until that result. The operator has 120 seconds, or until the offer expires if that is sooner. A refusal or a timeout closes the channel with daemon.pair_not_confirmed as the reason (relay close 4100 with that code, or the WebSocket close reason on a direct channel), and the offer stays unused until it expires. A short code derived from h is not used: whoever terminates a substituted handshake chooses message 2 and can grind h until a 6 digit code collides, which takes about a million tries. A 130-bit fingerprint cannot be ground.

Short typed codes (PAKE) are planned and not part of v1.

5.4 Revocation

viewport-daemon peers revoke <peer_id> removes the peer and closes its open channels. There are no tokens to expire because every connection is authenticated by the peer's key on each handshake.

6. L1: relay

6.1 Daemon side

The daemon connects outbound to wss://<relay>/v1/daemon with Authorization: Bearer <relay_token> (or the Sec-WebSocket-Protocol value viewport.relay.v1, auth.<token> for clients that cannot set headers). Tokens are RFC 7230 token characters, so they fit in that header. The relay echoes only viewport.relay.v1, never the auth. entry.

Text frames are relay control, binary frames are data.

relay  -> daemon  {"type":"challenge","relay_key_b64":"<X25519 ephemeral public key>","nonce_b64":"<32 bytes>"}
daemon -> relay   {"type":"register","daemon_key_b64":"<daemon static public key>","proof_b64":"<32 bytes>","name":"<optional>"}
relay  -> daemon  {"type":"registered","hub":"<daemon_id>","relay":{"name","version"}}
key   = HKDF-SHA256(ikm = X25519(daemon_static, relay_ephemeral), salt = "viewport.relay/v1 register",
                    info = relay_origin, L = 32)
proof = HMAC-SHA256(key, nonce || relay_key || daemon_key)

relay_origin is the origin of the relay URL the daemon dialed, serialized as in the WHATWG URL standard (wss://relay.example, lowercase, port only when not the default, no trailing dot). The relay checks it against its own public origin (config public_url, stored already serialized the same way). One relay per origin: two relays under different paths of one host would share an origin, and the binding could not tell them apart. relay_key, nonce and daemon_key are the raw 32-byte values. The relay computes the same DH with its ephemeral private key, which it uses for one challenge only. This proves the daemon holds the private key for daemon_id, so nobody else can take its hub. The origin binding stops a relay the daemon connects to from forwarding another relay's challenge and registering the daemon's hub there. The HKDF salt keeps this DH output from keying anything else. A second registration for a live hub replaces the first only if it proves the same key (a daemon restart); the old socket is closed with relay.hub_replaced.

Data frames on the daemon socket: op (1 byte) || conn (4 bytes, big endian) || body.

opNameDirectionBody
0x10openrelay to daemonUTF-8 JSON { "ip_hash": "<hex>" }, a salted hash for rate limiting and logs
0x11databothOne L2 channel message
0x12closeboth2-byte close code, then optional UTF-8 reason

conn is chosen by the relay, unique per daemon socket, never reused while the socket lives.

6.2 Viewer side

The viewer connects to wss://<relay>/v1/viewer?hub=<daemon_id> with the relay token as above (browsers use the Sec-WebSocket-Protocol form). Each binary WebSocket message is one L2 channel message, both ways. Text frames from the relay are status:

{"type":"status","code":"relay.hub_offline"}      the daemon is not connected; the socket stays open and the relay sends
{"type":"status","code":"relay.hub_online"}       when it connects. Channel messages sent while offline are dropped.
{"type":"status","code":"relay.rate_limited","retry_after_ms":30000}   sent before closing with 4008

A viewer sends its preamble only after relay.hub_online. A relay.hub_offline after that means the channel is dead; the viewer starts a fresh handshake after the next relay.hub_online.

6.3 Auth and limits

  • Relay tokens are operator credentials: they decide who may use the relay at all. They never grant access to a daemon. A relay may hold separate token lists for daemons and viewers.
  • Defaults: 65,600 bytes per WebSocket message (one channel message: a tag plus one Noise message), 4 MiB buffered per connection (then close relay.slow_consumer), 64 viewers per hub, 2000 connections total, 50 per IP, 120 upgrades per minute per IP, ping every 30 s.
  • A daemon socket carries every viewer of its hub, so the relay does not close it for one viewer's traffic. It counts each viewer's bytes still waiting in that socket's buffer. When the buffer is over its budget, the viewer with the most waiting bytes is closed with relay.slow_consumer, but only if that is more than its fair share: the budget divided by the hub's viewers, and never less than two maximum-size messages. A viewer at or under its fair share is never closed for this. Bytes of viewers already gone (closed by the relay, by the daemon, or by themselves) still drain but count against nobody. The daemon socket also has a hard cap that counts every buffered byte, cut viewers' included: past twice the budget the relay stops reading the hub's viewers and holds their messages, in order, until the socket drains below the budget. A daemon socket past four times the budget, or held back while draining less than 64 KiB in 10 s, is closed with relay.slow_consumer: a daemon that stops reading loses its hub rather than grow the relay. A slow daemon that keeps draining is never closed for that, and the sockets the relay paused are not closed for missing pings while it holds them.
  • The relay measures what a daemon has read with WebSocket pings in the daemon socket's data stream: after each 64 KiB it writes, it sends a ping carrying a payload, and keeps at most 1 MiB written that no pong has acknowledged. A daemon MUST answer each ping with a pong echoing its payload, as soon as it reads it (RFC 6455 5.5.2; WebSocket libraries do this by default). Pongs acknowledge cumulatively and in order, so answering only the latest of several pings is fine. A daemon that sends no pongs stalls at the 1 MiB window, is held back, and is closed with relay.slow_consumer within the drain deadline above.
  • A viewer closed with relay.slow_consumer waits before attaching to that hub from that IP again: after the first cut, which is forgiven, its upgrades are refused with relay.rate_limited and a retry_after_ms that doubles with each further cut (2 s up to 5 min). Backoff is never keyed by the relay token, which viewers may share, and never by the IP alone. Reconnects without a cut are never delayed.
  • The relay does not inspect data bodies beyond length.

6.4 Close codes

CodeMeaning
1000Normal
1001Relay or daemon shutting down
1002Protocol error (a malformed WebSocket frame; sent to the daemon in a close frame for that viewer)
1003A viewer sent a text frame (viewers send only binary channel messages)
1009Message too large
1011Relay internal error: admission failed, or a daemon dialed before the relay knows its public origin
4001relay.unauthorized (bad or missing token)
4003relay.forbidden (token not valid for this role or hub)
4004relay.hub_unknown (viewer named a hub id that is not well formed)
4008relay.rate_limited
4009relay.hub_replaced
4010relay.register_failed (bad proof)
4013relay.slow_consumer
4100channel.closed by the daemon (reason text carries the daemon.* code)

HTTP: GET /health returns { "ok": true }. GET /metrics (Prometheus) requires the admin token.

7. Security properties

  • End to end: the relay sees hub ids, connection counts, sizes and timing. It never sees L3.
  • Authentication: every viewer connection proves a paired key; the daemon proves its key in every handshake and at relay registration.
  • Forward secrecy: ephemeral keys per channel (Noise e). Compromise of a static key does not reveal past channels.
  • The local socket is a Unix domain socket inside the daemon home (directory 0700), not a TCP port: no other process can squat its address and harvest the token, because only the daemon's user can create files there and sandboxed children cannot reach the home at all. It requires the token and rejects any request with an Origin header (browsers must use the Direct path). Direct and Relay need no such protection: the viewer authenticates the daemon's key in the Noise handshake, so whoever answers on a port proves nothing.
  • The Direct endpoint answers 403 to an upgrade whose Origin header is present and not allowed (the origin of console_url, localhost and 127.0.0.1 interchangeable, plus allowed_origins), before the upgrade takes a pending-handshake slot: otherwise any web page could hold the per-address slots for loopback with idle sockets. An upgrade with no Origin is not from a browser and is allowed; a loopback one may use 2 slots kept from browser pages and from other addresses.
  • Child processes get a scrubbed environment (no VIEWPORT_* variables, nothing that holds a daemon secret such as the relay token). The viewport-daemon CLI passes only a minimal set (PATH, HOME, locale, terminal and similar) plus names given with --env-allow; claude-code children also get Claude Code's auth variables.
  • Trust boundary: the daemon trusts its OS user, not its children. By default (child_isolation: "home") every child runs in an OS sandbox (sandbox-exec on macOS, bwrap on Linux) with these rules:
    • No reads or writes of key material: the daemon home (by realpath, including a VIEWPORT_HOME override), Console's home (~/.viewport/console, VIEWPORT_CONSOLE_HOME, and every home a Console named in a local pair.offer, 5.2), ~/.viewport/viewer, and the browser profile directories where a browser viewer keeps its peer key (Chrome, Chromium, Edge, Brave, Firefox and Safari profile roots on that OS; the list is in the daemon's sandbox profile and extensible in config). Without that last rule a child could read a web Console's "non-extractable" key from the browser's disk store and answer approvals as Console.
    • Writes only to the session's cwd, the OS temp directory, and the runner's own state directory (for example ~/.claude for claude-code), extensible in config. This stops a child from planting code that later runs unsandboxed: login items, LaunchAgents and systemd user units, shell startup files, and the daemon's own install directory.
    • Linux: a new PID namespace (--unshare-pid), so a child cannot read the daemon through /proc/<pid>/mem or environ.
    • session.start.env applies inside the sandbox only. Loader variables (LD_*, DYLD_*) are refused with daemon.invalid_request, because on the launcher they would run code before the sandbox exists. If the platform has no such sandbox, runners fail to start with daemon.runner_unavailable unless the config sets child_isolation: "none", which hello reports so viewers can warn.
  • What this buys: an agent cannot read the token or any viewer key, so it cannot reach the local socket, pair itself, or answer approvals as a viewer, and the token does not answer approvals anyway (3.2, defense in depth). What it does not buy: an agent can still do anything its write paths allow, including editing the project a human later runs outside the daemon, and it can talk to the network. For agents you do not trust at all, run the daemon as a separate OS user.
  • What is out of scope for v1: hiding metadata from the relay, multi-relay routing, short code pairing.

8. Error codes

daemon.forbidden, daemon.invalid_request, daemon.session_not_found, daemon.runner_not_found, daemon.runner_unavailable, daemon.session_ended, daemon.approval_not_found, daemon.approval_already_resolved, daemon.updated_input_unsupported, daemon.peer_unknown, daemon.pair_offer_invalid, daemon.pair_target_unreachable, daemon.slow_consumer, daemon.shutting_down, daemon.idempotency_conflict, daemon.capacity, daemon.interrupted_by_restart, daemon.crypto_unsupported, daemon.approval_action_mismatch, daemon.pair_not_confirmed, channel.rejected, channel.message_too_large, channel.protocol_error, and the relay codes in 6.4.

9. Versioning

viewport.daemon/v1 changes only additively: new optional fields, new event types, new request types. A daemon answers an unknown request type with daemon.invalid_request and keeps the connection. A breaking change is v2, negotiated in hello (protocols) and the preamble v.

Additive changes since the first v1 draft:

  • SessionInfo.terminal (3.6): whether the session runs in a PTY (true) or over pipes (false), as the runner actually started it. Optional: agent runners and records written before it leave it out, and a viewer that does not know it ignores it.
  • pair.offer console_home (3.3, 5.2): local socket only. The daemon denies that directory to children from then on and across restarts. An older daemon ignores the unknown field, so a Console that needs the guarantee checks hello.isolation.
  • hello.isolation (3.3, 7): the absolute, realpath-resolved read-deny roots holding viewer and Console secrets, under child_isolation: "home" with a working sandbox. Optional: older daemons leave it out and older clients ignore it. The relay repo vendors this document (scripts/refresh-daemon-wire.sh) and needs the same sync.
  • Breaking for clients, within v1 before its first release: approval.respond with decision: "allow" requires action_digest at every size (3.8 step 7). It was required only above 16 KiB. Clients echo the digest the daemon already sends. The digest binds the answer to one exact action; it does not prove what the viewer displayed, so viewers fetch and show truncated actions before allowing (3.8 step 9).

On this page