Skip to content
pi-c Artifact [9c9c76dd02]
Login

Artifact [9c9c76dd02]

Artifact 9c9c76dd02a1a65f0e0e21ca293694c9134a8698d721e0d9c52b157019bf7d32:


/* See remote.h; the wire contract is docs/design/remote-protocol.md, and section numbers below
 * are its. One loop and one extra thread: the thread reads the relay's stream and writes whole
 * records to a pipe, never touching SQLite; the loop waits on that pipe and a 100 ms tick, as
 * pic attach does, and does everything else: handshakes, commands, following, posting. */
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <pthread.h>
#include <signal.h>
#include <stdarg.h>
#include <stdatomic.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/select.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <termios.h>
#include <time.h>
#include <unistd.h>

#include "ask.h"
#include "attach.h"
#include "cred.h"
#include "http.h"
#include "inbox.h"
#include "net.h"
#include "noise.h"
#include "pic.h"
#include "platform.h"
#include "remote.h"
#include "rpc.h"
#include "sqlar.h"
#include "sse.h"
#include "userdb.h"
#include "wake.h"
#include "webpush.h"

#define RMT_PAIR_TTL 600          /* an offer's lifetime, seconds */
#define RMT_PAIR_FAILS 5          /* first messages that fail to verify before an offer ends */
#define RMT_PHONE_PAIR_TTL 300   /* an offer a paired phone asked for, seconds */
#define RMT_PAIR_AGAIN 16         /* the same first message answered again (the phone reconnected) */
#define RMT_LAST_WORD_MS 30000LL  /* how long paired (or a refusal) waits for the phone to read it */
#define RMT_NO_PEER_MS 2000LL     /* the wait when the relay does not say whether it reads */
#define RMT_UNCONFIRMED_MS 30000LL
#define RMT_SILENT_MS 600000LL    /* a session silent this long is dropped */
#define RMT_REKEY_MS 86400000LL   /* a session older than this is asked to start again */
#define RMT_BYE_GRACE_MS 60000LL  /* and dropped if it has not, this long after */
#define RMT_POST_WAIT_MS 30000LL  /* a record that waited this long to be posted is dropped */
#define RMT_MSG_CAP (4u << 20)    /* an envelope message */
#define RMT_POST_RECORDS 32
#define RMT_POST_BYTES (256u << 10)
#define RMT_CMDS 64
#define RMT_CHOICES 32            /* conversations with a model or level chosen from a phone */
#define RMT_EARLIER 5             /* the requests an "earlier" sync point adds */
#define RMT_SESSIONS 32
#define RMT_LIST 50
#define RMT_IDLE_S 45             /* a stream with no byte this long is dead: the relay comments every 15 s */
#define RMT_QUIET_MS 120000LL     /* no record this long while a phone is on screen (it pings each minute): reconnect */
#define RMT_OPEN_FAILS 3          /* records in a row that do not open end a session */
#define RMT_TALLY_MS 10000LL      /* a kind of drop or reset is logged at most this often */
#define RMT_BUSY_MS 250           /* the longest the loop waits for a journal another pic is writing */
#define RMT_STALL_MS 10000LL      /* a loop tick this long is a stall: logged, and status says so */
#define RMT_PAGE 200              /* the most journal entries one follow pass sends; the rest next tick */
#define RMT_ASKS 50               /* the most asks one look reads from a journal; the rest next tick */
#define RMT_ASK_RING 64           /* the expired asks a journal remembers telling */
#define RMT_BACKOFF_MAX_MS 60000LL
#define RMT_JUMP_MS 10000LL       /* a tick this late, or a wall clock this far ahead: a sleep or a stop */
#define RMT_LIVE_MS 250LL         /* at most one live value this often per phone */
#define RMT_LIVE_KEEP 8192        /* the bytes of streamed text a live value carries */
#define RMT_PUSH_GAP_MS 30000LL   /* at most one notification per conversation this often */
#define RMT_PUSH_TTL 3600
#define RMT_PUSH_QUEUE 32         /* notifications waiting to be sent; more are dropped */
#define RMT_PUSH_REFUSED 3        /* 400s or 403s in a row that end a subscription */
#define RMT_ENDPOINT 2048
#define RMT_ACK_BYTES (256 << 10) /* read and not yet acknowledged: acknowledged at once past this, */
#define RMT_ACK_RECORDS 128        /* or this many records (a lane holds 1 MiB or 256), */
#define RMT_ACK_MS 5000LL          /* or after this long with no post to carry it */

static volatile sig_atomic_t rmt_stop;
static volatile sig_atomic_t rmt_restart_asked; /* SIGUSR1: pic remote restart */
/* The program this pic remote runs and its file's stamp when it started (platform.h's file_stamp):
 * a newer pic installed over it starts in its place at a quiet moment. */
static char rmt_exe[PATH_MAX], rmt_exe_stamp[128];
static long long rmt_started_ms;

static long long rmt_wall_ms(void) { return (long long)(pic_platform_get()->wall_ns() / 1000000); }
static long long rmt_mono_ms(void) { return (long long)(pic_platform_get()->mono_ns() / 1000000); }

/* A line of what pic remote says (~/.pic/remote.log when it runs at login), after the UTC time. */
static void rmt_log(FILE *f, const char *fmt, ...) {
    char when[32] = "";
    time_t t = (time_t)(rmt_wall_ms() / 1000);
    struct tm tm;
    va_list ap;
    if (gmtime_r(&t, &tm)) {
        (void)strftime(when, sizeof when, "%Y-%m-%dT%H:%M:%SZ", &tm);
    }
    flockfile(f);
    fprintf(f, "%s ", when);
    va_start(ap, fmt);
    vfprintf(f, fmt, ap);
    va_end(ap);
    funlockfile(f);
    (void)fflush(f);
}

/* The loop's watchdog: the loop stamps each tick and says what it is doing; a thread of its own
 * logs a tick that has not ended in RMT_STALL_MS, since the loop cannot say so itself. */
static atomic_llong rmt_beat_ms;
static atomic_llong rmt_stuck_ms; /* the stamp of the tick the watchdog logged as stuck, or 0 */
static pthread_mutex_t rmt_doing_mu = PTHREAD_MUTEX_INITIALIZER;
static char rmt_doing_what[256] = "starting";
static long long rmt_doing_ms; /* when the phase was named (mono), under rmt_doing_mu */

/* Names the phase the loop enters: each call that may block is named just before it, with the
 * journal or phone it is for, so a stall says where it is. */
static void rmt_doing(const char *what, const char *detail) {
    pthread_mutex_lock(&rmt_doing_mu);
    (void)snprintf(rmt_doing_what, sizeof rmt_doing_what, "%s%s%s", what, detail ? " " : "", detail ? detail : "");
    rmt_doing_ms = rmt_mono_ms();
    pthread_mutex_unlock(&rmt_doing_mu);
#ifdef PIC_FAULTS
    {
        /* the tests' seam: "TEXT:MS" sleeps MS, once, in the first phase whose name has TEXT */
        static int slept;
        const char *v = getenv("PIC_TEST_RC_SLOW_PHASE"), *colon = v ? strrchr(v, ':') : NULL;
        if (colon && !slept) {
            char want[128];
            (void)snprintf(want, sizeof want, "%.*s", (int)(colon - v), v);
            if (strstr(rmt_doing_what, want)) {
                long long ms = atoll(colon + 1);
                struct timespec ts = {(time_t)(ms / 1000), (long)(ms % 1000) * 1000000L};
                slept = 1;
                (void)nanosleep(&ts, NULL);
            }
        }
    }
#endif
}

static long long rmt_stall_ms(void) {
#ifdef PIC_FAULTS
    if (getenv("PIC_TEST_RC_STALL_MS")) { /* the tests' seam: a stall seen in a second or two */
        return atoll(getenv("PIC_TEST_RC_STALL_MS"));
    }
#endif
    return RMT_STALL_MS;
}

static void *rmt_watch_main(void *arg) {
    (void)arg;
    for (;;) {
        struct timespec ts = {0, 250000000L};
        long long beat, now;
        (void)nanosleep(&ts, NULL);
        beat = atomic_load(&rmt_beat_ms);
        now = rmt_mono_ms();
        /* the loop stamps its tick before it takes back the stuck mark: a stamp still unchanged
         * after the mark was looked at is a tick that has not ended */
        if (beat && now - beat > rmt_stall_ms() && atomic_load(&rmt_stuck_ms) != beat && atomic_load(&rmt_beat_ms) == beat) {
            char what[256];
            long long since;
            pthread_mutex_lock(&rmt_doing_mu);
            (void)snprintf(what, sizeof what, "%s", rmt_doing_what);
            since = rmt_doing_ms;
            pthread_mutex_unlock(&rmt_doing_mu);
            atomic_store(&rmt_stuck_ms, beat);
            rmt_log(stdout, "pic remote: stalled: the loop has been stuck for %lld s; its last phase, named %lld s ago: %s\n",
                    (now - beat) / 1000, (now - since) / 1000, what);
        }
    }
    return NULL;
}

static void rmt_hex(const unsigned char *b, size_t n, char *out) {
    static const char d[] = "0123456789abcdef";
    for (size_t i = 0; i < n; i++) {
        out[2 * i] = d[b[i] >> 4];
        out[2 * i + 1] = d[b[i] & 15];
    }
    out[2 * n] = '\0';
}

/* ---- JSON through SQLite's functions, on a private connection ------------------------ */

static sqlite3 *rmt_mem(void) {
    static sqlite3 *m;
    if (!m && sqlite3_open(":memory:", &m) != SQLITE_OK) {
        sqlite3_close(m);
        m = NULL;
    }
    return m;
}

/* The first column of SQL with N text binds (a NULL binds NULL), malloc'd; NULL when it is NULL
 * or on failure. */
static char *rmt_q(const char *sql, int n, ...) {
    sqlite3 *m = rmt_mem();
    sqlite3_stmt *q = NULL;
    char *out = NULL;
    va_list ap;
    if (!m || sqlite3_prepare_v2(m, sql, -1, &q, NULL) != SQLITE_OK) {
        return NULL;
    }
    va_start(ap, n);
    for (int i = 1; i <= n; i++) {
        const char *v = va_arg(ap, const char *);
        if (v) {
            sqlite3_bind_text(q, i, v, -1, SQLITE_TRANSIENT);
        }
    }
    va_end(ap);
    if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_type(q, 0) != SQLITE_NULL) {
        out = strdup((const char *)sqlite3_column_text(q, 0));
    }
    sqlite3_finalize(q);
    return out;
}

/* ---- keys and devices (section 1) ------------------------------------------------- */

typedef struct {
    pic_noise_keypair stat, vapid;
    unsigned char owner[32], mailbox[16];
} rmt_keys;

typedef struct {
    unsigned char id[16];
    char name[72];
    unsigned char stat[PIC_NOISE_PUB];
    unsigned char channel[16];
    long long paired_ms, seen_ms;
    /* its push subscription (section 5): notify is "all" or "remote", "" for none */
    char notify[8];
    char endpoint[RMT_ENDPOINT];
    unsigned char p256dh[PIC_WEBPUSH_PUB], auth[PIC_WEBPUSH_AUTH];
} rmt_device;

/* NAME's row: 0 with its public column in PUB (*PN bytes) and the opened secret in SEC (*SN
 * bytes); 1 when there is none; -1 with err. */
static int rmt_key_read(sqlite3 *db, const char *name, unsigned char *pub, size_t pcap, size_t *pn, unsigned char *sec,
                        size_t scap, size_t *sn, char *err, size_t cap) {
    sqlite3_stmt *q = NULL;
    char aad[64];
    int rc = 1;
    (void)snprintf(aad, sizeof aad, "remote-key:%s", name);
    if (sqlite3_prepare_v2(db, "SELECT public, sealed FROM picu_remote_key WHERE name = ?", -1, &q, NULL) != SQLITE_OK) {
        (void)snprintf(err, cap, "%s", sqlite3_errmsg(db));
        return -1;
    }
    sqlite3_bind_text(q, 1, name, -1, SQLITE_STATIC);
    if (sqlite3_step(q) == SQLITE_ROW) {
        size_t p = (size_t)sqlite3_column_bytes(q, 0), s = (size_t)sqlite3_column_bytes(q, 1);
        rc = -1;
        if (p > pcap || s < PIC_CRED_OVERHEAD || s - PIC_CRED_OVERHEAD > scap) {
            (void)snprintf(err, cap, "the remote key %s is damaged", name);
        } else if (pic_cred_unbox(aad, sqlite3_column_blob(q, 1), s, sec, err, cap) == 0) {
            if (p) {
                memcpy(pub, sqlite3_column_blob(q, 0), p);
            }
            *pn = p;
            *sn = s - PIC_CRED_OVERHEAD;
            rc = 0;
        }
    }
    sqlite3_finalize(q);
    return rc;
}

static int rmt_key_write(sqlite3 *db, const char *name, const unsigned char *pub, size_t pn, const unsigned char *sec,
                         size_t sn, char *err, size_t cap) {
    unsigned char box[64 + PIC_CRED_OVERHEAD];
    sqlite3_stmt *q = NULL;
    char aad[64];
    int rc = -1;
    (void)snprintf(aad, sizeof aad, "remote-key:%s", name);
    if (sn > 64 || pic_cred_box(aad, sec, sn, box, err, cap) != 0) {
        return -1;
    }
    if (sqlite3_prepare_v2(db, "INSERT INTO picu_remote_key(name, public, sealed, created_ms) VALUES(?1, ?2, ?3, ?4)", -1, &q,
                           NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, name, -1, SQLITE_STATIC);
        sqlite3_bind_blob(q, 2, pub, (int)pn, SQLITE_STATIC);
        sqlite3_bind_blob(q, 3, box, (int)(sn + PIC_CRED_OVERHEAD), SQLITE_STATIC);
        sqlite3_bind_int64(q, 4, rmt_wall_ms());
        rc = sqlite3_step(q) == SQLITE_DONE ? 0 : -1;
    }
    if (rc != 0) {
        (void)snprintf(err, cap, "%s", sqlite3_errmsg(db));
    }
    sqlite3_finalize(q);
    pic_cred_wipe(box, sizeof box);
    return rc;
}

/* The three keys, opened; CREATE makes the missing ones (the first /rc). The store must be
 * unlocked. 0; 1 when they do not exist and CREATE is 0; -1 with err. */
static int rmt_keys_load(rmt_keys *k, int create, char *err, size_t cap) {
    sqlite3 *db = pic_userdb(err, cap);
    unsigned char pub[PIC_NOISE_PUB], sec[64];
    size_t pn, sn;
    int rc;
    if (!db) {
        return -1;
    }
    if (create && sqlite3_exec(db, "BEGIN IMMEDIATE", NULL, NULL, NULL) != SQLITE_OK) {
        (void)snprintf(err, cap, "%s", sqlite3_errmsg(db));
        return -1;
    }
    rc = 0;
    {
        static const char *const names[] = {"static", "vapid", "mailbox"};
        for (int i = 0; i < 3 && rc == 0; i++) {
            int got = rmt_key_read(db, names[i], pub, sizeof pub, &pn, sec, sizeof sec, &sn, err, cap);
            if (got < 0) {
                rc = -1;
            } else if (got == 1 && !create) {
                rc = 1;
            } else if (got == 1) { /* made now */
                if (i < 2) {
                    pic_noise_keypair kp;
                    rc = pic_noise_keypair_make(&kp, NULL) == 0 ? 0 : -1;
                    if (rc == 0) {
                        rc = rmt_key_write(db, names[i], kp.pub, sizeof kp.pub, kp.priv, sizeof kp.priv, err, cap);
                        *(i == 0 ? &k->stat : &k->vapid) = kp;
                    } else {
                        (void)snprintf(err, cap, "no entropy for a key");
                    }
                    pic_cred_wipe(&kp, sizeof kp);
                } else if (pic_platform_get()->entropy(k->owner, 32) != 0) {
                    (void)snprintf(err, cap, "no entropy for a key");
                    rc = -1;
                } else {
                    pic_noise_id(k->mailbox, "pic-rc/1 mailbox", k->owner);
                    rc = rmt_key_write(db, names[i], k->mailbox, 16, k->owner, 32, err, cap);
                }
            } else if (i < 2) {
                pic_noise_keypair *kp = i == 0 ? &k->stat : &k->vapid;
                if (sn != 32 || pn != PIC_NOISE_PUB || pic_noise_keypair_make(kp, sec) != 0 || memcmp(kp->pub, pub, pn) != 0) {
                    (void)snprintf(err, cap, "the remote key %s is damaged", names[i]);
                    rc = -1;
                }
            } else {
                unsigned char m[16];
                memcpy(k->owner, sec, 32);
                pic_noise_id(m, "pic-rc/1 mailbox", k->owner);
                if (sn != 32 || pn != 16 || memcmp(m, pub, 16) != 0) {
                    (void)snprintf(err, cap, "the remote key mailbox is damaged");
                    rc = -1;
                }
                memcpy(k->mailbox, m, 16);
            }
        }
    }
    pic_cred_wipe(sec, sizeof sec);
    if (create) {
        (void)sqlite3_exec(db, rc == 0 ? "COMMIT" : "ROLLBACK", NULL, NULL, NULL);
    }
    return rc;
}

static void rmt_device_aad(const unsigned char id[16], char out[64]) {
    char hex[33];
    rmt_hex(id, 16, hex);
    (void)snprintf(out, 64, "remote-device:%s", hex);
}

/* Every device row that opens under the store's key, oldest first: *OUT (malloc'd) and *N. A row
 * that does not open is not a device, and is counted in *BAD. 0, or -1 with err. */
static int rmt_devices_load(rmt_device **out, int *n, int *bad, char *err, size_t cap) {
    sqlite3 *db = pic_userdb(err, cap);
    sqlite3_stmt *q = NULL;
    rmt_device *list = NULL;
    int count = 0, room = 0;
    *out = NULL;
    *n = 0;
    if (bad) {
        *bad = 0;
    }
    if (!db || sqlite3_prepare_v2(db, "SELECT id, sealed, paired_ms, coalesce(seen_ms, 0) FROM picu_remote_device ORDER BY paired_ms",
                                  -1, &q, NULL) != SQLITE_OK) {
        if (db) {
            (void)snprintf(err, cap, "%s", sqlite3_errmsg(db));
        }
        return -1;
    }
    while (sqlite3_step(q) == SQLITE_ROW) {
        rmt_device d;
        char aad[64], *plain, *name = NULL, *stat = NULL, *chan = NULL, *push = NULL;
        size_t sn = (size_t)sqlite3_column_bytes(q, 1);
        int ok = 0;
        memset(&d, 0, sizeof d);
        if (sqlite3_column_bytes(q, 0) != 16 || sn < PIC_CRED_OVERHEAD + 2 || sn > 65536 + PIC_CRED_OVERHEAD) {
            if (bad) {
                (*bad)++;
            }
            continue;
        }
        memcpy(d.id, sqlite3_column_blob(q, 0), 16);
        rmt_device_aad(d.id, aad);
        if (!(plain = malloc(sn - PIC_CRED_OVERHEAD + 1))) {
            break;
        }
        if (pic_cred_unbox(aad, sqlite3_column_blob(q, 1), sn, plain, err, cap) == 0) {
            plain[sn - PIC_CRED_OVERHEAD] = '\0';
            name = rmt_q("SELECT json_extract(?1, '$.name')", 1, plain);
            stat = rmt_q("SELECT json_extract(?1, '$.static')", 1, plain);
            chan = rmt_q("SELECT json_extract(?1, '$.channel')", 1, plain);
            push = rmt_q("SELECT CASE json_type(?1, '$.push') WHEN 'object' THEN json_extract(?1, '$.push') END", 1, plain);
            ok = name && stat && chan && pic_b64u_dec(stat, strlen(stat), d.stat, sizeof d.stat) == PIC_NOISE_PUB &&
                 pic_b64u_dec(chan, strlen(chan), d.channel, sizeof d.channel) == 16;
            if (ok) {
                (void)snprintf(d.name, sizeof d.name, "%s", name);
            }
            if (ok && push) { /* a subscription that does not read is none */
                char *ep = rmt_q("SELECT json_extract(?1, '$.endpoint')", 1, push);
                char *pk = rmt_q("SELECT json_extract(?1, '$.p256dh')", 1, push);
                char *au = rmt_q("SELECT json_extract(?1, '$.auth')", 1, push);
                char *nt = rmt_q("SELECT json_extract(?1, '$.notify')", 1, push);
                if (ep && pk && au && nt && strlen(ep) < sizeof d.endpoint && (!strcmp(nt, "all") || !strcmp(nt, "remote")) &&
                    pic_b64u_dec(pk, strlen(pk), d.p256dh, sizeof d.p256dh) == PIC_WEBPUSH_PUB &&
                    pic_b64u_dec(au, strlen(au), d.auth, sizeof d.auth) == PIC_WEBPUSH_AUTH) {
                    (void)snprintf(d.endpoint, sizeof d.endpoint, "%s", ep);
                    (void)snprintf(d.notify, sizeof d.notify, "%s", nt);
                }
                free(ep);
                free(pk);
                free(au);
                free(nt);
            }
            pic_cred_wipe(plain, sn - PIC_CRED_OVERHEAD);
        }
        free(plain);
        free(name);
        free(stat);
        free(chan);
        free(push);
        if (!ok) {
            if (bad) {
                (*bad)++;
            }
            continue;
        }
        d.paired_ms = sqlite3_column_int64(q, 2);
        d.seen_ms = sqlite3_column_int64(q, 3);
        if (count == room) {
            rmt_device *grown = realloc(list, (size_t)(room = room ? room * 2 : 8) * sizeof *grown);
            if (!grown) {
                break;
            }
            list = grown;
        }
        list[count++] = d;
    }
    sqlite3_finalize(q);
    *out = list;
    *n = count;
    return 0;
}

