Skip to content
pi-c Artifact [854994f848]
Login

Artifact [854994f848]

Artifact 854994f8484d21f0ab85c39066c791fe468cbfd8b99a9123814eeb7b435b909a:


/* The settings list; see settings.h. Each row's default and allowed values
 * follow the code that reads the setting (named on the row), and
 * docs/reference/settings.md names the same keys and defaults (make
 * test-docs compares them). */
#ifndef _DEFAULT_SOURCE
#define _DEFAULT_SOURCE 1
#endif
#include "settings.h"

#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "sqlite3.h"
#include "userdb.h"

#define G_MODEL "Model"
#define G_DISPLAY "Display"
#define G_MOUSE "Mouse"
#define G_BEHAVIOUR "Behaviour"
#define G_CONTEXT "Context"
#define G_FILES "Files"
#define G_PHONES "Phones"
#define G_SIGNIN "Sign-in"
#define ON_OFF {"on", "off"}
#define TRUE_FALSE {"true", "false"}
#define FALSE_TRUE {"false", "true"}
#define BIG 1000000000LL

/* Text checks (unit of a PIC_SET_TEXT row). */
#define T_MODEL "model"
#define T_TOOLS "tools"
#define T_URL "address"
#define T_LINE "text"
#define T_THEME "theme"

