Skip to content
pi-c Artifact [04359f442a]
Login

Artifact [04359f442a]

Artifact 04359f442a5eaadc331f498f5992e91bee0ff69bfdb73ec75625f19a2ed21253:


/* Pi v3 session files from the journal (pic export --pi): one append-only
 * JSONL file per conversation, named and shaped as Pi writes them
 * (reference/pi/packages/coding-agent/src/core/session-manager.ts), so ctx
 * and Pi's own tools read pic's work. Entry ids are journal entry numbers.
 * Only finished entries are written: never anything from the first entry of
 * an unfinished request on. Each export appends what is new after the
 * file's last complete entry, after dropping a torn last line. */
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>

#include "pic.h"
#include "userdb.h"

/* ~/.pic/sessions/--<cwd with / \ : as ->--, as Pi derives its folders. */
static int default_dir(const char *cwd, char *out, size_t cap) {
    const char *home = getenv("HOME");
    char enc[PATH_MAX];
    size_t j = 0;
    if (!home || !*home) {
        return -1;
    }
    for (const char *c = cwd[0] == '/' ? cwd + 1 : cwd; *c && j + 1 < sizeof enc; c++) {
        enc[j++] = (*c == '/' || *c == '\\' || *c == ':') ? '-' : *c;
    }
    enc[j] = '\0';
    return snprintf(out, cap, "%s/.pic/sessions/--%s--", home, enc) < (int)cap ? 0 : -1;
}

static int mkdirs(const char *path) {
    char p[PATH_MAX];
    (void)snprintf(p, sizeof p, "%s", path);
    for (char *c = p + 1; *c; c++) {
        if (*c == '/') {
            *c = '\0';
            if (mkdir(p, 0700) != 0 && errno != EEXIST) {
                return -1;
            }
            *c = '/';
        }
    }
    return mkdir(p, 0700) != 0 && errno != EEXIST ? -1 : 0;
}

/* DIR/<created, : and . as ->_<id>.jsonl, or "" when the conversation is unknown. */
static void file_for(pic_store *s, const char *dir, const char *id, char *out, size_t cap) {
    sqlite3_stmt *q = NULL;
    out[0] = '\0';
    if (sqlite3_prepare_v2(s->db,
                           "SELECT replace(replace(strftime('%Y-%m-%dT%H:%M:%fZ', created_ms / 1000.0, 'unixepoch'),"
                           " ':', '-'), '.', '-') FROM pic_session WHERE id = ?",
                           -1, &q, NULL) != SQLITE_OK) {
        return;
    }
    sqlite3_bind_text(q, 1, id, -1, SQLITE_STATIC);
    if (sqlite3_step(q) == SQLITE_ROW) {
        (void)snprintf(out, cap, "%s/%s_%s.jsonl", dir, (const char *)sqlite3_column_text(q, 0), id);
    }
    sqlite3_finalize(q);
}

/* What the file holds: the last entry number written and the last name.
 * A torn last line (no newline) is cut off so appends start clean. 0 when
 * the file does not exist yet (*exists = 0). */
static int file_state(pic_store *s, const char *path, int *exists, sqlite3_int64 *last, char *name, size_t cap) {
    FILE *f = fopen(path, "r+");
    char *line = NULL;
    size_t linecap = 0;
    ssize_t n;
    off_t good = 0;
    sqlite3_stmt *q = NULL;
    *exists = 0;
    *last = 0;
    name[0] = '\0';
    if (!f) {
        return errno == ENOENT ? 0 : -1;
    }
    *exists = 1;
    if (sqlite3_prepare_v2(s->db,
                           "SELECT json_extract(?1, '$.type'), CASE WHEN json_extract(?1, '$.type') IN"
                           " ('message','compaction','custom_message') THEN CAST(json_extract(?1, '$.id') AS INTEGER) END,"
                           " json_extract(?1, '$.name') WHERE json_valid(?1)",
                           -1, &q, NULL) != SQLITE_OK) {
        fclose(f);
        return -1;
    }
    while ((n = getline(&line, &linecap, f)) > 0) {
        if (line[n - 1] != '\n') {
            break; /* torn: not counted, cut below */
        }
        good += n;
        sqlite3_bind_text(q, 1, line, (int)n - 1, SQLITE_STATIC);
        if (sqlite3_step(q) == SQLITE_ROW) {
            const char *type = (const char *)sqlite3_column_text(q, 0);
            if (sqlite3_column_type(q, 1) == SQLITE_INTEGER && sqlite3_column_int64(q, 1) > *last) {
                *last = sqlite3_column_int64(q, 1);
            }
            if (type && strcmp(type, "session_info") == 0) {
                (void)snprintf(name, cap, "%s", sqlite3_column_text(q, 2) ? (const char *)sqlite3_column_text(q, 2) : "");
            }
        }
        sqlite3_reset(q);
        sqlite3_clear_bindings(q);
    }
    sqlite3_finalize(q);
    free(line);
    if (fflush(f) != 0 || ftruncate(fileno(f), good) != 0) {
        fclose(f);
        return -1;
    }
    return fclose(f) == 0 ? 0 : -1;
}