/* D's row sealed: a new one (ADD), or the existing one's sealed column replaced. 0, or -1 with err. */
static int rmt_device_write(const rmt_device *d, int add, char *err, size_t cap) {
    sqlite3 *db = pic_userdb(err, cap);
    sqlite3_stmt *q = NULL;
    char aad[64], stat[100], chan[32], pk[100], au[32], *json;
    unsigned char *box;
    size_t n;
    int rc = -1;
    if (!db) {
        return -1;
    }
    pic_b64u_enc(d->stat, sizeof d->stat, stat);
    pic_b64u_enc(d->channel, sizeof d->channel, chan);
    pic_b64u_enc(d->p256dh, sizeof d->p256dh, pk);
    pic_b64u_enc(d->auth, sizeof d->auth, au);
    if (!(json = rmt_q("SELECT json_object('name', ?1, 'static', ?2, 'channel', ?3, 'push', CASE WHEN ?7 = '' THEN json('null')"
                       " ELSE json_object('endpoint', ?4, 'p256dh', ?5, 'auth', ?6, 'notify', ?7) END)",
                       7, d->name, stat, chan, d->endpoint, pk, au, d->notify))) {
        (void)snprintf(err, cap, "out of memory");
        return -1;
    }
    n = strlen(json);
    rmt_device_aad(d->id, aad);
    if ((box = malloc(n + PIC_CRED_OVERHEAD)) && pic_cred_box(aad, json, n, box, err, cap) == 0 &&
        sqlite3_prepare_v2(db,
                           add ? "INSERT INTO picu_remote_device(id, sealed, paired_ms) VALUES(?1, ?2, ?3)"
                               : "UPDATE picu_remote_device SET sealed = ?2 WHERE id = ?1",
                           -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_blob(q, 1, d->id, 16, SQLITE_STATIC);
        sqlite3_bind_blob(q, 2, box, (int)(n + PIC_CRED_OVERHEAD), SQLITE_STATIC);
        if (add) {
            sqlite3_bind_int64(q, 3, rmt_wall_ms());
        }
        rc = sqlite3_step(q) == SQLITE_DONE ? 0 : -1;
        if (rc != 0) {
            (void)snprintf(err, cap, "%s", sqlite3_errmsg(db));
        }
    }
    sqlite3_finalize(q);
    if (box) {
        pic_cred_wipe(box, n + PIC_CRED_OVERHEAD);
    }
    free(box);
    pic_cred_wipe(json, n);
    free(json);
    return rc;
}

static int rmt_device_add(const rmt_device *d, char *err, size_t cap) { return rmt_device_write(d, 1, err, cap); }

static void rmt_device_seen(const unsigned char id[16]) {
    sqlite3 *db = pic_userdb(NULL, 0);
    sqlite3_stmt *q = NULL;
    if (db && sqlite3_prepare_v2(db, "UPDATE picu_remote_device SET seen_ms = ?2 WHERE id = ?1", -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_blob(q, 1, id, 16, SQLITE_STATIC);
        sqlite3_bind_int64(q, 2, rmt_wall_ms());
        (void)sqlite3_step(q);
    }
    sqlite3_finalize(q);
}

static void rmt_device_delete(const unsigned char id[16]) {
    sqlite3 *db = pic_userdb(NULL, 0);
    sqlite3_stmt *q = NULL;
    if (db && sqlite3_prepare_v2(db, "DELETE FROM picu_remote_device WHERE id = ?1", -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_blob(q, 1, id, 16, SQLITE_STATIC);
        (void)sqlite3_step(q);
    }
    sqlite3_finalize(q);
}

/* ---- the relay's API (section 6) ------------------------------------------------- */

typedef struct {
    char base[512];   /* https://host[:port], no trailing slash */
    char invite[512]; /* the setting remote.invite, or "" */
    char owner[64];   /* b64u(owner token) */
    char mbx[32];     /* b64u(mailbox id) */
    pic_net *net;
    int peer;         /* the last POST's Pic-Peer: 1, 0, or -1 when it had none */
    int last_status;  /* the last call's HTTP status, 0 when it got no answer */
    char ack[24];     /* Pic-Ack for the mailbox stream, sent with each call while set */
    int acked;        /* a call carried it and the relay took it */
} rmt_relay;

static void rmt_relay_init(rmt_relay *r, const rmt_keys *k) {
    char *v = pic_setting("remote.relay");
    size_t n;
    memset(r, 0, sizeof *r);
    (void)snprintf(r->base, sizeof r->base, "%s", v && *v ? v : PIC_REMOTE_RELAY);
    free(v);
    n = strlen(r->base);
    while (n && r->base[n - 1] == '/') {
        r->base[--n] = '\0';
    }
    v = pic_setting("remote.invite");
    (void)snprintf(r->invite, sizeof r->invite, "%s", v ? v : "");
    free(v);
    if (k) {
        pic_b64u_enc(k->owner, 32, r->owner);
        pic_b64u_enc(k->mailbox, 16, r->mbx);
    }
}

typedef struct {
    char *buf;
    size_t len, cap;
} rmt_buf;

static int rmt_buf_add(rmt_buf *b, const void *p, size_t n) {
    if (b->len + n + 1 > b->cap) {
        size_t cap = b->cap ? b->cap : 1024;
        char *grown;
        while (cap < b->len + n + 1) {
            cap *= 2;
        }
        if (!(grown = realloc(b->buf, cap))) {
            return -1;
        }
        b->buf = grown;
        b->cap = cap;
    }
    memcpy(b->buf + b->len, p, n);
    b->len += n;
    b->buf[b->len] = '\0';
    return 0;
}

static int rmt_collect(void *ctx, const char *bytes, size_t n) {
    rmt_buf *b = ctx;
    return b->len + n > 65536 ? 0 : rmt_buf_add(b, bytes, n) == 0 ? 0 : 1;
}

/* METHOD PATH (after the base) with the bearer token AUTH (b64u) and BODY: the status, the
 * response body in *RESP (malloc'd, may be NULL), or -1 with err. */
static int rmt_call(rmt_relay *r, const char *method, const char *path, const char *auth, const char *body, size_t n,
                    const char *ctype, char **resp, char *err, size_t cap) {
    char url[1024], ah[128], ch[128], ih[600], kh[48];
    const char *hdrs[4];
    size_t nh = 0;
    pic_http_resp hr;
    rmt_buf b = {NULL, 0, 0};
    int rc;
    if (resp) {
        *resp = NULL;
    }
    if (!r->net && !(r->net = pic_net_new(err, cap))) {
        return -1;
    }
    (void)snprintf(url, sizeof url, "%s%s", r->base, path);
    (void)snprintf(ah, sizeof ah, "Authorization: Bearer %s", auth);
    hdrs[nh++] = ah;
    if (ctype) {
        (void)snprintf(ch, sizeof ch, "Content-Type: %s", ctype);
        hdrs[nh++] = ch;
    }
    if (r->invite[0] && strcmp(method, "PUT") == 0 && strchr(path + 6, '/') == NULL) {
        (void)snprintf(ih, sizeof ih, "Pic-Invite: %s", r->invite);
        hdrs[nh++] = ih;
    }
    if (r->ack[0]) {
        (void)snprintf(kh, sizeof kh, "Pic-Ack: %s", r->ack);
        hdrs[nh++] = kh;
    }
    pic_http_resp_init(&hr, rmt_collect, &b);
    rc = pic_http_request(r->net, method, url, hdrs, nh, body, n, &hr, 15, 30, err, cap);
    pic_cred_wipe(ah, sizeof ah);
    r->peer = hr.peer[0] == '1' ? 1 : hr.peer[0] == '0' ? 0 : -1;
    r->last_status = rc != 0 ? 0 : hr.status;
    r->acked |= r->ack[0] && rc == 0 && hr.status >= 200 && hr.status < 300;
    if (rc != 0) {
        free(b.buf);
        return -1;
    }
    if (resp) {
        *resp = b.buf;
    } else {
        free(b.buf);
    }
    return hr.status;
}

static int rmt_put_mailbox(rmt_relay *r, char *err, size_t cap) {
    char path[128];
    int st;
    (void)snprintf(path, sizeof path, "/v1/m/%s", r->mbx);
    st = rmt_call(r, "PUT", path, r->owner, "", 0, "application/json", NULL, err, cap);
    if (st >= 200 && st < 300) {
        return 0;
    }
    if (st > 0) {
        if (st == 403) {
            (void)snprintf(err, cap, "the relay %s makes mailboxes by invitation: set it with pic settings remote.invite INVITE",
                           r->base);
        } else if (st == 429) {
            (void)snprintf(err, cap, "the relay %s refused a new mailbox for now (HTTP 429): try again later", r->base);
        } else {
            (void)snprintf(err, cap, "the relay %s refused the mailbox (HTTP %d)", r->base, st);
        }
    }
    return -1;
}

static int rmt_put_channel(rmt_relay *r, const unsigned char ch[16], int pair, char *err, size_t cap) {
    char path[128], id[32];
    const char *body = pair ? "{\"kind\":\"pair\",\"ttl\":600}" : "{\"kind\":\"device\"}";
    int st;
    pic_b64u_enc(ch, 16, id);
    (void)snprintf(path, sizeof path, "/v1/m/%s/c/%s", r->mbx, id);
    st = rmt_call(r, "PUT", path, r->owner, body, strlen(body), "application/json", NULL, err, cap);
    if (st >= 200 && st < 300) {
        return 0;
    }
    if (st > 0) {
        (void)snprintf(err, cap, st == 409 ? "the relay holds at most 8 phones for one computer: unpair one first (pic remote devices)"
                                 : "the relay refused a channel (HTTP %d)",
                       st);
    }
    return -1;
}

static void rmt_delete_channel(rmt_relay *r, const unsigned char ch[16]) {
    char path[128], id[32], err[256];
    pic_b64u_enc(ch, 16, id);
    (void)snprintf(path, sizeof path, "/v1/m/%s/c/%s", r->mbx, id);
    (void)rmt_call(r, "DELETE", path, r->owner, NULL, 0, NULL, NULL, err, sizeof err);
}

/* ---- the stream thread (section 3) --------------------------------------------------- */

/* What the thread writes to the loop's pipe: a kind, the channel, a length, then the record. */
enum { RMT_EV_FRAME = 'F', RMT_EV_GONE = 'G', RMT_EV_REPLACED = 'R', RMT_EV_REFUSED = 'X', RMT_EV_PEER = 'P' };

/* The stream's state, for pic remote status: set by the thread, read by the loop. */
enum { RMT_CONN_CONNECTING, RMT_CONN_CONNECTED, RMT_CONN_WAITING };

typedef struct {
    char url[1024];
    char auth[128];
    int mailbox; /* the mailbox stream: data is b64u(C).b64u(record) */
    unsigned char channel[16];
    int wfd;
    char last[64];
    pthread_t th;
    int started;
    atomic_int kick;      /* the loop saw a wake: drop this connection and reconnect at once */
    atomic_int state;     /* RMT_CONN_* */
    atomic_int attempts;  /* failed connections since the last one that worked */
    atomic_llong retry_at; /* wall ms of the next try while waiting */
    char why[256];        /* the last failure, written before state changes */
    /* what the mailbox stream has read: the last event id, and records and bytes so far */
    atomic_llong read_id, read_records, read_bytes;
    atomic_llong heard_ms; /* mono ms of the last record, or of the connection when none came yet */
    int asked;             /* this connection was dropped for a kick (the stream's thread only) */
    /* A pairing channel's stream in pic remote: told to quit when its offer ends, and freed by
     * whichever of the loop and the thread lets go of it last. */
    atomic_int quit;
    atomic_int refs; /* 2 while both hold it; 0 for a stream that is not on the heap */
} rmt_stream;

/* Two streams may write one pipe (pic remote's mailbox stream and an offer's): an event is
 * written whole under this lock. */
static pthread_mutex_t rmt_pipe_mu = PTHREAD_MUTEX_INITIALIZER;

static void rmt_stream_put(rmt_stream *s, int kind, const unsigned char ch[16], const unsigned char *rec, size_t n) {
    unsigned char head[19];
    head[0] = (unsigned char)kind;
    memcpy(head + 1, ch, 16);
    head[17] = (unsigned char)(n >> 8);
    head[18] = (unsigned char)n;
    pthread_mutex_lock(&rmt_pipe_mu);
    if (write(s->wfd, head, sizeof head) != (ssize_t)sizeof head || (n && write(s->wfd, rec, n) != (ssize_t)n)) {
        rmt_stop = 1;
    }
    pthread_mutex_unlock(&rmt_pipe_mu);
}

/* Lets go of a heap stream: the last of the loop and its thread to do so frees it. */
static void rmt_stream_release(rmt_stream *s) {
    if (s && atomic_fetch_sub(&s->refs, 1) == 1) {
        free(s);
    }
}

static int rmt_on_event(void *ctx, const char *event, const char *data, size_t len) {
    rmt_stream *s = ((void **)ctx)[0];
    pic_sse *p = ((void **)ctx)[1];
    if (strcmp(event, "frame") == 0) {
        unsigned char ch[16], rec[PIC_NOISE_RECORD_CAP];
        const char *dot = s->mailbox ? memchr(data, '.', len) : NULL;
        const char *r = dot ? dot + 1 : data;
        long n;
        memcpy(ch, s->channel, 16);
        if (s->mailbox && (!dot || pic_b64u_dec(data, (size_t)(dot - data), ch, 16) != 16)) {
            return 0;
        }
        n = pic_b64u_dec(r, len - (size_t)(r - data), rec, sizeof rec);
        if (n > 0) {
            rmt_stream_put(s, RMT_EV_FRAME, ch, rec, (size_t)n);
        }
        (void)snprintf(s->last, sizeof s->last, "%s", p->last_id);
        if (s->mailbox) {
            atomic_store(&s->read_id, strtoll(p->last_id, NULL, 10));
            atomic_fetch_add(&s->read_records, 1);
            atomic_fetch_add(&s->read_bytes, (long long)len);
            atomic_store(&s->heard_ms, rmt_mono_ms());
        }
    } else if (strcmp(event, "gone") == 0) {
        rmt_stream_put(s, RMT_EV_GONE, s->channel, NULL, 0);
        return 1;
    } else if (strcmp(event, "replaced") == 0) {
        rmt_stream_put(s, RMT_EV_REPLACED, s->channel, NULL, 0);
        return 1;
    } else if (strcmp(event, "peer") == 0) { /* "1" or "0"; "C.1" or "C.0" on the mailbox stream */
        unsigned char ch[16], on;
        const char *dot = s->mailbox ? memchr(data, '.', len) : NULL;
        memcpy(ch, s->channel, 16);
        if (s->mailbox && (!dot || pic_b64u_dec(data, (size_t)(dot - data), ch, 16) != 16)) {
            return 0;
        }
        on = (unsigned char)(dot ? dot + 1 < data + len && dot[1] == '1' : len && data[0] == '1');
        rmt_stream_put(s, RMT_EV_PEER, ch, &on, 1);
    }
    return 0;
}

static int rmt_stream_body(void *ctx, const char *bytes, size_t n) {
    rmt_stream *s = ((void **)ctx)[0];
    pic_sse *p = ((void **)ctx)[1];
    int rc;
    if (atomic_exchange(&s->kick, 0) || atomic_load(&s->quit)) {
        s->asked = 1;
        return 1; /* a wake: this connection may be a ghost; a new one resumes from Last-Event-ID */
    }
    if (atomic_load(&s->state) != RMT_CONN_CONNECTED) {
        atomic_store(&s->attempts, 0);
        atomic_store(&s->state, RMT_CONN_CONNECTED);
    }
    rc = pic_sse_feed(p, bytes, n);
    return rc < 0 ? 1 : rc;
}

/* A 200 to the stream's GET is a connection, though the relay may say nothing for 15 s. */
static int rmt_stream_head(void *ctx, const pic_http_resp *r) {
    rmt_stream *s = ((void **)ctx)[0];
    if (r->status == 200) {
        atomic_store(&s->heard_ms, rmt_mono_ms());
    }
    if (r->status == 200 && atomic_load(&s->state) != RMT_CONN_CONNECTED) {
        atomic_store(&s->attempts, 0);
        atomic_store(&s->state, RMT_CONN_CONNECTED);
    }
    return 0;
}

static int rmt_idle_s(void) {
#ifdef PIC_FAULTS
    if (getenv("PIC_TEST_RC_IDLE")) { /* the soak test's seam: a dead stream noticed in seconds */
        return atoi(getenv("PIC_TEST_RC_IDLE"));
    }
#endif
    return RMT_IDLE_S;
}

static long long rmt_quiet_ms(void) {
#ifdef PIC_FAULTS
    if (getenv("PIC_TEST_RC_QUIET_MS")) { /* the tests' seam: a stream bringing no records dropped in seconds */
        return atoll(getenv("PIC_TEST_RC_QUIET_MS"));
    }
#endif
    return RMT_QUIET_MS;
}

/* Reconnects with Last-Event-ID after 1 s, doubling to 60, each wait varied by a fifth either way;
 * a connection that lasted 30 s resets the wait, a wake (the loop's kick) skips it, and none lasts
 * more than 15 minutes. A connection with no byte for RMT_IDLE_S (the relay comments every 15 s)
 * is taken for dead. */
static void *rmt_stream_main(void *arg) {
    rmt_stream *s = arg;
    long long wait = 1000;
    char err[256];
    pic_net *net = pic_net_new(err, sizeof err);
    while (!rmt_stop && !atomic_load(&s->quit) && net) {
        char ah[160], lh[100];
        const char *hdrs[3] = {ah, "Accept: text/event-stream", lh};
        pic_sse p;
        pic_http_resp r;
        void *ctx[2] = {s, &p};
        long long t0 = rmt_mono_ms();
        int rc;
        (void)snprintf(ah, sizeof ah, "Authorization: Bearer %s", s->auth);
        (void)snprintf(lh, sizeof lh, "Last-Event-ID: %s", s->last);
        if (pic_sse_init(&p, 65536, 2 * PIC_NOISE_RECORD_CAP + 64, rmt_on_event, ctx) != 0) {
            break;
        }
        pic_http_resp_init(&r, rmt_stream_body, ctx);
        r.on_head = rmt_stream_head;
        atomic_store(&s->state, RMT_CONN_CONNECTING);
        s->asked = 0;
        rc = pic_http_get(net, s->url, hdrs, s->last[0] ? 3 : 2, &r, rmt_idle_s(), 900, err, sizeof err);
        pic_sse_free(&p);
        if (s->asked) {
            (void)snprintf(s->why, sizeof s->why, "asked to reconnect");
        } else if (rc != 0) {
            (void)snprintf(s->why, sizeof s->why, "%s", err);
        } else if (r.status != 200) {
            (void)snprintf(s->why, sizeof s->why, "the relay answered HTTP %d", r.status);
        } else {
            (void)snprintf(s->why, sizeof s->why, "the relay ended the stream");
        }
        if (r.status == 401 || r.status == 404) { /* no mailbox or channel: nothing to wait for */
            unsigned char st[2] = {(unsigned char)(r.status >> 8), (unsigned char)r.status};
            rmt_stream_put(s, RMT_EV_REFUSED, s->channel, st, 2);
            break;
        }
        if (rmt_mono_ms() - t0 >= 30000) {
            wait = 1000;
        }
        atomic_fetch_add(&s->attempts, 1);
        {
            unsigned char j;
            long long w;
            (void)pic_platform_get()->entropy(&j, 1);
            w = wait - wait / 5 + (long long)j * (2 * wait / 5) / 255;
            atomic_store(&s->retry_at, rmt_wall_ms() + w);
            atomic_store(&s->state, RMT_CONN_WAITING);
            if (s->mailbox && !rmt_stop) {
                rmt_log(stdout, "pic remote: the stream ended (%s); reconnecting in %.1f s\n", s->why, (double)w / 1000);
            }
            for (long long t = 0; t < w && !rmt_stop && !atomic_load(&s->quit); t += 50) {
                struct timespec ts = {0, 50000000L};
                if (atomic_exchange(&s->kick, 0)) {
                    wait = 500; /* doubled below: the next wait after this try is a second */
                    break;
                }
                (void)nanosleep(&ts, NULL);
            }
        }
        wait = wait * 2 > RMT_BACKOFF_MAX_MS ? RMT_BACKOFF_MAX_MS : wait * 2;
    }
    if (net) {
        pic_net_free(net);
    }
    if (atomic_load(&s->refs)) {
        rmt_stream_release(s);
    }
    return NULL;
}

static int rmt_stream_start(rmt_stream *s, int wfd) {
    sigset_t all, was;
    int rc;
    s->wfd = wfd;
    sigfillset(&all);
    pthread_sigmask(SIG_BLOCK, &all, &was); /* signals are the loop's */
    rc = pthread_create(&s->th, NULL, rmt_stream_main, s);
    pthread_sigmask(SIG_SETMASK, &was, NULL);
    s->started = rc == 0;
    return rc == 0 ? 0 : -1;
}

/* Reads one whole event from the pipe: 1 with it, 0 when none is ready, -1 at its end. */
static int rmt_pipe_read(int fd, int *kind, unsigned char ch[16], unsigned char *rec, size_t *n) {
    unsigned char head[19];
    ssize_t got = read(fd, head, sizeof head);
    size_t len, have = 0;
    if (got < 0 && (errno == EAGAIN || errno == EINTR)) {
        return 0;
    }
    if (got <= 0) {
        return -1;
    }
    while ((size_t)got < sizeof head) { /* the rest is on its way: the writer writes it at once */
        ssize_t more = read(fd, head + got, sizeof head - (size_t)got);
        if (more > 0) {
            got += more;
        } else if (more == 0 || (errno != EAGAIN && errno != EINTR)) {
            return -1;
        }
    }
    len = ((size_t)head[17] << 8) | head[18];
    while (have < len) {
        ssize_t more = read(fd, rec + have, len - have);
        if (more > 0) {
            have += (size_t)more;
        } else if (more == 0 || (errno != EAGAIN && errno != EINTR)) {
            return -1;
        }
    }
    *kind = head[0];
    memcpy(ch, head + 1, 16);
    *n = len;
    return 1;
}

/* ---- lanes: what waits to be posted to a channel's down lane --------------------------- */

typedef struct {
    unsigned char ch[16];
    unsigned char *q; /* records, each as ms (8), length (2), bytes */
    size_t qlen, qcap;
    long long retry_ms;
} rmt_lane;

static int rmt_lane_add(rmt_lane *l, const unsigned char *rec, size_t n) {
    long long now = rmt_mono_ms();
    if (l->qlen + n + 10 > l->qcap) {
        size_t cap = l->qcap ? l->qcap : 65536;
        unsigned char *grown;
        while (cap < l->qlen + n + 10) {
            cap *= 2;
        }
        if (cap > (64u << 20) || !(grown = realloc(l->q, cap))) {
            return -1;
        }
        l->q = grown;
        l->qcap = cap;
    }
    for (int i = 0; i < 8; i++) {
        l->q[l->qlen + (size_t)i] = (unsigned char)((unsigned long long)now >> (8 * (7 - i)));
    }
    l->q[l->qlen + 8] = (unsigned char)(n >> 8);
    l->q[l->qlen + 9] = (unsigned char)n;
    memcpy(l->q + l->qlen + 10, rec, n);
    l->qlen += n + 10;
    return 0;
}

/* After a sleep or a stop: what waits was queued before it, not 30 s ago in waking time; it is
 * posted now rather than dropped, and the next post is not held back. */
static void rmt_lane_restamp(rmt_lane *l) {
    long long now = rmt_mono_ms();
    for (size_t at = 0; at < l->qlen;) {
        size_t n = ((size_t)l->q[at + 8] << 8) | l->q[at + 9];
        for (int i = 0; i < 8; i++) {
            l->q[at + (size_t)i] = (unsigned char)((unsigned long long)now >> (8 * (7 - i)));
        }
        at += 10 + n;
    }
    l->retry_ms = 0;
}

/* One post of what waits (32 records, 256 KiB at most); records older than 30 s are dropped
 * unsent, which the phone sees as a gap. 0, or -1 when the post failed (kept for later). */
static int rmt_lane_flush(rmt_relay *r, rmt_lane *l) {
    long long now = rmt_mono_ms();
    rmt_buf body = {NULL, 0, 0};
    size_t at = 0, sent_to = 0;
    int nrec = 0, st;
    char path[128], id[32], err[256];
    if (!l->qlen || now < l->retry_ms) {
        return 0;
    }
    while (at < l->qlen) { /* the stale ones first */
        long long ms = 0;
        size_t n = ((size_t)l->q[at + 8] << 8) | l->q[at + 9];
        for (int i = 0; i < 8; i++) {
            ms = (ms << 8) | l->q[at + (size_t)i];
        }
        if (now - ms < RMT_POST_WAIT_MS) {
            break;
        }
        at += 10 + n;
    }
    if (at) {
        memmove(l->q, l->q + at, l->qlen - at);
        l->qlen -= at;
        at = 0;
    }
    while (at < l->qlen && nrec < RMT_POST_RECORDS) {
        size_t n = ((size_t)l->q[at + 8] << 8) | l->q[at + 9];
        if (body.len + n + 2 > RMT_POST_BYTES) {
            break;
        }
        if (rmt_buf_add(&body, l->q + at + 8, n + 2) != 0) {
            free(body.buf);
            return -1;
        }
        at += 10 + n;
        nrec++;
    }
    sent_to = at;
    if (!nrec) {
        return 0;
    }
    pic_b64u_enc(l->ch, 16, id);
    (void)snprintf(path, sizeof path, "/v1/m/%s/c/%s/down", r->mbx, id);
    st = rmt_call(r, "POST", path, r->owner, body.buf, body.len, "application/octet-stream", NULL, err, sizeof err);
    free(body.buf);
    if (st >= 200 && st < 300) {
        memmove(l->q, l->q + sent_to, l->qlen - sent_to);
        l->qlen -= sent_to;
        l->retry_ms = 0;
        return 0;
    }
    if (st == 404 || st == 401) { /* the channel is gone: nobody can read these */
        l->qlen = 0;
        return -1;
    }
    l->retry_ms = now + 1000;
    return -1;
}

/* ---- sessions (section 3) --------------------------------------------------------------- */

typedef struct {
    int used, confirmed;
    int fails;          /* records in a row that did not open */
    int dev;            /* index of its device */
    unsigned char ch[16];
    pic_noise_transport t;
    long long started_ms, heard_ms, reset_ms, bye_ms;
    rmt_buf msg; /* a message being assembled from its records */
} rmt_sess;

/* Equal in time that does not depend on where they differ. */
static int rmt_same(const unsigned char *a, const unsigned char *b, size_t n) {
    volatile unsigned char d = 0;
    for (size_t i = 0; i < n; i++) {
        d |= a[i] ^ b[i];
    }
    return d == 0;
}

/* How often a connected phone's seen_ms is written again: "last seen" is now, give or take this. */
#define RMT_SEEN_MS 30000
static long long rmt_seen_every_ms(void) {
#ifdef PIC_FAULTS
    if (getenv("PIC_TEST_RC_SEEN_MS")) { /* the tests' seam: written again after a fraction of a second */
        return atoll(getenv("PIC_TEST_RC_SEEN_MS"));
    }
#endif
    return RMT_SEEN_MS;
}

static long long rmt_rekey_ms(void) {
#ifdef PIC_FAULTS
    if (getenv("PIC_TEST_RC_REKEY_MS")) { /* the tests' seam: a session asked to start again in seconds */
        return atoll(getenv("PIC_TEST_RC_REKEY_MS"));
    }
#endif
    return RMT_REKEY_MS;
}

/* An envelope message to a session: records of 16383 bytes at most, the last flagged 0x01. */
static int rmt_sess_send(rmt_sess *s, rmt_lane *l, const char *json) {
    size_t n = strlen(json), at = 0;
    unsigned char rec[PIC_NOISE_RECORD_CAP];
    do {
        size_t part = n - at > PIC_NOISE_CHUNK ? PIC_NOISE_CHUNK : n - at;
        size_t rn = pic_noise_record(&s->t, at + part == n, json + at, part, rec);
        if (rmt_lane_add(l, rec, rn) != 0) {
            return -1;
        }
        at += part;
    } while (at < n);
    return 0;
}

/* Feeds a transport record's plaintext to S: 1 with a whole message in S->msg, 0 when more
 * follows, -1 when it was too long. A gap inside a message discards the part received. */
static int rmt_sess_take(rmt_sess *s, int flag, const unsigned char *data, size_t n, int gap) {
    if (gap) {
        s->msg.len = 0;
    }
    if (s->msg.len + n > RMT_MSG_CAP) {
        s->msg.len = 0;
        return -1;
    }
    if (rmt_buf_add(&s->msg, data, n) != 0) {
        return -1;
    }
    return flag == 1;
}

/* ---- an offer (section 2): its pairing channel, its one handshake, and the yes or no ------------- */

static void rmt_prologue(const unsigned char mailbox[16], const unsigned char ch[16], unsigned char out[41]) {
    memcpy(out, "pic-rc/1", 8);
    out[8] = 0;
    memcpy(out + 9, mailbox, 16);
    memcpy(out + 25, ch, 16);
}

/* A phone's name, for a terminal: each control character (C0, DEL, C1), bidi control and byte
 * that is not UTF-8 becomes '?', in place. */
static void rmt_name_clean(char *s) {
    const unsigned char *in = (const unsigned char *)s;
    char *out = s;
    while (*in) {
        unsigned cp = *in;
        size_t len = 1, k;
        if (cp >= 0xc2 && cp <= 0xdf) {
            len = 2, cp &= 0x1f;
        } else if (cp >= 0xe0 && cp <= 0xef) {
            len = 3, cp &= 0x0f;
        } else if (cp >= 0xf0 && cp <= 0xf4) {
            len = 4, cp &= 0x07;
        } else if (cp >= 0x80) {
            len = 0; /* a stray continuation byte or an invalid lead */
        }
        for (k = 1; k < len; k++) {
            if ((in[k] & 0xc0) != 0x80) {
                break;
            }
            cp = (cp << 6) | (in[k] & 0x3f);
        }
        if (len == 0 || k < len || (len == 3 && cp < 0x800) || (len == 4 && (cp < 0x10000 || cp > 0x10ffff)) ||
            (cp >= 0xd800 && cp <= 0xdfff) || cp < 0x20 || (cp >= 0x7f && cp <= 0x9f) || cp == 0x061c || cp == 0x200e ||
            cp == 0x200f || (cp >= 0x202a && cp <= 0x202e) || (cp >= 0x2066 && cp <= 0x2069)) {
            *out++ = '?';
            in += len && k == len ? len : 1;
            continue;
        }
        memmove(out, in, len);
        out += len;
        in += len;
    }
    *out = '\0';
}

/* One offer: made by /rc (pic remote pair) or for a paired phone (pic remote), answered by the
 * person there or by that phone. */
enum { OFFER_OPEN, OFFER_SHAKEN, OFFER_ASKING, OFFER_OVER };
enum { OFFER_EV_NONE, OFFER_EV_ASK, OFFER_EV_FAILED };

typedef struct {
    int stage;
    unsigned char P[16], psk[32], prologue[41], sid[8];
    unsigned char m1[PIC_NOISE_RECORD_CAP], m2rec[600];
    size_t m1n, m2n;
    int fails, again, said;
    char url[1024], vapid[100], host[256];
    long long expires, mono_end; /* Unix seconds; the monotonic ms it ends at */
    pic_noise_transport t;
    rmt_device d; /* the device asking: its id (chosen here), name, static key and channel */
    char sas[7];
    rmt_lane lane;
    rmt_buf msg;
} rmt_offer;

/* Makes the secret, registers the pairing channel and builds the QR code's address. */
static int rmt_offer_open(rmt_offer *o, rmt_relay *r, const rmt_keys *k, int ttl, char *err, size_t cap) {
    unsigned char ps[32], ptok[32], offer[PIC_NOISE_OFFER];
    char b64[200];
    memset(o, 0, sizeof *o);
    if (pic_platform_get()->entropy(ps, sizeof ps) != 0 || pic_platform_get()->entropy(o->d.id, sizeof o->d.id) != 0) {
        (void)snprintf(err, cap, "no entropy");
        return -1;
    }
    pic_noise_pair_derive(ps, o->psk, ptok, o->P);
    pic_cred_wipe(ptok, sizeof ptok);
    memcpy(o->lane.ch, o->P, 16);
    if (rmt_put_channel(r, o->P, 1, err, cap) != 0) {
        pic_cred_wipe(ps, sizeof ps);
        pic_cred_wipe(o->psk, sizeof o->psk);
        return -1;
    }
    o->expires = rmt_wall_ms() / 1000 + ttl;
    o->mono_end = rmt_mono_ms() + 1000LL * ttl;
    pic_noise_offer(k->mailbox, k->stat.pub, ps, (uint64_t)o->expires, offer);
    pic_b64u_enc(offer, sizeof offer, b64);
    (void)snprintf(o->url, sizeof o->url, "%s/#p1.%s", r->base, b64);
    pic_cred_wipe(ps, sizeof ps);
    pic_cred_wipe(offer, sizeof offer);
    pic_cred_wipe(b64, sizeof b64);
    (void)gethostname(o->host, sizeof o->host - 1);
    rmt_prologue(k->mailbox, o->P, o->prologue);
    pic_b64u_enc(k->vapid.pub, sizeof k->vapid.pub, o->vapid);
    return 0;
}

/* A record from the pairing channel's up lane: OFFER_EV_ASK once the device has made the handshake
 * and sent pair_ready (its name in o->d.name, the six digits in o->sas), OFFER_EV_FAILED when too
 * many first messages failed to verify. */
static int rmt_offer_frame(rmt_offer *o, rmt_relay *r, const rmt_keys *k, const unsigned char *rec, size_t n) {
    unsigned char pl[1024], m2[512];
    size_t pn, mn;
    if (n <= 9 || o->stage == OFFER_OVER) {
        return OFFER_EV_NONE;
    }
    if (rec[0] == PIC_NOISE_REC_M1 && o->stage != OFFER_OPEN) {
        /* One handshake an offer: the same first message again (the phone's stream reconnected)
         * gets the same answer; any other, a second device's, nothing. */
        if (n == o->m1n && memcmp(rec, o->m1, n) == 0 && ++o->again <= RMT_PAIR_AGAIN) {
            (void)rmt_lane_add(&o->lane, o->m2rec, o->m2n);
            (void)rmt_lane_flush(r, &o->lane);
        }
        return OFFER_EV_NONE;
    }
    if (rec[0] == PIC_NOISE_REC_M1) {
        char *payload, *pname, *pchan, *pv, idb[32], *reply;
        unsigned char chan[32];
        pic_noise_hs hs;
        pic_noise_hs_init(&hs, 0, &k->stat, NULL, o->psk, o->prologue, sizeof o->prologue);
        if (pic_noise_read1(&hs, rec + 9, n - 9, pl, sizeof pl - 1, &pn) != 0) {
            pic_noise_hs_wipe(&hs);
            return ++o->fails >= RMT_PAIR_FAILS ? OFFER_EV_FAILED : OFFER_EV_NONE;
        }
        pl[pn] = '\0';
        payload = (char *)pl;
        pv = rmt_q("SELECT json_extract(?1, '$.v') >= 1", 1, payload);
        pname = rmt_q("SELECT CASE json_type(?1, '$.name') WHEN 'text' THEN json_extract(?1, '$.name') END", 1, payload);
        pchan = rmt_q("SELECT CASE json_type(?1, '$.channel') WHEN 'text' THEN json_extract(?1, '$.channel') END", 1, payload);
        if (!pv || strcmp(pv, "1") != 0 || !pname || strlen(pname) > 64 || !*pname || !pchan ||
            pic_b64u_dec(pchan, strlen(pchan), chan, sizeof chan) != 16) {
            free(pv);
            free(pname);
            free(pchan);
            pic_noise_hs_wipe(&hs);
            return OFFER_EV_NONE;
        }
        rmt_name_clean(pname);
        free(pv);
        free(pchan);
        pic_b64u_enc(o->d.id, 16, idb);
        reply = rmt_q("SELECT json_object('v', 1, 'device', ?1, 'name', ?2, 'vapid', ?3)", 3, idb, o->host, o->vapid);
        if (!reply || pic_noise_write2(&hs, reply, strlen(reply), m2, sizeof m2, &mn) != 0) {
            free(reply);
            free(pname);
            pic_noise_hs_wipe(&hs);
            return OFFER_EV_NONE;
        }
        free(reply);
        (void)snprintf(o->d.name, sizeof o->d.name, "%s", pname);
        free(pname);
        memcpy(o->d.stat, hs.rs, PIC_NOISE_PUB);
        memcpy(o->d.channel, chan, 16);
        memcpy(o->m1, rec, n);
        o->m1n = n;
        memcpy(o->sid, rec + 1, 8);
        {
            unsigned char up[32], down[32];
            pic_noise_split(&hs, up, down);
            pic_noise_transport_init(&o->t, 0, o->sid, up, down);
            pic_noise_sas(hs.h, o->sas);
            pic_cred_wipe(up, sizeof up);
            pic_cred_wipe(down, sizeof down);
        }
        pic_noise_hs_wipe(&hs);
        o->m2n = pic_noise_head(PIC_NOISE_REC_M2, o->sid, m2, mn, o->m2rec);
        (void)rmt_lane_add(&o->lane, o->m2rec, o->m2n);
        (void)rmt_lane_flush(r, &o->lane);
        o->stage = OFFER_SHAKEN;
        o->msg.len = 0;
        return OFFER_EV_NONE;
    }
    if (rec[0] == PIC_NOISE_REC_DATA && o->stage == OFFER_SHAKEN && memcmp(rec + 1, o->sid, 8) == 0) {
        unsigned char data[PIC_NOISE_CHUNK];
        size_t dn;
        int flag, gap, ask = 0;
        char *type;
        if (pic_noise_open_record(&o->t, rec, n, &flag, data, &dn, &gap) != 0) {
            return OFFER_EV_NONE;
        }
        if (gap || o->msg.len + dn > RMT_MSG_CAP) { /* a gap, or longer than any message */
            o->msg.len = 0;
        }
        (void)rmt_buf_add(&o->msg, data, dn);
        if (flag != 1) {
            return OFFER_EV_NONE;
        }
        type = rmt_q("SELECT json_extract(?1, '$.type')", 1, o->msg.buf);
        o->msg.len = 0;
        if (type && strcmp(type, "pair_ready") == 0) {
            o->stage = OFFER_ASKING;
            ask = 1;
        }
        free(type);
        return ask ? OFFER_EV_ASK : OFFER_EV_NONE;
    }
    return OFFER_EV_NONE;
}

static void rmt_offer_say(rmt_offer *o, rmt_relay *r, const char *json) {
    unsigned char rec[PIC_NOISE_RECORD_CAP];
    size_t rn = pic_noise_record(&o->t, 1, json, strlen(json), rec);
    (void)rmt_lane_add(&o->lane, rec, rn);
    o->said = 1;
    (void)rmt_lane_flush(r, &o->lane);
}

/* Yes: the device row, its channel, then paired (section 2's order). The offer is over either way. */
static int rmt_offer_accept(rmt_offer *o, rmt_relay *r, char *err, size_t cap) {
    if (o->stage != OFFER_ASKING) {
        (void)snprintf(err, cap, "no device is waiting");
        return -1;
    }
    o->stage = OFFER_OVER;
    if (rmt_device_add(&o->d, err, cap) != 0) {
        rmt_offer_say(o, r, "{\"type\":\"error\",\"payload\":{\"code\":\"pair_refused\"}}");
        return -1;
    }
    if (rmt_put_channel(r, o->d.channel, 0, err, cap) != 0) { /* a row whose phone heard no would never connect */
        rmt_device_delete(o->d.id);
        rmt_offer_say(o, r, "{\"type\":\"error\",\"payload\":{\"code\":\"pair_refused\"}}");
        return -1;
    }
    rmt_offer_say(o, r, "{\"type\":\"paired\"}");
    return 0;
}

/* No, or the offer ended: a device that made the handshake hears so. */
static void rmt_offer_refuse(rmt_offer *o, rmt_relay *r) {
    if (o->stage == OFFER_SHAKEN || o->stage == OFFER_ASKING) {
        rmt_offer_say(o, r, "{\"type\":\"error\",\"payload\":{\"code\":\"pair_refused\"}}");
    }
    o->stage = OFFER_OVER;
}

static void rmt_offer_free(rmt_offer *o) {
    pic_cred_wipe(o->psk, sizeof o->psk);
    pic_cred_wipe(o->url, sizeof o->url);
    pic_cred_wipe(&o->t, sizeof o->t);
    free(o->msg.buf);
    free(o->lane.q);
    o->msg.buf = NULL;
    o->lane.q = NULL;
}

/* ---- the envelope (section 4) --------------------------------------------------------- */

typedef struct {
    char type[32], key[48], ptype[40];
    char *session, *payload;
    long long seq;
    int has_seq;
} rmt_env;

static void rmt_env_free(rmt_env *e) {
    free(e->session);
    free(e->payload);
}

static int rmt_env_parse(const char *json, rmt_env *e) {
    sqlite3 *m = rmt_mem();
    sqlite3_stmt *q = NULL;
    int rc = -1;
    memset(e, 0, sizeof *e);
    if (!m || sqlite3_prepare_v2(m,
                                 "SELECT json_extract(?1, '$.type'), json_extract(?1, '$.session'), json_extract(?1, '$.seq'),"
                                 " json_type(?1, '$.seq'), json_extract(?1, '$.key'),"
                                 " CASE json_type(?1, '$.payload') WHEN 'object' THEN json_extract(?1, '$.payload') END,"
                                 " CASE json_type(?1, '$.payload.type') WHEN 'text' THEN json_extract(?1, '$.payload.type') END"
                                 " WHERE json_valid(?1) AND json_type(?1) = 'object' AND json_type(?1, '$.type') = 'text'",
                                 -1, &q, NULL) != SQLITE_OK) {
        return -1;
    }
    sqlite3_bind_text(q, 1, json, -1, SQLITE_STATIC);
    if (sqlite3_step(q) == SQLITE_ROW) {
        const char *t = (const char *)sqlite3_column_text(q, 0), *k = (const char *)sqlite3_column_text(q, 4);
        const char *pt = (const char *)sqlite3_column_text(q, 6);
        (void)snprintf(e->type, sizeof e->type, "%s", t ? t : "");
        if (sqlite3_column_type(q, 1) == SQLITE_TEXT) {
            e->session = strdup((const char *)sqlite3_column_text(q, 1));
        }
        e->has_seq = sqlite3_column_text(q, 3) && strcmp((const char *)sqlite3_column_text(q, 3), "integer") == 0;
        e->seq = sqlite3_column_int64(q, 2);
        if (k && sqlite3_column_type(q, 4) == SQLITE_TEXT) {
            (void)snprintf(e->key, sizeof e->key, "%s", k);
        }
        if (sqlite3_column_type(q, 5) != SQLITE_NULL) {
            e->payload = strdup((const char *)sqlite3_column_text(q, 5));
        }
        (void)snprintf(e->ptype, sizeof e->ptype, "%s", pt ? pt : "");
        rc = 0;
    }
    sqlite3_finalize(q);
    return rc;
}

/* A key is 16 to 43 characters of [A-Za-z0-9_-]. */
static int rmt_key_ok(const char *k) {
    size_t n = strlen(k);
    if (n < 16 || n > 43) {
        return 0;
    }
    for (size_t i = 0; i < n; i++) {
        char c = k[i];
        if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' || c == '-')) {
            return 0;
        }
    }
    return 1;
}

/* ---- the serving state ------------------------------------------------------------------ */

typedef struct {
    long long *v;
    int n, cap;
} rmt_ids;

/* A conversation of the list (rmt_list), as its journal's query gave it. */
typedef struct {
    int jx;
    char id[64];
    char *name, *title, *preview;
    long long ms, seq;
    int running, attention, loops, asks;
} rmt_item;

typedef struct {
    char *parent; /* JOURNAL/ID */
    int n;
} rmt_helpers;

typedef struct {
    char *path, *workspace;
    char *real; /* path, resolved: what a helper's parent (pic_session_origin.parent) names it by */
    /* its part of the list, kept until the journal changes (rmt_list_part): -1, none yet */
    long long list_dv, list_tc;
    rmt_item *li;
    size_t nli;
    rmt_helpers *lh;
    size_t nlh;
    int list_slow; /* the last try ran out of time: said once */
    pic_store s;
    int open;
    int yielded; /* closed for a newer pic to migrate it: opened again after */
    int older;   /* not open because an older pic last used it: updated here once no pic has it (rmt_update) */
    long long update_failed_ms; /* when updating it last failed with no pic in it (monotonic) */
    char why[256];
    long long version;
    /* requests seen ending (section 5's When): every one above cut or in open ends here once */
    long long push_cut, push_version;
    rmt_ids push_open; /* admitted when this journal was first read */
    rmt_ids push_told; /* above cut, already notified */
    /* loops: when the journal was last asked what is due, and the newest change of a loop seen, so
     * a loop that comes to need a person is told once (and a restart repeats nothing) */
    long long wake_at, wake_seen;
    int wake_init;
    /* asks: the newest version told, and the data_version it was read at (rmt_ask_check) */
    long long ask_version, ask_dv;
    int ask_init;
    /* asks that expired unanswered and were told so (rmt_ask_expiry), and when it last looked */
    char ask_told[RMT_ASK_RING][PIC_ASK_ID_LEN + 1];
    unsigned ask_told_at;
    long long ask_expiry_ms;
} rmt_journal;

enum { CMD_INBOX = 1, CMD_PROMPT = 2, CMD_COMPACT = 3, CMD_DONE = 4 };

typedef struct {
    int kind;
    int jx;
    char key[48];      /* the phone's */
    char row[96];      /* rc:DEVICE:KEY */
    char *line;        /* the command, to tell a repeat from another command with the key */
    pid_t pid;         /* a prompt's child */
    long long expire_ms; /* when its expiry was last looked at */
    int errfd;         /* its submit's stderr */
    char err[512];
    size_t errlen;
    char conv[64];     /* a compaction's conversation */
    char *answer;      /* CMD_DONE: the response line a repeat of the key gets again */
} rmt_cmd;

/* A model or thinking level a phone chose for a conversation's next request (set_model,
 * set_thinking_level): held here, as pic --mode rpc holds its own, until a request starts with it. */
typedef struct {
    int jx;
    char conv[64];
    char model[256], thinking[32];
    char key[PIC_CRED_LABEL_CAP]; /* the key, by label, of the model's provider (set_credential); "" none */
} rmt_choice;

typedef struct {
    rmt_device d;
    char idb[32];  /* b64u(id) */
    rmt_lane lane;
    int sess;      /* its confirmed session, or -1 */
    int alive;     /* still in the table */
    /* following one conversation */
    int jx;
    char conv[64];
    char *wsess;   /* the session as the phone named it, W/C */
    char skey[48]; /* the sync's key, echoed on each event and mark of the follow; "" for none */
    pic_follow *f;
    long long fversion;
    int follow_now;
    /* the conversation list it asked for */
    int want_list;
    char *list_sent;
    rmt_cmd cmds[RMT_CMDS];
    int ncmds;
    long long fev;  /* the highest seq of an event this follow sent */
    int frunning;   /* what its last mark said */
    long long earlier; /* where a sync starts to show RMT_EARLIER more requests; -1: from the start already */
    /* the live value (section 4): the file read, its head, the text read and the last 8 KiB of it */
    long long live_ms, live_seq, live_pos, live_sent, live_chars;
    dev_t live_dev;
    ino_t live_ino;
    size_t live_head, live_len;
    char live_buf[RMT_LIVE_KEEP + 1];
    /* notifications (section 5) */
    int want_devices;         /* asked for the device list in this session: sent again on each change */
    int visible;              /* the session's last presence */
    int refused;              /* 400s and 403s in a row */
    long long push_hold_ms;   /* nothing sent before this (a 429's Retry-After) */
    struct {
        unsigned long long conv;
        long long ms;
    } pushed[16];             /* the last notification per conversation */
    long long seen_wr_ms;     /* when seen_ms was last written (monotonic) */
} rmt_dev;

/* One notification on its way, and what came of it. */
typedef struct {
    unsigned char dev[16];
    char endpoint[RMT_ENDPOINT];
    unsigned char p256dh[PIC_WEBPUSH_PUB], auth[PIC_WEBPUSH_AUTH];
    char topic[PIC_WEBPUSH_TOPIC];
    char *title, *session, *payload; /* payload: the plaintext, made by rmt_push_queue */
    long long seq;
    int shortened;
    pic_webpush_result res;
} rmt_push;

typedef struct {
    pthread_mutex_t mu;
    pthread_cond_t cv;
    rmt_push *todo[RMT_PUSH_QUEUE], *done[RMT_PUSH_QUEUE];
    int ntodo, ndone, started;
    int sending; /* one taken from todo and not yet done */
    pic_webpush_vapid vapid;
    char subject[512];
} rmt_pusher;

/* Counted for the log: the first is said at once, then one line every RMT_TALLY_MS at most. */
typedef struct {
    long long n, said_ms;
} rmt_tally;

static int rmt_tally_due(rmt_tally *t) {
    long long now = rmt_mono_ms();
    if (t->n++ && now - t->said_ms < RMT_TALLY_MS) {
        return 0;
    }
    t->said_ms = now;
    return 1;
}

typedef struct {
    const pic_remote_options *o;
    rmt_keys k;
    rmt_relay r;
    rmt_dev *devs;
    int ndevs;
    rmt_sess sess[RMT_SESSIONS];
    rmt_journal **js; /* pointers: a follower holds its journal's store */
    int njs;
    long long user_version;
    int lockfd;
    long long live_rev; /* every live value this process sends has a higher one */
    rmt_pusher push;
    rmt_choice choices[RMT_CHOICES];
    int nchoices;
    int pipe_w;         /* the streams' pipe, for an offer's stream */
    /* pairing from a paired phone: one offer at a time, the device that asked for it, and, once
     * it is over, how long its last word may wait for the new device to read it */
    rmt_offer *offer;
    rmt_stream *offer_str;
    int offer_dev, offer_posted, offer_reading;
    long long offer_close_ms;
    /* records dropped and sessions reset, for the log */
    rmt_tally dropped_unknown, dropped_again, reset_unknown;
} rmt_state;

static int rmt_send(rmt_state *st, rmt_dev *d, const char *json) {
    if (!json || d->sess < 0) {
        return -1;
    }
    return rmt_sess_send(&st->sess[d->sess], &d->lane, json);
}

static void rmt_send_free(rmt_state *st, rmt_dev *d, char *json) {
    (void)rmt_send(st, d, json);
    free(json);
}

static void rmt_error(rmt_state *st, rmt_dev *d, const char *key, const char *code, const char *message) {
    rmt_send_free(st, d,
                  rmt_q("SELECT json_patch('{}', json_object('type', 'error', 'key', ?1, 'payload',"
                        " json_patch('{}', json_object('code', ?2, 'message', ?3))))",
                        3, key && *key ? key : NULL, code, message));
}

/* The paired devices' names by their b64u ids, as a JSON object (malloc'd): who answered. */
static char *rmt_device_names(rmt_state *st) {
    char *out = strdup("{}");
    for (int i = 0; out && i < st->ndevs; i++) {
        char *more;
        if (!st->devs[i].alive) {
            continue;
        }
        more = rmt_q("SELECT json_set(?1, '$.\"' || ?2 || '\"', ?3)", 3, out, st->devs[i].idb, st->devs[i].d.name);
        free(out);
        out = more;
    }
    return out;
}

/* SQL: ask_settled's payload for V, an ask as pic_ask_list gives it, with MAP the device names:
 * {id, value, by: {kind: terminal|phone|attach|rpc|expired|cancelled, device: a name or null}}. */
#define RMT_SETTLED_SQL(V, MAP)                                                                                        \
    "json_object('id', json_extract(" V ", '$.id'), 'value', json_extract(" V ", '$.value'), 'by', json_object('kind',"   \
    " CASE json_extract(" V ", '$.state') WHEN 'withdrawn' THEN 'cancelled' WHEN 'expired' THEN 'expired' ELSE"          \
    " CASE WHEN json_extract(" V ", '$.answeredBy') LIKE 'remote:%' THEN 'phone' ELSE json_extract(" V ", '$.answeredBy')"\
    " END END, 'device', CASE WHEN json_extract(" V ", '$.answeredBy') LIKE 'remote:%' THEN json_extract(" MAP ", '$.\"' ||" \
    " substr(json_extract(" V ", '$.answeredBy'), 8) || '\"') END))"

/* ---- journals and the conversation list --------------------------------------------------- */

static long long rmt_data_version(sqlite3 *db) {
    sqlite3_stmt *q = NULL;
    long long v = -1;
    if (db && sqlite3_prepare_v2(db, "PRAGMA data_version", -1, &q, NULL) == SQLITE_OK && sqlite3_step(q) == SQLITE_ROW) {
        v = sqlite3_column_int64(q, 0);
    }
    sqlite3_finalize(q);
    return v;
}

static void rmt_push_watch(rmt_journal *j);

/* The schema version a journal at PATH says it has (pic_meta), or -1 when it is no journal. */
static long rmt_journal_schema(const char *path) {
    sqlite3 *db = NULL;
    sqlite3_stmt *q = NULL;
    long v = -1;
    if (sqlite3_open_v2(path, &db, SQLITE_OPEN_READONLY, pic_platform_get()->vfs) == SQLITE_OK &&
        sqlite3_prepare_v2(db, "SELECT CAST(value AS INTEGER) FROM pic_meta WHERE key = 'schema_version'", -1, &q, NULL) ==
            SQLITE_OK &&
        sqlite3_step(q) == SQLITE_ROW) {
        v = sqlite3_column_int(q, 0);
    }
    sqlite3_finalize(q);
    sqlite3_close(db);
    return v;
}

#define RMT_HELD_OLDER "open in an older pic; it updates when that pic closes"

/* Why J is not open, for a phone, by its schema SV (rmt_journal_schema). One an older pic last used
 * is updated here (rmt_update); until then an older pic has it open. */
static void rmt_why(rmt_journal *j, long sv) {
    j->older = 0;
    if (sv >= 0 && sv < atol(PIC_SCHEMA_VERSION)) { /* a phone has no use for the store's words */
        (void)snprintf(j->why, sizeof j->why, RMT_HELD_OLDER);
        j->older = 1;
    } else if (sv > atol(PIC_SCHEMA_VERSION)) {
        (void)snprintf(j->why, sizeof j->why, "a newer pic wrote it; update pic on this computer");
    } else {
        (void)snprintf(j->why, sizeof j->why, "%s", j->s.err[0] ? j->s.err : "cannot open the journal");
    }
}

/* J opened narrowly to be served: 0, or -1 with it closed. AGAIN: one let go of for a newer pic,
 * not opened while a migration still waits. */
static int rmt_serve_open(rmt_state *st, rmt_journal *j, int again) {
    if (pic_open_narrow(&j->s, j->path) == 0 && !(again && pic_migration_wanted(&j->s)) && pic_sqlar_register(j->s.db) == 0 &&
        pic_transform_register(j->s.db) == 0) { /* the functions get_messages' queries call */
        j->open = 1;
        j->list_dv = -1; /* a new connection: its part of the list is built afresh */
        (void)pic_busy_wait(j->s.db, RMT_BUSY_MS); /* the loop never waits long for another pic */
        j->yielded = 0;
        j->older = 0;
        j->why[0] = '\0';
        j->s.policy = st->o->policy; /* get_session_stats' context estimate */
        j->version = rmt_data_version(j->s.db);
        j->push_open.n = 0;
        rmt_push_watch(j);
        j->ask_init = 0; /* what was asked before is not news: sent only to a phone's new session */
        j->ask_dv = -1;
        return 0;
    }
    pic_close(&j->s);
    return -1;
}

/* A journal an older pic last used, brought up to date as pic's own open does it, when no process
 * has it open; one an older pic has open is left alone (never stopped) and looked at again on each
 * tick, its reason saying so. 1 when J is served now. */
static int rmt_update(rmt_state *st, rmt_journal *j) {
    pic_store m;
    long long now = rmt_mono_ms();
    if (j->open || !j->older) {
        return j->open;
    }
    if (!pic_journal_unheld(j->path)) {
        (void)snprintf(j->why, sizeof j->why, RMT_HELD_OLDER);
        return 0;
    }
    if (j->update_failed_ms && now - j->update_failed_ms < 60000) {
        return 0;
    }
    if (pic_open(&m, j->path) != 0) {
        if (pic_journal_unheld(j->path)) { /* the update itself failed: tried again in a minute */
            (void)snprintf(j->why, sizeof j->why, "pic could not update it: %s", m.err);
            j->update_failed_ms = now;
            rmt_log(stdout, "pic remote: could not update %s: %s\n", j->path, m.err);
            (void)fflush(stdout);
        } else { /* an older pic opened it meanwhile */
            (void)snprintf(j->why, sizeof j->why, RMT_HELD_OLDER);
        }
        pic_close(&m);
        return 0;
    }
    pic_close(&m);
    j->update_failed_ms = 0;
    rmt_log(stdout, "pic remote: updated %s\n", j->path);
    (void)fflush(stdout);
    if (rmt_serve_open(st, j, 0) != 0) {
        rmt_why(j, rmt_journal_schema(j->path));
        return 0;
    }
    return 1;
}

/* Whether workspace WS is under a temporary directory ($TMPDIR, /tmp, /var/folders): an agent's or
 * a test's scratch, never shown to a phone. */
static int rmt_temporary(const char *ws) {
    const char *roots[] = {getenv("TMPDIR"), "/tmp", "/private/tmp", "/var/folders", "/private/var/folders"};
    char real[PATH_MAX], rroot[PATH_MAX];
    const char *forms[2] = {ws, realpath(ws, real) ? real : ws};
    int nroots = (int)(sizeof roots / sizeof roots[0]);
#ifdef PIC_FAULTS
    if (getenv("PIC_TEST_RC_TEMP")) { /* the tests' seam: the temporary directories, instead */
        roots[0] = getenv("PIC_TEST_RC_TEMP");
        nroots = 1;
    }
#endif
    for (int i = 0; i < nroots; i++) {
        const char *r = roots[i];
        for (int form = 0; r && *r && form < 2; form++) {
            const char *rt = form ? (realpath(r, rroot) ? rroot : r) : r;
            size_t n = strlen(rt);
            while (n > 1 && rt[n - 1] == '/') {
                n--;
            }
            for (int k = 0; k < 2; k++) {
                if (strncmp(forms[k], rt, n) == 0 && (forms[k][n] == '/' || forms[k][n] == '\0')) {
                    return 1;
                }
            }
        }
    }
    return 0;
}

/* Whether a workspace's directory or its journal is gone (a test's, a deleted checkout). */
static int rmt_gone(const char *ws, const char *jp) {
    struct stat sb;
    return stat(ws, &sb) != 0 || !S_ISDIR(sb.st_mode) || stat(jp, &sb) != 0 || !S_ISREG(sb.st_mode);
}

/* The rows of picu_workspace to forget (their directory or journal gone, or a journal that is the
 * user database) or mend (to the workspace's own journal, when it has one), found while reading. */
typedef struct {
    char *ws, *jp; /* jp NULL: forget */
} rmt_heal;

/* Every picu_workspace row whose path still holds that journal, opened narrowly once each. A row
 * whose directory or journal is gone is forgotten, so the registry heals as it is read; one that
 * names the user database is mended or forgotten; a file that is no journal is never listed. */
static void rmt_journals_scan(rmt_state *st) {
    sqlite3 *db = pic_userdb(NULL, 0);
    sqlite3_stmt *q = NULL;
    rmt_heal fix[64];
    int nfix = 0;
    if (!db || sqlite3_prepare_v2(db, "SELECT path, journal FROM picu_workspace ORDER BY last_used_ms DESC", -1, &q, NULL) !=
                   SQLITE_OK) {
        return;
    }
    while (sqlite3_step(q) == SQLITE_ROW) {
        const char *ws = (const char *)sqlite3_column_text(q, 0), *jp = (const char *)sqlite3_column_text(q, 1);
        char own[PATH_MAX];
        int known = 0;
        long sv;
        rmt_journal **grown, *j;
        if (!ws || !jp) {
            continue;
        }
        if (pic_userdb_is(jp)) { /* registered by a pic run with --db naming the user database */
            if (nfix < 64) {
                int mend = snprintf(own, sizeof own, "%s/.pic/journal.sqlite", ws) < (int)sizeof own && !rmt_gone(ws, own) &&
                           !pic_userdb_is(own);
                fix[nfix].ws = strdup(ws);
                fix[nfix++].jp = mend ? strdup(own) : NULL;
            }
            continue;
        }
        if (rmt_gone(ws, jp)) {
            if (nfix < 64) {
                fix[nfix].ws = strdup(ws);
                fix[nfix++].jp = NULL;
            }
            continue;
        }
        if (rmt_temporary(ws)) { /* kept in the registry; never shown */
            continue;
        }
        for (int i = 0; i < st->njs; i++) {
            known = known || strcmp(st->js[i]->path, jp) == 0 || strcmp(st->js[i]->workspace, ws) == 0;
        }
        if (known || !(grown = realloc(st->js, (size_t)(st->njs + 1) * sizeof *grown))) {
            continue;
        }
        st->js = grown;
        if (!(j = calloc(1, sizeof *j))) {
            continue;
        }
        j->path = strdup(jp);
        j->workspace = strdup(ws);
        j->real = realpath(jp, own) ? strdup(own) : strdup(jp);
        if (!j->path || !j->workspace || !j->real) {
            free(j->path);
            free(j->workspace);
            free(j->real);
            free(j);
            continue;
        }
        st->js[st->njs] = j;
        if (rmt_serve_open(st, j, 0) == 0) {
        } else if ((sv = rmt_journal_schema(jp)) < 0) { /* not a journal: nothing to show */
            free(j->path);
            free(j->workspace);
            free(j->real);
            free(j);
            continue;
        } else {
            rmt_why(j, sv);
            (void)rmt_update(st, j); /* an older pic's, at start and on an install's restart */
        }
        st->njs++;
    }
    sqlite3_finalize(q);
    {
        int mended = 0;
        for (int i = 0; i < nfix; i++) {
            if (fix[i].ws) {
                mended += fix[i].jp && pic_workspace_touch(fix[i].ws, fix[i].jp) == 0;
                if (!fix[i].jp) {
                    (void)pic_workspace_forget(fix[i].ws);
                }
            }
            free(fix[i].ws);
            free(fix[i].jp);
        }
        if (mended) { /* the mended rows, read again (once: a mended row names a journal) */
            rmt_journals_scan(st);
        }
    }
}

/* SESSION as the phone names it, W/C: the journal and the conversation's id. 0, or -1. */
static int rmt_resolve(rmt_state *st, const char *session, int *jx, char conv[64]) {
    const char *slash = session ? strrchr(session, '/') : NULL;
    if (!slash || slash == session || !slash[1] || strlen(slash + 1) >= 64) {
        return -1;
    }
    for (int i = 0; i < st->njs; i++) {
        if (st->js[i]->open && strlen(st->js[i]->path) == (size_t)(slash - session) &&
            memcmp(st->js[i]->path, session, (size_t)(slash - session)) == 0) {
            sqlite3_stmt *q = NULL;
            int found = 0;
            if (sqlite3_prepare_v2(st->js[i]->s.db, "SELECT 1 FROM pic_session WHERE id = ?", -1, &q, NULL) == SQLITE_OK) {
                sqlite3_bind_text(q, 1, slash + 1, -1, SQLITE_STATIC);
                found = sqlite3_step(q) == SQLITE_ROW;
            }
            sqlite3_finalize(q);
            if (!found) {
                return -1;
            }
            *jx = i;
            (void)snprintf(conv, 64, "%s", slash + 1);
            return 0;
        }
    }
    return -1;
}

/* Whether journal I is shown: read now, or worth a line, with its directory and file still there. */
static int rmt_shown(rmt_state *st, int i) { return !rmt_gone(st->js[i]->workspace, st->js[i]->path); }

static const char *rmt_base(const char *p, size_t *n) {
    const char *end = p + strlen(p), *b;
    while (end > p + 1 && end[-1] == '/') {
        end--;
    }
    for (b = end; b > p && b[-1] != '/'; b--) {
    }
    *n = (size_t)(end - b);
    return b;
}

/* What a phone calls workspace I: its directory's name, or parent/name when another workspace shown
 * has a directory of that name too. */
static void rmt_ws_name(rmt_state *st, int i, char *out, size_t cap) {
    const char *w = st->js[i]->workspace, *b;
    size_t n, m;
    int twin = 0;
    b = rmt_base(w, &n);
    for (int k = 0; k < st->njs && !twin; k++) {
        const char *o;
        if (k == i || !rmt_shown(st, k)) {
            continue;
        }
        o = rmt_base(st->js[k]->workspace, &m);
        twin = m == n && memcmp(o, b, n) == 0;
    }
    if (twin && b > w + 1) {
        const char *pe = b - 1, *ps = pe;
        while (ps > w && ps[-1] != '/') {
            ps--;
        }
        (void)snprintf(out, cap, "%.*s/%.*s", (int)(pe - ps), ps, (int)n, b);
    } else {
        (void)snprintf(out, cap, "%.*s", (int)n, b);
    }
}


static int rmt_item_cmp(const void *a, const void *b) {
    const rmt_item *x = a, *y = b;
    return x->ms < y->ms ? 1 : x->ms > y->ms ? -1 : 0;
}

/* A journal's conversations for the list, newest first, with FILTER (SQL) on s: id, name, last
 * activity, running, last seq, title, attention, loops. */
#define RMT_LIST_SQL(FILTER)                                                                                         \
    "SELECT s.id, coalesce(s.name, ''), s.updated_ms,"                                                               \
    " EXISTS (SELECT 1 FROM pic_submission u WHERE u.session_id = s.id AND u.status = 'admitted'),"                  \
    /* its newest entry: the head the store keeps, not a walk of pic_entry */                                     \
    " coalesce(s.head_seq, 0), " PIC_TITLE_SQL("s") ","                                                              \
    /* attention: the last request failed, not stopped by the person, or hit the request cap */                     \
    " coalesce((SELECT (u.status = 'failed' AND coalesce(u.error, '') != 'cancelled')"                               \
    "  OR coalesce(u.stop_reason, '') = 'request_cap' FROM pic_submission u WHERE u.session_id = s.id"               \
    "  ORDER BY u.id DESC LIMIT 1), 0)"                                                                              \
    /* or a loop of it needs a person; and how many loops it has */                                                  \
    " OR EXISTS (SELECT 1 FROM pic_wake w WHERE w.session_id = s.id AND w.state = 'needs'),"                         \
    " (SELECT count(*) FROM pic_wake w WHERE w.session_id = s.id AND w.state != 'ended')"                            \
    " FROM pic_session s WHERE " PIC_LISTED_SQL("s") FILTER " ORDER BY s.updated_ms DESC LIMIT ?"

static void rmt_items_free(rmt_item *items, size_t n) {
    for (size_t i = 0; i < n; i++) {
        free(items[i].name);
        free(items[i].title);
        free(items[i].preview);
    }
    free(items);
}

static void rmt_helpers_free(rmt_helpers *h, size_t n) {
    for (size_t i = 0; i < n; i++) {
        free(h[i].parent);
    }
    free(h);
}

/* How long building one journal's part of the list may take: past it the part is given up and the
 * last one shown, so a slow disk never holds the loop that serves the phones. */
#define RMT_LIST_BUDGET_MS 250

static int rmt_list_deadline(void *arg) { return rmt_mono_ms() > *(long long *)arg; }

/* The virtual machine steps the last list build's statements took: the tests' measure of work
 * done, which a loaded machine's clock is not. */
static long long rmt_list_steps;

/* Journal I's part of the list: its MOST newest conversations a person drives, each with its
 * title and last line (ITEMS), and its running helpers by parent (HELPERS). 0, or -1 (none given
 * back) when it failed or took longer than BUDGET_MS. */
static int rmt_list_build(rmt_state *st, int i, size_t most, long long budget_ms, rmt_item **items, size_t *n,
                          rmt_helpers **helpers, size_t *nh) {
    rmt_journal *j = st->js[i];
    sqlite3_stmt *q = NULL;
    size_t cap = 0, hcap = 0;
    long long deadline = rmt_mono_ms() + budget_ms;
    int rc = 0, step;
#ifdef PIC_FAULTS
    if (getenv("PIC_TEST_RC_LIST_BUDGET_MS")) { /* the tests' seam: a budget a test runs out of */
        deadline = rmt_mono_ms() + atoll(getenv("PIC_TEST_RC_LIST_BUDGET_MS"));
    }
#endif
    *items = NULL;
    *helpers = NULL;
    *n = *nh = 0;
    rmt_list_steps = 0;
    sqlite3_progress_handler(j->s.db, 1000, rmt_list_deadline, &deadline);
    /* a person's alone: not an agent's, a loop's or a headless run's; a journal no pic of this
     * build has opened says nothing of origins, and is a person's */
    if (sqlite3_prepare_v2(j->s.db, RMT_LIST_SQL(" AND " PIC_STARTED_BY_SQL("s") " IN ('person', 'phone')"), -1, &q, NULL) !=
            SQLITE_OK &&
        (sqlite3_finalize(q), q = NULL, sqlite3_prepare_v2(j->s.db, RMT_LIST_SQL(""), -1, &q, NULL)) != SQLITE_OK) {
        rc = -1;
    }
    if (rc == 0) {
        sqlite3_bind_int64(q, 1, (sqlite3_int64)most);
        while ((step = sqlite3_step(q)) == SQLITE_ROW) {
            rmt_item *it;
            if (*n == cap) {
                rmt_item *grown = realloc(*items, (cap = cap ? cap * 2 : 64) * sizeof *grown);
                if (!grown) {
                    rc = -1;
                    break;
                }
                *items = grown;
            }
            it = &(*items)[(*n)++];
            memset(it, 0, sizeof *it);
            it->jx = i;
            (void)snprintf(it->id, sizeof it->id, "%s", (const char *)sqlite3_column_text(q, 0));
            it->name = strdup((const char *)sqlite3_column_text(q, 1));
            it->ms = sqlite3_column_int64(q, 2);
            it->running = sqlite3_column_int(q, 3);
            it->seq = sqlite3_column_int64(q, 4);
            it->title = sqlite3_column_type(q, 5) == SQLITE_NULL ? NULL : strdup((const char *)sqlite3_column_text(q, 5));
            it->attention = sqlite3_column_int(q, 6);
            it->loops = sqlite3_column_int(q, 7);
        }
        rc = rc == 0 && step == SQLITE_DONE ? 0 : -1;
    }
    rmt_list_steps += q ? sqlite3_stmt_status(q, SQLITE_STMTSTATUS_VM_STEP, 0) : 0;
    sqlite3_finalize(q);
    q = NULL;
    for (size_t k = 0; rc == 0 && k < *n; k++) {
        (*items)[k].preview = pic_session_last_line(&j->s, (*items)[k].id, 120);
        rc = rmt_mono_ms() > deadline ? -1 : 0; /* an interrupted read gives no line: not one to keep */
    }
    /* the helpers running here, by the conversation that started them; a journal no pic of this
     * build has opened has no origins, and no helpers */
    if (rc == 0 &&
        sqlite3_prepare_v2(j->s.db,
                           "SELECT o.parent, count(*) FROM pic_session_origin o JOIN pic_session c ON c.id = o.session_id"
                           " WHERE o.parent IS NOT NULL AND " PIC_LISTED_SQL("c")
                           " AND EXISTS (SELECT 1 FROM pic_submission u WHERE u.session_id = c.id AND u.status = 'admitted')"
                           " GROUP BY o.parent",
                           -1, &q, NULL) == SQLITE_OK) {
        while ((step = sqlite3_step(q)) == SQLITE_ROW) {
            if (*nh == hcap) {
                rmt_helpers *grown = realloc(*helpers, (hcap = hcap ? hcap * 2 : 8) * sizeof *grown);
                if (!grown) {
                    rc = -1;
                    break;
                }
                *helpers = grown;
            }
            if (!((*helpers)[*nh].parent = strdup((const char *)sqlite3_column_text(q, 0)))) {
                rc = -1;
                break;
            }
            (*helpers)[(*nh)++].n = sqlite3_column_int(q, 1);
        }
        rc = rc == 0 && step == SQLITE_DONE ? 0 : -1;
    }
    rmt_list_steps += q ? sqlite3_stmt_status(q, SQLITE_STMTSTATUS_VM_STEP, 0) : 0;
    sqlite3_finalize(q);
    q = NULL;
    /* the questions each conversation waits on (ask.h), by index; a journal with none has no table */
    if (rc == 0 && sqlite3_prepare_v2(j->s.db,
                                      "SELECT session_id, count(*) FROM pic_ask WHERE state = 'open' AND expires_ms > ?1 GROUP BY session_id", -1,
                                      &q, NULL) == SQLITE_OK) {
        sqlite3_bind_int64(q, 1, pic_wake_now_ms());
        while (sqlite3_step(q) == SQLITE_ROW) {
            for (size_t k = 0; k < *n; k++) {
                if (strcmp((*items)[k].id, (const char *)sqlite3_column_text(q, 0)) == 0) {
                    (*items)[k].asks = sqlite3_column_int(q, 1);
                }
            }
        }
    }
    sqlite3_finalize(q);
    sqlite3_progress_handler(j->s.db, 0, NULL, NULL);
    if (rc != 0) {
        rmt_items_free(*items, *n);
        rmt_helpers_free(*helpers, *nh);
        *items = NULL;
        *helpers = NULL;
        *n = *nh = 0;
    }
    return rc;
}

/* Journal I's part of the list, built again only when the journal changed since (another
 * process's commit, or this one's own write). One that runs out of time keeps the part it had,
 * and is tried again on the next look. */
static void rmt_list_part(rmt_state *st, int i) {
    rmt_journal *j = st->js[i];
    long long dv = rmt_data_version(j->s.db), tc = (long long)sqlite3_total_changes64(j->s.db), t0 = rmt_mono_ms();
    rmt_item *items;
    rmt_helpers *helpers;
    size_t n, nh;
    if (j->list_dv == dv && j->list_tc == tc && dv >= 0) {
        return;
    }
    rmt_doing("listing the conversations of", j->path);
    if (rmt_list_build(st, i, RMT_LIST, RMT_LIST_BUDGET_MS, &items, &n, &helpers, &nh) != 0) {
        if (!j->list_slow) {
            printf("pic remote: listing %s took over %d ms; the phone sees its last list until it is done\n", j->path,
                   RMT_LIST_BUDGET_MS);
            (void)fflush(stdout);
            j->list_slow = 1;
        }
        return;
    }
    rmt_items_free(j->li, j->nli);
    rmt_helpers_free(j->lh, j->nlh);
    j->li = items;
    j->nli = n;
    j->lh = helpers;
    j->nlh = nh;
    j->list_dv = dv;
    j->list_tc = tc;
    j->list_slow = 0;
#ifdef PIC_FAULTS
    if (getenv("PIC_TEST_RC_LIST_TIMES")) { /* the tests' seam: how long each part took, and its work */
        printf("pic remote: listed %s in %lld ms, %lld steps\n", j->path, rmt_mono_ms() - t0, rmt_list_steps);
        (void)fflush(stdout);
    }
#else
    (void)t0;
#endif
}

/* The sessions message: the 50 most recently active conversations across the journals, every
 * workspace and those that cannot be read. With ONLY (a journal's index), every conversation of
 * that workspace alone, as {"workspace":W,"sessions":[...]}. */
static char *rmt_list(rmt_state *st, int only) {
    rmt_item *items = NULL, *own = NULL;
    rmt_helpers *ownh = NULL;
    size_t n = 0, cap = 0, most = only >= 0 ? 2000 : RMT_LIST, nown = 0, nownh = 0;
    rmt_buf b = {NULL, 0, 0};
    char *out;
    (void)rmt_buf_add(&b, "[", 1);
    if (only >= 0) { /* one workspace, asked once: built now, within the budget, and not kept */
        if (st->js[only]->open && rmt_shown(st, only) &&
            rmt_list_build(st, only, most, 4 * RMT_LIST_BUDGET_MS, &own, &nown, &ownh, &nownh) == 0) {
            items = own;
            n = nown;
        }
    } else {
        for (int i = 0; i < st->njs; i++) {
            rmt_journal *j = st->js[i];
            if (!j->open || !rmt_shown(st, i)) {
                continue;
            }
            rmt_list_part(st, i);
            if (n + j->nli > cap) {
                rmt_item *grown = realloc(items, (cap = n + j->nli + 64) * sizeof *grown);
                if (!grown) {
                    break;
                }
                items = grown;
            }
            for (size_t k = 0; k < j->nli; k++) { /* the journal's own, borrowed: freed with its part */
                items[n] = j->li[k];
                items[n++].jx = i;
            }
        }
    }
    if (n) {
        qsort(items, n, sizeof *items, rmt_item_cmp);
    }
    for (size_t i = 0; i < n && i < most; i++) {
        char *sess = NULL, ms[32], seq[32], *one, wname[256], loops[16], nhelp[16] = "0", nasks[16];
        rmt_journal *j = st->js[items[i].jx];
        size_t rn = strlen(j->real);
        for (int h = 0; h < st->njs; h++) { /* a helper may run in any journal */
            rmt_helpers *hs = only >= 0 ? ownh : st->js[h]->open ? st->js[h]->lh : NULL;
            size_t nhs = only >= 0 ? nownh : st->js[h]->open ? st->js[h]->nlh : 0;
            for (size_t k = 0; k < nhs; k++) {
                if (strncmp(hs[k].parent, j->real, rn) == 0 && hs[k].parent[rn] == '/' && strcmp(hs[k].parent + rn + 1, items[i].id) == 0) {
                    (void)snprintf(nhelp, sizeof nhelp, "%d", atoi(nhelp) + hs[k].n);
                }
            }
            if (only >= 0) {
                break;
            }
        }
        rmt_ws_name(st, items[i].jx, wname, sizeof wname);
        size_t pn = strlen(j->path) + strlen(items[i].id) + 2;
        if ((sess = malloc(pn))) {
            (void)snprintf(sess, pn, "%s/%s", j->path, items[i].id);
        }
        (void)snprintf(ms, sizeof ms, "%lld", items[i].ms);
        (void)snprintf(seq, sizeof seq, "%lld", items[i].seq);
        (void)snprintf(loops, sizeof loops, "%d", items[i].loops);
        (void)snprintf(nasks, sizeof nasks, "%d", items[i].asks);
        /* a question waiting on the person is attention, running or not: "Needs you" */
        one = rmt_q("SELECT json_patch(json_object('session', ?1, 'name', ?2, 'workspace', ?3, 'lastMs', CAST(?4 AS INTEGER),"
                    " 'running', json(?5), 'seq', CAST(?6 AS INTEGER)), json_object('title', ?7, 'preview', ?8, 'state', ?9,"
                    " 'workspaceName', ?10, 'loops', nullif(CAST(?11 AS INTEGER), 0), 'helpers', nullif(CAST(?12 AS INTEGER), 0),"
                    " 'asks', nullif(CAST(?13 AS INTEGER), 0)))",
                    13, sess, items[i].name ? items[i].name : "", j->workspace, ms, items[i].running ? "true" : "false", seq,
                    items[i].title, items[i].preview,
                    items[i].asks ? "attention" : items[i].running ? "running" : items[i].attention ? "attention" : "idle", wname,
                    loops, nhelp, nasks);
        if (one) {
            if (b.len > 1) {
                (void)rmt_buf_add(&b, ",", 1);
            }
            (void)rmt_buf_add(&b, one, strlen(one));
        }
        free(one);
        free(sess);
    }
    if (only >= 0) {
        rmt_items_free(own, nown);
    } else {
        free(items);
    }
    rmt_helpers_free(ownh, nownh);
    (void)rmt_buf_add(&b, "]", 1);
    if (only >= 0) {
        out = rmt_q("SELECT json_object('type', 'sessions', 'payload', json_object('workspace', ?1, 'sessions', json(?2)))", 2,
                    st->js[only]->path, b.buf ? b.buf : "[]");
        free(b.buf);
        return out;
    }
    {
        rmt_buf u = {NULL, 0, 0};
        (void)rmt_buf_add(&u, "[", 1);
        for (int i = 0; i < st->njs; i++) {
            char *one, wname[256];
            if (st->js[i]->open || !rmt_shown(st, i)) {
                continue;
            }
            rmt_ws_name(st, i, wname, sizeof wname);
            one = rmt_q("SELECT json_object('workspace', ?1, 'reason', ?2, 'name', ?3)", 3, st->js[i]->workspace, st->js[i]->why,
                        wname);
            if (one) {
                if (u.len > 1) {
                    (void)rmt_buf_add(&u, ",", 1);
                }
                (void)rmt_buf_add(&u, one, strlen(one));
            }
            free(one);
        }
        (void)rmt_buf_add(&u, "]", 1);
        { /* every workspace, conversations or not, to start a new one in: W as in W/C */
            rmt_buf w = {NULL, 0, 0};
            (void)rmt_buf_add(&w, "[", 1);
            for (int i = 0; i < st->njs; i++) {
                rmt_journal *j = st->js[i];
                char ms[32] = "0", *one, wname[256];
                sqlite3_stmt *q = NULL;
                if (!j->open || !rmt_shown(st, i)) {
                    continue;
                }
                rmt_ws_name(st, i, wname, sizeof wname);
                if (sqlite3_prepare_v2(j->s.db, "SELECT coalesce(max(updated_ms), 0) FROM pic_session", -1, &q, NULL) == SQLITE_OK &&
                    sqlite3_step(q) == SQLITE_ROW) {
                    (void)snprintf(ms, sizeof ms, "%lld", (long long)sqlite3_column_int64(q, 0));
                }
                sqlite3_finalize(q);
                one = rmt_q("SELECT json_object('id', ?1, 'workspace', ?2, 'lastMs', CAST(?3 AS INTEGER), 'name', ?4)", 4, j->path,
                            j->workspace, ms, wname);
                if (one) {
                    if (w.len > 1) {
                        (void)rmt_buf_add(&w, ",", 1);
                    }
                    (void)rmt_buf_add(&w, one, strlen(one));
                }
                free(one);
            }
            (void)rmt_buf_add(&w, "]", 1);
            { /* the most recently used first */
                char *sorted = rmt_q("SELECT json_group_array(json_remove(value, '$.lastMs')) FROM (SELECT value FROM json_each(?1)"
                                     " ORDER BY json_extract(value, '$.lastMs') DESC)",
                                     1, w.buf ? w.buf : "[]");
                if (sorted) {
                    free(w.buf);
                    w.buf = sorted;
                }
            }
            out = rmt_q("SELECT json_object('type', 'sessions', 'payload', json_object('sessions', json(?1), 'workspaces', json(?3),"
                        " 'unavailable', json(?2), 'features', json_array('images', 'asks')))",
                        3, b.buf ? b.buf : "[]", u.buf ? u.buf : "[]", w.buf ? w.buf : "[]");
            free(w.buf);
        }
        free(u.buf);
    }
    free(b.buf);
    return out;
}

/* ---- following (section 4) --------------------------------------------------------------- */

typedef struct {
    rmt_state *st;
    rmt_dev *d;
} rmt_emit_ctx;

/* A person's message with images goes without their bytes: each image part names its index among
 * the message's images (attach.c puts image K at K + 1) and its size, and the phone asks for the
 * bytes with an image message when it shows it. NULL: EVENT has none. */
static char *rmt_image_refs(const char *event) {
    if (!strstr(event, "\"type\":\"image\"")) {
        return NULL;
    }
    return rmt_q("SELECT CASE WHEN json_extract(?1, '$.message.role') = 'user' AND json_type(?1, '$.message.content') = 'array'"
                 " THEN json_set(?1, '$.message.content', json((SELECT json_group_array(CASE WHEN json_extract(value, '$.type') = 'image'"
                 " THEN json_object('type', 'image', 'mimeType', json_extract(value, '$.mimeType'), 'index', key - 1, 'bytes',"
                 " length(json_extract(value, '$.data')) / 4 * 3 - (json_extract(value, '$.data') LIKE '%=')"
                 " - (json_extract(value, '$.data') LIKE '%==')) ELSE json(value) END ORDER BY key)"
                 " FROM json_each(?1, '$.message.content')))) END",
                 1, event);
}

static int rmt_emit(void *ctx, long long seq, const char *event) {
    rmt_emit_ctx *c = ctx;
    char s[32], *json, *refs = rmt_image_refs(event);
    if (refs) {
        event = refs;
    }
    (void)snprintf(s, sizeof s, "%lld", seq);
    if (seq > c->d->fev) {
        c->d->fev = seq;
    }
    /* The envelope's members before the payload: the sync's key, and for a person's message its
     * origin, remote:DEVICE for a phone's and local for any other (section 4). */
    static const char head[] =
        "SELECT substr(h, 1, length(h) - 1) || ',\"payload\":' || %s || '}' FROM (SELECT json_patch('{}', json_object('type',"
        " 'event', 'session', ?1, 'seq', CAST(?2 AS INTEGER), 'key', nullif(?3, ''), 'origin', CASE WHEN json_extract(?4,"
        " '$.origin') LIKE 'remote:%%' THEN json_extract(?4, '$.origin') WHEN json_extract(?4, '$.type') IN ('message_start',"
        " 'message_end') AND json_extract(?4, '$.message.role') = 'user' THEN 'local' END)) AS h)";
    char sql[1024];
    if (strlen(event) > (256u << 10)) { /* a large event goes as a note of what it was */
        char bytes[32], *t = rmt_q("SELECT json_extract(?1, '$.type')", 1, event);
        (void)snprintf(bytes, sizeof bytes, "%zu", strlen(event));
        (void)snprintf(sql, sizeof sql, head, "json_object('type', 'elided', 'eventType', ?5, 'bytes', CAST(?6 AS INTEGER))");
        json = rmt_q(sql, 6, c->d->wsess, s, c->d->skey, "{}", t ? t : "", bytes);
        free(t);
    } else {
        (void)snprintf(sql, sizeof sql, head, "json(?4)");
        json = rmt_q(sql, 4, c->d->wsess, s, c->d->skey, event);
    }
    free(refs);
    rmt_send_free(c->st, c->d, json);
    return 0;
}
/* Where a follow of CONV starts to show RMT_EARLIER more requests than one from FROM (-1: the latest
 * request's start) does: the seq before the first entry of the oldest of them; -1 when FROM shows
 * them all. The marks carry it as "earlier", and the phone's sync from it scrolls back. */
static long long rmt_earlier(pic_store *s, const char *conv, long long from) {
    sqlite3_stmt *q = NULL;
    long long at = -1;
    if (sqlite3_prepare_v2(s->db,
                           "WITH f(v) AS (SELECT CASE WHEN ?2 >= 0 THEN ?2 ELSE coalesce((SELECT min(e.seq) - 1 FROM pic_entry e"
                           " WHERE e.submission_id = (SELECT max(id) FROM pic_submission WHERE session_id = ?1)), 0) END),"
                           " r(id) AS (SELECT u.id FROM pic_submission u, f WHERE u.session_id = ?1 AND EXISTS (SELECT 1 FROM"
                           " pic_entry x WHERE x.submission_id = u.id AND x.seq <= f.v) ORDER BY u.id DESC LIMIT ?3)"
                           " SELECT max(0, (SELECT min(seq) FROM pic_entry WHERE submission_id = (SELECT min(id) FROM r)) - 1)",
                           -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, conv, -1, SQLITE_STATIC);
        sqlite3_bind_int64(q, 2, from);
        sqlite3_bind_int(q, 3, RMT_EARLIER);
        if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_type(q, 0) != SQLITE_NULL) {
            at = sqlite3_column_int64(q, 0);
        }
    }
    sqlite3_finalize(q);
    return at;
}

/* An image message (section 4): the bytes of image INDEX of the person's message at entry SEQ of
 * the conversation, or why not. */
static void rmt_image(rmt_state *st, rmt_dev *d, const rmt_env *e) {
    char conv[64], *index = e->payload ? rmt_q("SELECT CASE json_type(?1, '$.index') WHEN 'integer' THEN"
                                               " json_extract(?1, '$.index') END", 1, e->payload)
                                       : NULL;
    const char *why = "no_image";
    char *out = NULL;
    int jx;
    if (!index || !e->has_seq || !e->session) {
        rmt_error(st, d, NULL, "bad_message", "an image message names its session, seq and payload.index");
        free(index);
        return;
    }
    if (rmt_resolve(st, e->session, &jx, conv) == 0) {
        sqlite3_stmt *q = NULL;
        if (sqlite3_prepare_v2(st->js[jx]->s.db,
                               "SELECT i.mime, i.data IS NULL, (i.sz + 2) / 3 * 4 + 512 > ?4, CASE WHEN i.data IS NOT NULL AND"
                               " (i.sz + 2) / 3 * 4 + 512 <= ?4 THEN pic_base64(sqlar_uncompress(i.data, i.sz)) END"
                               " FROM pic_attachment a JOIN pic_image i ON i.hash = a.image JOIN pic_entry x ON x.seq = a.entry_seq"
                               " JOIN pic_submission u ON u.id = x.submission_id"
                               " WHERE a.entry_seq = ?1 AND a.ordinal = ?2 AND u.session_id = ?3 AND x.kind = 'user'",
                               -1, &q, NULL) == SQLITE_OK) {
            sqlite3_bind_int64(q, 1, e->seq);
            sqlite3_bind_int64(q, 2, atoll(index));
            sqlite3_bind_text(q, 3, conv, -1, SQLITE_STATIC);
            sqlite3_bind_int64(q, 4, (sqlite3_int64)(RMT_MSG_CAP - strlen(e->session)));
            if (sqlite3_step(q) == SQLITE_ROW) {
                if (sqlite3_column_int(q, 1)) {
                    why = "removed"; /* pic prune took its bytes */
                } else if (sqlite3_column_int(q, 2)) {
                    why = "too_large";
                } else if (sqlite3_column_text(q, 3)) {
                    char s[32];
                    (void)snprintf(s, sizeof s, "%lld", e->seq);
                    out = rmt_q("SELECT json_object('type', 'image', 'session', ?1, 'seq', CAST(?2 AS INTEGER), 'payload',"
                                " json_object('index', CAST(?3 AS INTEGER), 'mimeType', ?4, 'data', ?5))",
                                5, e->session, s, index, (const char *)sqlite3_column_text(q, 0),
                                (const char *)sqlite3_column_text(q, 3));
                }
            }
        }
        sqlite3_finalize(q);
    }
    if (!out) {
        char s[32];
        (void)snprintf(s, sizeof s, "%lld", e->seq);
        out = rmt_q("SELECT json_object('type', 'image', 'session', ?1, 'seq', CAST(?2 AS INTEGER), 'payload',"
                    " json_object('index', CAST(?3 AS INTEGER), 'error', ?4))",
                    4, e->session, s, index, why);
    }
    rmt_send_free(st, d, out);
    free(index);
}

static int rmt_page(void) {
#ifdef PIC_FAULTS
    if (getenv("PIC_TEST_RC_PAGE")) { /* the tests' seam: a history of a few entries goes in pages */
        return atoi(getenv("PIC_TEST_RC_PAGE"));
    }
#endif
    return RMT_PAGE;
}

/* Whether the last call on S failed because another pic holds the journal's write lock. */
static int rmt_busy(pic_store *s) { return (sqlite3_extended_errcode(s->db) & 0xff) == SQLITE_BUSY; }

#define RMT_BUSY_TEXT "this conversation is busy on the computer; try again"

/* One pass for D's conversation: its events, then a mark. */
static void rmt_follow_pass(rmt_state *st, rmt_dev *d) {
    rmt_emit_ctx c = {st, d};
    long long last = 0;
    int running = 0, more = 0;
    char s[32], earlier[32];
    if (!d->f || d->sess < 0) {
        return;
    }
    d->fversion = rmt_data_version(st->js[d->jx]->s.db);
    if (pic_follow_pass(d->f, rmt_emit, &c, rmt_page(), &last, &running, &more) != 0) {
        if (rmt_busy(&st->js[d->jx]->s)) {
            d->follow_now = 1; /* looked at again next tick */
            return;
        }
        rmt_error(st, d, NULL, "unavailable", "cannot read the conversation");
        return;
    }
    d->frunning = running;
    d->follow_now = more; /* a long history goes a page a tick, between everything else */
    (void)snprintf(s, sizeof s, "%lld", last);
    (void)snprintf(earlier, sizeof earlier, "%lld", d->earlier);
    rmt_send_free(st, d,
                  rmt_q("SELECT json_patch('{}', json_object('type', 'sync', 'session', ?1, 'seq', CAST(?2 AS INTEGER), 'key',"
                        " nullif(?4, ''), 'payload', json_object('running', json(?3), 'earlier', CASE WHEN CAST(?5 AS INTEGER) >= 0"
                        " THEN CAST(?5 AS INTEGER) END)))",
                        5, d->wsess, s, running ? "true" : "false", d->skey, earlier));
}

static void rmt_live_reset(rmt_dev *d) {
    d->live_ino = 0;
    d->live_dev = 0;
    d->live_head = d->live_len = 0;
    d->live_pos = d->live_chars = 0;
    d->live_sent = -1;
}

static void rmt_unfollow(rmt_dev *d) {
    pic_follow_free(d->f);
    d->f = NULL;
    free(d->wsess);
    d->wsess = NULL;
    d->skey[0] = '\0';
    d->fev = 0;
    d->frunning = 0;
    d->earlier = -1;
    rmt_live_reset(d);
}

/* ---- the reply as it streams (section 4) -------------------------------------------------- */

/* The characters in P's N bytes: the bytes that start one. */
static long long rmt_chars(const char *p, size_t n) {
    long long c = 0;
    for (size_t i = 0; i < n; i++) {
        c += ((unsigned char)p[i] & 0xC0) != 0x80;
    }
    return c;
}

/* D's live value, from the conversation's .live file (pic_live_path), while its last mark said a
 * request runs: at most one every 250 ms, and only when nothing waits to be posted to it, so one
 * value never queues behind another. A value is sent when the text grew; its seq is the entry the
 * reply came after, never behind an event this follow sent. */
static void rmt_live(rmt_state *st, rmt_dev *d) {
    char path[4096];
    struct stat sb;
    long long now = rmt_mono_ms();
    int fd;
    if (!d->f || d->sess < 0 || !d->frunning || d->lane.qlen || now - d->live_ms < RMT_LIVE_MS ||
        pic_live_path(&st->js[d->jx]->s, d->conv, path, sizeof path) != 0) {
        return;
    }
    if ((fd = open(path, O_RDONLY | O_CLOEXEC | O_NOFOLLOW)) < 0) {
        rmt_live_reset(d); /* no reply is streaming */
        return;
    }
    if (fstat(fd, &sb) != 0 || !S_ISREG(sb.st_mode)) {
        close(fd);
        return;
    }
    if (sb.st_ino != d->live_ino || sb.st_dev != d->live_dev) { /* a new reply */
        char head[64], *nl;
        ssize_t n = pread(fd, head, sizeof head - 1, 0);
        long long seq;
        rmt_live_reset(d);
        if (n <= 0 || !(nl = memchr(head, '\n', (size_t)n)) || (head[n] = '\0', sscanf(head, "pic-live 1 %lld", &seq) != 1)) {
            close(fd); /* its head not written yet */
            return;
        }
        d->live_ino = sb.st_ino;
        d->live_dev = sb.st_dev;
        d->live_head = (size_t)(nl - head) + 1;
        d->live_seq = seq;
    }
    if ((long long)sb.st_size > (long long)d->live_head + d->live_pos) {
        long long avail = (long long)sb.st_size - (long long)d->live_head - d->live_pos;
        size_t want = avail > (1 << 20) ? (size_t)(1 << 20) : (size_t)avail;
        char *tmp = malloc(d->live_len + want);
        ssize_t got = -1;
        if (tmp) {
            memcpy(tmp, d->live_buf, d->live_len);
            got = pread(fd, tmp + d->live_len, want, (off_t)((long long)d->live_head + d->live_pos));
        }
        if (got > 0) {
            size_t keep = d->live_len + (size_t)got, i = keep, cut;
            /* a character cut off at the end waits for its other bytes */
            while (i > d->live_len && keep - i < 3 && ((unsigned char)tmp[i - 1] & 0xC0) == 0x80) {
                i--;
            }
            if (i > d->live_len) {
                unsigned char c = (unsigned char)tmp[i - 1];
                size_t need = c >= 0xF0 ? 4 : c >= 0xE0 ? 3 : c >= 0xC0 ? 2 : 1;
                if (keep - (i - 1) < need) {
                    keep = i - 1;
                }
            }
            d->live_pos += (long long)(keep - d->live_len);
            cut = keep > RMT_LIVE_KEEP ? keep - RMT_LIVE_KEEP : 0;
            while (cut < keep && ((unsigned char)tmp[cut] & 0xC0) == 0x80) {
                cut++;
            }
            d->live_chars += rmt_chars(tmp, cut);
            memmove(d->live_buf, tmp + cut, keep - cut);
            d->live_len = keep - cut;
        }
        free(tmp);
    }
    close(fd);
    if (d->live_len && d->live_pos != d->live_sent && d->live_seq >= d->fev) {
        char seq[32], rev[32], off[32];
        d->live_buf[d->live_len] = '\0';
        (void)snprintf(seq, sizeof seq, "%lld", d->live_seq);
        (void)snprintf(rev, sizeof rev, "%lld", ++st->live_rev);
        (void)snprintf(off, sizeof off, "%lld", d->live_chars);
        rmt_send_free(st, d,
                      rmt_q("SELECT json_object('type', 'live', 'session', ?1, 'seq', CAST(?2 AS INTEGER), 'payload',"
                            " json_object('rev', CAST(?3 AS INTEGER), 'offset', CAST(?4 AS INTEGER), 'text', ?5))",
                            5, d->wsess, seq, rev, off, d->live_buf));
        d->live_sent = d->live_pos;
        d->live_ms = now;
    }
}

/* ---- commands (section 4) ----------------------------------------------------------------- */

static int rmt_cmd_find(rmt_dev *d, const char *key) {
    for (int i = 0; i < d->ncmds; i++) {
        if (strcmp(d->cmds[i].key, key) == 0) {
            return i;
        }
    }
    return -1;
}

static void rmt_cmd_drop(rmt_dev *d, int i) {
    free(d->cmds[i].line);
    free(d->cmds[i].answer);
    if (d->cmds[i].errfd >= 0) {
        close(d->cmds[i].errfd);
    }
    d->cmds[i] = d->cmds[--d->ncmds];
}

static rmt_cmd *rmt_cmd_add(rmt_dev *d, int kind, int jx, const char *key, const char *row, const char *line) {
    rmt_cmd *c;
    if (d->ncmds == RMT_CMDS) {
        rmt_cmd_drop(d, 0);
    }
    c = &d->cmds[d->ncmds++];
    memset(c, 0, sizeof *c);
    c->kind = kind;
    c->jx = jx;
    c->errfd = -1;
    (void)snprintf(c->key, sizeof c->key, "%s", key);
    (void)snprintf(c->row, sizeof c->row, "%s", row);
    c->line = line ? strdup(line) : NULL;
    return c;
}

static void rmt_response(rmt_state *st, rmt_dev *d, const char *key, const char *line) {
    rmt_send_free(st, d, rmt_q("SELECT json_object('type', 'response', 'key', ?1, 'payload', json(?2))", 2, key, line));
}

/* A prompt's success, naming the conversation it went to (a new one's id is learnt here). */
static void rmt_prompt_ok(rmt_state *st, rmt_dev *d, const char *key, int jx, const char *row) {
    rmt_journal *j = st->js[jx];
    sqlite3_stmt *q = NULL;
    char conv[64] = "", *wsess = NULL;
    if (sqlite3_prepare_v2(j->s.db, "SELECT session_id FROM pic_submission WHERE request_key = ?", -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, row, -1, SQLITE_STATIC);
        if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_text(q, 0)) {
            (void)snprintf(conv, sizeof conv, "%s", (const char *)sqlite3_column_text(q, 0));
        }
    }
    sqlite3_finalize(q);
    if (conv[0]) {
        size_t n = strlen(j->path) + strlen(conv) + 2;
        if ((wsess = malloc(n))) {
            (void)snprintf(wsess, n, "%s/%s", j->path, conv);
        }
    }
    rmt_send_free(st, d,
                  rmt_q("SELECT json_patch('{}', json_object('type', 'response', 'key', ?1, 'session', ?2, 'payload',"
                        " json_object('type', 'response', 'command', 'prompt', 'success', json('true'))))",
                        2, key, wsess));
    free(wsess);
}

