/* Control characters out of the text a provider's web search brings from the open web (stripctl.h),
* before it is written into the transcript: titles, addresses, snippets and queries, and nothing
* else (a tool call's arguments and the model's own words come back as they were sent). Header-only
* so each stream decoder, which is built and tested on its own, carries it. */
#ifndef PIC_STRIPCTL_H
#define PIC_STRIPCTL_H
#include <stdlib.h>
#include <string.h>
#include "sqlite3.h"
/* Whether code point CP could steer a terminal or reorder text when shown: C0 (but newline and tab),
* DEL, C1, and the bidi controls U+061C, U+200E, U+200F, U+202A-202E and U+2066-2069 (the rule the
* names of paired phones follow, remote.c). */
static inline int pic_cp_steers(unsigned long cp) {
return (cp < 0x20 && cp != 0x0a && cp != 0x09) || (cp >= 0x7f && cp <= 0x9f) || cp == 0x061c || cp == 0x200e ||
cp == 0x200f || (cp >= 0x202a && cp <= 0x202e) || (cp >= 0x2066 && cp <= 0x2069);
}
/* Removes from the decoded UTF-8 text S (in place) each character PIC_CP_STEERS says. */
static inline void pic_strip_text(char *s) {
char *o = s;
for (const unsigned char *p = (const unsigned char *)s; *p;) {
size_t n = *p < 0x80 ? 1 : (*p & 0xe0) == 0xc0 ? 2 : (*p & 0xf0) == 0xe0 ? 3 : (*p & 0xf8) == 0xf0 ? 4 : 1;
unsigned long cp = n == 1 ? *p : (n == 2 ? *p & 0x1fu : n == 3 ? *p & 0x0fu : *p & 0x07u);
size_t k;
for (k = 1; k < n && (p[k] & 0xc0) == 0x80; k++) {
cp = (cp << 6) | (p[k] & 0x3fu);
}
if (k < n) { /* not a whole sequence: the bytes stay as they are */
n = 1;
cp = 0x80000000ul;
}
if (!pic_cp_steers(cp)) {
memmove(o, p, n);
o += n;
}
p += n;
}
*o = '\0';
}
static inline void pic_strip_sql(sqlite3_context *c, int argc, sqlite3_value **argv) {
const unsigned char *t = argc == 1 ? sqlite3_value_text(argv[0]) : NULL;
char *copy;
if (!t) {
sqlite3_result_null(c);
return;
}
copy = strdup((const char *)t);
if (!copy) {
sqlite3_result_error_nomem(c);
return;
}
pic_strip_text(copy);
sqlite3_result_text(c, copy, -1, SQLITE_TRANSIENT);
free(copy);
}
/* Makes pic_strip(TEXT) an SQL function on DB: TEXT without the characters above, NULL for NULL. */
static inline int pic_strip_register(sqlite3 *db) {
return sqlite3_create_function(db, "pic_strip", 1, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL, pic_strip_sql, NULL, NULL);
}
#endif