static const pic_setting_def pst_rows[] = {
    /* main.c: the model when --model is not given (pic models --default) */
    {"defaultModel", "", "defaultModel", NULL, G_MODEL, "Default model", PIC_SET_PICKER, {NULL}, {NULL}, 0, 0, T_MODEL,
     "pic's own", "The model a new conversation starts on. Enter opens the model picker.", PIC_APPLY_NEW_CONVERSATION},
    /* main.c, app.c: when no per-model level is saved */
    {"defaultThinkingLevel", "medium", "defaultThinkingLevel", NULL, G_MODEL, "Default thinking level", PIC_SET_CHOICE,
     {"off", "minimal", "low", "medium", "high", "xhigh", "max"}, {NULL}, 0, 0, NULL, NULL,
     "The thinking level when none is saved for the model. A model without a level uses its nearest one.",
     PIC_APPLY_NEXT_REQUEST},
    /* app.c remember_model: anything but false is on */
    {"rememberModel", "true", "rememberModel", NULL, G_MODEL, "Remember chosen model", PIC_SET_CHOICE, TRUE_FALSE, {NULL},
     0, 0, NULL, NULL, "A model you choose becomes the default model, so the next conversation starts on it.",
     PIC_APPLY_NOW},
    /* picu_scoped: Ctrl+P's scope, saved with set_scoped_models */
    {"scopedModels", "", "scopedModels", NULL, G_MODEL, "Scoped models (Ctrl+P)", PIC_SET_PICKER, {NULL}, {NULL}, 0, 0,
     NULL, "every model with a key",
     "The models Ctrl+P cycles through. Enter opens the list of patterns.", PIC_APPLY_NOW},
    /* main.c, search.c pic_toolset_configure */
    {"defaultTools", "read,bash,edit,write,send_message,wake", "defaultTools", NULL, G_MODEL, "Default tools", PIC_SET_TEXT, {NULL}, {NULL},
     0, 0, T_TOOLS, NULL,
     "The tools a request offers, as --tools takes them: names, or +name and -name to change the default; empty is none.",
     PIC_APPLY_NEXT_REQUEST},

    /* app.c theme_setting */
    {"theme", "system", "theme", NULL, G_DISPLAY, "Theme", PIC_SET_PICKER, {NULL}, {NULL}, 0, 0, T_THEME, NULL,
     "The colour theme: dark, light, light/dark, system or a custom theme. Enter opens the theme picker.",
     PIC_APPLY_NOW},
    /* app.c pic_tui_main; --tui-mode for one run */
    {"tuiMode", "fullscreen", "tuiMode", NULL, G_DISPLAY, "TUI mode", PIC_SET_CHOICE, {"fullscreen", "regular"}, {NULL},
     0, 0, NULL, NULL,
     "fullscreen draws on its own screen with a scrollable transcript; regular writes into the terminal's history.",
     PIC_APPLY_NOW},
    /* app.c thinking_hidden: only true hides */
    {"hideThinking", "false", "hideThinking", NULL, G_DISPLAY, "Hide thinking", PIC_SET_CHOICE, FALSE_TRUE, {NULL}, 0, 0,
     NULL, NULL, "Show a one-line marker instead of a reply's thinking. Ctrl+T switches it.", PIC_APPLY_NOW},
    /* markdown.c tui_hyperlinks_supported */
    {"hyperlinks", "auto", "hyperlinks", NULL, G_DISPLAY, "Hyperlinks", PIC_SET_CHOICE, {"auto", "on", "off"}, {NULL}, 0,
     0, NULL, NULL, "Links in the conversation. auto is on except where the terminal is known to show or drop them.",
     PIC_APPLY_NOW},
    /* viewport.c tui_scrollbar_mode */
    {"fullscreenScrollbar", "auto", "fullscreenScrollbar", NULL, G_DISPLAY, "Fullscreen scrollbar", PIC_SET_CHOICE,
     {"auto", "always", "hidden"}, {NULL}, 0, 0, NULL, NULL,
     "The scrollbar beside the transcript. auto shows it while you scroll.", PIC_APPLY_NOW},
    /* render.c tui_render_options: only transcript prints it */
    {"fullscreenExitOutput", "transcript", "fullscreenExitOutput", NULL, G_DISPLAY, "Fullscreen exit output",
     PIC_SET_CHOICE, {"transcript", "resume-hint"}, {NULL}, 0, 0, NULL, NULL,
     "What fullscreen leaves in the terminal when pic exits: the transcript, or only how to resume.",
     PIC_APPLY_EXIT},

    /* app.c mouse_apply: auto is on except in Apple's Terminal (mouse_auto) */
    {"mouse", "auto", "mouse", NULL, G_MOUSE, "Mouse", PIC_SET_CHOICE, {"auto", "on", "off"}, {NULL}, 0, 0, NULL, NULL,
     "Fullscreen takes the mouse for the wheel, selection and link clicks; auto is on except in Apple's Terminal.",
     PIC_APPLY_NOW},
    /* app.c fs_apply: anything but false is on */
    {"fullscreenCopyOnSelect", "true", "fullscreenCopyOnSelect", NULL, G_MOUSE, "Copy on select", PIC_SET_CHOICE,
     TRUE_FALSE, {NULL}, 0, 0, NULL, NULL, "Copy text to the clipboard as soon as you select it with the mouse.",
     PIC_APPLY_NOW},
    /* viewport.c tui_wheel_lines */
    {"fullscreenWheelScrollLines", "auto", "fullscreenWheelScrollLines", NULL, G_MOUSE, "Wheel scrolling",
     PIC_SET_CHOICE, {"auto", "1", "2", "3", "5", "10"}, {NULL}, 0, 0, NULL, NULL,
     "Lines per wheel step. auto speeds up a fast wheel, except where the terminal already does.", PIC_APPLY_NOW},

    /* loop.c: only sequential is sequential */
    {"toolExecution", "parallel", "toolExecution", NULL, G_BEHAVIOUR, "Tool execution", PIC_SET_CHOICE,
     {"parallel", "sequential"}, {NULL}, 0, 0, NULL, NULL,
     "Whether a reply's tool calls run at once or one by one.", PIC_APPLY_NEXT_REQUEST},
    /* codemode.c cm_on: only true is on (PIC_CODEMODE, the terminal's /codemode, wins) */
    {"codemode", "false", "codemode", NULL, G_BEHAVIOUR, "Code mode", PIC_SET_CHOICE, FALSE_TRUE, {NULL}, 0, 0, NULL, NULL,
     "Offer the codemode tool: the model writes a script that calls the other tools. /codemode switches it for this session.",
     PIC_APPLY_NEW_CONVERSATION},
    /* app.c on_key: Esc twice on an empty editor */
    {"doubleEscapeAction", "rewind", "doubleEscapeAction", NULL, G_BEHAVIOUR, "Esc twice opens", PIC_SET_CHOICE,
     {"rewind", "tree", "fork", "none"}, {NULL}, 0, 0, NULL, NULL,
     "What Esc twice on an empty editor opens. Pi's default is tree.", PIC_APPLY_NOW},
    /* app.c done_signal: only false is off */
    {"notifyWhenDone", "true", "notifyWhenDone", NULL, G_BEHAVIOUR, "Notify when done", PIC_SET_CHOICE, TRUE_FALSE,
     {NULL}, 0, 0, NULL, NULL,
     "Ring the bell and ask for a desktop notification when a reply is ready and the window is not focused.",
     PIC_APPLY_REPLY_END},
    /* provider_http.c pic_cache_retention */
    {"cacheRetention", "short", "cacheRetention", NULL, G_BEHAVIOUR, "Cache retention", PIC_SET_CHOICE,
     {"short", "long", "none"}, {NULL}, 0, 0, NULL, NULL,
     "How long the provider keeps the prompt cache: long is an hour or more, none asks for no cache.",
     PIC_APPLY_NEXT_REQUEST},
    /* update.c, app.c update_kick: only false is off */
    {"autoUpdate", "true", "autoUpdate", NULL, G_BEHAVIOUR, "Auto update", PIC_SET_CHOICE, TRUE_FALSE, {NULL}, 0, 0, NULL, NULL,
     "Build trunk in the background, test it, and install it over this pic when it passes; the terminal then says to /restart.",
     PIC_APPLY_NEXT_USE},
    /* update.c upd_source */
    {"autoUpdate.source", "", "autoUpdate.source", NULL, G_BEHAVIOUR, "Auto update source", PIC_SET_TEXT, {NULL}, {NULL}, 0, 0,
     T_LINE, "pic's own clone in ~/.pic/src", "A checkout of pic's trunk to build from, which update pulls and builds in.",
     PIC_APPLY_NEXT_USE},
    /* userdb.c pic_offline (catalog_fetch.c, keyprobe.c), app.c: only true is on */
    {"offline", "false", "offline", NULL, G_BEHAVIOUR, "Offline", PIC_SET_CHOICE, FALSE_TRUE, {NULL}, 0, 0, NULL, NULL,
     "Send nothing but requests to the model: no model catalog fetch from pi.dev, no free check of a key.",
     PIC_APPLY_NOW},
    /* main.c bench_options: one of perm.h's modes, else pic refuses to start */
    {"permissionMode", "allow", "permissionMode", NULL, G_BEHAVIOUR, "Permission mode", PIC_SET_CHOICE,
     {"allow", "ask-edits", "ask-all", "read-only"}, {NULL}, 0, 0, NULL, NULL,
     "Which tool calls a new conversation asks you about first: none, edits, all but reads, or no changes at all.",
     PIC_APPLY_NEW_CONVERSATION},
    /* main.c bench_options, perm.c perm_read_only: names, or prefixes ending in * */
    {"readOnlyTools", "", "readOnlyTools", NULL, G_BEHAVIOUR, "Read-only tools", PIC_SET_TEXT, {NULL}, {NULL}, 0, 0, T_LINE,
     "none", "Tools a permission mode treats as read-only besides pic's own, such as mcp__docs__* (a server's word is not enough).",
     PIC_APPLY_NEXT_REQUEST},
    /* compact.c pic_branch_settings_get: only true skips */
    {"branchSummary.skipPrompt", "false", "branchSummary", "skipPrompt", G_BEHAVIOUR, "Skip branch summary prompt",
     PIC_SET_CHOICE, FALSE_TRUE, {NULL}, 0, 0, NULL, NULL,
     "Leave a branch in /tree without asking whether to summarize it.", PIC_APPLY_NOW},

    /* compact.c pic_compaction_settings_get: only false turns it off */
    {"compaction.enabled", "true", "compaction", "enabled", G_CONTEXT, "Auto-compact", PIC_SET_CHOICE, TRUE_FALSE, {NULL},
     0, 0, NULL, NULL, "Compact the conversation on its own when the context fills, and when a request overflows it.",
     PIC_APPLY_NEXT_REQUEST},
    /* compact.c setting_tokens: an integer, else the default */
    {"compaction.reserveTokens", "16384", "compaction", "reserveTokens", G_CONTEXT, "Compaction reserve",
     PIC_SET_NUMBER, {NULL}, {NULL}, 0, BIG, "tokens", NULL,
     "Compact when the context passes the model's window minus this many tokens.", PIC_APPLY_NEXT_REQUEST},
    {"compaction.keepRecentTokens", "20000", "compaction", "keepRecentTokens", G_CONTEXT, "Keep recent",
     PIC_SET_NUMBER, {NULL}, {NULL}, 0, BIG, "tokens", NULL,
     "About this much recent context is kept word for word when compacting.", PIC_APPLY_NEXT_REQUEST},
    /* main.c bench_options: on or off, else pic refuses to start */
    {"lapseCompaction", "on", "lapseCompaction", NULL, G_CONTEXT, "Lapse compaction", PIC_SET_CHOICE, ON_OFF, {NULL}, 0,
     0, NULL, NULL, "Compact a long conversation coming back after the prompt cache has expired.",
     PIC_APPLY_NEXT_REQUEST},
    /* compact.c pic_lapse_mode: only summary is summary */
    {"lapseMode", "trim", "lapseMode", NULL, G_CONTEXT, "Lapse mode", PIC_SET_CHOICE, {"trim", "summary"}, {NULL}, 0, 0,
     NULL, NULL, "How a lapse compacts: drop older context with no request, or write Pi's summary.",
     PIC_APPLY_NEXT_REQUEST},
    /* main.c bench_options: seconds from 1 up, else pic refuses to start */
    {"lapseSeconds", "", "lapseSeconds", NULL, G_CONTEXT, "Lapse after", PIC_SET_NUMBER, {NULL}, {NULL}, 1, BIG, "seconds",
     "cache lifetime", "How long the prompt cache is taken to live. Unset, it is the cache retention's lifetime.",
     PIC_APPLY_NEXT_REQUEST},
    /* main.c bench_options: tokens from 0 up, else pic refuses to start */
    {"lapseFloorTokens", "100000", "lapseFloorTokens", NULL, G_CONTEXT, "Lapse floor", PIC_SET_NUMBER, {NULL}, {NULL}, 0,
     BIG, "tokens", NULL, "Lapse compaction waits until the context is larger than this.", PIC_APPLY_NEXT_REQUEST},
    /* skills.c sk_listing_budget: from 0 up; 0 is no limit */
    {"skillBudget", "", "skillBudget", NULL, G_CONTEXT, "Skill list budget", PIC_SET_NUMBER, {NULL}, {NULL}, 0, BIG,
     "characters", "1% of the window",
     "The most the system prompt's list of skills may take. 0 is no limit; unset, 1% of the window.",
     PIC_APPLY_NEXT_REQUEST},

    /* filelog.c pic_filelog_cap: from 0 up */
    {"rewindMaxBytes", "1048576", "rewindMaxBytes", NULL, G_FILES, "Rewind file limit", PIC_SET_NUMBER, {NULL}, {NULL}, 0,
     BIG * 1000, "bytes", NULL, "The largest file whose contents are kept before a change, for rewind. 0 keeps none.",
     PIC_APPLY_NEXT_REQUEST},
    /* prune.c pic_prune: from 0 up; 0 never */
    {"imageRetentionDays", "30", "imageRetentionDays", NULL, G_FILES, "Image retention", PIC_SET_NUMBER, {NULL}, {NULL}, 0,
     100000, "days", NULL, "pic prune drops the bytes of images older than this. 0 keeps them.", PIC_APPLY_NEXT_USE},
    /* export_pi.c: only 1 writes them */
    {"piSessionFiles", "0", "piSessionFiles", NULL, G_FILES, "Pi session files", PIC_SET_CHOICE, {"0", "1"},
     {"false", "true"}, 0, 0, NULL, NULL, "Also write ~/.pic/sessions files when exporting Pi session lines.",
     PIC_APPLY_NEXT_USE},

    /* remote.c rmt_relay_init */
    {"remote.relay", "https://remote.zeitforge.app", "remote.relay", NULL, G_PHONES, "Relay", PIC_SET_TEXT, {NULL}, {NULL},
     0, 0, T_URL, NULL, "The relay pic remote and pairing use, an https:// address.", PIC_APPLY_NEXT_USE},
    {"remote.invite", "", "remote.invite", NULL, G_PHONES, "Invitation", PIC_SET_TEXT, {NULL}, {NULL}, 0, 0, T_LINE,
     "none", "The invitation the relay needs to make this computer's mailbox.", PIC_APPLY_NEXT_USE},
    /* remote.c rmt_offer_ask: only off is off */
    {"remote.phonePairing", "on", "remote.phonePairing", NULL, G_PHONES, "Phone pairing", PIC_SET_CHOICE, ON_OFF, {NULL},
     0, 0, NULL, NULL, "Whether a paired phone may add a device; off allows pairing at this computer only.",
     PIC_APPLY_NEXT_USE},
    /* remote.c rmt_notify */
    {"remote.notify", "all", "remote.notify", NULL, G_PHONES, "Notify phones", PIC_SET_CHOICE, {"all", "remote", "off"},
     {NULL}, 0, 0, NULL, NULL,
     "Which finished requests notify paired phones: all, those a phone started or steered, or none.",
     PIC_APPLY_REPLY_END},

    /* main.c expiry_notice, app.c: how many days ahead a key's expiry is warned of */
    {"keyExpiryWarnDays", "7", "keyExpiryWarnDays", NULL, G_SIGNIN, "Warn of expiry", PIC_SET_NUMBER, {NULL}, {NULL}, 0, 3650,
     "days", NULL, "How many days before a key's recorded or reported expiry pic warns of it.", PIC_APPLY_NEXT_USE},
    /* cred.c: PIC_PASSPHRASE_COMMAND wins */
    {"passphraseCommand", "", "passphraseCommand", NULL, G_SIGNIN, "Passphrase command", PIC_SET_TEXT, {NULL}, {NULL}, 0, 0,
     T_LINE, "ask", "A command whose first line of output opens the credential store, instead of asking.",
     PIC_APPLY_NEXT_USE},
};