/* Pi's response line for COMMAND (with the command's id, when it had one). */
static char *rmt_pi_response(const char *payload, const char *command, int success, const char *data, const char *error) {
    return rmt_q("SELECT json_patch('{}', json_object('id', json_extract(?1, '$.id'), 'type', 'response', 'command', ?2,"
                 " 'success', json(?3), 'data', json(?4), 'error', ?5))",
                 5, payload, command, success ? "true" : "false", data, error);
}

static rmt_choice *rmt_choice_find(rmt_state *st, int jx, const char *conv) {
    for (int i = 0; i < st->nchoices; i++) {
        if (st->choices[i].jx == jx && strcmp(st->choices[i].conv, conv) == 0) {
            return &st->choices[i];
        }
    }
    return NULL;
}

/* The conversation's choice, made now when it has none (the oldest gives way). */
static rmt_choice *rmt_choice_get(rmt_state *st, int jx, const char *conv) {
    rmt_choice *c = rmt_choice_find(st, jx, conv);
    if (c) {
        return c;
    }
    if (st->nchoices == RMT_CHOICES) {
        memmove(&st->choices[0], &st->choices[1], (RMT_CHOICES - 1) * sizeof st->choices[0]);
        st->nchoices--;
    }
    c = &st->choices[st->nchoices++];
    memset(c, 0, sizeof *c);
    c->jx = jx;
    (void)snprintf(c->conv, sizeof c->conv, "%s", conv);
    return c;
}

