Skip to content
pi-c Artifact [beaf6cbffe]
Login

Artifact [beaf6cbffe]

Artifact beaf6cbffe4dd46cea35aab7aa339b0d80591144c799531a87a83377478e8d0a:


/* Asks: see ask.h and docs/dev/asks.md. Core: the record, the one answer, the wait. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#include "ask.h"
#include "net.h"
#include "platform.h"
#include "wake.h"

static long long ask_now_ms(void) { return pic_wake_now_ms(); }

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

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

/* Whether this journal has asks at all: a journal no pic of this version opened fully has none. */
static int ask_table(pic_store *s) {
    sqlite3_stmt *q = NULL;
    int has = 0;
    if (sqlite3_prepare_v2(s->db, "SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = 'pic_ask'", -1, &q, NULL) == SQLITE_OK) {
        has = sqlite3_step(q) == SQLITE_ROW;
    }
    sqlite3_finalize(q);
    return has;
}

/* The next version: every open and close of an ask takes one, so a reader follows them by index. */
#define ASK_NEXT_VERSION "(SELECT coalesce(max(version), 0) + 1 FROM pic_ask)"

/* 16 random bytes as base64url, no padding: PIC_ASK_ID_LEN characters. */
static int ask_fresh_id(char id[PIC_ASK_ID_LEN + 1]) {
    static const char a[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
    unsigned char b[18] = {0};
    size_t o = 0;
    if (pic_platform_get()->entropy(b, 16) != 0) {
        return -1;
    }
    for (size_t i = 0; i < 18 && o < PIC_ASK_ID_LEN; i += 3) {
        unsigned v = (unsigned)b[i] << 16 | (unsigned)b[i + 1] << 8 | b[i + 2];
        for (int k = 3; k >= 0 && o < PIC_ASK_ID_LEN; k--) {
            id[o++] = a[(v >> (6 * k)) & 63];
        }
    }
    id[PIC_ASK_ID_LEN] = '\0';
    return id[0] == '-' ? ask_fresh_id(id) : 0; /* never read as a flag: pic answer ID VALUE */
}

/* A select's options, each made {"label", "destructive", "default"} with its label cut to
 * PIC_ASK_LABEL_MAX (malloc'd), or NULL with s->err when they are not 1 to 10 distinct labels with
 * at most one default. */
static char *ask_options(pic_store *s, const char *options) {
    sqlite3_stmt *q = NULL;
    char *out = NULL;
    if (sqlite3_prepare_v2(s->db,
                           "WITH o(k, label, destructive, dflt) AS (SELECT key, substr(CASE type WHEN 'text' THEN value"
                           " WHEN 'object' THEN json_extract(value, '$.label') END, 1, ?2), CASE WHEN type = 'object' THEN"
                           " json_extract(value, '$.destructive') END IS 1, CASE WHEN type = 'object' THEN json_extract(value,"
                           " '$.default') END IS 1 FROM json_each(iif(json_valid(?1) AND json_type(?1) = 'array', ?1, '[]')))"
                           " SELECT json_group_array(json(json_patch(json_object('label', label), json_object('destructive',"
                           " iif(destructive, json('true'), NULL), 'default', iif(dflt, json('true'), NULL))))) FROM (SELECT * FROM o ORDER BY k)"
                           " WHERE (SELECT count(*) FROM o) BETWEEN 1 AND ?3 AND NOT EXISTS (SELECT 1 FROM o WHERE"
                           " typeof(label) != 'text' OR length(label) = 0) AND (SELECT count(*) FROM o WHERE dflt) <= 1"
                           " AND (SELECT count(DISTINCT label) FROM o) = (SELECT count(*) FROM o)"
                           " HAVING count(*) > 0",
                           -1, &q, NULL) != SQLITE_OK) {
        (void)ask_sql_fail(s);
        return NULL;
    }
    sqlite3_bind_text(q, 1, options ? options : "[]", -1, SQLITE_STATIC);
    sqlite3_bind_int(q, 2, PIC_ASK_LABEL_MAX);
    sqlite3_bind_int(q, 3, PIC_ASK_OPTIONS_MAX);
    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);
    if (!out) {
        (void)ask_fail(s, 1, "a select needs 1 to 10 distinct labels, with at most one default");
    }
    return out;
}