#define NROWS (sizeof pst_rows / sizeof pst_rows[0])

size_t pic_settings_count(void) { return NROWS; }

const pic_setting_def *pic_settings_at(size_t i) { return i < NROWS ? &pst_rows[i] : NULL; }

const pic_setting_def *pic_settings_find(const char *id) {
    for (size_t i = 0; id && i < NROWS; i++) {
        if (strcmp(pst_rows[i].id, id) == 0) {
            return &pst_rows[i];
        }
    }
    return NULL;
}

const pic_setting_def *pic_settings_find_path(const char *key, const char *path) {
    if (!key || !path || strncmp(path, "$.", 2) != 0) {
        return NULL;
    }
    for (size_t i = 0; i < NROWS; i++) {
        if (pst_rows[i].field && strcmp(pst_rows[i].key, key) == 0 && strcmp(pst_rows[i].field, path + 2) == 0) {
            return &pst_rows[i];
        }
    }
    return NULL;
}

const char *pic_settings_applies_name(pic_setting_applies a) {
    switch (a) {
    case PIC_APPLY_NOW: return "now";
    case PIC_APPLY_REPLY_END: return "when the reply ends";
    case PIC_APPLY_EXIT: return "when pic exits";
    case PIC_APPLY_NEXT_REQUEST: return "next request";
    case PIC_APPLY_NEW_CONVERSATION: return "next conversation";
    case PIC_APPLY_NEXT_USE: return "next use";
    }
    return "now";
}

