/* 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. * With no Brave key it asks Stack Exchange's public search instead (Stack Overflow only, no key, * 300 requests a day per address): its replies are always gzip, inflated here, and a "backoff" it * names is kept in ~/.pic/pic.sqlite (picu_meta) so no search goes before that time. * 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. */ #ifndef _DEFAULT_SOURCE #define _DEFAULT_SOURCE 1 /* strdup and the rest of POSIX under -std=c11 on glibc */ #endif #include #include #include #include #include #include #include #include "zlib.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" #include "websearch_native.h" #define WS_ENDPOINT "https://api.search.brave.com/res/v1/web/search" #define WS_SE_ENDPOINT "https://api.stackexchange.com/2.3/search/excerpts" #define WS_SE_BACKOFF "stackexchange_backoff_until" /* picu_meta key: epoch seconds */ #define WS_SE_LOW_QUOTA 20 /* say how many are left at or below this */ #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 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). It uses Brave Search when a Brave key is set; without one it searches Stack Overflow only, which suits " "error messages and programming questions, so phrase the query as such a question.\"," "\"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; } /* IN (N bytes of gzip) inflated into *OUT (malloc'd, NUL-ended, *LEN bytes): 0; 1 when it would pass * the reply cap; -1 when it is not gzip or is cut short. */ static int ws_gunzip(const char *in, size_t n, char **out, size_t *len) { z_stream z; size_t cap = n * 4 + 4096, have = 0; char *buf; int zrc = Z_OK; *out = NULL; *len = 0; if (cap > WS_MAX_BODY + 1) { cap = WS_MAX_BODY + 1; } if (!(buf = malloc(cap + 1))) { return -1; } memset(&z, 0, sizeof z); if (inflateInit2(&z, 16 + MAX_WBITS) != Z_OK) { free(buf); return -1; } z.next_in = (Bytef *)(uintptr_t)in; z.avail_in = (uInt)n; while (zrc == Z_OK) { if (have == cap) { char *grown; if (cap > WS_MAX_BODY) { inflateEnd(&z); free(buf); return 1; } cap = cap * 2 > WS_MAX_BODY + 1 ? WS_MAX_BODY + 1 : cap * 2; if (!(grown = realloc(buf, cap + 1))) { inflateEnd(&z); free(buf); return -1; } buf = grown; } z.next_out = (Bytef *)buf + have; z.avail_out = (uInt)(cap - have); zrc = inflate(&z, Z_NO_FLUSH); have = cap - z.avail_out; if (zrc == Z_BUF_ERROR && z.avail_in == 0) { break; /* the stream stopped before its end */ } } inflateEnd(&z); if (zrc != Z_STREAM_END) { free(buf); return -1; } if (have > WS_MAX_BODY) { free(buf); return 1; } buf[have] = '\0'; *out = buf; *len = have; return 0; } /* When Stack Exchange said to wait until: epoch seconds, 0 for none (or no ~/.pic). */ static long long ws_se_backoff(void) { sqlite3 *db = pic_userdb(NULL, 0); sqlite3_stmt *q = NULL; long long until = 0; if (db && sqlite3_prepare_v2(db, "SELECT cast(value as integer) FROM picu_meta WHERE key = '" WS_SE_BACKOFF "'", -1, &q, NULL) == SQLITE_OK && sqlite3_step(q) == SQLITE_ROW) { until = sqlite3_column_int64(q, 0); } sqlite3_finalize(q); return until; } static void ws_se_backoff_set(long long until) { sqlite3 *db = pic_userdb(NULL, 0); sqlite3_stmt *q = NULL; if (db && sqlite3_prepare_v2(db, "INSERT OR REPLACE INTO picu_meta(key, value) VALUES ('" WS_SE_BACKOFF "', ?1)", -1, &q, NULL) == SQLITE_OK) { sqlite3_bind_int64(q, 1, until); (void)sqlite3_step(q); } sqlite3_finalize(q); } #define WS_NO_KEY_HINT "add a Brave Search API key (https://brave.com/search/api/, the free plan is enough) with `pic login brave-search`, or set BRAVE_API_KEY, to search the whole web" /* The keyless source: Stack Exchange's search of Stack Overflow, ENC the encoded query. */ static char *ws_stackexchange(const char *enc, long count, int *is_error) { const char *endpoint = WS_SE_ENDPOINT, *hdrs[3] = {"Accept: application/json", "Accept-Encoding: gzip", "User-Agent: pic"}; char *url = NULL, *result = NULL, *json = NULL, *valid = NULL, *field = NULL, err[300], neterr[256]; size_t urlcap, jlen = 0; long long now = (long long)time(NULL), until = ws_se_backoff(); pic_net *net = NULL; pic_http_resp hr; ws_body b; int rc; memset(&b, 0, sizeof b); if (until > now) { return ws_fmt(is_error, "web_search: Stack Exchange asked for a pause; try again in %lld seconds (or %s)", until - now, WS_NO_KEY_HINT); } #ifdef PIC_FAULTS if (getenv("PIC_TEST_STACKEXCHANGE_URL")) { endpoint = getenv("PIC_TEST_STACKEXCHANGE_URL"); } #endif urlcap = strlen(endpoint) + strlen(enc) + 96; if (!(url = malloc(urlcap))) { return ws_fmt(is_error, "web_search: out of memory"); } (void)snprintf(url, urlcap, "%s?order=desc&sort=relevance&site=stackoverflow&pagesize=%ld&q=%s", endpoint, count, enc); 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); hr.gzip_ok = 1; 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"); goto out; } else if (b.too_big) { result = ws_fmt(is_error, "web_search: the reply is too large (over 2 MB)"); goto out; } else if (rc != 0) { result = ws_fmt(is_error, "web_search: could not reach Stack Exchange: %s", err); goto out; } if (hr.gzip) { int z = ws_gunzip(b.p ? b.p : "", b.len, &json, &jlen); if (z != 0) { result = ws_fmt(is_error, z > 0 ? "web_search: the reply is too large (over 2 MB)" : "web_search: Stack Exchange's reply was not understood (bad gzip)"); goto out; } } else { json = b.p; b.p = NULL; } if (!(valid = json ? pic_web_json("SELECT json_valid(?1) AND json_type(?1) = 'object'", json) : NULL) || strcmp(valid, "1") != 0) { result = hr.status == 200 ? ws_fmt(is_error, "web_search: Stack Exchange's reply was not understood (not JSON)") : ws_fmt(is_error, "web_search: Stack Exchange answered HTTP %d", hr.status); goto out; } /* backoff: seconds before this method may be called again, in any reply */ if ((field = pic_web_json("SELECT cast(json_extract(?1,'$.backoff') as integer)", json)) && atoll(field) > 0) { long long wait = atoll(field); ws_se_backoff_set((long long)time(NULL) + (wait > 86400 ? 86400 : wait)); } free(field); field = NULL; if ((field = pic_web_json("SELECT json_extract(?1,'$.error_id')", json))) { char *name = pic_web_json("SELECT coalesce(json_extract(?1,'$.error_name'),'')", json); char *msg = pic_web_json("SELECT coalesce(json_extract(?1,'$.error_message'),'')", json); char *n = ws_line(name, 60), *m = ws_line(msg, 300); if (atoi(field) == 502) { /* throttle_violation: the day's quota for this address */ result = ws_fmt(is_error, "web_search: Stack Exchange's quota for this address is used up (300 searches a day without a key)%s%s; %s", m && *m ? ": " : "", m ? m : "", WS_NO_KEY_HINT); } else { result = ws_fmt(is_error, "web_search: Stack Exchange answered HTTP %d: %s%s%s", hr.status, n ? n : "", m && *m ? ": " : "", m ? m : ""); } free(name); free(msg); free(n); free(m); goto out; } if (hr.status != 200) { result = ws_fmt(is_error, "web_search: Stack Exchange answered HTTP %d", hr.status); goto out; } { sqlite3 *db = NULL; sqlite3_stmt *q = NULL; sqlite3_str *o = NULL; int rows = 0; long left = -1; if (sqlite3_open(":memory:", &db) == SQLITE_OK && (o = sqlite3_str_new(db)) && sqlite3_prepare_v2(db, "SELECT json_extract(value,'$.title')," " CASE WHEN json_extract(value,'$.item_type') = 'answer' AND json_extract(value,'$.answer_id') > 0" " THEN 'https://stackoverflow.com/a/' || cast(json_extract(value,'$.answer_id') as integer)" " WHEN json_extract(value,'$.question_id') > 0" " THEN 'https://stackoverflow.com/q/' || cast(json_extract(value,'$.question_id') as integer) END," " CASE WHEN json_extract(value,'$.item_type') = 'answer' THEN" " CASE WHEN json_extract(value,'$.is_accepted') THEN 'Accepted answer' ELSE 'Answer' END" " ELSE 'Question' || CASE WHEN json_extract(value,'$.has_accepted_answer') THEN ', answered'" " WHEN json_extract(value,'$.is_answered') THEN ', has answers' ELSE '' END END" " || ', score ' || coalesce(cast(json_extract(value,'$.score') as integer), 0)," " json_extract(value,'$.excerpt')," " coalesce(cast(json_extract(?1,'$.quota_remaining') as integer), -1)" " FROM json_each(?1,'$.items') LIMIT ?2", -1, &q, NULL) == SQLITE_OK) { sqlite3_bind_text(q, 1, json, -1, SQLITE_STATIC); sqlite3_bind_int(q, 2, (int)count); sqlite3_str_appendall(o, "Stack Overflow results (no Brave Search key is set, so only Stack Overflow was searched):\n\n"); while (sqlite3_step(q) == SQLITE_ROW) { char *t = ws_line((const char *)sqlite3_column_text(q, 0), WS_TITLE_CHARS); const char *u = (const char *)sqlite3_column_text(q, 1); const char *k = (const char *)sqlite3_column_text(q, 2); char *d = ws_line((const char *)sqlite3_column_text(q, 3), WS_SNIPPET_CHARS); left = (long)sqlite3_column_int64(q, 4); if (t && d && u) { sqlite3_str_appendf(o, "%d. %s\n %s\n %s%s%s\n\n", ++rows, *t ? t : "(no title)", u, k ? k : "", *d ? ": " : "", d); } free(t); free(d); } } sqlite3_finalize(q); if (rows > 0) { sqlite3_str_appendall(o, "Source: Stack Overflow (Stack Exchange), user contributions under CC BY-SA; see each link for its author and license.\n"); if (left >= 0 && left <= WS_SE_LOW_QUOTA) { sqlite3_str_appendf(o, "(%ld Stack Exchange searches left today from this address; %s.)\n", left, WS_NO_KEY_HINT); } } if (o && sqlite3_str_errcode(o) == SQLITE_OK && rows > 0) { char *text = sqlite3_str_value(o); size_t len = strlen(text); while (len > 0 && text[len - 1] == '\n') { text[--len] = '\0'; } result = strdup(text); } else if (rows == 0) { result = strdup("web_search: no results on Stack Overflow (with no Brave Search key only Stack Overflow is searched; " WS_NO_KEY_HINT ")"); } sqlite3_free(sqlite3_str_finish(o)); sqlite3_close(db); if (!result) { result = ws_fmt(is_error, "web_search: out of memory"); } } out: free(field); free(valid); free(json); free(b.p); free(url); if (net) { pic_net_free(net); } return result; } 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) { /* no Brave key: the keyless source */ result = ws_stackexchange(enc, count, is_error); goto out; } if (got < 0) { result = ws_fmt(is_error, "web_search: the Brave Search API key cannot be used: %s", 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; } /* Always offered: a Brave key, the provider's own search or, with neither, Stack Overflow answers it. */ static int ws_on(void) { return 1; } /* 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};