static void rmt_choice_clear(rmt_state *st, int jx, const char *conv) {
    rmt_choice *c = rmt_choice_find(st, jx, conv);
    if (c) {
        *c = st->choices[--st->nchoices];
    }
}

/* The model and thinking level CONV's next request runs on: a phone's choice, else what its last
 * request used, as at the terminal; with FRESH (a new conversation), the workspace's last. */
static void rmt_next_model(rmt_state *st, int jx, const char *conv, int fresh, char *model, size_t mcap, char *thinking,
                           size_t tcap) {
    rmt_choice *c = fresh ? NULL : rmt_choice_find(st, jx, conv);
    sqlite3_stmt *q = NULL;
    model[0] = thinking[0] = '\0';
    if (sqlite3_prepare_v2(st->js[jx]->s.db,
                           "SELECT model, thinking FROM pic_submission WHERE (?2 OR session_id = ?1) AND model IS NOT NULL"
                           " ORDER BY id DESC LIMIT 1",
                           -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, conv, -1, SQLITE_STATIC);
        sqlite3_bind_int(q, 2, fresh);
        if (sqlite3_step(q) == SQLITE_ROW) {
            (void)snprintf(model, mcap, "%s", (const char *)sqlite3_column_text(q, 0));
            if (sqlite3_column_type(q, 1) == SQLITE_TEXT) {
                (void)snprintf(thinking, tcap, "%s", (const char *)sqlite3_column_text(q, 1));
            }
        }
    }
    sqlite3_finalize(q);
    if (c && c->model[0]) {
        (void)snprintf(model, mcap, "%s", c->model);
    }
    if (c && c->thinking[0]) {
        (void)snprintf(thinking, tcap, "%s", c->thinking);
    }
}

/* The newest entries of a conversation's path a phone's question reads (get_messages,
 * get_session_stats, get_state's messageCount): its work is bounded by this, not by how long the
 * conversation is. */
#define RMT_PATH_MOST 300

/* Whether S may build Pi entries for a phone: only with the index of generations by entry, which
 * every pic since it makes when it opens the journal. Without it the build copies all of
 * pic_generation (tens of megabytes) into a temporary index on the loop; then S->err says so. */
static int rmt_entries_ok(pic_store *s) {
    sqlite3_stmt *q = NULL;
    int ok = 0;
    if (sqlite3_prepare_v2(s->db, "SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = 'pic_generation_entry'", -1, &q,
                           NULL) == SQLITE_OK) {
        ok = sqlite3_step(q) == SQLITE_ROW;
    }
    sqlite3_finalize(q);
    if (!ok) {
        (void)snprintf(s->err, sizeof s->err, "open pic in this workspace once on the computer, then ask again");
    }
    return ok;
}

/* get_state and get_messages, answered from the journal; no row. get_state reads no entries:
 * messageCount counts the messages among the newest RMT_PATH_MOST of the path. */
static void rmt_query(rmt_state *st, rmt_dev *d, rmt_env *e, int jx, const char *conv) {
    pic_store *s = &st->js[jx]->s;
    int state = strcmp(e->ptype, "get_state") == 0;
    char *entries = NULL, *msgs = NULL, *data = NULL, *line, count[24] = "0";
    s->err[0] = '\0';
    if (!state) {
        entries = rmt_entries_ok(s) ? pic_pi_entries(s, conv, RMT_PATH_MOST) : NULL;
        msgs = entries ? pic_rpc_messages(s->db, entries) : NULL;
    } else {
        sqlite3_stmt *q = NULL;
        if (sqlite3_prepare_v2(s->db,
                               "WITH RECURSIVE p(seq, n) AS (SELECT head_seq, 1 FROM pic_session WHERE id = ?1"
                               " UNION ALL SELECT x.parent_seq, p.n + 1 FROM pic_entry x JOIN p ON x.seq = p.seq"
                               " WHERE x.parent_seq IS NOT NULL AND p.n < ?2)"
                               " SELECT count(*) FROM p JOIN pic_entry e ON e.seq = p.seq WHERE e.kind IN ('user', 'assistant', 'tool_result')",
                               -1, &q, NULL) == SQLITE_OK) {
            sqlite3_bind_text(q, 1, conv, -1, SQLITE_STATIC);
            sqlite3_bind_int(q, 2, RMT_PATH_MOST);
            if (sqlite3_step(q) == SQLITE_ROW) {
                (void)snprintf(count, sizeof count, "%lld", (long long)sqlite3_column_int64(q, 0));
            }
        }
        sqlite3_finalize(q);
    }
    if (msgs && !state) {
        data = rmt_q("SELECT json_object('messages', json(?1))", 1, msgs);
    } else if (state) {
        sqlite3_stmt *q = NULL;
        if (sqlite3_prepare_v2(s->db,
                               "SELECT json_object('model', json((SELECT CASE WHEN instr(model, '/') THEN json_object('provider',"
                               " substr(model, 1, instr(model, '/') - 1), 'id', substr(model, instr(model, '/') + 1)) END"
                               " FROM pic_submission WHERE session_id = ?1 AND model IS NOT NULL ORDER BY id DESC LIMIT 1)),"
                               " 'thinkingLevel', (SELECT thinking FROM pic_submission WHERE session_id = ?1 AND thinking IS NOT NULL"
                               " ORDER BY id DESC LIMIT 1),"
                               " 'isStreaming', json(iif(EXISTS (SELECT 1 FROM pic_submission WHERE session_id = ?1 AND"
                               " status = 'admitted'), 'true', 'false')), 'isCompacting', json('false'), 'sessionId', ?1,"
                               " 'sessionName', (SELECT name FROM pic_session WHERE id = ?1), 'messageCount', CAST(?2 AS INTEGER),"
                               " 'pendingMessageCount', (SELECT count(*) FROM pic_inbox WHERE session_id = ?1 AND state = 'pending'))",
                               -1, &q, NULL) == SQLITE_OK) {
            sqlite3_bind_text(q, 1, conv, -1, SQLITE_STATIC);
            sqlite3_bind_text(q, 2, count, -1, SQLITE_STATIC);
            if (sqlite3_step(q) == SQLITE_ROW) {
                data = strdup((const char *)sqlite3_column_text(q, 0));
            }
        }
        sqlite3_finalize(q);
        if (data) { /* the key the next request goes with: the phone's choice, else the conversation's own */
            rmt_choice *c = rmt_choice_find(st, jx, conv);
            char model[256], thinking[16], label[PIC_CRED_LABEL_CAP], cred[PIC_CRED_NAME_CAP] = "", *patched;
            int own = pic_session_choice(s, conv, model, sizeof model, thinking, sizeof thinking, label, sizeof label) == 1;
            if (c && c->model[0]) {
                (void)snprintf(model, sizeof model, "%s", c->model);
            }
            if (c && c->key[0]) {
                (void)snprintf(label, sizeof label, "%s", c->key);
            }
            if ((own || (c && c->model[0])) && label[0] && strchr(model, '/')) {
                (void)snprintf(cred, sizeof cred, "%.*s:%s", (int)(strchr(model, '/') - model), model, label);
            }
            patched = cred[0] ? rmt_q("SELECT json_set(?1, '$.credential', ?2)", 2, data, cred) : NULL;
            if (patched) {
                free(data);
                data = patched;
            }
        }
        if (data) { /* the questions it waits on a person for (ask.h) */
            char *asks = pic_ask_list(s, conv, -1, RMT_ASKS), *settled = pic_ask_settled(s, conv), *names = rmt_device_names(st);
            char *patched = asks && settled && names
                                ? rmt_q("SELECT json_set(?1, '$.asks', json((SELECT json_group_array(json(json_remove(value, '$.session', '$.version')))"
                                        " FROM json_each(?2))), '$.settledAsks', json((SELECT json_group_array(json(" RMT_SETTLED_SQL("value", "?4") "))"
                                        " FROM json_each(?3))))",
                                        4, data, asks, settled, names)
                                : NULL;
            free(settled);
            free(names);
            if (patched) {
                free(data);
                data = patched;
            }
            free(asks);
        }
        if (data && rmt_choice_find(st, jx, conv)) { /* what the next request runs on */
            char model[256], thinking[32], *patched;
            rmt_next_model(st, jx, conv, 0, model, sizeof model, thinking, sizeof thinking);
            patched = rmt_q("SELECT json_set(?1, '$.model', CASE WHEN instr(?2, '/') THEN json_object('provider', substr(?2, 1,"
                            " instr(?2, '/') - 1), 'id', substr(?2, instr(?2, '/') + 1)) END, '$.thinkingLevel', nullif(?3, ''))",
                            3, data, model, thinking);
            if (patched) {
                free(data);
                data = patched;
            }
        }
    }
    line = rmt_pi_response(e->payload, e->ptype, data != NULL, data, data ? NULL : s->err[0] ? s->err : "cannot read the conversation");
    rmt_response(st, d, e->key, line);
    free(line);
    free(data);
    free(msgs);
    free(entries);
}

static int rmt_running(pic_store *s, const char *conv) {
    sqlite3_stmt *q = NULL;
    int running = 0;
    if (sqlite3_prepare_v2(s->db, "SELECT EXISTS (SELECT 1 FROM pic_submission WHERE session_id = ? AND status = 'admitted')", -1,
                           &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, conv, -1, SQLITE_STATIC);
        running = sqlite3_step(q) == SQLITE_ROW && sqlite3_column_int(q, 0);
    }
    sqlite3_finalize(q);
    return running;
}

/* Whether a request was admitted under ROW (the keyed admission's key). */
static int rmt_admitted(pic_store *s, const char *row) {
    sqlite3_stmt *q = NULL;
    int yes = 0;
    if (sqlite3_prepare_v2(s->db, "SELECT 1 FROM pic_submission WHERE request_key = ?", -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, row, -1, SQLITE_STATIC);
        yes = sqlite3_step(q) == SQLITE_ROW;
    }
    sqlite3_finalize(q);
    return yes;
}

/* steer, follow_up and abort through pic_inbox_accept, unchanged: ack once committed, the response
 * once the row leaves pending. */
static void rmt_inbox(rmt_state *st, rmt_dev *d, const char *key, int jx, const char *conv, const char *line) {
    pic_store *s = &st->js[jx]->s;
    pic_inbox_msg m;
    char row[96], sender[48], got[64], state[16];
    int rc;
    (void)snprintf(row, sizeof row, "rc:%s:%s", d->idb, key);
    (void)snprintf(sender, sizeof sender, "remote:%s", d->idb);
    memset(&m, 0, sizeof m);
    m.session = conv;
    m.key = row;
    m.line = line;
    m.sender = sender;
    rc = pic_inbox_accept(s, &m, got, sizeof got, state, sizeof state);
    if (rc < 0 && rmt_busy(s)) {
        rmt_error(st, d, key, "busy", RMT_BUSY_TEXT);
        return;
    }
    if (rc != 0) {
        rmt_error(st, d, key, rc > 0 ? "refused" : "failed", s->err);
        return;
    }
    if (strcmp(state, "pending") == 0) {
        if (rmt_cmd_find(d, key) < 0) {
            (void)rmt_cmd_add(d, CMD_INBOX, jx, key, row, line);
        }
        rmt_send_free(st, d, rmt_q("SELECT json_object('type', 'ack', 'key', ?1, 'payload', json_object('state', 'pending'))", 1, key));
        return;
    }
    {
        char *response = NULL;
        if (pic_inbox_status(s, row, state, sizeof state, &response) == 0 && response) {
            rmt_response(st, d, key, response);
        } else {
            rmt_send_free(st, d, rmt_q("SELECT json_object('type', 'response', 'key', ?1, 'payload', json_object('state', ?2))", 2,
                                       key, state));
        }
        free(response);
    }
}

/* A prompt's images, Pi's image content: 0 with none, 1 with *JSON their array (malloc'd), checked as
 * a pasted image is, or -1 with WHY when they are not images pic can send. */
static int rmt_prompt_images(const char *payload, char **json, char *why, size_t cap) {
    char *t = rmt_q("SELECT json_type(?1, '$.images')", 1, payload);
    pic_image *images = NULL;
    unsigned char *bytes = NULL;
    size_t n = 0;
    const char *error = NULL;
    char *text = NULL;
    int rc;
    *json = NULL;
    if (!t || strcmp(t, "null") == 0) {
        free(t);
        return 0;
    }
    rc = strcmp(t, "array") == 0 ? 0 : -1;
    free(t);
    if (rc != 0) {
        (void)snprintf(why, cap, "images must be an array");
        return -1;
    }
    if (pic_images_from_json(rmt_mem(), payload, "$.images", 1, &images, &n, &bytes, &error) != 0) {
        (void)snprintf(why, cap, "%s", error ? error : "images must be an array of image content");
        rc = -1;
    } else if (n && !(text = pic_image_prepare("", images, &n, why, cap))) {
        rc = -1;
    } else if (n) {
        rc = (*json = rmt_q("SELECT json_extract(?1, '$.images')", 1, payload)) ? 1 : -1;
        if (rc < 0) {
            (void)snprintf(why, cap, "out of memory");
        }
    }
    free(text);
    free(images);
    free(bytes);
    return rc;
}

/* prompt with nothing running: what pic submit KEY TEXT --session ID does, then pic run --session
 * ID, in one detached child in a session of its own, so it outlives pic remote. The submit runs
 * in a grandchild whose stderr comes back here; the run gets the master key over the handoff pipe
 * and no pipe to this process. */
/* A prompt as a keyed admission and a detached run. FRESH: CONV is a new conversation's id. */
static void rmt_prompt(rmt_state *st, rmt_dev *d, const char *key, int jx, const char *conv, const char *text,
                       const char *images, int fresh) {
    extern char **environ;
    rmt_journal *j = st->js[jx];
    const char *sub[20], *run[16];
    char row[96], keyenv[32], model[256] = "", thinking[32] = "", keylabel[PIC_CRED_LABEL_CAP] = "";
    char **env = NULL;
    size_t ne = 0;
    int errp[2], keyfd, null, imgfd = -1;
    pid_t pid;
    rmt_cmd *c;
    (void)snprintf(row, sizeof row, "rc:%s:%s", d->idb, key);
    rmt_next_model(st, jx, conv, fresh, model, sizeof model, thinking, sizeof thinking);
    {
        int a = 0, b = 0;
        const char *const head[] = {st->o->self, "--db", j->path, "--workspace", j->workspace};
        for (int i = 0; i < 5; i++) {
            sub[a++] = run[b++] = head[i];
        }
        if (model[0]) {
            sub[a++] = run[b++] = "--model";
            sub[a++] = run[b++] = model;
        }
        if (thinking[0]) {
            sub[a++] = run[b++] = "--thinking";
            sub[a++] = run[b++] = thinking;
        }
        {
            rmt_choice *ch = fresh ? NULL : rmt_choice_find(st, jx, conv);
            if (ch && ch->key[0]) { /* the phone's key for this conversation: the run's, as --key */
                (void)snprintf(keylabel, sizeof keylabel, "%s", ch->key);
                run[b++] = "--key";
                run[b++] = keylabel;
            }
        }
        sub[a++] = "submit";
        sub[a++] = row;
        sub[a++] = text;
        sub[a++] = fresh ? "--new-session" : "--session";
        sub[a++] = conv;
        if (images) { /* on the submit's stdin: a file no one else can open, gone when it closes */
            sub[a++] = "--images";
            sub[a++] = "-";
        }
        sub[a] = NULL;
        run[b++] = "run";
        run[b++] = "--session";
        run[b++] = conv;
        run[b] = NULL;
    }
    if (rmt_admitted(&j->s, row)) { /* a second admission with the key reports the first */
        rmt_prompt_ok(st, d, key, jx, row);
        return;
    }
    if (rmt_cmd_find(d, key) >= 0) {
        return; /* starting already */
    }
    if (images) {
        const char *tmp = getenv("TMPDIR");
        char path[PATH_MAX];
        size_t n = strlen(images), at = 0;
        (void)snprintf(path, sizeof path, "%s/pic-rc-images.XXXXXX", tmp && *tmp ? tmp : "/tmp");
        if ((imgfd = mkstemp(path)) >= 0) {
            (void)unlink(path);
            while (at < n) {
                ssize_t w = write(imgfd, images + at, n - at);
                if (w < 0 && errno == EINTR) {
                    continue;
                }
                if (w <= 0) {
                    break;
                }
                at += (size_t)w;
            }
            if (at < n || lseek(imgfd, 0, SEEK_SET) != 0) {
                close(imgfd);
                imgfd = -1;
            } else {
                (void)fcntl(imgfd, F_SETFD, FD_CLOEXEC);
            }
        }
        if (imgfd < 0) {
            rmt_error(st, d, key, "failed", "cannot keep the images for the request");
            return;
        }
    }
    /* Everything the children need is made before the fork: the stream thread may hold the
     * allocator's lock at that moment, so the child calls nothing that allocates. */
    while (environ[ne]) {
        ne++;
    }
    if (!(env = calloc(ne + 2, sizeof *env)) || pipe(errp) != 0) {
        free(env);
        if (imgfd >= 0) {
            close(imgfd);
        }
        rmt_error(st, d, key, "failed", strerror(errno));
        return;
    }
    if ((null = open("/dev/null", O_RDWR)) < 0) {
        free(env);
        close(errp[0]);
        close(errp[1]);
        if (imgfd >= 0) {
            close(imgfd);
        }
        rmt_error(st, d, key, "failed", strerror(errno));
        return;
    }
    keyfd = pic_cred_handoff();
    {
        size_t k = 0;
        for (size_t i = 0; i < ne; i++) {
            if (strncmp(environ[i], "PIC_KEY_FD=", 11) != 0) {
                env[k++] = environ[i];
            }
        }
        if (keyfd >= 0) {
            (void)snprintf(keyenv, sizeof keyenv, "PIC_KEY_FD=%d", keyfd);
            env[k++] = keyenv;
        }
        env[k] = NULL;
    }
    pid = fork();
    if (pid == 0) {
        int status = 0;
        pid_t g;
        if (st->lockfd >= 0) { /* the request must not hold pic remote's lock */
            close(st->lockfd);
        }
        (void)setsid();
        (void)signal(SIGINT, SIG_DFL);
        (void)signal(SIGTERM, SIG_DFL);
        (void)signal(SIGPIPE, SIG_DFL);
        (void)dup2(null, STDIN_FILENO);
        (void)dup2(null, STDOUT_FILENO);
        close(errp[0]);
        g = fork();
        if (g == 0) { /* the submit: its stderr comes back; no key, which it does not need */
            if (keyfd >= 0) {
                close(keyfd);
            }
            (void)dup2(errp[1], STDERR_FILENO);
            close(errp[1]);
            if (imgfd >= 0) {
                (void)dup2(imgfd, STDIN_FILENO);
            }
            execv(st->o->self, (char *const *)(void *)sub);
            _exit(127);
        }
        while (g > 0 && waitpid(g, &status, 0) < 0 && errno == EINTR) {
        }
        (void)dup2(null, STDERR_FILENO);
        close(errp[1]);
        if (g < 0 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) {
            _exit(1);
        }
        if (keyfd >= 0) {
            (void)fcntl(keyfd, F_SETFD, 0);
        }
        execve(st->o->self, (char *const *)(void *)run, env);
        _exit(127);
    }
    free(env);
    close(null);
    if (keyfd >= 0) {
        close(keyfd);
    }
    if (imgfd >= 0) {
        close(imgfd);
    }
    close(errp[1]);
    if (pid < 0) {
        close(errp[0]);
        rmt_error(st, d, key, "failed", strerror(errno));
        return;
    }
    (void)fcntl(errp[0], F_SETFD, FD_CLOEXEC);
    (void)fcntl(errp[0], F_SETFL, O_NONBLOCK);
    c = rmt_cmd_add(d, CMD_PROMPT, jx, key, row, NULL);
    c->pid = pid;
    c->errfd = errp[0];
    if (!fresh) { /* the request records the choice from here on */
        rmt_choice_clear(st, jx, conv);
    }
}

/* compact: pic compact --now in a child of its own, with the conversation's next model; the
 * response when it ends. A request running refuses it, where Pi's compact would stop the request. */
static void rmt_compact(rmt_state *st, rmt_dev *d, rmt_env *e, int jx, const char *conv) {
    extern char **environ;
    rmt_journal *j = st->js[jx];
    char model[256], thinking[32], keyenv[32], row[96];
    char *focus = rmt_q("SELECT CASE json_type(?1, '$.customInstructions') WHEN 'text' THEN json_extract(?1, '$.customInstructions')"
                        " END", 1, e->payload);
    const char *argv[16];
    char **env = NULL;
    size_t ne = 0;
    int n = 0, errp[2], keyfd, null;
    pid_t pid;
    rmt_cmd *c;
    if (rmt_running(&j->s, conv)) {
        char *line = rmt_pi_response(e->payload, "compact", 0, NULL, "A request is running. Stop it, or compact when it ends.");
        rmt_response(st, d, e->key, line);
        free(line);
        free(focus);
        return;
    }
    rmt_next_model(st, jx, conv, 0, model, sizeof model, thinking, sizeof thinking);
    argv[n++] = st->o->self;
    argv[n++] = "--db";
    argv[n++] = j->path;
    argv[n++] = "--workspace";
    argv[n++] = j->workspace;
    if (model[0]) {
        argv[n++] = "--model";
        argv[n++] = model;
    }
    argv[n++] = "compact";
    argv[n++] = "--now";
    argv[n++] = conv;
    if (focus && *focus) {
        argv[n++] = focus;
    }
    argv[n] = NULL;
    while (environ[ne]) {
        ne++;
    }
    if (!(env = calloc(ne + 2, sizeof *env)) || pipe(errp) != 0) {
        free(env);
        free(focus);
        rmt_error(st, d, e->key, "failed", strerror(errno));
        return;
    }
    if ((null = open("/dev/null", O_RDWR)) < 0) {
        free(env);
        free(focus);
        close(errp[0]);
        close(errp[1]);
        rmt_error(st, d, e->key, "failed", strerror(errno));
        return;
    }
    keyfd = pic_cred_handoff();
    {
        size_t k = 0;
        for (size_t i = 0; i < ne; i++) {
            if (strncmp(environ[i], "PIC_KEY_FD=", 11) != 0) {
                env[k++] = environ[i];
            }
        }
        if (keyfd >= 0) {
            (void)snprintf(keyenv, sizeof keyenv, "PIC_KEY_FD=%d", keyfd);
            env[k++] = keyenv;
        }
        env[k] = NULL;
    }
    pid = fork();
    if (pid == 0) { /* nothing that allocates: the stream thread may hold the allocator's lock */
        if (st->lockfd >= 0) {
            close(st->lockfd);
        }
        (void)setsid();
        (void)signal(SIGINT, SIG_DFL);
        (void)signal(SIGTERM, SIG_DFL);
        (void)signal(SIGPIPE, SIG_DFL);
        (void)dup2(null, STDIN_FILENO);
        (void)dup2(null, STDOUT_FILENO);
        (void)dup2(errp[1], STDERR_FILENO);
        close(errp[0]);
        close(errp[1]);
        if (keyfd >= 0) {
            (void)fcntl(keyfd, F_SETFD, 0);
        }
        execve(st->o->self, (char *const *)(void *)argv, env);
        _exit(127);
    }
    free(env);
    free(focus);
    close(null);
    if (keyfd >= 0) {
        close(keyfd);
    }
    close(errp[1]);
    if (pid < 0) {
        close(errp[0]);
        rmt_error(st, d, e->key, "failed", strerror(errno));
        return;
    }
    (void)fcntl(errp[0], F_SETFD, FD_CLOEXEC);
    (void)fcntl(errp[0], F_SETFL, O_NONBLOCK);
    (void)snprintf(row, sizeof row, "rc:%s:%s", d->idb, e->key);
    c = rmt_cmd_add(d, CMD_COMPACT, jx, e->key, row, e->payload);
    c->pid = pid;
    c->errfd = errp[0];
    (void)snprintf(c->conv, sizeof c->conv, "%s", conv);
}

/* Whether SQL (one ?1, the payload) answers 1. */
static int rmt_q_bool(const char *sql, const char *payload) {
    char *v = rmt_q(sql, 1, payload);
    int yes = v && strcmp(v, "1") == 0;
    free(v);
    return yes;
}

/* Answers that need no row: the conversation's stats, the levels and models a phone can pick. */
static void rmt_ask(rmt_state *st, rmt_dev *d, rmt_env *e, int jx, const char *conv) {
    char model[256], thinking[32], *line = NULL;
    const char *t = e->ptype;
    rmt_next_model(st, jx, conv, 0, model, sizeof model, thinking, sizeof thinking);
    if (strcmp(t, "get_session_stats") == 0) {
        char *data = rmt_entries_ok(&st->js[jx]->s) ? pic_rpc_session_stats_recent(&st->js[jx]->s, conv, model, RMT_PATH_MOST) : NULL;
        line = rmt_pi_response(e->payload, t, data != NULL, data, data ? NULL : st->js[jx]->s.err);
        free(data);
    } else if (strcmp(t, "get_available_thinking_levels") == 0) {
        char levels[192], data[224];
        (void)pic_rpc_levels(model, levels, sizeof levels);
        (void)snprintf(data, sizeof data, "{\"levels\":%s}", levels);
        line = rmt_pi_response(e->payload, t, 1, data, NULL);
    } else if (st->o->ask) { /* get_available_models: a component's */
        line = st->o->ask(st->js[jx]->workspace, model, e->payload);
    }
    if (line) {
        rmt_response(st, d, e->key, line);
    } else {
        rmt_error(st, d, e->key, "failed", "no answer");
    }
    free(line);
}

/* set_model, set_thinking_level: the conversation's next request runs on the choice; and
 * set_session_name, the conversation's name, written to the journal as pic --mode rpc does. */
static void rmt_set(rmt_state *st, rmt_dev *d, rmt_env *e, int jx, const char *conv) {
    const char *t = e->ptype;
    char *line = NULL;
    if (strcmp(t, "set_model") == 0) {
        char *name = rmt_q("SELECT CASE WHEN json_type(?1, '$.provider') = 'text' AND json_type(?1, '$.modelId') = 'text' THEN"
                           " json_extract(?1, '$.provider') || '/' || json_extract(?1, '$.modelId') END",
                           1, e->payload);
        char *profile = rmt_q("SELECT CASE json_type(?1, '$.profile') WHEN 'text' THEN json_extract(?1, '$.profile') END", 1, e->payload);
        char pmodel[200] = "", pkey[PIC_CRED_LABEL_CAP] = "", plevel[16] = "";
        char *obj = NULL;
        if (profile && pic_profile_get(profile, pmodel, sizeof pmodel, pkey, sizeof pkey, plevel, sizeof plevel)) {
            free(name); /* pic's: a profile's model, key and level */
            name = strdup(pmodel);
        }
        free(profile);
        if (name && st->o->ask) { /* one of the available models, as Pi's set_model requires */
            char *all = st->o->ask(st->js[jx]->workspace, name, "{\"type\":\"get_available_models\"}");
            obj = all ? rmt_q("SELECT value FROM json_each(?1, '$.data.models') WHERE json_extract(value, '$.provider') || '/' ||"
                              " json_extract(value, '$.id') = ?2",
                              2, all, name)
                      : NULL;
            free(all);
        } else if (name) {
            obj = pic_rpc_model_json(name, NULL);
        }
        if (!name) {
            line = rmt_pi_response(e->payload, t, 0, NULL, "provider and modelId must be strings");
        } else if (!obj || strlen(name) >= sizeof st->choices[0].model) {
            char msg[320];
            (void)snprintf(msg, sizeof msg, "Model not found: %.290s", name);
            line = rmt_pi_response(e->payload, t, 0, NULL, msg);
        } else {
            rmt_choice *c = rmt_choice_get(st, jx, conv);
            (void)snprintf(c->model, sizeof c->model, "%s", name);
            (void)snprintf(c->key, sizeof c->key, "%s", pkey); /* a model alone: its provider's key, by its rules */
            if (plevel[0]) {
                (void)snprintf(c->thinking, sizeof c->thinking, "%s", plevel);
            }
            line = rmt_pi_response(e->payload, t, 1, obj, NULL);
        }
        free(obj);
        free(name);
    } else if (strcmp(t, "set_credential") == 0) {
        /* the key this conversation's next requests use; persist: the provider's saved key, as pic auth use */
        char *provider = rmt_q("SELECT CASE json_type(?1, '$.provider') WHEN 'text' THEN json_extract(?1, '$.provider') END", 1, e->payload);
        char *label = rmt_q("SELECT CASE json_type(?1, '$.label') WHEN 'text' THEN json_extract(?1, '$.label') END", 1, e->payload);
        char probe[128], err[PIC_ERR_CAP], model[256], thinking[32];
        pic_model m;
        (void)snprintf(probe, sizeof probe, "%s/x", provider ? provider : "");
        rmt_next_model(st, jx, conv, 0, model, sizeof model, thinking, sizeof thinking);
        if (!provider || !label || pic_model_resolve(probe, &m, err, sizeof err) != 0 || strcmp(m.provider, provider) != 0) {
            line = rmt_pi_response(e->payload, t, 0, NULL, "set_credential needs a provider pic knows and a label");
        } else if (!pic_cred_has(provider, label, m.key_env, m.key_literal)) {
            (void)snprintf(err, sizeof err, "%.64s has no key named \"%.40s\"", provider, label);
            line = rmt_pi_response(e->payload, t, 0, NULL, err);
        } else if (rmt_q_bool("SELECT json_extract(?1, '$.persist')", e->payload) && st->o->ask) {
            line = st->o->ask(st->js[jx]->workspace, model, e->payload);
        } else {
            rmt_choice *c = rmt_choice_get(st, jx, conv);
            char data[200];
            if (!c->model[0] && strncmp(model, provider, strlen(provider)) == 0 && model[strlen(provider)] == '/') {
                (void)snprintf(c->model, sizeof c->model, "%s", model);
            }
            (void)snprintf(c->key, sizeof c->key, "%s", label);
            (void)snprintf(data, sizeof data, "{\"provider\":\"%s\",\"label\":\"%s\",\"persist\":false}", provider, label);
            line = rmt_pi_response(e->payload, t, 1, data, NULL);
        }
        free(provider);
        free(label);
    } else if (strcmp(t, "set_thinking_level") == 0) {
        char *level = rmt_q("SELECT CASE json_type(?1, '$.level') WHEN 'text' THEN json_extract(?1, '$.level') END", 1, e->payload);
        if (!level || pic_thinking_index(level) < 0) {
            char msg[160];
            (void)snprintf(msg, sizeof msg, "Invalid thinking level: %.40s (off, minimal, low, medium, high, xhigh, max)",
                           level ? level : "(not a string)");
            line = rmt_pi_response(e->payload, t, 0, NULL, msg);
        } else {
            rmt_choice *c = rmt_choice_get(st, jx, conv);
            (void)snprintf(c->thinking, sizeof c->thinking, "%s", level);
            line = rmt_pi_response(e->payload, t, 1, NULL, NULL);
        }
        free(level);
    } else { /* set_session_name */
        pic_store *s = &st->js[jx]->s;
        char *name = rmt_q("SELECT CASE json_type(?1, '$.name') WHEN 'text' THEN trim(json_extract(?1, '$.name'), ' ' ||"
                           " char(9, 10, 13)) END",
                           1, e->payload);
        if (!name || !*name) {
            line = rmt_pi_response(e->payload, t, 0, NULL, "Session name cannot be empty");
        } else if (pic_session_name(s, conv, name) != 0) {
            line = rmt_pi_response(e->payload, t, 0, NULL, s->err);
        } else {
            line = rmt_pi_response(e->payload, t, 1, NULL, NULL);
        }
        free(name);
    }
    rmt_response(st, d, e->key, line);
    free(line);
}

/* delete_session and restore_session (pic's own): the conversation deleted, or brought back, as pic
 * sessions delete and restore do; the list the phone gets next leaves it out, or has it again. */
