Skip to content
pi-c Artifact [3eb1f0a28d]
Login

Artifact [3eb1f0a28d]

Artifact 3eb1f0a28d26adc0742e5ca4e301d38541dd19645968bd06e7c8ca7b9c17bcc7:


/* Wakes: see wake.h and docs/design/wakes.md. Core: the record, the fire and the due check. No
 * timer: a caller asks what is due, and the clock is the platform's wall clock. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "inbox.h"
#include "platform.h"
#include "wake.h"

long long pic_wake_now_ms(void) {
#ifdef PIC_FAULTS
    const char *at = getenv("PIC_WAKE_NOW_MS"); /* tests: the wall clock at a chosen time */
    if (at && *at) {
        return strtoll(at, NULL, 10);
    }
#endif
    return (long long)(pic_platform_get()->wall_ns() / 1000000);
}

static int wake_fail(pic_store *s, int rc, const char *msg) {
    (void)snprintf(s->err, sizeof s->err, "%s", msg);
    return rc;
}

static int wake_sql_fail(pic_store *s) {
    (void)snprintf(s->err, sizeof s->err, "sql: %s", sqlite3_errmsg(s->db));
    return -1;
}

/* SQL's first column as an integer, ?1 the integer A and ?2 the text B (NULL: unbound). 0 or -1. */
static int wake_int(pic_store *s, const char *sql, long long a, const char *b, long long *out) {
    sqlite3_stmt *q = NULL;
    int rc;
    *out = 0;
    if (sqlite3_prepare_v2(s->db, sql, -1, &q, NULL) != SQLITE_OK) {
        return wake_sql_fail(s);
    }
    sqlite3_bind_int64(q, 1, a);
    if (b) {
        sqlite3_bind_text(q, 2, b, -1, SQLITE_STATIC);
    }
    rc = sqlite3_step(q);
    if (rc == SQLITE_ROW) {
        *out = sqlite3_column_int64(q, 0);
    }
    sqlite3_finalize(q);
    return rc == SQLITE_ROW || rc == SQLITE_DONE ? 0 : wake_sql_fail(s);
}

/* ---- intervals -------------------------------------------------------------------------------- */

int pic_wake_parse_every(const char *text, long long *ms) {
    long long total = 0;
    const char *p = text;
    if (!text || !*text) {
        return 1;
    }
    while (*p) {
        long long n = 0, unit;
        int digits = 0;
        while (*p >= '0' && *p <= '9' && n < 100000000LL) {
            n = n * 10 + (*p++ - '0');
            digits++;
        }
        if (!digits) {
            return 1;
        }
        switch (*p) {
        case 's':
            unit = 1000;
            break;
        case 'm':
            unit = 60000;
            break;
        case 'h':
            unit = 3600000;
            break;
        case 'd':
            unit = 86400000;
            break;
        case '\0':
            if (p == text + digits && total == 0) { /* a number alone is minutes */
                *ms = n * 60000;
                return 0;
            }
            return 1;
        default:
            return 1;
        }
        p++;
        total += n * unit;
    }
    *ms = total;
    return 0;
}

void pic_wake_every_text(long long ms, char *out, size_t cap) {
    if (ms > 0 && ms % 86400000LL == 0) {
        (void)snprintf(out, cap, "%lldd", ms / 86400000LL);
    } else if (ms > 0 && ms % 3600000LL == 0) {
        (void)snprintf(out, cap, "%lldh", ms / 3600000LL);
    } else if (ms > 0 && ms % 60000LL == 0) {
        (void)snprintf(out, cap, "%lldm", ms / 60000LL);
    } else {
        (void)snprintf(out, cap, "%llds", ms / 1000);
    }
}

/* ---- the record ------------------------------------------------------------------------------- */

