Skip to content
pi-c Artifact [f2995d09ac]
Login

Artifact [f2995d09ac]

Artifact f2995d09acadbd7188833ca8f48d2f1cf1b0256f5c6688fb4729d25b3a0e8407:


/* Cross-provider conversion, Pi's transformMessages rules in one place.
 *
 * A reply is replayed verbatim (its native form) only to the provider, API
 * and model that produced it. Any other target gets it rebuilt from the
 * neutral form: thinking is dropped (signatures are bound to the model that
 * made them), and tool-call ids are rewritten to the target's limits by
 * pic_norm_id, applied identically to the calls and to their results. */
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "pic.h"

/* 8 hex digits of FNV-1a: ids only need to be stable and distinct. */
static void short_hash(const char *s, char out[9]) {
    uint32_t h = 2166136261u;
    for (; *s; s++) {
        h ^= (unsigned char)*s;
        h *= 16777619u;
    }
    (void)snprintf(out, 9, "%08x", h);
}

/* Characters outside [A-Za-z0-9_-] become '_'. */
static void sanitize(char *s) {
    for (; *s; s++) {
        char c = *s;
        if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' || c == '-')) {
            *s = '_';
        }
    }
}

/* pic_norm_id(id, target_api, target_provider): a foreign tool-call id as
 * the target accepts it.
 *   anthropic-messages  [A-Za-z0-9_-], at most 64
 *   openai-completions  "call|item" ids become call_item; over 40 characters
 *                       becomes prefix_hash; OpenAI itself caps at 40
 *   openai-responses    [A-Za-z0-9_-], at most 64, no trailing '_'
 *   google-generative-ai [A-Za-z0-9_-], at most 64 (the default rule) */
static void norm_id(sqlite3_context *ctx, int argc, sqlite3_value **argv) {
    const char *id = (const char *)sqlite3_value_text(argv[0]);
    const char *api = (const char *)sqlite3_value_text(argv[1]);
    const char *provider = argc > 2 ? (const char *)sqlite3_value_text(argv[2]) : "";
    char buf[512], hash[9];
    size_t n;
    if (!id || !api) {
        sqlite3_result_null(ctx);
        return;
    }
    (void)snprintf(buf, sizeof buf, "%s", id);
    if (strcmp(api, "openai-completions") == 0) {
        char *bar = strchr(buf, '|');
        if (bar) {
            *bar = '_';
            sanitize(buf);
            if (strlen(buf) > 40) {
                short_hash(id, hash);
                buf[40 - 9] = '\0';
                (void)snprintf(buf + strlen(buf), sizeof buf - strlen(buf), "_%s", hash);
            }
        } else if (provider && strcmp(provider, "openai") == 0 && strlen(buf) > 40) {
            buf[40] = '\0';
        }
        sqlite3_result_text(ctx, buf, -1, SQLITE_TRANSIENT);
        return;
    }
    sanitize(buf);
    if (strlen(buf) > 64) {
        buf[64] = '\0';
    }
    if (strcmp(api, "openai-responses") == 0) {
        for (n = strlen(buf); n > 0 && buf[n - 1] == '_'; n--) {
            buf[n - 1] = '\0';
        }
    }
    sqlite3_result_text(ctx, buf, -1, SQLITE_TRANSIENT);
}

/* pic_base64(blob): its standard base64 text, as image blocks carry it. */
static void base64(sqlite3_context *ctx, int argc, sqlite3_value **argv) {
    const unsigned char *in = sqlite3_value_blob(argv[0]);
    size_t n = (size_t)sqlite3_value_bytes(argv[0]);
    char *out;
    (void)argc;
    if (sqlite3_value_type(argv[0]) == SQLITE_NULL) {
        sqlite3_result_null(ctx);
        return;
    }
    if (!(out = sqlite3_malloc64((n + 2) / 3 * 4 + 1))) {
        sqlite3_result_error_nomem(ctx);
        return;
    }
    n = pic_base64_encode(in, n, out);
    sqlite3_result_text64(ctx, out, n, sqlite3_free, SQLITE_UTF8);
}