#define ISO(ms) "strftime('%Y-%m-%dT%H:%M:%fZ', " ms " / 1000.0, 'unixepoch')"
#define USAGE_FIELD(a, b) "coalesce(json_extract(g.usage,'$." a "'), json_extract(g.usage,'$." b "'), 0)"

/* The conversation's finished path entries after LAST, as Pi entries. */
static const char entries_sql[] =
    "WITH RECURSIVE p(seq) AS (SELECT head_seq FROM pic_session WHERE id = ?1"
    " UNION ALL SELECT x.parent_seq FROM pic_entry x JOIN p ON x.seq = p.seq WHERE x.parent_seq IS NOT NULL),"
    " cut(seq) AS (SELECT coalesce((SELECT min(x.seq) FROM pic_entry x JOIN pic_submission y ON y.id = x.submission_id"
    "   WHERE y.status = 'admitted'), 9223372036854775807))"
    /* Hook context goes as instructions do: a custom message (pic.hook). */
    " SELECT e.seq, CASE iif(e.kind = 'hook', 'instructions', e.kind)"
    " WHEN 'user' THEN json_object('type','message','id',CAST(e.seq AS TEXT),'parentId',CAST(e.parent_seq AS TEXT),"
    "   'timestamp'," ISO("e.created_ms") ",'message',json_object('role','user','content',"
    "   coalesce(json(pic_content(e.seq,e.body,'pi',1,0)),json_array(json_object('type','text','text',e.body))),"
    "   'timestamp',e.created_ms))"
    " WHEN 'tool_result' THEN json_object('type','message','id',CAST(e.seq AS TEXT),'parentId',CAST(e.parent_seq AS TEXT),"
    "   'timestamp'," ISO("e.created_ms") ",'message',json_object('role','toolResult','toolCallId',f.call_id,"
    "   'toolName',f.tool,'content',coalesce(json(pic_content(e.seq,e.body,'pi',1,0)),"
    "   json_array(json_object('type','text','text',e.body))),"
    "   'isError',json(iif(f.is_error,'true','false')),'timestamp',e.created_ms))"
    " WHEN 'instructions' THEN json_object('type','custom_message','id',CAST(e.seq AS TEXT),"
    "   'parentId',CAST(e.parent_seq AS TEXT),'timestamp'," ISO("e.created_ms") ",'customType','pic.' || e.kind,"
    "   'content',e.body,'display',json('false'))"
    " WHEN 'compaction' THEN json_object('type','compaction','id',CAST(e.seq AS TEXT),"
    "   'parentId',CAST(e.parent_seq AS TEXT),'timestamp'," ISO("e.created_ms") ",'summary',e.body,"
    "   'firstKeptEntryId',CAST(e.first_kept_seq AS TEXT),'tokensBefore',coalesce(e.tokens_before,0),"
    "   'details',json_object('readFiles',json(coalesce(json_extract(e.native,'$.readFiles'),'[]')),"
    "     'modifiedFiles',json(coalesce(json_extract(e.native,'$.modifiedFiles'),'[]'))))"
    " ELSE json_object('type','message','id',CAST(e.seq AS TEXT),'parentId',CAST(e.parent_seq AS TEXT),"
    "   'timestamp'," ISO("e.created_ms") ",'message',json_object('role','assistant','content',json(e.body),"
    "   'api',e.api,'provider',e.provider,'model',e.model,'usage',json_object("
    "     'input',coalesce(json_extract(g.usage,'$.pic_tokens.input')," USAGE_FIELD("input_tokens", "prompt_tokens") "),"
    "     'output',coalesce(json_extract(g.usage,'$.pic_tokens.output')," USAGE_FIELD("output_tokens", "completion_tokens") "),"
    "     'cacheRead',coalesce(json_extract(g.usage,'$.pic_tokens.cacheRead'),json_extract(g.usage,'$.cache_read_input_tokens'),"
    "       json_extract(g.usage,'$.prompt_tokens_details.cached_tokens'),"
    "       json_extract(g.usage,'$.input_tokens_details.cached_tokens'),0),"
    "     'cacheWrite',coalesce(json_extract(g.usage,'$.pic_tokens.cacheWrite'),json_extract(g.usage,'$.cache_creation_input_tokens'),0),"
    "     'totalTokens',coalesce(json_extract(g.usage,'$.pic_tokens.totalTokens'),json_extract(g.usage,'$.total_tokens'),"
    "       " USAGE_FIELD("input_tokens", "prompt_tokens") " + " USAGE_FIELD("output_tokens", "completion_tokens") ""
    "       + coalesce(json_extract(g.usage,'$.cache_read_input_tokens'),0)"
    "       + coalesce(json_extract(g.usage,'$.cache_creation_input_tokens'),0)),"
    "     'cost',json(coalesce(json_extract(g.usage,'$.pic_cost'),"
    "       '{\"input\":0,\"output\":0,\"cacheRead\":0,\"cacheWrite\":0,\"total\":0}'))),"
    "   'stopReason',coalesce(g.stop_reason,'stop'),'timestamp',e.created_ms))"
    " END"
    " FROM pic_entry e JOIN p ON p.seq = e.seq LEFT JOIN pic_effect f ON f.id = e.effect_id"
    " LEFT JOIN pic_generation g ON g.entry_seq = e.seq AND g.state = 'done'"
    " WHERE e.seq > ?2 AND e.seq < (SELECT seq FROM cut) ORDER BY e.seq";