int pic_ask_open(pic_store *s, const pic_ask_new *a, char id[PIC_ASK_ID_LEN + 1]) {
    sqlite3_stmt *q = NULL;
    char sid[64] = "", *options = NULL;
    long long now = ask_now_ms();
    int rc;
    const char *kind = a->kind ? a->kind : "";
    id[0] = '\0';
    if (!a->key || !*a->key || strlen(a->key) > 200) {
        return ask_fail(s, 1, "an ask needs a key");
    }
    if (strcmp(kind, "confirm") != 0 && strcmp(kind, "select") != 0 && strcmp(kind, "input") != 0) {
        return ask_fail(s, 1, "an ask is a confirm, a select or an input");
    }
    if (!a->title || !*a->title) {
        return ask_fail(s, 1, "an ask needs a title");
    }
    if (!ask_table(s)) {
        return ask_fail(s, 1, "this journal keeps no asks: a pic of this version has not opened it");
    }
    if (pic_begin(s) != 0) {
        return -1;
    }
    if (sqlite3_prepare_v2(s->db, "SELECT id FROM pic_ask WHERE ask_key = ?1", -1, &q, NULL) != SQLITE_OK) {
        rc = ask_sql_fail(s);
        pic_rollback(s);
        return rc;
    }
    sqlite3_bind_text(q, 1, a->key, -1, SQLITE_STATIC);
    if (sqlite3_step(q) == SQLITE_ROW) {
        (void)snprintf(id, PIC_ASK_ID_LEN + 1, "%s", (const char *)sqlite3_column_text(q, 0));
    }
    sqlite3_finalize(q);
    q = NULL;
    if (id[0]) { /* asked already: the same question */
        return pic_commit(s) == 0 ? 0 : (pic_rollback(s), -1);
    }
    if (pic_session_resolve(s, a->session, sid, sizeof sid) != 0) {
        pic_rollback(s);
        return 1;
    }
    if (strcmp(kind, "select") == 0 && !(options = ask_options(s, a->options))) {
        pic_rollback(s);
        return 1;
    }
    if (ask_fresh_id(id) != 0) {
        pic_rollback(s);
        return ask_fail(s, -1, "no entropy for an ask's id");
    }
    if (sqlite3_prepare_v2(s->db,
                           "INSERT INTO pic_ask(id, ask_key, session_id, submission_id, kind, title, body, spec, created_ms, expires_ms,"
                           " state, version) VALUES(?10, ?1, ?2, nullif(?11, 0), ?3, substr(?4, 1, ?12), substr(nullif(?5, ''), 1, ?13),"
                           " CASE ?3 WHEN 'select' THEN json_object('options', json(?6))"
                           " WHEN 'input' THEN iif(?7 IS NULL, NULL, json_object('placeholder', substr(?7, 1, ?12))) END, ?8, ?9, 'open', " ASK_NEXT_VERSION ")",
                           -1, &q, NULL) != SQLITE_OK) {
        free(options);
        rc = ask_sql_fail(s);
        pic_rollback(s);
        return rc;
    }
    sqlite3_bind_text(q, 1, a->key, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 2, sid, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 3, kind, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 4, a->title, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 5, a->body ? a->body : "", -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 6, options ? options : "null", -1, SQLITE_STATIC);
    if (a->placeholder) {
        sqlite3_bind_text(q, 7, a->placeholder, -1, SQLITE_STATIC);
    }
    sqlite3_bind_int64(q, 8, now);
    sqlite3_bind_int64(q, 9, a->expires_ms > 0 ? a->expires_ms : now + PIC_ASK_EXPIRY_MS);
    sqlite3_bind_text(q, 10, id, -1, SQLITE_STATIC);
    sqlite3_bind_int64(q, 11, a->submission);
    sqlite3_bind_int(q, 12, PIC_ASK_TITLE_MAX);
    sqlite3_bind_int(q, 13, PIC_ASK_BODY_MAX);
    rc = sqlite3_step(q);
    sqlite3_finalize(q);
    free(options);
    if (rc != SQLITE_DONE) {
        rc = ask_sql_fail(s);
        pic_rollback(s);
        return rc;
    }
    if (pic_commit(s) != 0) {
        pic_rollback(s);
        return -1;
    }
    return 0;
}