const char *pic_settings_kind_name(pic_setting_kind k) {
    switch (k) {
    case PIC_SET_CHOICE: return "choice";
    case PIC_SET_NUMBER: return "number";
    case PIC_SET_TEXT: return "text";
    case PIC_SET_PICKER: return "picker";
    }
    return "text";
}

/* A whole number in [min, max], digits only (a leading minus for a negative minimum). */
static int pst_number(const char *v, long long min, long long max) {
    char *end = NULL;
    long long n;
    if (!*v || (!isdigit((unsigned char)v[0]) && !(v[0] == '-' && min < 0))) {
        return 0;
    }
    errno = 0;
    n = strtoll(v, &end, 10);
    return !errno && end && !*end && n >= min && n <= max;
}

/* Printable text of at most CAP bytes: no control characters. */
static int pst_line(const char *v, size_t cap) {
    size_t n = strlen(v);
    for (size_t i = 0; i < n; i++) {
        if ((unsigned char)v[i] < 0x20 || v[i] == 0x7f) {
            return 0;
        }
    }
    return n <= cap;
}

/* A tool list as --tools takes it: comma-separated names, each optionally +name or -name; empty
 * is no tools. */
static int pst_tools(const char *v) {
    const char *p = v;
    if (!*v) {
        return 1;
    }
    for (;;) {
        size_t n = strcspn(p, ","), k = 0;
        if (n && (p[0] == '+' || p[0] == '-')) {
            k = 1;
        }
        if (k == n) {
            return 0;
        }
        for (; k < n; k++) {
            unsigned char c = (unsigned char)p[k];
            if (!(isalnum(c) || c == '_' || c == '*' || c == '?' || c == '-' || c == ' ')) {
                return 0;
            }
        }
        if (!p[n]) {
            return 1;
        }
        p += n + 1;
    }
}

