# Remote control, stage 2: the relay protocol

Status: accepted; landed. Tether (ticket ed086ebc04) is remote control of a running pic from a
phone: a phone is one more sender and observer of the journal, through ssh (stage 1, `pic attach`
and `pic send`, in [grapevine](grapevine.md) and [the inbox](../dev/inbox.md)) or through a relay
that sees only ciphertext (this note). Done: ssh; pairing, `pic remote` and the phone page at
`remote.zeitforge.app` (`pic-relay`); the reply streamed as it is written; Web Push when a request
ends; `/rc` in one step with a short link and QR code per conversation; the interface following a
phone's request; a login agent (`pic remote install`) so `pic remote` comes back after a restart;
images in a prompt from the phone, and in the conversation on it.
The invariants are in [the relay side](../dev/remote.md), the user's view in
[remote control](../manual/remote-control.md). Deferred: durable questions (an approval answered
from the phone), and with them a "needs input" notification, which waits for that work; other
commands from the phone; opening the relay beyond invitations (open question 1).

Tier: bundled (`pic remote`, pairing in `/rc`, push; seams: the inbox and the read view), external
(the relay and the phone page, repository `pic-relay`). Clock: pi, os. Record: a `pic_inbox` row or
a keyed admission per command, the sender `remote:DEVICE` on what it caused; device and key rows in
`~/.pic/pic.sqlite`. Default: off; nothing dials out until `pic remote` is run.

This note is the wire contract between two implementations written in parallel: pic (C11, BearSSL)
and `pic-relay` (TypeScript: a Cloudflare Worker with one Durable Object per mailbox, and the phone
page, on WebCrypto). Everything either side must agree on is here and in the test vectors (section
8). Where this note says "must", a vector or a test in section 10 checks it.

The short form: **a phone is one more sender and one more observer of the journal.** `pic remote`
is a process beside the others on the shared store. It dials out to a relay that forwards
ciphertext, speaks a Noise session to each paired phone, turns each command into a journal row
before anything acts on it, and rebuilds events from committed rows as `pic attach` does. It holds
no lease and no state the journal and the user database do not already hold.

Durable questions (an approval answered from the phone) are a later ticket and are not here.

## Notation

- `||` joins bytes. Integers on the wire are big-endian. `b64u` is base64url without padding
  (RFC 4648 section 5). JSON is RFC 8259, UTF-8, no byte order mark.
- `SHA256(x)` is FIPS 180-4; `HMAC(k, x)` is HMAC-SHA-256 (RFC 2104); `trunc16` keeps the first 16
  bytes.
- "Noise" is The Noise Protocol Framework, revision 34 (2018-07-11); section numbers are its.
- pic is the **responder** and the phone the **initiator** in every handshake.
- `up` is phone to pic; `down` is pic to phone.

## 1. Roles and keys

| Party | Runs | Trusted with |
|---|---|---|
| pic | `pic remote`, and `/rc` while pairing | everything: it is the machine being controlled |
| phone | the page, in a browser or installed to the Home Screen | everything a local user of pic has (section 4) |
| relay | the Worker and its Durable Objects | availability and routing only; sees ciphertext and the metadata in section 3 |
| page host | the same Worker, serving the page's files | the integrity of the page's code (section 9) |
| push service | Apple, Google or Mozilla | delivering an encrypted notification; sees its size and time |

### Keys

| Key | Type | Made | Kept |
|---|---|---|---|
| pic static | P-256 ECDH | first `/rc` | `picu_remote_key` row `static`: public in the clear, private sealed |
| pic VAPID | P-256 ECDSA | first `/rc` | row `vapid`, the same way |
| mailbox owner token | 32 random bytes | first `/rc` | row `mailbox`, sealed; its public column is the mailbox id |
| phone static | P-256 ECDH, one per pairing | at pairing | IndexedDB, as a `CryptoKey` made with `extractable: false` |
| channel token | 32 random bytes, one per pairing | by the phone at pairing | IndexedDB; pic keeps only the channel id |
| pairing secret | 32 random bytes | per `/rc` offer | memory of the `/rc` process; shown once in the QR code |
| ephemerals, session keys | per handshake | | memory only, on both sides |

Three keys, three uses: the static key only does ECDH inside Noise, the VAPID key only signs VAPID
tokens, and the owner token is only ever shown to the relay. No key is used for two algorithms.

**pic's storage.** Two tables in `~/.pic/pic.sqlite`:

- `picu_remote_key(name TEXT PRIMARY KEY, public BLOB, sealed BLOB NOT NULL, created_ms INTEGER
  NOT NULL)`. `sealed` is `pic_cred_seal` (`src/cred.h`: ChaCha20-Poly1305 under the credential
  store's master key) with the additional data `remote-key:NAME`.
- `picu_remote_device(id BLOB PRIMARY KEY, sealed BLOB NOT NULL, paired_ms INTEGER NOT NULL,
  seen_ms INTEGER)`. `id` is 16 random bytes pic chose. `sealed` holds the JSON object `{"name",
  "static", "channel", "push"}` (the phone's name, its static public key and channel id as `b64u`,
  and its push subscription or `null`) with the additional data `remote-device:` and the id in
  hex.

The device row is sealed although it holds no private key: a row that does not open under the
master key is not a device, so adding a phone takes the passphrase, not just write access to the
file. The relay's address is the setting `remote.relay`.

**The phone's storage.** One IndexedDB database, `pic-rc`, with one object per pairing: the static
`CryptoKeyPair` (`{name: "ECDH", namedCurve: "P-256"}`, `extractable: false`, usage `deriveBits`),
pic's static public key, the mailbox id, the channel token, the device id, pic's VAPID public key
and pic's name. `CryptoKey` objects are stored by structured clone; the private key's bytes never
exist in script. A second store, `outbox`, holds commands not yet answered (section 4). Conversation content and cursors are held in memory only and are gone when the
page closes.

### Unpairing

- **At the terminal.** `/rc` lists devices (name, paired, last seen) and unpairs one: the row is
  deleted in one transaction, which needs no passphrase. A running `pic remote` sees the change
  within a second (it polls the user database's `PRAGMA data_version`), sends that device
  `{"type":"unpaired"}` if it has a session, drops the session and deletes the channel at the
  relay. With no `pic remote` running, the next one deletes the channel when it reconciles (section
  7). The row's deletion is the revocation; the relay's part only saves traffic.
- **On the phone.** "Forget this computer" sends `{"type":"unpair"}` when it has a session and
  deletes the pairing object either way.
- **Everything.** `/rc` reset deletes every device row and all three keys, and the mailbox at the
  relay. The next `/rc` starts from nothing.

A revoked phone still holds a channel token and a static key that no longer open anything: pic
refuses a handshake whose static key is not in the table, and the relay refuses a deleted channel.

## 2. Pairing

### Primitives

One suite, in pic from BearSSL and in the page from WebCrypto, with no other cryptographic code on
either side:

| Function | Choice | BearSSL | WebCrypto |
|---|---|---|---|
| DH | P-256 | `br_ec_p256_m31` `mulgen` and `mul` | `generateKey`, `deriveBits` with `ECDH` |
| cipher | AES-256-GCM, Noise `AESGCM` (12.4) | `br_gcm` over `br_aes_ct_ctr` (or `x86ni`), `br_ghash_ctmul32` | `AES-GCM`, 96-bit iv, 128-bit tag |
| hash | SHA-256, Noise `SHA256` (12.5) | `br_sha256` | `digest` |
| HKDF | Noise's (4.3) | `br_hmac` | `sign` with `HMAC` |

Noise defines no P-256 DH function, so this note does, in the form section 4.1 asks for:

- `GENERATE_KEYPAIR()`: a P-256 key pair.
- A public key on the wire is its 65-byte uncompressed encoding, `0x04 || X || Y` (SEC 1 version 2,
  section 2.3.3). An encrypted static key is therefore 81 bytes.
- `DH(pair, public)`: the 32-byte X coordinate of the shared point (SEC 1 section 3.3.1; what
  `deriveBits` returns for 256 bits and what RFC 8291 uses).
- A received public key must be a valid point on the curve other than the point at infinity
  (NIST SP 800-56A revision 3, section 5.6.2.3.4). `br_ec_p256_m31.mul` returning 0 and
  `importKey("raw", ...)` rejecting are that check; a handshake that fails it is dropped.
- `DHLEN` is 65 for public keys and 32 for DH outputs. Nothing else in Noise depends on the two
  being equal.

The same suite with the same deviations is in deployed use: the hybrid transport of CTAP 2.2
(passkeys across devices) is `Noise_KNpsk0_P256_AESGCM_SHA256` and `Noise_NKpsk0_P256_AESGCM_SHA256`
started from a QR code.

Noise's `HKDF(ck, ikm, n)` is computed as three HMAC calls, as section 4.3 writes it, on both
sides. The page does not use WebCrypto's `HKDF` algorithm, because `Split()` passes a zero-length
key and importing one fails in some browsers; with HMAC the key is always the 32-byte `ck`.

### Patterns

| Use | Protocol name (section 8) | Pattern |
|---|---|---|
| pairing | `Noise_IKpsk1_P256_AESGCM_SHA256` | `<- s` ... `-> e, es, s, ss, psk` / `<- e, ee, se` |
| session | `Noise_IK_P256_AESGCM_SHA256` | `<- s` ... `-> e, es, s, ss` / `<- e, ee, se` |

`IK` (7.5) is the pattern for an initiator that already knows the responder's static key, which the
QR code gives the phone. It takes one message each way, it carries the phone's static key encrypted
to pic's, so pic learns which device is calling from the handshake itself and several phones can
share one code path, and it is the pattern WireGuard uses for the same shape of problem. `IKpsk1`
(9.4) is the same pattern with the one-time pairing secret mixed in at the end of the first
message, so the first message's payload already proves the sender scanned the code. The names are
31 and 27 bytes long, so `h` starts as the name padded with zeros to 32 bytes (5.2). In the `psk`
protocol each `e` token also calls `MixKey(e.public_key)` (9.2).

Rejected: `XX` and `XXpsk3` spend a third message to transmit a static key the phone already has
and would still need the comparison `IK` does for free; `KK` needs pic to know which device is
calling before it can read the first message, which means a cleartext device name; `NK` gives the
phone no key to be recognized by later.

The prologue (section 6) of both handshakes is 41 bytes:

    "pic-rc/1" || 0x00 || mailbox id (16) || channel id (16)

with the pairing channel's id when pairing and the device's channel id in a session. A handshake
replayed onto another mailbox or channel, or between protocol versions, fails.

### The offer and the QR code

`/rc` unlocks the credential store (asking for the passphrase if it is locked), makes the keys and
the mailbox on first use, and then for each offer:

    ps          = 32 random bytes                      the pairing secret
    psk         = HMAC(ps, "pic-rc/1 pair psk")        Noise's psk
    pair_token  = HMAC(ps, "pic-rc/1 pair token")      shown to the relay
    P           = trunc16(SHA256("pic-rc/1 channel" || pair_token))

It registers channel `P` as a pairing channel with a lifetime of 600 seconds, opens that channel's
stream, and shows a QR code of

    https://RELAY/#p1.<b64u(0x01 || mailbox id (16) || pic static public (65) || ps (32) || expires (8))>

`expires` is Unix seconds. The offer is 122 bytes and the address about 200 characters, which is a
version 9 QR code. Everything secret is in the fragment, which a browser does not send to a
server. The relay is the address's own origin. The relay learns `pair_token`, from which `psk`
cannot be computed.

An offer admits one device. It ends when a device is paired or refused, at `expires`, when `/rc`
is closed, or after 5 first messages that fail to verify.

### The handshake

The phone opens the address. The page reads the fragment, removes it from the address bar
(`history.replaceState`) before anything else runs, refuses an expired offer, and makes: a static
key pair, a channel token `D` (32 random bytes) with its channel id `C = trunc16(SHA256("pic-rc/1
channel" || D))`, and a session id (8 random bytes).

1. Phone to pic, on channel `P` with `pair_token`: message 1 with the payload
   `{"v":1,"name":NAME,"channel":b64u(C)}`. `NAME` is a label the phone picks ("iPhone, Safari"),
   at most 64 bytes.
2. pic reads it. A message that does not verify counts against the offer and is otherwise ignored.
   One that does proves its sender knew `ps` and holds the static key it sent. pic answers with
   message 2 and the payload `{"v":1,"device":b64u(id),"name":HOST,"vapid":b64u(VAPID public)}`.
3. Both sides now hold the handshake hash `h` (11.2) and the two transport keys. Each computes

       sas = decimal(uint32(HMAC(h, "pic-rc/1 sas")[0..4]) mod 1000000), 6 digits, zero-padded

4. The phone shows the code and sends the transport message `{"type":"pair_ready"}`.
5. On `pair_ready`, the terminal shows the device's name and the code and asks: "Pair NAME? It
   should show 333 054. [y/N]". Nothing has been written yet.
6. On yes, pic commits the device row, registers channel `C` as a device channel, sends
   `{"type":"paired"}` and deletes channel `P`. On no, or at expiry, it sends
   `{"type":"error","payload":{"code":"pair_refused"}}` and deletes `P`.
7. On `paired`, the phone stores the pairing and opens its first session on `C`.

A crash of `/rc` between the row and `paired` leaves a device that never connects and shows as
"never seen" in the list; the phone reports that pairing failed. The channel registration is
repeated by the next `pic remote` (section 7).

### What stops a relay in the middle

The relay carries every handshake byte and never sees the fragment. To answer the phone as pic it
needs pic's static private key, since the phone encrypts to the public key it read from the
screen (`es`, `ss`). To call pic as a phone it needs `psk`, which is derived from `ps`. It has
neither, so it can only drop or delay messages.

The code on both screens covers the case the secret does not: a QR code that leaked (a photograph,
a shared screen). Whoever uses it first holds the offer, and the terminal then shows a name and a
code that the owner's own phone is not showing; the owner's phone shows a failure. The prompt
defaults to no.

## 3. Transport over the relay

### Mailboxes and channels

A **mailbox** belongs to one pic install. A **channel** is one phone's lane in it, or one pairing
offer's. Both are named by a hash of a random token, so presenting the token proves the right to
use the name and the relay stores no secrets:

    mailbox id  M = trunc16(SHA256("pic-rc/1 mailbox" || owner token))
    channel id  C = trunc16(SHA256("pic-rc/1 channel" || channel token))

pic creates the mailbox and registers every channel in it (section 6); a phone can use only a
channel pic registered. Tokens travel only in the `Authorization: Bearer b64u(token)` header, over
TLS, never in an address.

Each channel has two one-way lanes. A lane is an ordered pipe with a short memory, not a queue for
an absent reader:

| Lane | Writer | Reader |
|---|---|---|
| `up` | the phone: `POST .../c/C/up` | pic: one stream for all its device channels |
| `down` | pic: `POST .../c/C/down` | the phone: `GET .../c/C/down` |

Both directions are server-sent events down and `POST` up, on both sides. pic reads its stream
with `pic_http_get` and the framer in `src/sse.c`. The page reads its stream with `fetch` and a
`ReadableStream`, not `EventSource`, which cannot send the `Authorization` header.

### Records

The unit the relay forwards is a **record**, opaque to it:

| First byte | Record | Layout after the first byte |
|---|---|---|
| `0x01` | handshake message 1 | session id (8), Noise message |
| `0x02` | handshake message 2 | session id (8), Noise message |
| `0x03` | transport | session id (8), counter `n` (8), ciphertext |
| `0x04` | reset | session id (8) |

The session id is the initiator's 8 random bytes; it only tells sessions on one channel apart. The
channel's kind decides which protocol a message 1 starts. A record is at most 16417 bytes.

A `POST` body is `application/octet-stream`: records one after another, each behind its length as
2 bytes; at most 32 records and 256 KiB. A stream event is

    id: N
    event: frame
    data: b64u(record)            a channel's stream
    data: b64u(C).b64u(record)    pic's mailbox stream

### Transport messages

After message 2, `Split()` (5.2) gives two cipher states: the first encrypts `up`, the second
`down`. A transport record carries its nonce, as section 11.4 provides for transports that can
lose messages:

    ciphertext = ENCRYPT(k, n, zerolen, plaintext)      nonce = 0x00000000 || n (8 bytes), section 12.4

Rules, each side for the lane it writes:

- `n` starts at 0 and goes up by one for every record sent. A value is never used twice under one
  key. Keys and counters live in memory only and a session is never resumed from storage, so a
  restart cannot repeat a nonce: it starts a new handshake.
- A session ends, and the phone starts a new one, before `n` reaches 2^32 in either direction or
  after 24 hours. pic asks for it with `{"type":"bye","payload":{"reason":"rekey"}}`. `Rekey()`
  (11.3) is not used: a new handshake is the one way keys change, and it brings new ephemerals.

Rules for the lane it reads:

- Keep `last`, the highest `n` accepted, starting at -1. A record with `n <= last` is dropped
  before decryption (a replay, or a duplicate from a reconnect). A record with `n > last` is
  decrypted with that `n`; if it verifies, `last = n`. The relay keeps a lane in order, so no
  window is needed.
- A record that fails to verify is dropped and changes nothing.
- `n > last + 1` is a **gap**: records were lost. The transport reports the gap to the layer above
  and carries on. Reliability is the envelope's business (section 4), not the transport's.

The plaintext is one flag byte and up to 16383 bytes of an envelope message: `0x00` when more of
the message follows in the next record, `0x01` on its last record. A message's records are
consecutive. A gap inside a message discards the part received. A message is at most 4 MiB.

### Sessions

1. The phone opens its stream and posts message 1 with the payload `{"v":1}`.
2. pic reads it and looks up the static key it carried. The key must be a device in the table,
   and that device's channel must be the channel the record came on; otherwise the record is
   dropped without an answer. pic answers with message 2, payload `{"v":1}`, and holds the session
   as **unconfirmed**.
3. The phone sends its first transport message (a `sessions` or `sync`, section 4). When it
   verifies, the session is **confirmed**.

pic sends nothing but message 2 on an unconfirmed session and acts on nothing from it. Message 1
of `IK` can be replayed by anyone who recorded it (7.7), and a replay gets exactly that: a message
2 it cannot use. Unconfirmed sessions are dropped after 30 seconds, and a channel has at most two.
A confirmed session replaces the device's earlier ones.

`v` is the highest version the sender speaks; this note defines 1. An incompatible change gets a
new prologue label, so the two versions cannot complete a handshake with each other.

A session outlives its streams: when a stream breaks, both sides reconnect and continue with the
same keys. pic drops a session that has been silent for 10 minutes. The page sends
`{"type":"ping"}` every 60 seconds while it is visible and pic answers `{"type":"pong"}`. A
transport record for a session pic does not have is answered with a **reset** record, which is
not authenticated and so may cause one thing only: the phone starts a new handshake, at most once
every 5 seconds.

### What the relay sees

For every record: the mailbox id, the channel id, the direction, the length, the time, and the
record's cleartext head (its type, the session id and the counter). For every connection: the
address, the TLS and HTTP details any server sees, the bearer token, and so which mailbox or
channel is connected and when. From registration: how many devices a mailbox has, and when an
offer was open.

It does not see: any key but the tokens, pic's or the phone's static public key, the device's
name, which conversation or workspace is in use, any command, event or text, or anything about
push (pic talks to the push service itself).

Lengths are not padded in version 1. The size and rhythm of records shows when a reply is
streaming and roughly how long it is.

### Reconnecting

- **Streams.** Either side reconnects with `Last-Event-ID`. The relay sends the records it still
  holds after that id, or all it holds when it does not know the id. Duplicates fall to the
  counter rule.
- **pic.** Reconnects after 1 second, doubling to 60, each wait varied by a fifth either way; a
  connection that lasted 30 seconds resets the wait. It reconnects at least every 15 minutes. A
  record that has waited 30 seconds to be posted is dropped unsent, which the phone sees as a gap.
- **The phone.** The same schedule capped at 30 seconds instead of 60, and the 45-second idle
  timeout of section 6. It retries at once, resetting the wait, when the page becomes visible,
  when the browser reports `online`, on `pageshow` from the page cache, and when its once-a-second
  timer fires more than 5 seconds late (the phone slept); then an open stream silent for 20
  seconds is replaced rather than trusted, and it sends `ping`. It also sends `ping` whenever a
  stream reopens and when pic's `peer` comes back, so a lost record shows as a gap in the `pong`'s
  counter at once. A page that was hidden for more than 30 seconds, or that sees a reset, or no
  `pong` for 150 seconds, starts a new session.
- **Acknowledging.** A reader names the last event id it read in `Pic-Ack` (section 6) on its
  next request, and the relay forgets what it names. A lane holds 1 MiB at most, so a reader that
  has read 256 KiB or 128 records it has not named yet names them at once, with a request of its
  own: pic with `GET /v1/m/M/c`, the phone with a `POST` of no records. pic also does so for
  anything it read 5 seconds ago and has not named. Without this a message over 1 MiB waits on
  the relay's 60 seconds.
- **After any gap or new session,** the phone sends `sync` with its cursor (section 4) and
  repeats the commands it has no answer for. That is the whole of resumption: the journal's `seq`
  for what flows down, idempotency keys for what flows up.

## 4. The envelope

An envelope message is one JSON object with up to five members:

| Member | Meaning |
|---|---|
| `type` | what this is, from the tables below |
| `session` | a conversation: `W/C`, the workspace's id (`picu_workspace.journal`) and the conversation's id; `+W` for a conversation not yet made |
| `seq` | a position in that workspace's journal: `pic_entry.seq` |
| `key` | a command's idempotency key: 16 to 43 characters of `[A-Za-z0-9_-]`, 16 random bytes as `b64u` by default |
| `payload` | a Pi RPC command, response or event, unchanged, or the type's own object |

Pi's commands and events are carried as they are ([RPC commands](../reference/rpc-commands.md),
[events](../reference/events.md)); the envelope adds addressing and nothing else. Members a
receiver does not know are ignored; a `type` it does not know is answered with
`{"type":"error","payload":{"code":"unknown_type"}}`.

### Up: phone to pic

| `type` | Members | Meaning |
|---|---|---|
| `sessions` | `payload` optional | send the list of conversations, and again when it changes; with `{"workspace":W}`, once, every conversation of that workspace |
| `sync` | `session`, `seq`, `key` | follow this conversation from after `seq`; -1: from the start of its latest request. `key` names this follow (below) |
| `fetch` | `session`, `payload` | `{"after":A,"to":B}`: the events in `(A, B]`; `{"before":X,"limit":N}`: the `N` entries before `X` |
| `command` | `session`, `key`, `payload` | a Pi RPC command |
| `presence` | `payload` | `{"visible":true}` or `false` |
| `push` | `payload` | `{"subscription":{...},"notify":"all"\|"remote"}` or `{"subscription":null}` (section 5) |
| `image` | `session`, `seq`, `payload` | `{"index":I}`: the bytes of image `I` of the person's message at entry `seq` (below) |
| `ping`, `unpair`, `pair_ready` | | |

### Down: pic to phone

| `type` | Members | Meaning |
|---|---|---|
| `sessions` | `payload` | `{"sessions":[{"session","name","workspace","lastMs","running","seq","title","preview","state"}],"workspaces":[{"id","workspace"}],"unavailable":[{"workspace","reason"}],"features":["images"]}`; to a `sessions` with a workspace, `{"workspace":W,"sessions":[...]}`. `title`, `preview` and `state` are optional (below) |
| `event` | `session`, `seq`, `key`, `origin`, `payload` | a Pi event rebuilt from committed rows |
| `sync` | `session`, `seq`, `key`, `payload` | a mark: the phone has everything through `seq`; `{"running":BOOL}` |
| `fetch` | `session`, `seq`, `payload` | the end of a `fetch`: `{"done":true}` |
| `live` | `session`, `seq`, `payload` | the reply being streamed, as one value (below) |
| `ack` | `key`, `session` for `+W`, `payload` | the command is committed: `{"state":"pending"}` |
| `response` | `key`, `session` for `+W`, `payload` | the Pi RPC response line |
| `error` | `key` if it answers a command, `payload` | `{"code","message"}` |
| `image` | `session`, `seq`, `payload` | `{"index","mimeType","data"}`, or `{"index","error"}`: `no_image`, `removed` (pruned), `too_large` |
| `pong`, `paired`, `unpaired`, `bye` | | |

A conversation in `sessions` carries what tells it apart, the same as the terminal's `/resume` and
`pic sessions` show:

- `title`: its name, else the first line of its first prompt (of the conversation it was forked
  from, when it has none of its own), at most 60 characters; absent when there is neither.
- `preview`: the first line of its last message along its path, a reply's text else a prompt, at
  most 120 characters; absent when it has none. Lines are cut as a notification's `B` is.
- `state`: `running` while a request is admitted; `attention` when its last request failed (not
  stopped by the person) or reached the request cap; else `idle`. `running` stays, and wins: a
  mark's `running` is newer than the list.

A page shows `title`, else `name`, else "Untitled", so an older pic is still understood; an older
page ignores the three.

### Following and catching up

A phone is a replica of one conversation at a time, and its **cursor** is the `seq` of the last
mark it received.

- On `sync`, pic follows the conversation as `pic attach --from SEQ` does: the same pass over
  committed rows (`src/attach.c`), run when the journal's `data_version` changes, with a sink in
  place of stdout. A new `sync` replaces the one before.
- Each pass sends its events in order, each with the `seq` of the entry it came from, then one
  mark with the highest `seq` the pass read and whether a request is running. The first mark
  answers the `sync` even when the pass had no events.
- The phone shows events as they come and moves its cursor only at a mark. After a gap it drops
  what it holds past the cursor and sends `sync` from the cursor. Events are never applied twice
  and none is missed, because a pass is one read transaction and a mark closes it.
- **The sync's key.** A `sync` carries `key`, an opaque string of 16 to 43 characters of
  `[A-Za-z0-9_-]` the phone makes new for each `sync`. pic copies it, unchanged, into every
  `event` and mark it sends for that follow, through later passes, until a new `sync` replaces it.
  The phone drops an `event` or mark whose `key` is not its latest. Without it, the tail of a
  pass that was under way when the phone sent a new `sync` (after a gap) reaches the phone after
  it dropped its tentative events, and the new pass sends the same events again: they would apply
  twice. A message with no `key` is accepted, for a pic that does not copy it.
- **Origin.** An `event` rebuilt from a row a phone caused (its prompt's admission, its steer or
  follow-up) carries `origin` `remote:DEVICE`, the device id as `b64u`, as on the row's sender.
  Every other `event` that comes from a person's message carries `origin` `local`; events with no
  sender of their own (the assistant's, tools') need none. The page shows the user's messages in
  one timeline marked "this phone", "another phone" or "the terminal".
- **A request's end.** `agent_end` has no entry of its own: it carries the `seq` of its request's
  last entry. A request stopped before anything after its prompt was committed ends at a `seq` a
  mark has already closed, so the phone applies an `agent_end` at its cursor, once; any other
  event at or before the cursor is dropped as applied.
- `fetch` is for scrolling back and is answered once, without following.
- An event larger than 256 KiB is sent as `{"type":"elided","eventType":T,"bytes":N}` in the
  payload; `fetch` with `"full":true` returns it whole, up to the message limit.

What is rebuilt is what `pic attach` rebuilds today ([the inbox](../dev/inbox.md)): `agent_start`,
`message_start` and `message_end`, `tool_execution_start` and `tool_execution_end`, `agent_end`.
Anything `pic attach` learns to rebuild, the phone gets with no change here.

### The reply as it streams

Streamed text is not journaled. From the landing that adds it (section 10), the pic running a
request publishes its `message_update` lines as grapevine's stage 3 describes, and `pic remote`
folds them into one value per conversation, in memory: the partial reply so far.

    {"type":"live","session":S,"seq":N,"payload":{"rev":R,"offset":K,"text":T}}

`seq` is the last committed entry the text comes after, `rev` goes up with every value sent, and
`text` is the reply's text from character `K` on (pic keeps the last 8 KiB). The phone keeps the
value with the highest `rev` and discards it when an event with a greater `seq` arrives. A value
replaces the one before; it is never appended to. pic sends at most one every 250 ms per phone and
never queues one behind another: when a post finishes it sends the newest value or nothing. A lost
`live` message is never repaired. It promises nothing, as in grapevine.

The page also refuses a value whose `seq` is behind an event it has already applied, drops the
value when a mark says nothing is running, and forgets it, with the `rev` it had reached, when a
new session starts (a restarted `pic remote` counts `rev` from the start again). It shows the
value after the committed events, as one item, with a leading ellipsis when `offset` is not 0;
the committed message that follows replaces it, so the text is never shown twice.

### Images

`features` in `sessions` lists what pic carries beyond this note's first version; `images` means
the rest of this section. A pic without it answers a prompt with images `not_available`, and the
page offers no images.

- **Up.** A `prompt` carries Pi's `images`, `[{"type":"image","data":BASE64,"mimeType":T}]`,
  with or without text. The page shrinks each image before it is sealed: the long side to 1568
  pixels, JPEG unless it was already a small PNG, JPEG, GIF or WebP; at most 8 a message, and
  3.5 MiB of base64 in all, so the command stays under the 4 MiB message. pic checks them as it
  checks a pasted image (what the bytes are, 8000 pixels a side, the 4.5 MB limit) and answers
  `bad_command` naming the image; a prompt it admits keeps them as the terminal keeps pasted
  ones, and a steer or follow-up takes them through the inbox.
- **Retries.** A command is repeated every 5 seconds once for each 256 KiB it holds (a minute at
  most), and not while its records are still queued to go. A gap inside it discards it whole;
  the repeat sends it whole again, under its key, and a key pic knows is not admitted twice.
- **Down.** An event with a person's message names its images and carries none of their bytes:
  each image part is `{"type":"image","mimeType","index","bytes"}`, `index` its place among the
  message's images. The phone asks for an image with `image` when it shows it, one at a time,
  again on a new session or after 20 seconds and a second per 64 KiB, three times. pic answers
  from the journal, any image of any message the phone could follow, pasted at the terminal or
  sent from a phone. One whose base64 would not fit a message is `too_large`.

The relay sees records as it sees any others: an image is a run of full ones.

### Commands, keys and exactly once

Every command that changes anything is a committed journal row before `pic remote` answers it:

- The row's key is `rc:DEVICE:KEY`, with the device id as `b64u`, and its sender is
  `remote:DEVICE`. One phone cannot reuse or collide with another's keys.
- `steer`, `follow_up` and `abort` go through `pic_inbox_accept`, unchanged. pic answers `ack`
  once the row is committed, and `response` with the row's response line when it leaves
  `pending`.
- `prompt` with nothing running is a keyed admission: what `pic submit KEY TEXT --session ID`
  does, followed by `pic run --session ID`, in one detached child in a session of its own
  (`setsid`), as `pic attach -i` starts a request today. A second admission with the key reports
  the first. `prompt` while a request runs follows Pi: with `streamingBehavior` it is the steer
  or follow-up above, without it the response is Pi's error.
- A known key with the same command returns the same `ack` or `response` again and changes
  nothing. The same key with another command is refused, as the inbox does.
- The phone repeats a command with its key every 5 seconds, and at the start of each new session,
  until it has an `ack` or a `response` for the key. It keeps asking for a `response` it lacks
  the same way.
- **Order.** The phone sends a command to a conversation only once every earlier command it made
  for that conversation has an `ack` or an answer, except `abort`, which never waits. So commands
  arrive in the order typed, even when a lost record is resent after a later one would have gone.
- **Offline.** A command made while there is no session is kept in IndexedDB (`pic-rc`, store
  `outbox`: the key, the device, `session`, `payload` and when it was made) and sent with its key
  when a session opens, after a reload too. It is deleted on its `response` or `error`. One that
  waited longer than the inbox would keep it (10 minutes for a steer or a stop, a day for anything
  else) is not sent and is shown as not delivered.
- **What the page sends for typed text.** `prompt` with `streamingBehavior` `steer` when the
  conversation was running as it was typed, `followUp` otherwise, so the command is still right if
  the request ended, or another started, before it arrived.
- **A new conversation.** `command` with `session` `+W` (`W` from the `workspaces` list) and a
  `prompt`. pic makes the conversation and puts its `W/C` in the `session` member of the `ack` and
  the `response` (and may repeat it as the response's `data.session`); a repeat of the key names
  the same conversation and makes no second one. The new conversation appears in the next
  `sessions`. Resuming a conversation is a `prompt` to its `W/C`: no message of its own.

So a command that was acknowledged is delivered once or reported as not delivered, whatever the
network, the relay, `pic remote` or the phone did in between: the promise of
[durability](../dev/durability.md), unchanged. Expiry is the inbox's: 10 minutes for a steer or an
abort, a day for a follow-up.

### Which commands, and what "the same as local" means

| Commands | How | From landing |
|---|---|---|
| `get_state`, `get_messages`, `get_entries`, `get_tree`, `get_session_stats`, `get_last_assistant_text`, `get_fork_messages`, `get_commands`, `get_available_models`, `get_available_thinking_levels` | answered from the journal through the narrow open; no row | 1: the first two; 2: the rest |
| `steer`, `follow_up`, `abort` | the inbox | 1 |
| `prompt` | keyed admission, or the inbox while a request runs; `images` as above | 1; with `images`, 4 |
| `new_session` then `prompt` | `prompt` with `session` `+W`; the response names the conversation | 2 |
| `clear_queue`, `set_model`, `cycle_model`, `set_thinking_level`, `cycle_thinking_level`, `set_steering_mode`, `set_follow_up_mode`, `set_session_name`, `set_auto_compaction`, `set_auto_retry`, `abort_retry`, `compact`, `bash`, `abort_bash`, `fork`, `clone`, `rewind` | the inbox, each added there as grapevine adds commands | 2 and later |
| `switch_session` | not carried: the envelope's `session` selects the conversation | |
| `export_html`, `extension_ui_response`, `login`, `logout`, `get_auth_status` | not carried; answered `not_available` | |

A paired phone has the permissions of the person at the terminal. Exactly:

1. There are no roles, no read-only devices and no per-device list of commands or conversations.
   A paired phone sees every conversation of every workspace this user's pic knows, and may send
   any carried command to any of them.
2. A prompt from the phone starts a request whose tools run as the user, in that conversation's
   workspace, with no approval step that a local prompt would not have. Through `bash`, in a tool
   or as the command, that is a shell as the user: a paired phone can read and change anything
   the user can, including `~/.pic`.
3. Its text is the user's own. It is not framed as a peer's message, and the limits grapevine puts
   on peers (hops, wakes, no waking an idle conversation) do not apply to it.
4. Hooks run as they do locally and may refuse. They see `origin` `remote:DEVICE`, so a policy
   stricter than this note's is a hook, not a setting here.
5. It is recorded: the sender is on the inbox row or the request, so the journal says which device
   asked for what.
6. What it cannot do is what is not carried: sign in or out of a provider, pair or unpair another
   device, change settings files, or take a conversation's lease.

## 5. Web Push

A notification is sent by `pic remote`, straight to the phone's push service, when a request ends
in a conversation the phone could see. The relay has no part in it and learns nothing of it.

### Subscribing

The page subscribes with `pushManager.subscribe({userVisibleOnly: true, applicationServerKey})`,
the key being pic's VAPID public key from pairing, and sends the result up in `push`: the
`endpoint`, and `keys.p256dh` (65 bytes) and `keys.auth` (16 bytes) as `b64u`. pic checks the
endpoint (`https`, port 443, a host name, not an address) and seals it into the device's row. At
the start of every session the page compares `pushManager.getSubscription()` with what it last
sent and sends `push` again when they differ; `pushsubscriptionchange` is not relied on.

`notify` is this device's choice, made on the phone: `all` (the default when absent), every
request that ends, or `remote`, only those a phone started or steered. pic seals it into the
device's row with the subscription and sends to a device only what both its `notify` and the
setting `remote.notify` allow. `{"subscription":null}` turns the device's notifications off.

The page keeps one service worker registration for each paired computer, at scope
`/push/DEVICE/` (the pairing's device id), because a subscription belongs to one VAPID key and
each computer has its own. The registration's scope also tells the service worker which computer a
push came from, so the plaintext carries nothing about it. The browser decrypts the push (RFC
8291) with keys it made for the subscription and hands the service worker the plaintext: no page
or worker code decrypts, which is why vector 5 is checked by decrypting as a browser would. The
page asks for permission only from a tap, and on iOS and iPadOS offers notifications only in the
installed page. It sends `presence` at the start of every session as well as when it is hidden or
shown.

A subscription ends when the push service says so: a 404 or 410 (RFC 8030 section 7.3) removes it
from the row, as do three refusals in a row with 400 or 403. Unpairing removes it with the row. A
new VAPID key (after a reset) invalidates every subscription, which is why reset unpairs
everything.

On iOS and iPadOS, push works only from 16.4, only for a page added to the Home Screen (a manifest
with `"display":"standalone"`), and only after permission was asked for from a tap inside that
installed page. The installed page has storage of its own, apart from Safari's, so a pairing made
in a Safari tab is not there: the phone pairs inside the installed page. The camera opens a
scanned address in Safari, so on iOS the Safari page offers "Copy pairing link" and the installed
page offers "Paste"; the offer's ten minutes cover it. Every push must show a notification, so
pic sends none it means to be silent. Safari also clears the storage of a site not on the Home
Screen after seven days without a visit, which unpairs a phone that only used a tab.

### The request

One `POST` to the endpoint, with `pic_http_post`:

    TTL: 3600
    Urgency: normal
    Topic: b64u(trunc16(HMAC(auth, "pic-rc/1 topic" || 0x00 || session)))
    Content-Encoding: aes128gcm
    Authorization: vapid t=JWT, k=b64u(VAPID public)

`Topic` (RFC 8030 section 5.4) lets a newer notification for a conversation replace an undelivered
older one, and tells the push service nothing about which conversation it is.

**VAPID** (RFC 8292). The token is a JWT (RFC 7519) signed with ES256 (RFC 7518 section 3.4): the
header is exactly `{"typ":"JWT","alg":"ES256"}`, the claims are `aud` (the endpoint's origin),
`exp` (12 hours ahead, as RFC 8292 section 2 allows up to 24) and `sub` (the relay's origin, an
`https:` address; never a mail address). The signature is the 64 bytes `r || s`, from
`br_ecdsa_i31_sign_raw`, which derives its nonce by RFC 6979 and so needs no randomness and gives
the same token for the same input.

**Encryption** (RFC 8291, with the `aes128gcm` coding of RFC 8188). For each push pic makes a new
P-256 key pair and a 16-byte salt, and computes, in RFC 8291 section 3.4's names:

    ecdh_secret = DH(as_private, ua_public)
    IKM   = HMAC(HMAC(auth_secret, ecdh_secret), "WebPush: info" || 0x00 || ua_public || as_public || 0x01)
    PRK   = HMAC(salt, IKM)
    CEK   = HMAC(PRK, "Content-Encoding: aes128gcm" || 0x00 || 0x01)[0..16]
    NONCE = HMAC(PRK, "Content-Encoding: nonce" || 0x00 || 0x01)[0..12]
    body  = salt (16) || 0x00001000 || 0x41 || as_public (65) || AES-128-GCM(CEK, NONCE, plaintext || 0x02)

One record, no padding beyond the delimiter. The plaintext is at most 3993 bytes; pic's is far
smaller.

### One line

The plaintext is `{"v":1,"title":T,"body":B,"session":S,"seq":N}`.

- `T` is the conversation's name, or else the last part of the workspace's path; at most 60
  characters.
- `B` is the first line that is not empty of the text of the request's last reply, with runs of
  white space made one space and control characters removed, cut to 200 characters with an
  ellipsis. When the request ended with no reply text, it is how it ended: "Stopped", "Failed:"
  and the error's first line, or "Reached the request cap".
- Nothing else is ever in a notification: no prompt, no tool input or output, no path beyond `T`.

The push service cannot read it. The phone's lock screen shows it, which is the point.

### When

For each request that `pic remote` sees end while it is following (it never sends for one that
ended before it started, so a restart repeats nothing), and for each device with a subscription,
unless that device has a confirmed session whose last `presence` was visible. At most one per
conversation every 30 seconds. A push is sent once and never retried: it is a hint, and the page
catches up from the journal whatever happened to it. The setting `remote.notify` is `all` (the
default), `remote` (only requests a phone started or steered) or `off`.

The page's service worker shows the notification with `tag` set to the device id and the
conversation, and a tap opens the page at that conversation on that computer
(`/#s=SESSION&c=DEVICE`, or a message to a page already open), where a normal session and `sync`
begin.

## 6. The relay

One Worker, in the repository `pic-relay`, on the owner's Cloudflare account. It serves the page's
files and the API below. Each mailbox is one Durable Object, addressed by the mailbox id.

### Endpoints

Ids in paths are `b64u`. "Owner" means the bearer token hashes to the mailbox id; "channel" means
it hashes to the channel id and the channel is registered in the mailbox. Both are checked on
every request.

| Request | Who | Does |
|---|---|---|
| `PUT /v1/m/M` | owner | makes the mailbox, or marks it used |
| `DELETE /v1/m/M` | owner | deletes it and its channels |
| `GET /v1/m/M/c` | owner | lists channels: `[{"id","kind","expires"}]` |
| `PUT /v1/m/M/c/C` | owner | registers a channel: `{"kind":"device"}` or `{"kind":"pair","ttl":SECONDS}` |
| `DELETE /v1/m/M/c/C` | owner | removes it; its readers get `event: gone` |
| `GET /v1/m/M/up` | owner | stream: the `up` lanes of all device channels |
| `GET /v1/m/M/c/C/up` | owner | stream: the `up` lane of one pairing channel |
| `POST /v1/m/M/c/C/down` | owner | records for the phone |
| `GET /v1/m/M/c/C/down` | channel | stream: the `down` lane |
| `POST /v1/m/M/c/C/up` | channel | records for pic |
| `GET /`, and the page's files | anyone | the page, its service worker and manifest |

A `POST` answers 204 with `Pic-Peer: 1` or `0`: whether the lane's reader is connected, so the
page can say "pic remote is not running on your computer" instead of waiting. A `POST` with no
records only acknowledges (its `Pic-Ack`) and counts as a request. Errors are a status
and `{"error":CODE}`: 401 (a token that does not hash to the id), 404 (no such mailbox or
channel; to a phone, the relay's unauthenticated word that the pairing is gone, never by itself
a reason to forget it), 413, 429 with `Retry-After`.

A stream sends `event: frame` (section 3), `event: peer` when the other side connects or leaves,
`event: replaced` to a reader another connection took the lane from (a lane has one reader),
`event: gone`, and a comment line (`:`) as its first bytes, the moment it opens, and every 15
seconds after, on every stream: pic's mailbox stream, a phone's lane, and both lanes of a pairing
channel. The relay may end any
stream at any time.

On a phone's `down` lane, a `peer` of `0` is followed by `event: seen` with `data:` the Unix time
in milliseconds pic was last seen: when its mailbox stream last closed, or, if it has not read it
since the mailbox's object started, the last time it opened that stream (kept in the mailbox
record) or else last used the mailbox. It is sent when the phone connects while pic is away and
when pic leaves. pic's own streams carry no `seen`.

**The idle timeout.** Every stream carries at least a comment every 15 seconds, so a reader that
has received nothing at all, not even a comment, for 45 seconds treats the stream as dead: it
aborts it and reconnects with `Last-Event-ID` (section 3). Both pic and the page do this.

The API sends no CORS headers: the page is same-origin and pic is not a browser. The page is
served with `Content-Security-Policy: default-src 'none'; script-src 'self'; style-src 'self';
img-src 'self' data:; connect-src 'self'; manifest-src 'self'; worker-src 'self'; base-uri 'none';
form-action 'none'; frame-ancestors 'none'`, `Referrer-Policy: no-referrer` and
`Cross-Origin-Opener-Policy: same-origin`, loads nothing from any other origin, and ships no
cryptographic code: it calls `crypto.subtle` and nothing else.

### Retention

A record is held in the Durable Object's memory, never in its storage, until the lane's reader
has acknowledged it (a later `Last-Event-ID`, or `Pic-Ack: N` on any of its requests) or it is 60
seconds old, whichever comes first. An object that is evicted loses what it held, which the
endpoints see as a gap. Storage holds only the mailbox's record: when it was made and last used,
and its channels with their kinds and expiry times. A mailbox whose owner has not connected for 90
days is deleted.

### Limits

| What | Limit |
|---|---|
| a record | 16417 bytes |
| a `POST` | 32 records, 256 KiB |
| a lane's held records | 256, or 1 MiB; over it the writer gets 429 |
| a channel, per direction | 120 requests and 8 MiB a minute |
| a mailbox | 8 device channels and 1 pairing channel |
| a pairing channel | 900 seconds, 16 records, 64 KiB |
| streams | 1 reader a lane; 6 connections a minute a lane |
| new mailboxes | 10 an hour from one address; a global daily cap set in the Worker's configuration |

Creating a mailbox takes the `Pic-Invite` header, a secret in the Worker's configuration, until
registration is opened (open question 1); pic sends the setting `remote.invite`.

### Abuse

Nothing can be stored for longer than a minute or read by anyone without a token, so the relay is
of little use as a drop. Channels cannot be made without the owner token, so a phone cannot widen
its own access. A token that fails is answered 401 with no detail, and failures count against the
address's rate. The Worker has no outbound requests at all: it fetches nothing on anyone's
behalf.

### Logs

The Worker logs, per request: the time, the route's pattern (never an id), the status, the byte
count and an error code. It does not log ids, tokens, addresses, user agents or bodies, and
Workers Logs' own capture of request headers is off. Counters (requests, bytes, open streams,
refusals by code) are kept in aggregate. What Cloudflare records as the platform is outside this
note and inside the threat model.

### Cost

A stream keeps its Durable Object in memory, and `pic remote` holds one open as long as it runs,
so a mailbox costs duration for as long as its owner's `pic remote` is up: about 0.125 GB-seconds
a second. That is the price of SSE over a hibernating WebSocket and was accepted with the
transport; the figure is to be measured in the first landing.

## 7. `pic remote`

`pic remote` runs in the foreground until it is stopped. It is the only process that talks to the
relay outside pairing.

### Start

1. Takes `~/.pic/remote.lock` exclusively (`flock`, through `pic_platform`, as a lease is taken).
   A second `pic remote` says one is running and exits. The kernel drops the lock when the process
   dies; the file is never removed.
2. Asks for the credential store's passphrase on the terminal, every time: it does not take a key
   handed down by a parent (`PIC_KEY_FD`), and with no terminal it exits with a message.
3. Opens the keys and the device rows. With no device paired it says so, names `/rc`, and waits
   for one.
4. Reconciles the relay with the table: `PUT` the mailbox, list its channels, register every
   device's channel, delete every device channel that has no row.
5. Opens the mailbox stream and prints one line: the relay, how many devices, how many
   workspaces.

### Running

- **One loop, one extra thread.** A thread reads the stream and writes whole records to a pipe;
  like the inbox's watcher it never touches SQLite. The loop waits on that pipe and a 100 ms tick,
  as `pic attach` does.
- **Devices.** It polls the user database's `PRAGMA data_version` each second. A new row (paired
  in `/rc` meanwhile) is served from then on; a deleted row ends that device's sessions.
- **Workspaces.** The conversations a phone can see are those of every `picu_workspace` row whose
  path still holds that journal, opened with `pic_open_narrow`: the user's own file, this build's
  schema, no recovery, no migration. A journal the narrow open refuses is listed as unavailable
  with its reason. `sessions` lists the 50 most recently active conversations across them.
- **Following.** One read connection per journal that has a followed conversation, and the
  `pic attach` pass per followed conversation, each pass one read transaction whose output is
  queued and sent after the transaction ends, so a slow phone never pins a WAL.
- **Commands.** Section 4: a row through `pic_inbox_accept`, or a keyed admission in a child. A
  child gets the unlocked master key over the pipe `pic_cred_handoff` makes, as the terminal's
  children do, and is in a session of its own, so it outlives `pic remote`.
- **Several phones.** Each has its channel, its sessions and its followed conversation. They
  share nothing but the journal.
- **Sending.** One post in flight per channel; records queue behind it and go out together. A
  `live` value never queues.

It never takes a lease, never opens a journal other than narrowly, never listens on any socket,
and writes nothing to a journal but inbox rows.

### Stopping and dying

`SIGINT` and `SIGTERM` send `bye` to each session and exit. `SIGKILL`, a crash or a power cut
leave:

| What | After |
|---|---|
| commands that were acknowledged | committed rows; delivered by whoever runs the conversation |
| a request it started | running in its own process; unaffected |
| a command received and not yet committed | never acknowledged; the phone sends it again |
| sessions, cursors, the live text | gone; the phone starts a session and sends `sync` |
| a push not yet sent | not sent |
| the lock | released by the kernel |

There is nothing to recover and no file to clean. Starting it again is the whole repair.

`/rc` shows whether a `pic remote` is running, by trying the lock for an instant, next to the
devices and the pairing code.

## 8. Test vectors

Both implementations must reproduce, byte for byte, one file of vectors:
`test/pic/remote-vectors.json` in pic, the canonical copy, and `test/vectors/remote-v1.json` in
`pic-relay`, byte-identical. Each
repository's tests check the file's SHA-256 against a constant, so the copies cannot drift without
a test failing in the repository that changed. A change to the vectors lands in pic first and
carries the new hash in its changelog line.

The file is made by a third implementation, `tools/remote-vectors.js` (Node's built-in `crypto`
only, about 150 lines, kept in both repositories beside the file), so that neither product
implementation is its own reference. It exists, and its handshake, transport keys and VAPID
signature have been reproduced with the vendored BearSSL; it also reproduces RFC 8291's own
example. The first file's SHA-256 is
`fa895483624944e6f7e36b690bc3344a19e6755c270d49d10c4a876869e0e4ab`.

All private keys in it are counting bytes, 32 from the given first byte:

| Input | Value |
|---|---|
| pic static private | `01`..`20` |
| phone static private | `21`..`40` |
| pairing ephemerals: phone, pic | `41`..`60`, `61`..`80` |
| session ephemerals: phone, pic | `81`..`a0`, `a1`..`c0` |
| pairing secret | `c1`..`e0` |
| owner token, channel token | `10`..`2f`, `30`..`4f` |
| VAPID private | `51`..`70` |
| push: phone private, auth secret, pic's ephemeral private, salt | `71`..`90`, `00`..`0f`, `91`..`b0`, `f0`..`ff` |

What each side must produce from them:

1. **Derivations.** The mailbox id `09060344e6cc9b82378e25518284a1cf`, the `psk`, the pairing
   token and channel, the device channel `17ad112a3b7c0e38e0c245aa466c607d`, and the offer's 122
   bytes and its address for `expires` 1800000000.
2. **The pairing handshake**, session id `0102030405060708`, with the two payloads given as exact
   bytes: both records, the handshake hash
   `d9941f270bb65ba3791e4c250514644f47fd26395f9052d44cd9d8c937d65a93`, the code `333054`, both
   transport keys, and the first transport record each way (`pair_ready`, `paired`).
3. **The session handshake**, session id `1112131415161718`: both records, the hash
   `cb4a1cc231d2e46aab6a622d17cf5c24ab87244af781aa699508e1926c3f42a6`, both keys, the transport
   records with `n` 0 each way and `n` 7 down, a 20000-byte message as two records (`n` 1 and 2
   up, given by their SHA-256), and a reset record.
4. **VAPID.** The token for the exact header and claims bytes in the file. pic must produce the
   signature itself, since RFC 6979 makes it unique; the page never signs, and `pic-relay`'s test
   verifies it.
5. **Push.** The body for the file's plaintext, keys and salt, the `Topic` value, and the body of
   RFC 8291 appendix A from that appendix's inputs.

Each implementation also has, as tests of its own with these keys: every initiator vector read by
its responder and the reverse (so both roles exist on both sides, the unused one in tests only);
and the refusals: a record with one bit changed anywhere, a replayed `n`, a message 1 with the
wrong `psk`, with a public key not on the curve, with an unknown static key, and with the right
key on the wrong channel. Each must be dropped with no state changed.

## 9. Threats, and what an outside reviewer checks

### Who can do what

| Attacker | Can | Cannot |
|---|---|---|
| **the relay**, malicious or compromised, as a message carrier | drop, delay, reorder or replay records, which ends in a gap, a dropped record or a new handshake; refuse service; see the metadata of section 3; learn when you work and roughly how much the model writes | read or change a command, an event or a notification; pair a device; pass as pic or as a phone; cause a command to run twice, or one the phone did not send |
| **a network attacker** | what TLS allows a network attacker, and then at most what the relay can | the same |
| **a leaked QR code**, within its ten minutes and before the owner's phone used it | start a pairing, which shows the attacker's name and a code on the terminal that the owner's phone is not showing | pair without a yes at the terminal; do anything once the offer is used or over; learn anything about later sessions |
| **a leaked QR code**, later | learn pic's static public key and mailbox id, and so tell that a mailbox exists | anything else: the secret is spent, the pairing channel deleted |
| **a stolen phone, locked** | read notification lines on the lock screen, as the owner chose | open the page |
| **a stolen phone, unlocked** | everything the owner can, until it is unpaired at the terminal | take the static key elsewhere: it is not extractable, so unpairing that one device ends it; reach anything while `pic remote` is not running |
| **the page host**, malicious or compromised (a changed page, a taken-over Cloudflare account or domain) | serve script that, on each phone that loads it, reads what is on screen and sends commands as that phone, for as long as it is served: full control of every paired pic that has `pic remote` running | export a phone's static key, so the control ends when the page is honest again; pair a new device; reach a pic whose `pic remote` is not running |
| **the push service** | see that a notification was sent, its size and time, and pic's address and VAPID public key; drop it | read it or forge one the phone's browser accepts |
| **another user on the machine** | nothing: `~/.pic` is 0700 | |
| **the same user's other processes** | anything pic can, as before | add a device without the passphrase, short of the above |

The page host is the weak point of any design that runs in a browser, and this one does not hide
it: the relay is blind to the data it carries, but the code that sees the data is served from the
same place. A browser cannot check that code against anything. What limits the damage is that the
key cannot leave, pairing needs the terminal, the page loads nothing from a third party, and
nothing works unless the user has chosen to run `pic remote`. The ssh transport of stage 1 has no
page and no relay and stays for anyone who will not take this trade.

Not defended: a compromised machine running pic; a user who answers yes to a code they did not
check; traffic analysis; denial of service by the relay or the network.

### The review

The cryptography is standard pieces in a named arrangement, and the arrangement is ours. Before
registration is opened to anyone but the owner, someone outside the project reviews:

1. The P-256 DH definition against Noise 4.1 and 14: point validation, the encoding, the X
   coordinate as the output, and that nothing depends on `DHLEN` being one number.
2. `IKpsk1` and `IK` as used: the payload properties of 7.7 against what each message carries,
   that pic sends and acts on nothing before a session is confirmed, and that a replayed message 1
   gains nothing in either protocol.
3. The explicit counter (11.4): strictly increasing, never reused, never persisted, the 2^32 and
   24-hour ends, and that the unauthenticated head (type, session id, counter) and the reset
   record give an attacker nothing beyond a dropped session.
4. Pairing: the derivations from `ps`, that the relay's token reveals nothing of `psk`, the offer's
   single use and failure count, the six digits against an attacker who races the owner's phone,
   and the order of the row, the channel and `paired`.
5. The page: that the static key is not extractable and has only `deriveBits`, that the fragment
   is cleared before any request, the content security policy, the absence of third-party code,
   and what the session keys in script memory expose.
6. The relay: that it stores nothing durable but routing, token checks in constant time, the
   limits, and the logs.
7. Web Push: VAPID's claims and lifetime, RFC 8291's key schedule, a new key pair and salt for
   every push, the endpoint check, and the one-line rule against what can reach a lock screen.
8. pic: sealing of keys and device rows, the passphrase at every start, the key handed to
   children, and that every command path commits before it answers.
9. Both implementations against the vectors and the refusals of section 8, and the parsers (the
   record, the envelope, the stream) under a fuzzer.

## 10. Landings

Each landing is one change in each repository, tested alone against the vectors and together by
the end-to-end test.

**The end-to-end test** lives in `pic-relay`: the Worker under `wrangler dev`, the page's protocol
module (no DOM in it) driven from Node, and a real `pic` (named by `PIC`) with the scripted
provider and a private `HOME`. pic's own suite needs no Worker: `test/pic/remote.sh` runs
`pic remote` against a small loopback relay in the test harness that implements section 6 without
limits, with the dev build's initiator playing the phone.

### 1. Pair, follow, prompt

The smallest thing that is useful: start a request from the phone, watch it, steer it, stop it.

- **pic.** The two tables; the Noise module over BearSSL, both roles, passing vectors 1 to 3;
  pairing in `/rc` (the offer, the QR code, the code on screen, yes or no, the device list,
  unpair, reset); `pic remote` (lock, passphrase, reconcile, stream and post, sessions, backoff);
  `sessions`, `sync`, `event`, marks, `ping`; `get_state` and `get_messages`; `steer`,
  `follow_up` and `abort` through the inbox; `prompt` by keyed admission. Crash tests: `pic
  remote` killed before and after a command's commit delivers once; killed mid-follow, a new
  session with the old cursor shows no gap and no repeat.
- **`pic-relay`.** The Worker and Durable Object with every endpoint, limit and the invite; the
  page: open an offer, pair, show the code, list conversations, follow one (messages, tool calls
  and their results, how a request ended), a box to type in (a prompt when idle, a steer while
  running) and a stop button; reconnecting, cursors and command retries; vectors 1 to 3 on
  WebCrypto in a real browser engine.
- Left out: text as it streams, push, images, any other command, installing to the Home Screen.

### 2. Streaming text and the rest of the commands

- **pic.** The `live` value (with grapevine's stage 3 publishing the text locally); `fetch` and
  elision; a new conversation from the phone; the model, thinking, queue, name and compaction
  commands as the inbox gains them; the remaining queries.
- **`pic-relay`.** The streamed reply, scrolling back, a conversation picker with new
  conversation, model and thinking controls.

### 3. Notifications

- **pic.** VAPID and RFC 8291 (vectors 4 and 5), the `push` and `presence` messages, the one-line
  rule, `remote.notify`.
- **`pic-relay`.** The manifest, the service worker, the permission prompt, the Home Screen flow
  on iOS with pairing by copied link, a mute switch per device.

### 4. After

Images in a prompt and in the conversation (section 4, "Images"); `bash`, `fork`, `clone` and
`rewind`, padding of record lengths, and, after the review of section 9, opening registration.

## Open questions

1. **Who may use the relay?** It starts closed, behind an invite secret. Opening it to every pic
   user makes the owner's Cloudflare account pay for each running `pic remote` and makes the page
   host a target worth attacking. Open it after the review, keep it closed and document running
   your own, or both?
2. **The relay's name.** Pairings are tied to the page's origin: moving it later unpairs every
   phone. Which domain?
3. **Which finished requests notify?** The default here is all of them while the phone is not
   showing the page, which includes requests started at the desk. The alternative is only those
   a phone started or steered.
4. **iOS, twice or once?** A phone that wants notifications must pair inside the installed page,
   by a copied link. Is that acceptable for landing 3, or should landing 1 already steer iOS users
   to install first so that they pair once?
5. **Who reviews, and when?** This note gates opening registration on the review. Should it gate
   the owner's own daily use too, and who is asked?

## Amendments

Deviations and additions made while building the relay and page, landing 2 of `pic-relay`. pic
matches these.

- Streams send a comment when they open as well as every 15 seconds, and both sides apply a
  45-second idle timeout (section 6).
- The relay sends `event: seen` after `peer` `0` on a phone's `down` lane (section 6); the
  mailbox record's `used` is set each time pic opens its mailbox stream.
- The phone's reconnect schedule is 1 second doubling to 30 (not 60), each wait varied by a fifth
  either way, the wait reset by a connection that lasted 30 seconds, and an immediate retry on
  wake (section 3). pic keeps its 60-second cap; both apply the 45-second idle timeout.
- A stream's first bytes are its keepalive comment, on pairing channels too (section 6).
- The relay drops a stream whose reader has not taken 2 MiB written to it (a stalled reader);
  the reader catches up from `Last-Event-ID` when it reconnects.
- A request for a mailbox or channel that does not exist (404) counts against the address as a
  failed token does: 60 an hour, then 429 for the rest of the hour, refused before any mailbox
  is reached.
- The page is served with `Strict-Transport-Security: max-age=63072000; includeSubDomains`.
- The page never pairs on its own: a pairing link that opens it shows the offer (the computer's
  name, when the mailbox is one it is already paired with) and waits for a tap before message 1.
  Pairing shows the computer's name with the code, and the new computer becomes current only
  when the person opens it.
- A 404 or `gone` from the relay is unauthenticated: the page keeps the pairing, says the relay
  reported it gone and to check `pic remote devices` on the computer, and offers to try again.
  Only an `unpaired` inside the session deletes the pairing.
- Up `sync` carries `key`; pic echoes it on every `event` and mark of that follow (section 4).
- Down `event` carries `origin`: `remote:DEVICE` or `local` (section 4).
- Down `sessions` carries `workspaces` `[{"id","workspace"}]` and `unavailable`; up `sessions` may
  carry `{"workspace":W}`, answered once with `{"workspace":W,"sessions":[...]}` (section 4).
- `ack` and `response` to a `+W` command carry the new conversation in `session` (section 4).
- The phone orders its commands per conversation, keeps unanswered ones in an IndexedDB outbox,
  and sends typed text as `prompt` with `streamingBehavior` (section 4).
- Up `push` carries `notify`, `all` or `remote`, the device's own choice; pic applies it with
  `remote.notify` (section 5).
- The page sends `presence` at the start of every session (section 5).
- The page refuses a `live` value behind an applied event, drops it when nothing is running,
  and resets `rev` with each new session (section 4).
- Push uses one service worker registration per paired computer, scoped `/push/DEVICE/`; the
  notification's `tag` is the device id and the conversation (section 5). No change on the wire.
- The link `/rc` shows names the conversation by its id alone, `/#s=ID&c=DEVICE` (no journal path,
  so its QR code stays small and the link reveals no path); the page opens the conversation of
  its list whose name ends `/ID`. A notification's link still carries the full name (section 5).
- A conversation in `sessions` carries `title`, `preview` and `state`, all optional (section 4);
  the page lists by them, newest first, with a search, and heads a conversation with its title.
- Images (section 4): `features` in `sessions`; `images` in a phone's `prompt`; image parts in a
  person's message without their bytes; up and down `image`. Readers acknowledge as they read, and
  a `POST` with no records only acknowledges (sections 3 and 6).

### Pairing from a paired phone

Status: accepted, 2026-11-23. A paired phone may let a new device pair, with nobody at the
computer; the remedy for a lost phone is unpairing every device, from the computer or from any
paired phone. The new device's side is the pairing of section 2, unchanged; the person at the
terminal is replaced by the paired phone that asked for the offer, over its confirmed session.

Tier: bundled (in `pic remote`). Clock: os. Record: a device row, as `/rc`'s. Default: on;
`remote.phonePairing off` refuses every request below.

Up, on a confirmed session:

| Message | Payload | Does |
|---|---|---|
| `pair_offer` | none | asks for an offer: pic makes one as `/rc` does, open 300 seconds |
| `pair_approve` | `{"code":"NNNNNN"}` | pairs the device that is waiting, if `code` is its six digits |
| `pair_deny` | none | refuses, or withdraws the offer |
| `devices` | none | asks for the list of paired devices |
| `unpair_device` | `{"device":ID}` | unpairs that device; ID is `b64u` of its 16-byte id |
| `unpair_all` | none | unpairs every device, this one included |

Down:

| Message | Payload | When |
|---|---|---|
| `pair_offer` | `{"url","expires"}` | the offer's address (section 2's QR code), `expires` in Unix seconds |
| `pair_request` | `{"name","code"}` | the new device has made the handshake and sent `pair_ready`; sent again on each new session of the asking phone while it waits |
| `pair_end` | `{"result"[, "name", "device"]}` | the offer is over: `paired`, `refused`, `expired`, `failed` (5 first messages did not verify, or the relay refused), `busy` (another offer is open), `off` (the setting), `full` (8 devices) |
| `devices` | `{"devices":[{"id","name","pairedMs","seenMs","self"}]}` | the answer to `devices`, and after each pairing or unpairing to every phone that has asked for it in its session |

An unpaired device gets `unpaired`, as from the terminal. An old pic answers `error` `unknown_type`
to each of these; the page then says the computer's pic is too old to add a device from a phone.

pic keeps one offer at a time (the relay holds one pairing channel a mailbox). It belongs to the
device that asked: `pair_approve` and `pair_deny` from any other device, or with no device
waiting, are answered `error` `no_offer` and change nothing. A `code` that is not the waiting
device's six digits refuses the offer: there is one try. On approval pic commits the device row,
registers its channel and sends the new device `paired`, in section 2's order.

Why this holds:

- **Only a paired device can approve.** The approval arrives inside a Noise `IK` session whose
  static key is a row in the table (section 3); an unpaired device cannot make one, and the relay
  cannot forge or alter a transport record.
- **A replayed approval does nothing.** A record is accepted once (the counter rule); a new
  session has new keys; the approval names the six digits of one handshake, and an offer admits
  one handshake and ends with it.
- **A rival device is caught as at the terminal.** Whoever uses the offer first holds it; the
  approving phone then shows that device's name and six digits, which the new device in the
  owner's hand is not showing, and the owner taps no. The digits come from the handshake hash of
  the new device's own handshake with pic, so the approving phone shows exactly what pic would.
- **The offer's secret** travels to the approving phone inside its session, so the relay sees it no
  more than the terminal's QR code; it is shown on the phone's screen for the new device to scan.
- **The trade.** A paired phone can now add a device; before, only the computer could. A stolen,
  unlocked phone could already run commands as the owner (section 9), so this adds no power it
  lacked, but the device it adds outlives the stolen phone's own unpairing. The remedy is
  `unpair_all` from any paired phone or `pic remote unpair --all` at the computer, then pairing
  the phones that remain; `remote.phonePairing off` keeps adding devices at the computer only.

**A code to type.** For a device that cannot scan the paired phone's screen (the same iPhone's
Home Screen page, a laptop), the approving phone also shows a code of 10 symbols from Crockford's
base32 (`0-9 A-Z` without `I L O U`), shown `XXXXX-XXXXX`, read case-insensitively with `I` and
`L` as `1`, `O` as `0`, and hyphens and spaces ignored: 50 bits. pic has no part in it:

    out  = PBKDF2-HMAC-SHA256(password = the 10 symbols in upper case, salt = "pic-rc/1 code",
                              iterations = 200000, 64 bytes)
    I    = out[0..16]                     the lookup id, shown to the relay
    k    = out[32..64]                    an AES-256-GCM key
    box  = AES-256-GCM(k, iv = 12 zero bytes, aad = "pic-rc/1 code", the 122-byte offer)

The approving phone stores the box with `PUT /v1/m/M/c/C/code` (its own channel's token; body
`{"id":b64u(I),"box":b64u(box),"ttl":SECONDS}`, at most 600 seconds; only a device channel may)
and the new device takes it with `GET /v1/code/b64u(I)`, no token: the first read answers 200
`{"box"}` and deletes it, a miss is 404 and counts against the address as a failed token does.
The relay holds a box in memory only, at most 600 seconds, and 1000 boxes at once (then 429). The
key is used once, so the zero iv is safe. A relay that wanted the offer would have to search the
code's 2^50 values at 200000 HMAC pairs each within the offer's five minutes, and an offer it
won would still face the six digits on the approving phone: the code adds nothing a leaked QR
code does not.

The page's pairing takes fewer steps; none of this changes the wire:

- A pairing link still waits for one tap ("Pair this phone") before message 1: a link is a request
  from whoever sent it. After a pairing begun with that tap, the page opens the new computer at
  once, with no second tap.
- On an iPhone or iPad the page pairs in Safari directly, with no Home Screen step first. Once
  paired it says, once, that notifications need the page on the Home Screen, and that the Home
  Screen page is added as a new device with a code typed from this one's "Add a device".
- Both phones show the six digits large.
