/* Gemini stream decoder; see gemini.h. Finish reasons follow Pi's mapStopReason:
* STOP is stop (toolUse once the reply has tool calls), MAX_TOKENS and
* CONTINUATION are length, every other reason fails the stream, as does a
* stream that ends without one. A call without an id, or with one already
* used in the reply, gets "name_N". */
#ifndef _DEFAULT_SOURCE
#define _DEFAULT_SOURCE 1
#endif
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "gemini.h"
#include "stripctl.h"
static int gem_fail(pic_gemini *g, const char *fmt, ...) {
va_list ap;
if (!g->failed) {
va_start(ap, fmt);
(void)vsnprintf(g->err, sizeof g->err, fmt, ap);
va_end(ap);
g->failed = 1;
}
return -1;
}
static char *gem_dup_n(const char *s, size_t n) {
char *p = malloc(n + 1);
if (p) {
memcpy(p, s, n);
p[n] = '\0';
}
return p;
}
/* SELECT with text arguments; *out gets column 0 as text or NULL. */
static int gem_sql_text(pic_gemini *g, const char *sql, char **out, int nargs, ...) {
sqlite3_stmt *st = NULL;
va_list ap;
int rc;
*out = NULL;
if (sqlite3_prepare_v2(g->db, sql, -1, &st, NULL) != SQLITE_OK) {
return gem_fail(g, "json: %s", sqlite3_errmsg(g->db));
}
va_start(ap, nargs);
for (int i = 1; i <= nargs; i++) {
const char *s = va_arg(ap, const char *);
size_t n = va_arg(ap, size_t);
if (s) {
(void)sqlite3_bind_text(st, i, s, (int)n, SQLITE_STATIC);
}
}
va_end(ap);
rc = sqlite3_step(st);
if (rc == SQLITE_ROW && sqlite3_column_type(st, 0) != SQLITE_NULL) {
*out = gem_dup_n((const char *)sqlite3_column_text(st, 0), (size_t)sqlite3_column_bytes(st, 0));
if (!*out) {
rc = SQLITE_NOMEM;
}
}
sqlite3_finalize(st);
if (rc != SQLITE_ROW && rc != SQLITE_DONE) {
return gem_fail(g, "malformed event JSON");
}
return 0;
}
static int gem_keep(pic_gemini *g, char **slot, char *value) {
size_t n = value ? strlen(value) : 0;
if (n > PIC_GEMINI_CAP - g->total) {
free(value);
return gem_fail(g, "reply exceeds %u bytes", PIC_GEMINI_CAP);
}
g->total += n;
free(*slot);
*slot = value;
return 0;
}
int pic_gemini_init(pic_gemini *g, sqlite3 *db) {
memset(g, 0, sizeof *g);
g->db = db;
g->native = sqlite3_str_new(db);
g->neutral = sqlite3_str_new(db);
g->text = sqlite3_str_new(db);
g->ids = gem_dup_n("\n", 1);
sqlite3_str_appendall(g->native, "[");
sqlite3_str_appendall(g->neutral, "[");
(void)pic_strip_register(db); /* a search's queries and titles come from the open web */
return g->native && g->neutral && g->text && g->ids ? 0 : -1;
}
void pic_gemini_free(pic_gemini *g) {
sqlite3_free(sqlite3_str_finish(g->native));
sqlite3_free(sqlite3_str_finish(g->neutral));
sqlite3_free(sqlite3_str_finish(g->text));
free(g->sig);
free(g->ids);
free(g->finish_reason);
free(g->usage);
free(g->response_id);
free(g->error);
free(g->sources);
memset(g, 0, sizeof *g);
}
/* Appends one element (JSON text) to a block list. */
static int gem_add(pic_gemini *g, sqlite3_str *list, int *n, const char *json) {
size_t len = json ? strlen(json) : 0;
if (!json) {
return gem_fail(g, "could not build a reply block");
}
if (len > PIC_GEMINI_CAP - g->total) {
return gem_fail(g, "reply exceeds %u bytes", PIC_GEMINI_CAP);
}
g->total += len;
sqlite3_str_appendall(list, *n ? "," : "");
sqlite3_str_appendall(list, json);
(*n)++;
return 0;
}
/* Closes the open text or thinking block into both lists. */
static int flush(pic_gemini *g) {
char *text, *neutral = NULL, *native = NULL;
int rc, thinking = g->kind == 2;
if (g->kind == 0) {
return 0;
}
text = sqlite3_str_finish(g->text);
g->text = sqlite3_str_new(g->db);
g->kind = 0;
if (!text || !g->text) {
sqlite3_free(text);
return gem_fail(g, "out of memory");
}
rc = gem_sql_text(g,
thinking ? "SELECT json_patch(json_object('type','thinking','thinking',?1),json_object('signature',?2))"
: "SELECT json_patch(json_object('type','text','text',?1),json_object('textSignature',?2))",
&neutral, 2, text, strlen(text), g->sig, g->sig ? strlen(g->sig) : (size_t)0);
if (rc == 0) {
rc = gem_sql_text(g,
"SELECT json_patch(json_object('text',?1),json_object('thought',CASE WHEN ?3 THEN json('true') END,"
"'thoughtSignature',?2))",
&native, 3, text, strlen(text), g->sig, g->sig ? strlen(g->sig) : (size_t)0,
thinking ? "1" : "0", (size_t)1);
}
sqlite3_free(text);
free(g->sig);
g->sig = NULL;
if (rc == 0) {
rc = gem_add(g, g->neutral, &g->nneutral, neutral) == 0 ? gem_add(g, g->native, &g->nnative, native) : -1;
}
free(neutral);
free(native);
return rc;
}
static int text_part(pic_gemini *g, const char *text, size_t n, int thought, const char *sig) {
int kind = thought ? 2 : 1;
if (g->kind != kind && (flush(g) != 0 || (g->kind = kind) == 0)) {
return -1;
}
if (n > PIC_GEMINI_CAP - g->total) {
return gem_fail(g, "reply exceeds %u bytes", PIC_GEMINI_CAP);
}
g->total += n;
sqlite3_str_append(g->text, text, (int)n);
if (sig && *sig) {
char *copy = gem_dup_n(sig, strlen(sig));
if (!copy) {
return gem_fail(g, "out of memory");
}
free(g->sig);
g->sig = copy;
}
if (g->on_delta && n > 0) {
g->on_delta(g->delta_ctx, thought, text, n);
}
return 0;
}
static int call_part(pic_gemini *g, const char *call, const char *name, const char *id, const char *sig) {
char *neutral = NULL, *native = NULL, made[300], *grown;
const char *use = id && *id ? id : NULL;
size_t n;
int rc;
if (flush(g) != 0) {
return -1;
}
g->calls++;
if (use) { /* already used in this reply? */
char needle[300];
(void)snprintf(needle, sizeof needle, "\n%.250s\n", use);
if (strstr(g->ids, needle)) {
use = NULL;
}
}
for (int k = g->calls; !use; k++) {
char needle[300];
(void)snprintf(made, sizeof made, "%.200s_%d", name ? name : "", k);
(void)snprintf(needle, sizeof needle, "\n%s\n", made);
if (!strstr(g->ids, needle)) {
use = made;
}
}
n = strlen(g->ids) + strlen(use) + 2;
grown = realloc(g->ids, n);
if (!grown) {
return gem_fail(g, "out of memory");
}
g->ids = grown;
(void)snprintf(g->ids + strlen(g->ids), n - strlen(g->ids), "%s\n", use);
rc = gem_sql_text(g,
"SELECT json_patch(json_object('type','toolCall','id',?1,'name',coalesce(?2,''),'arguments',"
"json(CASE WHEN json_type(?3,'$.args')='object' THEN json_extract(?3,'$.args') ELSE '{}' END)),"
"json_object('thoughtSignature',?4))",
&neutral, 4, use, strlen(use), name, name ? strlen(name) : (size_t)0, call, strlen(call), sig,
sig ? strlen(sig) : (size_t)0);
if (rc == 0) {
rc = gem_sql_text(g, "SELECT json_patch(json_object('functionCall',json(?1)),json_object('thoughtSignature',?2))",
&native, 2, call, strlen(call), sig, sig ? strlen(sig) : (size_t)0);
}
if (rc == 0) {
rc = gem_add(g, g->neutral, &g->nneutral, neutral) == 0 ? gem_add(g, g->native, &g->nnative, native) : -1;
}
free(neutral);
free(native);
return rc;
}
/* A server-side tool's part (PART, whole): native as it came; a search call also as text. */
static int server_part(pic_gemini *g, const char *part) {
char *neutral = NULL;
if (flush(g) != 0 || gem_add(g, g->native, &g->nnative, part) != 0) {
return -1;
}
if (gem_sql_text(g,
"SELECT CASE WHEN json_type(?1,'$.toolCall') = 'object' AND json_extract(?1,'$.toolCall.toolType') LIKE 'GOOGLE_SEARCH%'"
" THEN json_object('type','text','text','Searched the web for: ' || pic_strip(coalesce((SELECT group_concat(q.value, ', ')"
" FROM json_each(?1,'$.toolCall.args.queries') q), json_extract(?1,'$.toolCall.args.query'), '')) || char(10)) END",
&neutral, 1, part, strlen(part)) != 0) {
return -1;
}
if (neutral) {
int rc = gem_add(g, g->neutral, &g->nneutral, neutral);
free(neutral);
return rc;
}
return 0;
}
/* The parts of a response: text (thought or not), function calls and server-side tool parts. */
static int parts(pic_gemini *g, const char *data, size_t len) {
sqlite3_stmt *q = NULL;
int step, rc = 0;
if (sqlite3_prepare_v2(g->db,
"SELECT json_type(p.value,'$.text'), json_extract(p.value,'$.text'),"
" coalesce(json_extract(p.value,'$.thought') = 1, 0), json_extract(p.value,'$.thoughtSignature'),"
" json_type(p.value,'$.functionCall'), json_extract(p.value,'$.functionCall'),"
" json_extract(p.value,'$.functionCall.name'), json_extract(p.value,'$.functionCall.id'),"
" json_type(p.value,'$.toolCall') = 'object' OR json_type(p.value,'$.toolResponse') = 'object', json(p.value)"
" FROM json_each(?1,'$.candidates[0].content.parts') p ORDER BY p.key",
-1, &q, NULL) != SQLITE_OK) {
return gem_fail(g, "json: %s", sqlite3_errmsg(g->db));
}
sqlite3_bind_text(q, 1, data, (int)len, SQLITE_STATIC);
while (rc == 0 && (step = sqlite3_step(q)) == SQLITE_ROW) {
const char *sig = (const char *)sqlite3_column_text(q, 3);
if (sqlite3_column_text(q, 0) && strcmp((const char *)sqlite3_column_text(q, 0), "text") == 0) {
rc = text_part(g, (const char *)sqlite3_column_text(q, 1), (size_t)sqlite3_column_bytes(q, 1),
sqlite3_column_int(q, 2), sig);
}
if (rc == 0 && sqlite3_column_int(q, 8)) {
rc = server_part(g, (const char *)sqlite3_column_text(q, 9));
}
if (rc == 0 && sqlite3_column_text(q, 4) && strcmp((const char *)sqlite3_column_text(q, 4), "object") == 0) {
rc = call_part(g, (const char *)sqlite3_column_text(q, 5), (const char *)sqlite3_column_text(q, 6),
(const char *)sqlite3_column_text(q, 7), sig);
}
}
if (rc == 0 && step != SQLITE_DONE) {
rc = gem_fail(g, "malformed event JSON");
}
sqlite3_finalize(q);
return rc;
}
int pic_gemini_event(void *ctx, const char *event, const char *data, size_t len) {
pic_gemini *g = ctx;
char *s = NULL;
(void)event;
if (g->failed) {
return -1;
}
if (gem_sql_text(g, "SELECT CASE WHEN json_valid(?1) AND json_type(?1)='object' THEN 'ok' END", &s, 1, data, len) != 0) {
return -1;
}
if (!s) {
return gem_fail(g, "an event that is not a JSON object");
}
free(s);
if (gem_sql_text(g,
"SELECT CASE WHEN json_type(?1,'$.error')='object' THEN coalesce(json_extract(?1,'$.error.message'),"
" json_extract(?1,'$.error.status'), 'error') END",
&s, 1, data, len) != 0) {
return -1;
}
if (s) {
return gem_keep(g, &g->error, s);
}
if (gem_sql_text(g, "SELECT 'prompt blocked: ' || json_extract(?1,'$.promptFeedback.blockReason')", &s, 1, data, len) != 0 ||
gem_keep(g, &g->error, s) != 0) {
return -1;
}
if (!g->response_id) {
if (gem_sql_text(g, "SELECT nullif(json_extract(?1,'$.responseId'),'')", &s, 1, data, len) != 0 ||
gem_keep(g, &g->response_id, s) != 0) {
return -1;
}
}
if (parts(g, data, len) != 0) {
return -1;
}
/* Grounding sources: the last event that names them wins (they come whole, with the finish). */
if (gem_sql_text(g,
"SELECT 'Sources:' || group_concat(char(10) || (c.key + 1) || '. ' || pic_strip(coalesce(json_extract(c.value,'$.web.title'),''))"
" || char(10) || ' ' || pic_strip(coalesce(json_extract(c.value,'$.web.uri'),'')), '') || char(10,10)"
" FROM json_each(?1,'$.candidates[0].groundingMetadata.groundingChunks') c WHERE json_type(c.value,'$.web') = 'object'"
" HAVING count(*) > 0",
&s, 1, data, len) != 0) {
return -1;
}
if (s && gem_keep(g, &g->sources, s) != 0) {
return -1;
}
if (gem_sql_text(g, "SELECT json_extract(?1,'$.candidates[0].finishReason')", &s, 1, data, len) != 0) {
return -1;
}
if (s) {
if (gem_keep(g, &g->finish_reason, s) != 0) {
return -1;
}
}
/* Pi's usage: input is the prompt less cached tokens, output adds the
* thinking tokens. */
if (gem_sql_text(g,
"SELECT CASE json_type(?1,'$.usageMetadata') WHEN 'object' THEN json_object("
"'input_tokens', coalesce(json_extract(?1,'$.usageMetadata.promptTokenCount'),0)"
" - coalesce(json_extract(?1,'$.usageMetadata.cachedContentTokenCount'),0),"
"'output_tokens', coalesce(json_extract(?1,'$.usageMetadata.candidatesTokenCount'),0)"
" + coalesce(json_extract(?1,'$.usageMetadata.thoughtsTokenCount'),0),"
"'cache_read_input_tokens', coalesce(json_extract(?1,'$.usageMetadata.cachedContentTokenCount'),0),"
"'reasoning_tokens', coalesce(json_extract(?1,'$.usageMetadata.thoughtsTokenCount'),0),"
"'total_tokens', coalesce(json_extract(?1,'$.usageMetadata.totalTokenCount'),0)) END",
&s, 1, data, len) != 0) {
return -1;
}
if (s) {
return gem_keep(g, &g->usage, s);
}
return 0;
}
int pic_gemini_finish(pic_gemini *g) {
const char *why = g->finish_reason;
if (g->failed) {
return -1;
}
if (g->error) {
return gem_fail(g, "%.200s", g->error);
}
if (!why) {
return gem_fail(g, "stream ended without a finish reason");
}
if (strcmp(why, "STOP") != 0 && strcmp(why, "MAX_TOKENS") != 0 && strcmp(why, "CONTINUATION") != 0) {
return gem_fail(g, "Provider stopped with: %.60s", why);
}
if (!g->flushed) {
char *src = NULL;
if (flush(g) != 0) {
return -1;
}
g->flushed = 1;
if (g->sources) {
if (gem_sql_text(g, "SELECT json_object('type','text','text',?1)", &src, 1, g->sources, strlen(g->sources)) != 0 ||
gem_add(g, g->neutral, &g->nneutral, src) != 0) {
free(src);
return -1;
}
free(src);
}
}
return 0;
}
/* The list so far, closed (the list itself stays open). */
static char *list_text(sqlite3_str *list) {
const char *t = sqlite3_str_value(list);
size_t n = t ? strlen(t) : 0;
char *res = t ? malloc(n + 2) : NULL;
if (res) {
memcpy(res, t, n);
res[n] = ']';
res[n + 1] = '\0';
}
return res;
}
char *pic_gemini_native(pic_gemini *g) { return list_text(g->native); }
char *pic_gemini_neutral(pic_gemini *g) { return list_text(g->neutral); }
const char *pic_gemini_stop(const pic_gemini *g) {
if (g->finish_reason && strcmp(g->finish_reason, "STOP") != 0) {
return "length";
}
return g->calls > 0 ? "toolUse" : "stop";
}