int pic_settings_check(const pic_setting_def *d, const char *value, char *err, size_t errcap) {
    const char *why = NULL;
    char list[160];
    if (!d || !value) {
        return 0;
    }
    switch (d->kind) {
    case PIC_SET_CHOICE: {
        size_t used = 0;
        for (size_t i = 0; i < PIC_SETTING_VALUES && d->values[i]; i++) {
            if (strcmp(value, d->values[i]) == 0) {
                return 0;
            }
            used += (size_t)snprintf(list + used, sizeof list - used, "%s%s", i ? ", " : "", d->values[i]);
            if (used >= sizeof list) {
                used = sizeof list - 1;
            }
        }
        (void)snprintf(err, errcap, "%s is one of %s, not %.80s", d->id, list, value);
        return -1;
    }
    case PIC_SET_NUMBER:
        if (pst_number(value, d->min, d->max)) {
            return 0;
        }
        (void)snprintf(err, errcap, "%s is a whole number of %s from %lld to %lld, not %.80s", d->id, d->unit, d->min,
                       d->max, value);
        return -1;
    case PIC_SET_TEXT:
    case PIC_SET_PICKER:
        if (!d->unit) {
            why = "not a setting of its own";
        } else if (strcmp(d->unit, T_MODEL) == 0) {
            const char *slash = strchr(value, '/');
            if (!slash || slash == value || !slash[1] || strpbrk(value, " \t") || !pst_line(value, 200)) {
                why = "a model as provider/id";
            }
        } else if (strcmp(d->unit, T_TOOLS) == 0) {
            if (!pst_tools(value)) {
                why = "a comma list of tool names (read,bash or +grep,-write)";
            }
        } else if (strcmp(d->unit, T_URL) == 0) {
            if ((strncmp(value, "https://", 8) != 0 && strncmp(value, "http://", 7) != 0) || strpbrk(value, " \t") ||
                !pst_line(value, 255) || !value[strncmp(value, "https://", 8) == 0 ? 8 : 7]) {
                why = "an http:// or https:// address";
            }
        } else if (strcmp(d->unit, T_THEME) == 0) {
            if (!*value || !pst_line(value, 63)) {
                why = "a theme's name";
            }
        } else if (!pst_line(value, 1024)) {
            why = "one line of text";
        }
        if (!why) {
            return 0;
        }
        (void)snprintf(err, errcap, "%s is %s, not %.80s", d->id, why, value);
        return -1;
    }
    return 0;
}