int pic_wake_create(pic_store *s, const pic_wake_new *w, long long *id, char *session_out, size_t cap) {
    sqlite3_stmt *q = NULL;
    long long every = w->every_ms ? w->every_ms : PIC_WAKE_SELF_PACED_MS, now = pic_wake_now_ms(), live = 0;
    char sid[64] = "";
    int rc;
    *id = 0;
    if (!w->kind || strcmp(w->kind, "loop") != 0) {
        return wake_fail(s, 1, "only loops are made here");
    }
    if (!w->prompt || !*w->prompt) {
        return wake_fail(s, 1, "a loop needs a prompt");
    }
    if (every < PIC_WAKE_MIN_EVERY_MS) {
        return wake_fail(s, 1, "the shortest interval is 1m");
    }
    if (every > PIC_WAKE_EXPIRY_MS) {
        return wake_fail(s, 1, "the longest interval is 7d, when a loop ends");
    }
    if (pic_begin(s) != 0) {
        return -1;
    }
    if (!w->session || !*w->session) { /* a new, empty conversation for it */
        if (sqlite3_prepare_v2(s->db,
                               "INSERT INTO pic_session(id, created_ms, updated_ms) VALUES(lower(hex(randomblob(4))), ?1, ?1)"
                               " RETURNING id",
                               -1, &q, NULL) != SQLITE_OK) {
            rc = wake_sql_fail(s);
            pic_rollback(s);
            return rc;
        }
        sqlite3_bind_int64(q, 1, now);
        if (sqlite3_step(q) == SQLITE_ROW) {
            (void)snprintf(sid, sizeof sid, "%s", (const char *)sqlite3_column_text(q, 0));
        }
        sqlite3_finalize(q);
        q = NULL;
    } else if (pic_session_resolve(s, w->session, sid, sizeof sid) != 0) {
        pic_rollback(s);
        return 1;
    }
    if (!sid[0]) {
        rc = wake_sql_fail(s);
        pic_rollback(s);
        return rc;
    }
    if (wake_int(s, "SELECT count(*) FROM pic_wake WHERE session_id = ?2 AND state != 'ended' AND ?1 = ?1", 0, sid, &live) != 0) {
        pic_rollback(s);
        return -1;
    }
    if (live >= PIC_WAKE_MAX) {
        pic_rollback(s);
        (void)snprintf(s->err, sizeof s->err,
                       "this conversation has %d loops, monitors and goals already: stop one first (/loop lists them)",
                       PIC_WAKE_MAX);
        return 1;
    }
    if (sqlite3_prepare_v2(s->db,
                           "INSERT INTO pic_wake(session_id, kind, prompt, every_ms, state, creator, due_ms, created_ms,"
                           " expires_ms, updated_ms, options) VALUES (?1, ?2, ?3, ?4, 'active', ?5, ?6, ?6, ?7, ?6,"
                           " CASE WHEN ?8 IS NOT NULL THEN json_object('model', ?8) END)",
                           -1, &q, NULL) != SQLITE_OK) {
        rc = wake_sql_fail(s);
        pic_rollback(s);
        return rc;
    }
    sqlite3_bind_text(q, 1, sid, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 2, w->kind, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 3, w->prompt, -1, SQLITE_STATIC);
    sqlite3_bind_int64(q, 4, every);
    sqlite3_bind_text(q, 5, w->creator ? w->creator : "user", -1, SQLITE_STATIC);
    sqlite3_bind_int64(q, 6, now);
    sqlite3_bind_int64(q, 7, now + PIC_WAKE_EXPIRY_MS);
    if (w->model && *w->model) {
        sqlite3_bind_text(q, 8, w->model, -1, SQLITE_STATIC);
    }
    rc = sqlite3_step(q);
    sqlite3_finalize(q);
    if (rc != SQLITE_DONE) {
        rc = wake_sql_fail(s);
        pic_rollback(s);
        return rc;
    }
    *id = sqlite3_last_insert_rowid(s->db);
    if (pic_commit(s) != 0) {
        pic_rollback(s);
        return -1;
    }
    (void)snprintf(session_out, cap, "%s", sid);
    return 0;
}

int pic_wake_resolve(pic_store *s, const char *name, long long *id) {
    const char *p = name;
    long long n = 0, found = 0;
    *id = 0;
    if (p && (*p == 'L' || *p == 'l' || *p == 'M' || *p == 'm' || *p == 'G' || *p == 'g')) {
        p++;
    }
    if (!p || !*p) {
        (void)snprintf(s->err, sizeof s->err, "no loop, monitor or goal %s", name ? name : "");
        return 1;
    }
    for (; *p; p++) {
        if (*p < '0' || *p > '9' || n > 1000000000LL) {
            (void)snprintf(s->err, sizeof s->err, "no loop, monitor or goal %s", name);
            return 1;
        }
        n = n * 10 + (*p - '0');
    }
    if (wake_int(s, "SELECT count(*) FROM pic_wake WHERE id = ?1", n, NULL, &found) != 0) {
        return -1;
    }
    if (!found) {
        (void)snprintf(s->err, sizeof s->err, "no loop, monitor or goal %s", name);
        return 1;
    }
    *id = n;
    return 0;
}

int pic_wake_set(pic_store *s, long long id, const char *action, const char *why) {
    sqlite3_stmt *q = NULL;
    char state[16] = "";
    long long now = pic_wake_now_ms(), expires = 0;
    const char *to, *sql;
    int rc;
    if (pic_begin(s) != 0) {
        return -1;
    }
    if (sqlite3_prepare_v2(s->db, "SELECT state, expires_ms FROM pic_wake WHERE id = ?", -1, &q, NULL) != SQLITE_OK) {
        rc = wake_sql_fail(s);
        pic_rollback(s);
        return rc;
    }
    sqlite3_bind_int64(q, 1, id);
    if (sqlite3_step(q) == SQLITE_ROW) {
        (void)snprintf(state, sizeof state, "%s", (const char *)sqlite3_column_text(q, 0));
        expires = sqlite3_column_int64(q, 1);
    }
    sqlite3_finalize(q);
    if (state[0] && strcmp(state, "ended") == 0 && strcmp(action, "stop") == 0) { /* stopped already: the same answer */
        pic_rollback(s);
        return 0;
    }
    if (!state[0] || strcmp(state, "ended") == 0) {
        pic_rollback(s);
        (void)snprintf(s->err, sizeof s->err, state[0] ? "it has ended" : "no such loop, monitor or goal");
        return 1;
    }
    if (strcmp(action, "pause") == 0) {
        to = "paused";
        why = why ? why : "paused";
        sql = "UPDATE pic_wake SET state = ?2, why = ?3, updated_ms = ?4 WHERE id = ?1";
    } else if (strcmp(action, "resume") == 0) {
        if (now >= expires) {
            pic_rollback(s);
            return wake_fail(s, 1, "it has expired: loops, monitors and goals end after 7 days");
        }
        to = "active";
        why = NULL;
        sql = "UPDATE pic_wake SET state = ?2, why = ?3, updated_ms = ?4, due_ms = coalesce(due_ms, ?4) WHERE id = ?1";
    } else if (strcmp(action, "stop") == 0) {
        to = "ended";
        why = why ? why : "stopped";
        sql = "UPDATE pic_wake SET state = ?2, why = ?3, updated_ms = ?4 WHERE id = ?1";
    } else {
        pic_rollback(s);
        return wake_fail(s, 1, "pause, resume or stop");
    }
    if (sqlite3_prepare_v2(s->db, sql, -1, &q, NULL) != SQLITE_OK) {
        rc = wake_sql_fail(s);
        pic_rollback(s);
        return rc;
    }
    sqlite3_bind_int64(q, 1, id);
    sqlite3_bind_text(q, 2, to, -1, SQLITE_STATIC);
    if (why) {
        sqlite3_bind_text(q, 3, why, -1, SQLITE_STATIC);
    }
    sqlite3_bind_int64(q, 4, now);
    rc = sqlite3_step(q);
    sqlite3_finalize(q);
    if (rc != SQLITE_DONE) {
        rc = wake_sql_fail(s);
        pic_rollback(s);
        return rc;
    }
    return pic_commit(s) == 0 ? 0 : (pic_rollback(s), -1);
}

