Artifact d2359def124dbf4d96ae37852ba3c3c3a1bf7e4a7eaf0ffee5063f03c4abb0b4:
- File
src/commands.c
— part of check-in
[c55dfbb163]
at
2026-11-19 23:39:49
on branch images
— Images, as Pi's
User messages, steering and follow-ups, and tool results can carry images. Journal version 9 keeps their bytes in SQLite (pic_image, deduplicated by SHA3-256, deflated only when smaller) linked by pic_attachment, written in the same transaction as the entry; pic check covers them. Each adapter sends its native shape (Anthropic base64 blocks, Chat image_url data URLs, Responses input_image); a model whose catalog input lacks images gets Pi's placeholders. pic ask --image PATH, the RPC images field and the read tool on image files add them; the Pi and HTML exports include them. (user: dmestas, size: 11412) [annotate] [blame] [check-ins using]
/* --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 "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 */ } 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); } /* The command's images (Pi's ImageContent: type "image", base64 data, * mimeType) decoded into *list (bytes in one malloc'd *buf). -1 with * *error set when one is not an image block or not base64. */ static int decode_images(const char *line, pic_image **list, size_t *n, unsigned char **buf, const char **error) { sqlite3_stmt *q = NULL; size_t cap = 0, used = 0; int step, rc = 0; *list = NULL; *buf = NULL; *n = 0; if (sqlite3_prepare_v2(cmd.s->db, "SELECT json_extract(value, '$.type') = 'image' AND json_type(value, '$.data') = 'text'" " AND json_type(value, '$.mimeType') = 'text'," " json_extract(value, '$.data'), json_extract(value, '$.mimeType') FROM json_each(?1, '$.images')", -1, &q, NULL) != SQLITE_OK) { *error = "out of memory"; return -1; } sqlite3_bind_text(q, 1, line, -1, SQLITE_STATIC); /* First pass: check each and count the room the bytes need. */ while ((step = sqlite3_step(q)) == SQLITE_ROW && rc == 0) { if (!sqlite3_column_int(q, 0)) { *error = "each image must be {\"type\":\"image\",\"data\":BASE64,\"mimeType\":TYPE}"; rc = -1; } else { cap += (size_t)sqlite3_column_bytes(q, 1) / 4 * 3 + 3 + (size_t)sqlite3_column_bytes(q, 2) + 1; (*n)++; } } if (rc == 0 && *n > 0 && (!(*list = calloc(*n, sizeof **list)) || !(*buf = malloc(cap)))) { *error = "out of memory"; rc = -1; } sqlite3_reset(q); for (size_t i = 0; rc == 0 && i < *n && sqlite3_step(q) == SQLITE_ROW; i++) { const char *data = (const char *)sqlite3_column_text(q, 1), *mime = (const char *)sqlite3_column_text(q, 2); size_t got = pic_base64_decode(data, (size_t)sqlite3_column_bytes(q, 1), *buf + used); if (got == (size_t)-1) { *error = "image data is not base64"; rc = -1; break; } (*list)[i].data = *buf + used; (*list)[i].len = got; used += got; memcpy(*buf + used, mime, strlen(mime) + 1); (*list)[i].mime = (const char *)(*buf + used); used += strlen(mime) + 1; } sqlite3_finalize(q); if (rc != 0) { free(*list); free(*buf); *list = NULL; *buf = NULL; *n = 0; } return rc; } /* 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; pic_image *images = NULL; unsigned char *bytes = NULL; size_t n = 0; s->err[0] = '\0'; if (decode_images(line, &images, &n, &bytes, &error) != 0) { respond(line, type, 0, NULL, error); } else if (!(text = pic_image_prepare(expanded ? expanded : message, images, &n))) { respond(line, type, 0, NULL, "out of memory"); } else if (pic_queue_add_images(s, type, text, images, n) != 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); 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; } void pic_commands_stop(void) { if (cmd.s) { settle_abort(cmd.s); cmd.s->cancelled = NULL; } pic_side_fd = -1; pic_side_ready = NULL; free(cmd.buf); memset(&cmd, 0, sizeof cmd); }