int pic_ask_state(pic_store *s, const char *id, char *state, size_t cap, char **value) {
    sqlite3_stmt *q = NULL;
    int rc;
    state[0] = '\0';
    if (value) {
        *value = NULL;
    }
    if (sqlite3_prepare_v2(s->db,
                           "SELECT iif(state = 'open' AND expires_ms <= ?2, 'expired', state), answer FROM pic_ask WHERE id = ?1", -1,
                           &q, NULL) != SQLITE_OK) {
        return ask_table(s) ? ask_sql_fail(s) : 0;
    }
    sqlite3_bind_text(q, 1, id, -1, SQLITE_STATIC);
    sqlite3_bind_int64(q, 2, ask_now_ms());
    rc = sqlite3_step(q);
    if (rc == SQLITE_ROW) {
        (void)snprintf(state, cap, "%s", (const char *)sqlite3_column_text(q, 0));
        if (value && sqlite3_column_type(q, 1) != SQLITE_NULL) {
            *value = strdup((const char *)sqlite3_column_text(q, 1));
        }
    }
    sqlite3_finalize(q);
    return rc == SQLITE_ROW || rc == SQLITE_DONE ? 0 : ask_sql_fail(s);
}

int pic_ask_wait(pic_store *s, const char *id, char *state, size_t cap, char **value) {
    for (;;) {
        if (pic_ask_state(s, id, state, cap, value) != 0) {
            return -1;
        }
        if (strcmp(state, "open") != 0) {
            return state[0] ? 0 : ask_fail(s, -1, "no such ask");
        }
        if (pic_interrupted) {
            return 1;
        }
        struct timespec ts = {0, 100000000L};
        (void)nanosleep(&ts, NULL);
    }
}

/* Closes KEY's open ask as TO (answered, with VALUE and BY; or withdrawn), inside a transaction. */
static int ask_close_key(pic_store *s, const char *key, const char *to, const char *value, const char *by) {
    sqlite3_stmt *q = NULL;
    int rc;
    if (!ask_table(s)) {
        return 0;
    }
    if (sqlite3_prepare_v2(s->db,
                           "UPDATE pic_ask SET state = ?2, answer = ?3, answered_by = ?4, answered_ms = iif(?3 IS NULL AND ?4 IS NULL, NULL, ?5),"
                           " version = " ASK_NEXT_VERSION " WHERE ask_key = ?1 AND state = 'open'",
                           -1, &q, NULL) != SQLITE_OK) {
        return ask_sql_fail(s);
    }
    sqlite3_bind_text(q, 1, key, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 2, to, -1, SQLITE_STATIC);
    if (value) {
        sqlite3_bind_text(q, 3, value, -1, SQLITE_STATIC);
    }
    if (by) {
        sqlite3_bind_text(q, 4, by, -1, SQLITE_STATIC);
    }
    sqlite3_bind_int64(q, 5, ask_now_ms());
    rc = sqlite3_step(q);
    sqlite3_finalize(q);
    return rc == SQLITE_DONE ? 0 : ask_sql_fail(s);
}

int pic_ask_settle(pic_store *s, const char *key, const char *value, const char *by) {
    return ask_close_key(s, key, "answered", value, by);
}

int pic_ask_withdraw(pic_store *s, const char *key) {
    if (pic_begin(s) != 0) {
        return -1;
    }
    if (ask_close_key(s, key, "withdrawn", NULL, NULL) != 0) {
        pic_rollback(s);
        return -1;
    }
    return pic_commit(s) == 0 ? 0 : (pic_rollback(s), -1);
}