/* The text form of a field read with json_extract: booleans as true and false. */
static char *pst_field(const char *json, const char *field) {
    sqlite3 *db = pic_userdb(NULL, 0);
    sqlite3_stmt *q = NULL;
    char path[80], *out = NULL;
    (void)snprintf(path, sizeof path, "$.%s", field);
    if (db && sqlite3_prepare_v2(db,
                                 "SELECT CASE json_type(?1, ?2) WHEN 'true' THEN 'true' WHEN 'false' THEN 'false'"
                                 " WHEN 'null' THEN NULL WHEN 'object' THEN json_extract(?1, ?2)"
                                 " WHEN 'array' THEN json_extract(?1, ?2) ELSE CAST(json_extract(?1, ?2) AS TEXT) END"
                                 " WHERE json_valid(?1) AND json_type(?1) = 'object'",
                                 -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, json, -1, SQLITE_STATIC);
        sqlite3_bind_text(q, 2, path, -1, SQLITE_STATIC);
        if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_type(q, 0) != SQLITE_NULL) {
            out = strdup((const char *)sqlite3_column_text(q, 0));
        }
    }
    sqlite3_finalize(q);
    return out;
}

/* The JSON type of a field: "integer", "true", "text", ... or NULL. */
static char *pst_field_type(const char *json, const char *field) {
    sqlite3 *db = pic_userdb(NULL, 0);
    sqlite3_stmt *q = NULL;
    char path[80], *out = NULL;
    (void)snprintf(path, sizeof path, "$.%s", field);
    if (db && sqlite3_prepare_v2(db, "SELECT json_type(?1, ?2) WHERE json_valid(?1) AND json_type(?1) = 'object'", -1, &q,
                                 NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, json, -1, SQLITE_STATIC);
        sqlite3_bind_text(q, 2, path, -1, SQLITE_STATIC);
        if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_type(q, 0) != SQLITE_NULL) {
            out = strdup((const char *)sqlite3_column_text(q, 0));
        }
    }
    sqlite3_finalize(q);
    return out;
}