/* A JSON string literal of the n bytes at t. */
static void json_string(sqlite3_str *out, const char *t, size_t n) {
    sqlite3_str_appendchar(out, 1, '"');
    for (size_t i = 0; i < n; i++) {
        unsigned char c = (unsigned char)t[i];
        if (c == '"' || c == '\\') {
            sqlite3_str_appendchar(out, 1, '\\');
            sqlite3_str_appendchar(out, 1, (char)c);
        } else if (c == '\n') {
            sqlite3_str_appendall(out, "\\n");
        } else if (c == '\t') {
            sqlite3_str_appendall(out, "\\t");
        } else if (c == '\r') {
            sqlite3_str_appendall(out, "\\r");
        } else if (c < 0x20) {
            sqlite3_str_appendf(out, "\\u%04x", c);
        } else {
            sqlite3_str_appendchar(out, 1, (char)c);
        }
    }
    sqlite3_str_appendchar(out, 1, '"');
}

static int tf_blank(const char *t, size_t n) {
    for (size_t i = 0; i < n; i++) {
        if (t[i] != ' ' && t[i] != '\t' && t[i] != '\n' && t[i] != '\r') {
            return 0;
        }
    }
    return 1;
}

/* One block of an entry's content as it goes out: text (owned) or an image
 * (mime and base64 data, owned). */
typedef struct {
    char *text, *mime, *data;
} block;

static char *tf_dup_text(const char *t) {
    size_t n = strlen(t);
    char *p = sqlite3_malloc64(n + 1);
    if (p) {
        memcpy(p, t, n + 1);
    }
    return p;
}

static void text_block(sqlite3_str *out, const char *type, const char *text) {
    sqlite3_str_appendf(out, "{\"type\":\"%s\",\"text\":", type);
    json_string(out, text, strlen(text));
    sqlite3_str_appendchar(out, 1, '}');
}

static void image_block(sqlite3_str *out, const char *shape, const block *b) {
    if (strncmp(shape, "pi", 2) == 0) {
        sqlite3_str_appendf(out, "{\"type\":\"image\",\"data\":\"%s\",\"mimeType\":\"%s\"}", b->data, b->mime);
    } else if (strncmp(shape, "anthropic", 9) == 0) {
        sqlite3_str_appendf(out, "{\"type\":\"image\",\"source\":{\"type\":\"base64\",\"media_type\":\"%s\",\"data\":\"%s\"}}",
                            b->mime, b->data);
    } else if (strncmp(shape, "chat", 4) == 0) {
        sqlite3_str_appendf(out, "{\"type\":\"image_url\",\"image_url\":{\"url\":\"data:%s;base64,%s\"}}", b->mime, b->data);
    } else {
        sqlite3_str_appendf(out, "{\"type\":\"input_image\",\"detail\":\"auto\",\"image_url\":\"data:%s;base64,%s\"}", b->mime,
                            b->data);
    }
}

/* The text blocks joined by newlines, as Pi joins a tool result's text. */
static void joined_text(sqlite3_str *t, const block *v, int n) {
    int first = 1;
    for (int i = 0; i < n; i++) {
        if (v[i].text) {
            sqlite3_str_appendall(t, first ? "" : "\n");
            sqlite3_str_appendall(t, v[i].text);
            first = 0;
        }
    }
}

/* pic_content(seq, body, shape, vision, first): the content of user or
 * tool_result entry SEQ, whose text is BODY, with its images, as JSON text
 * in SHAPE (wrap it in json()); NULL when it has no images, so callers send
 * BODY as they always have. Each image goes out as itself, or as text: Pi's
 * placeholder when the model takes no images (VISION 0) or the image is
 * older than attachment FIRST (the request's image budget, provider_http.c),
 * consecutive ones as one, as Pi's transformMessages does; "[image removed]"
 * once its bytes are pruned. Shapes, as Pi's adapters build them:
 *   pi               every block in Pi's own form (sessions, export)
 *   pi-images        the blocks after the text (events add them to it)
 *   anthropic-user   the blocks, blank text left out
 *   anthropic-tool   the blocks while an image is left, else the text joined
 *   chat-user        the blocks, empty text left out
 *   chat-tool        the text joined, as a string
 *   chat-tool-images the image parts alone, NULL when none is left (they go
 *                    after the run of tool results in a user message)
 *   responses-user   the blocks
 *   responses-tool   the text and the images while an image is left, else
 *                    the text joined */
