/* The web_search tool: one GET of Brave's web search endpoint over pic's own HTTP and TLS, with
* the key from the credential store (or BRAVE_API_KEY) sent as the token header and nowhere else.
* The reply is capped (2 MB, 20 s); each result is cut to a title, a URL and a snippet, HTML
* markup and entities in them are turned to plain text, and control characters are dropped, since
* these words come from the open web and go to the model and to every screen that shows the call. */
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "cred.h"
#include "htmltext.h"
#include "http.h"
#include "net.h"
#include "toolreg.h"
#include "userdb.h"
#include "webfetch.h"
#include "websearch.h"
#define WS_ENDPOINT "https://api.search.brave.com/res/v1/web/search"
#define WS_MAX_BODY (2u * 1024u * 1024u)
#define WS_DEADLINE 20
#define WS_QUERY_CHARS 400
#define WS_DEFAULT_COUNT 5
#define WS_MAX_COUNT 10
#define WS_TITLE_CHARS 200
#define WS_URL_CHARS 500
#define WS_SNIPPET_CHARS 500
static const char ws_schema[] =
"{\"name\":\"web_search\",\"description\":\"Search the web (Brave Search) and return the top results as a numbered "
"list of title, URL and a short snippet. Use it to find pages, then read one with web_fetch. count is how many "
"results (default 5, at most 10). Needs a Brave Search API key, added with pic login brave-search.\","
"\"input_schema\":{\"type\":\"object\",\"properties\":{"
"\"query\":{\"type\":\"string\",\"description\":\"What to search for (at most 400 characters)\"},"
"\"count\":{\"type\":\"integer\",\"description\":\"How many results (default 5, at most 10)\"}},"
"\"required\":[\"query\"]}}";
static char *ws_fmt(int *is_error, const char *fmt, ...) {
va_list ap;
int n;
char *out;
va_start(ap, fmt);
n = vsnprintf(NULL, 0, fmt, ap);
va_end(ap);
if (n < 0 || !(out = malloc((size_t)n + 1))) {
return NULL;
}
va_start(ap, fmt);
(void)vsnprintf(out, (size_t)n + 1, fmt, ap);
va_end(ap);
*is_error = 1;
return out;
}
typedef struct {
char *p;
size_t len, cap;
int too_big, oom;
} ws_body;
static int ws_on_body(void *ctx, const char *bytes, size_t n) {
ws_body *b = ctx;
if (b->len + n > WS_MAX_BODY) {
b->too_big = 1;
return 1;
}
if (b->len + n + 1 > b->cap) {
size_t cap = b->cap ? b->cap : 16384;
char *q;
while (cap < b->len + n + 1) {
cap *= 2;
}
if (!(q = realloc(b->p, cap))) {
b->oom = 1;
return 1;
}
b->p = q;
b->cap = cap;
}
memcpy(b->p + b->len, bytes, n);
b->len += n;
b->p[b->len] = '\0';
return 0;
}
/* S as one line of plain text of at most MAX characters (malloc'd): controls dropped, markup and
* entities resolved, white space collapsed, a "..." where it was cut. */
static char *ws_line(const char *s, size_t max) {
size_t n = s ? strlen(s) : 0, len, o = 0, chars = 0, cut = 0;
char *clean = pic_web_utf8(s ? s : "", n, 0, &len), *text, *out;
int space = 0;
if (!clean) {
return NULL;
}
text = pic_html_plain(clean, len);
free(clean);
if (!text) {
return NULL;
}
out = malloc(strlen(text) + 5);
if (!out) {
free(text);
return NULL;
}
for (const char *p = text; *p && !cut; p++) {
unsigned char c = (unsigned char)*p;
if (isspace(c)) {
space = o > 0;
continue;
}
if ((c & 0xc0) != 0x80) {
if (chars == max) {
cut = 1;
break;
}
chars++;
if (space) {
out[o++] = ' ';
space = 0;
}
}
out[o++] = (char)c;
}
if (cut) {
memcpy(out + o, "...", 3);
o += 3;
}
out[o] = '\0';
free(text);
return out;
}
/* The query, percent-encoded (malloc'd); NULL for an unusable one, WHY saying how. */
static char *ws_encode(const char *q, const char **why) {
size_t chars = 0, n = strlen(q);
char *out = malloc(n * 3 + 1);
size_t o = 0;
if (!out) {
*why = "out of memory";
return NULL;
}
for (const unsigned char *p = (const unsigned char *)q; *p; p++) {
if (*p < 0x20 || *p == 0x7f) {
free(out);
*why = "the query has a control character";
return NULL;
}
chars += (*p & 0xc0) != 0x80;
if (isalnum(*p) || *p == '-' || *p == '.' || *p == '_' || *p == '~') {
out[o++] = (char)*p;
} else {
o += (size_t)snprintf(out + o, 4, "%%%02X", *p);
}
}
out[o] = '\0';
if (chars == 0 || chars > WS_QUERY_CHARS) {
free(out);
*why = chars ? "the query is too long (at most 400 characters)" : "the query is empty";
return NULL;
}
return out;
}
static char *ws_run(void *state, const char *workspace, const char *tool, const pic_tool_args *args,
const pic_tool_hooks *h, int *is_error) {
const char *input = h->input && *h->input ? h->input : "{}", *why = NULL, *endpoint = WS_ENDPOINT;
char *type, *qv = NULL, *cv, *enc = NULL, *result = NULL, key[PIC_CRED_KEY_CAP], err[300], neterr[256], *url = NULL;
char token[PIC_CRED_KEY_CAP + 32];
const char *hdrs[3];
long count = WS_DEFAULT_COUNT;
int got, rc;
size_t urlcap;
char *valid = NULL;
pic_net *net = NULL;
pic_http_resp hr;
ws_body b;
(void)state;
(void)workspace;
(void)tool;
*is_error = 0;
memset(&b, 0, sizeof b);
key[0] = token[0] = '\0';
if (h->started == NULL || h->started(h->ctx, NULL, 0) != 0) {
return NULL;
}
if (args->bad_input) {
return ws_fmt(is_error, "web_search: %s", args->bad_input);
}
if (pic_offline()) {
return ws_fmt(is_error, "web_search: offline is on, so nothing was searched (turn it off with pic settings --unset offline)");
}
type = pic_web_json("SELECT json_valid(?1) || json_type(?1)", input);
if (!type || strcmp(type, "1object") != 0) {
free(type);
return ws_fmt(is_error, "web_search: the input is not a JSON object");
}
free(type);
type = pic_web_json("SELECT json_type(?1, '$.query')", input);
qv = type && strcmp(type, "text") == 0 ? pic_web_json("SELECT json_extract(?1, '$.query')", input) : NULL;
free(type);
if (!qv) {
return ws_fmt(is_error, "web_search: query is required, a string");
}
type = pic_web_json("SELECT json_type(?1, '$.count')", input);
if (type) {
cv = strcmp(type, "integer") == 0 || strcmp(type, "real") == 0
? pic_web_json("SELECT cast(json_extract(?1, '$.count') as integer)", input)
: NULL;
free(type);
count = cv ? strtol(cv, NULL, 10) : 0;
free(cv);
if (count < 1) {
free(qv);
return ws_fmt(is_error, "web_search: count must be a whole number from 1 to %d", WS_MAX_COUNT);
}
if (count > WS_MAX_COUNT) {
count = WS_MAX_COUNT;
}
}
enc = ws_encode(qv, &why);
if (!enc) {
free(qv);
return ws_fmt(is_error, "web_search: %s", why);
}
{
const char *env = getenv("BRAVE_API_KEY");
got = pic_cred_stored(PIC_WEBSEARCH_KEY) || (env && *env)
? pic_cred_get(PIC_WEBSEARCH_KEY, "BRAVE_API_KEY", "", key, sizeof key, err, sizeof err)
: 1;
}
if (got != 0) {
result = ws_fmt(is_error, "web_search: %s%s", got > 0
? "no Brave Search API key is set. Get one at https://brave.com/search/api/ (the free plan is enough), "
"then add it with `pic login brave-search`, or set BRAVE_API_KEY."
: "the Brave Search API key cannot be used: ",
got > 0 ? "" : err);
goto out;
}
#ifdef PIC_FAULTS
if (getenv("PIC_TEST_WEB_SEARCH_URL")) {
endpoint = getenv("PIC_TEST_WEB_SEARCH_URL");
}
#endif
urlcap = strlen(endpoint) + strlen(enc) + 32; /* the encoded query is as long as it is: never cut */
url = malloc(urlcap);
if (!url) {
result = ws_fmt(is_error, "web_search: out of memory");
goto out;
}
(void)snprintf(url, urlcap, "%s?q=%s&count=%ld", endpoint, enc, count);
(void)snprintf(token, sizeof token, "X-Subscription-Token: %s", key);
hdrs[0] = token;
hdrs[1] = "Accept: application/json";
hdrs[2] = "User-Agent: pic";
if (!(net = pic_net_new(neterr, sizeof neterr))) {
result = ws_fmt(is_error, "web_search: cannot start the network: %s", neterr);
goto out;
}
pic_http_resp_init(&hr, ws_on_body, &b);
err[0] = '\0';
rc = pic_http_get(net, url, hdrs, 3, &hr, WS_DEADLINE, WS_DEADLINE, err, sizeof err);
if (b.oom) {
result = ws_fmt(is_error, "web_search: out of memory");
} else if (b.too_big) {
result = ws_fmt(is_error, "web_search: the reply is too large (over 2 MB)");
} else if (rc != 0) {
pic_cred_scrub(err, key);
result = ws_fmt(is_error, "web_search: could not reach Brave Search: %s", err);
} else if (hr.status == 401 || hr.status == 403) {
result = ws_fmt(is_error, "web_search: Brave answered HTTP %d: the API key was refused; check it (pic login brave-search) and its plan",
hr.status);
} else if (hr.status == 429) {
char wait[40];
size_t o = 0;
for (const char *p = hr.retry_after; *p && o + 1 < sizeof wait; p++) {
if ((unsigned char)*p >= 0x20 && (unsigned char)*p < 0x7f) { /* Brave's words reach the model: printable only */
wait[o++] = *p;
}
}
wait[o] = '\0';
result = ws_fmt(is_error, "web_search: Brave answered HTTP 429: the rate limit or quota for this key is used up%s%s",
o ? "; try again in " : "", wait);
} else if (hr.status != 200) {
result = ws_fmt(is_error, "web_search: Brave answered HTTP %d", hr.status);
} else if (!(valid = b.p ? pic_web_json("SELECT json_valid(?1)", b.p) : NULL) || strcmp(valid, "1") != 0) {
result = ws_fmt(is_error, "web_search: Brave's reply was not understood (not JSON)");
} else {
sqlite3 *db = NULL;
sqlite3_stmt *q = NULL;
char *out = NULL;
size_t len = 0, cap = 0;
int rows = 0;
if (sqlite3_open(":memory:", &db) == SQLITE_OK &&
sqlite3_prepare_v2(db,
"SELECT json_extract(value,'$.title'), json_extract(value,'$.url'),"
" json_extract(value,'$.description') FROM json_each(?1,'$.web.results') LIMIT ?2",
-1, &q, NULL) == SQLITE_OK) {
sqlite3_bind_text(q, 1, b.p, -1, SQLITE_STATIC);
sqlite3_bind_int(q, 2, (int)count);
while (sqlite3_step(q) == SQLITE_ROW) {
char *t = ws_line((const char *)sqlite3_column_text(q, 0), WS_TITLE_CHARS);
char *u = ws_line((const char *)sqlite3_column_text(q, 1), WS_URL_CHARS);
char *d = ws_line((const char *)sqlite3_column_text(q, 2), WS_SNIPPET_CHARS);
size_t need = (t ? strlen(t) : 0) + (u ? strlen(u) : 0) + (d ? strlen(d) : 0) + 64;
char *grown = t && u && d ? realloc(out, cap + need) : NULL;
if (grown) {
out = grown;
cap += need;
len += (size_t)snprintf(out + len, cap - len, "%d. %s\n", ++rows, *t ? t : "(no title)");
if (*u) {
len += (size_t)snprintf(out + len, cap - len, " %s\n", u);
}
if (*d) {
len += (size_t)snprintf(out + len, cap - len, " %s\n", d);
}
len += (size_t)snprintf(out + len, cap - len, "\n");
}
free(t);
free(u);
free(d);
if (!grown) {
break;
}
}
}
sqlite3_finalize(q);
sqlite3_close(db);
if (rows == 0) {
free(out);
result = strdup("web_search: no results");
} else {
while (len > 0 && out[len - 1] == '\n') {
out[--len] = '\0';
}
result = out;
}
}
out:
free(url);
free(valid);
free(b.p);
free(qv);
free(enc);
if (net) {
pic_net_free(net);
}
pic_cred_wipe(key, sizeof key);
pic_cred_wipe(token, sizeof token);
return result;
}
/* Offered when a key exists (sealed, which needs no unlock to know, or in the variable); named
* with --tools it is offered without one and explains how to add it. */
static int ws_on(void) {
const char *env = getenv("BRAVE_API_KEY");
return pic_cred_stored(PIC_WEBSEARCH_KEY) || (env && *env);
}
/* A GET that changes nothing here, so a replay after a crash is safe; it still sends words to a
* third party, so a permission mode counts it as a change (read_only 0), as web_fetch is. */
const pic_tool_def pic_websearch_tool = {"web_search", ws_schema, 1, 0, PIC_TIER_BUNDLED, 1, ws_on, ws_run, NULL, 0};