/* Pi v3 session JSONL into a new pic conversation (Pi's /import). Only the
* text survives: each user message becomes a request, 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"
typedef struct {
char *buf;
size_t len, cap;
} buf;
static int buf_add(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 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;
}
/* One finished request: the user text and, when there was any, the answer. */
static int add_turn(pic_store *s, const char *session, const char *key, const char *user, const char *answer) {
sqlite3_int64 sub, seq;
sqlite3_stmt *q = NULL;
char *body = NULL;
int rc;
if (run(s, "INSERT INTO pic_submission(request_key, content, status, session_id) VALUES(?, ?, 'admitted', ?)", "ttt",
key, user, session) != 0) {
return -1;
}
sub = sqlite3_last_insert_rowid(s->db);
if (run(s, "INSERT INTO pic_entry(submission_id, kind, body) VALUES(?, 'user', ?)", "it", sub, user) != 0) {
return -1;
}
if (!answer || !*answer) {
return 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 = 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 run(s, "UPDATE pic_submission SET status = 'answered' WHERE id = ?", "i", sub) ||
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, *name = NULL, session[16], key[96];
size_t linecap = 0;
buf answer = {NULL, 0, 0};
long n = 0;
ssize_t got;
int rc = -1;
struct timespec ts;
(void)clock_gettime(CLOCK_REALTIME, &ts);
if (pic_begin(s) != 0) {
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);
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;
got = getline(&line, &linecap, in);
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%09ld-%ld", session, (long long)ts.tv_sec, ts.tv_nsec, n);
if (add_turn(s, session, key, user, answer.buf) != 0) {
free(u);
goto out;
}
n++;
free(user);
user = NULL;
answer.len = 0;
if (answer.buf) {
answer.buf[0] = '\0';
}
}
if (u) {
user = u;
} else if (a && user && *a) {
if ((answer.len && buf_add(&answer, "\n\n", 2) != 0) || 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 && 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(user);
free(name);
free(answer.buf);
return rc;
}