Skip to content
pi-c Documentation
Login

Documentation

/* pic attach: see attach.h. Every pass reads the journal in one read
 * transaction (one snapshot), so a request's end is never seen before its
 * last entries. Events carry "seq" where they come from an entry, so a
 * client that restarts with --from its last seq sees no gap and no
 * duplicate. */
#include <errno.h>
#include <fcntl.h>
#include <sys/select.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>

#include "attach.h"
#include "cred.h"
#include "inbox.h"
#include "models.h"
#include "pic.h"
#include "sqlar.h"

#define ATT_KEYS 64

typedef struct {
    pic_store *s;
    const pic_attach_options *o;
    /* pic_follow: each event goes to emit with the seq it came from, not to stdout */
    int (*emit)(void *ctx, long long seq, const char *event);
    void *emit_ctx;
    int running; /* pic_follow: a request was admitted at the pass's snapshot */
    int limit;   /* pic_follow: the most entries one pass reads (0: no bound) */
    int capped;  /* the last pass stopped at limit, with more to read */
    char sid[64];
    long long from, last;
    long long open;   /* the request whose events are open (0: none) */
    int open_live;    /* something of it was shown, or it was running at attach */
    int open_ended;   /* its agent_end went out */
    long long *started; /* effects of the open request whose start went out */
    size_t nstarted, capstarted;
    char keys[ATT_KEYS][40]; /* -i: messages sent and not yet settled */
    char kinds[ATT_KEYS][16];
    char *texts[ATT_KEYS];             /* what was typed, for a steer sent to this attach's own request */
    unsigned char to_child[ATT_KEYS];  /* sent while that request was starting or running */
    int nkeys;
    char *in; /* -i: stdin read so far */
    size_t inlen, incap;
    int in_eof;
    pid_t child;    /* -i: the pic ask running a request this attach started, or 0 */
    int child_err;  /* its stderr's read end */
    char err[1024]; /* the last of what it wrote there */
    size_t errlen;
    char *out; /* this pass's lines, written once its read transaction ends */
    size_t outlen, outcap;
    /* The pic running the open request: its lease, looked at twice a second while the request is
     * admitted and its agent_start went out. Gone for ATT_GONE_MS, the request is reported
     * interrupted (agent_end, status "interrupted"); taken again, it is started again. */
    long long admitted; /* the conversation's admitted request at the last pass, or 0 */
    int shown_start;    /* the open request's agent_start went out */
    int interrupted;    /* its interrupted agent_end went out */
    int owner_seen;     /* its lease was seen held: only then is a free lease a death, not a run starting */
    long long probe_ms, gone_ms;
    /* The reply streaming now (JSON, following): the owner's .live file, read as it grows. */
    int live_open;            /* its message_start went out */
    unsigned long long live_ino, live_dev;
    long long live_seq;       /* the journal's last entry when the reply began */
    size_t live_head;         /* the file's header line */
    char *live;               /* the text read so far: what went out, then a cut character */
    size_t live_len, live_sent, live_cap;
} att_state;

#define ATT_GONE_MS 2000

/* Output is collected and written after each pass's read transaction has
 * ended (att_flush): a reader that stops reading must not hold the
 * snapshot, or no checkpoint could shrink the WAL behind it. */
static int att_append(att_state *a, const char *bytes, size_t n) {
    if (a->outlen + n + 1 > a->outcap) {
        size_t cap = a->outcap ? a->outcap : 8192;
        char *grown;
        while (cap < a->outlen + n + 1) {
            cap *= 2;
        }
        if (!(grown = realloc(a->out, cap))) {
            return -1;
        }
        a->out = grown;
        a->outcap = cap;
    }
    memcpy(a->out + a->outlen, bytes, n);
    a->outlen += n;
    return 0;
}

static int att_out(att_state *a, const char *line) {
    if (a->emit) { /* "SEQ JSON": the seq of the entry it came from, for att_flush to hand on */
        char tag[32];
        int n = snprintf(tag, sizeof tag, "%lld ", a->last);
        if (att_append(a, tag, (size_t)n) != 0) {
            return -1;
        }
    }
    return att_append(a, line, strlen(line)) == 0 && att_append(a, "\n", 1) == 0 ? 0 : -1;
}

/* FMT has two %s, filled with X and Y; a line for a person, any length. */
static int att_note(att_state *a, const char *fmt, const char *x, const char *y) {
    int n = snprintf(NULL, 0, fmt, x ? x : "", y ? y : "");
    char *line = n >= 0 ? malloc((size_t)n + 1) : NULL;
    int rc;
    if (!line) {
        return -1;
    }
    (void)snprintf(line, (size_t)n + 1, fmt, x ? x : "", y ? y : "");
    rc = att_out(a, line);
    free(line);
    return rc;
}

/* Outside any transaction: what the pass collected, to stdout. */
static int att_flush(att_state *a) {
    int rc = 0;
    if (a->emit) {
        char *at = a->out, *end = a->out + a->outlen;
        while (rc == 0 && at < end) {
            char *nl = memchr(at, '\n', (size_t)(end - at)), *json;
            long long seq = strtoll(at, &json, 10);
            *nl = '\0';
            rc = a->emit(a->emit_ctx, seq, json + 1);
            at = nl + 1;
        }
        a->outlen = 0;
        return rc;
    }
    if (a->outlen && (fwrite(a->out, 1, a->outlen, stdout) != a->outlen || fflush(stdout) == EOF)) {
        rc = -1;
    }
    a->outlen = 0;
    return rc;
}

static int att_sql_fail(att_state *a) {
    fprintf(stderr, "pic: attach: %s\n", sqlite3_errmsg(a->s->db));
    return -1;
}

static int att_was_started(const att_state *a, long long effect) {
    for (size_t i = 0; i < a->nstarted; i++) {
        if (a->started[i] == effect) {
            return 1;
        }
    }
    return 0;
}

static int att_mark_started(att_state *a, long long effect) {
    if (a->nstarted == a->capstarted) {
        size_t cap = a->capstarted ? a->capstarted * 2 : 16;
        long long *grown = realloc(a->started, cap * sizeof *grown);
        if (!grown) {
            return -1;
        }
        a->started = grown;
        a->capstarted = cap;
    }
    a->started[a->nstarted++] = effect;
    return 0;
}

/* tool_execution_start for the open request's calls that have left intent:
 * those of entry ENTRY (0: of every entry shown so far), or call EFFECT
 * alone. A call whose turn came before --from is not repeated. */
