Skip to content
pi-c Documentation
Login

Documentation

/* --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 */
    struct unhooked *unhooked; /* queued messages whose prompt hooks are still to run */
    size_t nunhooked;
} 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). */
/* A steer or follow-up queued before its prompt hooks ran (they run at the
 * loop's next step: never inside a network or tool wait, whose idle limit
 * they would eat into, and always before the queue is delivered). */
typedef struct unhooked {
    int64_t queued;
    char *message;
} unhooked;

static int prompt_hooks_wanted(pic_store *s) {
    return pic_hooks_has(s->hooks, "UserPromptSubmit") || pic_hooks_has(s->hooks, "SessionStart");
}

/* SessionStart (when this process has not started the conversation) and
 * UserPromptSubmit for queued message QUEUED. A block takes the message
 * back out of the queue, unrun, reported as Pi reports returned messages
 * (queue_returned, with the hook's reason) and a queue_update. */
static void run_prompt_hooks(pic_store *s, int64_t queued, const char *message) {
    sqlite3_stmt *q = NULL;
    char session[64] = "", kind[16] = "", saved[PIC_ERR_CAP];
    int64_t first = 0, delivered = 0;
    int rc;
    (void)snprintf(saved, sizeof saved, "%s", s->err);
    /* Queued, or already delivered (a follow-up to an answered request is
     * admitted at once): then its hooks still run and their context goes to
     * the request it became, but it can no longer be taken back. */
    if (sqlite3_prepare_v2(s->db,
                           "SELECT session_id, kind, CASE WHEN state = 'delivered' THEN submission_id ELSE 0 END FROM pic_queued"
                           " WHERE id = ? AND state IN ('queued', 'delivered')",
                           -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_int64(q, 1, queued);
        if (sqlite3_step(q) == SQLITE_ROW) {
            (void)snprintf(session, sizeof session, "%s", (const char *)sqlite3_column_text(q, 0));
            (void)snprintf(kind, sizeof kind, "%s", (const char *)sqlite3_column_text(q, 1));
            delivered = sqlite3_column_int64(q, 2);
        }
    }
    sqlite3_finalize(q);
    if (!session[0]) {
        return; /* cleared or returned meanwhile */
    }
    rc = pic_hooks_session_start(s, session, "resume");
    if (rc == 0) {
        rc = pic_hooks_prompt(s, session, message, &first);
    }
    if (rc == 0 || (rc == 1 && delivered)) {
        if (pic_begin(s) != 0 || pic_hooks_claim(s, first, delivered, delivered ? 0 : queued) != 0 || pic_commit(s) != 0) {
            pic_rollback(s);
        }
    } else if (rc == 1 && !pic_interrupted) {
        char *reason = strdup(s->err);
        int cleared = 0;
        if (pic_begin(s) == 0 && sqlite3_prepare_v2(s->db, "UPDATE pic_queued SET state = 'cleared' WHERE id = ? AND state = 'queued'",
                                                    -1, &q, NULL) == SQLITE_OK) {
            sqlite3_bind_int64(q, 1, queued);
            cleared = sqlite3_step(q) == SQLITE_DONE && sqlite3_changes(s->db) == 1;
            sqlite3_finalize(q);
            q = NULL;
        }
        if (!cleared || pic_commit(s) != 0) {
            pic_rollback(s);
            cleared = 0;
        }
        if (cleared && sqlite3_prepare_v2(s->db,
                                          "SELECT json_object('type', 'queue_returned',"
                                          " 'steering', json(CASE WHEN ?1 = 'steer' THEN json_array(?2) ELSE '[]' END),"
                                          " 'followUp', json(CASE WHEN ?1 = 'follow_up' THEN json_array(?2) ELSE '[]' END),"
                                          " 'reason', ?3)",
                                          -1, &q, NULL) == SQLITE_OK) {
            sqlite3_bind_text(q, 1, kind, -1, SQLITE_STATIC);
            sqlite3_bind_text(q, 2, message, -1, SQLITE_STATIC);
            sqlite3_bind_text(q, 3, reason ? reason : "", -1, SQLITE_STATIC);
            if (sqlite3_step(q) == SQLITE_ROW) {
                pic_ev_line(s, (const char *)sqlite3_column_text(q, 0));
            }
            sqlite3_finalize(q);
            pic_queue_event(s);
        }
        free(reason);
    }
    (void)snprintf(s->err, sizeof s->err, "%s", saved);
}

/* The prompt hooks of every message queued before they ran, in order. */
static void flush_unhooked(void) {
    size_t n = cmd.nunhooked;
    unhooked *list = cmd.unhooked;
    cmd.unhooked = NULL;
    cmd.nunhooked = 0;
    for (size_t i = 0; i < n; i++) {
        if (cmd.s) {
            run_prompt_hooks(cmd.s, list[i].queued, list[i].message);
        }
        free(list[i].message);
    }
    free(list);
}

/* steer or follow_up: journaled, then answered, then the queues reported;
 * its prompt hooks run at the loop's next step (or now, when pic is at
 * one). 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;
    s->err[0] = '\0';
    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_images(s, type, text, images, n) != 0) {
        respond(line, type, 0, NULL, s->err);
    } else {
        int64_t queued = 0;
        sqlite3_stmt *q = NULL;
        if (sqlite3_prepare_v2(s->db, "SELECT max(id) FROM pic_queued", -1, &q, NULL) == SQLITE_OK && sqlite3_step(q) == SQLITE_ROW) {
            queued = sqlite3_column_int64(q, 0);
        }
        sqlite3_finalize(q);
        respond(line, type, 1, "{\"disposition\":\"queued\"}", NULL);
        pic_queue_event(s);
        if (queued && prompt_hooks_wanted(s)) {
            unhooked *grown = realloc(cmd.unhooked, (cmd.nunhooked + 1) * sizeof *grown);
            if (grown && (grown[cmd.nunhooked].message = strdup(message)) != NULL) {
                grown[cmd.nunhooked++].queued = queued;
            }
            cmd.unhooked = grown ? grown : cmd.unhooked;
            if (pic_side_safe) {
                flush_unhooked();
            }
        }
    }
    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);
    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);
}

/* 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_unhooked;
}

void pic_commands_stop(void) {
    if (cmd.s) {
        flush_unhooked(); /* what is still queued has its prompt hooks run */
        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);
}