int pic_wake_pause_all(pic_store *s, const char *session, const char *why, int *count) {
    sqlite3_stmt *q = NULL;
    int rc;
    *count = 0;
    if (pic_begin(s) != 0) {
        return -1;
    }
    if (sqlite3_prepare_v2(s->db,
                           "UPDATE pic_wake SET state = 'paused', why = ?2, updated_ms = ?3 WHERE session_id = ?1 AND state = 'active'",
                           -1, &q, NULL) != SQLITE_OK) {
        rc = wake_sql_fail(s);
        pic_rollback(s);
        return rc;
    }
    sqlite3_bind_text(q, 1, session, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 2, why ? why : "paused with /stop", -1, SQLITE_STATIC);
    sqlite3_bind_int64(q, 3, pic_wake_now_ms());
    rc = sqlite3_step(q);
    sqlite3_finalize(q);
    if (rc != SQLITE_DONE) {
        rc = wake_sql_fail(s);
        pic_rollback(s);
        return rc;
    }
    *count = sqlite3_changes(s->db);
    return pic_commit(s) == 0 ? 0 : (pic_rollback(s), -1);
}

int pic_wake_cancelled(pic_store *s, long long submission) {
    sqlite3_stmt *q = NULL;
    int rc;
    if (sqlite3_prepare_v2(s->db,
                           "UPDATE pic_wake SET state = 'paused', why = 'stopped during its run', updated_ms = ?2"
                           " WHERE state = 'active' AND id = (SELECT " PIC_WAKE_OF_SQL("u") " FROM pic_submission u WHERE u.id = ?1)",
                           -1, &q, NULL) != SQLITE_OK) {
        return wake_sql_fail(s);
    }
    sqlite3_bind_int64(q, 1, submission);
    sqlite3_bind_int64(q, 2, pic_wake_now_ms());
    rc = sqlite3_step(q);
    sqlite3_finalize(q);
    return rc == SQLITE_DONE ? 0 : wake_sql_fail(s);
}

/* ---- the fire --------------------------------------------------------------------------------- */

/* SQL: wake W.id has a fire not yet taken up: its inbox row pending, or delivered as a follow-up
 * still queued behind a running request. */
#define WAKE_WAITING_SQL(W)                                                                                            \
    "EXISTS (SELECT 1 FROM pic_inbox w_p WHERE w_p.sender = 'wake:' || " W ".id AND (w_p.state = 'pending'"            \
    " OR (w_p.state = 'delivered' AND w_p.queued_id IN (SELECT w_q.id FROM pic_queued w_q WHERE w_q.state = 'queued'))))"

/* A wake whose time has come at NOW (?1): a loop at or past its due time, or with its last fire
 * ahead of the clock (the clock stepped back), or any wake past its expiry. */
#define WAKE_DUE_SQL(W)                                                                                                \
    "(" W ".state = 'active' AND ((" W ".kind = 'loop' AND (" W ".due_ms <= ?1 OR " W ".fired_ms > ?1))"               \
    " OR " W ".expires_ms <= ?1))"

static char *wake_message(pic_store *s, long long id, long long every, long long fires, long long ticks, int last,
                          const char *prompt) {
    sqlite3_stmt *q = NULL;
    char head[400], ev[32];
    char *out = NULL;
    size_t n;
    pic_wake_every_text(every, ev, sizeof ev);
    n = (size_t)snprintf(head, sizeof head, "[Loop L%lld, every %s, run %lld: sent by a loop the user set up, not typed just now.", id,
                         ev, fires);
    if (ticks > 1 && n < sizeof head) {
        n += (size_t)snprintf(head + n, sizeof head - n, " It stands for the %lld runs that came due while no pic was running.", ticks);
    }
    if (last && n < sizeof head) {
        n += (size_t)snprintf(head + n, sizeof head - n, " This is its last run: loops end 7 days after they start.");
    }
    if (n < sizeof head) {
        (void)snprintf(head + n, sizeof head - n, "]");
    }
    if (sqlite3_prepare_v2(s->db,
                           "SELECT json_object('type', 'prompt', 'streamingBehavior', 'followUp', 'message',"
                           " ?2 || char(10) || char(10) || ?1)",
                           -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, head, -1, SQLITE_STATIC);
        sqlite3_bind_text(q, 2, prompt, -1, SQLITE_STATIC);
        if (sqlite3_step(q) == SQLITE_ROW) {
            out = strdup((const char *)sqlite3_column_text(q, 0));
        }
    }
    sqlite3_finalize(q);
    return out;
}