static int att_tool_starts(att_state *a, long long entry, long long effect) {
    sqlite3_stmt *q = NULL;
    int rc = 0;
    if (sqlite3_prepare_v2(a->s->db,
                           "SELECT f.id, json_object('type', 'tool_execution_start', 'toolCallId', f.call_id, 'toolName', f.tool,"
                           " 'args', json(CASE WHEN json_valid(f.input) THEN f.input ELSE '{}' END)), f.tool,"
                           " substr(replace(coalesce(json_extract(CASE WHEN json_valid(f.input) THEN f.input END, '$.command'),"
                           " json_extract(CASE WHEN json_valid(f.input) THEN f.input END, '$.path'), ''), char(10), ' '), 1, 100)"
                           " FROM pic_effect f JOIN pic_entry e ON e.seq = f.entry_seq"
                           " WHERE e.submission_id = ?1 AND e.seq > ?2 AND e.seq <= ?3 AND f.state != 'intent'"
                           " AND (?4 = 0 OR e.seq = ?4) AND (?5 = 0 OR f.id = ?5) ORDER BY f.entry_seq, f.ordinal",
                           -1, &q, NULL) != SQLITE_OK) {
        return att_sql_fail(a);
    }
    sqlite3_bind_int64(q, 1, a->open);
    sqlite3_bind_int64(q, 2, a->from);
    sqlite3_bind_int64(q, 3, a->last);
    sqlite3_bind_int64(q, 4, entry);
    sqlite3_bind_int64(q, 5, effect);
    while (rc == 0 && sqlite3_step(q) == SQLITE_ROW) {
        long long id = sqlite3_column_int64(q, 0);
        if (att_was_started(a, id)) {
            continue;
        }
        rc = att_mark_started(a, id);
        if (rc == 0) {
            rc = a->o->text ? att_note(a, "       -> %s %s", (const char *)sqlite3_column_text(q, 2),
                                       (const char *)sqlite3_column_text(q, 3))
                            : att_out(a, (const char *)sqlite3_column_text(q, 1));
        }
    }
    sqlite3_finalize(q);
    return rc;
}

/* agent_end for the open request once it has ended. */
static int att_maybe_end(att_state *a) {
    sqlite3_stmt *q = NULL;
    int rc = 0;
    if (!a->open || !a->open_live || a->open_ended) {
        return 0;
    }
    if (sqlite3_prepare_v2(a->s->db,
                           "SELECT status, json_patch('{}', json_object('type', 'agent_end', 'messages', json('[]'), 'request',"
                           " request_key, 'status', status, 'errorMessage', error, 'stopReason', stop_reason)),"
                           " coalesce(error, stop_reason, '') FROM pic_submission WHERE id = ?",
                           -1, &q, NULL) != SQLITE_OK) {
        return att_sql_fail(a);
    }
    sqlite3_bind_int64(q, 1, a->open);
    if (sqlite3_step(q) == SQLITE_ROW && strcmp((const char *)sqlite3_column_text(q, 0), "admitted") != 0) {
        const char *status = (const char *)sqlite3_column_text(q, 0), *why = (const char *)sqlite3_column_text(q, 2);
        a->open_ended = 1;
        if (!a->o->text) {
            rc = att_out(a, (const char *)sqlite3_column_text(q, 1));
        } else if (strcmp(status, "answered") == 0) {
            rc = att_out(a, "       (done)");
        } else if (strcmp(status, "failed") == 0) {
            rc = strcmp(why, "cancelled") == 0 ? att_out(a, "       (request cancelled)")
                                               : att_note(a, "       (request failed: %s)%s", why, NULL);
        } else {
            rc = att_note(a, "       (request stopped: %s)%s", why, NULL);
        }
    }
    sqlite3_finalize(q);
    return rc;
}

/* agent_start for request ID: at its first entry, for one already running at --from end, and
 * again when a request reported interrupted is taken up. In text, a line saying it runs. */
static int att_agent_start(att_state *a, long long id) {
    sqlite3_stmt *q = NULL;
    int rc = 0;
    if (a->o->text) {
        return att_out(a, "       (a request is running)");
    }
    if (sqlite3_prepare_v2(a->s->db,
                           "SELECT json_patch('{}', json_object('type', 'agent_start', 'request', request_key, 'conversation',"
                           " session_id, 'model', model)) FROM pic_submission WHERE id = ?",
                           -1, &q, NULL) != SQLITE_OK) {
        return att_sql_fail(a);
    }
    sqlite3_bind_int64(q, 1, id);
    if (sqlite3_step(q) == SQLITE_ROW) {
        rc = att_out(a, (const char *)sqlite3_column_text(q, 0));
    }
    sqlite3_finalize(q);
    return rc;
}

static void att_live_reset(att_state *a);

static long long att_mono_ms(void) { return (long long)(pic_platform_get()->mono_ns() / 1000000); }

/* The open request's owner: see att_state. Outside any read transaction. */
static int att_owner(att_state *a) {
    long long now = att_mono_ms();
    long holder;
    sqlite3_stmt *q = NULL;
    int rc = 0;
    if (!a->admitted || a->admitted != a->open || !a->shown_start) {
        a->gone_ms = 0;
        return 0;
    }
    if (now - a->probe_ms < 500) {
        return 0;
    }
    a->probe_ms = now;
    if ((holder = pic_lease_holder(a->s, a->sid)) != 0) {
        a->gone_ms = 0;
        a->owner_seen = 1;
        if (a->interrupted) { /* resumed by another pic */
            a->interrupted = a->open_ended = 0;
            return att_agent_start(a, a->open);
        }
        return 0;
    }
    if (a->interrupted || a->open_ended || !a->owner_seen) {
        return 0; /* admitted and not yet taken (pic submit, then a pic run starting) is not a death */
    }
    if (!a->gone_ms) {
        a->gone_ms = now;
        return 0;
    }
    if (now - a->gone_ms < ATT_GONE_MS) {
        return 0;
    }
    a->interrupted = a->open_ended = 1;
    att_live_reset(a); /* the next reply is a new one, though its file may reuse the inode */
    if (a->o->text) {
        return att_note(a, "       (interrupted: the pic running it stopped; pic run --session %s finishes it)%s", a->sid, NULL);
    }
    if (sqlite3_prepare_v2(a->s->db,
                           "SELECT json_patch('{}', json_object('type', 'agent_end', 'messages', json('[]'), 'request', request_key,"
                           " 'status', 'interrupted', 'model', model)) FROM pic_submission WHERE id = ?",
                           -1, &q, NULL) != SQLITE_OK) {
        return att_sql_fail(a);
    }
    sqlite3_bind_int64(q, 1, a->open);
    if (sqlite3_step(q) == SQLITE_ROW) {
        rc = att_out(a, (const char *)sqlite3_column_text(q, 0));
    }
    sqlite3_finalize(q);
    return rc;
}