/* Whether a field's stored JSON type is what its readers take: a boolean for
 * a choice of true and false, an integer for a number. */
static int pst_field_typed(const pic_setting_def *d, const char *type) {
    if (!type || strcmp(type, "null") == 0) {
        return 1;
    }
    if (d->kind == PIC_SET_NUMBER) {
        return strcmp(type, "integer") == 0;
    }
    return strcmp(type, "true") == 0 || strcmp(type, "false") == 0;
}

int pic_settings_check_object(const char *key, const char *json, char *err, size_t errcap) {
    int has_rows = 0, rc = 0;
    for (size_t i = 0; i < NROWS; i++) {
        has_rows |= pst_rows[i].field && strcmp(pst_rows[i].key, key) == 0;
    }
    if (!has_rows || !json) {
        return 0;
    }
    {
        sqlite3 *db = pic_userdb(NULL, 0);
        sqlite3_stmt *q = NULL;
        int ok = 0;
        if (db && sqlite3_prepare_v2(db, "SELECT json_valid(?1) AND json_type(?1) = 'object'", -1, &q, NULL) == SQLITE_OK) {
            sqlite3_bind_text(q, 1, json, -1, SQLITE_STATIC);
            ok = sqlite3_step(q) == SQLITE_ROW && sqlite3_column_int(q, 0);
        }
        sqlite3_finalize(q);
        if (!ok) {
            (void)snprintf(err, errcap, "%s is a JSON object, as Pi's settings.json has it", key);
            return -1;
        }
    }
    for (size_t i = 0; i < NROWS && rc == 0; i++) {
        const pic_setting_def *d = &pst_rows[i];
        char *v, *type;
        if (!d->field || strcmp(d->key, key) != 0) {
            continue;
        }
        type = pst_field_type(json, d->field);
        v = pst_field(json, d->field);
        if (!pst_field_typed(d, type)) {
            (void)snprintf(err, errcap, "%s is %s, not %.80s", d->id,
                           d->kind == PIC_SET_NUMBER ? "a whole number" : "true or false", v ? v : type);
            rc = -1;
        } else {
            rc = pic_settings_check(d, v, err, errcap);
        }
        free(v);
        free(type);
    }
    return rc;
}

