# Wire protocol reference

`@edgeai/edge-client-ts` speaks the **exact same wire protocol** as the
Rust `edge-client` (`ec` binary). This document is the authoritative
spec; both clients must conform.

> If you find a discrepancy between the TS and Rust implementations,
> that is a bug — open an issue.

---

## Transport

- **WebSocket** to the relay's `/edge` path (text + binary frames).
- **Subprotocol** header: `Sec-WebSocket-Protocol: edgeai-v2, <auth_token>[, device-secret=<value>]`.
  - The `<auth_token>` is the **fleet shared secret** (`EDGE_AUTH_TOKEN`).
  - `device-secret=<value>` is sent when the device has been issued a
    per-machine secret (post-enrollment).
- **TLS** (recommended for production):
  - `wss://` only — `ws://` is refused when `EDGEAI_REQUIRE_TLS=1` or
    `NODE_ENV=production`.
  - Optional **SPKI fingerprint pin** (SHA-256 hex of the DER
    `SubjectPublicKeyInfo`). Pin mismatch → handshake aborted.

---

## `/edge` JSON connection

All messages are JSON, UTF-8 text frames.

### Client → Server

#### `register`

First message after upgrade.

```json
{
  "type": "register",
  "machine_id": "<uuid-v4>",
  "agent_id": "worker_default",
  "platform": "linux",
  "hostname": "<short-hostname>",
  "agent_version": "0.1.0",
  "operator_id": "op_<your-operator-id>"
}
```

| Field | Required | Notes |
|-------|----------|-------|
| `machine_id` | yes | Stable per-machine UUID. The relay uses this as the device PK. |
| `agent_id` | yes | Default agent id for dispatch when the dashboard does not pin one. |
| `platform` | no | `linux` / `darwin` / `win32`. |
| `hostname` | no | Display only; relay stores on `devices.display_name`. |
| `agent_version` | no | Display only. |
| `operator_id` | no | When set, the relay auto-claims ownership on first heartbeat. |

#### `heartbeat`

Every `heartbeat_interval_s` seconds (default 30).

```json
{
  "type": "heartbeat",
  "machine_id": "<uuid-v4>",
  "operator_id": "op_<your-operator-id>",
  "system": {
    "cpu_cores": 8,
    "cpu_usage_pct": 12.4,
    "mem_total_mb": 16384,
    "mem_available_mb": 9216,
    "disk_total_gb": 512.0,
    "disk_free_gb": 320.5,
    "load_avg_1m": 0.42,
    "process_count": 312
  }
}
```

#### `ack`

Acknowledge receipt of a `stream` message from the relay.

```json
{ "type": "ack", "msg_id": "<relay-msg-id>" }
```

#### `stream` (rare)

The TS client sends `stream` messages from the offline buffer drain —
they have the same shape as relay → client `stream` messages.

#### `execute_response` / `agent_list` / `browser_fetch_result`

Server-originated RPC responses, forwarded back to the dashboard.

### Server → Client

#### `registered`

Sent once on successful registration.

```json
{ "type": "registered", "machine_id": "<uuid-v4>", "agent_id": "worker_default" }
```

If the relay just minted a per-device secret, the next message is
`device_secret_issued` (one-time).

#### `device_secret_issued`

```json
{
  "type": "device_secret_issued",
  "secret": "<base64-32-bytes>",
  "device_id": "<uuid-v4>"
}
```

#### `stream`

A message destined for the local agent.

```json
{
  "type": "stream",
  "msg_id": "<uuid-v4>",
  "machine_id": "<uuid-v4>",
  "agent_id": "worker_default",
  "payload": { "...": "agent-specific JSON" },
  "timestamp": 1721000000000
}
```

The TS client forwards `payload` to the local `agent_id` Pi process and
replies with `ack`.

#### `set_config`

Live config push from the relay.

```json
{
  "type": "set_config",
  "heartbeat_interval_s": 30,
  "network_mode": "lan"
}
```

#### `execute` / `list_agents` / `get_available_models` / `browser_fetch`

RPC commands from the dashboard. The TS client spawns the relevant
handler and replies via the buffer queue.

---

## `/shell-edge` binary channel

After `/edge` registration succeeds, the TS client opens a second
WebSocket to `/shell-edge`. This channel carries **binary frames** for
shell sessions — byte-exact with the Rust client.

### Frame layout

```
+----------------+----------------+----------+----------------+
| session_id     | FrameType      | payload_len (u32 BE) | payload     |
| 16 bytes (UUID)| 1 byte         | 4 bytes              | N bytes     |
+----------------+----------------+----------------------+------------+
```

Total header size: **17 bytes** (UUID + FrameType + u32 BE length).

### `FrameType` enum

| Value | Name | Direction | Payload |
|-------|------|-----------|---------|
| 0x00 | `Data` | both | PTY output bytes |
| 0x01 | `Resize` | client → server | `{ cols: u16 BE, rows: u16 BE }` |
| 0x02 | `Close` | both | empty (graceful shutdown) |
| 0x03 | `Ping` | both | empty (heartbeat) |
| 0x04 | `Pong` | both | empty (heartbeat reply) |

The first frame after upgrade MUST carry a `session_id` matching the
one issued by the relay's `share_token` handshake. A mismatch is a
fatal protocol error (close code 4403).

---

## Buffer dump encryption

When the in-memory queue overflows, the daemon encrypts entries with
AES-256-GCM and writes them to disk.

### Envelope

```
+----------------+----------+----------------------------+
| KEY_VERSION=1  | nonce    | ciphertext + GCM tag       |
| 1 byte         | 12 bytes | N bytes                   |
+----------------+----------+----------------------------+
```

- **KEY_VERSION**: always `0x01` in v1.x. A future major version may
  introduce `0x02`.
- **nonce**: 12 random bytes (NEVER reuse with the same key).
- **key**: 32 bytes (256 bits), configured via `EDGE_BUFFER_KEY` (hex, 64 chars).
- **tag**: 16 bytes (default GCM tag length).
- **algorithm**: AES-256-GCM (RFC 5116).

Key rotation is supported via `EDGE_BUFFER_KEY_PREVIOUS` — the daemon
can decrypt entries written with the previous key and re-encrypt with
the new one on next dump.

---

## TLS pinning

When `relay.fingerprint` (or `EDGE_RELAY_FINGERPRINT`) is set, the
client:

1. Completes the standard TLS handshake against the Mozilla CA bundle.
2. Extracts the leaf certificate's `SubjectPublicKeyInfo`.
3. Hashes it with SHA-256.
4. Compares in constant time against the configured pin.

**Extract the pin for a relay cert:**

```bash
openssl s_client -connect <relay-host>:443 < /dev/null 2>/dev/null \
  | openssl x509 -pubkey -noout \
  | openssl pkey -pubin -outform DER \
  | openssl dgst -sha256 -binary \
  | xxd -p -c 64
```

> **Cert-renewal-safe.** The pin is over the **public key**, not the
> full cert — operators do not need to repin on a cert rotation,
> only on a keypair rotation.

---

## Versioning

The wire protocol is versioned implicitly via the `Sec-WebSocket-Protocol`
identifier (`edgeai-v2`). Future major versions will use `edgeai-v3`,
etc. The TS client will refuse to connect if the relay advertises an
unrecognized protocol version.