static void content(sqlite3_context *ctx, int argc, sqlite3_value **argv) {
    sqlite3 *db = sqlite3_context_db_handle(ctx);
    sqlite3_int64 seq = sqlite3_value_int64(argv[0]), first = sqlite3_value_int64(argv[4]);
    const char *body = (const char *)sqlite3_value_text(argv[1]);
    const char *shape = (const char *)sqlite3_value_text(argv[2]);
    int vision = sqlite3_value_int(argv[3]), n = 0, cap = 0, images = 0, step, oom = 0, failed = 0;
    int pi, tool;
    const char *ttype, *placeholder;
    block *v = NULL;
    sqlite3_stmt *q = NULL;
    sqlite3_str *out;
    (void)argc;
    if (!shape) {
        sqlite3_result_error(ctx, "pic_content: no shape", -1);
        return;
    }
    pi = strncmp(shape, "pi", 2) == 0;
    tool = strstr(shape, "-tool") != NULL;
    ttype = strncmp(shape, "responses", 9) == 0 ? "input_text" : "text";
    placeholder = tool ? PIC_IMAGE_TOOL_PLACEHOLDER : PIC_IMAGE_USER_PLACEHOLDER;
    if (pi) {
        vision = 1;
        first = 0;
    }
    if (sqlite3_prepare_v2(db,
                           "SELECT r.id, i.mime, pic_base64(sqlar_uncompress(i.data, i.sz)) FROM pic_attachment r"
                           " JOIN pic_image i ON i.hash = r.image WHERE r.entry_seq = ?1 ORDER BY r.ordinal",
                           -1, &q, NULL) != SQLITE_OK) {
        sqlite3_result_error(ctx, sqlite3_errmsg(db), -1);
        return;
    }
    sqlite3_bind_int64(q, 1, seq);
    if (!(v = sqlite3_malloc64(4 * sizeof *v)) || !(v[0].text = tf_dup_text(body ? body : ""))) {
        sqlite3_free(v);
        sqlite3_finalize(q);
        sqlite3_result_error_nomem(ctx);
        return;
    }
    v[0].mime = v[0].data = NULL;
    n = 1;
    cap = 4;
    while ((step = sqlite3_step(q)) == SQLITE_ROW) {
        block b = {NULL, NULL, NULL};
        if (sqlite3_column_type(q, 2) == SQLITE_NULL) {
            b.text = tf_dup_text(PIC_IMAGE_REMOVED);
        } else if (!vision || sqlite3_column_int64(q, 0) < first) {
            if (v[n - 1].text && n > 1 && strcmp(v[n - 1].text, placeholder) == 0) {
                continue; /* one placeholder for a run of images */
            }
            b.text = tf_dup_text(placeholder);
        } else {
            b.mime = tf_dup_text((const char *)sqlite3_column_text(q, 1));
            b.data = tf_dup_text((const char *)sqlite3_column_text(q, 2));
            images++;
        }
        if (n == cap) {
            block *grown = sqlite3_realloc64(v, (sqlite3_uint64)cap * 2 * sizeof *v);
            if (!grown) {
                sqlite3_free(b.text);
                sqlite3_free(b.mime);
                sqlite3_free(b.data);
                oom = 1;
                break;
            }
            v = grown;
            cap *= 2;
        }
        v[n++] = b;
        oom |= !(b.text || (b.mime && b.data));
    }
    failed = !oom && step != SQLITE_DONE;
    sqlite3_finalize(q);
    out = sqlite3_str_new(db);
    if (n <= 1 || failed || oom) {
        /* no images: NULL */
    } else if (strcmp(shape, "chat-tool") == 0 || (!images && (strcmp(shape, "anthropic-tool") == 0 || strcmp(shape, "responses-tool") == 0))) {
        sqlite3_str *t = sqlite3_str_new(db);
        char *joined;
        joined_text(t, v, n);
        joined = sqlite3_str_finish(t);
        json_string(out, joined && !tf_blank(joined, strlen(joined)) ? joined : images ? "(see attached image)" : "(no tool output)",
                    joined && !tf_blank(joined, strlen(joined)) ? strlen(joined) : images ? 20 : 16);
        sqlite3_free(joined);
    } else if (strcmp(shape, "chat-tool-images") == 0 || strcmp(shape, "pi-images") == 0) {
        int any = 0;
        sqlite3_str_appendchar(out, 1, '[');
        for (int i = 1; i < n; i++) {
            if (v[i].text && strcmp(shape, "pi-images") != 0) {
                continue;
            }
            sqlite3_str_appendall(out, any++ ? "," : "");
            if (v[i].text) {
                text_block(out, ttype, v[i].text);
            } else {
                image_block(out, shape, &v[i]);
            }
        }
        sqlite3_str_appendchar(out, 1, ']');
        if (!any) {
            sqlite3_str_reset(out);
        }
    } else if (strcmp(shape, "responses-tool") == 0) {
        sqlite3_str *t = sqlite3_str_new(db);
        char *joined;
        int any = 0;
        joined_text(t, v, n);
        joined = sqlite3_str_finish(t);
        sqlite3_str_appendchar(out, 1, '[');
        if (joined && !tf_blank(joined, strlen(joined))) {
            text_block(out, ttype, joined);
            any = 1;
        }
        sqlite3_free(joined);
        for (int i = 1; i < n; i++) {
            if (!v[i].text) {
                sqlite3_str_appendall(out, any++ ? "," : "");
                image_block(out, shape, &v[i]);
            }
        }
        sqlite3_str_appendchar(out, 1, ']');
    } else {
        int any = 0;
        sqlite3_str_appendchar(out, 1, '[');
        for (int i = 0; i < n; i++) {
            if (v[i].text && ((strcmp(shape, "anthropic-user") == 0 && tf_blank(v[i].text, strlen(v[i].text))) ||
                              (strcmp(shape, "chat-user") == 0 && !*v[i].text))) {
                continue;
            }
            sqlite3_str_appendall(out, any++ ? "," : "");
            if (v[i].text) {
                text_block(out, ttype, v[i].text);
            } else {
                image_block(out, shape, &v[i]);
            }
        }
        sqlite3_str_appendchar(out, 1, ']');
    }
    for (int i = 0; i < n; i++) {
        sqlite3_free(v[i].text);
        sqlite3_free(v[i].mime);
        sqlite3_free(v[i].data);
    }
    sqlite3_free(v);
    if (failed) {
        sqlite3_free(sqlite3_str_finish(out));
        sqlite3_result_error(ctx, "pic_content: cannot read the images", -1);
    } else if (oom || sqlite3_str_errcode(out) != SQLITE_OK) {
        sqlite3_free(sqlite3_str_finish(out));
        sqlite3_result_error_nomem(ctx);
    } else if (sqlite3_str_length(out) == 0) {
        sqlite3_free(sqlite3_str_finish(out));
        sqlite3_result_null(ctx);
    } else {
        int len = sqlite3_str_length(out);
        sqlite3_result_text(ctx, sqlite3_str_finish(out), len, sqlite3_free);
    }
}

