Skip to content
pi-c Artifact [03d69c0671]
Login

Artifact [03d69c0671]

Artifact 03d69c0671c07dec8af0d487596a4068ddf48a73d2ebb871654fc22855e04e9f:


/* --commands: Pi's RPC command lines, read without blocking the loop. */
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "commands.h"
#include "hooks.h"
#include "net.h"

#define LINE_CAP (16u << 20) /* a longer line is answered with an error and dropped */

static struct {
    pic_store *s;
    char *(*expand)(void *ctx, const char *text);
    void *ctx;
    char *buf;
    size_t len, cap;
    int overlong; /* the line being read is past LINE_CAP */
    char *abort_line; /* an abort answered once its cancel is journaled */
    char **deferred;  /* lines held for a step of the loop (pic_side_safe) */
    size_t ndeferred;
} cmd;

/* Pi's response line: id echoed when the command had one; data (JSON) on
 * success, error (text) on failure. */
static void respond(const char *line, const char *command, int ok, const char *data, const char *error) {
    sqlite3_stmt *q = NULL;
    if (sqlite3_prepare_v2(cmd.s->db,
                           "SELECT json_patch('{}', json_object('id', CASE WHEN json_valid(?1) AND json_type(?1) = 'object'"
                           " THEN json_extract(?1, '$.id') END, 'type', 'response', 'command', ?2,"
                           " 'success', json(iif(?3, 'true', 'false')), 'data', json(?4), 'error', ?5))",
                           -1, &q, NULL) != SQLITE_OK) {
        return;
    }
    sqlite3_bind_text(q, 1, line, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 2, command, -1, SQLITE_STATIC);
    sqlite3_bind_int(q, 3, ok);
    if (data) {
        sqlite3_bind_text(q, 4, data, -1, SQLITE_STATIC);
    }
    if (error) {
        sqlite3_bind_text(q, 5, error, -1, SQLITE_STATIC);
    }
    if (sqlite3_step(q) == SQLITE_ROW) {
        pic_ev_line(cmd.s, (const char *)sqlite3_column_text(q, 0));
    }
    sqlite3_finalize(q);
}

/* UserPromptSubmit for a steer or follow-up (with SessionStart first, when
 * this process has not started the conversation): 0 to queue it, with the
 * first run in *first; 1 when a hook rejects it, or on an error (s->err). */
static int prompt_hooks(pic_store *s, const char *message, int64_t *first) {
    sqlite3_stmt *q = NULL;
    char session[64] = "";
    *first = 0;
    if (!s->hooks) {
        return 0;
    }
    if (sqlite3_prepare_v2(s->db, "SELECT session_id FROM pic_submission WHERE id = ?", -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_int64(q, 1, (sqlite3_int64)s->running);
        if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_text(q, 0)) {
            (void)snprintf(session, sizeof session, "%s", (const char *)sqlite3_column_text(q, 0));
        }
    }
    sqlite3_finalize(q);
    if (!session[0]) {
        (void)snprintf(s->err, sizeof s->err, "no request is running");
        return 1;
    }
    return pic_hooks_session_start(s, session, "resume") != 0 || pic_hooks_prompt(s, session, message, first) != 0;
}

/* steer or follow_up: journaled, then answered, then the queues reported.
 * Images that cannot go inline become notes after the text, as Pi's. */
static void enqueue(const char *line, const char *type, const char *message) {
    pic_store *s = cmd.s;
    char *expanded = message[0] == '/' && cmd.expand ? cmd.expand(cmd.ctx, message) : NULL, *text = NULL;
    const char *error = NULL;
    char why[PIC_ERR_CAP];
    pic_image *images = NULL;
    unsigned char *bytes = NULL;
    size_t n = 0;
    int64_t first = 0;
    s->err[0] = '\0';
    if (prompt_hooks(s, message, &first) != 0) {
        respond(line, type, 0, NULL, s->err);
    } else if (pic_images_from_json(s->db, line, "$.images", 1, &images, &n, &bytes, &error) != 0) {
        respond(line, type, 0, NULL, error);
    } else if (!(text = pic_image_prepare(expanded ? expanded : message, images, &n, why, sizeof why))) {
        respond(line, type, 0, NULL, why);
    } else if (pic_queue_add_hooked(s, type, text, images, n, first) != 0) {
        respond(line, type, 0, NULL, s->err);
    } else {
        respond(line, type, 1, "{\"disposition\":\"queued\"}", NULL);
        pic_queue_event(s);
    }
    free(text);
    free(images);
    free(bytes);
    free(expanded);
}