/* A conversation's loops (wake.h), pic's own commands: get_wakes lists them; pause_wake,
 * resume_wake and stop_wake act on one of the conversation's by id; pause_wakes on all. Each
 * action is committed before the answer, and a repeat answers the same. */
static void rmt_wake(rmt_state *st, rmt_dev *d, rmt_env *e, int jx, const char *conv) {
    pic_store *s = &st->js[jx]->s;
    const char *t = e->ptype;
    char *id = rmt_q("SELECT CASE json_type(?1, '$.id') WHEN 'text' THEN json_extract(?1, '$.id') END", 1, e->payload);
    char *list = NULL, *data = NULL, *line, why[PIC_ERR_CAP] = "", by[48];
    long long wid = 0;
    int count = 0;
    (void)snprintf(by, sizeof by, "remote:%s", d->idb);
    if (strcmp(t, "pause_wakes") == 0) {
        if (pic_wake_pause_all(s, conv, "paused from a phone", &count) != 0) {
            (void)snprintf(why, sizeof why, "%s", s->err);
        }
    } else if (strcmp(t, "get_wakes") != 0) {
        char owner[64] = "";
        if (!id) {
            (void)snprintf(why, sizeof why, "id is required (L1)");
        } else if (pic_wake_resolve(s, id, &wid) != 0) {
            (void)snprintf(why, sizeof why, "%s", s->err);
        } else {
            sqlite3_stmt *q = NULL;
            if (sqlite3_prepare_v2(s->db, "SELECT session_id FROM pic_wake WHERE id = ?", -1, &q, NULL) == SQLITE_OK) {
                sqlite3_bind_int64(q, 1, wid);
                if (sqlite3_step(q) == SQLITE_ROW) {
                    (void)snprintf(owner, sizeof owner, "%s", (const char *)sqlite3_column_text(q, 0));
                }
            }
            sqlite3_finalize(q);
            if (strcmp(owner, conv) != 0) {
                (void)snprintf(why, sizeof why, "no loop %s in this conversation", id);
            } else if ((strcmp(t, "approve_wake") == 0 || strcmp(t, "decline_wake") == 0
                            ? pic_wake_answer(s, wid, t[0] == 'a', by) % 2 /* decided so already (2) is done too */
                            : pic_wake_set(s, wid, strcmp(t, "pause_wake") == 0 ? "pause" : strcmp(t, "resume_wake") == 0 ? "resume" : "stop",
                                           strcmp(t, "pause_wake") == 0 ? "paused from a phone" : NULL)) != 0) {
                (void)snprintf(why, sizeof why, "%s", s->err);
            }
        }
    }
    if (!why[0] && !(list = pic_wake_list(s, conv, 0))) {
        (void)snprintf(why, sizeof why, "%s", s->err);
    }
    if (why[0] && rmt_busy(s)) {
        (void)snprintf(why, sizeof why, "%s", RMT_BUSY_TEXT);
    }
    if (!why[0]) {
        char n[16], now[32];
        (void)snprintf(n, sizeof n, "%d", count);
        (void)snprintf(now, sizeof now, "%lld", pic_wake_now_ms());
        data = rmt_q("SELECT json_patch(json_object('wakes', json(?1), 'nowMs', CAST(?4 AS INTEGER)), json_object('paused',"
                     " CASE WHEN ?2 = 'pause_wakes' THEN CAST(?3 AS INTEGER) END))",
                     4, list, t, n, now);
    }
    line = rmt_pi_response(e->payload, t, !why[0], data, why[0] ? why : NULL);
    rmt_response(st, d, e->key, line);
    free(line);
    free(data);
    free(list);
    free(id);
}

static void rmt_trash(rmt_state *st, rmt_dev *d, rmt_env *e, int jx, const char *conv) {
    pic_store *s = &st->js[jx]->s;
    char id[64], title[160], *line;
    int rc = strcmp(e->ptype, "delete_session") == 0 ? pic_trash_delete(s, conv, id, sizeof id, title, sizeof title)
                                                      : pic_trash_restore(s, conv, id, sizeof id, title, sizeof title);
    line = rmt_pi_response(e->payload, e->ptype, rc == 0, NULL, rc == 0 ? NULL : s->err);
    rmt_response(st, d, e->key, line);
    free(line);
}

static void rmt_answer(rmt_state *st, rmt_dev *d, rmt_env *e, int jx, const char *conv);

static void rmt_command(rmt_state *st, rmt_dev *d, rmt_env *e) {
    int jx;
    char conv[64];
    const char *t = e->ptype;
    if (!rmt_key_ok(e->key)) {
        rmt_error(st, d, NULL, "bad_key", "a command's key is 16 to 43 characters of A-Z, a-z, 0-9, _ and -");
        return;
    }
    if (!e->payload || !*t) {
        rmt_error(st, d, e->key, "bad_command", "a command's payload is a Pi RPC command");
        return;
    }
    if (e->session && e->session[0] == '+') { /* +W: a prompt that starts a new conversation in W */
        char *text = strcmp(t, "prompt") == 0
                         ? rmt_q("SELECT CASE json_type(?1, '$.message') WHEN 'text' THEN json_extract(?1, '$.message') END", 1, e->payload)
                         : NULL;
        char row[96], why[256];
        char *images = NULL;
        int imgs = strcmp(t, "prompt") == 0 ? rmt_prompt_images(e->payload, &images, why, sizeof why) : 0;
        jx = -1;
        for (int i = 0; i < st->njs; i++) {
            if (st->js[i]->open && strcmp(st->js[i]->path, e->session + 1) == 0) {
                jx = i;
            }
        }
        (void)snprintf(row, sizeof row, "rc:%s:%s", d->idb, e->key);
        if (jx < 0) {
            rmt_error(st, d, e->key, "no_session", "no such workspace");
        } else if (strcmp(t, "prompt") != 0) {
            rmt_error(st, d, e->key, "bad_command", "a new conversation starts with a prompt");
        } else if (imgs < 0) {
            rmt_error(st, d, e->key, "bad_command", why);
        } else if (!text || (!*text && !imgs)) {
            rmt_error(st, d, e->key, "bad_command", "a prompt needs its message");
        } else if (rmt_admitted(&st->js[jx]->s, row)) {
            rmt_prompt_ok(st, d, e->key, jx, row);
        } else if (rmt_cmd_find(d, e->key) < 0) {
            unsigned char r[4];
            char id[16] = "";
            for (int tries = 0; tries < 8 && !id[0]; tries++) { /* a fresh id, as the journal makes them */
                sqlite3_stmt *q = NULL;
                if (pic_platform_get()->entropy(r, sizeof r) != 0) {
                    break;
                }
                rmt_hex(r, sizeof r, id);
                if (sqlite3_prepare_v2(st->js[jx]->s.db, "SELECT 1 FROM pic_session WHERE id = ?", -1, &q, NULL) == SQLITE_OK) {
                    sqlite3_bind_text(q, 1, id, -1, SQLITE_STATIC);
                    if (sqlite3_step(q) == SQLITE_ROW) {
                        id[0] = '\0';
                    }
                }
                sqlite3_finalize(q);
            }
            if (id[0]) {
                rmt_prompt(st, d, e->key, jx, id, text, images, 1);
            } else {
                rmt_error(st, d, e->key, "failed", "no id for a new conversation");
            }
        }
        free(text);
        free(images);
        return;
    }
    if (rmt_resolve(st, e->session, &jx, conv) != 0) {
        rmt_error(st, d, e->key, "no_session", "no such conversation");
        return;
    }
    {
        int known = rmt_cmd_find(d, e->key);
        if (known >= 0 && d->cmds[known].line && strcmp(d->cmds[known].line, e->payload) != 0) {
            rmt_error(st, d, e->key, "refused", "that key was used for another command");
            return;
        }
        if (known >= 0 && d->cmds[known].kind == CMD_DONE) { /* a repeat: the same answer */
            rmt_response(st, d, e->key, d->cmds[known].answer);
            return;
        }
        if (known >= 0 && d->cmds[known].kind == CMD_COMPACT) {
            return; /* still compacting */
        }
    }
    if (strcmp(t, "get_state") == 0 || strcmp(t, "get_messages") == 0) {
        rmt_query(st, d, e, jx, conv);
    } else if (strcmp(t, "steer") == 0 || strcmp(t, "follow_up") == 0 || strcmp(t, "abort") == 0) {
        rmt_inbox(st, d, e->key, jx, conv, e->payload);
    } else if (strcmp(t, "prompt") == 0) {
        char *text = rmt_q("SELECT CASE json_type(?1, '$.message') WHEN 'text' THEN json_extract(?1, '$.message') END", 1, e->payload);
        char *behavior = rmt_q("SELECT json_extract(?1, '$.streamingBehavior')", 1, e->payload);
        char *images = NULL;
        char row[96], why[256];
        int imgs = rmt_prompt_images(e->payload, &images, why, sizeof why);
        (void)snprintf(row, sizeof row, "rc:%s:%s", d->idb, e->key);
        if (imgs < 0) {
            rmt_error(st, d, e->key, "bad_command", why);
        } else if (!text || (!*text && !imgs)) {
            rmt_error(st, d, e->key, "bad_command", "a prompt needs its message");
        } else if (rmt_admitted(&st->js[jx]->s, row) || rmt_cmd_find(d, e->key) >= 0 || !rmt_running(&st->js[jx]->s, conv)) {
            rmt_prompt(st, d, e->key, jx, conv, text, images, 0);
        } else if (behavior && (strcmp(behavior, "steer") == 0 || strcmp(behavior, "followUp") == 0)) {
            char *line = rmt_q("SELECT json_patch(json_object('type', ?1, 'message', ?2), json_object('images', json(?3)))", 3,
                               strcmp(behavior, "steer") == 0 ? "steer" : "follow_up", text, images);
            if (line) {
                rmt_inbox(st, d, e->key, jx, conv, line);
            }
            free(line);
        } else {
            char *line = rmt_pi_response(e->payload, "prompt", 0, NULL,
                                         "Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message.");
            rmt_response(st, d, e->key, line);
            free(line);
        }
        free(text);
        free(behavior);
        free(images);
    } else if (strcmp(t, "get_session_stats") == 0 || strcmp(t, "get_available_thinking_levels") == 0 ||
               strcmp(t, "get_available_models") == 0 || strcmp(t, "get_credentials") == 0 ||
               strcmp(t, "check_credentials") == 0 || strcmp(t, "get_profiles") == 0) {
        rmt_ask(st, d, e, jx, conv); /* get_credentials and the rest: names, kinds, states and numbers, never a key */
    } else if (strcmp(t, "set_model") == 0 || strcmp(t, "set_thinking_level") == 0 || strcmp(t, "set_session_name") == 0 ||
               strcmp(t, "set_credential") == 0) {
        rmt_set(st, d, e, jx, conv);
    } else if (strcmp(t, "compact") == 0) {
        rmt_compact(st, d, e, jx, conv);
    } else if (strcmp(t, "delete_session") == 0 || strcmp(t, "restore_session") == 0) {
        rmt_trash(st, d, e, jx, conv);
    } else if (strcmp(t, "get_wakes") == 0 || strcmp(t, "pause_wake") == 0 || strcmp(t, "resume_wake") == 0 ||
               strcmp(t, "stop_wake") == 0 || strcmp(t, "pause_wakes") == 0 || strcmp(t, "approve_wake") == 0 ||
               strcmp(t, "decline_wake") == 0) {
        rmt_wake(st, d, e, jx, conv);
    } else if (strcmp(t, "answer") == 0) {
        rmt_answer(st, d, e, jx, conv);
    } else if (strcmp(t, "switch_session") == 0) {
        rmt_error(st, d, e->key, "not_available", "the envelope's session selects the conversation");
    } else {
        rmt_error(st, d, e->key, "not_available", "this command is not carried by remote control yet");
    }
}

/* Each tick: commands waiting for their row to settle, or for their request to be admitted. */
static void rmt_commands_poll(rmt_state *st, rmt_dev *d) {
    for (int i = 0; i < d->ncmds; i++) {
        rmt_cmd *c = &d->cmds[i];
        pic_store *s = &st->js[c->jx]->s;
        if (c->kind == CMD_DONE) {
            continue;
        }
        if (c->kind == CMD_INBOX) {
            char state[16], *response = NULL;
            long long now = rmt_mono_ms();
            if (now - c->expire_ms >= 5000) { /* a write: not on every tick */
                c->expire_ms = now;
                (void)pic_inbox_expire(s, c->row);
            }
            if (pic_inbox_status(s, c->row, state, sizeof state, &response) != 0 || strcmp(state, "pending") == 0) {
                free(response);
                continue;
            }
            if (d->sess >= 0) {
                if (response) {
                    rmt_response(st, d, c->key, response);
                } else {
                    rmt_send_free(st, d, rmt_q("SELECT json_object('type', 'response', 'key', ?1, 'payload', json_object('state', ?2))",
                                               2, c->key, state));
                }
            }
            free(response);
            rmt_cmd_drop(d, i--);
            continue;
        }
        if (c->errfd >= 0) {
            char buf[256];
            ssize_t n;
            while ((n = read(c->errfd, buf, sizeof buf)) > 0) {
                size_t k = (size_t)n;
                if (c->errlen + k >= sizeof c->err) {
                    c->errlen = 0;
                }
                memcpy(c->err + c->errlen, buf, k < sizeof c->err - 1 ? k : sizeof c->err - 1);
                c->errlen += k < sizeof c->err - 1 ? k : sizeof c->err - 1;
            }
        }
        if (c->kind == CMD_COMPACT) {
            int status = 0;
            if (c->pid > 0 && waitpid(c->pid, &status, WNOHANG) == c->pid) {
                char *line;
                c->pid = 0;
                if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
                    char *data = rmt_q("SELECT json_object('tokensBefore', (SELECT e.tokens_before FROM pic_entry e JOIN pic_submission u"
                                       " ON u.id = e.submission_id WHERE u.session_id = ?1 AND e.kind = 'compaction'"
                                       " ORDER BY e.seq DESC LIMIT 1))",
                                       1, c->conv);
                    line = rmt_pi_response(c->line, "compact", 1, data ? data : "{}", NULL);
                    free(data);
                } else {
                    char *last, *end;
                    c->err[c->errlen < sizeof c->err ? c->errlen : sizeof c->err - 1] = '\0';
                    end = c->err + strlen(c->err);
                    while (end > c->err && end[-1] == '\n') {
                        *--end = '\0';
                    }
                    last = strrchr(c->err, '\n');
                    last = last ? last + 1 : c->err;
                    if (strncmp(last, "pic: ", 5) == 0) {
                        last += 5;
                    }
                    line = rmt_pi_response(c->line, "compact", 0, NULL, *last ? last : "the compaction failed");
                }
                if (d->sess >= 0 && line) {
                    rmt_response(st, d, c->key, line);
                }
                close(c->errfd); /* kept as the answer to a repeat of its key */
                c->errfd = -1;
                c->kind = CMD_DONE;
                c->answer = line;
            }
            continue;
        }
        if (rmt_admitted(s, c->row)) {
            if (d->sess >= 0) {
                rmt_prompt_ok(st, d, c->key, c->jx, c->row);
            }
            rmt_cmd_drop(d, i--);
            continue;
        }
        if (c->pid > 0) {
            int status = 0;
            if (waitpid(c->pid, &status, WNOHANG) == c->pid) {
                char *last, *end;
                c->pid = 0;
                if (rmt_admitted(s, c->row)) {
                    i--; /* reported above on the next look */
                    continue;
                }
                c->err[c->errlen < sizeof c->err ? c->errlen : sizeof c->err - 1] = '\0';
                end = c->err + strlen(c->err);
                while (end > c->err && end[-1] == '\n') {
                    *--end = '\0';
                }
                last = strrchr(c->err, '\n');
                last = last ? last + 1 : c->err;
                if (strncmp(last, "pic: ", 5) == 0) {
                    last += 5;
                }
                if (d->sess >= 0) {
                    char *line = rmt_q("SELECT json_object('type', 'response', 'command', 'prompt', 'success', json('false'),"
                                       " 'error', ?1)",
                                       1, *last ? last : "the request could not be started");
                    rmt_response(st, d, c->key, line);
                    free(line);
                }
                rmt_cmd_drop(d, i--);
            }
        }
    }
}

/* ---- a whole message from a phone -------------------------------------------------------- */

/* ---- notifications (section 5) ------------------------------------------------------------ */

static int rmt_ids_has(const rmt_ids *a, long long v) {
    for (int i = 0; i < a->n; i++) {
        if (a->v[i] == v) {
            return 1;
        }
    }
    return 0;
}

static void rmt_ids_add(rmt_ids *a, long long v) {
    if (a->n == a->cap) {
        long long *grown = realloc(a->v, (size_t)(a->cap = a->cap ? a->cap * 2 : 8) * sizeof *grown);
        if (!grown) {
            a->cap = a->n;
            return;
        }
        a->v = grown;
    }
    a->v[a->n++] = v;
}

/* Drops V, or (BELOW) every value up to V. */
static void rmt_ids_drop(rmt_ids *a, long long v, int below) {
    int k = 0;
    for (int i = 0; i < a->n; i++) {
        if (below ? a->v[i] > v : a->v[i] != v) {
            a->v[k++] = a->v[i];
        }
    }
    a->n = k;
}

static long long rmt_push_gap_ms(void) {
#ifdef PIC_FAULTS
    if (getenv("PIC_TEST_RC_PUSH_GAP_MS")) { /* the tests' seam: several notifications for one conversation */
        return atoll(getenv("PIC_TEST_RC_PUSH_GAP_MS"));
    }
#endif
    return RMT_PUSH_GAP_MS;
}

/* Section 5's check of an endpoint; dev builds also take the tests' push service on loopback. */
static int rmt_endpoint_ok(const char *ep) {
#ifdef PIC_FAULTS
    if (getenv("PIC_TEST_RC_PUSH_HTTP") && strncmp(ep, "http://127.0.0.1:", 17) == 0) {
        return 1;
    }
#endif
    return pic_webpush_endpoint_ok(ep);
}

static void rmt_push_free(rmt_push *p) {
    if (p) {
        free(p->title);
        free(p->payload);
        free(p->session);
        pic_cred_wipe(p, sizeof *p);
        free(p);
    }
}

/* The pusher: one thread that sends what the loop queues, so a slow push service never holds up
 * the loop, the relay's lanes or a request. It touches no database; the loop applies outcomes. */
static void *rmt_pusher_main(void *arg) {
    rmt_pusher *pu = arg;
    char err[256];
    pic_net *net = pic_net_new(err, sizeof err);
    for (;;) {
        rmt_push *p;
        (void)pthread_mutex_lock(&pu->mu);
        while (!pu->ntodo) {
            (void)pthread_cond_wait(&pu->cv, &pu->mu);
        }
        p = pu->todo[0];
        memmove(pu->todo, pu->todo + 1, (size_t)(pu->ntodo - 1) * sizeof *pu->todo);
        pu->ntodo--;
        pu->sending = 1;
        (void)pthread_mutex_unlock(&pu->mu);
        memset(&p->res, 0, sizeof p->res);
        if (!net) {
            p->res.outcome = PIC_WEBPUSH_FAILED;
            (void)snprintf(p->res.err, sizeof p->res.err, "%s", err);
        } else {
            pic_webpush_sub sub;
            sub.endpoint = p->endpoint;
            memcpy(sub.p256dh, p->p256dh, sizeof sub.p256dh);
            memcpy(sub.auth, p->auth, sizeof sub.auth);
            (void)pic_webpush_send(net, &sub, &pu->vapid, p->topic, p->payload, strlen(p->payload), RMT_PUSH_TTL, &p->res);
        }
        (void)pthread_mutex_lock(&pu->mu);
        pu->sending = 0;
        if (pu->ndone < RMT_PUSH_QUEUE) {
            pu->done[pu->ndone++] = p;
            p = NULL;
        }
        (void)pthread_mutex_unlock(&pu->mu);
        rmt_push_free(p);
    }
    return NULL;
}

/* Queues P for the pusher with its plaintext, {"v":1,"title","body","session","seq"} with BODY.
 * P is the pusher's, or freed: 0 when queued, else -1. */
static int rmt_push_queue(rmt_state *st, rmt_push *p, const char *body) {
    rmt_pusher *pu = &st->push;
    char seq[32];
    int queued = 0;
    (void)snprintf(seq, sizeof seq, "%lld", p->seq);
    free(p->payload);
    p->payload = rmt_q("SELECT json_object('v', 1, 'title', ?1, 'body', ?2, 'session', ?3, 'seq', CAST(?4 AS INTEGER))", 4, p->title,
                    body, p->session, seq);
    if (!p->payload) {
        rmt_push_free(p);
        return -1;
    }
    if (!pu->started) {
        pthread_t t;
        pthread_attr_t a;
        (void)pthread_attr_init(&a);
        (void)pthread_attr_setdetachstate(&a, PTHREAD_CREATE_DETACHED);
        pu->started = pthread_create(&t, &a, rmt_pusher_main, pu) == 0;
        (void)pthread_attr_destroy(&a);
        if (!pu->started) {
            rmt_push_free(p);
            return -1;
        }
    }
    (void)pthread_mutex_lock(&pu->mu);
    if (pu->ntodo < RMT_PUSH_QUEUE) { /* else dropped: a notification is a hint */
        pu->todo[pu->ntodo++] = p;
        queued = 1;
        (void)pthread_cond_signal(&pu->cv);
    }
    (void)pthread_mutex_unlock(&pu->mu);
    if (!queued) {
        rmt_push_free(p);
    }
    return queued ? 0 : -1;
}

static unsigned long long rmt_hash(const char *s) {
    unsigned long long h = 1469598103934665603ull;
    while (*s) {
        h = (h ^ (unsigned char)*s++) * 1099511628211ull;
    }
    return h;
}

/* A request ended in conversation CONV of J, titled CTITLE (PIC_TITLE_SQL; "" for none): one line to
 * each device that wants it (its notify, remote.notify, not looking at the page, not one for this
 * conversation in the last 30 s). */
static void rmt_notify(rmt_state *st, rmt_journal *j, const char *conv, const char *ctitle, int phone, long long seq,
                       const char *body) {
    char *setting = pic_setting("remote.notify"), *title, *sess;
    const char *mode = setting && *setting ? setting : "all";
    long long now = rmt_mono_ms();
    unsigned long long h;
    size_t n;
    if (strcmp(mode, "off") == 0 || (strcmp(mode, "remote") == 0 && !phone)) {
        free(setting);
        return;
    }
    free(setting);
    if (ctitle && *ctitle) {
        title = pic_one_line(ctitle, 60);
    } else {
        size_t e = strlen(j->workspace);
        char *base;
        while (e > 1 && j->workspace[e - 1] == '/') {
            e--;
        }
        base = strndup(j->workspace, e);
        title = base ? pic_one_line(strrchr(base, '/') ? strrchr(base, '/') + 1 : base, 60) : NULL;
        free(base);
    }
    n = strlen(j->path) + strlen(conv) + 2;
    if (!title || !(sess = malloc(n))) {
        free(title);
        return;
    }
    (void)snprintf(sess, n, "%s/%s", j->path, conv);
    h = rmt_hash(sess);
    for (int i = 0; i < st->ndevs; i++) {
        rmt_dev *d = &st->devs[i];
        rmt_push *p;
        int slot = 0;
        if (!d->alive || !d->d.notify[0] || (strcmp(d->d.notify, "remote") == 0 && !phone) || now < d->push_hold_ms ||
            (d->sess >= 0 && st->sess[d->sess].confirmed && d->visible)) {
            continue;
        }
        for (int k = 0; k < 16; k++) { /* this conversation's slot, else the oldest */
            if (d->pushed[k].conv == h) {
                slot = k;
                break;
            }
            if (d->pushed[k].ms < d->pushed[slot].ms) {
                slot = k;
            }
        }
        if (d->pushed[slot].conv == h && d->pushed[slot].ms && now - d->pushed[slot].ms < rmt_push_gap_ms()) {
            continue;
        }
        if (!(p = calloc(1, sizeof *p))) {
            continue;
        }
        memcpy(p->dev, d->d.id, 16);
        (void)snprintf(p->endpoint, sizeof p->endpoint, "%s", d->d.endpoint);
        memcpy(p->p256dh, d->d.p256dh, sizeof p->p256dh);
        memcpy(p->auth, d->d.auth, sizeof p->auth);
        pic_webpush_topic(d->d.auth, sess, p->topic);
        p->title = strdup(title);
        p->session = strdup(sess);
        p->seq = seq;
        if (!p->title || !p->session) {
            rmt_push_free(p);
            continue;
        }
        if (rmt_push_queue(st, p, body) != 0) {
            continue;
        }
        d->pushed[slot].conv = h;
        d->pushed[slot].ms = now ? now : 1;
    }
    free(title);
    free(sess);
}

/* What J holds of requests now, for watching them end: the last one, and those running. */
static void rmt_push_watch(rmt_journal *j) {
    sqlite3_stmt *q = NULL;
    j->push_version = rmt_data_version(j->s.db);
    if (sqlite3_prepare_v2(j->s.db, "SELECT coalesce(max(id), 0) FROM pic_submission", -1, &q, NULL) == SQLITE_OK &&
        sqlite3_step(q) == SQLITE_ROW) {
        j->push_cut = sqlite3_column_int64(q, 0);
    }
    sqlite3_finalize(q);
    q = NULL;
    if (sqlite3_prepare_v2(j->s.db, "SELECT id FROM pic_submission WHERE status = 'admitted'", -1, &q, NULL) == SQLITE_OK) {
        while (sqlite3_step(q) == SQLITE_ROW) {
            rmt_ids_add(&j->push_open, sqlite3_column_int64(q, 0));
        }
    }
    sqlite3_finalize(q);
}

/* Requests of J that ended since the last look (section 5's When): ones running when pic remote
 * first read the journal, and ones admitted after, each once. A request that asked no model
 * (a command the user ran) or was imported ends nothing. One read transaction. */

/* The requests of J that ended above ?1 or among ?2 (a JSON array), with FILTER (SQL) on u: id,
 * conversation, status, error, stop reason, whether a phone asked, title, last seq, reply text. */
#define RMT_ENDED_SQL(FILTER)                                                                                         \
    "SELECT u.id, u.session_id, u.status, coalesce(u.error, ''), coalesce(u.stop_reason, ''),"                       \
    " u.request_key LIKE 'rc:%' OR EXISTS (SELECT 1 FROM pic_inbox i WHERE i.submission_id = u.id AND i.sender LIKE 'remote:%')," \
    " coalesce((SELECT " PIC_TITLE_SQL("t") " FROM pic_session t WHERE t.id = u.session_id), ''),"                  \
    " coalesce((SELECT max(seq) FROM pic_entry WHERE submission_id = u.id), 0),"                                     \
    " (SELECT t FROM (SELECT e.seq AS seq, (SELECT group_concat(json_extract(c.value, '$.text'), '') FROM json_each(e.body) c" \
    "   WHERE json_extract(c.value, '$.type') = 'text') AS t FROM pic_entry e WHERE e.submission_id = u.id"            \
    "   AND e.kind IN ('assistant', 'answer') AND json_valid(e.body)) WHERE trim(coalesce(t, '')) != '' ORDER BY seq DESC LIMIT 1)" \
    " FROM pic_submission u WHERE u.status != 'admitted' AND u.session_id IS NOT NULL"                              \
    " AND (u.id > ?1 OR u.id IN (SELECT value FROM json_each(?2))) AND u.request_key NOT LIKE 'import-%'" FILTER      \
    " AND EXISTS (SELECT 1 FROM pic_generation g WHERE g.submission_id = u.id) ORDER BY u.id"

