Artifact 0f7ff21cc832f1174330569e7911ce8962494144f999a780c13e0fdaae322bde:
- File
src/import_pi.c
— part of check-in
[9dabe49948]
at
2026-11-21 19:00:33
on branch amalgam
— Amalgamation: pic as one pic.c beside the vendored sources, built by one cc line
make amalgamation writes pic-amalgamation-VERSION/ and its tarball; make test-amal builds it from the README's own line and runs crash, print and tools against that binary, and is part of make test-pic. About 60 file-local names that collided in one translation unit take their file's prefix; test/pic/amalgam.sh fails on a new collision. (user: dmestas, size: 12193) [annotate] [blame] [check-ins using] [more...]
/* Pi v3 session JSONL into a new pic conversation (Pi's /import). Only the * text and the user's images survive: each user message becomes a request * (its images checked as any input's; one that fails becomes Pi's note * after the text), and the assistant * text that followed it (before the next user message) its answer. Tool * calls and results, thinking and the branch structure of the file are not * carried over: the messages are taken in file order as one path. The * answers are marked as from an unknown model, so any model is sent them * converted, never verbatim. */ #include <stdarg.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <unistd.h> #include "pic.h" #include "platform.h" typedef struct { char *buf; size_t len, cap; } ipi_buf; static int ipi_buf_add(ipi_buf *b, const char *s, size_t n) { if (b->len + n + 1 > b->cap) { size_t cap = b->cap ? b->cap : 256; char *grown; while (cap < b->len + n + 1) { cap *= 2; } if (!(grown = realloc(b->buf, cap))) { return -1; } b->buf = grown; b->cap = cap; } memcpy(b->buf + b->len, s, n); b->len += n; b->buf[b->len] = '\0'; return 0; } /* A statement with text (t) and integer (i) parameters; NULL text binds null. */ static int ipi_run(pic_store *s, const char *sql, const char *fmt, ...) { sqlite3_stmt *q = NULL; va_list ap; int rc; if (sqlite3_prepare_v2(s->db, sql, -1, &q, NULL) != SQLITE_OK) { (void)snprintf(s->err, sizeof s->err, "sql: %s", sqlite3_errmsg(s->db)); return -1; } va_start(ap, fmt); for (int i = 1; *fmt; fmt++, i++) { if (*fmt == 't') { const char *t = va_arg(ap, const char *); if (t) { sqlite3_bind_text(q, i, t, -1, SQLITE_STATIC); } } else { sqlite3_bind_int64(q, i, va_arg(ap, sqlite3_int64)); } } va_end(ap); rc = sqlite3_step(q); sqlite3_finalize(q); if (rc != SQLITE_DONE && rc != SQLITE_ROW) { (void)snprintf(s->err, sizeof s->err, "sql: %s", sqlite3_errmsg(s->db)); return -1; } return 0; } /* The text of a Pi message of ROLE (a string content, or the text parts of a * content array joined by newlines), malloc'd; NULL when the line is not one. */ static char *message_text(pic_store *s, const char *line, const char *role) { sqlite3_stmt *q = NULL; char *out = NULL; if (sqlite3_prepare_v2( s->db, "SELECT CASE json_type(?1, '$.message.content') WHEN 'text' THEN json_extract(?1, '$.message.content')" " ELSE (SELECT group_concat(json_extract(value, '$.text'), char(10)) FROM json_each(?1, '$.message.content')" " WHERE json_extract(value, '$.type') = 'text') END" " WHERE json_valid(?1) AND json_extract(?1, '$.type') = 'message' AND json_extract(?1, '$.message.role') = ?2", -1, &q, NULL) != SQLITE_OK) { return NULL; } sqlite3_bind_text(q, 1, line, -1, SQLITE_STATIC); sqlite3_bind_text(q, 2, role, -1, SQLITE_STATIC); if (sqlite3_step(q) == SQLITE_ROW) { const char *t = (const char *)sqlite3_column_text(q, 0); out = strdup(t ? t : ""); } sqlite3_finalize(q); return out; } /* The user message's text with a note for each image that fails its check * (malloc'd), its good images moved to the front of *list (*n of them). */ static char *with_images(pic_store *s, const char *user, const char *line, pic_image **list, size_t *n, unsigned char **bytes) { const char *error = NULL; size_t kept = 0; ipi_buf text = {NULL, 0, 0}; if (pic_images_from_json(s->db, line, "$.message.content", 0, list, n, bytes, &error) != 0) { *n = 0; /* malformed blocks: the text alone, noted */ if (ipi_buf_add(&text, user, strlen(user)) != 0 || ipi_buf_add(&text, "\n\n" PIC_IMAGE_UNCONVERTIBLE, 2 + strlen(PIC_IMAGE_UNCONVERTIBLE)) != 0) { free(text.buf); return NULL; } return text.buf; } if (ipi_buf_add(&text, user, strlen(user)) != 0) { return NULL; } for (size_t i = 0, noted = 0; i < *n; i++) { int rc = pic_image_check(&(*list)[i], (*list)[i].mime, NULL, 0); if (rc == PIC_IMAGE_OK) { (*list)[kept++] = (*list)[i]; } else if (ipi_buf_add(&text, "\n\n", noted++ ? 1 : 2) != 0 || ipi_buf_add(&text, pic_image_note(rc), strlen(pic_image_note(rc))) != 0) { free(text.buf); return NULL; } } *n = kept; return text.buf; } /* One finished request: the user text (and images) and, when there was any, * the answer. */ static int add_turn(pic_store *s, const char *session, const char *key, const char *user_text, const char *line, const char *answer) { sqlite3_int64 sub, seq; sqlite3_stmt *q = NULL; char *body = NULL, *user; pic_image *images = NULL; unsigned char *bytes = NULL; size_t n = 0; int rc; if (!(user = with_images(s, user_text, line, &images, &n, &bytes))) { (void)snprintf(s->err, sizeof s->err, "out of memory"); return -1; } rc = ipi_run(s, "INSERT INTO pic_submission(request_key, content, status, session_id) VALUES(?, ?, 'admitted', ?)", "ttt", key, user, session) != 0 || ipi_run(s, "INSERT INTO pic_entry(submission_id, kind, body) SELECT max(id), 'user', ? FROM pic_submission", "t", user) != 0 || pic_attach_images(s, sqlite3_last_insert_rowid(s->db), 0, images, n) != 0; free(user); free(images); free(bytes); if (rc != 0) { return -1; } sub = 0; if (sqlite3_prepare_v2(s->db, "SELECT max(id) FROM pic_submission", -1, &q, NULL) == SQLITE_OK && sqlite3_step(q) == SQLITE_ROW) { sub = sqlite3_column_int64(q, 0); } sqlite3_finalize(q); q = NULL; if (!answer || !*answer) { return ipi_run(s, "UPDATE pic_submission SET status = 'failed', error = 'imported without a reply' WHERE id = ?", "i", sub); } if (sqlite3_prepare_v2(s->db, "SELECT json_array(json_object('type', 'text', 'text', ?1))", -1, &q, NULL) != SQLITE_OK) { return -1; } sqlite3_bind_text(q, 1, answer, -1, SQLITE_STATIC); if (sqlite3_step(q) == SQLITE_ROW) { body = strdup((const char *)sqlite3_column_text(q, 0)); } sqlite3_finalize(q); if (!body) { return -1; } rc = ipi_run(s, "INSERT INTO pic_entry(submission_id, kind, body, native, provider, api, model)" " VALUES(?1, 'answer', ?2, ?2, 'anthropic', 'anthropic-messages', 'unknown')", "it", sub, body); free(body); if (rc != 0) { return -1; } seq = sqlite3_last_insert_rowid(s->db); return ipi_run(s, "UPDATE pic_submission SET status = 'answered' WHERE id = ?", "i", sub) || ipi_run(s, "INSERT INTO pic_generation(submission_id, turn, attempt, state, entry_seq, stop_reason, purpose)" " VALUES(?, 1, 1, 'done', ?, 'stop', 'reply')", "ii", sub, seq); } int pic_import_pi(pic_store *s, FILE *in, char *session_out, size_t cap, long *turns) { char *line = NULL, *user = NULL, *user_line = NULL, *name = NULL, session[16], key[96]; ipi_buf answer = {NULL, 0, 0}, input = {NULL, 0, 0}; size_t at = 0; long n = 0; ssize_t got; int rc = -1; long long now_ns = (long long)pic_platform_get()->wall_ns(); /* All of the input first: it may be a pipe that takes its time, and no * write transaction is held while waiting on anything outside the * journal (other pic processes are waiting on this one's). */ for (;;) { char chunk[65536]; size_t r = fread(chunk, 1, sizeof chunk, in); if (r && ipi_buf_add(&input, chunk, r) != 0) { free(input.buf); (void)snprintf(s->err, sizeof s->err, "out of memory"); return -1; } if (r < sizeof chunk) { break; } } if (pic_begin(s) != 0) { free(input.buf); return -1; } { sqlite3_stmt *q = NULL; if (sqlite3_prepare_v2(s->db, "INSERT INTO pic_session(id, created_ms, updated_ms) VALUES(lower(hex(randomblob(4)))," " CAST(unixepoch('subsec') * 1000 AS INTEGER), CAST(unixepoch('subsec') * 1000 AS INTEGER))" " RETURNING id", -1, &q, NULL) != SQLITE_OK || sqlite3_step(q) != SQLITE_ROW) { (void)snprintf(s->err, sizeof s->err, "sql: %s", sqlite3_errmsg(s->db)); sqlite3_finalize(q); pic_rollback(s); free(input.buf); return -1; } (void)snprintf(session, sizeof session, "%s", (const char *)sqlite3_column_text(q, 0)); sqlite3_finalize(q); } for (;;) { char *u = NULL, *a = NULL, *info = NULL; int end; free(line); line = NULL; got = -1; if (at < input.len) { /* the next line, its newline included */ const char *nl = memchr(input.buf + at, '\n', input.len - at); size_t len = nl ? (size_t)(nl - (input.buf + at)) + 1 : input.len - at; if (!(line = malloc(len + 1))) { goto out; } memcpy(line, input.buf + at, len); line[len] = '\0'; at += len; got = (ssize_t)len; } end = got < 0; if (!end) { u = message_text(s, line, "user"); a = u ? NULL : message_text(s, line, "assistant"); if (!u && !a) { sqlite3_stmt *q = NULL; if (sqlite3_prepare_v2(s->db, "SELECT json_extract(?1, '$.name') WHERE json_valid(?1) AND json_extract(?1, '$.type') = 'session_info'", -1, &q, NULL) == SQLITE_OK) { sqlite3_bind_text(q, 1, line, -1, SQLITE_STATIC); if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_text(q, 0)) { info = strdup((const char *)sqlite3_column_text(q, 0)); } } sqlite3_finalize(q); if (info) { free(name); name = info; } } } if ((end || u) && user) { /* the turn that was open is finished */ (void)snprintf(key, sizeof key, "import-%s-%lld-%ld", session, now_ns, n); if (add_turn(s, session, key, user, user_line, answer.buf) != 0) { free(u); goto out; } n++; free(user); free(user_line); user = user_line = NULL; answer.len = 0; if (answer.buf) { answer.buf[0] = '\0'; } } if (u) { user = u; if (!(user_line = strdup(line))) { goto out; } } else if (a && user && *a) { if ((answer.len && ipi_buf_add(&answer, "\n\n", 2) != 0) || ipi_buf_add(&answer, a, strlen(a)) != 0) { free(a); goto out; } } free(a); if (end) { break; } } if (n == 0) { (void)snprintf(s->err, sizeof s->err, "no user messages in the session file (a Pi v3 session JSONL is expected)"); goto out; } if (name && *name && ipi_run(s, "UPDATE pic_session SET name = ? WHERE id = ?", "tt", name, session) != 0) { goto out; } if (pic_commit(s) != 0) { goto out; } (void)snprintf(session_out, cap, "%s", session); if (turns) { *turns = n; } rc = 0; out: if (rc != 0) { pic_rollback(s); } free(line); free(input.buf); free(user); free(user_line); free(name); free(answer.buf); return rc; }