/* 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. */
#ifndef _DEFAULT_SOURCE
#define _DEFAULT_SOURCE 1
#endif
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "pic.h"
#include "provider_http.h"
/* pic_norm_id(id, target_api, target_provider): a foreign tool-call id as
* the target accepts it, by the rule of the adapter registered under
* TARGET_API (provider_http.h), else the default: [A-Za-z0-9_-], at most 64. */
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]) : "";
const pic_provider_adapter *a;
char buf[512];
if (!id || !api) {
sqlite3_result_null(ctx);
return;
}
(void)snprintf(buf, sizeof buf, "%s", id);
a = pic_provider_adapter_named(api);
if (a && a->norm_id) {
a->norm_id(buf, sizeof buf, id, provider);
} else {
pic_id_sanitize(buf);
if (strlen(buf) > 64) {
buf[64] = '\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, '}');
}
/* 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. SHAPE names a pic_content_shape (provider_http.h):
* core's pi (every block in Pi's own form, for sessions and export) and
* pi-images (the blocks after the text, which events add to it), or one a
* registered adapter declares for its requests. */
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 pic_content_shape *shape = pic_content_shape_named((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;
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 such shape", -1);
return;
}
ttype = shape->text_type ? shape->text_type : "text";
placeholder = shape->tool ? PIC_IMAGE_TOOL_PLACEHOLDER : PIC_IMAGE_USER_PLACEHOLDER;
if (shape->every_image) {
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 (shape->form == PIC_SHAPE_TEXT ||
(!images && (shape->form == PIC_SHAPE_BLOCKS_OR_TEXT || shape->form == PIC_SHAPE_TEXT_IMAGES))) {
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 (shape->form == PIC_SHAPE_AFTER) {
int any = 0;
sqlite3_str_appendchar(out, 1, '[');
for (int i = 1; i < n; i++) {
if (v[i].text && shape->images_only) {
continue;
}
sqlite3_str_appendall(out, any++ ? "," : "");
if (v[i].text) {
text_block(out, ttype, v[i].text);
} else {
shape->image(out, v[i].mime, v[i].data);
}
}
sqlite3_str_appendchar(out, 1, ']');
if (!any) {
sqlite3_str_reset(out);
}
} else if (shape->form == PIC_SHAPE_TEXT_IMAGES) {
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++ ? "," : "");
shape->image(out, v[i].mime, v[i].data);
}
}
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 && ((shape->skip == 1 && tf_blank(v[i].text, strlen(v[i].text))) ||
(shape->skip == 2 && !*v[i].text))) {
continue;
}
sqlite3_str_appendall(out, any++ ? "," : "");
if (v[i].text) {
text_block(out, ttype, v[i].text);
} else {
shape->image(out, v[i].mime, v[i].data);
}
}
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;
}