/* 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 '_' */
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 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;
}
/* pic_content(seq, body, shape, vision): the content of user or tool_result
* entry SEQ, whose text is BODY, with its images, as JSON in SHAPE; NULL when
* it has no images (callers send BODY as they always have). VISION is
* whether the model takes images; when it does not, Pi's transformMessages
* puts one placeholder where they were. Shapes, as Pi's adapters build them:
* pi [text, image...] in Pi's own blocks (sessions, export)
* pi-images [image...] alone (events add them after the text)
* anthropic-user [text unless blank, image... | placeholder]
* anthropic-tool [text, image...], or the text and placeholder as a string
* chat-user [text unless empty, image_url... | placeholder]
* chat-tool the text (with the placeholder) as a string
* chat-tool-images image_url parts alone, NULL without vision (they go
* after the run of tool results in a user message)
* responses-user [input_text, input_image... | placeholder]
* responses-tool [input_text unless blank, input_image...], or a string */
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]);
const char *body = (const char *)sqlite3_value_text(argv[1]);
size_t blen = (size_t)sqlite3_value_bytes(argv[1]);
const char *shape = (const char *)sqlite3_value_text(argv[2]);
int vision = sqlite3_value_int(argv[3]), n = 0, first = 1, step;
const char *text_type = "text", *placeholder = PIC_IMAGE_USER_PLACEHOLDER;
int keep_text = 1, as_string = 0, images_only = 0;
sqlite3_stmt *q = NULL;
sqlite3_str *out;
(void)argc;
if (!body) {
body = "";
}
if (!shape) {
sqlite3_result_error(ctx, "pic_content: no shape", -1);
return;
}
if (sqlite3_prepare_v2(db,
"SELECT 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 (strcmp(shape, "pi") == 0) {
vision = 1;
} else if (strcmp(shape, "pi-images") == 0) {
vision = 1;
images_only = 1;
} else if (strcmp(shape, "anthropic-user") == 0 || strcmp(shape, "responses-tool") == 0) {
keep_text = !blank(body, blen);
} else if (strcmp(shape, "chat-user") == 0) {
keep_text = blen > 0;
} else if (strcmp(shape, "chat-tool-images") == 0) {
images_only = 1;
}
if (strncmp(shape, "responses", 9) == 0) {
text_type = "input_text";
}
if (strcmp(shape, "chat-tool") == 0 || (!vision && strstr(shape, "-tool"))) {
as_string = 1;
placeholder = PIC_IMAGE_TOOL_PLACEHOLDER;
}
out = sqlite3_str_new(db);
if (!as_string) {
sqlite3_str_appendchar(out, 1, '[');
}
if (as_string || (keep_text && !images_only)) {
if (!as_string) {
sqlite3_str_appendf(out, "{\"type\":\"%s\",\"text\":", text_type);
}
if (as_string && vision) {
json_string(out, body, blen);
} else if (as_string) {
char *joined = sqlite3_mprintf("%s\n%s", body, placeholder);
json_string(out, joined ? joined : "", joined ? strlen(joined) : 0);
sqlite3_free(joined);
} else {
json_string(out, body, blen);
sqlite3_str_appendchar(out, 1, '}');
}
first = 0;
}
while ((step = sqlite3_step(q)) == SQLITE_ROW) {
const char *mime = (const char *)sqlite3_column_text(q, 0), *data = (const char *)sqlite3_column_text(q, 1);
n++;
if (as_string || (!vision && n > 1)) {
continue;
}
sqlite3_str_appendall(out, first ? "" : ",");
first = 0;
if (!vision) {
sqlite3_str_appendf(out, "{\"type\":\"%s\",\"text\":", text_type);
json_string(out, placeholder, strlen(placeholder));
sqlite3_str_appendchar(out, 1, '}');
} else if (strncmp(shape, "pi", 2) == 0) {
sqlite3_str_appendf(out, "{\"type\":\"image\",\"data\":\"%s\",\"mimeType\":\"%s\"}", data, mime);
} else if (strncmp(shape, "anthropic", 9) == 0) {
sqlite3_str_appendf(out,
"{\"type\":\"image\",\"source\":{\"type\":\"base64\",\"media_type\":\"%s\",\"data\":\"%s\"}}",
mime, data);
} else if (strncmp(shape, "chat", 4) == 0) {
sqlite3_str_appendf(out, "{\"type\":\"image_url\",\"image_url\":{\"url\":\"data:%s;base64,%s\"}}", mime, data);
} else {
sqlite3_str_appendf(out, "{\"type\":\"input_image\",\"detail\":\"auto\",\"image_url\":\"data:%s;base64,%s\"}",
mime, data);
}
}
sqlite3_finalize(q);
if (!as_string) {
sqlite3_str_appendchar(out, 1, ']');
}
if (step != SQLITE_DONE) {
sqlite3_free(sqlite3_str_finish(out));
sqlite3_result_error(ctx, "pic_content: cannot read the images", -1);
} else if (n == 0 || (images_only && !vision)) {
sqlite3_free(sqlite3_str_finish(out));
sqlite3_result_null(ctx);
} else if (sqlite3_str_errcode(out) != SQLITE_OK) {
sqlite3_free(sqlite3_str_finish(out));
sqlite3_result_error_nomem(ctx);
} else {
int len = sqlite3_str_length(out);
sqlite3_result_text(ctx, sqlite3_str_finish(out), len, sqlite3_free); /* JSON text: wrap it in json() */
}
}
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", 4, 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;
}