static void set_mode(const char *line, const char *type, const char *mode, int *all) {
    if (mode && (strcmp(mode, "all") == 0 || strcmp(mode, "one-at-a-time") == 0)) {
        *all = strcmp(mode, "all") == 0;
        respond(line, type, 1, NULL, NULL);
    } else {
        respond(line, type, 0, NULL, "mode must be \"all\" or \"one-at-a-time\"");
    }
}

static void handle(const char *line) {
    pic_store *s = cmd.s;
    sqlite3_stmt *q = NULL;
    char saved[PIC_ERR_CAP];
    char *type = NULL, *message = NULL, *mode = NULL;
    int valid = 0, bad_images = 0;
    if (sqlite3_prepare_v2(s->db,
                           "SELECT json_valid(?1) AND json_type(?1) = 'object',"
                           " CASE WHEN json_valid(?1) AND json_type(?1, '$.type') = 'text' THEN json_extract(?1, '$.type') END,"
                           " CASE WHEN json_valid(?1) AND json_type(?1, '$.message') = 'text' THEN json_extract(?1, '$.message') END,"
                           " CASE WHEN json_valid(?1) AND json_type(?1, '$.mode') = 'text' THEN json_extract(?1, '$.mode') END,"
                           " json_valid(?1) AND json_type(?1, '$.images') NOT IN ('array', 'null')",
                           -1, &q, NULL) != SQLITE_OK) {
        return;
    }
    sqlite3_bind_text(q, 1, line, -1, SQLITE_STATIC);
    if (sqlite3_step(q) == SQLITE_ROW) {
        valid = sqlite3_column_int(q, 0);
        type = sqlite3_column_text(q, 1) ? strdup((const char *)sqlite3_column_text(q, 1)) : NULL;
        message = sqlite3_column_text(q, 2) ? strdup((const char *)sqlite3_column_text(q, 2)) : NULL;
        mode = sqlite3_column_text(q, 3) ? strdup((const char *)sqlite3_column_text(q, 3)) : NULL;
        bad_images = sqlite3_column_int(q, 4);
    }
    sqlite3_finalize(q);
    /* The run's own error message survives a command. */
    (void)snprintf(saved, sizeof saved, "%s", s->err);
    /* A steer or follow-up whose prompt hooks run (and whatever comes after
     * it, but an abort) waits for a step of the loop: a hook run inside a
     * network or tool wait would eat into that wait's idle limit. */
    if (valid && type && !pic_side_safe && strcmp(type, "abort") != 0 &&
        (cmd.ndeferred || ((strcmp(type, "steer") == 0 || strcmp(type, "follow_up") == 0) &&
                           (pic_hooks_has(s->hooks, "UserPromptSubmit") || pic_hooks_has(s->hooks, "SessionStart"))))) {
        char **grown = realloc(cmd.deferred, (cmd.ndeferred + 1) * sizeof *grown);
        if (grown && (grown[cmd.ndeferred] = strdup(line)) != NULL) {
            cmd.deferred = grown;
            cmd.ndeferred++;
        } else {
            cmd.deferred = grown ? grown : cmd.deferred;
            respond(line, type, 0, NULL, "out of memory");
        }
        free(type);
        free(message);
        free(mode);
        return;
    }
    if (!valid) {
        respond(line, "parse", 0, NULL, "Failed to parse command: not a JSON object");
    } else if (!type) {
        respond(line, "", 0, NULL, "Unknown command: ");
    } else if (strcmp(type, "steer") == 0 || strcmp(type, "follow_up") == 0) {
        if (bad_images) {
            respond(line, type, 0, NULL, "images must be an array");
        } else if (message) {
            enqueue(line, type, message);
        } else {
            respond(line, type, 0, NULL, "message must be a string");
        }
    } else if (strcmp(type, "clear_queue") == 0) {
        char *cleared = NULL;
        s->err[0] = '\0';
        if (pic_queue_clear(s, &cleared) != 0) {
            respond(line, type, 0, NULL, s->err);
        } else {
            respond(line, type, 1, cleared, NULL);
            pic_queue_event(s);
        }
        free(cleared);
    } else if (strcmp(type, "abort") == 0) {
        /* The loop cancels the request at its next step; 2, not Ctrl-C's 1,
         * so a Ctrl-C meanwhile is still a first one. */
        if (!pic_interrupted) {
            pic_interrupted = 2;
        }
        if (cmd.abort_line) { /* one abort is enough: an earlier one is answered now */
            respond(cmd.abort_line, "abort", 1, NULL, NULL);
            free(cmd.abort_line);
        }
        cmd.abort_line = strdup(line);
    } else if (strcmp(type, "set_steering_mode") == 0) {
        set_mode(line, type, mode, &s->steer_all);
    } else if (strcmp(type, "set_follow_up_mode") == 0) {
        set_mode(line, type, mode, &s->follow_up_all);
    } else {
        char error[160];
        (void)snprintf(error, sizeof error, "Unknown command: %.100s", type);
        respond(line, type, 0, NULL, error);
    }
    (void)snprintf(s->err, sizeof s->err, "%s", saved);
    free(type);
    free(message);
    free(mode);
}