/* Wake ID fires at NOW when its time has come and no fire of it waits, in one transaction: its
 * count, due time and last fire advance, and its inbox row is inserted. 1 fired, 0 nothing to do,
 * -1 (rolled back; s->err). */
static int wake_fire(pic_store *s, long long id, long long now, char *session, size_t cap) {
    sqlite3_stmt *q = NULL;
    char kind[16] = "", *prompt = NULL, *line = NULL, key[96], sender[48], got[96], state[16];
    long long every = 0, fires = 0, due = 0, fired = 0, expires = 0, waiting = 0, ticks = 1, next;
    int ok = 0, rc = -1, last;
    pic_inbox_msg m;
    session[0] = '\0';
    if (pic_begin_outer(s) != 0) {
        return -1;
    }
    if (sqlite3_prepare_v2(s->db,
                           "SELECT kind, session_id, prompt, coalesce(every_ms, 0), fires, coalesce(due_ms, ?1), coalesce(fired_ms, 0),"
                           " expires_ms, " WAKE_WAITING_SQL("w") " FROM pic_wake w WHERE w.id = ?2 AND " WAKE_DUE_SQL("w"),
                           -1, &q, NULL) != SQLITE_OK) {
        (void)wake_sql_fail(s);
        goto out;
    }
    sqlite3_bind_int64(q, 1, now);
    sqlite3_bind_int64(q, 2, id);
    if (sqlite3_step(q) == SQLITE_ROW) {
        ok = 1;
        (void)snprintf(kind, sizeof kind, "%s", (const char *)sqlite3_column_text(q, 0));
        (void)snprintf(session, cap, "%s", (const char *)sqlite3_column_text(q, 1));
        prompt = strdup((const char *)sqlite3_column_text(q, 2));
        every = sqlite3_column_int64(q, 3);
        fires = sqlite3_column_int64(q, 4);
        due = sqlite3_column_int64(q, 5);
        fired = sqlite3_column_int64(q, 6);
        expires = sqlite3_column_int64(q, 7);
        waiting = sqlite3_column_int64(q, 8);
    }
    sqlite3_finalize(q);
    q = NULL;
    if (!ok) { /* another process fired it, or it was paused, since the look */
        rc = 0;
        goto out;
    }
    if (!prompt) {
        (void)wake_fail(s, -1, "out of memory");
        goto out;
    }
    last = now >= expires;
    if (waiting && !last) { /* a fire still waits to be taken up: this one is folded into the next */
        rc = 0;
        goto out;
    }
    if (waiting || strcmp(kind, "loop") != 0) { /* expired with a fire waiting, or a kind this build cannot fire */
        if (sqlite3_prepare_v2(s->db, "UPDATE pic_wake SET state = 'ended', why = 'expired', updated_ms = ?2 WHERE id = ?1", -1, &q,
                               NULL) != SQLITE_OK) {
            (void)wake_sql_fail(s);
            goto out;
        }
        sqlite3_bind_int64(q, 1, id);
        sqlite3_bind_int64(q, 2, now);
        rc = sqlite3_step(q) == SQLITE_DONE ? 0 : wake_sql_fail(s);
        sqlite3_finalize(q);
        q = NULL;
        if (rc == 0 && pic_commit(s) != 0) {
            rc = -1;
        }
        goto out;
    }
    if (fired > now || due > now) { /* the clock stepped back past the last fire: fire once, anchored anew */
        next = now + every;
    } else {
        ticks = (now - due) / every + 1;
        next = due + ticks * every;
    }
    if (!(line = wake_message(s, id, every, fires + 1, ticks, last, prompt))) {
        (void)wake_fail(s, -1, "out of memory");
        goto out;
    }
    (void)snprintf(key, sizeof key, "wake:%lld:%lld", id, fires + 1);
    (void)snprintf(sender, sizeof sender, "wake:%lld", id);
    memset(&m, 0, sizeof m);
    m.session = session;
    m.key = key;
    m.line = line;
    m.sender = sender;
    rc = pic_inbox_accept(s, &m, got, sizeof got, state, sizeof state);
    if (rc < 0) {
        goto out;
    }
    if (rc == 1) { /* the inbox refused it (full, the conversation gone): a person has to look */
        char why[PIC_ERR_CAP + 40];
        (void)snprintf(why, sizeof why, "its message was refused: %s", s->err);
        if (sqlite3_prepare_v2(s->db, "UPDATE pic_wake SET state = 'needs', why = ?3, updated_ms = ?2 WHERE id = ?1", -1, &q, NULL) !=
            SQLITE_OK) {
            rc = wake_sql_fail(s);
            goto out;
        }
        sqlite3_bind_int64(q, 1, id);
        sqlite3_bind_int64(q, 2, now);
        sqlite3_bind_text(q, 3, why, -1, SQLITE_TRANSIENT);
        rc = sqlite3_step(q) == SQLITE_DONE ? 0 : wake_sql_fail(s);
        sqlite3_finalize(q);
        q = NULL;
        if (rc == 0 && pic_commit(s) != 0) {
            rc = -1;
        }
        goto out;
    }
    if (sqlite3_prepare_v2(s->db,
                           "UPDATE pic_wake SET fires = fires + 1, fired_ms = ?2, due_ms = ?3, updated_ms = ?2,"
                           " state = iif(?4, 'ended', state), why = iif(?4, 'expired', why) WHERE id = ?1",
                           -1, &q, NULL) != SQLITE_OK) {
        rc = wake_sql_fail(s);
        goto out;
    }
    sqlite3_bind_int64(q, 1, id);
    sqlite3_bind_int64(q, 2, now);
    sqlite3_bind_int64(q, 3, next);
    sqlite3_bind_int(q, 4, last);
    rc = sqlite3_step(q) == SQLITE_DONE ? 0 : wake_sql_fail(s);
    sqlite3_finalize(q);
    q = NULL;
    if (rc != 0) {
        goto out;
    }
    pic_fault("wake_fire");
    if (pic_commit(s) != 0) {
        rc = -1;
        goto out;
    }
    pic_fault("wake_fire");
    pic_inbox_ring(s, session); /* the worker looks only after the commit */
    rc = 1;
out:
    if (rc < 0 || (rc == 0 && s->nest)) {
        pic_rollback(s);
    }
    free(prompt);
    free(line);
    return rc;
}