/* message_update with N bytes of TEXT as Pi's text_delta. */
static int att_delta(att_state *a, const char *text, size_t n) {
    sqlite3_stmt *q = NULL;
    int rc = 0;
    if (sqlite3_prepare_v2(a->s->db,
                           "SELECT json_object('type', 'message_update', 'assistantMessageEvent', json_object('type', 'text_delta',"
                           " 'contentIndex', 0, 'delta', ?1))",
                           -1, &q, NULL) != SQLITE_OK) {
        return att_sql_fail(a);
    }
    sqlite3_bind_text(q, 1, text, (int)n, SQLITE_STATIC);
    if (sqlite3_step(q) == SQLITE_ROW) {
        rc = att_out(a, (const char *)sqlite3_column_text(q, 0));
    }
    sqlite3_finalize(q);
    return rc;
}

static void att_live_reset(att_state *a) {
    a->live_open = 0;
    a->live_ino = a->live_dev = 0;
    a->live_len = a->live_sent = 0;
}

/* The reply committed as FINAL (its text blocks joined): what streamed and did not reach this
 * reader yet goes out as one last delta before its message_end. */
static int att_live_finish(att_state *a, const char *final) {
    int rc = 0;
    if (a->live_open && final && strlen(final) > a->live_sent && strncmp(final, a->live, a->live_sent) == 0) {
        rc = att_delta(a, final + a->live_sent, strlen(final) - a->live_sent);
    }
    att_live_reset(a);
    return rc;
}

/* JSON, following: the owner's .live file (docs/dev/remote.md), read as it grows, as Pi's
 * message_start and message_update events. Not durable; a reply may show only when committed. */
static int att_live(att_state *a) {
    char path[4096];
    struct stat sb;
    int fd, rc = 0;
    if (a->o->text || !a->o->follow || !a->admitted || a->interrupted || a->admitted != a->open ||
        pic_live_path(a->s, a->sid, path, sizeof path) != 0) {
        return 0;
    }
    if ((fd = open(path, O_RDONLY | O_CLOEXEC | O_NOFOLLOW)) < 0) {
        return 0; /* none streams; one that ended is closed by its message_end */
    }
    if (fstat(fd, &sb) != 0 || !S_ISREG(sb.st_mode)) {
        close(fd);
        return 0;
    }
    if ((unsigned long long)sb.st_ino != a->live_ino || (unsigned long long)sb.st_dev != a->live_dev ||
        (long long)sb.st_size < (long long)(a->live_head + a->live_len)) { /* a new reply */
        char head[64], *nl;
        ssize_t n = pread(fd, head, sizeof head - 1, 0);
        long long seq;
        att_live_reset(a);
        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 is not written yet */
            return 0;
        }
        if (seq < a->last) { /* committed already (the entry it made is past its head), or a dead process's */
            close(fd);
            return 0;
        }
        a->live_ino = (unsigned long long)sb.st_ino;
        a->live_dev = (unsigned long long)sb.st_dev;
        a->live_head = (size_t)(nl - head) + 1;
        a->live_seq = seq;
    }
    if ((long long)sb.st_size > (long long)(a->live_head + a->live_len)) {
        size_t want = (size_t)((long long)sb.st_size - (long long)(a->live_head + a->live_len)), keep;
        ssize_t got;
        if (want > (1u << 20)) {
            want = 1u << 20;
        }
        if (a->live_len + want + 1 > a->live_cap) {
            size_t cap = a->live_cap ? a->live_cap : 8192;
            char *grown;
            while (cap < a->live_len + want + 1) {
                cap *= 2;
            }
            if (!(grown = realloc(a->live, cap))) {
                close(fd);
                return -1;
            }
            a->live = grown;
            a->live_cap = cap;
        }
        got = pread(fd, a->live + a->live_len, want, (off_t)(a->live_head + a->live_len));
        if (got > 0) {
            a->live_len += (size_t)got;
            a->live[a->live_len] = '\0';
            keep = a->live_len; /* a character cut off at the end waits for its other bytes */
            for (size_t i = a->live_len, back = 0; i > a->live_sent && back < 4; i--, back++) {
                unsigned char c = (unsigned char)a->live[i - 1];
                if ((c & 0xC0) == 0xC0) {
                    size_t need = c >= 0xF0 ? 4 : c >= 0xE0 ? 3 : 2;
                    keep = a->live_len - (i - 1) >= need ? a->live_len : i - 1;
                    break;
                }
                if ((c & 0x80) == 0) {
                    break;
                }
            }
            if (keep > a->live_sent) {
                if (!a->live_open) {
                    a->live_open = 1;
                    rc = att_out(a, "{\"type\":\"message_start\",\"message\":{\"role\":\"assistant\",\"content\":[]}}");
                }
                if (rc == 0) {
                    rc = att_delta(a, a->live + a->live_sent, keep - a->live_sent);
                }
                a->live_sent = keep;
            }
        }
    }
    close(fd);
    return rc;
}


/* A user entry's content as Pi sends it: its text, then each image pasted with it, in order (one
 * whose bytes were pruned as Pi's note). pic remote finds image K at position K + 1. */
#define ATT_USER_CONTENT                                                                                               \
    "json((SELECT json_group_array(json(v) ORDER BY o) FROM (SELECT json_object('type', 'text', 'text', e.body) AS v, -1 AS o" \
    " UNION ALL SELECT CASE WHEN i.data IS NULL THEN json_object('type', 'text', 'text', '" PIC_IMAGE_REMOVED "') ELSE"  \
    " json_object('type', 'image', 'data', pic_base64(sqlar_uncompress(i.data, i.sz)), 'mimeType', i.mime) END,"      \
    " a.ordinal FROM pic_attachment a JOIN pic_image i ON i.hash = a.image WHERE a.entry_seq = e.seq)))"

/* Every entry of the conversation after the last one shown, in seq order,
 * with the events around them. */