/* Where the lines go: a file (appended), standard output, or rows of
 * picu_pi_session_line in ~/.pic/pic.sqlite. Each knows what it already
 * holds: the last entry number written and the last name recorded. */
typedef struct sink {
    int exists;              /* the header line is already there */
    sqlite3_int64 last;      /* the last journal entry written */
    char name[512];          /* the last session_info name written */
    FILE *f;                 /* file and stdout sinks */
    sqlite3 *udb;            /* row sink */
    sqlite3_stmt *ins;
    const char *conversation, *workspace;
    sqlite3_int64 next_seq;  /* row sink: the next line number */
} sink;

/* One line: TYPE is the Pi entry type ("session" for the header), ENTRY the
 * journal entry number (0 for the header and names). */
static int put(sink *k, const char *type, sqlite3_int64 entry, const char *line) {
    if (k->f) {
        return fprintf(k->f, "%s\n", line) < 0 ? -1 : 0;
    }
    sqlite3_bind_text(k->ins, 1, k->conversation, -1, SQLITE_STATIC);
    sqlite3_bind_int64(k->ins, 2, k->next_seq++);
    sqlite3_bind_text(k->ins, 3, k->workspace, -1, SQLITE_STATIC);
    sqlite3_bind_text(k->ins, 4, type, -1, SQLITE_STATIC);
    if (entry) {
        sqlite3_bind_int64(k->ins, 5, entry);
    } else {
        sqlite3_bind_null(k->ins, 5);
    }
    sqlite3_bind_text(k->ins, 6, line, -1, SQLITE_STATIC);
    {
        int rc = sqlite3_step(k->ins) == SQLITE_DONE ? 0 : -1;
        sqlite3_reset(k->ins);
        sqlite3_clear_bindings(k->ins);
        return rc;
    }
}

/* A row sink for conversation ID: what the rows already hold, and the
 * insert, inside a transaction the caller commits. */