/* ---- the due check ---------------------------------------------------------------------------- */

static int (*wake_start)(const char *db, const char *workspace, const char *session);

void pic_wake_starter(int (*start)(const char *db, const char *workspace, const char *session)) { wake_start = start; }

/* The conversations a run was started for lately, so a fire that a run cannot take up (its model
 * has no key) is not started again on every look. */
static struct {
    char session[64];
    long long at;
} wake_started[16];

static int wake_recent(const char *session, long long now) {
    int oldest = 0;
    for (int i = 0; i < 16; i++) {
        if (strcmp(wake_started[i].session, session) == 0) {
            if (now - wake_started[i].at < 30000 && now >= wake_started[i].at) {
                return 1;
            }
            oldest = i;
            break;
        }
        if (wake_started[i].at < wake_started[oldest].at) {
            oldest = i;
        }
    }
    (void)snprintf(wake_started[oldest].session, sizeof wake_started[oldest].session, "%s", session);
    wake_started[oldest].at = now;
    return 0;
}

/* The journal's path: the lock's, less its suffix. */
static void wake_db_path(pic_store *s, char *out, size_t cap) {
    size_t n = s->lock_path ? strlen(s->lock_path) : 0, suffix = strlen(".pic-lock");
    out[0] = '\0';
    if (n > suffix && n - suffix < cap) {
        memcpy(out, s->lock_path, n - suffix);
        out[n - suffix] = '\0';
    }
}

/* The next time a wake of SESSION (NULL: any) is due, wall ms; 0 when none is. 0 or -1. */
static int wake_next(pic_store *s, const char *session, long long *next_ms) {
    return wake_int(s,
                    "SELECT coalesce(min(min(coalesce(w.due_ms, w.expires_ms), w.expires_ms)), 0) FROM pic_wake w"
                    " WHERE w.state = 'active' AND (?2 IS NULL OR w.session_id = ?2) AND NOT " WAKE_WAITING_SQL("w")
                    " AND ?1 = ?1",
                    0, session, next_ms);
}

int pic_wake_due(pic_store *s, const char *workspace, const char *session, int start, int *fired, long long *next_ms) {
    sqlite3_stmt *q = NULL;
    long long now = pic_wake_now_ms(), ids[64];
    size_t n = 0;
    int rc = 0;
    *fired = 0;
    *next_ms = 0;
    /* A read first: every look must not take the write lock to learn nothing. */
    if (sqlite3_prepare_v2(s->db,
                           "SELECT w.id FROM pic_wake w WHERE " WAKE_DUE_SQL("w") " AND (?2 IS NULL OR w.session_id = ?2)"
                           " AND (NOT " WAKE_WAITING_SQL("w") " OR w.expires_ms <= ?1) ORDER BY w.due_ms, w.id LIMIT 64",
                           -1, &q, NULL) != SQLITE_OK) {
        return wake_sql_fail(s);
    }
    sqlite3_bind_int64(q, 1, now);
    if (session) {
        sqlite3_bind_text(q, 2, session, -1, SQLITE_STATIC);
    }
    while (sqlite3_step(q) == SQLITE_ROW) {
        ids[n++] = sqlite3_column_int64(q, 0);
    }
    sqlite3_finalize(q);
    for (size_t i = 0; i < n && rc == 0; i++) {
        char sid[64];
        int one = wake_fire(s, ids[i], now, sid, sizeof sid);
        if (one < 0) {
            rc = -1;
        } else {
            *fired += one;
        }
    }
    /* A fire waiting in a conversation nobody works: a pic run there takes it up. */
    if (rc == 0 && start && wake_start) {
        char db[4096], (*sids)[64] = NULL;
        size_t ns = 0;
        wake_db_path(s, db, sizeof db);
        if (sqlite3_prepare_v2(s->db,
                               "SELECT DISTINCT session_id FROM pic_inbox WHERE state = 'pending' AND sender LIKE 'wake:%'"
                               " AND (?1 IS NULL OR session_id = ?1) LIMIT 16",
                               -1, &q, NULL) == SQLITE_OK) {
            if (session) {
                sqlite3_bind_text(q, 1, session, -1, SQLITE_STATIC);
            }
            sids = calloc(16, sizeof *sids);
            while (sids && sqlite3_step(q) == SQLITE_ROW && ns < 16) {
                (void)snprintf(sids[ns++], 64, "%s", (const char *)sqlite3_column_text(q, 0));
            }
        }
        sqlite3_finalize(q);
        for (size_t i = 0; i < ns && db[0]; i++) {
            if (pic_lease_holder(s, sids[i]) == 0 && !wake_recent(sids[i], now)) {
                (void)wake_start(db, workspace, sids[i]);
            }
        }
        free(sids);
    }
    return rc == 0 ? wake_next(s, session, next_ms) : rc;
}