static int att_entries(att_state *a) {
    sqlite3_stmt *q = NULL;
    int rc = 0, step, rows = 0;
    if (sqlite3_prepare_v2(
            a->s->db,
            "SELECT e.seq, e.kind, e.submission_id, coalesce(e.effect_id, 0),"
            " (SELECT min(x.seq) FROM pic_entry x WHERE x.submission_id = e.submission_id),"
            " json_patch('{}', json_object('type', 'agent_start', 'request', u.request_key, 'conversation', u.session_id, 'model', u.model)),"
            " CASE e.kind"
            "  WHEN 'user' THEN json_patch(json_object('type', 'message_end', 'seq', e.seq, 'message', json_object('role', 'user',"
            "   'content', " ATT_USER_CONTENT ")), json_object('origin', " PIC_ORIGIN_SQL "))"
            "  WHEN 'tool_result' THEN json_object('type', 'tool_execution_end', 'seq', e.seq, 'toolCallId', f.call_id,"
            "   'toolName', f.tool, 'result', json_object('content', json_array(json_object('type', 'text', 'text', e.body))),"
            "   'isError', json(iif(f.is_error, 'true', 'false'))) END,"
            " CASE WHEN e.kind IN ('assistant', 'answer') THEN json_object('type', 'message_end', 'seq', e.seq, 'message',"
            "   json_object('role', 'assistant', 'content', json(CASE WHEN json_valid(e.body) THEN e.body ELSE '[]' END),"
            "   'stopReason', (SELECT g.stop_reason FROM pic_generation g WHERE g.entry_seq = e.seq AND g.state = 'done' LIMIT 1),"
            "   'provider', e.provider, 'api', e.api, 'model', e.model)) END,"
            " CASE e.kind WHEN 'user' THEN e.body"
            "  WHEN 'tool_result' THEN substr(replace(e.body, char(10), ' '), 1, 100)"
            "  ELSE coalesce((SELECT group_concat(json_extract(value, '$.text'), char(10)) FROM json_each(CASE WHEN"
            "   json_valid(e.body) THEN e.body ELSE '[]' END) WHERE json_extract(value, '$.type') = 'text'), '') END,"
            " coalesce(f.is_error, 0), coalesce(f.entry_seq, 0),"
            " CASE WHEN e.kind = 'user' THEN json_patch(json_object('type', 'message_start', 'message', json_object('role', 'user',"
            "   'content', " ATT_USER_CONTENT ")), json_object('origin', " PIC_ORIGIN_SQL ")) END,"
            " CASE WHEN e.kind IN ('assistant', 'answer') THEN coalesce((SELECT group_concat(json_extract(value, '$.text'), '')"
            "   FROM json_each(CASE WHEN json_valid(e.body) THEN e.body ELSE '[]' END) WHERE json_extract(value, '$.type') = 'text'),"
            "   '') END"
            " FROM pic_entry e JOIN pic_submission u ON u.id = e.submission_id LEFT JOIN pic_effect f ON f.id = e.effect_id"
            " AND e.kind = 'tool_result'"
            " WHERE u.session_id = ?1 AND e.seq > ?2 ORDER BY e.seq LIMIT ?3",
            -1, &q, NULL) != SQLITE_OK) {
        return att_sql_fail(a);
    }
    sqlite3_bind_text(q, 1, a->sid, -1, SQLITE_STATIC);
    sqlite3_bind_int64(q, 2, a->last);
    sqlite3_bind_int(q, 3, a->limit > 0 ? a->limit : -1);
    a->capped = 0;
    while (rc == 0 && (step = sqlite3_step(q)) == SQLITE_ROW) {
        long long seq = sqlite3_column_int64(q, 0), sub = sqlite3_column_int64(q, 2), effect = sqlite3_column_int64(q, 3);
        long long first = sqlite3_column_int64(q, 4), call_seq = sqlite3_column_int64(q, 10);
        const char *kind = (const char *)sqlite3_column_text(q, 1), *text = (const char *)sqlite3_column_text(q, 8);
        char tag[32];
        if (sub != a->open) {
            /* A new request: the one before it has ended. */
            if ((rc = att_maybe_end(a)) != 0) {
                break;
            }
            a->open = sub;
            a->open_live = a->open_ended = a->shown_start = a->interrupted = a->owner_seen = 0;
            a->nstarted = 0;
            a->gone_ms = 0;
            att_live_reset(a);
            a->last = seq; /* agent_start carries its first entry's seq */
            if (first == seq) {
                a->shown_start = 1;
                rc = a->o->text ? 0 : att_out(a, (const char *)sqlite3_column_text(q, 5));
            }
        } else if (a->interrupted) { /* taken up again before a look at its lease saw it */
            a->interrupted = a->open_ended = 0;
            rc = att_agent_start(a, sub);
        }
        a->open_live = 1;
        a->last = seq;
        a->capped = a->limit > 0 && ++rows >= a->limit;
        (void)snprintf(tag, sizeof tag, "[%lld]", seq);
        if (rc != 0) {
            break;
        }
        if (strcmp(kind, "user") == 0) {
            if (a->o->text) {
                rc = att_note(a, "\n%s you: %s", tag, text);
            } else { /* message_start, then message_end, as the owner sends them */
                rc = att_out(a, (const char *)sqlite3_column_text(q, 11));
                if (rc == 0) {
                    rc = att_out(a, (const char *)sqlite3_column_text(q, 6));
                }
            }
        } else if (strcmp(kind, "assistant") == 0 || strcmp(kind, "answer") == 0) {
            if (!a->o->text) {
                rc = att_live_finish(a, (const char *)sqlite3_column_text(q, 12));
            }
            if (rc == 0) {
                rc = a->o->text ? (*text ? att_note(a, "%s pic: %s", tag, text) : 0)
                                : att_out(a, (const char *)sqlite3_column_text(q, 7));
            }
            if (rc == 0) {
                rc = att_tool_starts(a, seq, 0);
            }
        } else if (strcmp(kind, "tool_result") == 0) {
            if (call_seq > a->from && !att_was_started(a, effect)) {
                rc = att_tool_starts(a, 0, effect);
            }
            if (rc == 0) {
                rc = a->o->text ? att_note(a, sqlite3_column_int(q, 9) ? "%s    = error: %s" : "%s    = %s", tag, text)
                                : att_out(a, (const char *)sqlite3_column_text(q, 6));
            }
        }
    }
    sqlite3_finalize(q);
    if (rc == 0 && step != SQLITE_DONE && step != SQLITE_ROW) {
        return att_sql_fail(a);
    }
    return rc;
}