/* {"state","value","answeredBy"} of ask ID, malloc'd. */
static char *ask_standing(pic_store *s, const char *id) {
    sqlite3_stmt *q = NULL;
    char *out = NULL;
    if (sqlite3_prepare_v2(s->db,
                           "SELECT json_object('state', iif(state = 'open' AND expires_ms <= ?2, 'expired', state), 'value', json(answer),"
                           " 'answeredBy', answered_by) FROM pic_ask WHERE id = ?1",
                           -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, id, -1, SQLITE_STATIC);
        sqlite3_bind_int64(q, 2, ask_now_ms());
        if (sqlite3_step(q) == SQLITE_ROW) {
            out = strdup((const char *)sqlite3_column_text(q, 0));
        }
    }
    sqlite3_finalize(q);
    return out;
}

/* Whether ask ID was answered by BY with VALUE (the same JSON value): a retry of one's own answer. */
static int ask_mine(pic_store *s, const char *id, const char *value, const char *by) {
    sqlite3_stmt *q = NULL;
    int mine = 0;
    if (sqlite3_prepare_v2(s->db,
                           "SELECT 1 FROM pic_ask WHERE id = ?1 AND state = 'answered' AND answered_by = ?2 AND json(answer) = json(?3)", -1,
                           &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, id, -1, SQLITE_STATIC);
        sqlite3_bind_text(q, 2, by, -1, SQLITE_STATIC);
        sqlite3_bind_text(q, 3, value, -1, SQLITE_STATIC);
        mine = sqlite3_step(q) == SQLITE_ROW;
    }
    sqlite3_finalize(q);
    return mine;
}

static int ask_already(pic_store *s, const char *id, const char *value, const char *by, char **standing) {
    char state[16] = "";
    if (ask_mine(s, id, value, by)) {
        return PIC_ASK_ANSWERED;
    }
    if (standing) {
        *standing = ask_standing(s, id);
    }
    (void)pic_ask_state(s, id, state, sizeof state, NULL);
    return strcmp(state, "expired") == 0 ? PIC_ASK_EXPIRED : PIC_ASK_ALREADY;
}

/* An open ask past its expiry, closed as expired, so its readers are told (a version). */
static void ask_expire(pic_store *s, const char *id) {
    sqlite3_stmt *q = NULL;
    if (pic_begin(s) != 0) {
        return;
    }
    if (sqlite3_prepare_v2(s->db, "UPDATE pic_ask SET state = 'expired', version = " ASK_NEXT_VERSION
                                  " WHERE id = ?1 AND state = 'open' AND expires_ms <= ?2", -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, id, -1, SQLITE_STATIC);
        sqlite3_bind_int64(q, 2, ask_now_ms());
        (void)sqlite3_step(q);
    }
    sqlite3_finalize(q);
    if (pic_commit(s) != 0) {
        pic_rollback(s);
    }
}