/* ---- listing ---------------------------------------------------------------------------------- */

/* SQL: wake W's spend, summed from the journal's usage rows of the requests it started. */
#define WAKE_SPEND_SQL(W, FIELD)                                                                                       \
    "(SELECT coalesce(sum(json_extract(g.usage, '$." FIELD "')), 0) FROM pic_generation g JOIN pic_submission u"       \
    " ON u.id = g.submission_id WHERE u.session_id = " W ".session_id AND " PIC_WAKE_OF_SQL("u") " = " W ".id)"

char *pic_wake_list(pic_store *s, const char *session, int all) {
    sqlite3_stmt *q = NULL;
    char *out = NULL;
    int rc;
    if (sqlite3_prepare_v2(
            s->db,
            "SELECT json_group_array(json_object('id', w.id, 'name', upper(substr(w.kind, 1, 1)) || w.id, 'kind', w.kind,"
            " 'session', w.session_id, 'prompt', w.prompt, 'everyMs', w.every_ms, 'state', w.state, 'why', w.why,"
            " 'creator', w.creator, 'fires', w.fires, 'dueMs', w.due_ms, 'firedMs', w.fired_ms, 'createdMs', w.created_ms,"
            " 'expiresMs', w.expires_ms, 'cost', " WAKE_SPEND_SQL("w", "pic_cost.total") ", 'tokens',"
            " " WAKE_SPEND_SQL("w", "pic_tokens.totalTokens") ", 'waiting', json(iif(" WAKE_WAITING_SQL("w") ", 'true', 'false')),"
            " 'late', json(iif(w.state = 'active' AND NOT " WAKE_WAITING_SQL("w") " AND w.due_ms < ?1 - ?3, 'true', 'false'))))"
            " FROM (SELECT * FROM pic_wake WHERE (?2 IS NULL OR session_id = ?2) AND (?4 OR state != 'ended') ORDER BY id) w",
            -1, &q, NULL) != SQLITE_OK) {
        (void)wake_sql_fail(s);
        return NULL;
    }
    sqlite3_bind_int64(q, 1, pic_wake_now_ms());
    if (session) {
        sqlite3_bind_text(q, 2, session, -1, SQLITE_STATIC);
    }
    sqlite3_bind_int64(q, 3, PIC_WAKE_LATE_MS);
    sqlite3_bind_int(q, 4, all);
    rc = sqlite3_step(q);
    if (rc == SQLITE_ROW && sqlite3_column_text(q, 0)) {
        out = strdup((const char *)sqlite3_column_text(q, 0));
    }
    sqlite3_finalize(q);
    if (!out) {
        (void)(rc == SQLITE_ROW ? wake_fail(s, -1, "out of memory") : wake_sql_fail(s));
    }
    return out;
}

int pic_usage_by_wake(pic_store *s, int json, FILE *out) {
    sqlite3_stmt *q = NULL;
    if (sqlite3_prepare_v2(s->db,
                           "SELECT upper(substr(w.kind, 1, 1)) || w.id, w.kind, w.state, w.fires,"
                           " (SELECT count(*) FROM pic_submission u WHERE u.session_id = w.session_id AND " PIC_WAKE_OF_SQL("u") " = w.id),"
                           " " WAKE_SPEND_SQL("w", "pic_tokens.totalTokens") ", " WAKE_SPEND_SQL("w", "pic_cost.total") ","
                           " w.session_id, pic_line(w.prompt, 40) FROM pic_wake w ORDER BY w.id",
                           -1, &q, NULL) != SQLITE_OK) {
        return wake_sql_fail(s);
    }
    if (!json) {
        fprintf(out, "%-6s %-8s %-7s %6s %9s %10s %9s  %s\n", "WAKE", "KIND", "STATE", "FIRES", "REQUESTS", "TOKENS", "COST", "PROMPT");
    }
    while (sqlite3_step(q) == SQLITE_ROW) {
        if (json) {
            sqlite3_str *t = sqlite3_str_new(NULL);
            char *line;
            sqlite3_str_appendall(t, "{\"wake\":");
            pic_rpc_quote(t, (const char *)sqlite3_column_text(q, 0));
            sqlite3_str_appendall(t, ",\"kind\":");
            pic_rpc_quote(t, (const char *)sqlite3_column_text(q, 1));
            sqlite3_str_appendall(t, ",\"state\":");
            pic_rpc_quote(t, (const char *)sqlite3_column_text(q, 2));
            sqlite3_str_appendf(t, ",\"fires\":%lld,\"requests\":%lld,\"tokens\":%lld,\"cost\":%.6f,\"session\":",
                                (long long)sqlite3_column_int64(q, 3), (long long)sqlite3_column_int64(q, 4),
                                (long long)sqlite3_column_int64(q, 5), sqlite3_column_double(q, 6));
            pic_rpc_quote(t, (const char *)sqlite3_column_text(q, 7));
            sqlite3_str_appendall(t, "}");
            line = sqlite3_str_finish(t);
            if (line) {
                fprintf(out, "%s\n", line);
            }
            sqlite3_free(line);
        } else {
            fprintf(out, "%-6s %-8s %-7s %6lld %9lld %10lld %9.4f  %s\n", (const char *)sqlite3_column_text(q, 0),
                    (const char *)sqlite3_column_text(q, 1), (const char *)sqlite3_column_text(q, 2),
                    (long long)sqlite3_column_int64(q, 3), (long long)sqlite3_column_int64(q, 4),
                    (long long)sqlite3_column_int64(q, 5), sqlite3_column_double(q, 6),
                    sqlite3_column_text(q, 8) ? (const char *)sqlite3_column_text(q, 8) : "");
        }
    }
    sqlite3_finalize(q);
    return 0;
}