/* One pass over what was committed since the last. */
static int att_sync(att_state *a) {
    int rc;
    if (sqlite3_exec(a->s->db, "BEGIN", NULL, NULL, NULL) != SQLITE_OK) {
        return att_sql_fail(a);
    }
    rc = att_entries(a);
    /* A pass cut short at its limit is the middle of the conversation: what is open is not over */
    if (rc == 0 && a->open && !a->capped) {
        rc = att_tool_starts(a, 0, 0);
    }
    if (rc == 0 && !a->capped) {
        rc = att_maybe_end(a);
    }
    if (rc == 0) {
        sqlite3_stmt *q = NULL;
        if (sqlite3_prepare_v2(a->s->db, "SELECT coalesce(max(id), 0) FROM pic_submission WHERE session_id = ? AND status = 'admitted'",
                               -1, &q, NULL) != SQLITE_OK) {
            rc = att_sql_fail(a);
        } else {
            sqlite3_bind_text(q, 1, a->sid, -1, SQLITE_STATIC);
            a->admitted = sqlite3_step(q) == SQLITE_ROW ? sqlite3_column_int64(q, 0) : 0;
            a->running = a->admitted != 0;
        }
        sqlite3_finalize(q);
    }
    (void)sqlite3_exec(a->s->db, "COMMIT", NULL, NULL, NULL);
    return rc == 0 ? att_flush(a) : rc;
}

static void att_drop(att_state *a, int i) {
    free(a->texts[i]);
    memmove(a->keys[i], a->keys[i + 1], (size_t)(a->nkeys - i - 1) * sizeof a->keys[0]);
    memmove(a->kinds[i], a->kinds[i + 1], (size_t)(a->nkeys - i - 1) * sizeof a->kinds[0]);
    memmove(&a->texts[i], &a->texts[i + 1], (size_t)(a->nkeys - i - 1) * sizeof a->texts[0]);
    memmove(&a->to_child[i], &a->to_child[i + 1], (size_t)(a->nkeys - i - 1) * sizeof a->to_child[0]);
    a->nkeys--;
}

/* -i: the messages sent that have settled since the last look; one past
 * its expiry with nothing to settle it is settled here, as expired. */
static int att_settled(att_state *a) {
    for (int i = 0; i < a->nkeys; i++) {
        char state[16];
        char *response = NULL;
        int rc = pic_inbox_expire(a->s, a->keys[i]) == 0 ? pic_inbox_status(a->s, a->keys[i], state, sizeof state, &response) : -1;
        if (rc < 0) {
            return att_sql_fail(a);
        }
        if (rc == 0 && strcmp(state, "pending") == 0) {
            free(response);
            continue;
        }
        if (!a->o->text) {
            rc = response ? att_out(a, response) : 0;
        } else if (strcmp(state, "delivered") == 0) {
            rc = att_note(a, "       (%s delivered)%s", a->kinds[i], NULL);
        } else {
            char why[300] = "";
            sqlite3_stmt *q = NULL;
            if (response && sqlite3_prepare_v2(a->s->db, "SELECT coalesce(json_extract(?, '$.error'), '')", -1, &q, NULL) == SQLITE_OK) {
                sqlite3_bind_text(q, 1, response, -1, SQLITE_STATIC);
                if (sqlite3_step(q) == SQLITE_ROW) {
                    (void)snprintf(why, sizeof why, "%s", (const char *)sqlite3_column_text(q, 0));
                }
            }
            sqlite3_finalize(q);
            rc = att_note(a, "       (%s not delivered: %s)", a->kinds[i], why[0] ? why : state);
        }
        free(response);
        if (rc != 0) {
            return -1;
        }
        att_drop(a, i);
        i--;
    }
    return 0;
}

/* -i, nothing running: TEXT starts a request in a child pic ask --session,
 * in a session of its own, so a dropped connection does not end the run.
 * Its output is the journal's, which this process shows as it commits. */
static int att_spawn(att_state *a, const char *text) {
    const pic_attach_options *o = a->o;
    const char *argv[16];
    int n = 0, errp[2], keyfd;
    pid_t pid;
    argv[n++] = o->self;
    argv[n++] = "--db";
    argv[n++] = o->db;
    argv[n++] = "--workspace";
    argv[n++] = o->workspace;
    if (o->model) {
        argv[n++] = "--model";
        argv[n++] = o->model;
    }
    if (o->thinking) {
        argv[n++] = "--thinking";
        argv[n++] = o->thinking;
    }
    argv[n++] = "ask";
    argv[n++] = "--session";
    argv[n++] = a->sid;
    argv[n++] = text;
    argv[n] = NULL;
    if (o->key_model) { /* a sealed key: asked for once, on this terminal; the child has none */
        pic_model m;
        char err[PIC_ERR_CAP];
        if (pic_model_resolve(o->key_model, &m, err, sizeof err) == 0 &&
            pic_cred_ready(m.provider, m.key_env, m.key_literal, err, sizeof err) != 0) {
            return att_note(a, "       (cannot start a request: %s)%s", err, NULL);
        }
    }
    if (pipe(errp) != 0) {
        return att_note(a, "       (cannot start a request: %s)%s", strerror(errno), NULL);
    }
    (void)fflush(stdout);
    keyfd = pic_cred_handoff();
    pid = fork();
    if (pid < 0) {
        close(errp[0]);
        close(errp[1]);
        if (keyfd >= 0) {
            close(keyfd);
        }
        return att_note(a, "       (cannot start a request: %s)%s", strerror(errno), NULL);
    }
    if (pid == 0) {
        int null = open("/dev/null", O_RDWR);
        if (keyfd >= 0) { /* only the number is in the environment; the child reads and closes it */
            char num[16];
            (void)fcntl(keyfd, F_SETFD, 0);
            (void)snprintf(num, sizeof num, "%d", keyfd);
            (void)setenv("PIC_KEY_FD", num, 1);
        }
        (void)setsid();
        if (null < 0 || dup2(null, STDIN_FILENO) < 0 || dup2(null, STDOUT_FILENO) < 0 || dup2(errp[1], STDERR_FILENO) < 0) {
            _exit(127);
        }
        close(errp[0]);
        execv(o->self, (char *const *)(void *)argv);
        _exit(127);
    }
    close(errp[1]);
    if (keyfd >= 0) {
        close(keyfd);
    }
    (void)fcntl(errp[0], F_SETFD, FD_CLOEXEC);
    (void)fcntl(errp[0], F_SETFL, O_NONBLOCK);
    a->child = pid;
    a->child_err = errp[0];
    a->errlen = 0;
    return a->o->text ? att_out(a, "       (starting a request)") : 0;
}

/* -i, the request this attach started having ended: steers sent to it and
 * never delivered (it failed first, or they came as it finished) are taken
 * back, so nothing waits for a request that is gone. After a failure they
 * are reported not delivered; after an answer their text starts the next
 * request, as a line typed now would. */