int pic_ask_answer(pic_store *s, const char *id, const char *value, const char *by, char **standing) {
    sqlite3_stmt *q = NULL;
    char key[220] = "", kind[16] = "", state[16] = "", fit[16] = "";
    long long now = ask_now_ms();
    int rc, yes = 0;
    if (standing) {
        *standing = NULL;
    }
    if (!value || !by || !*by) {
        return ask_fail(s, PIC_ASK_REFUSED, "an answer needs a value");
    }
    if (!id || !ask_table(s)) {
        (void)snprintf(s->err, sizeof s->err, "no question %s", id ? id : "");
        return PIC_ASK_REFUSED;
    }
    /* What it asks, and whether VALUE answers it: "ok", "null" (a dismissal), or "" (not an answer). */
    if (sqlite3_prepare_v2(s->db,
                           "SELECT ask_key, kind, iif(state = 'open' AND expires_ms <= ?3, 'expired', state),"
                           " CASE WHEN NOT json_valid(?2) THEN '' WHEN json_type(?2) = 'null' THEN 'null'"
                           " WHEN kind = 'confirm' AND json_type(?2) IN ('true', 'false') THEN 'ok'"
                           " WHEN kind = 'input' AND json_type(?2) = 'text' AND length(json_extract(?2, '$')) <= ?4 THEN 'ok'"
                           " WHEN kind = 'select' AND json_type(?2) = 'text' AND EXISTS (SELECT 1 FROM json_each(spec, '$.options') o"
                           "  WHERE json_extract(o.value, '$.label') = json_extract(?2, '$')) THEN 'ok' ELSE '' END, json_valid(?2) AND json_type(?2) = 'true' FROM pic_ask WHERE id = ?1",
                           -1, &q, NULL) != SQLITE_OK) {
        return ask_sql_fail(s);
    }
    sqlite3_bind_text(q, 1, id, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 2, value, -1, SQLITE_STATIC);
    sqlite3_bind_int64(q, 3, now);
    sqlite3_bind_int(q, 4, PIC_ASK_TEXT_MAX);
    if (sqlite3_step(q) == SQLITE_ROW) {
        (void)snprintf(key, sizeof key, "%s", (const char *)sqlite3_column_text(q, 0));
        (void)snprintf(kind, sizeof kind, "%s", (const char *)sqlite3_column_text(q, 1));
        (void)snprintf(state, sizeof state, "%s", (const char *)sqlite3_column_text(q, 2));
        (void)snprintf(fit, sizeof fit, "%s", (const char *)sqlite3_column_text(q, 3));
        yes = sqlite3_column_int(q, 4);
    }
    sqlite3_finalize(q);
    q = NULL;
    if (!key[0]) {
        (void)snprintf(s->err, sizeof s->err, "no question %s", id);
        return PIC_ASK_REFUSED;
    }
    if (strcmp(state, "expired") == 0) {
        ask_expire(s, id);
    }
    if (strcmp(state, "open") != 0) {
        return ask_already(s, id, value, by, standing);
    }
    if (!fit[0]) {
        return ask_fail(s, PIC_ASK_REFUSED,
                        strcmp(kind, "confirm") == 0  ? "a confirm is answered true or false"
                        : strcmp(kind, "select") == 0 ? "a select is answered with one of its labels"
                                                      : "an input is answered with text of at most 4000 characters");
    }
    if (strncmp(key, "wake:", 5) == 0) { /* a loop or goal the model asked for: its decision is the answer */
        if (strcmp(fit, "null") == 0) {
            return ask_fail(s, PIC_ASK_REFUSED, "a loop or goal is approved (true) or declined (false)");
        }
        rc = pic_wake_answer(s, strtoll(key + 5, NULL, 10), yes, by);
        if (rc == 0) {
            return PIC_ASK_ANSWERED;
        }
        if (rc < 0) {
            return -1;
        }
        s->err[0] = '\0';
        return ask_already(s, id, value, by, standing);
    }
    if (pic_begin(s) != 0) {
        return -1;
    }
    /* first writer wins: the row is still open inside this IMMEDIATE transaction, or it is not */
    if (sqlite3_prepare_v2(s->db,
                           "UPDATE pic_ask SET state = 'answered', answer = json(?2), answered_by = ?3, answered_ms = ?4, version = " ASK_NEXT_VERSION
                           " WHERE id = ?1 AND state = 'open' AND expires_ms > ?4",
                           -1, &q, NULL) != SQLITE_OK) {
        rc = ask_sql_fail(s);
        pic_rollback(s);
        return rc;
    }
    sqlite3_bind_text(q, 1, id, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 2, value, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 3, by, -1, SQLITE_STATIC);
    sqlite3_bind_int64(q, 4, now);
    rc = sqlite3_step(q);
    sqlite3_finalize(q);
    if (rc != SQLITE_DONE) {
        rc = ask_sql_fail(s);
        pic_rollback(s);
        return rc;
    }
    if (sqlite3_changes(s->db) == 0) { /* another answer came first, or it expired just now */
        pic_rollback(s);
        ask_expire(s, id);
        return ask_already(s, id, value, by, standing);
    }
    pic_fault("ask_answer");
    if (pic_commit(s) != 0) {
        pic_rollback(s);
        return -1;
    }
    pic_fault("ask_answer");
    return PIC_ASK_ANSWERED;
}