static int rows_open(sink *k, sqlite3 *udb, const char *id, const char *cwd) {
    sqlite3_stmt *q = NULL;
    memset(k, 0, sizeof *k);
    k->udb = udb;
    k->conversation = id;
    k->workspace = cwd;
    if (sqlite3_exec(udb, "BEGIN IMMEDIATE", NULL, NULL, NULL) != SQLITE_OK) {
        return -1;
    }
    if (sqlite3_prepare_v2(udb,
                           "SELECT count(*), coalesce(max(entry), 0), coalesce(max(seq) + 1, 0),"
                           " (SELECT json_extract(CAST(CASE WHEN l.sz = length(l.line) THEN l.line ELSE sqlar_uncompress(l.line, l.sz) END"
                           "   AS TEXT), '$.name') FROM picu_pi_session_line l WHERE l.conversation = ?1 AND l.kind = 'session_info'"
                           "   ORDER BY l.seq DESC LIMIT 1)"
                           " FROM picu_pi_session_line WHERE conversation = ?1",
                           -1, &q, NULL) != SQLITE_OK) {
        return -1;
    }
    sqlite3_bind_text(q, 1, id, -1, SQLITE_STATIC);
    if (sqlite3_step(q) == SQLITE_ROW) {
        k->exists = sqlite3_column_int(q, 0) > 0;
        k->last = sqlite3_column_int64(q, 1);
        k->next_seq = sqlite3_column_int64(q, 2);
        if (sqlite3_column_text(q, 3)) {
            (void)snprintf(k->name, sizeof k->name, "%s", (const char *)sqlite3_column_text(q, 3));
        }
    }
    sqlite3_finalize(q);
    return sqlite3_prepare_v2(udb,
                              "INSERT INTO picu_pi_session_line(conversation, seq, workspace, kind, entry, sz, line)"
                              " VALUES(?1, ?2, ?3, ?4, ?5, length(CAST(?6 AS BLOB)), sqlar_compress(CAST(?6 AS BLOB)))",
                              -1, &k->ins, NULL) == SQLITE_OK
               ? 0
               : -1;
}

static int rows_close(sink *k, int ok) {
    sqlite3_finalize(k->ins);
    k->ins = NULL;
    if (ok && sqlite3_exec(k->udb, "COMMIT", NULL, NULL, NULL) == SQLITE_OK) {
        return 0;
    }
    (void)sqlite3_exec(k->udb, "ROLLBACK", NULL, NULL, NULL);
    return -1;
}

/* Writes what SINK lacks of conversation ID: the header, the finished path
 * entries after the last one written, and a session_info line when the
 * name changed. PARENT is the source file of a fork, or "". */