static int att_orphans(att_state *a, int failed) {
    char *next = NULL;
    size_t len = 0;
    int rc = 0;
    for (int i = 0; i < a->nkeys && rc == 0; i++) {
        int took;
        if (!a->to_child[i]) {
            continue;
        }
        took = pic_inbox_withdraw(a->s, a->keys[i], failed ? "the request failed" : "the request had ended");
        if (took < 0) {
            return att_sql_fail(a);
        }
        if (took == 0) {
            a->to_child[i] = 0; /* delivered after all: it settles as any */
            continue;
        }
        if (failed) {
            rc = a->o->text ? att_note(a, "       (%s not delivered: the request failed)%s", a->kinds[i], NULL) : 0;
        } else if (a->texts[i]) {
            size_t n = strlen(a->texts[i]);
            char *grown = realloc(next, len + n + 3);
            if (grown) {
                next = grown;
                if (len) {
                    memcpy(next + len, "\n\n", 2);
                    len += 2;
                }
                memcpy(next + len, a->texts[i], n + 1);
                len += n;
            }
        }
        att_drop(a, i);
        i--;
    }
    if (rc == 0 && next) {
        rc = att_spawn(a, next);
    }
    free(next);
    return rc;
}

/* -i: the child's stderr, and its end. A request it ran ends in the
 * journal (agent_end); what kept it from running is said here. */
static int att_reap(att_state *a) {
    char buf[sizeof a->err]; /* as large as what is kept: the cut-to-the-tail case is then reachable */
    ssize_t got;
    int status = 0, failed = 0;
    pid_t done;
    if (!a->child) {
        return 0;
    }
    while ((got = read(a->child_err, buf, sizeof buf)) > 0) {
        size_t n = (size_t)got;
        if (n >= sizeof a->err) {
            memcpy(a->err, buf + n - (sizeof a->err - 1), sizeof a->err - 1);
            a->errlen = sizeof a->err - 1;
        } else {
            if (a->errlen + n >= sizeof a->err) {
                size_t drop = a->errlen + n - (sizeof a->err - 1);
                memmove(a->err, a->err + drop, a->errlen - drop);
                a->errlen -= drop;
            }
            memcpy(a->err + a->errlen, buf, n);
            a->errlen += n;
        }
    }
    done = waitpid(a->child, &status, WNOHANG);
    if (done != a->child) {
        return 0;
    }
    close(a->child_err);
    a->child = 0;
    a->err[a->errlen] = '\0';
    if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
        char *last, *end = a->err + a->errlen;
        while (end > a->err && end[-1] == '\n') {
            *--end = '\0';
        }
        last = strrchr(a->err, '\n');
        last = last ? last + 1 : a->err;
        if (strncmp(last, "pic: ", 5) == 0) {
            last += 5;
        }
        if (strstr(last, "in use by another pic process") || strstr(last, "still working on a request")) {
            last = "busy: another request is running";
        }
        failed = 1;
        if (strcmp(last, "cancelled") != 0) { /* a cancel shows as the request's end */
            if (a->o->text) {
                if (att_note(a, "       (the request did not finish: %s)%s", *last ? last : "pic ask failed", NULL) != 0) {
                    return -1;
                }
            } else {
                fprintf(stderr, "pic: attach: the request did not finish: %s\n", *last ? last : "pic ask failed");
            }
        }
    }
    return att_orphans(a, failed);
}

/* -i: one line of stdin to the inbox. "/abort" aborts; a JSON object is
 * sent as the RPC command it is, but a prompt while nothing runs starts a
 * request, as text does; other text is a steer while a request runs. */
static int att_send(att_state *a, const char *text) {
    sqlite3_stmt *q = NULL;
    pic_inbox_msg m;
    char key[64], state[16], kind[16] = "";
    char *line = NULL;
    int rc;
    if (!*text) {
        return 0;
    }
    if (text[0] == '{' && !a->child) { /* Pi's prompt while nothing runs starts a request, as a line of text does */
        char *message = NULL;
        if (sqlite3_prepare_v2(a->s->db,
                               "SELECT json_extract(?1, '$.message') WHERE json_valid(?1) AND json_extract(?1, '$.type') = 'prompt'"
                               " AND json_type(?1, '$.message') = 'text' AND coalesce(json_array_length(?1, '$.images'), 0) = 0"
                               " AND NOT EXISTS (SELECT 1 FROM pic_submission WHERE session_id = ?2 AND status = 'admitted')",
                               -1, &q, NULL) != SQLITE_OK) {
            return att_sql_fail(a);
        }
        sqlite3_bind_text(q, 1, text, -1, SQLITE_STATIC);
        sqlite3_bind_text(q, 2, a->sid, -1, SQLITE_STATIC);
        if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_text(q, 0)) {
            message = strdup((const char *)sqlite3_column_text(q, 0));
        }
        sqlite3_finalize(q);
        if (message) {
            int started = *message ? att_spawn(a, message) : 0;
            free(message);
            return started;
        }
    }
    if (strcmp(text, "/abort") != 0 && text[0] != '{' && !a->child) {
        long long running = 0;
        if (sqlite3_prepare_v2(a->s->db, "SELECT EXISTS (SELECT 1 FROM pic_submission WHERE session_id = ? AND status = 'admitted')",
                               -1, &q, NULL) != SQLITE_OK) {
            return att_sql_fail(a);
        }
        sqlite3_bind_text(q, 1, a->sid, -1, SQLITE_STATIC);
        running = sqlite3_step(q) == SQLITE_ROW ? sqlite3_column_int64(q, 0) : 0;
        sqlite3_finalize(q);
        if (!running) {
            return att_spawn(a, text);
        }
    }
    /* A request this attach started counts as running before it is admitted. */
    if (sqlite3_prepare_v2(a->s->db,
                           "SELECT CASE WHEN ?2 = '/abort' THEN json_object('type', 'abort')"
                           " WHEN substr(?2, 1, 1) = '{' THEN ?2"
                           " ELSE json_object('type', iif(?3 OR EXISTS (SELECT 1 FROM pic_submission WHERE session_id = ?1"
                           " AND status = 'admitted'), 'steer', 'follow_up'), 'message', ?2) END",
                           -1, &q, NULL) != SQLITE_OK) {
        return att_sql_fail(a);
    }
    sqlite3_bind_text(q, 1, a->sid, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 2, text, -1, SQLITE_STATIC);
    sqlite3_bind_int(q, 3, a->child != 0);
    if (sqlite3_step(q) == SQLITE_ROW) {
        line = strdup((const char *)sqlite3_column_text(q, 0));
    }
    sqlite3_finalize(q);
    if (!line) {
        return att_sql_fail(a);
    }
    if (sqlite3_prepare_v2(a->s->db, "SELECT coalesce(CASE WHEN json_valid(?1) THEN json_extract(?1, '$.type') END, '')", -1, &q,
                           NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, line, -1, SQLITE_STATIC);
        if (sqlite3_step(q) == SQLITE_ROW) {
            (void)snprintf(kind, sizeof kind, "%s", (const char *)sqlite3_column_text(q, 0));
        }
    }
    sqlite3_finalize(q);
    memset(&m, 0, sizeof m);
    m.session = a->sid;
    m.line = line;
    m.sender = "attach";
    rc = pic_inbox_accept(a->s, &m, key, sizeof key, state, sizeof state);
    free(line);
    if (rc != 0) {
        if (rc < 0) {
            fprintf(stderr, "pic: attach: %s\n", a->s->err);
            return -1;
        }
        return a->o->text ? att_note(a, "       (not sent: %s)%s", a->s->err, NULL)
                          : (fprintf(stderr, "pic: attach: %s\n", a->s->err), 0);
    }
    if (a->o->text && strcmp(kind, "follow_up") == 0) {
        rc = att_out(a, "       (follow-up sent: it runs when a request next runs here)");
    } else if (a->o->text) {
        rc = att_note(a, "       (%s sent)%s", kind, NULL);
    }
    if (a->nkeys < ATT_KEYS) {
        (void)snprintf(a->keys[a->nkeys], sizeof a->keys[0], "%s", key);
        (void)snprintf(a->kinds[a->nkeys], sizeof a->kinds[0], "%s", kind[0] ? kind : "message");
        a->to_child[a->nkeys] = a->child != 0 && strcmp(kind, "steer") == 0 && text[0] != '{';
        a->texts[a->nkeys] = a->to_child[a->nkeys] ? strdup(text) : NULL;
        a->nkeys++;
    }
    return rc;
}