sqlite3_int64 pic_image_budget(pic_store *s, int64_t submission) {
    sqlite3_stmt *q = NULL;
    sqlite3_int64 first = INT64_MAX;
    if (sqlite3_prepare_v2(s->db,
                           PIC_CONTEXT_CTE "SELECT min(id) FROM (SELECT r.id, sum((i.sz + 2) / 3 * 4) OVER w AS total,"
                           " row_number() OVER w AS k FROM pic_attachment r JOIN pic_image i ON i.hash = r.image"
                           " JOIN v ON v.seq = r.entry_seq WHERE i.data IS NOT NULL WINDOW w AS (ORDER BY r.id DESC))"
                           " WHERE total <= ?2 AND k <= ?3",
                           -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_int64(q, 1, submission);
        sqlite3_bind_int64(q, 2, PIC_REQUEST_IMAGE_BYTES);
        sqlite3_bind_int64(q, 3, PIC_REQUEST_IMAGES);
        if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_type(q, 0) != SQLITE_NULL) {
            first = sqlite3_column_int64(q, 0);
        }
    }
    sqlite3_finalize(q);
    return first;
}

int pic_images_from_json(sqlite3 *db, const char *json, const char *path, int all, 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;
    /* Each element must be an object (json_extract on a string element
     * would fail the whole statement, not just the row). */
    if (sqlite3_prepare_v2(db,
                           "SELECT CASE type WHEN 'object' THEN json_extract(value, '$.type') IS 'image'"
                           " AND json_type(value, '$.data') IS 'text' AND json_type(value, '$.mimeType') IS 'text' ELSE 0 END,"
                           " CASE type WHEN 'object' THEN json_extract(value, '$.data') END,"
                           " CASE type WHEN 'object' THEN json_extract(value, '$.mimeType') END"
                           " FROM json_each(?1, ?2) WHERE ?3 OR CASE type WHEN 'object' THEN json_extract(value, '$.type') IS 'image' ELSE 0 END",
                           -1, &q, NULL) != SQLITE_OK) {
        *error = "out of memory";
        return -1;
    }
    sqlite3_bind_text(q, 1, json, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 2, path, -1, SQLITE_STATIC);
    sqlite3_bind_int(q, 3, all);
    /* 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 && step != SQLITE_DONE) {
        *error = "images could not be read";
        rc = -1;
    }
    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; i++) {
        if (sqlite3_step(q) != SQLITE_ROW) {
            *error = "images could not be read";
            rc = -1;
            break;
        }
        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;
}

int pic_transform_register(sqlite3 *db) {
    return sqlite3_create_function(db, "pic_norm_id", 3, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, norm_id, NULL,
                                   NULL) == SQLITE_OK &&
                   sqlite3_create_function(db, "pic_base64", 1, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, base64, NULL,
                                           NULL) == SQLITE_OK &&
                   sqlite3_create_function(db, "pic_content", 5, SQLITE_UTF8, NULL, content, NULL,
                                           NULL) == SQLITE_OK
               ? 0
               : -1;
}

char *pic_neutral_from_anthropic(sqlite3 *db, const char *native) {
    sqlite3_stmt *q = NULL;
    char *out = NULL;
    /* Block types pic does not map (server tools, compaction, …) stay in the
     * native form only: the same model gets them back, others never see them. */
    if (sqlite3_prepare_v2(
            db,
            "SELECT coalesce(json_group_array(json(x)), '[]') FROM (SELECT CASE json_extract(value,'$.type')"
            " WHEN 'text' THEN json_object('type','text','text',json_extract(value,'$.text'))"
            " WHEN 'thinking' THEN json_object('type','thinking','thinking',coalesce(json_extract(value,'$.thinking'),''),"
            "   'signature',json_extract(value,'$.signature'))"
            " WHEN 'redacted_thinking' THEN json_object('type','thinking','thinking','','signature',"
            "   json_extract(value,'$.data'),'redacted',json('true'))"
            " WHEN 'tool_use' THEN json_object('type','toolCall','id',coalesce(json_extract(value,'$.id'),''),"
            "   'name',coalesce(json_extract(value,'$.name'),''),'arguments',"
            "   CASE json_type(value,'$.input') WHEN 'object' THEN json(json_extract(value,'$.input'))"
            "   ELSE json_object('pic_invalid_input', json_extract(value,'$.input')) END)"
            " END AS x FROM json_each(?1) ORDER BY key) WHERE x IS NOT NULL",
            -1, &q, NULL) != SQLITE_OK) {
        return NULL;
    }
    sqlite3_bind_text(q, 1, native, -1, SQLITE_STATIC);
    if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_text(q, 0)) {
        const char *t = (const char *)sqlite3_column_text(q, 0);
        out = malloc(strlen(t) + 1);
        if (out) {
            memcpy(out, t, strlen(t) + 1);
        }
    }
    sqlite3_finalize(q);
    return out;
}