char *pic_ask_list(pic_store *s, const char *session, long long after, int max) {
    sqlite3_stmt *q = NULL;
    char *out = NULL;
    if (!ask_table(s)) {
        out = strdup("[]");
        if (!out) {
            (void)ask_fail(s, -1, "out of memory");
        }
        return out;
    }
    if (sqlite3_prepare_v2(
            s->db,
            "SELECT coalesce(json_group_array(json(j)), '[]') FROM (SELECT json_patch(json_object('id', a.id, 'session', a.session_id,"
            " 'kind', a.kind, 'title', a.title, 'createdMs', a.created_ms, 'expiresMs', a.expires_ms, 'state', iif(a.state = 'open'"
            " AND a.expires_ms <= ?4, 'expired', a.state), 'version', a.version), json_object('body', a.body, 'options',"
            " json_extract(a.spec, '$.options'), 'placeholder', json_extract(a.spec, '$.placeholder'), 'value', json(a.answer),"
            " 'answeredBy', a.answered_by, 'wake', CASE WHEN a.ask_key LIKE 'wake:%' THEN (SELECT upper(substr(w.kind, 1, 1)) || w.id"
            " FROM pic_wake w WHERE w.id = CAST(substr(a.ask_key, 6) AS INTEGER)) END)) AS j FROM pic_ask a"
            " WHERE (?2 < 0 AND a.state = 'open' AND a.expires_ms > ?4 AND (?1 IS NULL OR a.session_id = ?1)) OR (?2 >= 0 AND a.version > ?2)"
            " ORDER BY iif(?2 < 0, a.rowid, a.version) LIMIT ?3)",
            -1, &q, NULL) != SQLITE_OK) {
        (void)ask_sql_fail(s);
        return NULL;
    }
    if (session) {
        sqlite3_bind_text(q, 1, session, -1, SQLITE_STATIC);
    }
    sqlite3_bind_int64(q, 2, after);
    sqlite3_bind_int(q, 3, max > 0 ? max : 100);
    sqlite3_bind_int64(q, 4, ask_now_ms());
    if (sqlite3_step(q) == SQLITE_ROW) {
        out = strdup((const char *)sqlite3_column_text(q, 0));
    }
    if (!out) {
        (void)ask_sql_fail(s);
    }
    sqlite3_finalize(q);
    return out;
}

char *pic_ask_settled(pic_store *s, const char *session) {
    sqlite3_stmt *q = NULL;
    char *out = NULL;
    if (!ask_table(s)) {
        return strdup("[]");
    }
    if (sqlite3_prepare_v2(s->db,
                           "SELECT coalesce(json_group_array(json_patch(json_object('id', a.id, 'state', a.state), json_object('value',"
                           " json(a.answer), 'answeredBy', a.answered_by))), '[]') FROM pic_ask a JOIN pic_submission u ON u.id = a.submission_id"
                           " WHERE a.session_id = ?1 AND u.status = 'admitted' AND a.state != 'open'",
                           -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, session, -1, SQLITE_STATIC);
        if (sqlite3_step(q) == SQLITE_ROW) {
            out = strdup((const char *)sqlite3_column_text(q, 0));
        }
    }
    sqlite3_finalize(q);
    return out;
}

/* ---- the commands ---------------------------------------------------------------------- */