/* -i: what stdin has, each complete line sent. */
static int att_read(att_state *a) {
    ssize_t n;
    if (a->incap - a->inlen < 4097) {
        size_t cap = a->incap ? a->incap * 2 : 8192;
        char *grown = cap > PIC_INBOX_LINE_CAP + 8192 ? NULL : realloc(a->in, cap);
        if (!grown) {
            fprintf(stderr, "pic: attach: a line longer than 16 MB\n");
            return -1;
        }
        a->in = grown;
        a->incap = cap;
    }
    n = read(STDIN_FILENO, a->in + a->inlen, a->incap - a->inlen - 1);
    if (n < 0) {
        return errno == EINTR || errno == EAGAIN ? 0 : -1;
    }
    if (n == 0) {
        a->in_eof = 1;
        if (a->inlen) { /* the last line, without its newline */
            a->in[a->inlen++] = '\n';
        }
    }
    a->inlen += (size_t)n;
    for (;;) {
        char *nl = memchr(a->in, '\n', a->inlen);
        size_t len;
        int rc;
        if (!nl) {
            break;
        }
        len = (size_t)(nl - a->in);
        *nl = '\0';
        if (len && a->in[len - 1] == '\r') {
            a->in[len - 1] = '\0';
        }
        rc = att_send(a, a->in);
        memmove(a->in, nl + 1, a->inlen - len - 1);
        a->inlen -= len + 1;
        if (rc != 0) {
            return -1;
        }
    }
    return 0;
}

/* -i at the end of input: messages still to settle. A follow-up sent while
 * nothing ran waits for a request that may be a day away; it is left. */
static int att_waiting(const att_state *a) {
    int n = a->child != 0; /* and the request it started, to its end */
    for (int i = 0; i < a->nkeys; i++) {
        n += strcmp(a->kinds[i], "follow_up") != 0;
    }
    return n;
}

