Skip to content
pi-c Artifact [4e80e4b8f7]
Login

Artifact [4e80e4b8f7]

Artifact 4e80e4b8f7d1001eef8a56769af81e039f32d2386fdc7fa300401b7f7fbcc08a:


# 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. The phone page also keeps bounded, sealed copies of the list and recent history for
offline reading; they carry no sync cursor and are never used to resume the protocol.

### 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, and
  when its stream has brought no record for 2 minutes (comments say only that it is open). 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; with `"archived":true`, archived conversations too; with `"trash":true`, deleted ones too (Amendments) |
| `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`, `key`, `payload` | `{"before":X,"limit":N}`: the `N` entries before `X` (at most 200, the default, and about 2 MiB), once; `key` required; `{"after":A,"to":B}` is not carried (Amendments) |
| `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) |
| `upload_begin` | `session`, `payload` | `{"id","name","size","mime"}`: a file for the workspace of `session` (`W/C` or `+W`) begins (Amendments) |
| `upload_chunk` | `payload` | `{"id","n","data"}`: chunk `n` (from 0, in order) of upload `id`, `data` its bytes in base64 |
| `upload_end` | `payload` | `{"id","sha256"}`: the upload is whole; `sha256` in hex |
| `repair` | `key`, `payload` | `{"workspace":W}`, from a page before 2026-11-25: update `W` now if pic can (Amendments) |
| `ping`, `unpair`, `pair_ready` | | |

### Down: pic to phone

| `type` | Members | Meaning |
|---|---|---|
| `sessions` | `payload` | `{"sessions":[{"session","name","workspace","lastMs","startedMs","running","seq","title","preview","state","archived","deleted","deletedMs"}],"workspaces":[{"id","workspace"}],"unavailable":[{"workspace","reason"}],"features":["images"]}`; to a `sessions` with a workspace, `{"workspace":W,"sessions":[...]}`. `title`, `preview`, `state`, `archived`, `deleted` and `deletedMs` 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,"earlier":SEQ}`, `earlier` absent when the follow shows the first request |
| `fetch` | `session`, `seq`, `key`, `payload` | the end of a `fetch`: `{"done":true,"more":BOOL}`, `seq` the first entry it sent |
| `live` | `session`, `seq`, `payload` | the reply being streamed, as one value (below) |
| `ack` | `key`, `session` for `+W`, `payload` | the command is committed: `{"state":"pending"}` |
| `uploaded` | `payload` | `{"id","path"}`: upload `id` is in the workspace at `path`, synced (Amendments) |
| `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` |
| `repair` | `key`, `payload` | the answer to a `repair`: `{"workspace":W,"ok":BOOL,"message":TEXT}`, `TEXT` a sentence for the person |
| `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 (the first prompt on its path, of
  the furthest conversation it was forked from through forks of forks, 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".
- **Earlier requests.** Each mark carries `earlier`, the `seq` a `sync` would start from to show
  five more of the conversation's requests than this follow does (the seq before the first entry
  of the oldest of them), and leaves it out when the follow already starts at the first request.
  The phone scrolls back by sending `sync` from it, under a new key: everything after it comes
  again, and the phone keeps showing what it had until that sync's first mark.
- **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: the events of the last
  `limit` entries before `before`, each carrying the fetch's `key`, then the `fetch` end (Amendments,
  "Earlier pages").
- 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.
- **Busy.** pic waits at most a quarter of a second for a journal another pic is writing. A
  command it cannot commit in that time is answered `error` `busy` ("this conversation is busy on
  the computer; try again"); the page shows it, and sending it again may succeed.
- **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: `get_session_stats` and the two `get_available_` lists; later: the rest |
| `steer`, `follow_up`, `abort` | the inbox | 1 |
| `prompt` | keyed admission, or the inbox while a request runs; `images` as above; `files`, uploads it names (Amendments) | 1; with `images`, 4 |
| `new_session` then `prompt` | `prompt` with `session` `+W`; the response names the conversation | 2 |
| `set_model`, `set_thinking_level` | held by `pic remote` for the conversation's next request, as `pic --mode rpc` holds its own; that request records it | 2 |
| `set_session_name` | the conversation's name, written as `pic --mode rpc` writes it | 2 |
| `get_credentials`, `check_credentials`, `get_profiles` | pic's: answered by `pic remote` as `pic --mode rpc` answers them: names, kinds, states, what is left, expiry, rules and profiles, never a key | amendment, 2026-11-24 |
| `set_credential` | pic's: the conversation's next requests go with that key of the model's provider, held as `set_model` is; with `persist`, the provider's saved key (`pic auth use`) | amendment, 2026-11-24 |
| `compact` | `pic compact --now` in a process of its own; refused while a request runs | 2 |
| `delete_session`, `restore_session` | pic's own, not Pi's: the conversation deleted (hidden from every list) or brought back, as `pic sessions delete` and `restore` do; deleting a running one is refused | amendment, 2026-11-24 |
| `fork_session` | pic's own, not Pi's: a new conversation from this one's end or an entry, as `pic fork --at` makes it | amendment, 2026-11-28 |
| `archive_session`, `unarchive_session` | pic's own, not Pi's: the conversation out of the lists until it is unarchived or sent a message, or back, as `pic archive` and `unarchive` do | amendment, 2026-11-26 |
| `purge_session` | pic's own, not Pi's: a deleted conversation emptied for good now, as `pic sessions empty-trash` does for each | amendment, 2026-11-26 |
| `clear_queue`, `cycle_model`, `cycle_thinking_level`, `set_steering_mode`, `set_follow_up_mode`, `set_auto_compaction`, `set_auto_retry`, `abort_retry`, `bash`, `abort_bash`, `fork`, `clone`, `rewind` | the inbox (`fork_session` above forks), each added there as grapevine adds commands | 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 `title` (section 4: its name, else its first prompt's first line), 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 beyond the line that titles the conversation,
  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. A record
  on a channel no device has reads the devices again first when the database has changed
  (amended 2026-11-25), so a phone paired a moment ago has its first message answered, not dropped.
- **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.
  Amended 2026-11-23: a row whose directory or journal is gone is not listed and is deleted; one
  whose journal is the user database is pointed at `PATH/.pic/journal.sqlite` when that exists,
  else deleted; a file that is no journal (no `pic_meta`) is not listed. An older journal is
  updated by `pic remote` itself (amended 2026-11-25); while an older pic has it open its reason
  is "open in an older pic; it updates when that pic closes". A newer one's is "a newer pic wrote
  it; update pic on this computer"; no other store error reaches a phone in place of these.
- **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).
- Down `sessions` (2026-11-23): each of `workspaces` and `unavailable` carries `name`, and each
  conversation `workspaceName`: the directory's name, or `PARENT/NAME` when another workspace listed
  has a directory of that name. A page shows it instead of the path's last part.
- `bye` with `reason` `restart` (2026-11-23): `pic remote` is starting a newer pic in its place;
  the phone starts a new session, as after `rekey`.
- Repair (2026-11-24): an `unavailable` entry an older pic last used carries `fix`: `true`; up
  `repair` `{"workspace":W}` runs `pic doctor` for it on the computer, one at a time, answered by a
  down `repair` with `ok` and `message` when it ends (an `error` `no_session`, `busy` or `failed`
  when it cannot run), and the list is sent again as it changes. A page shows the entry's reason
  with a Fix it action. While a newer pic updates a journal, `pic remote` lets go of it and lists it
  as unavailable ("a newer pic is updating NAME"), and serves it again after.
- Updating by itself (2026-11-25): `pic remote` updates a journal an older pic last used, as
  pic's own open does, whenever no process has it open: when it starts (so after an install's
  restart too), on each tick, and when a phone sends `repair` for it. One an older pic has open
  is listed in `unavailable` with the reason "open in an older pic; it updates when that pic
  closes"; that pic is never stopped. `unavailable` entries no longer carry `fix`, and a page
  shows no action for them, only the reason. `repair` is still answered for pages from before:
  `ok` `true` when the workspace is served now, else `false` with the entry's reason as
  `message`; `busy` is no longer sent. Tier: client. Clock: none. Record: journal schema.
  Default: on.
- A person's conversations alone (2026-11-25): `sessions` lists only conversations a person
  started, at a terminal or from a phone. pic records what started each one (a table of its own,
  `pic_session_origin`, with no schema change; no row reads as a person's); those an agent, a hook, a loop no person made, or a run with no one at a terminal
  started are never sent, nor notified (section 5), and no workspace under a temporary directory
  (`$TMPDIR`, `/tmp`, `/var/folders`) is listed. A conversation in `sessions` carries `helpers`, how many conversations
  its tool calls or hooks started are running now (absent for none); a page shows it on the row,
  as "2 helpers running". Tier: client. Clock: none. Record: `pic_session` origin. Default: on.
- `ack` and `response` to a `+W` command carry the new conversation in `session` (section 4).
- `delete_session` and `restore_session` (2026-11-24), pic's own commands: `command` to a `W/C`
  with payload `{"type":"delete_session"}` or `{"type":"restore_session"}`, answered with a Pi
  response line, `{"type":"response","command":"delete_session","success":true}`, or `success`
  `false` with `error` a sentence for the person (`"NAME" is running. Stop it, then delete it.`).
  Both are idempotent: a repeat of either on a conversation already so answers `success` again.
  The next `sessions` leaves a deleted conversation out and lists a restored one again. A
  conversation deleted 30 days ago is purged for good and can no longer be restored. The page hides
  the row at once, offers Undo (a `restore_session`) for a few seconds, and puts the row back when
  the delete is refused; an older pic answers `error` `not_available`, and the page says to update
  pic on the computer.
- `startedMs` (2026-11-26): a conversation in `sessions`, in the list and in a workspace's, carries
  `startedMs`, when it began (milliseconds since the epoch), beside `lastMs`, its last activity. It
  never changes, so two conversations with the same title are told apart by it. Tier: client.
  Clock: none. Record: `pic_session.created_ms`. Default: on.
- `archive_session` and `unarchive_session` (2026-11-26), pic's own commands: `command` to a `W/C`
  with payload `{"type":"archive_session"}` or `{"type":"unarchive_session"}`, answered with a Pi
  response line whose `data` is the conversation's row, `{"session":W/C,"archived":BOOL,
  "archivedMs":MS}` (`archivedMs` `null` when not archived). Both are idempotent. An archived
  conversation is left out of `sessions` and of a workspace's `sessions`, unless that `sessions`
  carries `"archived":true`: then archived ones are listed too, each with `"archived":true`
  (absent on the rest). A prompt to an archived conversation, from anywhere, unarchives it. An
  older pic answers `error` `not_available`. Tier: client. Clock: none. Record: `pic_archive`.
  Default: on.
- Deleted conversations (2026-11-26): a `sessions`, the list or a workspace's, with `"trash":true`
  includes the deleted conversations that are not purged yet, at most 50 a workspace in the list,
  each with `"deleted":true` and `deletedMs`, when it was deleted (absent on the rest), and
  `"archived":true` too when it was archived first; without it they are left out, as before.
  `trash` alone decides whether a deleted one is listed: `"archived":true` adds only archived ones
  that are not deleted (#117). `restore_session` brings one back, archived if it was. `purge_session`, pic's own
  command, empties one for good now, as `pic sessions empty-trash` does: answered with a Pi
  response line, `success` `true`, or `false` with `error` `Delete it first` for one not deleted,
  or a sentence when it is running or open in a pic. A purged conversation is listed nowhere. An
  older pic answers a `purge_session` `error` `not_available`, and ignores `trash`. Tier: client.
  Clock: none. Record: `pic_trash`. Default: on.
- Files from the phone (2026-11-26): a file goes up in chunks on the encrypted lanes. Up
  `upload_begin` `{"id","name","size","mime"}` with `session` a `W/C` or `+W` (the workspace it
  goes to), then `upload_chunk` `{"id","n","data"}` for `n` from 0 in order, each at most 512 KiB
  of bytes in base64, then `upload_end` `{"id","sha256"}`. `id` is 16 to 43 characters of
  `[A-Za-z0-9_-]`. pic writes the bytes as they come to a part file in the workspace's
  `.pic/uploads` (no symbolic link is followed there), checks the size and the sha256 against what
  is on disk, syncs the file, and gives it `name`, or `name-2.ext` and on when another file has
  that name; the same bytes under that name are that file. Down `uploaded` `{"id","path"}`, `path`
  relative to the workspace (`.pic/uploads/NAME`); a repeat of `upload_end` for one of the last 8
  gets the same. Errors are `error` with `key` the upload's id: `bad_message` (a name that is not
  one path component, has a leading dot or control characters, or is over 128 bytes; no size),
  `too_large` (over 25 MiB), `quota` (4 uploads open at once from a device, or 256 MiB from it in a
  day), `no_session`, `bad_upload` (a chunk out of order or not base64, the wrong size or sha256,
  an unknown id; the upload ends and its part file goes), `failed` (the disk). An upload with no
  chunk for 5 minutes is given up. `prompt` takes `files`, at most 16 paths of uploads of that
  workspace (`.pic/uploads/NAME`, there now); pic appends a line `[attached: PATH]` for each to the
  message, and the model reads them with its tools; any other is `bad_command`. An older pic
  answers `upload_begin` `error` `unknown_type`. Tier: client. Clock: none. Record: workspace
  files. Default: on.
- `rename_device` (2026-11-26): up `{"type":"rename_device","payload":{"device":ID,"name":N}}`,
  from any paired phone for any paired device, since every one is the same person's. `N` follows
  these steps, in order, which a page can repeat to know its own rename: (1) C0 controls (U+0000
  to U+001F), DEL (U+007F) and C1 controls (U+0080 to U+009F) are removed; (2) the bidi controls
  U+061C, U+200E, U+200F, U+202A to U+202E and U+2066 to U+2069, surrogates and bytes that are
  not UTF-8 each become `?`; (3) U+0020 alone is trimmed at both ends; (4) a name left empty, or
  over 64 bytes, is refused with `error` `bad_message`, never cut short. Nothing else changes: no
  normalization (NFC or other), no collapsing of spaces. An unknown device is `error`
  `no_device`. pic writes the device's row and sends `devices` to every
  phone with a session. Later `ask_settled` say the new name in `by.device`; `by.deviceId` is
  unchanged. The terminal's device list shows it too. Tier: client. Clock: none. Record: device
  table. Default: on.
- 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).
- Marks carry `earlier`, and a phone scrolls back with `sync` from it rather than `fetch`, which was
  not carried until "Earlier pages" below (section 4).
- `get_session_stats`, `get_available_models` and `get_available_thinking_levels` are answered,
  for the model the conversation's next request runs on. `set_model` (one of the available models)
  and `set_thinking_level` are not rows: `pic remote` holds the choice in memory, reports it in
  `get_state`, and passes it to the next request it starts there, which records it; a restart
  before then forgets it. `set_session_name` writes the name. `compact` runs `pic compact --now` in
  a child and answers when it ends, the same answer to its key again; while a request runs it is
  refused, where Pi's would abort the request (section 4).
- The phone sends the questions (`get_` commands) with a key and repeats them while a session is
  open, but keeps them in no outbox and never orders them behind its other commands.
- 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.
- A notification's `T` is the conversation's `title`, the list's, so a lock screen shows the line
  the owner asked for; the workspace only when there is none (section 5).
- Loops (2026-11-24, [loops](../manual/loops.md)): a conversation in `sessions` carries `loops`,
  how many loops, monitors and goals it has that have not ended (absent for none), and is
  `attention` when one needs the person. pic's own commands to a `W/C`: `get_wakes` (the
  conversation's, as pic's RPC `get_wakes` lists them), `pause_wake`, `resume_wake` and
  `stop_wake` with `id` (`L1`), `approve_wake` and `decline_wake` (a loop or goal the model asked for,
listed with `asking` true: Start and No), and `pause_wakes`; each answers a Pi response line whose `data` has
  `wakes` (what is left of the conversation's after the change) and `nowMs` (the computer's clock,
  for a countdown), and `paused` for `pause_wakes`. An action is committed before it is answered;
  `stop_wake` on one already ended answers `success` again; an `id` of another conversation is
  refused. `pic remote` asks each journal it serves what is due every 5 seconds, so loops fire with
  the terminal closed, and a loop that comes to need the person (its message refused, its 7 days
  up) is one notification (section 5) whose `B` says so: `Loop L1 needs you: …`. An older pic
  answers `not_available`; the page then shows no loops.
- 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).
- Questions (2026-11-25, [questions](../manual/questions.md)): a conversation that waits on a
  person (a loop or goal the model asked for, and later a permission) has a question, durable in
  pic's journal, which any surface answers once. Tier: core (`src/ask.c`). Clock: durability.
  Record: `pic_ask`. Default: on. `features` in `sessions` lists `asks`; an older pic answers the
  command below `not_available`, and the page shows no questions.
  - Down `ask`, to every phone with a confirmed session when a question is asked, and every open
    one at the start of each session: `{"type":"ask","session":S,"payload":{"id","kind","title",
    "createdMs","expiresMs","state"}}`, with `body`, `options`, `placeholder` and `wake` when they
    apply. `id` is 22 characters of random base64url, unique across conversations and computers.
    `kind` is `confirm`, `select` (with `options`) or `input` (with `placeholder`); `wake` names the
    loop or goal (`L1`) whose OK it asks.
  - Options are `[{"label","destructive","default"}]`, in pic's order and of equal weight, except
    that one may carry `destructive: true` and at most one `default: true`.
  - Limits: a title has at most 120 characters, a body 2,000, a label 60, and a select at most 10
    options; pic cuts a longer text before it sends it. A text answer has at most 4,000 characters.
  - Up: the command `{"type":"answer","id":ID,"value":V}` under the key `ask-ID`. `V` is `true` or
    `false` to a confirm, one of the labels to a select, text to an input, or `null` to dismiss it.
    The first answer from any surface stands, committed before it is answered. The response's
    `data` is `{"result","id","value","by"}`: `result` `answered`, `already_answered` (another
    answer stood first, or the question was withdrawn) or `expired` (it timed out unanswered),
    with the answer that stands and who gave it. A resend of the key from the same device returns
    the original result. Two phones sending the same key send two commands: the first wins and the
    second gets `already_answered`. An answer over a limit is `error` `bad_command`. A question not
    of that conversation (`no_ask`) and a value that is not an answer to it (`bad_answer`) are the
    response's `success: false` with `error` a sentence; `busy` as for any command. Nulls
    are kept: `value`, `device` and `deviceId` are `null`, not left out, in `data` here, in
    `ask_settled` and in `get_state`'s `settledAsks`.
  - Down `ask_settled` to every phone with a confirmed session when a question closes, so every
    surface shows the outcome: `{"type":"ask_settled","session":S,"payload":{"id","value","by":
    {"kind","device","deviceId"}}}`, `kind` `terminal`, `phone`, `attach`, `rpc`, `expired` or
    `cancelled` (its asker stopped waiting), `device` the answering phone's name, and `deviceId` its
    pairing's id, `remote:` and the id `pic remote devices` lists; both are `null` unless `kind` is
    `phone`. Two phones can share a name, never an id. A page may tell its own answer by
    `deviceId`, or by its answer's reply.
    A confirm's `value` is `true` or `false`, as it was answered.
  - `get_state` carries `asks`, the conversation's open questions, and `settledAsks`, those settled
    while the run waiting on them is still running (`ask_settled`'s payloads).
  - A conversation in `sessions` carries `asks`, how many questions it has open (absent for none),
    and is then `attention` whether or not it runs, so a page lists it under "Needs you" without
    fetching each conversation.
  - `test/pic/remote-asks.json` holds these records as pic writes them, one a line: `down`
    (an `ask` of each kind, a confirm with and without `wake`, a select with a destructive and a
    default option, an input; `ask_settled` by phone, terminal, attach, rpc, dismissed, expired and
    cancelled), `up` (the `answer` payloads, including two that are refused), `responses` (the
    payload of each reply: `answered`, `already_answered`, `expired`, two `bad_answer` and a
    `no_ask`, none acknowledged first) and `state` (`get_state`'s `asks` and `settledAsks`).
    `test/pic/remote.sh` makes it from a running `pic remote` and fails when it differs
    (`PIC_UPDATE_FIXTURES=1` rewrites it); ids, times, paths and the device's id are fixed in it.
    `pic-relay` copies the file byte for byte, as section 8's vectors.
  - A new question is one notification (section 5) whose `B` is pic's fixed text, `T needs your
    answer` with `T` the conversation's title, never the question's own words, so nothing it says
    reaches a lock screen. A loop's OK is told this way, not as "needs you".
- Permission modes (2026-11-27, [permissions](../manual/permissions.md)): a conversation has a
  permission mode, durable in pic's journal, that says which tool calls wait for the person's yes:
  `allow` (none, the default), `ask-edits` (write and edit), `ask-all` (every call that is not
  read-only) or `read-only` (those are refused, not asked). Tier: core (`src/perm.c`). Clock:
  durability. Record: `pic_permission`, a `pic_ask` per call that asks. Default: `allow`.
  `features` in `sessions` lists `permissions`; an older pic answers the command below
  `not_available`, and the page then shows no mode.
  - `get_state` carries `permissionMode`, always. A conversation in `sessions` carries
    `permissionMode` when it is not `allow` (absent for `allow`).
  - Up: the command `{"type":"set_permission_mode","mode":M}` with `M` one of the four. It is
    committed before it is answered; the response's `data` is `{"permissionMode","allowed"}`,
    `allowed` the tools the person allowed for the conversation (names, as `["bash"]`). A mode that
    is not one is the response's `success: false` with `error` "a permission mode is allow,
    ask-edits, ask-all or read-only"; `busy` as for any command. A resend of the key from the same
    device returns the original result and changes nothing, even after the mode was changed
    elsewhere (pic keeps the answer under the key).
  - A call that asks is a question (above): `kind` `select`, `title` "Allow TOOL: KEY?" (the
    command, path or first text argument, cut at its first line), `body` a preview (the command;
    the path and the start of a write's content; the path and an edit's old and new lines),
    `options` `Allow`, `Allow for this conversation` and `Deny`, none `default` or `destructive`.
    The page answers it with `answer` like any select; the record carries no other mark, so a page
    shows it as it shows any question.
- Earlier pages (2026-11-26): pic carries `fetch` `{"before":X,"limit":N}`, so a page scrolls
  back a bounded amount at a time instead of a `sync` from `earlier`, which sends everything from
  there to the end again and, on a long conversation, held the computer's loop for minutes. A
  fetch carries a `key`, as a sync does, and one without it is `error` `bad_message`. pic answers
  with the events of the last `N` entries of the conversation before entry `X` (`N` at most 200,
  the default when absent or larger; fewer when their events would come to more than about 2 MiB,
  one at least), each an `event` carrying the fetch's `key`, then
  `{"type":"fetch","session":S,"seq":F,"key":K,"payload":{"done":true,"more":BOOL}}`: `F` the
  first entry sent (`X` when there was none), `more` whether the conversation has entries before
  `F`. A request cut by `X` gets no `agent_end` there; one wholly inside the page does. The page
  sends `before` as the first entry it holds, shows the events above what it has (they are all
  behind its cursor and change nothing it follows), and offers "Earlier messages" again while
  `more` is true, the next `before` being `F`. `{"after":A,"to":B}` is answered `error`
  `not_available`. Marks still carry `earlier`, and a `sync` from it still works, for pages from
  before. pic posts to the relay off its loop now, on two connections of its own, the second only
  for small posts, so a pong or an answer never waits behind a large page on its way to any phone.
  Tier: client. Clock: none. Record: none. Default: on.
- Keys pic remote lacks (2026-11-28): the responses to `get_available_models` and
  `get_credentials` carry `data.missing`, the providers that need a key and have none `pic remote`
  can use (none stored, and its variable not set in `pic remote`'s own environment, which for one
  the system started at login is not a terminal's), in pic's order:
  `[{"provider":P,"env":VAR,"fix":["pic auth login P --command 'COMMAND THAT PRINTS THE KEY'",
  "pic auth login P --api-key"]}]`. `fix` holds commands to run at the computer, each a line to
  show as it is: the first stores the command that prints the key (a secret manager's), run at
  each request, so nothing secret is written and a rotated key is picked up; the second stores a
  key the person pastes. pic never suggests copying the variable's value. An empty list is `[]`;
  an older pic sends no `missing`, and a page then shows nothing for it. A page shows the list
  below the models and the keys, as "No key for pic remote", with the commands. Tier: client.
  Clock: none. Record: none. Default: on.
- Folders (2026-11-28): a phone may start a conversation in a folder pic has not run in yet. Down
  `sessions` (the list, not a workspace's) carries `folders`, `[{"id":F,"name":N,"root":R}]`: each
  immediate subfolder of a root that is no workspace yet, the most recently changed first, at most
  500. `F` is the folder's real path (every link resolved), `N` its last part, and `R` its root's
  real path, for a page to group them by. The roots are the setting `remote.folders` (folders
  separated by `:`, `~` the home folder; any folder, `/` included, lists its subfolders), or, unset,
  the folders holding the workspaces pic knows, except the home folder and the folders above it,
  anything under `/Volumes`, and the home folder's private folders (Desktop, Documents, Downloads,
  Library, Movies, Music, Pictures) and anything inside them. pic reads at most 2000 entries of a
  root each time. A folder whose name starts with `.`, one a link takes out of its root, one under a
  temporary directory and one that is a workspace already (that is in `workspaces` or `unavailable`)
  is not listed. pic reads them again when its registry or settings change and every 10 seconds. An
  empty list is `[]`; an older pic sends no `folders`, and a page then offers only `workspaces`.
  - `+F`, with `F` exactly an `id` of the last `folders` pic made, starts a conversation there as
    `+W` does (`prompt` only). pic makes the folder's `.pic` (which ignores itself, and is named in
    a fossil or zit checkout's ignore rules) and its journal `F/.pic/journal.sqlite` unless it has
    one; the `response` (and the `ack`, when one is sent, as for `+W`) carry `session`
    `F/.pic/journal.sqlite/C`, and the next `sessions` lists it in `workspaces` with `id`
    `F/.pic/journal.sqlite`, and no longer in `folders`. A folder whose journal could not be made
    stays in `folders`.
  - Anything else is `error` `no_session` "no such workspace", and nothing is made: a path that is
    not one of `folders` (another spelling of it, a `..`, a link, a hidden folder, a folder
    elsewhere). A folder that is gone or is no longer that real path when the command runs is the
    same error; a `.pic` that cannot be made, or a journal that cannot be started, is `error`
    `failed` with the reason in `message`.
  - `upload_begin` takes `+W` only, not `+F`: a page sends files to a folder once it is a
    workspace. `features` is unchanged.
  - Tier: client. Clock: none. Record: the folder's new journal, its row in pic's workspace
    registry, the setting `remote.folders`. Default: on.
- Forking (2026-11-28): pic's own command `fork_session`, to a `W/C`, with payload
  `{"type":"fork_session"}` or `{"type":"fork_session","at":SEQ}`, makes a new conversation that
  goes on from this one, as `/fork` and `pic fork --at` do; this one is left as it was.
  - `at` is an entry's `seq`, as events carry it: the new conversation holds every entry of this
    one's path up to and including `SEQ`, which must be on that path and end a turn (a reply with
    no tool call still waiting, a cancelled prompt; not a prompt its reply follows). Absent or
    `null`, it is the conversation's end: the last such entry of a request that is not running, so
    while a request runs the fork starts from where the last finished request ended, without the
    running one.
  - The answer is a Pi response line whose `data` is `{"session":"W/C2","at":SEQ}`: `C2` the new
    conversation's id, in the same workspace, and `SEQ` the entry it was forked at (the end's, when
    `at` was absent). The new conversation is a phone's (`origin` `phone`), has this one's
    permission mode and no name (its `title` is this one's first prompt until it has one), and
    the next `sessions` lists it. The fork and its key are one commit before the answer.
  - Once per key: a resend of the key from the same device returns the same `data`, after a restart
    of `pic remote` too, and makes nothing more, even once the fork was deleted and purged: it then
    names the purged conversation, which every command answers `error` `no_session`. The same key
    with another `at` or another conversation is `error` `refused` "that key was used to fork
    another point or conversation".
  - Refusals, the response's `success: false` with `error`: `entry SEQ is not a point to fork from:
    it must be on this conversation and end a turn`; `entry SEQ is in the request still running:
    fork from an earlier entry, or once it ends`; `There is nothing to fork yet.` (no entry ends a
    turn: an empty conversation, or one whose first request is running). An `at` that is not a
    positive integer or `null` is `error` `bad_command`; `busy` as for any command, and then
    nothing was made. An older pic answers `error` `not_available`, and a page then offers no fork.
  - A page offers Fork on an entry and in the conversation's menu, opens the new conversation from
    `data.session` once answered, and keeps the command in its outbox as any other. `features` is
    unchanged. Tier: client. Clock: none. Record: a `pic_session` row (`forked_from`), its
    `pic_session_origin` and `pic_permission` rows, and `pic_fork_key`. Default: on.
- A new conversation's choices (2026-11-28): a `prompt` to `+W` or `+F` may carry its first
  request's model, thinking level and key, as members of the prompt's payload named as `set_model`
  names them: `provider` and `modelId` (both, strings: one of the workspace's
  `get_available_models`), `thinkingLevel` (`off`, `minimal`, `low`, `medium`, `high`, `xhigh`,
  `max`) and `credential` (the label of a key of that model's provider, one `get_credentials`
  lists). Each is optional; one left out is what a new conversation there starts on without it.
  The request records them as any request does (the submission's model and level, each
  generation's key). Later requests of that conversation go on with its model, level and key, as
  after any request: a conversation keeps the key its replies went with, and `pic remote` passes
  it to each of its requests unless `set_credential` or `set_model` holds another choice. A key
  gone by then refuses the prompt, nothing admitted, with the response's `success: false` and
  `error` `The key "L" this conversation went with is gone from P: choose another with
  set_credential.`; this holds for every conversation a phone prompts. A model chosen without
  `thinkingLevel` runs at the workspace's last level when it thinks at that one, else at the
  nearest it does (`off` for a model that does not think); so does any request `pic remote`
  starts, so a level never outlives the model it was chosen for.
  - Questions before the conversation exists: `get_available_models`,
    `get_available_thinking_levels`, `get_credentials`, `check_credentials` and `get_profiles` to
    `+W` or `+F` are answered as for a conversation there, and make nothing (no journal in a
    folder). `get_available_models`'s `data` also carries `model`, Pi's model object for the model a
    new conversation there starts on (the workspace's last request's, else the one pic starts on at
    the terminal: the saved default, or the first provider with a key), `null` when pic knows none,
    and `thinkingLevel`, the workspace's last request's level, `null` for pic's default; it and
    `get_credentials` carry `missing` as for a conversation. A page shows those as the
    new-conversation screen's defaults. Any other question to `+W` or `+F` is `error` `bad_command`,
    as before.
  - `get_available_thinking_levels` to `+W` or `+F` (2026-11-28) may carry `provider` and
    `modelId`, as the prompt does, and then answers the levels of that model, so a page can offer
    the levels of the model chosen on its new-conversation screen: `{"levels":[...],"model":
    {"provider":P,"id":M}}`, `model` the one they are for (the default's when none was sent, `null`
    when pic knows none; an older pic's answer has no `model`, so a page can tell). A model that
    is not one of the workspace's `get_available_models` is the response's `success: false` with
    `error` `Model not found: P/M`; `provider` without `modelId`, or either not a string, is `error`
    `bad_command` "provider and modelId must be strings". Without them it answers for the model a
    new conversation there starts on, as before. An older pic ignores them and answers for that
    model.
  - Checked before anything is made, a folder's journal included: `provider` without `modelId` (or
    either not a string) is `error` `bad_command` "provider and modelId must be strings" (the two
    are matched apart, so an id may hold a `/` and a provider that does is no model's); a
    `credential` that is not a string is `bad_command` "credential is a key's label", and one sent
    without `provider` and `modelId` is `bad_command` "a credential is chosen with its model: send
    provider and modelId with it". These are the response's `success: false` with `error`: a model
    not available, `Model not found: P/M`; a level that is not one, `Invalid thinking level: L (off,
    minimal, low, medium, high, xhigh, max)`, `L` being `(not a string)` for one that is not a
    string; a level the model (the chosen one, else the one a new
    conversation there starts on) does not think at, `thinking level L is not supported by P/M
    (supported: off)` with its levels; a label the provider has no key by, `P has no key named
    "L"`.
  - Once per key, as any prompt: a resend of a prompt already admitted under its key reports the
    first (its `session` the conversation made then) without checking the choice again. `busy` as
    for any command, and then nothing was made. An older pic ignores the four members (the request
    starts on what it would have) and answers the questions to `+W` or `+F` `bad_command` (to `+F`
    after making the folder's journal); a page tells an older pic by `get_available_models` to `+W`
    failing, and then offers no choice.
  - Tier: client. Clock: none. Record: the request's model and level (`pic_submission`) and key
    (`pic_generation.credential`), as for any request. Default: on.
- `get_commands` (2026-11-28): answered for a `W/C`, and for `+W` or `+F` before a conversation is
  made there (nothing is made), as `pic --mode rpc` answers it, for that workspace: `data.commands`,
  `[{"name","description","source","sourceInfo"}]` with `argumentHint` for a template, `source`
  `prompt` (a template, `name` as typed after `/`) or `skill` (`name` `skill:NAME`), the person's
  and the workspace's (a workspace's own only when it is trusted), in pic's order. A page lists them
  in its `/` menu after its own commands, and a prompt naming one is expanded as at the terminal.
  Nothing secret is in it; `sourceInfo.path` is the file's path on the computer. An older pic
  answers `error` `not_available`, and a page then lists only its own commands. A name, description
  or `argumentHint` is sent without control characters (tab, newline and return become a space;
  other C0 controls, DEL, C1 controls and the bidi controls U+061C, U+200E, U+200F, U+202A to U+202E
  and U+2066 to U+2069 are left out; a byte that is not UTF-8 becomes `?`) and cut on a character to
  at most 200 bytes, `…` ending one that was cut, as `pic --mode rpc` sends it. Tier: client. Clock:
  none. Record: none. Default: on.

### 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 |
| `rename_device` | `{"device":ID,"name":N}` | renames that device, any paired one; ID as for `unpair_device`, or `remote:` and it (the `deviceId` of `ask_settled`) (Amendments) |
| `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; after a rename, to every phone with a 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.

### Keys and profiles

Added with pic's `/auth` (2026-11-24). A phone sees the keys and switches between them; it never
reads one. No change to the envelope, the records or the relay.

- `get_credentials` answers every key of every provider: its `provider`, `label`, `kind`,
  whether it is `active`, its `state`, what is `left` and how old that is, its expiry, and the
  rules (`bindings`) that give a family of models a key. `check_credentials` runs the free
  checks first, on the computer; the phone never talks to a provider. `get_profiles` lists the
  profiles, each a name for a model, a key and a thinking level.
- `set_credential` (`provider`, `label`) is held by `pic remote` for the conversation, as
  `set_model` is, and passed to its next request as the key to use; `get_state` reports it as
  `credential` (`provider:label`), or the conversation's own when the phone chose none. With
  `persist: true` it is the provider's saved key instead, for every conversation.
- `set_model` takes `profile` in place of `provider` and `modelId`: the profile's model, and its
  key and thinking level when it names them.
- Not carried, and answered `not_available`: storing a key (`add_credential`), a key from a
  command, removing a key, rules (`set_model_credential`), expiry (`set_credential_expiry`) and
  `unlock`. A key, a command or a passphrase never crosses the relay.