static int export_lines(pic_store *s, sink *k, const char *cwd, const char *id, const char *parent) {
    sqlite3_stmt *q = NULL;
    char *want_name = NULL, *created = NULL;
    sqlite3_int64 wrote = k->last;
    int step, rc = 0;
    if (sqlite3_prepare_v2(s->db, "SELECT name, " ISO("created_ms") " FROM pic_session WHERE id = ?", -1, &q, NULL) !=
        SQLITE_OK) {
        return -1;
    }
    sqlite3_bind_text(q, 1, id, -1, SQLITE_STATIC);
    if (sqlite3_step(q) == SQLITE_ROW) {
        want_name = sqlite3_column_text(q, 0) ? strdup((const char *)sqlite3_column_text(q, 0)) : NULL;
        created = strdup((const char *)sqlite3_column_text(q, 1));
    }
    sqlite3_finalize(q);
    if (!k->exists) {
        sqlite3_stmt *h = NULL;
        if (sqlite3_prepare_v2(s->db,
                               "SELECT json_object('type','session','version',3,'id',?1,'timestamp',?2,'cwd',?3,"
                               "'parentSession',nullif(?4,''))",
                               -1, &h, NULL) == SQLITE_OK) {
            sqlite3_bind_text(h, 1, id, -1, SQLITE_STATIC);
            sqlite3_bind_text(h, 2, created ? created : "", -1, SQLITE_STATIC);
            sqlite3_bind_text(h, 3, cwd, -1, SQLITE_STATIC);
            sqlite3_bind_text(h, 4, parent, -1, SQLITE_STATIC);
            if (sqlite3_step(h) == SQLITE_ROW) {
                /* json_object keeps a null parentSession; Pi omits it. */
                const char *t = (const char *)sqlite3_column_text(h, 0);
                const char *nul = strstr(t, ",\"parentSession\":null");
                char *line = nul ? sqlite3_mprintf("%.*s}", (int)(nul - t), t) : sqlite3_mprintf("%s", t);
                rc = line ? put(k, "session", 0, line) : -1;
                sqlite3_free(line);
            }
            sqlite3_finalize(h);
        }
    }
    if (rc == 0 && sqlite3_prepare_v2(s->db, entries_sql, -1, &q, NULL) != SQLITE_OK) {
        (void)snprintf(s->err, sizeof s->err, "sql: %s", sqlite3_errmsg(s->db));
        rc = -1;
    }
    if (rc == 0) {
        sqlite3_bind_text(q, 1, id, -1, SQLITE_STATIC);
        sqlite3_bind_int64(q, 2, k->last);
        while (rc == 0 && (step = sqlite3_step(q)) == SQLITE_ROW) {
            const char *line = (const char *)sqlite3_column_text(q, 1);
            char type[32] = "message";
            const char *t = strstr(line, "\"type\":\"");
            if (t) {
                (void)snprintf(type, sizeof type, "%.*s", (int)strcspn(t + 8, "\""), t + 8);
            }
            rc = put(k, type, sqlite3_column_int64(q, 0), line);
            wrote = sqlite3_column_int64(q, 0);
        }
        if (rc == 0 && step != SQLITE_DONE) {
            (void)snprintf(s->err, sizeof s->err, "sql: %s", sqlite3_errmsg(s->db));
            rc = -1;
        }
        sqlite3_finalize(q);
    }
    /* A name given or changed since the last export, as Pi records one. */
    if (rc == 0 && want_name && strcmp(want_name, k->name) != 0) {
        sqlite3_stmt *n = NULL;
        if (sqlite3_prepare_v2(s->db,
                               "SELECT json_object('type','session_info','id','name-' || ?1 || '-' || hex(randomblob(4)),"
                               "'parentId',nullif(?1,'0'),'timestamp'," ISO("CAST(unixepoch('subsec') * 1000 AS INTEGER)")
                               ",'name',?2)",
                               -1, &n, NULL) == SQLITE_OK) {
            char at[32];
            (void)snprintf(at, sizeof at, "%lld", (long long)wrote);
            sqlite3_bind_text(n, 1, at, -1, SQLITE_TRANSIENT);
            sqlite3_bind_text(n, 2, want_name, -1, SQLITE_STATIC);
            if (sqlite3_step(n) == SQLITE_ROW) {
                rc = put(k, "session_info", 0, (const char *)sqlite3_column_text(n, 0));
            }
            sqlite3_finalize(n);
        }
    }
    free(want_name);
    free(created);
    return rc;
}

/* The source file of a fork, named as its file in DIR would be. */
static void parent_of(pic_store *s, const char *dir, const char *id, char *out, size_t cap) {
    sqlite3_stmt *q = NULL;
    out[0] = '\0';
    if (sqlite3_prepare_v2(s->db, "SELECT forked_from FROM pic_session WHERE id = ?", -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, id, -1, SQLITE_STATIC);
        if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_text(q, 0) && dir) {
            char forked[64];
            (void)snprintf(forked, sizeof forked, "%s", (const char *)sqlite3_column_text(q, 0));
            sqlite3_finalize(q);
            file_for(s, dir, forked, out, cap);
            return;
        }
        sqlite3_finalize(q);
    }
}

