Skip to content
pi-c Artifact [2ce17e6079]
Login

Artifact [2ce17e6079]

Artifact 2ce17e60796b7535f38604e45dacb45830186df50a81a3c7d8b270c0ac84d7bf:


/* 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"

/* ~/.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))"
    " SELECT e.seq, CASE 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',"
    "   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',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.instructions',"
    "   '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'," USAGE_FIELD("input_tokens", "prompt_tokens") ",'output'," USAGE_FIELD("output_tokens", "completion_tokens") ","
    "     'cacheRead',coalesce(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,'$.cache_creation_input_tokens'),0),"
    "     'totalTokens',coalesce(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_object('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";

static int export_one(pic_store *s, const char *dir, const char *cwd, const char *id) {
    sqlite3_stmt *q = NULL;
    char path[PATH_MAX], parent[PATH_MAX] = "", name[512], *forked = NULL, *want_name = NULL, *created = NULL;
    sqlite3_int64 last = 0, wrote = 0;
    int exists = 0, step, rc = 0;
    FILE *f;
    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, &exists, &last, name, sizeof name) != 0) {
        (void)snprintf(s->err, sizeof s->err, "cannot read %s: %s", path, strerror(errno));
        return -1;
    }
    if (sqlite3_prepare_v2(s->db,
                           "SELECT forked_from, 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) {
        forked = sqlite3_column_text(q, 0) ? strdup((const char *)sqlite3_column_text(q, 0)) : NULL;
        want_name = sqlite3_column_text(q, 1) ? strdup((const char *)sqlite3_column_text(q, 1)) : NULL;
        created = strdup((const char *)sqlite3_column_text(q, 2));
    }
    sqlite3_finalize(q);
    if (forked) {
        file_for(s, dir, forked, parent, sizeof parent);
    }
    f = fopen(path, "a");
    if (!f) {
        (void)snprintf(s->err, sizeof s->err, "cannot write %s: %s", path, strerror(errno));
        rc = -1;
        goto done;
    }
    if (!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");
                if (nul) {
                    fprintf(f, "%.*s}\n", (int)(nul - t), t);
                } else {
                    fprintf(f, "%s\n", t);
                }
            }
            sqlite3_finalize(h);
        }
    }
    if (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));
        fclose(f);
        rc = -1;
        goto done;
    }
    sqlite3_bind_text(q, 1, id, -1, SQLITE_STATIC);
    sqlite3_bind_int64(q, 2, last);
    wrote = last;
    while ((step = sqlite3_step(q)) == SQLITE_ROW) {
        fprintf(f, "%s\n", (const char *)sqlite3_column_text(q, 1));
        wrote = sqlite3_column_int64(q, 0);
    }
    sqlite3_finalize(q);
    if (step != SQLITE_DONE) {
        (void)snprintf(s->err, sizeof s->err, "sql: %s", sqlite3_errmsg(s->db));
        rc = -1;
    }
    /* A name given or changed since the last export, as Pi records one. */
    if (rc == 0 && want_name && strcmp(want_name, 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) {
                fprintf(f, "%s\n", (const char *)sqlite3_column_text(n, 0));
            }
            sqlite3_finalize(n);
        }
    }
    if (fflush(f) != 0 || fsync(fileno(f)) != 0) {
        rc = -1;
    }
    if (fclose(f) != 0 && rc == 0) {
        (void)snprintf(s->err, sizeof s->err, "cannot write %s: %s", path, strerror(errno));
        rc = -1;
    }
done:
    free(forked);
    free(want_name);
    free(created);
    return rc;
}

int pic_export_pi(pic_store *s, const char *workspace, const char *dir, const char *session) {
    char cwd[PATH_MAX], dbuf[PATH_MAX];
    sqlite3_stmt *q = NULL;
    int rc = 0;
    if (!realpath(workspace, cwd)) {
        (void)snprintf(cwd, sizeof cwd, "%s", workspace);
    }
    if (!dir) {
        if (default_dir(cwd, dbuf, sizeof dbuf) != 0) {
            (void)snprintf(s->err, sizeof s->err, "no home directory for ~/.pic/sessions");
            return -1;
        }
        dir = dbuf;
    }
    if (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;
}