static long long att_data_version(att_state *a) {
    sqlite3_stmt *q = NULL;
    long long v = -1;
    if (sqlite3_prepare_v2(a->s->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;
}

/* --from end in a running request: tool_execution_start for its calls running now (out of
 * intent, no result yet), so their ends that follow have their starts. */
static int att_running_calls(att_state *a) {
    sqlite3_stmt *q = NULL;
    int rc = 0;
    if (sqlite3_prepare_v2(a->s->db,
                           "SELECT f.id, json_object('type', 'tool_execution_start', 'toolCallId', f.call_id, 'toolName', f.tool,"
                           " 'args', json(CASE WHEN json_valid(f.input) THEN f.input ELSE '{}' END)), f.tool,"
                           " substr(replace(coalesce(json_extract(CASE WHEN json_valid(f.input) THEN f.input END, '$.command'),"
                           " json_extract(CASE WHEN json_valid(f.input) THEN f.input END, '$.path'), ''), char(10), ' '), 1, 100)"
                           " FROM pic_effect f JOIN pic_entry e ON e.seq = f.entry_seq"
                           " WHERE e.submission_id = ?1 AND f.state != 'intent'"
                           " AND NOT EXISTS (SELECT 1 FROM pic_entry r WHERE r.effect_id = f.id) ORDER BY f.entry_seq, f.ordinal",
                           -1, &q, NULL) != SQLITE_OK) {
        return att_sql_fail(a);
    }
    sqlite3_bind_int64(q, 1, a->open);
    while (rc == 0 && sqlite3_step(q) == SQLITE_ROW) {
        rc = att_mark_started(a, sqlite3_column_int64(q, 0));
        if (rc == 0) {
            rc = a->o->text ? att_note(a, "       -> %s %s", (const char *)sqlite3_column_text(q, 2),
                                       (const char *)sqlite3_column_text(q, 3))
                            : att_out(a, (const char *)sqlite3_column_text(q, 1));
        }
    }
    sqlite3_finalize(q);
    return rc;
}

/* Where to start: the latest request's first entry, unless --from says. A
 * request running at the start counts as shown, so its end is shown. */
static int att_start(att_state *a) {
    sqlite3_stmt *q = NULL;
    if (a->o->from == -2) { /* --from end: only what comes after now */
        if (sqlite3_prepare_v2(a->s->db, "SELECT coalesce(max(seq), 0) FROM pic_entry", -1, &q, NULL) != SQLITE_OK) {
            return att_sql_fail(a);
        }
        a->from = sqlite3_step(q) == SQLITE_ROW ? sqlite3_column_int64(q, 0) : 0;
        sqlite3_finalize(q);
    } else if (a->o->from < 0) {
        if (sqlite3_prepare_v2(a->s->db,
                               "SELECT 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)",
                               -1, &q, NULL) != SQLITE_OK) {
            return att_sql_fail(a);
        }
        sqlite3_bind_text(q, 1, a->sid, -1, SQLITE_STATIC);
        a->from = sqlite3_step(q) == SQLITE_ROW ? sqlite3_column_int64(q, 0) : 0;
        sqlite3_finalize(q);
    } else {
        a->from = a->o->from;
    }
    a->last = a->from;
    if (a->from > 0) {
        if (sqlite3_prepare_v2(a->s->db,
                               "SELECT u.id, u.status = 'admitted' FROM pic_entry e JOIN pic_submission u ON u.id = e.submission_id"
                               " WHERE u.session_id = ?1 AND e.seq <= ?2 ORDER BY e.seq DESC LIMIT 1",
                               -1, &q, NULL) != SQLITE_OK) {
            return att_sql_fail(a);
        }
        sqlite3_bind_text(q, 1, a->sid, -1, SQLITE_STATIC);
        sqlite3_bind_int64(q, 2, a->from);
        if (sqlite3_step(q) == SQLITE_ROW) {
            a->open = sqlite3_column_int64(q, 0);
            a->open_live = sqlite3_column_int(q, 1);
        }
        sqlite3_finalize(q);
        /* --from end in the middle of a request another pic runs: it is shown as running, so a
         * client that came in now knows to steer it rather than start one. */
        if (a->o->from == -2 && a->open_live && pic_lease_holder(a->s, a->sid) != 0) {
            a->shown_start = a->owner_seen = 1;
            return att_agent_start(a, a->open) == 0 ? att_running_calls(a) : -1;
        }
    }
    return 0;
}

/* Whether FD (-1: none) is readable within MS. select, not poll: macOS's
 * poll never reports the end of a FIFO whose writer has gone. */
static int att_wait(int fd, int ms) {
    struct timeval tv = {0, ms * 1000};
    fd_set r;
    FD_ZERO(&r);
    if (fd >= 0) {
        FD_SET(fd, &r);
    }
    return select(fd >= 0 ? fd + 1 : 0, &r, NULL, NULL, &tv) > 0 && fd >= 0 && FD_ISSET(fd, &r);
}

int pic_attach_main(const pic_attach_options *o) {
    att_state a;
    pic_store st;
    long long seen = -2;
    int rc = 0;
    unsigned polls = 0;
    memset(&a, 0, sizeof a);
    a.o = o;
    a.s = &st;
    if (pic_open_narrow(a.s, o->db) != 0 || pic_sqlar_register(a.s->db) != 0 || pic_transform_register(a.s->db) != 0 ||
        pic_session_resolve(a.s, o->session, a.sid, sizeof a.sid) != 0 || att_start(&a) != 0) {
        fprintf(stderr, "pic: attach: %s\n", a.s->err[0] ? a.s->err : "cannot read the journal");
        pic_close(a.s);
        return 1;
    }
    /* Without -i, a pipe or socket on stdin is a lifeline: when whoever
     * holds its other end goes (the interface that started this follower,
     * an ssh client), this exits instead of following for no one. */
    struct stat sb;
    int lifeline = !o->interactive && o->follow && fstat(STDIN_FILENO, &sb) == 0 &&
                   (S_ISFIFO(sb.st_mode) || S_ISSOCK(sb.st_mode));
    if (lifeline) {
        (void)pic_watch_hold(a.s, a.sid); /* advisory: a sender's tool result says it is open somewhere */
    }
    if (o->text) {
        rc = att_note(&a, "pic: attached to %s (%s)", a.sid, o->interactive ? "lines you type are sent to it" : "read-only");
    }
    while (rc == 0) {
        long long v = att_data_version(&a);
        int in = (o->interactive || lifeline) && !a.in_eof ? STDIN_FILENO : -1;
        if (a.child) {
            pid_t was = a.child;
            rc = att_reap(&a);
            if (rc == 0 && was && !a.child) {
                seen = -2; /* its last commits, then the exit check */
            }
        }
        if (rc == 0 && v != seen) {
            seen = v;
            rc = att_sync(&a);
            if (rc == 0 && a.nkeys) {
                rc = att_settled(&a);
            }
        }
        if (rc == 0 && o->follow) {
            rc = att_owner(&a);
        }
        if (rc == 0 && o->follow) {
            rc = att_live(&a);
        }
        if (rc == 0) {
            rc = att_flush(&a);
        }
        if (rc != 0) {
            break;
        }
        /* Done: --no-follow once caught up; -i once stdin has ended and
         * every message it sent has settled. */
        if (o->interactive ? a.in_eof && !att_waiting(&a) : !o->follow) {
            break;
        }
        /* A newer pic waits to migrate the journal: a follower lets go of it, once nothing it
         * started runs (a.child), and says so; attaching again works once it has migrated. */
        if (o->follow && !a.child && ++polls % 10 == 0 && pic_migration_wanted(a.s)) {
            fprintf(stderr, "pic: attach: a newer pic is updating this journal; attach again with it\n");
            rc = 1;
            break;
        }
        if (att_wait(in, 100)) {
            if (lifeline) {
                char junk[512];
                ssize_t r = read(STDIN_FILENO, junk, sizeof junk);
                if (r == 0 || (r < 0 && errno != EINTR && errno != EAGAIN)) {
                    break;
                }
                continue;
            }
            rc = att_read(&a);
            seen = -2; /* look at once: a sent message may settle quickly */
        }
    }
    (void)att_flush(&a);
    for (int i = 0; i < a.nkeys; i++) {
        free(a.texts[i]);
    }
    free(a.started);
    free(a.in);
    free(a.out);
    free(a.live);
    pic_close(a.s);
    return rc == 0 ? 0 : 1;
}

struct pic_follow {
    att_state a;
    pic_attach_options o;
};

pic_follow *pic_follow_new(pic_store *s, const char *session, long long from, char *err, size_t cap) {
    pic_follow *f = calloc(1, sizeof *f);
    if (!f) {
        (void)snprintf(err, cap, "out of memory");
        return NULL;
    }
    f->o.from = from;
    f->o.follow = 1;
    f->a.o = &f->o;
    f->a.s = s;
    (void)snprintf(f->a.sid, sizeof f->a.sid, "%s", session);
    if (att_start(&f->a) != 0) {
        (void)snprintf(err, cap, "%s", sqlite3_errmsg(s->db));
        free(f);
        return NULL;
    }
    return f;
}

int pic_follow_pass(pic_follow *f, int (*emit)(void *ctx, long long seq, const char *event), void *ctx, int max,
                    long long *last, int *running, int *more) {
    int rc;
    f->a.emit = emit;
    f->a.emit_ctx = ctx;
    f->a.outlen = 0;
    f->a.limit = max;
    rc = att_sync(&f->a);
    *last = f->a.last;
    *running = f->a.running;
    *more = f->a.capped;
    return rc;
}

void pic_follow_free(pic_follow *f) {
    if (f) {
        free(f->a.started);
        free(f->a.out);
        free(f->a.live);
        free(f);
    }
}