static int export_file(pic_store *s, const char *dir, const char *cwd, const char *id) {
    char path[PATH_MAX], parent[PATH_MAX];
    sink k;
    int rc;
    memset(&k, 0, sizeof k);
    file_for(s, dir, id, path, sizeof path);
    if (!path[0]) {
        (void)snprintf(s->err, sizeof s->err, "no conversation %s", id);
        return -1;
    }
    if (file_state(s, path, &k.exists, &k.last, k.name, sizeof k.name) != 0 || !(k.f = fopen(path, "a"))) {
        (void)snprintf(s->err, sizeof s->err, "cannot write %s: %s", path, strerror(errno));
        return -1;
    }
    parent_of(s, dir, id, parent, sizeof parent);
    rc = export_lines(s, &k, cwd, id, parent);
    if (fflush(k.f) != 0 || fsync(fileno(k.f)) != 0) {
        rc = -1;
    }
    if (fclose(k.f) != 0 && rc == 0) {
        (void)snprintf(s->err, sizeof s->err, "cannot write %s: %s", path, strerror(errno));
        rc = -1;
    }
    return rc;
}

static int export_stdout(pic_store *s, const char *cwd, const char *id) {
    sink k;
    memset(&k, 0, sizeof k);
    k.f = stdout;
    return export_lines(s, &k, cwd, id, "");
}

static int export_rows(pic_store *s, sqlite3 *udb, const char *dir, const char *cwd, const char *id) {
    char parent[PATH_MAX];
    sink k;
    int rc;
    parent_of(s, dir, id, parent, sizeof parent);
    if (rows_open(&k, udb, id, cwd) != 0) {
        (void)snprintf(s->err, sizeof s->err, "pic.sqlite: %s", sqlite3_errmsg(udb));
        (void)rows_close(&k, 0);
        return -1;
    }
    rc = export_lines(s, &k, cwd, id, parent);
    if (rows_close(&k, rc == 0) != 0 && rc == 0) {
        (void)snprintf(s->err, sizeof s->err, "pic.sqlite: %s", sqlite3_errmsg(udb));
        rc = -1;
    }
    return rc;
}

/* DIR NULL: rows in ~/.pic/pic.sqlite (ctx reads them), plus the ~/.pic/sessions
 * files only with piSessionFiles=1; "-": standard output; otherwise files in DIR. */
static int export_one(pic_store *s, const char *dir, const char *cwd, const char *id) {
    char dbuf[PATH_MAX], err[256];
    sqlite3 *udb;
    int rc = 0;
    if (dir && strcmp(dir, "-") == 0) {
        return export_stdout(s, cwd, id);
    }
    if (dir) {
        return export_file(s, dir, cwd, id);
    }
    if (default_dir(cwd, dbuf, sizeof dbuf) != 0) {
        (void)snprintf(s->err, sizeof s->err, "no home directory for ~/.pic");
        return -1;
    }
    if (!(udb = pic_userdb(err, sizeof err))) {
        (void)snprintf(s->err, sizeof s->err, "%s", err);
        return -1;
    }
    rc = export_rows(s, udb, dbuf, cwd, id);
    {
        char *files = pic_setting("piSessionFiles");
        int write_files = files && strcmp(files, "1") == 0;
        free(files);
        if (rc == 0 && write_files) {
            rc = mkdirs(dbuf) != 0 ? -1 : export_file(s, dbuf, cwd, id);
        }
    }
    return rc;
}

int pic_export_pi(pic_store *s, const char *workspace, const char *dir, const char *session) {
    char cwd[PATH_MAX];
    sqlite3_stmt *q = NULL;
    int rc = 0;
    if (!realpath(workspace, cwd)) {
        (void)snprintf(cwd, sizeof cwd, "%s", workspace);
    }
    if (dir && strcmp(dir, "-") != 0 && mkdirs(dir) != 0) {
        (void)snprintf(s->err, sizeof s->err, "cannot create %s: %s", dir, strerror(errno));
        return -1;
    }
    if (session) {
        char id[64];
        return pic_session_resolve(s, session, id, sizeof id) == 0 ? export_one(s, dir, cwd, id) : -1;
    }
    if (sqlite3_prepare_v2(s->db, "SELECT id FROM pic_session WHERE head_seq IS NOT NULL ORDER BY created_ms, id", -1,
                           &q, NULL) != SQLITE_OK) {
        return -1;
    }
    while (rc == 0 && sqlite3_step(q) == SQLITE_ROW) {
        char id[64];
        (void)snprintf(id, sizeof id, "%s", (const char *)sqlite3_column_text(q, 0));
        rc = export_one(s, dir, cwd, id);
    }
    sqlite3_finalize(q);
    return rc;
}