Skip to content
pi-c Artifact [64f9121a02]
Login

Artifact [64f9121a02]

Artifact 64f9121a02a6679b0173b1edbc2775558662bf8c77952b158bb26e46b5157d67:


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

#include "commands.h"
#include "hooks.h"
#include "net.h"
#include "userdb.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 */
    int own_fd;       /* the descriptor is ours to read (not the caller's) */
    int (*other)(void *ctx, const char *line, const char *type);
    void *other_ctx;
    void (*sink)(void *ctx, const char *response); /* takes the response lines instead of the events' out */
    void *sink_ctx;
} cmd_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 (!command) { /* queued for the caller, who answered it already */
        return;
    }
    if (sqlite3_prepare_v2(cmd_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) {
        if (cmd_cmd.sink) {
            cmd_cmd.sink(cmd_cmd.sink_ctx, (const char *)sqlite3_column_text(q, 0));
        } else {
            pic_ev_line(cmd_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). */
/* steer or follow_up: journaled (with its prompt hooks pending, when there
 * are any: the loop runs them at its next step, never inside a network or
 * tool wait, and before the message can be delivered), then answered, then
 * the queues reported. Images that cannot go inline become notes after the
 * text, as Pi's. */
static int enqueue(const char *line, const char *command, const char *type, const char *message) {
    pic_store *s = cmd_cmd.s;
    char *expanded = (message[0] == '/' || strchr(message, '@')) && cmd_cmd.expand ? cmd_cmd.expand(cmd_cmd.ctx, message) : NULL,
         *text = NULL;
    const char *error = NULL;
    char why[PIC_ERR_CAP];
    int rc = -1;
    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, command, 0, NULL, error);
    } else if (!(text = pic_image_prepare(expanded ? expanded : message, images, &n, why, sizeof why))) {
        respond(line, command, 0, NULL, why);
    } else if (pic_queue_add_images(s, type, text, images, n) != 0) {
        respond(line, command, 0, NULL, s->err);
    } else {
        respond(line, command, 1, "{\"disposition\":\"queued\"}", NULL);
        pic_queue_event(s);
        rc = 0;
    }
    free(text);
    free(images);
    free(bytes);
    free(expanded);
    return rc;
}

static void cmd_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_cmd.s;
    sqlite3_stmt *q = NULL;
    char saved[PIC_ERR_CAP];
    char *type = NULL, *message = NULL, *mode = NULL;
    int valid = 0, bad_images = 0, enabled = -1;
    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'),"
                           " CASE WHEN json_valid(?1) THEN CASE json_type(?1, '$.enabled') WHEN 'true' THEN 1 WHEN 'false' THEN 0 END END",
                           -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);
        enabled = sqlite3_column_type(q, 5) == SQLITE_NULL ? -1 : sqlite3_column_int(q, 5);
    }
    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) {
            (void)enqueue(line, type, 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_cmd.abort_line) { /* one abort is enough: an earlier one is answered now */
            respond(cmd_cmd.abort_line, "abort", 1, NULL, NULL);
            free(cmd_cmd.abort_line);
        }
        cmd_cmd.abort_line = strdup(line);
    } else if (strcmp(type, "set_steering_mode") == 0) {
        cmd_set_mode(line, type, mode, &s->steer_all);
    } else if (strcmp(type, "set_follow_up_mode") == 0) {
        cmd_set_mode(line, type, mode, &s->follow_up_all);
    } else if (strcmp(type, "set_auto_compaction") == 0) {
        /* Pi's setCompactionEnabled: compaction.enabled in the user's
         * settings, which every later request reads (this run's next one too). */
        if (enabled < 0) {
            respond(line, type, 0, NULL, "enabled must be a boolean");
        } else if (pic_setting_set_json("compaction", "$.enabled", enabled ? "true" : "false") != 0) {
            respond(line, type, 0, NULL, "cannot write ~/.pic/pic.sqlite");
        } else {
            respond(line, type, 1, NULL, NULL);
        }
    } else if (!cmd_cmd.other || !cmd_cmd.other(cmd_cmd.other_ctx, line, type)) {
        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_cmd.buf + start, '\n', cmd_cmd.len - start);
        size_t end;
        if (!nl && !(at_eof && start < cmd_cmd.len)) {
            break;
        }
        end = nl ? (size_t)(nl - cmd_cmd.buf) : cmd_cmd.len;
        cmd_cmd.buf[end] = '\0';
        if (end > start && cmd_cmd.buf[end - 1] == '\r') {
            cmd_cmd.buf[end - 1] = '\0';
        }
        if (cmd_cmd.overlong) {
            respond("", "parse", 0, NULL, "Failed to parse command: the line is too long");
            cmd_cmd.overlong = 0;
        } else if (cmd_cmd.buf[start]) {
            handle(cmd_cmd.buf + start);
        }
        start = nl ? end + 1 : cmd_cmd.len;
    }
    memmove(cmd_cmd.buf, cmd_cmd.buf + start, cmd_cmd.len - start);
    cmd_cmd.len -= start;
}

static void ready(void) {
    ssize_t n;
    if (cmd_cmd.cap - cmd_cmd.len < 4097) {
        size_t ncap = cmd_cmd.cap ? cmd_cmd.cap * 2 : 8192;
        char *b = cmd_cmd.len + 4097 > LINE_CAP ? NULL : realloc(cmd_cmd.buf, ncap);
        if (!b) { /* too long (or no memory): drop what is buffered of this line */
            cmd_cmd.len = 0;
            cmd_cmd.overlong = 1;
        } else {
            cmd_cmd.buf = b;
            cmd_cmd.cap = ncap;
        }
    }
    if (!cmd_cmd.buf) {
        pic_side_fd = -1;
        return;
    }
    n = read(pic_side_fd, cmd_cmd.buf + cmd_cmd.len, cmd_cmd.cap - cmd_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_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_cmd.abort_line) {
        respond(cmd_cmd.abort_line, "abort", 1, NULL, NULL);
        free(cmd_cmd.abort_line);
        cmd_cmd.abort_line = NULL;
    }
}

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

void pic_commands_other(int (*other)(void *ctx, const char *line, const char *type), void *ctx) {
    cmd_cmd.other = other;
    cmd_cmd.other_ctx = ctx;
}

void pic_commands_line(const char *line) {
    if (cmd_cmd.s && line[0]) {
        handle(line);
    }
}

int pic_commands_active(void) { return cmd_cmd.s != NULL; }

void pic_commands_sink(void (*sink)(void *ctx, const char *response), void *ctx) {
    cmd_cmd.sink = sink;
    cmd_cmd.sink_ctx = ctx;
}

int pic_commands_enqueue(const char *line, const char *command, const char *type, const char *message) {
    char saved[PIC_ERR_CAP];
    int rc;
    if (!cmd_cmd.s) {
        return -1;
    }
    (void)snprintf(saved, sizeof saved, "%s", cmd_cmd.s->err);
    rc = enqueue(line, command, type, message);
    (void)snprintf(cmd_cmd.s->err, sizeof cmd_cmd.s->err, "%s", saved);
    return rc;
}

void pic_commands_stop(void) {
    if (cmd_cmd.s) {
        settle_abort(cmd_cmd.s);
        cmd_cmd.s->cancelled = NULL;
    }
    if (cmd_cmd.own_fd) {
        pic_side_fd = -1;
        pic_side_ready = NULL;
    }
    free(cmd_cmd.buf);
    memset(&cmd_cmd, 0, sizeof cmd_cmd);
}