static int ask_rpc_open(pic_rpc_call *c, pic_store *s) {
    if (!c->db || !*c->db) {
        (void)snprintf(c->err, sizeof c->err, "no journal");
        return -1;
    }
    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 rpc_get_asks(pic_rpc_call *c) {
    pic_store s;
    char *session = pic_rpc_text(c, "$.session"), *all = pic_rpc_text(c, "$.all"), *list;
    const char *which = session && *session ? session : c->session;
    int every = all && strcmp(all, "1") == 0;
    free(all);
    if ((!every && (!which || !*which)) || ask_rpc_open(c, &s) != 0) { /* nothing run here yet: none */
        free(session);
        if (c->err[0] && strncmp(c->err, "no journal", 10) != 0) {
            return -1;
        }
        c->err[0] = '\0';
        c->data = strdup("{\"asks\":[]}");
        return c->data ? 0 : -1;
    }
    list = pic_ask_list(&s, every ? NULL : which, -1, 100);
    if (!list) {
        (void)snprintf(c->err, sizeof c->err, "%s", s.err);
    } else {
        size_t n = strlen(list) + 16;
        if ((c->data = malloc(n))) {
            (void)snprintf(c->data, n, "{\"asks\":%s}", list);
        }
    }
    free(list);
    free(session);
    pic_close(&s);
    return c->data ? 0 : -1;
}

/* answer_ask {ask, value, by}: data {id, result} with result "answered", "already_answered" or
 * "expired", and the answer that stands (standing) when not this one. */
static int rpc_answer_ask(pic_rpc_call *c) {
    pic_store s;
    sqlite3 *mem = NULL;
    sqlite3_stmt *q = NULL;
    char *value = NULL, *standing = NULL, *id = NULL, *by = pic_rpc_text(c, "$.by");
    int rc = -1;
    if (sqlite3_open(":memory:", &mem) == SQLITE_OK &&
        sqlite3_prepare_v2(mem, "SELECT CASE json_type(?1, '$.ask') WHEN 'text' THEN json_extract(?1, '$.ask') END, ?1 -> '$.value',"
                                " json_type(?1, '$.value') IS NOT NULL",
                           -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, c->line, -1, SQLITE_STATIC);
        if (sqlite3_step(q) == SQLITE_ROW) {
            if (sqlite3_column_type(q, 0) != SQLITE_NULL) {
                id = strdup((const char *)sqlite3_column_text(q, 0));
            }
            if (sqlite3_column_int(q, 2)) {
                value = strdup((const char *)sqlite3_column_text(q, 1));
            }
        }
    }
    sqlite3_finalize(q);
    sqlite3_close(mem);
    if (!id || !value || strlen(id) > 64) {
        (void)snprintf(c->err, sizeof c->err, "ask (its id) and value are required");
    } else if (ask_rpc_open(c, &s) == 0) {
        rc = pic_ask_answer(&s, id, value, by && strcmp(by, "terminal") == 0 ? "terminal" : "rpc", &standing);
        if (rc == PIC_ASK_ANSWERED || rc == PIC_ASK_ALREADY || rc == PIC_ASK_EXPIRED) {
            size_t n = strlen(id) + (standing ? strlen(standing) : 4) + 96;
            if ((c->data = malloc(n))) {
                (void)snprintf(c->data, n, "{\"id\":\"%s\",\"result\":\"%s\",\"standing\":%s}", id,
                               rc == PIC_ASK_ANSWERED ? "answered" : rc == PIC_ASK_EXPIRED ? "expired" : "already_answered",
                               rc != PIC_ASK_ANSWERED && standing ? standing : "null");
            }
            rc = c->data ? 0 : -1;
        } else {
            (void)snprintf(c->err, sizeof c->err, "%s", s.err);
            rc = -1;
        }
        pic_close(&s);
    }
    free(standing);
    free(value);
    free(id);
    free(by);
    return rc;
}

const pic_rpc_command pic_get_asks_rpc = {"get_asks", "the questions the conversation waits on a person for; all: true for every conversation's",
                                          PIC_RPC_JOURNAL_FREE | PIC_RPC_IMMEDIATE, rpc_get_asks};
const pic_rpc_command pic_answer_ask_rpc = {"answer_ask", "answer a question: ask (its id), value true or false, a label, text, or null to dismiss",
                                            PIC_RPC_JOURNAL_FREE | PIC_RPC_IMMEDIATE, rpc_answer_ask};