char *pic_settings_stored(const pic_setting_def *d) {
    char *v, *out;
    if (!d || (d->kind == PIC_SET_PICKER && !d->unit)) {
        return NULL;
    }
    v = pic_setting(d->key);
    if (!d->field || !v) {
        return v;
    }
    out = pst_field(v, d->field);
    free(v);
    return out;
}

static int pst_count(void *ctx, const char *pattern) {
    (void)pattern;
    ++*(int *)ctx;
    return 0;
}

char *pic_settings_effective(const pic_setting_def *d, int *valid) {
    char *v = pic_settings_stored(d), err[8];
    int ok = 1;
    if (d && d->kind == PIC_SET_PICKER && !d->unit) { /* scopedModels: the patterns in picu_scoped */
        int n = 0;
        char buf[32] = "";
        (void)pic_scoped_each(pst_count, &n);
        if (n > 0) {
            (void)snprintf(buf, sizeof buf, "%d pattern%s", n, n == 1 ? "" : "s");
        }
        if (valid) {
            *valid = 1;
        }
        return strdup(buf);
    }
    if (v && d->field) {
        char *json = pic_setting(d->key), *type = json ? pst_field_type(json, d->field) : NULL;
        ok = pst_field_typed(d, type);
        free(json);
        free(type);
    }
    if (v && ok && pic_settings_check(d, v, err, sizeof err) == 0) {
        if (valid) {
            *valid = 1;
        }
        return v;
    }
    if (valid) {
        *valid = !v;
    }
    free(v);
    return strdup(d ? d->def : "");
}

int pic_settings_write(const pic_setting_def *d, const char *value, char *err, size_t errcap) {
    int rc;
    if (!d) {
        (void)snprintf(err, errcap, "no such setting");
        return -1;
    }
    if (d->kind == PIC_SET_PICKER && !d->unit) {
        (void)snprintf(err, errcap, "%s is not a setting of its own", d->id);
        return -1;
    }
    if (pic_settings_check(d, value, err, errcap) != 0) {
        return -1;
    }
    if (!d->field) {
        rc = pic_setting_set(d->key, value);
    } else {
        char path[80];
        (void)snprintf(path, sizeof path, "$.%s", d->field);
        /* a choice of true and false is a JSON boolean, a number an integer: what the readers take */
        rc = pic_setting_set_json(d->key, path, value);
    }
    if (rc != 0) {
        (void)snprintf(err, errcap, "could not save the setting %s", d->id);
    }
    return rc;
}

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