/* Each complete line in the buffer, then what is left moved to its start. */
static void drain_lines(int at_eof) {
    size_t start = 0;
    for (;;) {
        char *nl = memchr(cmd.buf + start, '\n', cmd.len - start);
        size_t end;
        if (!nl && !(at_eof && start < cmd.len)) {
            break;
        }
        end = nl ? (size_t)(nl - cmd.buf) : cmd.len;
        cmd.buf[end] = '\0';
        if (end > start && cmd.buf[end - 1] == '\r') {
            cmd.buf[end - 1] = '\0';
        }
        if (cmd.overlong) {
            respond("", "parse", 0, NULL, "Failed to parse command: the line is too long");
            cmd.overlong = 0;
        } else if (cmd.buf[start]) {
            handle(cmd.buf + start);
        }
        start = nl ? end + 1 : cmd.len;
    }
    memmove(cmd.buf, cmd.buf + start, cmd.len - start);
    cmd.len -= start;
}

static void ready(void) {
    ssize_t n;
    if (cmd.cap - cmd.len < 4097) {
        size_t ncap = cmd.cap ? cmd.cap * 2 : 8192;
        char *b = cmd.len + 4097 > LINE_CAP ? NULL : realloc(cmd.buf, ncap);
        if (!b) { /* too long (or no memory): drop what is buffered of this line */
            cmd.len = 0;
            cmd.overlong = 1;
        } else {
            cmd.buf = b;
            cmd.cap = ncap;
        }
    }
    if (!cmd.buf) {
        pic_side_fd = -1;
        return;
    }
    n = read(pic_side_fd, cmd.buf + cmd.len, cmd.cap - cmd.len - 1);
    if (n < 0 && (errno == EINTR || errno == EAGAIN)) {
        return;
    }
    if (n <= 0) { /* end of input: what is left is the last line */
        drain_lines(1);
        pic_side_fd = -1;
        return;
    }
    cmd.len += (size_t)n;
    drain_lines(0);
}

/* The held lines, in order, now that pic is at a step of its loop. */
static void flush_deferred(void) {
    size_t n = cmd.ndeferred;
    char **lines = cmd.deferred;
    int safe = pic_side_safe;
    cmd.deferred = NULL;
    cmd.ndeferred = 0;
    pic_side_safe = 1;
    for (size_t i = 0; i < n; i++) {
        handle(lines[i]);
        free(lines[i]);
    }
    free(lines);
    pic_side_safe = safe;
}

/* Answers an abort waiting for its cancel (or for the run to end). */
static void settle_abort(pic_store *s) {
    (void)s;
    if (cmd.abort_line) {
        respond(cmd.abort_line, "abort", 1, NULL, NULL);
        free(cmd.abort_line);
        cmd.abort_line = NULL;
    }
}

void pic_commands_start(pic_store *s, int fd, char *(*expand)(void *ctx, const char *text), void *ctx) {
    memset(&cmd, 0, sizeof cmd);
    s->cancelled = settle_abort;
    cmd.s = s;
    cmd.expand = expand;
    cmd.ctx = ctx;
    pic_side_ready = ready;
    pic_side_fd = fd;
    pic_side_idle = flush_deferred;
}

void pic_commands_stop(void) {
    if (cmd.s) {
        flush_deferred(); /* answered: queued for what follows, or refused */
        settle_abort(cmd.s);
        cmd.s->cancelled = NULL;
    }
    pic_side_fd = -1;
    pic_side_ready = NULL;
    pic_side_idle = NULL;
    free(cmd.buf);
    memset(&cmd, 0, sizeof cmd);
}