/* ---- RPC commands ----------------------------------------------------------------------------- */

/* The journal for a command, opened narrowly from the call's path; with CREATE, one not made yet
 * is made (a loop started before the conversation's first request). 0, or -1 with c->err. */
static int wake_open(pic_rpc_call *c, pic_store *s, int create) {
    if (!c->db || !*c->db) {
        (void)snprintf(c->err, sizeof c->err, "no journal");
        return -1;
    }
    if (create && pic_open_narrow(s, c->db) != 0) {
        pic_close(s);
        if (pic_open(s, c->db) == 0) {
            return 0;
        }
        (void)snprintf(c->err, sizeof c->err, "%s", s->err);
        pic_close(s);
        return -1;
    }
    if (create) {
        return 0;
    }
    if (pic_open_narrow(s, c->db) != 0) {
        (void)snprintf(c->err, sizeof c->err, "%s", s->err);
        pic_close(s);
        return -1;
    }
    return 0;
}

static int wake_flag(const pic_rpc_call *c, const char *path) {
    char *v = pic_rpc_text(c, path);
    int on = v && (strcmp(v, "1") == 0 || strcmp(v, "true") == 0);
    free(v);
    return on;
}

/* c->data: {"wake": THE ONE, "wakes": SESSION's} after an action on wake ID. */
static int wake_reply(pic_rpc_call *c, pic_store *s, long long id, const char *session, const char *extra) {
    sqlite3_stmt *q = NULL;
    char *list = pic_wake_list(s, session, 0), *all = id ? pic_wake_list(s, NULL, 1) : NULL;
    int rc = -1;
    if (!list || (id && !all)) {
        (void)snprintf(c->err, sizeof c->err, "%s", s->err);
    } else if (sqlite3_prepare_v2(s->db,
                                  "SELECT json_object('wake', json((SELECT value FROM json_each(?1) WHERE json_extract(value, '$.id') = ?2)),"
                                  " 'wakes', json(?3), 'session', ?4) || ''",
                                  -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, all ? all : "[]", -1, SQLITE_STATIC);
        sqlite3_bind_int64(q, 2, id);
        sqlite3_bind_text(q, 3, list, -1, SQLITE_STATIC);
        if (session) {
            sqlite3_bind_text(q, 4, session, -1, SQLITE_STATIC);
        }
        if (sqlite3_step(q) == SQLITE_ROW) {
            const char *j = (const char *)sqlite3_column_text(q, 0);
            size_t n = strlen(j), e = extra ? strlen(extra) : 0;
            if ((c->data = malloc(n + e + 2))) {
                memcpy(c->data, j, n - 1); /* without its closing brace, for EXTRA */
                (void)snprintf(c->data + n - 1, e + 3, "%s}", extra ? extra : "");
                rc = 0;
            }
        }
    }
    sqlite3_finalize(q);
    free(list);
    free(all);
    return rc;
}

static int rpc_get_wakes(pic_rpc_call *c) {
    pic_store s;
    char *session = pic_rpc_text(c, "$.session"), extra[160] = "";
    const char *which = session ? (strcmp(session, "all") == 0 ? NULL : session) : (c->session[0] ? c->session : NULL);
    int fired = 0, rc;
    long long next = 0;
    if (wake_open(c, &s, 0) != 0) {
        free(session);
        if (strncmp(c->err, "no journal", 10) == 0) { /* nothing run here yet: none */
            c->data = strdup("{\"wake\":null,\"wakes\":[],\"session\":null,\"fired\":0,\"nextDueMs\":0}");
            return c->data ? 0 : -1;
        }
        return -1;
    }
    if (wake_flag(c, "$.fire") ? pic_wake_due(&s, c->workspace, NULL, 1, &fired, &next) != 0 || wake_next(&s, which, &next) != 0
                               : wake_next(&s, which, &next) != 0) {
        (void)snprintf(c->err, sizeof c->err, "%s", s.err);
        pic_close(&s);
        free(session);
        return -1;
    }
    (void)snprintf(extra, sizeof extra, ",\"fired\":%d,\"nextDueMs\":%lld,\"nowMs\":%lld", fired, next, pic_wake_now_ms());
    rc = wake_reply(c, &s, 0, which, extra);
    pic_close(&s);
    free(session);
    return rc;
}