static void rmt_push_check(rmt_state *st, rmt_journal *j) {
    sqlite3_stmt *q = NULL;
    rmt_buf open = {NULL, 0, 0};
    long long v = rmt_data_version(j->s.db);
    if (v == j->push_version || sqlite3_exec(j->s.db, "BEGIN", NULL, NULL, NULL) != SQLITE_OK) {
        return;
    }
    j->push_version = v;
    (void)rmt_buf_add(&open, "[", 1);
    for (int i = 0; i < j->push_open.n; i++) {
        char one[32];
        int k = snprintf(one, sizeof one, "%s%lld", i ? "," : "", j->push_open.v[i]);
        (void)rmt_buf_add(&open, one, (size_t)k);
    }
    (void)rmt_buf_add(&open, "]", 2);
    /* a person's conversations alone (rmt_list), so no other's words leave the computer */
    if (sqlite3_prepare_v2(j->s.db,
                           RMT_ENDED_SQL(" AND (SELECT " PIC_STARTED_BY_SQL("t") " FROM pic_session t WHERE t.id = u.session_id)"
                                         " IN ('person', 'phone')"),
                           -1, &q, NULL) == SQLITE_OK ||
        (sqlite3_finalize(q), q = NULL, sqlite3_prepare_v2(j->s.db, RMT_ENDED_SQL(""), -1, &q, NULL)) == SQLITE_OK) {
        sqlite3_bind_int64(q, 1, j->push_cut);
        sqlite3_bind_text(q, 2, open.buf, -1, SQLITE_STATIC);
        while (sqlite3_step(q) == SQLITE_ROW) {
            long long id = sqlite3_column_int64(q, 0);
            const char *conv = (const char *)sqlite3_column_text(q, 1), *status = (const char *)sqlite3_column_text(q, 2);
            const char *error = (const char *)sqlite3_column_text(q, 3), *stop = (const char *)sqlite3_column_text(q, 4);
            const char *text = (const char *)sqlite3_column_text(q, 8);
            char *body, *why = NULL;
            if (rmt_ids_has(&j->push_open, id)) {
                rmt_ids_drop(&j->push_open, id, 0);
            } else if (rmt_ids_has(&j->push_told, id)) {
                continue;
            } else {
                rmt_ids_add(&j->push_told, id);
            }
            if (!text) { /* no reply text: how it ended */
                if (strcmp(status, "failed") == 0 && strcmp(error, "cancelled") != 0) {
                    size_t n = strlen(error) + 16;
                    if ((why = malloc(n))) {
                        (void)snprintf(why, n, "Failed: %s", error);
                    }
                }
                text = why ? why
                       : strcmp(status, "failed") == 0 || strcmp(status, "stopped") == 0
                           ? (strcmp(stop, "request_cap") == 0 ? "Reached the request cap" : "Stopped")
                           : "Done";
            }
            body = pic_one_line(text, 200);
            if (body) {
                rmt_notify(st, j, conv, (const char *)sqlite3_column_text(q, 6), sqlite3_column_int(q, 5),
                           sqlite3_column_int64(q, 7), body);
            }
            free(body);
            free(why);
        }
    }
    sqlite3_finalize(q);
    q = NULL;
    /* Everything up to the oldest request still running has been looked at. */
    if (sqlite3_prepare_v2(j->s.db,
                           "SELECT coalesce((SELECT min(id) - 1 FROM pic_submission WHERE id > ?1 AND status = 'admitted'),"
                           " (SELECT max(id) FROM pic_submission), ?1)",
                           -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_int64(q, 1, j->push_cut);
        if (sqlite3_step(q) == SQLITE_ROW) {
            j->push_cut = sqlite3_column_int64(q, 0);
        }
    }
    sqlite3_finalize(q);
    (void)sqlite3_exec(j->s.db, "COMMIT", NULL, NULL, NULL);
    rmt_ids_drop(&j->push_told, j->push_cut, 1);
    free(open.buf);
}

/* A device's subscription ends (gone at the push service, or refused three times). */
static void rmt_push_end(rmt_dev *d, const char *why) {
    char err[256];
    d->d.notify[0] = '\0';
    d->d.endpoint[0] = '\0';
    memset(d->d.p256dh, 0, sizeof d->d.p256dh);
    memset(d->d.auth, 0, sizeof d->d.auth);
    d->refused = 0;
    if (rmt_device_write(&d->d, 0, err, sizeof err) != 0) {
        rmt_log(stderr, "pic remote: %s\n", err);
    }
    rmt_log(stdout, "pic remote: notifications to %s ended: %s\n", d->d.name, why);
    (void)fflush(stdout);
}

/* What the pusher made of what it sent. */
static void rmt_push_results(rmt_state *st) {
    rmt_pusher *pu = &st->push;
    rmt_push *done[RMT_PUSH_QUEUE];
    int n;
    if (!pu->started) {
        return;
    }
    (void)pthread_mutex_lock(&pu->mu);
    n = pu->ndone;
    memcpy(done, pu->done, (size_t)n * sizeof *done);
    pu->ndone = 0;
    (void)pthread_mutex_unlock(&pu->mu);
    for (int i = 0; i < n; i++) {
        rmt_push *p = done[i];
        rmt_dev *d = NULL;
        for (int k = 0; k < st->ndevs && !d; k++) {
            d = st->devs[k].alive && memcmp(st->devs[k].d.id, p->dev, 16) == 0 ? &st->devs[k] : NULL;
        }
        if (d && strcmp(d->d.endpoint, p->endpoint) == 0) { /* still that subscription */
            switch (p->res.outcome) {
            case PIC_WEBPUSH_SENT:
                d->refused = 0;
                break;
            case PIC_WEBPUSH_GONE:
                rmt_push_end(d, p->res.err);
                break;
            case PIC_WEBPUSH_RETRY: {
                long secs = p->res.retry_after >= 0 ? (p->res.retry_after > 86400 ? 86400 : p->res.retry_after) : 60;
                d->push_hold_ms = rmt_mono_ms() + secs * 1000LL;
                break;
            }
            case PIC_WEBPUSH_TOO_LARGE:
                if (!p->shortened) { /* once more with a shorter line: a different push, not a retry */
                    char *line = rmt_q("SELECT json_extract(?1, '$.body')", 1, p->payload), *cut = pic_one_line(line, 40);
                    free(line);
                    p->shortened = 1;
                    if (cut) {
                        (void)rmt_push_queue(st, p, cut); /* P is the pusher's now, or freed */
                        free(cut);
                        p = NULL;
                    }
                }
                break;
            case PIC_WEBPUSH_FAILED:
                if ((p->res.status == 400 || p->res.status == 403) && ++d->refused >= RMT_PUSH_REFUSED) {
                    rmt_push_end(d, p->res.err);
                }
                break;
            }
        }
        rmt_push_free(p);
    }
}

/* push from the phone: its subscription and notify, or null to end it, sealed into its row. */
static void rmt_push_set(rmt_state *st, rmt_dev *d, const char *payload) {
    rmt_device nd = d->d;
    char err[256], *t = payload ? rmt_q("SELECT json_type(?1, '$.subscription')", 1, payload) : NULL;
    if (t && strcmp(t, "null") == 0) {
        nd.notify[0] = '\0';
        nd.endpoint[0] = '\0';
        memset(nd.p256dh, 0, sizeof nd.p256dh);
        memset(nd.auth, 0, sizeof nd.auth);
    } else if (t && strcmp(t, "object") == 0) {
        char *ep = rmt_q("SELECT CASE json_type(?1, '$.subscription.endpoint') WHEN 'text' THEN json_extract(?1, '$.subscription.endpoint') END",
                         1, payload);
        char *pk = rmt_q("SELECT CASE json_type(?1, '$.subscription.keys.p256dh') WHEN 'text' THEN json_extract(?1,"
                         " '$.subscription.keys.p256dh') END",
                         1, payload);
        char *au = rmt_q("SELECT CASE json_type(?1, '$.subscription.keys.auth') WHEN 'text' THEN json_extract(?1,"
                         " '$.subscription.keys.auth') END",
                         1, payload);
        char *nt = rmt_q("SELECT CASE WHEN json_type(?1, '$.notify') IS NULL THEN 'all' WHEN json_type(?1, '$.notify') = 'text'"
                         " THEN json_extract(?1, '$.notify') END",
                         1, payload);
        int ok = ep && pk && au && nt && strlen(ep) < sizeof nd.endpoint && rmt_endpoint_ok(ep) &&
                 (strcmp(nt, "all") == 0 || strcmp(nt, "remote") == 0) &&
                 pic_b64u_dec(pk, strlen(pk), nd.p256dh, sizeof nd.p256dh) == PIC_WEBPUSH_PUB && pic_noise_pub_valid(nd.p256dh) &&
                 pic_b64u_dec(au, strlen(au), nd.auth, sizeof nd.auth) == PIC_WEBPUSH_AUTH;
        if (ok) {
            (void)snprintf(nd.endpoint, sizeof nd.endpoint, "%s", ep);
            (void)snprintf(nd.notify, sizeof nd.notify, "%s", nt);
        }
        free(ep);
        free(pk);
        free(au);
        free(nt);
        if (!ok) {
            free(t);
            rmt_error(st, d, NULL, "bad_message",
                      "a push subscription is an https endpoint on port 443 with a host name, keys.p256dh (a P-256 public key)"
                      " and keys.auth (16 bytes), and notify all or remote");
            return;
        }
    } else {
        free(t);
        rmt_error(st, d, NULL, "bad_message", "push carries a subscription, or null");
        return;
    }
    free(t);
    if (strcmp(nd.notify, d->d.notify) == 0 && strcmp(nd.endpoint, d->d.endpoint) == 0 &&
        memcmp(nd.p256dh, d->d.p256dh, sizeof nd.p256dh) == 0 && memcmp(nd.auth, d->d.auth, sizeof nd.auth) == 0) {
        return;
    }
    if (rmt_device_write(&nd, 0, err, sizeof err) != 0) {
        rmt_error(st, d, NULL, "failed", err);
        return;
    }
    d->d = nd;
    d->refused = 0;
    d->push_hold_ms = 0;
}

/* ---- repair: an older page's Fix ------------------------------------------------------- */

/* repair {"workspace":W}, which pages from before pic updated journals itself send: W is updated
 * now when it can be (rmt_update), and the answer says whether it is served. Nothing is offered
 * for it any more. */
static void rmt_repair(rmt_state *st, rmt_dev *d, rmt_env *e) {
    char *w = e->payload ? rmt_q("SELECT CASE json_type(?1, '$.workspace') WHEN 'text' THEN json_extract(?1, '$.workspace') END", 1,
                                 e->payload)
                         : NULL;
    int jx = -1, ok;
    for (int i = 0; w && i < st->njs && jx < 0; i++) {
        jx = strcmp(st->js[i]->workspace, w) == 0 ? i : -1; /* as unavailable names it */
    }
    free(w);
    if (!rmt_key_ok(e->key)) {
        rmt_error(st, d, NULL, "bad_message", "a repair's key is 16 to 43 characters of A-Z, a-z, 0-9, _ and -");
        return;
    }
    if (jx < 0) {
        rmt_error(st, d, e->key, "no_session", "no such workspace");
        return;
    }
    ok = rmt_update(st, st->js[jx]);
    rmt_send_free(st, d,
                  rmt_q("SELECT json_object('type', 'repair', 'key', ?1, 'payload', json_object('workspace', ?2, 'ok', json(?3),"
                        " 'message', ?4))",
                        4, e->key, st->js[jx]->workspace, ok ? "true" : "false",
                        ok ? "It is up to date; its conversations show again." : st->js[jx]->why));
}

static void rmt_unpair_device(rmt_state *st, int di, int tell);
static void rmt_offer_tell(rmt_state *st);
static void rmt_offer_ask(rmt_state *st, int di);
static void rmt_offer_answer(rmt_state *st, int di, int yes, const char *code);
static char *rmt_devices_json(rmt_state *st, int self);
static void rmt_devices_tell(rmt_state *st);

/* What a phone's message is (its type and command), for the tests' count of the work it took. */
static char rmt_answering[80];

/* The most work one phone message may do in the journals, and for how long: past either its
 * statement is interrupted and the phone is told it failed, so no question about a long
 * conversation holds the loop that serves every phone. */
#define RMT_MESSAGE_STEPS 50000000LL
#define RMT_MESSAGE_MS 2000

typedef struct {
    long long steps, deadline;
} rmt_budget;

static int rmt_budget_spent(void *arg) {
    rmt_budget *b = arg;
    b->steps += 100;
    return b->steps > RMT_MESSAGE_STEPS || rmt_mono_ms() > b->deadline;
}

static void rmt_message_one(rmt_state *st, int si, const char *json);
static void rmt_asks_open(rmt_state *st, rmt_dev *d);

static void rmt_message(rmt_state *st, int si, const char *json) {
    rmt_budget b = {0, rmt_mono_ms() + RMT_MESSAGE_MS};
    rmt_answering[0] = '\0';
    for (int i = 0; i < st->njs; i++) {
        if (st->js[i]->open) {
            sqlite3_progress_handler(st->js[i]->s.db, 100, rmt_budget_spent, &b);
        }
    }
    rmt_message_one(st, si, json);
    for (int i = 0; i < st->njs; i++) { /* the journals open now: a message may have opened or closed one */
        if (st->js[i]->open) {
            sqlite3_progress_handler(st->js[i]->s.db, 0, NULL, NULL);
        }
    }
#ifdef PIC_FAULTS
    if (getenv("PIC_TEST_RC_MESSAGE_STEPS") && rmt_answering[0]) { /* the tests' seam: the work each message took */
        printf("pic remote: answered %s in %lld steps\n", rmt_answering, b.steps);
        (void)fflush(stdout);
    }
#endif
}

static void rmt_message_one(rmt_state *st, int si, const char *json) {
    rmt_sess *s = &st->sess[si];
    rmt_dev *d = &st->devs[s->dev];
    rmt_env e;
    if (!s->confirmed) { /* the first message that verifies confirms the session */
        s->confirmed = 1;
        for (int i = 0; i < RMT_SESSIONS; i++) { /* and replaces the device's earlier ones */
            if (i != si && st->sess[i].used && st->sess[i].dev == s->dev) {
                free(st->sess[i].msg.buf);
                memset(&st->sess[i], 0, sizeof st->sess[i]);
            }
        }
        d->sess = si;
        d->visible = 0; /* until its presence says */
        rmt_unfollow(d); /* the phone sends sync and sessions again in a new session */
        d->want_list = 0;
        free(d->list_sent);
        d->list_sent = NULL;
        rmt_device_seen(d->d.id);
        d->want_devices = 0;
        if (st->offer && st->offer_dev == s->dev && st->offer->stage == OFFER_ASKING) {
            rmt_offer_tell(st); /* still waiting for this phone's answer */
        }
        rmt_asks_open(st, d); /* the questions waiting now, whatever an earlier session was told */
        d->seen_wr_ms = rmt_mono_ms();
    } else if (rmt_mono_ms() - d->seen_wr_ms >= rmt_seen_every_ms()) { /* connected all along: seen now */
        rmt_device_seen(d->d.id);
        d->seen_wr_ms = rmt_mono_ms();
    }
    if (rmt_env_parse(json, &e) != 0) {
        rmt_error(st, d, NULL, "bad_message", "not an envelope message");
        return;
    }
    {
        char what[160];
        (void)snprintf(what, sizeof what, "%s's %s%s%s", d->d.name, e.type, e.ptype[0] ? " " : "", e.ptype);
        rmt_doing("answering", what);
        (void)snprintf(rmt_answering, sizeof rmt_answering, "%s%s%s", e.type, e.ptype[0] ? " " : "", e.ptype);
    }
    if (strcmp(e.type, "sessions") == 0) {
        char *w = e.payload ? rmt_q("SELECT CASE json_type(?1, '$.workspace') WHEN 'text' THEN json_extract(?1, '$.workspace') END",
                                    1, e.payload)
                            : NULL;
        if (w) { /* one workspace's conversations, once */
            int jx = -1;
            for (int i = 0; i < st->njs && jx < 0; i++) {
                jx = st->js[i]->open && strcmp(st->js[i]->path, w) == 0 ? i : -1;
            }
            if (jx < 0) {
                rmt_error(st, d, NULL, "no_session", "no such workspace");
            } else {
                rmt_send_free(st, d, rmt_list(st, jx));
            }
            free(w);
        } else {
            d->want_list = 1;
            free(d->list_sent);
            d->list_sent = NULL;
        }
    } else if (strcmp(e.type, "sync") == 0) {
        int jx;
        char conv[64], err[256];
        if (e.key[0] && !rmt_key_ok(e.key)) {
            rmt_error(st, d, NULL, "bad_message", "a sync's key is 16 to 43 characters of A-Z, a-z, 0-9, _ and -");
        } else if (rmt_resolve(st, e.session, &jx, conv) != 0) {
            rmt_error(st, d, NULL, "no_session", "no such conversation");
        } else {
            rmt_unfollow(d); /* a new sync replaces the one before */
            (void)snprintf(d->skey, sizeof d->skey, "%s", e.key);
            d->jx = jx;
            (void)snprintf(d->conv, sizeof d->conv, "%s", conv);
            d->wsess = strdup(e.session);
            d->f = pic_follow_new(&st->js[jx]->s, conv, e.has_seq ? e.seq : -1, err, sizeof err);
            if (!d->f) {
                rmt_error(st, d, NULL, "unavailable", err);
            } else {
                d->follow_now = 1;
                d->earlier = rmt_earlier(&st->js[jx]->s, conv, e.has_seq ? e.seq : -1);
            }
        }
    } else if (strcmp(e.type, "command") == 0) {
        rmt_command(st, d, &e);
    } else if (strcmp(e.type, "image") == 0) {
        rmt_image(st, d, &e);
    } else if (strcmp(e.type, "repair") == 0) {
        rmt_repair(st, d, &e);
    } else if (strcmp(e.type, "ping") == 0) {
        rmt_send_free(st, d, strdup("{\"type\":\"pong\"}"));
    } else if (strcmp(e.type, "unpair") == 0) {
        rmt_env_free(&e);
        rmt_unpair_device(st, s->dev, 0);
        return;
    } else if (strcmp(e.type, "presence") == 0) {
        char *v = e.payload ? rmt_q("SELECT json_type(?1, '$.visible')", 1, e.payload) : NULL;
        d->visible = v && strcmp(v, "true") == 0;
        free(v);
    } else if (strcmp(e.type, "push") == 0) {
        rmt_push_set(st, d, e.payload);
    } else if (strcmp(e.type, "pair_offer") == 0) {
        rmt_offer_ask(st, s->dev);
    } else if (strcmp(e.type, "pair_approve") == 0 || strcmp(e.type, "pair_deny") == 0) {
        char *code = strcmp(e.type, "pair_approve") != 0 ? NULL
                     : e.payload ? rmt_q("SELECT CASE json_type(?1, '$.code') WHEN 'text' THEN json_extract(?1, '$.code') END", 1,
                                         e.payload)
                                 : NULL;
        rmt_offer_answer(st, s->dev, strcmp(e.type, "pair_approve") == 0, code ? code : "");
        free(code);
    } else if (strcmp(e.type, "devices") == 0) {
        d->want_devices = 1;
        rmt_send_free(st, d, rmt_devices_json(st, s->dev));
    } else if (strcmp(e.type, "unpair_device") == 0) {
        char *id = e.payload ? rmt_q("SELECT CASE json_type(?1, '$.device') WHEN 'text' THEN json_extract(?1, '$.device') END", 1,
                                     e.payload)
                             : NULL;
        unsigned char raw[32];
        int di = -1, self = 0;
        if (id && pic_b64u_dec(id, strlen(id), raw, sizeof raw) == 16) {
            for (int i = 0; i < st->ndevs && di < 0; i++) {
                di = st->devs[i].alive && memcmp(st->devs[i].d.id, raw, 16) == 0 ? i : -1;
            }
        }
        free(id);
        if (di < 0) {
            rmt_error(st, d, NULL, "no_device", "no such paired device");
        } else {
            self = di == s->dev;
            rmt_log(stdout, "pic remote: %s unpaired %s\n", d->d.name, st->devs[di].d.name);
            (void)fflush(stdout);
            rmt_unpair_device(st, di, 1);
            rmt_devices_tell(st);
            if (self) { /* its session is gone with it */
                rmt_env_free(&e);
                return;
            }
        }
    } else if (strcmp(e.type, "unpair_all") == 0) {
        rmt_log(stdout, "pic remote: %s unpaired every device\n", d->d.name);
        (void)fflush(stdout);
        rmt_env_free(&e);
        for (int i = 0; i < st->ndevs; i++) {
            if (st->devs[i].alive) {
                rmt_unpair_device(st, i, 1);
            }
        }
        return;
    } else if (strcmp(e.type, "pair_ready") == 0 || strcmp(e.type, "fetch") == 0) {
        /* fetch, scrolling back, is a later landing */
        if (strcmp(e.type, "fetch") == 0) {
            rmt_error(st, d, NULL, "not_available", "fetch is not carried yet");
        }
    } else {
        rmt_error(st, d, NULL, "unknown_type", e.type);
    }
    rmt_env_free(&e);
}

/* ---- records from the relay ----------------------------------------------------------------- */

static int rmt_dev_by_channel(rmt_state *st, const unsigned char ch[16]) {
    for (int i = 0; i < st->ndevs; i++) {
        if (st->devs[i].alive && memcmp(st->devs[i].d.channel, ch, 16) == 0) {
            return i;
        }
    }
    return -1;
}

/* Message 1 of a session: the static key it carries must be a device in the table, and that
 * device's channel the channel it came on; otherwise it is dropped without an answer. */
static int rmt_devices_sync(rmt_state *st, int quiet);

/* The device of channel CH, or -1. A channel no device has may be a phone paired a moment ago (by
 * /rc or pic remote pair, in another process): when the user database has changed since this
 * process last read it, the devices are read again first, so the phone's first message is answered
 * now rather than dropped and asked again. The once-a-second look reads the rest of it as before. */
static int rmt_dev_for_record(rmt_state *st, const unsigned char ch[16]) {
    int di = rmt_dev_by_channel(st, ch);
    if (di < 0 && rmt_data_version(pic_userdb(NULL, 0)) != st->user_version) {
        (void)rmt_devices_sync(st, 0);
        di = rmt_dev_by_channel(st, ch);
    }
    return di;
}

static void rmt_handshake(rmt_state *st, const unsigned char ch[16], const unsigned char *rec, size_t n) {
    int di = rmt_dev_for_record(st, ch), slot = -1, unconfirmed = 0;
    unsigned char prologue[41], pl[512], m2[256], out[300];
    size_t pn, mn;
    pic_noise_hs hs;
    if (di < 0 || n < 9) {
        return;
    }
    for (int i = 0; i < RMT_SESSIONS; i++) {
        rmt_sess *s = &st->sess[i];
        if (s->used && memcmp(s->ch, ch, 16) == 0 && memcmp(s->t.sid, rec + 1, 8) == 0) {
            if (s->confirmed) {
                return; /* a replayed message 1 of a live session: nothing to gain */
            }
            slot = i; /* the same handshake again: answered afresh */
        }
    }
    rmt_prologue(st->k.mailbox, ch, prologue);
    pic_noise_hs_init(&hs, 0, &st->k.stat, NULL, NULL, prologue, sizeof prologue);
    if (pic_noise_read1(&hs, rec + 9, n - 9, pl, sizeof pl, &pn) != 0 || !rmt_same(hs.rs, st->devs[di].d.stat, PIC_NOISE_PUB)) {
        pic_noise_hs_wipe(&hs);
        return;
    }
    if (pic_noise_write2(&hs, "{\"v\":1}", 7, m2, sizeof m2, &mn) != 0) {
        pic_noise_hs_wipe(&hs);
        return;
    }
    for (int i = 0; i < RMT_SESSIONS; i++) { /* at most two unconfirmed sessions a channel */
        if (i != slot && st->sess[i].used && !st->sess[i].confirmed && memcmp(st->sess[i].ch, ch, 16) == 0 && ++unconfirmed >= 2) {
            free(st->sess[i].msg.buf);
            memset(&st->sess[i], 0, sizeof st->sess[i]);
        }
    }
    for (int i = 0; slot < 0 && i < RMT_SESSIONS; i++) {
        if (!st->sess[i].used) {
            slot = i;
        }
    }
    if (slot < 0) {
        pic_noise_hs_wipe(&hs);
        return;
    }
    {
        rmt_sess *s = &st->sess[slot];
        unsigned char up[32], down[32];
        free(s->msg.buf);
        memset(s, 0, sizeof *s);
        s->used = 1;
        s->dev = di;
        memcpy(s->ch, ch, 16);
        pic_noise_split(&hs, up, down);
        pic_noise_transport_init(&s->t, 0, rec + 1, up, down);
        pic_cred_wipe(up, sizeof up);
        pic_cred_wipe(down, sizeof down);
        s->started_ms = s->heard_ms = rmt_mono_ms();
    }
    pic_noise_hs_wipe(&hs);
    (void)rmt_lane_add(&st->devs[di].lane, out, pic_noise_head(PIC_NOISE_REC_M2, rec + 1, m2, mn, out));
}

static void rmt_record(rmt_state *st, const unsigned char ch[16], const unsigned char *rec, size_t n) {
    int di;
    if (n < 9) {
        return;
    }
    if (rec[0] == PIC_NOISE_REC_M1) {
        rmt_handshake(st, ch, rec, n);
        return;
    }
    if (rec[0] != PIC_NOISE_REC_DATA) {
        return;
    }
    if ((di = rmt_dev_for_record(st, ch)) < 0) {
        if (rmt_tally_due(&st->dropped_unknown)) {
            char id[24];
            pic_b64u_enc(ch, 16, id);
            rmt_log(stdout, "pic remote: dropped a record on channel %s, which no paired device has (%lld so far)\n", id,
                    st->dropped_unknown.n);
        }
        return;
    }
    for (int i = 0; i < RMT_SESSIONS; i++) {
        rmt_sess *s = &st->sess[i];
        unsigned char data[PIC_NOISE_CHUNK];
        size_t dn;
        int flag, gap, whole;
        if (!s->used || memcmp(s->ch, ch, 16) != 0 || memcmp(s->t.sid, rec + 1, 8) != 0) {
            continue;
        }
        if (pic_noise_open_record(&s->t, rec, n, &flag, data, &dn, &gap) != 0) {
            /* Dropped, nothing changed. A counter already used is a replay or a duplicate, which
             * says nothing against the session. On an unconfirmed session it may be the phone's
             * live session after a replayed message 1 (the relay holds records a minute, so a pic
             * remote started again reads the phone's last handshake): a reset, at most one a
             * second, lets the phone make a new one instead of waiting out this one. A confirmed
             * session whose records keep failing is reset too, or the phone would wait on it. */
            long long now = rmt_mono_ms();
            unsigned long long c = 0;
            unsigned char out[16];
            for (size_t k = 1 + PIC_NOISE_SID; k < 1 + PIC_NOISE_SID + 8 && k < n; k++) {
                c = (c << 8) | rec[k];
            }
            if (n >= 1 + PIC_NOISE_SID + 8 && s->t.last >= 0 && c <= (unsigned long long)s->t.last) {
                if (rmt_tally_due(&st->dropped_again)) {
                    rmt_log(stdout, "pic remote: dropped a record %s sent before (%lld so far)\n", st->devs[di].d.name,
                            st->dropped_again.n);
                }
                return;
            }
            if (s->confirmed || now - s->reset_ms >= 1000) {
                char sid[17];
                rmt_hex(s->t.sid, PIC_NOISE_SID, sid);
                rmt_log(stdout,
                        "pic remote: dropped a record from %s that did not open (%d in a row): session %.8s, %s, counter %llu"
                        " after %lld, last heard %lld s ago\n",
                        st->devs[di].d.name, s->confirmed ? s->fails + 1 : 1, sid, s->confirmed ? "confirmed" : "unconfirmed", c,
                        (long long)s->t.last, (now - s->heard_ms) / 1000);
            }
            if (s->confirmed && ++s->fails >= RMT_OPEN_FAILS) {
                rmt_log(stdout, "pic remote: reset %s's session: %d records in a row did not open\n", st->devs[di].d.name,
                        s->fails);
                (void)rmt_lane_add(&st->devs[di].lane, out, pic_noise_head(PIC_NOISE_REC_RESET, rec + 1, NULL, 0, out));
                if (st->devs[di].sess == i) {
                    st->devs[di].sess = -1;
                }
                free(s->msg.buf);
                memset(s, 0, sizeof *s);
            } else if (!s->confirmed && now - s->reset_ms >= 1000) {
                rmt_log(stdout, "pic remote: reset a new session of %s: a record did not open\n", st->devs[di].d.name);
                s->reset_ms = now;
                (void)rmt_lane_add(&st->devs[di].lane, out, pic_noise_head(PIC_NOISE_REC_RESET, rec + 1, NULL, 0, out));
            }
            return;
        }
        s->fails = 0;
        s->heard_ms = rmt_mono_ms();
        whole = rmt_sess_take(s, flag, data, dn, gap);
        if (whole == 1) {
            char *json = malloc(s->msg.len + 1);
            if (json) {
                memcpy(json, s->msg.buf, s->msg.len);
                json[s->msg.len] = '\0';
            }
            s->msg.len = 0;
            if (json) {
                rmt_message(st, i, json);
            }
            free(json);
        }
        return;
    }
    { /* a session pic does not have: a reset, which can cause only a new handshake */
        unsigned char out[16];
        if (rmt_tally_due(&st->reset_unknown)) {
            rmt_log(stdout, "pic remote: reset a session of %s that this pic remote does not have (%lld so far)\n",
                    st->devs[di].d.name, st->reset_unknown.n);
        }
        (void)rmt_lane_add(&st->devs[di].lane, out, pic_noise_head(PIC_NOISE_REC_RESET, rec + 1, NULL, 0, out));
    }
}

/* ---- devices coming and going ---------------------------------------------------------------- */

static void rmt_offer_closing(rmt_state *st);
static int rmt_devices_sync(rmt_state *st, int quiet);

static void rmt_unpair_device(rmt_state *st, int di, int tell) {
    rmt_dev *d = &st->devs[di];
    if (tell && d->sess >= 0) {
        rmt_send_free(st, d, strdup("{\"type\":\"unpaired\"}"));
        (void)rmt_lane_flush(&st->r, &d->lane);
    }
    for (int i = 0; i < RMT_SESSIONS; i++) {
        if (st->sess[i].used && st->sess[i].dev == di) {
            free(st->sess[i].msg.buf);
            memset(&st->sess[i], 0, sizeof st->sess[i]);
        }
    }
    d->sess = -1;
    if (st->offer && st->offer_dev == di && st->offer->stage != OFFER_OVER) { /* its offer has no one to answer it */
        rmt_offer_refuse(st->offer, &st->r);
        rmt_offer_closing(st);
    }
    if (d->alive) {
        rmt_device_delete(d->d.id);
    }
    d->alive = 0;
    rmt_unfollow(d);
    rmt_delete_channel(&st->r, d->d.channel);
    d->lane.qlen = 0;
}

/* ---- pairing from a paired phone (Amendments) ------------------------------------------------- */

/* The device list, as SELF sees it. */
static char *rmt_devices_json(rmt_state *st, int self) {
    rmt_buf b = {NULL, 0, 0};
    char *out;
    (void)rmt_buf_add(&b, "[", 1);
    for (int i = 0; i < st->ndevs; i++) {
        rmt_dev *d = &st->devs[i];
        char paired[24], seen[24], *one;
        if (!d->alive) {
            continue;
        }
        (void)snprintf(paired, sizeof paired, "%lld", d->d.paired_ms);
        (void)snprintf(seen, sizeof seen, "%lld", d->sess >= 0 ? rmt_wall_ms() : d->d.seen_ms);
        one = rmt_q("SELECT json_object('id', ?1, 'name', ?2, 'pairedMs', CAST(?3 AS INTEGER), 'seenMs', CAST(?4 AS INTEGER),"
                    " 'self', json(?5))",
                    5, d->idb, d->d.name, paired, seen, i == self ? "true" : "false");
        if (one) {
            if (b.len > 1) {
                (void)rmt_buf_add(&b, ",", 1);
            }
            (void)rmt_buf_add(&b, one, strlen(one));
        }
        free(one);
    }
    (void)rmt_buf_add(&b, "]", 1);
    out = rmt_q("SELECT json_object('type', 'devices', 'payload', json_object('devices', json(?1)))", 1, b.buf);
    free(b.buf);
    return out;
}

/* After a pairing or an unpairing: the list again to each phone that has asked for it. */
static void rmt_devices_tell(rmt_state *st) {
    for (int i = 0; i < st->ndevs; i++) {
        if (st->devs[i].alive && st->devs[i].sess >= 0 && st->devs[i].want_devices) {
            rmt_send_free(st, &st->devs[i], rmt_devices_json(st, i));
        }
    }
}

static void rmt_pair_end(rmt_state *st, int di, const char *result, const char *name, const char *device) {
    if (di < 0 || di >= st->ndevs || !st->devs[di].alive) {
        return;
    }
    rmt_send_free(st, &st->devs[di],
                  rmt_q("SELECT json_object('type', 'pair_end', 'payload',"
                        " json_patch(json_object('result', ?1), json_object('name', ?2, 'device', ?3)))",
                        3, result, name, device));
}

/* The waiting device's name and six digits, to the phone that asked for the offer. */
static void rmt_offer_tell(rmt_state *st) {
    rmt_dev *d = &st->devs[st->offer_dev];
    rmt_send_free(st, d,
                  rmt_q("SELECT json_object('type', 'pair_request', 'payload', json_object('name', ?1, 'code', ?2))", 2,
                        st->offer->d.name, st->offer->sas));
}

/* The offer is over: its last word (paired, or a refusal) is posted, and the channel goes once the
 * new device has read it, as rmt_pair_last_word waits, without holding up the loop. */
static void rmt_offer_closing(rmt_state *st) {
    rmt_offer *o = st->offer;
    long long now = rmt_mono_ms();
    o->stage = OFFER_OVER;
    st->offer_posted = o->said && !o->lane.qlen;
    st->offer_reading = st->offer_posted ? st->r.peer : -1;
    st->offer_close_ms = !o->said ? now : st->offer_posted && st->offer_reading < 0 ? now + RMT_NO_PEER_MS : now + RMT_LAST_WORD_MS;
}

static void rmt_offer_close(rmt_state *st) {
    if (!st->offer) {
        return;
    }
    rmt_delete_channel(&st->r, st->offer->P);
    if (st->offer_str) {
        atomic_store(&st->offer_str->quit, 1);
        rmt_stream_release(st->offer_str);
        st->offer_str = NULL;
    }
    rmt_offer_free(st->offer);
    free(st->offer);
    st->offer = NULL;
}

static void rmt_offer_ask(rmt_state *st, int di) {
    char err[256], *set = pic_setting("remote.phonePairing"), exp[24], tok[32];
    int off = set && strcmp(set, "off") == 0, alive = 0;
    rmt_offer *o;
    rmt_stream *str;
    free(set);
    if (off) {
        rmt_pair_end(st, di, "off", NULL, NULL);
        return;
    }
    if (st->offer && st->offer->stage != OFFER_OVER) {
        if (st->offer_dev != di) {
            rmt_pair_end(st, di, "busy", NULL, NULL);
            return;
        }
        (void)snprintf(exp, sizeof exp, "%lld", st->offer->expires); /* asked again: the same offer */
        rmt_send_free(st, &st->devs[di],
                      rmt_q("SELECT json_object('type', 'pair_offer', 'payload', json_object('url', ?1, 'expires', CAST(?2 AS INTEGER)))",
                            2, st->offer->url, exp));
        if (st->offer->stage == OFFER_ASKING) {
            rmt_offer_tell(st);
        }
        return;
    }
    rmt_offer_close(st); /* one whose last word still waits: a new offer replaces it at the relay anyway */
    for (int i = 0; i < st->ndevs; i++) {
        alive += st->devs[i].alive;
    }
    if (alive >= 8) {
        rmt_pair_end(st, di, "full", NULL, NULL);
        return;
    }
    o = calloc(1, sizeof *o);
    str = calloc(1, sizeof *str);
    if (!o || !str || rmt_offer_open(o, &st->r, &st->k, RMT_PHONE_PAIR_TTL, err, sizeof err) != 0) {
        free(o);
        free(str);
        rmt_pair_end(st, di, "failed", NULL, NULL);
        return;
    }
    pic_b64u_enc(o->P, 16, tok);
    (void)snprintf(str->url, sizeof str->url, "%s/v1/m/%s/c/%s/up", st->r.base, st->r.mbx, tok);
    (void)snprintf(str->auth, sizeof str->auth, "%s", st->r.owner);
    memcpy(str->channel, o->P, 16);
    atomic_store(&str->refs, 2);
    if (rmt_stream_start(str, st->pipe_w) != 0) {
        rmt_delete_channel(&st->r, o->P);
        rmt_offer_free(o);
        free(o);
        free(str);
        rmt_pair_end(st, di, "failed", NULL, NULL);
        return;
    }
    (void)pthread_detach(str->th);
    st->offer = o;
    st->offer_str = str;
    st->offer_dev = di;
    (void)snprintf(exp, sizeof exp, "%lld", o->expires);
    rmt_send_free(st, &st->devs[di],
                  rmt_q("SELECT json_object('type', 'pair_offer', 'payload', json_object('url', ?1, 'expires', CAST(?2 AS INTEGER)))", 2,
                        o->url, exp));
    rmt_log(stdout, "pic remote: %s is adding a device\n", st->devs[di].d.name);
    (void)fflush(stdout);
}

/* pair_approve (YES, with the six digits in CODE) or pair_deny, from device DI. Only the device
 * that asked for the offer answers it, and an approval only once a device waits; a code that is
 * not the waiting device's refuses the offer: one try. */
static void rmt_offer_answer(rmt_state *st, int di, int yes, const char *code) {
    rmt_offer *o = st->offer;
    char err[256], idb[32], name[72];
    if (!o || o->stage == OFFER_OVER || st->offer_dev != di || (yes && o->stage != OFFER_ASKING)) {
        rmt_error(st, &st->devs[di], NULL, "no_offer", "no device is waiting for this phone's answer");
        return;
    }
    if (!yes || strlen(code) != 6 || !rmt_same((const unsigned char *)code, (const unsigned char *)o->sas, 6) ||
        rmt_dev_by_channel(st, o->d.channel) >= 0) { /* a channel already a device's is no new device's */
        rmt_offer_refuse(o, &st->r);
        rmt_offer_closing(st);
        rmt_pair_end(st, di, "refused", o->d.name, NULL);
        rmt_log(stdout, "pic remote: %s did not pair %s\n", st->devs[di].d.name, o->d.name);
        (void)fflush(stdout);
        return;
    }
    if (rmt_offer_accept(o, &st->r, err, sizeof err) != 0) {
        rmt_offer_closing(st);
        rmt_pair_end(st, di, "failed", o->d.name, NULL);
        rmt_log(stderr, "pic remote: %s\n", err);
        return;
    }
    rmt_offer_closing(st);
    pic_b64u_enc(o->d.id, 16, idb);
    (void)snprintf(name, sizeof name, "%s", o->d.name);
    rmt_log(stdout, "pic remote: %s paired %s\n", st->devs[di].d.name, name);
    (void)fflush(stdout);
    (void)rmt_devices_sync(st, 0); /* this process's own write: data_version does not show it */
    rmt_pair_end(st, di, "paired", name, idb);
    rmt_devices_tell(st);
}

/* Each tick: the offer's expiry, its posts, and the end of its last word's wait. */
static void rmt_offer_tick(rmt_state *st) {
    rmt_offer *o = st->offer;
    long long now = rmt_mono_ms();
    if (!o) {
        return;
    }
    if (o->stage != OFFER_OVER && now > o->mono_end) {
        rmt_offer_refuse(o, &st->r);
        rmt_offer_closing(st);
        rmt_pair_end(st, st->offer_dev, "expired", o->d.name[0] ? o->d.name : NULL, NULL);
    }
    if (o->lane.qlen) {
        (void)rmt_lane_flush(&st->r, &o->lane);
        if (o->stage == OFFER_OVER && !o->lane.qlen && !st->offer_posted) {
            st->offer_posted = 1;
            st->offer_reading = st->r.peer;
            if (st->offer_reading < 0) {
                st->offer_close_ms = now + RMT_NO_PEER_MS;
            }
        }
    }
    if (o->stage == OFFER_OVER && ((st->offer_posted && st->offer_reading == 1) || now >= st->offer_close_ms)) {
        rmt_offer_close(st);
    }
}

/* An event from the offer's stream (its channel, not the mailbox stream's). */
static void rmt_offer_event(rmt_state *st, int kind, const unsigned char *rec, size_t n) {
    rmt_offer *o = st->offer;
    if (kind == RMT_EV_FRAME) {
        int ev = rmt_offer_frame(o, &st->r, &st->k, rec, n);
        if (ev == OFFER_EV_FAILED) {
            rmt_offer_closing(st);
            rmt_pair_end(st, st->offer_dev, "failed", NULL, NULL);
        } else if (ev == OFFER_EV_ASK) {
            rmt_offer_tell(st);
        }
    } else if (kind == RMT_EV_PEER) {
        if (o->stage == OFFER_OVER && st->offer_posted && n == 1 && rec[0] == 1) {
            rmt_offer_close(st); /* the new device is back, and has been sent what the relay held */
        }
    } else if (kind == RMT_EV_GONE || kind == RMT_EV_REFUSED) { /* another offer (/rc's) replaced it at the relay */
        if (o->stage != OFFER_OVER) {
            o->stage = OFFER_OVER;
            rmt_pair_end(st, st->offer_dev, "failed", NULL, NULL);
        }
        o->said = 0;
        rmt_offer_close(st);
    }
}

/* The table, read again: new rows are served from now on, deleted ones end their sessions. */
static int rmt_devices_sync(rmt_state *st, int quiet) {
    rmt_device *list;
    int n, bad, changed = 0;
    char err[256];
    if (rmt_devices_load(&list, &n, &bad, err, sizeof err) != 0) {
        return -1;
    }
    for (int i = 0; i < st->ndevs; i++) {
        int still = 0;
        for (int k = 0; k < n; k++) {
            still = still || memcmp(list[k].id, st->devs[i].d.id, 16) == 0;
        }
        if (st->devs[i].alive && !still) {
            st->devs[i].alive = 0; /* deleted at the terminal: the row's deletion is the revocation */
            rmt_unpair_device(st, i, 1);
            changed = 1;
            if (!quiet) {
                rmt_log(stdout, "pic remote: %s was unpaired\n", st->devs[i].d.name);
                (void)fflush(stdout);
            }
        }
    }
    for (int k = 0; k < n; k++) {
        int known = 0;
        for (int i = 0; i < st->ndevs; i++) {
            known = known || (st->devs[i].alive && memcmp(list[k].id, st->devs[i].d.id, 16) == 0);
        }
        if (!known) {
            rmt_dev *grown = realloc(st->devs, (size_t)(st->ndevs + 1) * sizeof *grown), *d;
            if (!grown) {
                continue;
            }
            st->devs = grown;
            d = &st->devs[st->ndevs++];
            memset(d, 0, sizeof *d);
            d->d = list[k];
            pic_b64u_enc(d->d.id, 16, d->idb);
            memcpy(d->lane.ch, d->d.channel, 16);
            d->sess = -1;
            d->alive = 1;
            changed = 1;
            if (rmt_put_channel(&st->r, d->d.channel, 0, err, sizeof err) != 0 && !quiet) {
                rmt_log(stderr, "pic remote: %s\n", err);
            }
            if (!quiet) {
                rmt_log(stdout, "pic remote: serving %s\n", d->d.name);
                (void)fflush(stdout);
            }
        }
    }
    free(list);
    if (changed && !quiet) {
        rmt_devices_tell(st);
    }
    return 0;
}

/* Section 7's reconcile: the mailbox, every device's channel, and no device channel without a row. */
static int rmt_reconcile(rmt_state *st, char *err, size_t cap) {
    char path[128], *list = NULL;
    int stc;
    if (rmt_put_mailbox(&st->r, err, cap) != 0) {
        return -1;
    }
    (void)snprintf(path, sizeof path, "/v1/m/%s/c", st->r.mbx);
    stc = rmt_call(&st->r, "GET", path, st->r.owner, NULL, 0, NULL, &list, err, cap);
    if (stc == 200 && list) {
        sqlite3_stmt *q = NULL;
        if (sqlite3_prepare_v2(rmt_mem(), "SELECT json_extract(value, '$.id') FROM json_each(?1)"
                                          " WHERE json_extract(value, '$.kind') = 'device'",
                               -1, &q, NULL) == SQLITE_OK) {
            sqlite3_bind_text(q, 1, list, -1, SQLITE_STATIC);
            while (sqlite3_step(q) == SQLITE_ROW) {
                const char *id = (const char *)sqlite3_column_text(q, 0);
                unsigned char ch[16];
                if (id && pic_b64u_dec(id, strlen(id), ch, sizeof ch) == 16 && rmt_dev_by_channel(st, ch) < 0) {
                    rmt_delete_channel(&st->r, ch);
                }
            }
        }
        sqlite3_finalize(q);
    }
    free(list);
    return 0;
}

/* ---- pic remote ------------------------------------------------------------------------------ */

static void rmt_on_signal(int sig) {
    if (sig == SIGUSR1) {
        rmt_restart_asked = 1;
    } else {
        rmt_stop = 1;
    }
}

static int rmt_lock(void) {
    char path[PATH_MAX];
    const char *home = getenv("HOME");
    if (!home || snprintf(path, sizeof path, "%s/.pic/remote.lock", home) >= (int)sizeof path) {
        return -1;
    }
    return pic_platform_get()->lock(path, 0);
}

/* Whether a pic remote is running, by trying its lock for an instant: 1, 0, or -1. */
static int rmt_running_now(void) {
    int h = rmt_lock();
    if (h >= 0) {
        pic_platform_get()->unlock(h);
        return 0;
    }
    return h == -2 ? 1 : -1;
}

/* The store's key from its own source every time, never one handed down by a parent: a
 * passphrase store asks on the terminal; a key in the Keychain or the key file needs no one, so
 * launchd can start it. */
static int rmt_unlock_fresh(char *err, size_t cap) {
    pic_cred_lock();
    if (pic_cred_state() == PIC_CRED_NEW) {
        (void)snprintf(err, cap, "the credential store has no key yet: pair a phone with /rc or pic remote pair first");
        return -1;
    }
    return pic_cred_unlock(err, cap);
}

/* ---- status: ~/.pic/remote.status, written by the running pic remote, read by status and stop ---- */

static int rmt_status_path(char *out, size_t cap, const char *suffix) {
    const char *home = getenv("HOME");
    return home && snprintf(out, cap, "%s/.pic/remote.status%s", home, suffix) < (int)cap ? 0 : -1;
}

/* The phones in a session now, as JSON: [{"name","session","visible"}], session the W/C each follows
 * or null; written into the status file for the terminal's footer. */
static char *rmt_phones;

/* The running one's state, replaced whole (a rename), so a reader never sees half of it. */
static void rmt_status_write(const char *state, const char *relay, int devices, int attempts, long long retry_at,
                             const char *why) {
    char path[PATH_MAX], tmp[PATH_MAX], pid[24], n[24], a[24], r[24], now[24], started[24];
    char *json, *with;
    FILE *f;
    if (rmt_status_path(path, sizeof path, "") != 0 || rmt_status_path(tmp, sizeof tmp, ".tmp") != 0) {
        return;
    }
    (void)snprintf(started, sizeof started, "%lld", rmt_started_ms);
    (void)snprintf(pid, sizeof pid, "%ld", (long)getpid());
    (void)snprintf(n, sizeof n, "%d", devices);
    (void)snprintf(a, sizeof a, "%d", attempts);
    (void)snprintf(r, sizeof r, "%lld", retry_at);
    (void)snprintf(now, sizeof now, "%lld", rmt_wall_ms());
    json = rmt_q("SELECT json_object('pid', CAST(?1 AS INTEGER), 'state', ?2, 'relay', ?3, 'devices', CAST(?4 AS INTEGER),"
                 " 'attempts', CAST(?5 AS INTEGER), 'retryAtMs', CAST(?6 AS INTEGER), 'error', ?7, 'updatedMs', CAST(?8 AS INTEGER),"
                 " 'phones', json(?9))",
                 9, pid, state, relay ? relay : "", n, a, r, why ? why : "", now,
                 rmt_phones && strcmp(state, "connected") == 0 ? rmt_phones : "[]");
    /* what it runs, for status to tell an older pic remote from this pic */
    with = json ? rmt_q("SELECT json_set(?1, '$.exe', ?2, '$.exeStamp', ?3, '$.startedMs', CAST(?4 AS INTEGER))", 4, json, rmt_exe,
                        rmt_exe_stamp, started)
                : NULL;
    free(json);
    json = with;
    if (json && (f = fopen(tmp, "w")) != NULL) {
        int ok = fputs(json, f) >= 0 && fputc('\n', f) != EOF;
        ok = fclose(f) == 0 && ok;
        if (!ok || rename(tmp, path) != 0) {
            (void)unlink(tmp);
        }
    }
    free(json);
}

/* What the status file says, malloc'd, or NULL. */
static char *rmt_status_read(void) {
    char path[PATH_MAX], buf[4096];
    FILE *f;
    size_t n;
    if (rmt_status_path(path, sizeof path, "") != 0 || !(f = fopen(path, "r"))) {
        return NULL;
    }
    n = fread(buf, 1, sizeof buf - 1, f);
    fclose(f);
    buf[n] = '\0';
    return n ? strdup(buf) : NULL;
}

static int rmt_device_count(void) { return pic_remote_phones(); }

int pic_remote_running(void) { return rmt_running_now() == 1; }

/* Appends S to OUT percent-encoded but for unreserved characters and '/'; 0, or -1 when it does not fit. */
static int rmt_link_add(char *out, size_t cap, size_t *len, const char *s, int encode) {
    static const char hex[] = "0123456789ABCDEF";
    for (; *s; s++) {
        unsigned char c = (unsigned char)*s;
        int plain = !encode || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') ||
                    strchr("-._~/", c) != NULL;
        if (*len + (plain ? 1 : 3) >= cap) {
            return -1;
        }
        if (plain) {
            out[(*len)++] = (char)c;
        } else {
            out[(*len)++] = '%';
            out[(*len)++] = hex[c >> 4];
            out[(*len)++] = hex[c & 15];
        }
    }
    out[*len] = '\0';
    return 0;
}

int pic_remote_link(const char *session, char *out, size_t cap) {
    sqlite3 *db = pic_userdb(NULL, 0);
    sqlite3_stmt *q = NULL;
    rmt_relay r;
    char phone[32] = "";
    size_t len = 0;
    int n = rmt_device_count();
    if (!cap) {
        return -1;
    }
    out[0] = '\0';
    rmt_relay_init(&r, NULL);
    if (n == 1 && db && sqlite3_prepare_v2(db, "SELECT id FROM picu_remote_device", -1, &q, NULL) == SQLITE_OK &&
        sqlite3_step(q) == SQLITE_ROW && sqlite3_column_bytes(q, 0) == 16) {
        pic_b64u_enc(sqlite3_column_blob(q, 0), 16, phone);
    }
    sqlite3_finalize(q);
    if (rmt_link_add(out, cap, &len, r.base, 0) != 0 || rmt_link_add(out, cap, &len, "/", 0) != 0) {
        return -1;
    }
    /* The conversation's id alone: the page finds it in the list pic remote sends, so no path is in the link. */
    if (session && *session &&
        (rmt_link_add(out, cap, &len, "#s=", 0) != 0 || rmt_link_add(out, cap, &len, session, 1) != 0)) {
        return -1;
    }
    if (phone[0] && (rmt_link_add(out, cap, &len, strchr(out, '#') ? "&c=" : "#c=", 0) != 0 ||
                     rmt_link_add(out, cap, &len, phone, 0) != 0)) {
        return -1;
    }
    return n;
}

/* The stream's state into the status file when it changed, and every 5 s regardless. */
static void rmt_status_tick(rmt_state *st, rmt_stream *str, int force) {
    static int last_state = -1, last_attempts = -1;
    static long long last_ms;
    int state = atomic_load(&str->state), attempts = atomic_load(&str->attempts), alive = 0;
    long long now = rmt_mono_ms();
    char *phones = NULL;
    {
        sqlite3_str *p = sqlite3_str_new(NULL);
        sqlite3_str_appendall(p, "SELECT json_array(");
        for (int i = 0, k = 0; i < st->ndevs; i++) {
            if (st->devs[i].alive && st->devs[i].sess >= 0) {
                sqlite3_str_appendf(p, "%sjson_object('name', %Q, 'session', %Q, 'visible', json(%Q))", k++ ? "," : "",
                                    st->devs[i].d.name, st->devs[i].f ? st->devs[i].wsess : NULL,
                                    st->devs[i].visible ? "true" : "false");
            }
        }
        sqlite3_str_appendall(p, ")");
        {
            char *sql = sqlite3_str_finish(p);
            phones = sql ? rmt_q(sql, 0) : NULL;
            sqlite3_free(sql);
        }
    }
    if (phones && (!rmt_phones || strcmp(phones, rmt_phones) != 0)) { /* a phone came, went or opened another */
        free(rmt_phones);
        rmt_phones = phones;
        force = 1;
    } else {
        free(phones);
    }
    if (!force && state == last_state && attempts == last_attempts && now - last_ms < 5000) {
        return;
    }
    for (int i = 0; i < st->ndevs; i++) {
        alive += st->devs[i].alive;
    }
    last_state = state;
    last_attempts = attempts;
    last_ms = now;
    rmt_status_write(state == RMT_CONN_CONNECTED ? "connected" : attempts ? "reconnecting" : "connecting", st->r.base, alive,
                     attempts, state == RMT_CONN_WAITING ? atomic_load(&str->retry_at) : 0,
                     state == RMT_CONN_CONNECTED ? "" : str->why);
}

/* The conversation list to D when it differs from the one it has. */
static void rmt_list_check(rmt_state *st, rmt_dev *d) {
    char *list = rmt_list(st, -1);
    if (list && (!d->list_sent || strcmp(list, d->list_sent) != 0)) {
        (void)rmt_send(st, d, list);
        free(d->list_sent);
        d->list_sent = list;
    } else {
        free(list);
    }
}

/* Loops with the terminal closed: every 5 seconds this journal is asked what is due (wake.h),
 * which fires it and starts its request; and a loop that came to need a person since the last
 * look (its message refused, its 7 days up) is a notification, once. */
static void rmt_wake_tick(rmt_state *st, rmt_journal *j) {
    long long now = rmt_mono_ms(), next = 0;
    sqlite3_stmt *q = NULL;
    int fired = 0;
    if (j->wake_at && now - j->wake_at < 5000 && now >= j->wake_at) {
        return;
    }
    j->wake_at = now ? now : 1;
    rmt_doing("looking at the loops of", j->path);
    if (pic_wake_due(&j->s, j->workspace, NULL, 1, &fired, &next) != 0) {
        j->s.err[0] = '\0';
    }
    if (!j->wake_init) { /* what came before this pic remote is not news */
        if (sqlite3_prepare_v2(j->s.db, "SELECT coalesce(max(updated_ms), 0) FROM pic_wake", -1, &q, NULL) == SQLITE_OK &&
            sqlite3_step(q) == SQLITE_ROW) {
            j->wake_seen = sqlite3_column_int64(q, 0);
            j->wake_init = 1;
        }
        sqlite3_finalize(q);
        return;
    }
    if (sqlite3_prepare_v2(j->s.db,
                           "SELECT w.session_id, upper(substr(w.kind, 1, 1)) || substr(w.kind, 2) || ' ' || upper(substr(w.kind, 1, 1))"
                           " || w.id || CASE WHEN w.state = 'needs' THEN ' needs you: ' || coalesce(w.why, '')"
                           " ELSE ' has ended: its 7 days are up' END,"
                           " coalesce((SELECT " PIC_TITLE_SQL("t") " FROM pic_session t WHERE t.id = w.session_id), ''),"
                           " coalesce((SELECT t.head_seq FROM pic_session t WHERE t.id = w.session_id), 0), w.updated_ms"
                           " FROM pic_wake w WHERE w.updated_ms > ?1 AND (w.state = 'needs' OR (w.state = 'ended' AND w.why = 'expired'))"
                           /* waiting for an OK: an ask, told by rmt_ask_check */
                           " AND NOT (coalesce(json_extract(w.options, '$.approval'), '') = 'asked' AND w.state = 'needs'"
                           " AND EXISTS (SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = 'pic_ask'))"
                           " ORDER BY w.updated_ms",
                           -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_int64(q, 1, j->wake_seen);
        while (sqlite3_step(q) == SQLITE_ROW) {
            char *body = pic_one_line((const char *)sqlite3_column_text(q, 1), 200);
            if (body) {
                rmt_notify(st, j, (const char *)sqlite3_column_text(q, 0), (const char *)sqlite3_column_text(q, 2), 1,
                           sqlite3_column_int64(q, 3), body);
            }
            free(body);
            if (sqlite3_column_int64(q, 4) > j->wake_seen) {
                j->wake_seen = sqlite3_column_int64(q, 4);
            }
        }
    }
    sqlite3_finalize(q);
    /* changes since, of any loop: a later look need not read them again */
    if (sqlite3_prepare_v2(j->s.db, "SELECT coalesce(max(updated_ms), 0) FROM pic_wake WHERE updated_ms > ?1", -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_int64(q, 1, j->wake_seen);
        if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_int64(q, 0) > j->wake_seen) {
            j->wake_seen = sqlite3_column_int64(q, 0);
        }
    }
    sqlite3_finalize(q);
}

/* ---- asks (ask.h): a question a conversation waits on a person for ------------------------- */

/* Each ask of LIST (pic_ask_list's array) of journal J to D, or (D NULL) to every device with a
 * confirmed session: an open one as ask, a settled one as ask_settled. With TELL, an open one is
 * also a notification, in pic's own words so nothing the question says reaches a lock screen. */
static void rmt_asks_send(rmt_state *st, rmt_dev *d, rmt_journal *j, const char *list, int tell) {
    sqlite3_stmt *q = NULL;
    char *names = rmt_device_names(st);
    if (!list || !names ||
        sqlite3_prepare_v2(rmt_mem(),
                           "SELECT CASE WHEN json_extract(value, '$.state') = 'open' THEN json_object('type', 'ask', 'session', ?2 || '/'"
                           " || json_extract(value, '$.session'), 'payload', json_remove(value, '$.session', '$.version'))"
                           " ELSE json_object('type', 'ask_settled', 'session', ?2 || '/' || json_extract(value, '$.session'), 'payload', "
                           RMT_SETTLED_SQL("value", "?3") ") END, json_extract(value, '$.session'), json_extract(value, '$.state') = 'open'"
                           " FROM json_each(?1)",
                           -1, &q, NULL) != SQLITE_OK) {
        free(names);
        return;
    }
    sqlite3_bind_text(q, 1, list, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 2, j->path, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 3, names, -1, SQLITE_STATIC);
    while (sqlite3_step(q) == SQLITE_ROW) {
        const char *rec = (const char *)sqlite3_column_text(q, 0);
        for (int i = 0; i < st->ndevs; i++) {
            rmt_dev *o = &st->devs[i];
            if ((d ? o == d : o->alive && o->sess >= 0 && st->sess[o->sess].confirmed)) {
                (void)rmt_send(st, o, rec);
            }
        }
        if (tell && sqlite3_column_int(q, 2)) {
            const char *conv = (const char *)sqlite3_column_text(q, 1);
            sqlite3_stmt *t = NULL;
            char *ctitle = NULL, *who = NULL, body[300];
            long long seq = 0;
            if (sqlite3_prepare_v2(j->s.db, "SELECT " PIC_TITLE_SQL("t") ", coalesce(t.head_seq, 0) FROM pic_session t WHERE t.id = ?1", -1, &t,
                                   NULL) == SQLITE_OK) {
                sqlite3_bind_text(t, 1, conv, -1, SQLITE_STATIC);
                if (sqlite3_step(t) == SQLITE_ROW) {
                    ctitle = sqlite3_column_type(t, 0) == SQLITE_NULL ? NULL : strdup((const char *)sqlite3_column_text(t, 0));
                    seq = sqlite3_column_int64(t, 1);
                }
            }
            sqlite3_finalize(t);
            /* the title the notification shows: the conversation's, else the workspace's folder */
            if (ctitle && *ctitle) {
                who = pic_one_line(ctitle, 60);
            } else if ((who = strdup(j->workspace))) {
                size_t e = strlen(who);
                while (e > 1 && who[e - 1] == '/') {
                    who[--e] = '\0';
                }
                if (strrchr(who, '/')) {
                    memmove(who, strrchr(who, '/') + 1, strlen(strrchr(who, '/') + 1) + 1);
                }
            }
            (void)snprintf(body, sizeof body, "%s needs your answer", who ? who : "A conversation");
            rmt_notify(st, j, conv, ctitle, 1, seq, body);
            free(who);
            free(ctitle);
        }
    }
    sqlite3_finalize(q);
    free(names);
}

/* A phone's new session: the open asks of every journal, whatever it was told before. */
static void rmt_asks_open(rmt_state *st, rmt_dev *d) {
    for (int i = 0; i < st->njs; i++) {
        if (st->js[i]->open) {
            char *list = pic_ask_list(&st->js[i]->s, NULL, -1, RMT_ASKS);
            rmt_asks_send(st, d, st->js[i], list, 0);
            free(list);
        }
    }
}

/* Asks of J that expired unanswered with nobody answering, looked at every 5 s by index: each is
 * ask_settled with kind expired, once (the ring of those told). */
static void rmt_ask_expiry(rmt_state *st, rmt_journal *j) {
    long long now = rmt_mono_ms();
    sqlite3_stmt *q = NULL;
    rmt_buf b = {NULL, 0, 0};
    if (j->ask_expiry_ms && now - j->ask_expiry_ms < 5000 && now >= j->ask_expiry_ms) {
        return;
    }
    j->ask_expiry_ms = now ? now : 1;
    if (sqlite3_prepare_v2(j->s.db, "SELECT id, session_id FROM pic_ask WHERE state = 'open' AND expires_ms <= ?1 ORDER BY rowid LIMIT ?2",
                           -1, &q, NULL) != SQLITE_OK) {
        return;
    }
    sqlite3_bind_int64(q, 1, pic_wake_now_ms());
    sqlite3_bind_int(q, 2, RMT_ASKS);
    (void)rmt_buf_add(&b, "[", 1);
    while (sqlite3_step(q) == SQLITE_ROW) {
        const char *id = (const char *)sqlite3_column_text(q, 0);
        int told = 0;
        for (int k = 0; k < RMT_ASK_RING; k++) {
            told |= strcmp(j->ask_told[k], id) == 0;
        }
        if (told) {
            continue;
        }
        (void)snprintf(j->ask_told[j->ask_told_at++ % RMT_ASK_RING], sizeof j->ask_told[0], "%s", id);
        if (j->ask_init) {
            char *one = rmt_q("SELECT json_object('id', ?1, 'session', ?2, 'state', 'expired')", 2, id,
                              (const char *)sqlite3_column_text(q, 1));
            if (one) {
                if (b.len > 1) {
                    (void)rmt_buf_add(&b, ",", 1);
                }
                (void)rmt_buf_add(&b, one, strlen(one));
            }
            free(one);
        }
    }
    sqlite3_finalize(q);
    (void)rmt_buf_add(&b, "]", 2);
    if (b.buf && b.len > 2) {
        rmt_asks_send(st, NULL, j, b.buf, 0);
    }
    free(b.buf);
}

/* The asks of J opened or closed since the last look, by version (an index), when the journal
 * changed: each to every phone, an open one notified. The first look only learns where it is. */
static void rmt_ask_check(rmt_state *st, rmt_journal *j) {
    long long v = rmt_data_version(j->s.db);
    char *list;
    rmt_ask_expiry(st, j);
    if (v == j->ask_dv) {
        return;
    }
    j->ask_dv = v;
    if (!j->ask_init) {
        sqlite3_stmt *q = NULL;
        if (sqlite3_prepare_v2(j->s.db, "SELECT coalesce(max(version), 0) FROM pic_ask", -1, &q, NULL) == SQLITE_OK &&
            sqlite3_step(q) == SQLITE_ROW) {
            j->ask_version = sqlite3_column_int64(q, 0);
        } else {
            j->ask_version = 0; /* no asks yet: every one made from now on is news */
        }
        sqlite3_finalize(q);
        j->ask_init = 1;
        return;
    }
    if (!(list = pic_ask_list(&j->s, NULL, j->ask_version, RMT_ASKS))) {
        j->s.err[0] = '\0';
        j->ask_dv = -1; /* busy, say: looked at again next tick */
        return;
    }
    rmt_asks_send(st, NULL, j, list, 1);
    {
        char *top = rmt_q("SELECT coalesce(max(json_extract(value, '$.version')), 0) FROM json_each(?1)", 1, list);
        if (top && atoll(top) > j->ask_version) {
            j->ask_version = atoll(top);
            j->ask_dv = -1; /* there may be more than one page */
        }
        free(top);
    }
    free(list);
}

/* The command answer {id, value}, sent under the key ask-ID: the ask of the conversation answered,
 * first writer wins. data {result: answered, already_answered or expired, id, value, by} with the
 * answer that stands. A repeat of the key (or of the device's own answer) gets the same result:
 * it is read from the row. Not an answer, or over a limit: bad_command. */
static void rmt_answer(rmt_state *st, rmt_dev *d, rmt_env *e, int jx, const char *conv) {
    char by[48], owner[64] = "";
    char *id = rmt_q("SELECT CASE json_type(?1, '$.id') WHEN 'text' THEN json_extract(?1, '$.id') END", 1, e->payload);
    char *value = rmt_q("SELECT ?1 -> '$.value' WHERE json_type(?1, '$.value') IS NOT NULL", 1, e->payload);
    char *standing = NULL, *data = NULL, *names = NULL, *line;
    pic_store *s = &st->js[jx]->s;
    int rc;
    if (!id || !value || strlen(id) > 64) {
        rmt_error(st, d, e->key, "bad_command", "an answer is {\"type\":\"answer\",\"id\":ID,\"value\":V}");
        goto done;
    }
    {
        sqlite3_stmt *q = NULL;
        if (sqlite3_prepare_v2(s->db, "SELECT session_id FROM pic_ask WHERE id = ?1", -1, &q, NULL) == SQLITE_OK) {
            sqlite3_bind_text(q, 1, id, -1, SQLITE_STATIC);
            if (sqlite3_step(q) == SQLITE_ROW) {
                (void)snprintf(owner, sizeof owner, "%s", (const char *)sqlite3_column_text(q, 0));
            }
        }
        sqlite3_finalize(q);
    }
    if (strcmp(owner, conv) != 0) { /* no_ask, as the response's error */
        line = rmt_pi_response(e->payload, "answer", 0, NULL, "no such question in this conversation");
        rmt_response(st, d, e->key, line);
        free(line);
        goto done;
    }
    {
        char *len = rmt_q("SELECT iif(json_type(?1) = 'text', length(json_extract(?1, '$')), 0)", 1, value);
        int over = len && atoll(len) > PIC_ASK_TEXT_MAX;
        free(len);
        if (over) {
            rmt_error(st, d, e->key, "bad_command", "an answer has at most 4000 characters");
            goto done;
        }
    }
    (void)snprintf(by, sizeof by, "remote:%s", d->idb);
    s->err[0] = '\0';
    rc = pic_ask_answer(s, id, value, by, &standing);
    st->js[jx]->ask_dv = -1; /* its own write does not change its data_version: the close is told next tick */
    if (rc == PIC_ASK_REFUSED) { /* bad_answer, as the response's error */
        line = rmt_pi_response(e->payload, "answer", 0, NULL, s->err);
        rmt_response(st, d, e->key, line);
        free(line);
        goto done;
    }
    if (rc < 0) {
        rmt_error(st, d, e->key, rmt_busy(s) ? "busy" : "failed", rmt_busy(s) ? RMT_BUSY_TEXT : s->err);
        goto done;
    }
    names = rmt_device_names(st);
    if (rc == PIC_ASK_ANSWERED) {
        standing = rmt_q("SELECT json_object('state', 'answered', 'value', json(?1), 'answeredBy', ?2)", 2, value, by);
    }
    data = rmt_q("SELECT json_patch(json_object('result', ?1), " RMT_SETTLED_SQL("json_set(?2, '$.id', ?4)", "?3") ")", 4,
                 rc == PIC_ASK_ANSWERED ? "answered" : rc == PIC_ASK_EXPIRED ? "expired" : "already_answered", standing ? standing : "{}",
                 names, id);
    line = rmt_pi_response(e->payload, "answer", data != NULL, data, data ? NULL : "out of memory");
    rmt_response(st, d, e->key, line);
    free(line);
done:
    free(names);
    free(data);
    free(standing);
    free(id);
    free(value);
}

static void rmt_serve_tick(rmt_state *st) {
    long long now = rmt_mono_ms();
    for (int i = 0; i < RMT_SESSIONS; i++) {
        rmt_sess *s = &st->sess[i];
        if (!s->used) {
            continue;
        }
        /* A phone that did not start again after bye, or a session at the counters' end, is dropped. */
        int ignored_bye = s->bye_ms && now - s->bye_ms > (rmt_rekey_ms() < RMT_BYE_GRACE_MS ? rmt_rekey_ms() : RMT_BYE_GRACE_MS);
        int spent = s->t.send_n >= (1ull << 32) - 1024 || s->t.last >= (int64_t)((1ll << 32) - 1024);
        if ((!s->confirmed && now - s->started_ms > RMT_UNCONFIRMED_MS) || now - s->heard_ms > RMT_SILENT_MS || ignored_bye || spent) {
            if (st->devs[s->dev].sess == i) {
                st->devs[s->dev].sess = -1;
            }
            free(s->msg.buf);
            memset(s, 0, sizeof *s);
        } else if (s->confirmed && !s->bye_ms &&
                   (now - s->started_ms > rmt_rekey_ms() || s->t.send_n >= 0xfff00000u || s->t.last >= (int64_t)0xfff00000u)) {
            rmt_dev *d = &st->devs[s->dev];
            if (d->sess == i) {
                rmt_send_free(st, d, strdup("{\"type\":\"bye\",\"payload\":{\"reason\":\"rekey\"}}"));
                s->bye_ms = now; /* asked once */
            }
        }
    }
    for (int i = 0; i < st->ndevs; i++) {
        rmt_dev *d = &st->devs[i];
        if (!d->alive) {
            continue;
        }
        if (d->sess >= 0) {
            rmt_doing("reading the version of the journal followed for", d->d.name);
            if (d->f && (d->follow_now || rmt_data_version(st->js[d->jx]->s.db) != d->fversion)) {
                char what[160];
                (void)snprintf(what, sizeof what, "%s, from %s", d->d.name, st->js[d->jx]->path);
                rmt_doing("sending a conversation to", what);
                d->follow_now = 0;
                rmt_follow_pass(st, d);
            }
            if (d->want_list && !d->list_sent) { /* asked for now; looked at again each second */
                rmt_doing("checking the conversation list for", d->d.name);
                rmt_list_check(st, d);
            }
            rmt_doing("reading the reply as it streams for", d->d.name);
            rmt_live(st, d);
        }
        rmt_doing("looking at the commands of", d->d.name);
        rmt_commands_poll(st, d);
        rmt_doing("posting to the relay for", d->d.name);
        (void)rmt_lane_flush(&st->r, &d->lane);
    }
    for (int i = 0; i < st->njs; i++) {
        if (st->js[i]->open) {
            rmt_doing("looking for finished requests to notify in", st->js[i]->path);
            rmt_push_check(st, st->js[i]);
            rmt_wake_tick(st, st->js[i]);
            rmt_doing("looking for questions in", st->js[i]->path);
            rmt_ask_check(st, st->js[i]);
        }
    }
    rmt_doing("taking the push service's answers", NULL);
    rmt_push_results(st);
}

/* How pic remote was started: at a terminal, by /rc (the key on an inherited pipe), or by the
 * login agent (pic remote install), which must not fail where waiting or leaving is right: a
 * failure is started again. */
enum { RMT_TERMINAL, RMT_DETACHED, RMT_LOGIN };

/* ---- a newer pic installed over this one --------------------------------------------------- */

/* 1 when this pic remote should start again: pic remote restart asked, or the file it runs was
 * replaced and has then kept still for 2 s (an install is not caught halfway). */
static int rmt_exe_changed(void) {
    static long long checked_ms, new_ms;
    static char seen[128];
    const pic_platform *p = pic_platform_get();
    char now[128];
    long long t = rmt_mono_ms();
    if (rmt_restart_asked) {
        return 1;
    }
    if (!p->file_stamp || !rmt_exe[0] || !rmt_exe_stamp[0] || t - checked_ms < 500) {
        return 0;
    }
    checked_ms = t;
    if (p->file_stamp(rmt_exe, now, sizeof now) != 0 || strcmp(now, rmt_exe_stamp) == 0 || access(rmt_exe, X_OK) != 0) {
        seen[0] = '\0';
        return 0;
    }
    if (strcmp(now, seen) != 0) {
        (void)snprintf(seen, sizeof seen, "%s", now);
        new_ms = t;
        return 0;
    }
    {
        long long settle = 2000;
#ifdef PIC_FAULTS
        if (getenv("PIC_TEST_RC_SETTLE_MS")) { /* the tests' seam: a replaced file noticed and not acted on */
            settle = atoll(getenv("PIC_TEST_RC_SETTLE_MS"));
        }
#endif
        return t - new_ms >= settle;
    }
}

/* Nothing in hand that a restart would lose: no command waiting for its row or its child, no
 * record waiting to be posted, no message half received, no pairing open, no push on its way. */
static int rmt_quiet(rmt_state *st) {
    int busy;
    if (st->offer) {
        return 0;
    }
    for (int i = 0; i < st->ndevs; i++) {
        if (st->devs[i].alive && (st->devs[i].ncmds > 0 || st->devs[i].lane.qlen > 0)) {
            return 0;
        }
    }
    for (int i = 0; i < RMT_SESSIONS; i++) {
        if (st->sess[i].used && st->sess[i].msg.len > 0) {
            return 0;
        }
    }
    (void)pthread_mutex_lock(&st->push.mu);
    busy = st->push.ntodo > 0 || st->push.ndone > 0 || st->push.sending;
    (void)pthread_mutex_unlock(&st->push.mu);
    return !busy;
}

/* ---- a newer pic migrating a journal ------------------------------------------------------ */

/* Each second: a journal that a newer pic waits to migrate (pic_migration_wanted) is closed once
 * nothing under way needs it, the phones following one of its conversations told; one closed so is
 * opened again when no migration waits, or shown as a newer pic's once one has migrated it. */
static void rmt_yield_tick(rmt_state *st) {
    for (int i = 0; i < st->njs; i++) {
        rmt_journal *j = st->js[i];
        const char *base = strrchr(j->workspace, '/');
        base = base && base[1] ? base + 1 : j->workspace;
        if (j->open && pic_migration_wanted(&j->s) && rmt_quiet(st)) {
            for (int k = 0; k < st->ndevs; k++) {
                rmt_dev *d = &st->devs[k];
                if (d->alive && d->f && d->jx == i) {
                    rmt_error(st, d, NULL, "unavailable", "a newer pic is updating this workspace");
                    rmt_unfollow(d);
                }
            }
            pic_close(&j->s);
            j->open = 0;
            j->yielded = 1;
            (void)snprintf(j->why, sizeof j->why, "a newer pic is updating %s", base);
            rmt_log(stdout, "pic remote: let go of %s for a newer pic to update it\n", j->path);
            (void)fflush(stdout);
        } else if (!j->open && j->yielded) {
            long sv;
            if (rmt_serve_open(st, j, 1) == 0) {
                rmt_log(stdout, "pic remote: serving %s again\n", j->path);
                (void)fflush(stdout);
                continue;
            }
            if ((sv = rmt_journal_schema(j->path)) != atol(PIC_SCHEMA_VERSION)) {
                j->yielded = 0; /* not this pic's: a newer one's (a restart as it can read it), or still older */
                rmt_why(j, sv);
            }
        } else if (!j->open && j->older) { /* an older pic's: updated once nothing has it open */
            (void)rmt_update(st, j);
        }
    }
}

/* This process becomes the pic now at rmt_exe, keeping its pid (/rc's watch and the login agent see
 * one process throughout): a bye to each session (the phone starts a new one, as after any
 * restart; nothing else lives only in memory), then exec. The store's key goes on as /rc hands it
 * over; the login agent's opens the store itself. Returns only when exec failed. */
static void rmt_restart(rmt_state *st, int mode) {
    int keyfd = -1;
    for (int i = 0; i < st->ndevs; i++) {
        rmt_dev *d = &st->devs[i];
        if (d->alive && d->sess >= 0) {
            rmt_send_free(st, d, strdup("{\"type\":\"bye\",\"payload\":{\"reason\":\"restart\"}}"));
            d->lane.retry_ms = 0;
            (void)rmt_lane_flush(&st->r, &d->lane);
        }
    }
    rmt_status_write("restarting", st->r.base, 0, 0, 0, NULL);
    rmt_log(stdout, "pic remote: %s; starting %s\n", rmt_restart_asked ? "asked to restart" : "a newer pic was installed",
            rmt_exe);
    (void)fflush(stdout);
    (void)fflush(stderr);
    if (mode != RMT_LOGIN) {
        char num[16];
        if ((keyfd = pic_cred_handoff()) < 0) {
            rmt_log(stderr, "pic remote: cannot hand the store's key to the new pic; going on as this one\n");
            return;
        }
        (void)fcntl(keyfd, F_SETFD, 0);
        (void)snprintf(num, sizeof num, "%d", keyfd);
        (void)setenv("PIC_KEY_FD", num, 1);
    }
    execl(rmt_exe, rmt_exe, "remote", mode == RMT_LOGIN ? "--login" : "--detached", (char *)NULL);
    rmt_log(stderr, "pic remote: cannot start %s: %s; going on as this one\n", rmt_exe, strerror(errno));
    (void)unsetenv("PIC_KEY_FD");
    if (keyfd >= 0) {
        close(keyfd);
    }
}

/* What pic remote install and --login say of a store that asks for a passphrase. */
#define RMT_NEEDS_QUIET                                                                                                \
    "pic remote: the credential store asks for a passphrase, and no one is there to type it at login; move its key "  \
    "with pic auth rekey keychain (or pic auth rekey file), then run pic remote install\n"

static int rmt_serve(const pic_remote_options *o, int mode) {
    rmt_state st;
    rmt_stream str;
    char err[512];
    int lock, pfd[2], waiting = 0;
    long long last_list = 0, last_user = 0, last_yield = 0, tick_mono, tick_wall;
    long long ack_id = 0, ack_recs = 0, ack_bytes = 0, ack_since = 0, ack_try = 0;
    struct sigaction sa;
    memset(&st, 0, sizeof st);
    st.o = o;
    st.lockfd = -1;
#ifdef PIC_FAULTS
    if (getenv("PIC_TEST_RC_DEADLINE_S")) { /* the tests' seam: a pic remote a killed test left ends by itself */
        (void)alarm((unsigned)atoi(getenv("PIC_TEST_RC_DEADLINE_S"))); /* kept across a restart's exec */
    }
#endif
    if ((lock = rmt_lock()) < 0) {
        rmt_log(stderr, "%s",
                lock == -2 ? "pic remote: one is already running for this user\n" : "pic remote: cannot take ~/.pic/remote.lock\n");
        return lock == -2 && mode == RMT_LOGIN ? 0 : 1;
    }
    st.lockfd = lock;
    (void)fcntl(lock, F_SETFD, FD_CLOEXEC);
    {
        const pic_platform *p = pic_platform_get();
        rmt_started_ms = rmt_wall_ms();
        if (!p->self_path || p->self_path(rmt_exe, sizeof rmt_exe) != 0 || !p->file_stamp ||
            p->file_stamp(rmt_exe, rmt_exe_stamp, sizeof rmt_exe_stamp) != 0) {
            rmt_exe[0] = rmt_exe_stamp[0] = '\0';
        }
    }
    rmt_status_write("starting", NULL, 0, 0, 0, NULL);
    /* At the terminal the key comes from the store's source every time (a passphrase store asks).
     * Started by /rc (detached), the key is
     * the one the person at the terminal just unlocked, handed down on an inherited pipe. */
    memset(&sa, 0, sizeof sa);
    sa.sa_handler = rmt_on_signal;
    sigemptyset(&sa.sa_mask);
    (void)sigaction(SIGINT, &sa, NULL);
    (void)sigaction(SIGTERM, &sa, NULL);
    (void)sigaction(SIGUSR1, &sa, NULL);
    (void)signal(SIGPIPE, SIG_IGN);
    if (mode == RMT_LOGIN) { /* no one to ask: a store that needs a passphrase, or none yet, is not a failure */
        int q = pic_cred_state() == PIC_CRED_NEW ? 2 : pic_cred_quiet(err, sizeof err);
        if (q != 0) {
            if (q == 2) {
                rmt_log(stderr, "pic remote: the credential store has no key yet: pair a phone with /rc or pic remote pair\n");
            } else if (q == 1) {
                rmt_log(stderr, "%s", RMT_NEEDS_QUIET);
            } else {
                rmt_log(stderr, "pic remote: %s\n", err);
            }
            rmt_status_write("stopped", NULL, 0, 0, 0, q < 0 ? err : NULL);
            return q < 0 ? 1 : 0;
        }
    } else if ((mode == RMT_DETACHED ? pic_cred_unlock(err, sizeof err) : rmt_unlock_fresh(err, sizeof err)) != 0) {
        rmt_log(stderr, "pic remote: %s\n", err);
        rmt_status_write("stopped", NULL, 0, 0, 0, err);
        return 1;
    }
    for (;;) {
        int rc = rmt_keys_load(&st.k, 0, err, sizeof err);
        if (rc < 0 || (rc > 0 && mode != RMT_LOGIN)) {
            rmt_log(stderr, "pic remote: %s\n",
                    rc > 0 ? "no phone is paired: pair one with /rc in pic, or pic remote pair" : err);
            return 1;
        }
        if (rc == 0) {
            break;
        }
        if (!waiting) { /* started at login before the first pairing: it waits for one */
            rmt_log(stdout, "pic remote: no phone is paired yet; pair one with /rc in pic (waiting)\n");
            (void)fflush(stdout);
            rmt_status_write("waiting for a phone", NULL, 0, 0, 0, NULL);
            waiting = 1;
        }
        for (int t = 0; t < 10 && !rmt_stop; t++) {
            struct timespec ts = {0, 100000000L};
            (void)nanosleep(&ts, NULL);
        }
        if (rmt_stop) {
            rmt_status_write("stopped", NULL, 0, 0, 0, NULL);
            return 0;
        }
    }
    rmt_relay_init(&st.r, &st.k);
    /* the pusher's VAPID key and the token's sub, the relay's origin (section 5) */
    (void)pthread_mutex_init(&st.push.mu, NULL);
    (void)pthread_cond_init(&st.push.cv, NULL);
    memcpy(st.push.vapid.priv, st.k.vapid.priv, sizeof st.push.vapid.priv);
    if (pic_webpush_origin(st.r.base, st.push.subject, sizeof st.push.subject) < 0) {
        (void)snprintf(st.push.subject, sizeof st.push.subject, "%s", PIC_REMOTE_RELAY);
    }
    st.push.vapid.subject = st.push.subject;
    st.user_version = rmt_data_version(pic_userdb(NULL, 0));
    if (rmt_devices_sync(&st, 1) != 0) {
        rmt_log(stderr, "pic remote: cannot read the paired devices\n");
        return 1;
    }
    while (!rmt_stop) { /* with no device paired: say so, and wait for one */
        int alive = 0;
        for (int i = 0; i < st.ndevs; i++) {
            alive += st.devs[i].alive;
        }
        if (alive) {
            break;
        }
        if (!waiting) {
            rmt_log(stdout, "pic remote: no phone is paired yet; pair one with /rc in pic (waiting)\n");
            (void)fflush(stdout);
            rmt_status_write("waiting for a phone", st.r.base, 0, 0, 0, NULL);
            waiting = 1;
        }
        {
            struct timespec ts = {1, 0};
            (void)nanosleep(&ts, NULL);
        }
        (void)rmt_devices_sync(&st, 1);
    }
    if (rmt_stop) {
        return 0;
    }
    { /* the relay unreachable at the start is waited for, as a broken stream is; a refusal is not */
        long long wait = 1000;
        int tries = 0;
        while (!rmt_stop && rmt_reconcile(&st, err, sizeof err) != 0) {
            unsigned char j;
            long long w;
            if (st.r.last_status > 0) {
                rmt_log(stderr, "pic remote: %s\n", err);
                rmt_status_write("stopped", st.r.base, 0, 0, 0, err);
                return 1;
            }
            (void)pic_platform_get()->entropy(&j, 1);
            w = wait - wait / 5 + (long long)j * (2 * wait / 5) / 255;
            rmt_log(stderr, "pic remote: the relay %s is unreachable (%s); trying again in %lld s\n", st.r.base, err,
                    (w + 999) / 1000);
            rmt_status_write("reconnecting", st.r.base, 0, ++tries, rmt_wall_ms() + w, err);
            for (long long t = 0; t < w && !rmt_stop; t += 100) {
                struct timespec ts = {0, 100000000L};
                (void)nanosleep(&ts, NULL);
            }
            wait = wait * 2 > RMT_BACKOFF_MAX_MS ? RMT_BACKOFF_MAX_MS : wait * 2;
        }
        if (rmt_stop) {
            rmt_status_write("stopped", st.r.base, 0, 0, 0, NULL);
            return 0;
        }
    }
    rmt_journals_scan(&st);
    if (pipe(pfd) != 0) {
        rmt_log(stderr, "pic remote: %s\n", strerror(errno));
        return 1;
    }
    (void)fcntl(pfd[0], F_SETFL, O_NONBLOCK);
    (void)fcntl(pfd[0], F_SETFD, FD_CLOEXEC);
    (void)fcntl(pfd[1], F_SETFD, FD_CLOEXEC);
    memset(&str, 0, sizeof str);
    (void)snprintf(str.url, sizeof str.url, "%s/v1/m/%s/up", st.r.base, st.r.mbx);
    (void)snprintf(str.auth, sizeof str.auth, "%s", st.r.owner);
    str.mailbox = 1;
    st.pipe_w = pfd[1];
    if (rmt_stream_start(&str, pfd[1]) != 0) {
        rmt_log(stderr, "pic remote: cannot start the stream reader\n");
        return 1;
    }
    {
        int alive = 0;
        for (int i = 0; i < st.ndevs; i++) {
            alive += st.devs[i].alive;
        }
        rmt_log(stdout, "pic remote: connected to %s; %d device%s, %d workspace%s\n", st.r.base, alive, alive == 1 ? "" : "s",
                st.njs, st.njs == 1 ? "" : "s");
        (void)fflush(stdout);
    }
    tick_mono = rmt_mono_ms();
    tick_wall = rmt_wall_ms();
    {
        pthread_t wt;
        sigset_t all, was;
        atomic_store(&rmt_beat_ms, tick_mono);
        sigfillset(&all);
        pthread_sigmask(SIG_BLOCK, &all, &was); /* signals are the loop's */
        if (pthread_create(&wt, NULL, rmt_watch_main, NULL) == 0) {
            (void)pthread_detach(wt);
        }
        pthread_sigmask(SIG_SETMASK, &was, NULL);
    }
    while (!rmt_stop) {
        struct timeval tv = {0, 100000};
        fd_set rs;
        long long now = rmt_mono_ms(), wall = rmt_wall_ms();
        long long stuck;
        atomic_store(&rmt_beat_ms, now);
        stuck = atomic_exchange(&rmt_stuck_ms, 0);
        rmt_doing("starting a tick", NULL);
        if (stuck) {
            rmt_log(stdout, "pic remote: the loop is moving again after %lld s\n", (now - stuck) / 1000);
        }
#ifdef PIC_FAULTS
        while (getenv("PIC_TEST_RC_STALL_FILE") && access(getenv("PIC_TEST_RC_STALL_FILE"), F_OK) == 0) {
            struct timespec ts = {0, 50000000L}; /* the tests' seam: the loop held until the file goes */
            rmt_doing("held by", "PIC_TEST_RC_STALL_FILE");
            (void)nanosleep(&ts, NULL);
        }
#endif
        /* A wake from sleep or a SIGCONT: the tick came far too late, or the wall clock ran ahead
         * of the monotonic one (which stops in sleep on some systems). The stream may be a ghost
         * and every wait is stale: reconnect at once and post what waits. A stall the watchdog saw
         * was not a sleep, but leaves the same to do. */
        if (now - tick_mono > RMT_JUMP_MS || (wall - tick_wall) - (now - tick_mono) > RMT_JUMP_MS) {
            long long gap = (wall - tick_wall) > (now - tick_mono) ? wall - tick_wall : now - tick_mono;
            rmt_log(stdout, stuck ? "pic remote: back after %lld s (stalled); reconnecting\n"
                                  : "pic remote: back after %lld s (asleep or stopped); reconnecting\n",
                    gap / 1000);
            (void)fflush(stdout);
            atomic_store(&str.kick, 1);
            for (int i = 0; i < st.ndevs; i++) {
                rmt_lane_restamp(&st.devs[i].lane);
            }
        }
        tick_mono = now;
        tick_wall = wall;
        rmt_doing("writing the status file", NULL);
        rmt_status_tick(&st, &str, 0);
        FD_ZERO(&rs);
        FD_SET(pfd[0], &rs);
        rmt_doing("waiting on the stream pipe", NULL);
        if (select(pfd[0] + 1, &rs, NULL, NULL, &tv) > 0) {
            for (;;) {
                int kind, got;
                unsigned char ch[16], rec[PIC_NOISE_RECORD_CAP];
                size_t n;
                rmt_doing("reading the stream pipe", NULL);
                got = rmt_pipe_read(pfd[0], &kind, ch, rec, &n);
                if (got <= 0) {
                    if (got < 0) {
                        rmt_stop = 1;
                    }
                    break;
                }
                if (st.offer && memcmp(ch, st.offer->P, 16) == 0) {
                    rmt_doing("pairing a new phone", NULL);
                    rmt_offer_event(&st, kind, rec, n);
                } else if (kind == RMT_EV_FRAME) {
                    int di = rmt_dev_by_channel(&st, ch);
                    rmt_doing("reading a record from", di >= 0 ? st.devs[di].d.name : "the relay");
                    rmt_record(&st, ch, rec, n);
                } else if (memcmp(ch, str.channel, 16) != 0) {
                    /* an ended offer's stream, not yet gone */
                } else if (kind == RMT_EV_REPLACED) {
                    rmt_log(stderr, "pic remote: another connection took the relay's stream; stopping\n");
                    rmt_stop = 1;
                } else if (kind == RMT_EV_GONE || kind == RMT_EV_REFUSED) {
                    rmt_log(stderr, "pic remote: the relay no longer has this mailbox (it was reset); stopping\n");
                    rmt_stop = 1;
                }
            }
        }
        /* A phone on screen pings each minute. Keepalives on a stream that brings none of its
         * records say only that the connection is open, not that the relay still writes to it:
         * a new one resumes from Last-Event-ID. */
        if (atomic_load(&str.state) == RMT_CONN_CONNECTED && now - atomic_load(&str.heard_ms) > rmt_quiet_ms()) {
            for (int i = 0; i < st.ndevs; i++) {
                rmt_dev *d = &st.devs[i];
                if (d->alive && d->sess >= 0 && st.sess[d->sess].confirmed && d->visible) {
                    rmt_log(stdout, "pic remote: no record in %lld s while %s is open; reconnecting\n",
                            (now - atomic_load(&str.heard_ms)) / 1000, d->d.name);
                    atomic_store(&str.heard_ms, now);
                    atomic_store(&str.kick, 1);
                    break;
                }
            }
        }
        if (now - last_user >= 1000) { /* devices paired or unpaired meanwhile, new workspaces */
            long long v;
            rmt_doing("reading the user database's version", NULL);
            v = rmt_data_version(pic_userdb(NULL, 0));
            last_user = now;
            if (v != st.user_version) {
                st.user_version = v;
                rmt_doing("reading the paired devices and workspaces", NULL);
                (void)rmt_devices_sync(&st, 0);
                rmt_journals_scan(&st);
            }
        }
        if (now - last_list >= 1000) {
            last_list = now;
            for (int i = 0; i < st.ndevs; i++) {
                if (st.devs[i].alive && st.devs[i].want_list && st.devs[i].list_sent && st.devs[i].sess >= 0) {
                    rmt_doing("checking the conversation list for", st.devs[i].d.name);
                    rmt_list_check(&st, &st.devs[i]);
                }
            }
        }
        { /* Pic-Ack (section 6): what the stream read goes with every post, and on its own, with a
           * list request, when much waits or it has waited; the relay holds a lane's records until
           * then, and a full lane stalls a phone's large message */
            long long id = atomic_load(&str.read_id), recs = atomic_load(&str.read_records);
            long long bytes = atomic_load(&str.read_bytes);
            st.r.acked = 0;
            st.r.ack[0] = '\0';
            if (id > ack_id) {
                (void)snprintf(st.r.ack, sizeof st.r.ack, "%lld", id);
                ack_since = ack_since ? ack_since : now;
            }
            rmt_doing("serving the phones", NULL);
            rmt_serve_tick(&st);
            if (st.r.ack[0] && !st.r.acked && now - ack_try >= 1000 &&
                (recs - ack_recs >= RMT_ACK_RECORDS || bytes - ack_bytes >= RMT_ACK_BYTES || now - ack_since >= RMT_ACK_MS)) {
                char path[64];
                ack_try = now;
                rmt_doing("acknowledging the stream to the relay", NULL);
                (void)snprintf(path, sizeof path, "/v1/m/%s/c", st.r.mbx);
                (void)rmt_call(&st.r, "GET", path, st.r.owner, NULL, 0, NULL, NULL, err, sizeof err);
            }
            if (st.r.acked) {
                ack_id = id;
                ack_recs = recs;
                ack_bytes = bytes;
                ack_since = 0;
            }
            st.r.ack[0] = '\0';
        }
        rmt_doing("pairing a new phone", NULL);
        rmt_offer_tick(&st);
        if (now - last_yield >= 1000) {
            last_yield = now;
            rmt_doing("checking for journals to let go", NULL);
            rmt_yield_tick(&st);
        }
        rmt_doing("checking for a newer pic", NULL);
        if (!rmt_stop && rmt_exe_changed() && rmt_quiet(&st)) {
            const pic_platform *p = pic_platform_get();
            rmt_doing("starting the newer pic", NULL);
            rmt_restart(&st, mode); /* back only when it failed: not tried again for this file */
            rmt_restart_asked = 0;
            (void)p->file_stamp(rmt_exe, rmt_exe_stamp, sizeof rmt_exe_stamp);
        }
    }
    if (st.offer) { /* stopped with an offer open: the new device hears no, the channel goes */
        rmt_offer_refuse(st.offer, &st.r);
        st.offer->lane.retry_ms = 0;
        (void)rmt_lane_flush(&st.r, &st.offer->lane);
        rmt_offer_close(&st);
    }
    for (int i = 0; i < st.ndevs; i++) { /* SIGINT, SIGTERM: bye to each session */
        rmt_dev *d = &st.devs[i];
        if (d->alive && d->sess >= 0) {
            rmt_send_free(&st, d, strdup("{\"type\":\"bye\",\"payload\":{\"reason\":\"stopped\"}}"));
            d->lane.retry_ms = 0;
            (void)rmt_lane_flush(&st.r, &d->lane);
        }
    }
    rmt_status_write("stopped", st.r.base, 0, 0, 0, NULL);
    puts("pic remote: stopped");
    (void)fflush(stdout);
    _exit(0); /* the stream thread may be in a read; the kernel drops the lock */
}

/* ---- pairing (section 2) ----------------------------------------------------------------------- */

typedef struct {
    int pipe_mode; /* --pipe: JSON lines out, y or n on stdin */
} rmt_pair_opts;

static void rmt_say(int pipe_mode, const char *type, const char *k1, const char *v1, const char *k2, const char *v2) {
    if (pipe_mode) {
        char *line = rmt_q("SELECT json_patch('{}', json_object('type', ?1, ?2, ?3, ?4, ?5))", 5, type, k1 ? k1 : "x", v1,
                           k2 ? k2 : "y", v2);
        if (line) {
            puts(line);
        }
        free(line);
        (void)fflush(stdout);
    }
}

/* The last word (paired, or a refusal) is posted, and the pairing channel is deleted only once the
 * phone has it: deleting the channel drops what the relay holds, so a phone that was reconnecting
 * when the word was posted would lose it. A post answered Pic-Peer: 1 went to a phone reading the
 * lane; after Pic-Peer: 0 it waits for the relay's peer event that the phone is back (the relay
 * sends it what it holds as it reconnects), at most RMT_LAST_WORD_MS; with no Pic-Peer at all,
 * RMT_NO_PEER_MS. */
static void rmt_pair_last_word(rmt_relay *r, rmt_lane *lane, int fd, int said) {
    long long until = rmt_mono_ms() + RMT_LAST_WORD_MS;
    int reading = -1, posted = 0;
    if (!said) {
        return; /* nothing to say: no handshake was made */
    }
    if (!lane->qlen) { /* posted already: the post's answer says whether the phone read it */
        posted = 1;
        reading = r->peer;
        if (reading < 0) {
            until = rmt_mono_ms() + RMT_NO_PEER_MS;
        }
    }
    while (rmt_mono_ms() < until) {
        struct timeval tv = {0, 100000};
        fd_set rs;
        if (lane->qlen) {
            lane->retry_ms = 0;
            (void)rmt_lane_flush(r, lane);
            if (!lane->qlen) {
                posted = 1;
                reading = r->peer;

                if (reading < 0) {
                    until = rmt_mono_ms() + RMT_NO_PEER_MS;
                }
            }
        }
        if (posted && reading == 1) {
            return;
        }
        FD_ZERO(&rs);
        FD_SET(fd, &rs);
        if (select(fd + 1, &rs, NULL, NULL, &tv) > 0) {
            int kind, got;
            unsigned char ch[16], rec[PIC_NOISE_RECORD_CAP];
            size_t n;
            while ((got = rmt_pipe_read(fd, &kind, ch, rec, &n)) == 1) {
                if (kind == RMT_EV_PEER && n == 1 && posted && rec[0] == 1) {
                    return; /* the phone is back, and has been sent what the relay held */
                }
                if (kind == RMT_EV_GONE || kind == RMT_EV_REFUSED) {
                    return;
                }
            }
            if (got < 0) {
                return;
            }
        }
    }
}

/* A yes or no from the terminal: one key, y pairs and anything else does not. --pipe reads a line. */
static int rmt_pair_answer(int pipe_mode) {
    char line[64];
    struct termios was, raw;
    int tty = !pipe_mode && isatty(STDIN_FILENO) && tcgetattr(STDIN_FILENO, &was) == 0;
    ssize_t n;
    if (tty) {
        raw = was;
        raw.c_lflag &= (tcflag_t) ~(ICANON | ECHO);
        raw.c_cc[VMIN] = 1;
        raw.c_cc[VTIME] = 0;
        (void)tcsetattr(STDIN_FILENO, TCSANOW, &raw);
    }
    n = read(STDIN_FILENO, line, tty ? 1 : sizeof line - 1);
    if (tty) {
        (void)tcsetattr(STDIN_FILENO, TCSANOW, &was);
        printf("%c\n", n > 0 && (line[0] == 'y' || line[0] == 'Y') ? 'y' : 'n');
    }
    return n > 0 && (line[0] == 'y' || line[0] == 'Y');
}

static int rmt_pair(const pic_remote_options *o, int pipe_mode) {
    rmt_keys k;
    rmt_relay r;
    rmt_stream str;
    rmt_offer of;
    char err[512], tok[64];
    long long expires;
    int pfd[2], rc = 1, ttl, over = 0;
    if (pic_cred_prepare(err, sizeof err) != 0 || rmt_keys_load(&k, 1, err, sizeof err) != 0) {
        rmt_say(pipe_mode, "error", "message", err, NULL, NULL);
        fprintf(stderr, "pic remote: %s\n", err);
        return 1;
    }
    {
        struct sigaction sa;
        memset(&sa, 0, sizeof sa);
        sa.sa_handler = rmt_on_signal; /* /rc closed, or Ctrl-C: the offer ends with a refusal */
        sigemptyset(&sa.sa_mask);
        (void)sigaction(SIGINT, &sa, NULL);
        (void)sigaction(SIGTERM, &sa, NULL);
    }
    (void)signal(SIGPIPE, SIG_IGN);
    rmt_relay_init(&r, &k);
    if (rmt_put_mailbox(&r, err, sizeof err) != 0) {
        rmt_say(pipe_mode, "error", "message", err, NULL, NULL);
        fprintf(stderr, "pic remote: %s\n", err);
        return 1;
    }
    ttl = RMT_PAIR_TTL;
#ifdef PIC_FAULTS
    if (getenv("PIC_TEST_PAIR_TTL")) { /* the tests' seam: an offer that ends in seconds */
        ttl = atoi(getenv("PIC_TEST_PAIR_TTL"));
    }
#endif
    if (rmt_offer_open(&of, &r, &k, ttl, err, sizeof err) != 0) {
        rmt_say(pipe_mode, "error", "message", err, NULL, NULL);
        fprintf(stderr, "pic remote: %s\n", err);
        return 1;
    }
    expires = of.expires;
    if (pipe(pfd) != 0) {
        return 1;
    }
    (void)fcntl(pfd[0], F_SETFL, O_NONBLOCK);
    memset(&str, 0, sizeof str);
    pic_b64u_enc(of.P, 16, tok);
    (void)snprintf(str.url, sizeof str.url, "%s/v1/m/%s/c/%s/up", r.base, r.mbx, tok);
    (void)snprintf(str.auth, sizeof str.auth, "%s", r.owner);
    memcpy(str.channel, of.P, 16);
    if (rmt_stream_start(&str, pfd[1]) != 0) {
        return 1;
    }
    {
        char exp[32];
        (void)snprintf(exp, sizeof exp, "%lld", expires);
        rmt_say(pipe_mode, "offer", "url", of.url, "expires", exp);
    }
    if (!pipe_mode) {
        puts("Scan this with your phone's camera to pair it with this computer (it works once, for ten minutes):");
        if (o->show_qr) {
            o->show_qr(of.url);
        }
        printf("%s\n", of.url);
        puts("Once a phone is paired, it can add your other devices: Add a device, in its menu.");
        (void)fflush(stdout);
    }
    while (!over && !rmt_stop) {
        struct timeval tv = {0, 100000};
        fd_set rs;
        int maxfd = pfd[0];
        FD_ZERO(&rs);
        FD_SET(pfd[0], &rs);
        if (of.stage == OFFER_ASKING) {
            FD_SET(STDIN_FILENO, &rs);
            maxfd = maxfd > STDIN_FILENO ? maxfd : STDIN_FILENO;
        }
        if (rmt_mono_ms() > of.mono_end) {
            rmt_say(pipe_mode, "expired", NULL, NULL, NULL, NULL);
            if (!pipe_mode) {
                puts("The pairing offer expired.");
            }
            break;
        }
        if (select(maxfd + 1, &rs, NULL, NULL, &tv) > 0) {
            if (of.stage == OFFER_ASKING && FD_ISSET(STDIN_FILENO, &rs)) {
                if (rmt_pair_answer(pipe_mode)) {
                    if (rmt_offer_accept(&of, &r, err, sizeof err) != 0) {
                        rmt_say(pipe_mode, "error", "message", err, NULL, NULL);
                        fprintf(stderr, "pic remote: %s\n", err);
                    } else {
                        rmt_say(pipe_mode, "paired", "name", of.d.name, NULL, NULL);
                        if (!pipe_mode) {
                            printf(rmt_running_now() == 1 ? "Paired %s. pic remote is running: the phone reaches this computer now.\n"
                                                          : "Paired %s. Run pic remote (or pic remote install) to reach this computer from it.\n",
                                   of.d.name);
                        }
                        rc = 0;
                    }
                } else {
                    rmt_offer_refuse(&of, &r);
                    rmt_say(pipe_mode, "refused", NULL, NULL, NULL, NULL);
                    if (!pipe_mode) {
                        puts("Not paired.");
                    }
                    rc = 2;
                }
                over = 1;
                continue;
            }
            for (;;) {
                int kind, got, ev;
                unsigned char ch[16], rec[PIC_NOISE_RECORD_CAP];
                size_t n;
                got = rmt_pipe_read(pfd[0], &kind, ch, rec, &n);
                if (got <= 0) {
                    break;
                }
                if (kind == RMT_EV_PEER) {
                    continue;
                }
                if (kind != RMT_EV_FRAME) {
                    rmt_say(pipe_mode, "error", "message", "the relay ended the pairing offer", NULL, NULL);
                    over = 1;
                    break;
                }
                ev = rmt_offer_frame(&of, &r, &k, rec, n);
                if (ev == OFFER_EV_FAILED) {
                    rmt_say(pipe_mode, "error", "message", "too many pairing attempts failed; the offer ended", NULL, NULL);
                    if (!pipe_mode) {
                        puts("Too many pairing attempts failed; the offer ended.");
                    }
                    over = 1;
                    break;
                }
                if (ev == OFFER_EV_ASK) {
                    char shown[8];
                    (void)snprintf(shown, sizeof shown, "%.3s %.3s", of.sas, of.sas + 3);
                    rmt_say(pipe_mode, "code", "name", of.d.name, "code", shown);
                    if (!pipe_mode) {
                        if (isatty(STDIN_FILENO)) { /* a key pressed before the question is not its answer */
                            (void)tcflush(STDIN_FILENO, TCIFLUSH);
                        }
                        printf("Pair \"%s\"? It should show %s. y pairs, any other key does not. ", of.d.name, shown);
                        (void)fflush(stdout);
                    }
                }
            }
        }
        (void)rmt_lane_flush(&r, &of.lane);
    }
    if (rmt_stop && !over) {
        rmt_say(pipe_mode, "cancelled", NULL, NULL, NULL, NULL);
    }
    rmt_offer_refuse(&of, &r); /* expired or failed after a handshake: the phone hears no */
    rmt_pair_last_word(&r, &of.lane, pfd[0], of.said);
    rmt_delete_channel(&r, of.P);
    rmt_offer_free(&of);
    (void)fflush(stdout);
    _exit(rc == 0 ? 0 : 1);
}

/* ---- the other subcommands ----------------------------------------------------------------------- */

static void rmt_when(long long ms, char *out, size_t cap) {
    time_t t = (time_t)(ms / 1000);
    struct tm tm;
    if (!ms) {
        (void)snprintf(out, cap, "never");
        return;
    }
    (void)localtime_r(&t, &tm);
    (void)strftime(out, cap, "%Y-%m-%d %H:%M", &tm);
}

static int rmt_devices(int json) {
    rmt_device *list = NULL;
    int n = 0, bad = 0, running = rmt_running_now();
    char err[256];
    if (pic_cred_state() == PIC_CRED_NEW) {
        if (json) {
            printf("{\"type\":\"devices\",\"running\":%s,\"devices\":[]}\n", running == 1 ? "true" : "false");
        } else {
            puts("No phone is paired.");
        }
        return 0;
    }
    if (pic_cred_unlock(err, sizeof err) != 0 || rmt_devices_load(&list, &n, &bad, err, sizeof err) != 0) {
        fprintf(stderr, "pic remote: %s\n", err);
        return 1;
    }
    if (json) {
        rmt_buf b = {NULL, 0, 0};
        char *out;
        (void)rmt_buf_add(&b, "[", 1);
        for (int i = 0; i < n; i++) {
            char hex[33], idb[32], paired[32], seen[32], *one;
            rmt_hex(list[i].id, 16, hex);
            pic_b64u_enc(list[i].id, 16, idb);
            (void)snprintf(paired, sizeof paired, "%lld", list[i].paired_ms);
            (void)snprintf(seen, sizeof seen, "%lld", list[i].seen_ms);
            one = rmt_q("SELECT json_object('id', ?1, 'name', ?2, 'pairedMs', CAST(?3 AS INTEGER), 'seenMs', CAST(?4 AS INTEGER),"
                        " 'origin', 'remote:' || ?5, 'notify', nullif(?6, ''))",
                        6, hex, list[i].name, paired, seen, idb, list[i].notify);
            if (one) {
                if (b.len > 1) {
                    (void)rmt_buf_add(&b, ",", 1);
                }
                (void)rmt_buf_add(&b, one, strlen(one));
            }
            free(one);
        }
        (void)rmt_buf_add(&b, "]", 1);
        out = rmt_q("SELECT json_object('type', 'devices', 'running', json(?1), 'devices', json(?2))", 2,
                    running == 1 ? "true" : "false", b.buf);
        puts(out ? out : "{}");
        free(out);
        free(b.buf);
    } else {
        printf("pic remote is %s\n", running == 1 ? "running" : "not running");
        if (!n) {
            puts("No phone is paired.");
        }
        for (int i = 0; i < n; i++) {
            char hex[33], paired[32], seen[32];
            rmt_hex(list[i].id, 16, hex);
            rmt_when(list[i].paired_ms, paired, sizeof paired);
            rmt_when(list[i].seen_ms, seen, sizeof seen);
            printf("%.8s  %-24s paired %s, last seen %s%s\n", hex, list[i].name, paired, seen,
                   !list[i].notify[0] ? "" : strcmp(list[i].notify, "remote") == 0 ? ", notifies for the phone's requests" : ", notifies");
        }
    }
    free(list);
    return 0;
}

/* Deletes the device whose id (hex) starts with PREFIX, in one transaction, asking nothing. */
static int rmt_unpair_cmd(const char *prefix) {
    sqlite3 *db = pic_userdb(NULL, 0);
    sqlite3_stmt *q = NULL;
    int count = -1;
    if (db && strcmp(prefix, "--all") == 0) { /* every device, keeping the keys and the mailbox (reset deletes those) */
        if (sqlite3_exec(db, "DELETE FROM picu_remote_device", NULL, NULL, NULL) != SQLITE_OK) {
            fprintf(stderr, "pic remote: %s\n", sqlite3_errmsg(db));
            return 1;
        }
        count = sqlite3_changes(db);
        printf("unpaired %d device%s\n", count, count == 1 ? "" : "s");
        return 0;
    }
    if (!db || strlen(prefix) < 4 || strspn(prefix, "0123456789abcdefABCDEF") != strlen(prefix)) {
        fputs("pic remote: unpair takes a device's id, at least its first 4 characters (pic remote devices)\n", stderr);
        return 2;
    }
    if (sqlite3_exec(db, "BEGIN IMMEDIATE", NULL, NULL, NULL) != SQLITE_OK) {
        fprintf(stderr, "pic remote: %s\n", sqlite3_errmsg(db));
        return 1;
    }
    if (sqlite3_prepare_v2(db, "SELECT count(*) FROM picu_remote_device WHERE lower(hex(id)) LIKE lower(?1) || '%'", -1, &q, NULL) ==
        SQLITE_OK) {
        sqlite3_bind_text(q, 1, prefix, -1, SQLITE_STATIC);
        count = sqlite3_step(q) == SQLITE_ROW ? sqlite3_column_int(q, 0) : -1;
    }
    sqlite3_finalize(q);
    if (count == 1 && sqlite3_prepare_v2(db, "DELETE FROM picu_remote_device WHERE lower(hex(id)) LIKE lower(?1) || '%'", -1, &q,
                                         NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, prefix, -1, SQLITE_STATIC);
        count = sqlite3_step(q) == SQLITE_DONE ? 1 : -1;
        sqlite3_finalize(q);
    }
    (void)sqlite3_exec(db, count == 1 ? "COMMIT" : "ROLLBACK", NULL, NULL, NULL);
    if (count != 1) {
        fprintf(stderr, count == 0 ? "pic remote: no paired device has an id starting %s\n"
                                   : "pic remote: more than one device has an id starting %s; give more of it\n",
                prefix);
        return 1;
    }
    puts("unpaired");
    return 0;
}

static int rmt_stop_cmd(void);

/* Every device row and all three keys, and the mailbox at the relay. A running pic remote is
 * stopped first: it would go on serving keys that are gone. Before that the rows go, which it
 * reads each second as unpair at the terminal: it tells each connected phone it was unpaired, so
 * the phone does not take the mailbox's deletion for the relay losing its pairing. */
static int rmt_reset(void) {
    sqlite3 *db = pic_userdb(NULL, 0);
    rmt_keys k;
    char err[256];
    int have = 0;
    if (!db) {
        return 1;
    }
    if (rmt_running_now() == 1) {
        if (pic_remote_phones() > 0 && sqlite3_exec(db, "DELETE FROM picu_remote_device", NULL, NULL, NULL) == SQLITE_OK) {
            struct timespec ts = {1, 500000000L}; /* its check each second, and the message out */
            (void)nanosleep(&ts, NULL);
        }
        if (rmt_stop_cmd() != 0) {
            return 1;
        }
    }
    if (pic_cred_state() != PIC_CRED_NEW && pic_cred_unlock(err, sizeof err) == 0 && rmt_keys_load(&k, 0, err, sizeof err) == 0) {
        rmt_relay r;
        char path[128];
        rmt_relay_init(&r, &k);
        (void)snprintf(path, sizeof path, "/v1/m/%s", r.mbx);
        if (rmt_call(&r, "DELETE", path, r.owner, NULL, 0, NULL, NULL, err, sizeof err) < 0) {
            fprintf(stderr, "pic remote: the relay's mailbox was not deleted (%s); it goes after 90 days unused\n", err);
        }
        have = 1;
    }
    if (sqlite3_exec(db, "BEGIN IMMEDIATE; DELETE FROM picu_remote_device; DELETE FROM picu_remote_key; COMMIT", NULL, NULL, NULL) !=
        SQLITE_OK) {
        fprintf(stderr, "pic remote: %s\n", sqlite3_errmsg(db));
        (void)sqlite3_exec(db, "ROLLBACK", NULL, NULL, NULL);
        return 1;
    }
    puts(have ? "reset: every phone unpaired, the keys and the mailbox deleted" : "reset: every phone unpaired, the keys deleted");
    return 0;
}

/* The login agent's mechanism into KIND ("" when none is installed or the platform has none). */
static void rmt_agent_kind(char *kind, size_t cap) {
    const pic_platform *p = pic_platform_get();
    pic_login_agent ag;
    char err[256];
    memset(&ag, 0, sizeof ag);
    kind[0] = '\0';
    if (p->login_agent && p->login_agent(PIC_AGENT_STATE, &ag, err, sizeof err) == 1) {
        (void)snprintf(kind, cap, "%s", ag.kind);
    }
}

/* Whether the running pic remote, by what its status file says, runs an older pic than the one now
 * at its path: 1, or 0 when it is the same or cannot be told. A status without a stamp was written
 * by a pic from before stamps, older than any that has them. */
static int rmt_status_stale(const char *st) {
    const pic_platform *p = pic_platform_get();
    char *exe = st ? rmt_q("SELECT json_extract(?1, '$.exe')", 1, st) : NULL;
    char *stamp = st ? rmt_q("SELECT json_extract(?1, '$.exeStamp')", 1, st) : NULL;
    char now[128];
    int stale = 0;
    if (st && !stamp) {
        char *v = rmt_q("SELECT json_valid(?1) AND json_type(?1, '$.exeStamp') IS NULL", 1, st);
        stale = v && strcmp(v, "1") == 0;
        free(v);
        free(exe);
        return stale;
    }
    if (exe && *exe && stamp && *stamp && p->file_stamp && p->file_stamp(exe, now, sizeof now) == 0) {
        stale = strcmp(now, stamp) != 0;
    }
    free(exe);
    free(stamp);
    return stale;
}

/* pic remote status [--json]: whether one runs (its lock), and what it last wrote of itself. */
static int rmt_status_cmd(int json) {
    int running = rmt_running_now(), devices = rmt_device_count();
    char *st = running == 1 ? rmt_status_read() : NULL;
    char *state = st ? rmt_q("SELECT json_extract(?1, '$.state')", 1, st) : NULL;
    char *relay = st ? rmt_q("SELECT json_extract(?1, '$.relay')", 1, st) : NULL;
    char *why = st ? rmt_q("SELECT json_extract(?1, '$.error')", 1, st) : NULL;
    char *pid = st ? rmt_q("SELECT json_extract(?1, '$.pid')", 1, st) : NULL;
    char *retry = st ? rmt_q("SELECT json_extract(?1, '$.retryAtMs')", 1, st) : NULL;
    char *att = st ? rmt_q("SELECT json_extract(?1, '$.attempts')", 1, st) : NULL;
    char *phones = st ? rmt_q("SELECT json_extract(?1, '$.phones')", 1, st) : NULL;
    char *updated = st ? rmt_q("SELECT json_extract(?1, '$.updatedMs')", 1, st) : NULL;
    long long in_ms = retry && atoll(retry) > 0 ? atoll(retry) - rmt_wall_ms() : 0;
    /* Connected, its loop writes this file at least every 5 s: older than that and a stall is a
     * loop that is stuck, whatever it last said. */
    long long still_ms = updated ? rmt_wall_ms() - atoll(updated) : 0;
    if (state && strcmp(state, "connected") == 0 && still_ms > rmt_stall_ms() + 5000) {
        free(state);
        state = strdup("stalled");
    }
    if (in_ms < 0) {
        in_ms = 0;
    }
    char agent[16];
    int stale = running == 1 && rmt_status_stale(st);
    rmt_agent_kind(agent, sizeof agent);
    if (running == 1 && (!state || !*state)) {
        free(state);
        state = strdup("starting");
    }
    if (json) {
        char devs[16], ms[24];
        char *out;
        (void)snprintf(devs, sizeof devs, "%d", devices);
        (void)snprintf(ms, sizeof ms, "%lld", in_ms);
        out = rmt_q("SELECT json_object('type', 'status', 'running', json(?1), 'pid', CAST(?2 AS INTEGER), 'state', ?3,"
                    " 'relay', ?4, 'devices', CAST(?5 AS INTEGER), 'attempts', CAST(?6 AS INTEGER), 'retryInMs', CAST(?7 AS INTEGER),"
                    " 'error', ?8, 'loginAgent', ?9, 'phones', json(coalesce(?10, '[]')), 'stale', json(?11))",
                    11, running == 1 ? "true" : "false", pid, running == 1 ? state : "off", relay, devs, att ? att : "0", ms,
                    why ? why : "", agent, phones, stale ? "true" : "false");
        puts(out ? out : "{}");
        free(out);
    } else if (running != 1) {
        printf("pic remote is not running; %d phone%s paired\n", devices, devices == 1 ? "" : "s");
    } else if (state && strcmp(state, "stalled") == 0) {
        printf("pic remote is running (pid %s): stalled for %lld s, not answering phones (~/.pic/remote.log says where); %d "
               "phone%s paired\n",
               pid ? pid : "?", still_ms / 1000, devices, devices == 1 ? "" : "s");
    } else if (state && strcmp(state, "reconnecting") == 0) {
        printf("pic remote is running (pid %s): reconnecting to %s (attempt %s, next try in %lld s)%s%s; %d phone%s paired\n",
               pid ? pid : "?", relay ? relay : "the relay", att ? att : "?", (in_ms + 999) / 1000, why && *why ? ": " : "",
               why ? why : "", devices, devices == 1 ? "" : "s");
    } else {
        printf("pic remote is running (pid %s): %s%s%s; %d phone%s paired\n", pid ? pid : "?", state ? state : "starting",
               relay && *relay ? " to " : "", relay ? relay : "", devices, devices == 1 ? "" : "s");
    }
    if (!json && stale) {
        puts("It runs an older pic than the one installed now: pic remote restart starts the new one.");
    }
    if (!json && agent[0]) {
        printf("It starts at login (%s).\n", agent);
    } else if (!json && pic_platform_get()->login_agent) {
        puts("It does not start at login: pic remote install sets that up.");
    }
    free(st);
    free(state);
    free(relay);
    free(why);
    free(pid);
    free(retry);
    free(att);
    free(phones);
    free(updated);
    return 0;
}

/* pic remote stop: SIGTERM to the running one (its pid from the status file, while it holds the
 * lock), then wait up to 10 s for the lock to go. */
static int rmt_stop_cmd(void) {
    char *st, *pid;
    long p;
    if (rmt_running_now() != 1) {
        puts("pic remote is not running");
        return 0;
    }
    st = rmt_status_read();
    pid = st ? rmt_q("SELECT json_extract(?1, '$.pid')", 1, st) : NULL;
    p = pid ? atol(pid) : 0;
    free(st);
    free(pid);
    if (p <= 1 || kill((pid_t)p, SIGTERM) != 0) {
        fputs("pic remote: cannot tell which process is pic remote (no ~/.pic/remote.status)\n", stderr);
        return 1;
    }
    for (int i = 0; i < 200 && rmt_running_now() == 1; i++) {
        struct timespec ts = {0, 50000000L};
        (void)nanosleep(&ts, NULL);
    }
    if (rmt_running_now() == 1) {
        fputs("pic remote: it did not stop within 10 s\n", stderr);
        return 1;
    }
    puts("pic remote: stopped");
    return 0;
}

/* pic remote restart: the running one starts again as the pic now installed (SIGUSR1), at its next
 * quiet moment; waits up to 30 s for the new one's first word. One from before restarts were
 * possible is only told how. */
static int rmt_restart_cmd(void) {
    char *st, *pid, *was, *v;
    long p;
    int done = 0;
    if (rmt_running_now() != 1) {
        puts("pic remote is not running");
        return 1;
    }
    st = rmt_status_read();
    pid = st ? rmt_q("SELECT json_extract(?1, '$.pid')", 1, st) : NULL;
    was = st ? rmt_q("SELECT json_extract(?1, '$.startedMs')", 1, st) : NULL;
    p = pid ? atol(pid) : 0;
    free(st);
    free(pid);
    if (!was) {
        fputs("pic remote: the one running is too old to restart itself: pic remote stop, then turn it on again with /rc "
              "(s) or pic remote\n",
              stderr);
        return 1;
    }
    if (p <= 1 || kill((pid_t)p, SIGUSR1) != 0) {
        free(was);
        fputs("pic remote: cannot tell which process is pic remote (no ~/.pic/remote.status)\n", stderr);
        return 1;
    }
    for (int i = 0; i < 600 && !done; i++) {
        struct timespec ts = {0, 50000000L};
        (void)nanosleep(&ts, NULL);
        st = rmt_status_read();
        v = st ? rmt_q("SELECT json_extract(?1, '$.startedMs')", 1, st) : NULL;
        done = v && strcmp(v, was) != 0;
        free(v);
        free(st);
    }
    free(was);
    if (!done) {
        fputs("pic remote: it has not restarted within 30 s (it waits for what it is doing to finish)\n", stderr);
        return 1;
    }
    puts("pic remote: restarted");
    return 0;
}

/* pic remote install: the platform's login agent runs pic remote --login, which needs the store
 * to open with no one there. */
static int rmt_install(const pic_remote_options *o) {
    const pic_platform *p = pic_platform_get();
    const char *home = getenv("HOME");
    pic_login_agent ag;
    char err[512], log[PATH_MAX];
    int rc, running;
    memset(&ag, 0, sizeof ag);
    if (!p->login_agent) {
        fputs("pic remote: this build of pic has no way to start a program at login\n", stderr);
        return 1;
    }
    if (!o->self || o->self[0] != '/' || !home) {
        fputs("pic remote: cannot tell where this pic is, or HOME is not set\n", stderr);
        return 1;
    }
    if (pic_cred_state() == PIC_CRED_NEW) {
        fputs("pic remote: the credential store has no key yet: pair a phone with /rc or pic remote pair first\n", stderr);
        return 1;
    }
    rc = pic_cred_quiet(err, sizeof err);
    if (rc == 1 || (rc == 0 && strcmp(pic_cred_source_name(), "passphrase") == 0)) {
        fputs(RMT_NEEDS_QUIET, stderr);
        return 1;
    }
    if (rc != 0) {
        fprintf(stderr, "pic remote: %s\n", err);
        return 1;
    }
    (void)snprintf(log, sizeof log, "%s/.pic/remote.log", home);
    {
        const char *args[] = {o->self, "remote", "--login", NULL};
        ag.argv = args;
        ag.log = log;
        running = rmt_running_now() == 1;
        if (p->login_agent(PIC_AGENT_INSTALL, &ag, err, sizeof err) != 1) {
            fprintf(stderr, "pic remote: %s\n", err);
            return 1;
        }
    }
    if (strcmp(ag.kind, "cron") == 0) {
        printf("pic remote now starts whenever this computer starts (cron @reboot, in your crontab)%s\n",
               running ? "; it is running now" : "; run pic remote to start it now");
    } else {
        printf("pic remote now starts whenever you log in (%s: %s)%s\n", ag.kind, ag.where,
               running ? "; it is running now"
               : ag.started ? ", and it is starting now"
                            : "; it starts at your next login");
    }
    printf("Its messages go to %s. pic remote uninstall undoes this.\n", log);
    return 0;
}

static int rmt_uninstall(void) {
    const pic_platform *p = pic_platform_get();
    pic_login_agent ag;
    char err[512];
    int rc;
    memset(&ag, 0, sizeof ag);
    if (!p->login_agent) {
        puts("pic remote was not set to start at login");
        return 0;
    }
    rc = p->login_agent(PIC_AGENT_REMOVE, &ag, err, sizeof err);
    if (rc < 0) {
        fprintf(stderr, "pic remote: %s\n", err);
        return 1;
    }
    if (rc == 0) {
        puts("pic remote was not set to start at login");
    } else {
        printf("pic remote no longer starts at login (%s: %s removed)\n", ag.kind, ag.where);
    }
    return 0;
}

int pic_remote_main(const pic_remote_options *o, int argc, char **argv) {
    if (argc == 0) {
        return rmt_serve(o, RMT_TERMINAL);
    }
    if (argc == 1 && strcmp(argv[0], "--detached") == 0) { /* /rc's: the key on an inherited pipe */
        return rmt_serve(o, RMT_DETACHED);
    }
    if (argc == 1 && strcmp(argv[0], "--login") == 0) { /* the login agent's */
        return rmt_serve(o, RMT_LOGIN);
    }
    if (strcmp(argv[0], "install") == 0 && argc == 1) {
        return rmt_install(o);
    }
    if (strcmp(argv[0], "uninstall") == 0 && argc == 1) {
        return rmt_uninstall();
    }
    if (strcmp(argv[0], "status") == 0 && (argc == 1 || (argc == 2 && strcmp(argv[1], "--json") == 0))) {
        return rmt_status_cmd(argc == 2);
    }
    if (strcmp(argv[0], "stop") == 0 && argc == 1) {
        return rmt_stop_cmd();
    }
    if (strcmp(argv[0], "restart") == 0 && argc == 1) {
        return rmt_restart_cmd();
    }
    if (strcmp(argv[0], "pair") == 0 && (argc == 1 || (argc == 2 && strcmp(argv[1], "--pipe") == 0))) {
        if (argc == 1 && !isatty(STDIN_FILENO)) {
            fputs("pic remote: pair asks for a yes on the terminal\n", stderr);
            return 2;
        }
        return rmt_pair(o, argc == 2);
    }
    if (strcmp(argv[0], "devices") == 0 && (argc == 1 || (argc == 2 && strcmp(argv[1], "--json") == 0))) {
        return rmt_devices(argc == 2);
    }
    if (strcmp(argv[0], "unpair") == 0 && argc == 2) {
        return rmt_unpair_cmd(argv[1]);
    }
    if (strcmp(argv[0], "reset") == 0 && argc == 1) {
        return rmt_reset();
    }
    fputs("usage: pic remote [pair | devices | status | stop | restart | install | uninstall | unpair ID | unpair --all | reset]\n", stderr);
    return 2;
}