static int rpc_create_wake(pic_rpc_call *c) {
    pic_store s;
    pic_wake_new w;
    char *prompt = pic_rpc_text(c, "$.prompt"), *every = pic_rpc_text(c, "$.every"), *kind = pic_rpc_text(c, "$.kind"),
         *session = pic_rpc_text(c, "$.session"), sid[64] = "";
    long long id = 0, ms = 0;
    int rc = -1;
    memset(&w, 0, sizeof w);
    if (every && *every && pic_wake_parse_every(every, &ms) != 0) {
        (void)snprintf(c->err, sizeof c->err, "%.60s is not an interval (5m, 90s, 2h, 1d)", every);
    } else if (wake_open(c, &s, 1) == 0) {
        w.session = session ? session : c->session;
        w.kind = kind ? kind : "loop";
        w.prompt = prompt;
        w.every_ms = ms;
        w.creator = "user";
        w.model = c->model;
        rc = pic_wake_create(&s, &w, &id, sid, sizeof sid);
        if (rc != 0) {
            (void)snprintf(c->err, sizeof c->err, "%s", s.err);
            rc = -1;
        } else {
            rc = wake_reply(c, &s, id, sid, NULL);
        }
        pic_close(&s);
    }
    free(prompt);
    free(every);
    free(kind);
    free(session);
    return rc;
}

static int wake_action(pic_rpc_call *c, const char *action) {
    pic_store s;
    char *name = pic_rpc_text(c, "$.id"), sid[64] = "";
    long long id = 0;
    int rc = -1;
    if (!name) {
        (void)snprintf(c->err, sizeof c->err, "id is required (L1, M2, G3)");
        return -1;
    }
    if (wake_open(c, &s, 0) == 0) {
        if (pic_wake_resolve(&s, name, &id) != 0 || pic_wake_set(&s, id, action, NULL) != 0) {
            (void)snprintf(c->err, sizeof c->err, "%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, id);
                if (sqlite3_step(q) == SQLITE_ROW) {
                    (void)snprintf(sid, sizeof sid, "%s", (const char *)sqlite3_column_text(q, 0));
                }
            }
            sqlite3_finalize(q);
            rc = wake_reply(c, &s, id, sid, NULL);
        }
        pic_close(&s);
    }
    free(name);
    return rc;
}

static int rpc_pause_wake(pic_rpc_call *c) { return wake_action(c, "pause"); }
static int rpc_resume_wake(pic_rpc_call *c) { return wake_action(c, "resume"); }
static int rpc_stop_wake(pic_rpc_call *c) { return wake_action(c, "stop"); }

static int rpc_pause_wakes(pic_rpc_call *c) {
    pic_store s;
    char *session = pic_rpc_text(c, "$.session"), extra[40];
    const char *which = session ? session : c->session;
    int count = 0, rc = -1;
    if (!which || !*which) { /* a conversation not begun has none */
        free(session);
        c->data = strdup("{\"wake\":null,\"wakes\":[],\"session\":null,\"paused\":0}");
        return c->data ? 0 : -1;
    }
    if (wake_open(c, &s, 0) == 0) {
        if (pic_wake_pause_all(&s, which, NULL, &count) != 0) {
            (void)snprintf(c->err, sizeof c->err, "%s", s.err);
        } else {
            (void)snprintf(extra, sizeof extra, ",\"paused\":%d", count);
            rc = wake_reply(c, &s, 0, which, extra);
        }
        pic_close(&s);
    }
    free(session);
    return rc;
}

const pic_rpc_command pic_get_wakes_rpc = {"get_wakes", "the conversation's loops, monitors and goals; fire: true fires what is due",
                                           PIC_RPC_JOURNAL_FREE | PIC_RPC_IMMEDIATE, rpc_get_wakes};
const pic_rpc_command pic_create_wake_rpc = {"create_wake", "start a loop in the conversation: prompt, every",
                                             PIC_RPC_JOURNAL_FREE | PIC_RPC_IMMEDIATE, rpc_create_wake};
const pic_rpc_command pic_pause_wake_rpc = {"pause_wake", "pause a loop, monitor or goal by id",
                                            PIC_RPC_JOURNAL_FREE | PIC_RPC_IMMEDIATE, rpc_pause_wake};
const pic_rpc_command pic_resume_wake_rpc = {"resume_wake", "resume a paused loop, monitor or goal by id",
                                             PIC_RPC_JOURNAL_FREE | PIC_RPC_IMMEDIATE, rpc_resume_wake};
const pic_rpc_command pic_stop_wake_rpc = {"stop_wake", "end a loop, monitor or goal by id",
                                           PIC_RPC_JOURNAL_FREE | PIC_RPC_IMMEDIATE, rpc_stop_wake};
const pic_rpc_command pic_pause_wakes_rpc = {"pause_wakes", "pause every loop, monitor and goal of the conversation (/stop)",
                                             PIC_RPC_JOURNAL_FREE | PIC_RPC_IMMEDIATE, rpc_pause_wakes};