/* * ws_providers.c - the six search backends and their result normalisation. * * Every provider returns the same shape, so the agent and the page never see * provider-specific field names: * * {title, url, snippet, published, site} * * The five keyed providers are plain JSON calls (Brave GET, Tavily POST, Exa * POST, Perplexity POST, SearXNG GET ?format=json). DuckDuckGo has no API, so * its HTML page is parsed — and that parser is the only place in this plugin * where markup is trusted to be well-formed: every buffer it fills is bounded * and every string it copies goes through the JSON escaper on output. * * Provider ids are stable strings ("duckduckgo", "searxng", "brave", "tavily", * "exa", "perplexity") because they are MCP tool arguments and config values. * * Two rules the code enforces rather than documents: * 1. A secret never leaves this file. `ws_provider_has_key()` is the only way * the rest of the plugin learns about a key, and it answers a boolean. * 2. An upstream error is reported with the provider's own message and its * HTTP status. Swallowing a 401 into "no results" makes a wrong key look * like a working query with nothing to say. * * MIT License. Copyright (c) 2026 SCORPIOX INC. */ #if defined(_WIN32) && !defined(_WIN32_WINNT) # define _WIN32_WINNT 0x0601 #endif #if !defined(_WIN32) # if !defined(_POSIX_C_SOURCE) || _POSIX_C_SOURCE < 200809L # undef _POSIX_C_SOURCE # define _POSIX_C_SOURCE 200809L # endif # ifndef _DEFAULT_SOURCE # define _DEFAULT_SOURCE 1 # endif #endif #include "ws.h" #include "sx_http_tls.h" #include #include #include #include #include const ws_provider_info WS_PROVIDERS[WS_PROVIDER_COUNT] = { { "duckduckgo", "DuckDuckGo", "No key needed", "https://duckduckgo.com/", 0, 0 }, { "searxng", "SearXNG", "Self-hosted", "https://docs.searxng.org/", 0, 1 }, { "brave", "Brave", "Structured API", "https://brave.com/search/api/", 1, 0 }, { "tavily", "Tavily", "Agent-optimised", "https://tavily.com/", 1, 0 }, { "exa", "Exa", "Neural search", "https://exa.ai/", 1, 0 }, { "perplexity", "Perplexity", "Answer + sources", "https://perplexity.ai/", 1, 0 } }; int ws_provider_known(const char *id) { int i; if (!id || !*id) return 0; for (i = 0; i < WS_PROVIDER_COUNT; i++) if (ws_ieq(id, WS_PROVIDERS[i].id)) return 1; return 0; } const char *ws_provider_active(const ws_config *cfg) { if (cfg && cfg->active[0] && ws_provider_known(cfg->active)) return cfg->active; return "duckduckgo"; } int ws_provider_has_key(const ws_config *cfg, const char *id) { if (!cfg || !id) return 0; if (ws_ieq(id, "brave")) return cfg->brave_key[0] ? 1 : 0; if (ws_ieq(id, "tavily")) return cfg->tavily_key[0] ? 1 : 0; if (ws_ieq(id, "exa")) return cfg->exa_key[0] ? 1 : 0; if (ws_ieq(id, "perplexity")) return cfg->pplx_key[0] ? 1 : 0; return 0; } int ws_provider_ready(const ws_config *cfg, const char *id) { if (!cfg || !id) return 0; if (ws_ieq(id, "duckduckgo")) return 1; if (ws_ieq(id, "searxng")) return cfg->searxng_base[0] ? 1 : 0; if (ws_ieq(id, "brave")) return cfg->brave_key[0] ? 1 : 0; if (ws_ieq(id, "tavily")) return cfg->tavily_key[0] ? 1 : 0; if (ws_ieq(id, "exa")) return cfg->exa_key[0] ? 1 : 0; if (ws_ieq(id, "perplexity")) return cfg->pplx_key[0] ? 1 : 0; return 0; } /* ------------------------------------------------------------- results bag */ void ws_results_init(ws_results *r) { memset(r, 0, sizeof *r); ws_buf_init(&r->answer); ws_buf_init(&r->citations); } void ws_results_free(ws_results *r) { if (!r) return; free(r->items); r->items = NULL; r->n = r->cap = 0; ws_buf_free(&r->answer); ws_buf_free(&r->citations); } ws_result *ws_results_push(ws_results *r) { if (r->n >= r->cap) { int want = r->cap ? r->cap * 2 : 8; ws_result *np = (ws_result *)realloc(r->items, (size_t)want * sizeof *np); if (!np) return NULL; r->items = np; r->cap = want; } memset(&r->items[r->n], 0, sizeof r->items[r->n]); return &r->items[r->n++]; } /* Host part of a URL, for the "site" field. Never returns a credential. */ static void site_of(const char *url, char *out, size_t capsz) { const char *p = url; const char *e; out[0] = '\0'; if (!url || !*url) return; if (ws_iprefix(p, "https://")) p += 8; else if (ws_iprefix(p, "http://")) p += 7; e = p; while (*e && *e != '/' && *e != '?' && *e != '#') e++; if (e == p) return; if ((size_t)(e - p) >= capsz) e = p + capsz - 1; memcpy(out, p, (size_t)(e - p)); out[e - p] = '\0'; } static void fill_result(ws_result *it, const char *title, const char *url, const char *snippet, const char *published) { char tmp[4096]; ws_html_text(tmp, sizeof tmp, title ? title : ""); ws_copy(it->title, sizeof it->title, tmp); ws_copy(it->url, sizeof it->url, url ? url : ""); ws_html_text(tmp, sizeof tmp, snippet ? snippet : ""); ws_copy(it->snippet, sizeof it->snippet, tmp); ws_copy(it->published, sizeof it->published, published ? published : ""); site_of(it->url, it->site, sizeof it->site); } /* ------------------------------------------------------------- helpers */ static const char *jstr(yyjson_val *o, const char *key) { yyjson_val *v; if (!o || !yyjson_is_obj(o)) return NULL; v = yyjson_obj_get(o, key); return (v && yyjson_is_str(v)) ? yyjson_get_str(v) : NULL; } static yyjson_val *jobj(yyjson_val *o, const char *key) { yyjson_val *v; if (!o || !yyjson_is_obj(o)) return NULL; v = yyjson_obj_get(o, key); return (v && yyjson_is_obj(v)) ? v : NULL; } static yyjson_val *jarr(yyjson_val *o, const char *key) { yyjson_val *v; if (!o || !yyjson_is_obj(o)) return NULL; v = yyjson_obj_get(o, key); return (v && yyjson_is_arr(v)) ? v : NULL; } /* Trim a base URL's trailing slashes so joining a path is predictable. */ static void base_trim(char *out, size_t capsz, const char *base) { size_t n; ws_copy(out, capsz, base); n = strlen(out); while (n > 0 && out[n - 1] == '/') out[--n] = '\0'; } /* Upstream error text: the provider's own `error`/`message`/`detail` field * when the body parses, the first 300 bytes of the body otherwise. The body is * never echoed wholesale — a provider error page can be a whole HTML document. */ static void upstream_error(ws_resp *r, const char *provider, char *err, size_t errsz) { char detail[320]; yyjson_doc *doc = NULL; detail[0] = '\0'; if (r->body && r->body_len) { doc = yyjson_read(r->body, r->body_len, 0); if (doc) { yyjson_val *root = yyjson_doc_get_root(doc); const char *m = jstr(root, "message"); if (!m) m = jstr(root, "error"); if (!m) m = jstr(root, "detail"); if (!m) { yyjson_val *e = yyjson_obj_get(root, "error"); /* some providers nest {"error":{"message":"..."}} */ if (e && yyjson_is_obj(e)) m = jstr(e, "message"); } if (m) ws_copy(detail, sizeof detail, m); yyjson_doc_free(doc); } } if (!detail[0] && r->body && r->body_len) { char tmp[321]; size_t n = r->body_len < 300 ? r->body_len : 300; char stripped[321]; memcpy(tmp, r->body, n); tmp[n] = '\0'; ws_html_text(stripped, sizeof stripped, tmp); ws_copy(detail, sizeof detail, stripped); } snprintf(err, errsz, "%s returned HTTP %ld%s%s", provider, r->status, detail[0] ? ": " : "", detail); } static int parse_json(ws_resp *r, yyjson_doc **out, const char *provider, char *err, size_t errsz) { *out = NULL; if (!r->body || !r->body_len) { snprintf(err, errsz, "%s returned an empty response", provider); return -1; } *out = yyjson_read(r->body, r->body_len, 0); if (!*out) { snprintf(err, errsz, "%s returned a body that is not JSON", provider); return -1; } return 0; } /* ------------------------------------------------------------- DuckDuckGo */ /* Finds the next `inner` at or after `from`. * Returns 1 and fills href/inner, or 0. Done by hand rather than with a regex * because C99 has none and because every offset here is bounded by hlen. */ static int next_anchor(const char *hay, size_t hlen, size_t from, const char *needle, char *href, size_t hrefcap, const char **inner, size_t *inner_len) { size_t i = from; while (i + 2 < hlen) { const char *tag, *close, *attr, *ih; size_t tag_end, attr_len; tag = ws_memmem(hay + i, hlen - i, "', hlen - i); if (!close) return 0; tag_end = (size_t)(close - hay); attr = tag; attr_len = tag_end - i + 1; /* Match `class="…needle…"` inside the tag only. */ { const char *cpos = ws_memmem(attr, attr_len, "class="); int matched = 0; if (cpos) { const char *v = cpos + 6; char quote = '"'; const char *vend; if (*v == '"' || *v == '\'') { quote = *v; v++; } vend = memchr(v, quote, (size_t)(attr + attr_len - v)); if (!vend) vend = attr + attr_len; if (ws_memmem(v, (size_t)(vend - v), needle)) matched = 1; } if (!matched) { i = tag_end + 1; continue; } } ih = ws_memmem(attr, attr_len, "href="); if (href && hrefcap) { href[0] = '\0'; if (ih) { const char *v = ih + 5; char quote = '"'; const char *vend; if (*v == '"' || *v == '\'') { quote = *v; v++; } vend = memchr(v, quote, (size_t)(attr + attr_len - v)); if (vend) { size_t n = (size_t)(vend - v); if (n >= hrefcap) n = hrefcap - 1; memcpy(href, v, n); href[n] = '\0'; } } } { const char *istart = hay + tag_end + 1; const char *iend = ws_memmem(istart, hlen - (size_t)(istart - hay), ". */ static void ddg_real_url(char *out, size_t capsz, const char *href) { const char *u = href; out[0] = '\0'; if (!href) return; if (href[0] == '/' && href[1] == '/') { /* "//host/path" — same scheme as the page we fetched it from. */ char joined[2048]; snprintf(joined, sizeof joined, "https:%.2030s", href); ws_copy(out, capsz, joined); return; } if (href[0] == '/') { const char *uddg = strstr(href, "uddg="); if (uddg) { char enc[2048], dec[2048]; const char *amp = strchr(uddg + 5, '&'); size_t n = amp ? (size_t)(amp - (uddg + 5)) : strlen(uddg + 5); if (n >= sizeof enc) n = sizeof enc - 1; memcpy(enc, uddg + 5, n); enc[n] = '\0'; ws_url_decode(dec, sizeof dec, enc); ws_copy(out, capsz, dec); return; } ws_copy(out, capsz, href); return; } ws_copy(out, capsz, u); } static int search_duckduckgo(const ws_config *cfg, const char *query, int count, const char *region, const char *safe, ws_results *res, long *status_out, char *err, size_t errsz) { static const char *const SAFE_PARAM_STRICT = "1"; static const char *const SAFE_PARAM_MODERATE = "-1"; static const char *const SAFE_PARAM_OFF = "-2"; const char *sp = SAFE_PARAM_MODERATE; char base[WS_URL_MAX], url[1200]; char body[4096]; ws_buf form; ws_resp r; size_t pos = 0; int n = 0; if (safe && ws_ieq(safe, "strict")) sp = SAFE_PARAM_STRICT; else if (safe && ws_ieq(safe, "off")) sp = SAFE_PARAM_OFF; base_trim(base, sizeof base, cfg->ddg_base[0] ? cfg->ddg_base : "https://html.duckduckgo.com"); snprintf(url, sizeof url, "%s/html/", base); ws_buf_init(&form); ws_buf_puts(&form, "q="); ws_url_encode(query, &form); if (region && *region) { ws_buf_puts(&form, "&kl="); ws_url_encode(region, &form); } ws_buf_puts(&form, "&kp="); ws_buf_puts(&form, sp); snprintf(body, sizeof body, "%s", ws_buf_str(&form)); ws_buf_free(&form); /* POST, not GET: html.duckduckgo.com answers a bare GET with a bot * challenge and the same query as a form post with a result page. */ if (ws_http_do("POST", url, "Content-Type: application/x-www-form-urlencoded\r\n" "Accept: text/html\r\n" "User-Agent: SCORPIOXBOT-websearch/" WS_VER " (+https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-websearch)\r\n", body, strlen(body), 25000, &r) != 0) { ws_copy(err, errsz, r.error); ws_resp_free(&r); return -1; } if (status_out) *status_out = r.status; if (!r.ok || r.status >= 400) { upstream_error(&r, "DuckDuckGo", err, errsz); ws_resp_free(&r); return -1; } if (!r.body || !r.body_len) { ws_copy(err, errsz, "DuckDuckGo returned an empty page"); ws_resp_free(&r); return -1; } for (;;) { char href[2048]; const char *inner = NULL; size_t inner_len = 0; char title_html[2048], snippet_html[4096]; char realurl[1024]; ws_result *it; if (n >= count) break; if (!next_anchor(r.body, r.body_len, pos, "result__a", href, sizeof href, &inner, &inner_len)) break; /* Where the snippet starts: right after this anchor's . */ { const char *after = ws_memmem(inner + inner_len, r.body_len - (size_t)(inner + inner_len - r.body), "searxng_base[0]) { ws_copy(err, errsz, "SearXNG needs a base URL (a self-hosted instance). Set " "WEBSEARCH_SEARXNG_BASE, or set it on the plugin page."); return -1; } base_trim(base, sizeof base, cfg->searxng_base); snprintf(url, sizeof url, "%s/search?q=", base); ws_buf_init(&q); ws_buf_puts(&q, url); ws_url_encode(query, &q); ws_buf_puts(&q, "&format=json"); if (cfg->searxng_categories[0]) { ws_buf_puts(&q, "&categories="); ws_url_encode(cfg->searxng_categories, &q); } if (language && *language) { ws_buf_puts(&q, "&language="); ws_url_encode(language, &q); } if (safe && *safe) { ws_buf_puts(&q, "&safesearch="); if (ws_ieq(safe, "strict")) ws_buf_puts(&q, "2"); else if (ws_ieq(safe, "off")) ws_buf_puts(&q, "0"); else ws_buf_puts(&q, "1"); } ws_copy(url, sizeof url, ws_buf_str(&q)); ws_buf_free(&q); if (ws_http_do("GET", url, "Accept: application/json\r\n", NULL, 0, 25000, &r) != 0) { ws_copy(err, errsz, r.error); ws_resp_free(&r); return -1; } if (status_out) *status_out = r.status; if (!r.ok || r.status >= 400) { upstream_error(&r, "SearXNG", err, errsz); ws_resp_free(&r); return -1; } if (parse_json(&r, &doc, "SearXNG", err, errsz) != 0) { ws_resp_free(&r); return -1; } root = yyjson_doc_get_root(doc); arr = jarr(root, "results"); if (!arr) { ws_copy(err, errsz, "SearXNG answered without a results array - check that this " "instance allows ?format=json (settings.yml: search.formats)"); yyjson_doc_free(doc); ws_resp_free(&r); return -1; } yyjson_arr_iter iter; yyjson_arr_iter_init(arr, &iter); while ((el = yyjson_arr_iter_next(&iter)) && n < count) { const char *title = jstr(el, "title"); const char *u = jstr(el, "url"); const char *content = jstr(el, "content"); const char *pub = jstr(el, "publishedDate"); ws_result *it; if (!u || !*u) continue; it = ws_results_push(res); if (!it) { ws_copy(err, errsz, "out of memory"); yyjson_doc_free(doc); ws_resp_free(&r); return -1; } fill_result(it, title, u, content, pub); n++; } yyjson_doc_free(doc); ws_resp_free(&r); return 0; } /* ------------------------------------------------------------------ Brave */ static int search_brave(const ws_config *cfg, const char *query, int count, const char *country, const char *language, const char *freshness, ws_results *res, long *status_out, char *err, size_t errsz) { char base[WS_URL_MAX], url[2000]; char hdr[1200]; ws_buf q; ws_resp r; yyjson_doc *doc = NULL; yyjson_val *root, *web, *arr, *el; int n = 0; if (!cfg->brave_key[0]) { ws_copy(err, errsz, "Brave needs an API key. Set BRAVE_API_KEY, or save one on the " "plugin page."); return -1; } base_trim(base, sizeof base, cfg->brave_base); ws_buf_init(&q); ws_buf_printf(&q, "%s/res/v1/web/search?q=", base); ws_url_encode(query, &q); { char num[16]; snprintf(num, sizeof num, "%d", count); ws_buf_puts(&q, "&count="); ws_buf_puts(&q, num); } if (country && *country) { ws_buf_puts(&q, "&country="); ws_url_encode(country, &q); } if (language && *language) { ws_buf_puts(&q, "&search_lang="); ws_url_encode(language, &q); } if (freshness && *freshness) { ws_buf_puts(&q, "&freshness="); ws_url_encode(freshness, &q); } ws_copy(url, sizeof url, ws_buf_str(&q)); ws_buf_free(&q); snprintf(hdr, sizeof hdr, "Accept: application/json\r\n" "Accept-Encoding: identity\r\n" "X-Subscription-Token: %s\r\n", cfg->brave_key); if (ws_http_do("GET", url, hdr, NULL, 0, 25000, &r) != 0) { ws_copy(err, errsz, r.error); ws_resp_free(&r); return -1; } if (status_out) *status_out = r.status; if (!r.ok || r.status >= 400) { upstream_error(&r, "Brave", err, errsz); ws_resp_free(&r); return -1; } if (parse_json(&r, &doc, "Brave", err, errsz) != 0) { ws_resp_free(&r); return -1; } root = yyjson_doc_get_root(doc); web = jobj(root, "web"); arr = jarr(web, "results"); if (arr) { yyjson_arr_iter iter; yyjson_arr_iter_init(arr, &iter); while ((el = yyjson_arr_iter_next(&iter)) && n < count) { const char *title = jstr(el, "title"); const char *u = jstr(el, "url"); const char *desc = jstr(el, "description"); const char *age = jstr(el, "age"); ws_result *it; if (!u || !*u) continue; it = ws_results_push(res); if (!it) { ws_copy(err, errsz, "out of memory"); yyjson_doc_free(doc); ws_resp_free(&r); return -1; } fill_result(it, title, u, desc, age); n++; } } yyjson_doc_free(doc); ws_resp_free(&r); return 0; } /* ----------------------------------------------------------------- Tavily */ /* One POST body shared by the keyed POST providers: build with yyjson so a * quote in the query cannot break the document. */ static char *json_body(const char *query, int count, int advanced, int answer) { yyjson_mut_doc *md = yyjson_mut_doc_new(NULL); yyjson_mut_val *root; char *js; size_t len; if (!md) return NULL; root = yyjson_mut_obj(md); yyjson_mut_doc_set_root(md, root); yyjson_mut_obj_add_strcpy(md, root, "query", query); yyjson_mut_obj_add_int(md, root, "max_results", count); if (advanced) yyjson_mut_obj_add_strcpy(md, root, "search_depth", "advanced"); if (answer) yyjson_mut_obj_add_bool(md, root, "include_answer", 1); js = yyjson_mut_write(md, 0, &len); yyjson_mut_doc_free(md); return js; } static int search_tavily(const ws_config *cfg, const char *query, int count, ws_results *res, long *status_out, char *err, size_t errsz) { char base[WS_URL_MAX], url[1300], hdr[1200]; char *body; ws_resp r; yyjson_doc *doc = NULL; yyjson_val *root, *arr, *el; int n = 0; if (!cfg->tavily_key[0]) { ws_copy(err, errsz, "Tavily needs an API key. Set TAVILY_API_KEY, or save one on the " "plugin page."); return -1; } base_trim(base, sizeof base, cfg->tavily_base); snprintf(url, sizeof url, "%s/search", base); body = json_body(query, count, cfg->tavily_advanced, cfg->tavily_answer); if (!body) { ws_copy(err, errsz, "out of memory"); return -1; } snprintf(hdr, sizeof hdr, "Content-Type: application/json\r\n" "Accept: application/json\r\n" "Authorization: Bearer %s\r\n", cfg->tavily_key); if (ws_http_do("POST", url, hdr, body, strlen(body), 30000, &r) != 0) { ws_copy(err, errsz, r.error); free(body); ws_resp_free(&r); return -1; } free(body); if (status_out) *status_out = r.status; if (!r.ok || r.status >= 400) { upstream_error(&r, "Tavily", err, errsz); ws_resp_free(&r); return -1; } if (parse_json(&r, &doc, "Tavily", err, errsz) != 0) { ws_resp_free(&r); return -1; } root = yyjson_doc_get_root(doc); { const char *ans = jstr(root, "answer"); if (ans && *ans) ws_buf_puts(&res->answer, ans); } arr = jarr(root, "results"); if (arr) { yyjson_arr_iter iter; yyjson_arr_iter_init(arr, &iter); while ((el = yyjson_arr_iter_next(&iter)) && n < count) { const char *title = jstr(el, "title"); const char *u = jstr(el, "url"); const char *content = jstr(el, "content"); const char *pub = jstr(el, "published_date"); ws_result *it; if (!u || !*u) continue; it = ws_results_push(res); if (!it) { ws_copy(err, errsz, "out of memory"); yyjson_doc_free(doc); ws_resp_free(&r); return -1; } fill_result(it, title, u, content, pub); n++; } } yyjson_doc_free(doc); ws_resp_free(&r); return 0; } /* -------------------------------------------------------------------- Exa */ static int search_exa(const ws_config *cfg, const char *query, int count, ws_results *res, long *status_out, char *err, size_t errsz) { char base[WS_URL_MAX], url[1300], hdr[1200]; yyjson_mut_doc *md; yyjson_mut_val *root, *contents; char *body; size_t blen; ws_resp r; yyjson_doc *doc = NULL; yyjson_val *jroot, *arr, *el; int n = 0; if (!cfg->exa_key[0]) { ws_copy(err, errsz, "Exa needs an API key. Set EXA_API_KEY, or save one on the " "plugin page."); return -1; } base_trim(base, sizeof base, cfg->exa_base); /* Both https://api.exa.ai and a base that already ends in /search work. */ if (strlen(base) >= 7 && ws_ieq(base + strlen(base) - 7, "/search")) snprintf(url, sizeof url, "%s", base); else snprintf(url, sizeof url, "%s/search", base); md = yyjson_mut_doc_new(NULL); if (!md) { ws_copy(err, errsz, "out of memory"); return -1; } root = yyjson_mut_obj(md); yyjson_mut_doc_set_root(md, root); yyjson_mut_obj_add_strcpy(md, root, "query", query); yyjson_mut_obj_add_int(md, root, "numResults", count); contents = yyjson_mut_obj(md); yyjson_mut_obj_add_bool(md, contents, "highlights", 1); yyjson_mut_obj_add_val(md, root, "contents", contents); body = yyjson_mut_write(md, 0, &blen); yyjson_mut_doc_free(md); if (!body) { ws_copy(err, errsz, "out of memory"); return -1; } snprintf(hdr, sizeof hdr, "Content-Type: application/json\r\n" "Accept: application/json\r\n" "x-api-key: %s\r\n", cfg->exa_key); if (ws_http_do("POST", url, hdr, body, blen, 30000, &r) != 0) { ws_copy(err, errsz, r.error); free(body); ws_resp_free(&r); return -1; } free(body); if (status_out) *status_out = r.status; if (!r.ok || r.status >= 400) { upstream_error(&r, "Exa", err, errsz); ws_resp_free(&r); return -1; } if (parse_json(&r, &doc, "Exa", err, errsz) != 0) { ws_resp_free(&r); return -1; } jroot = yyjson_doc_get_root(doc); arr = jarr(jroot, "results"); if (arr) { yyjson_arr_iter iter; yyjson_arr_iter_init(arr, &iter); while ((el = yyjson_arr_iter_next(&iter)) && n < count) { const char *title = jstr(el, "title"); const char *u = jstr(el, "url"); const char *pub = jstr(el, "publishedDate"); const char *text = jstr(el, "text"); const char *first_highlight = NULL; ws_result *it; if (!u || !*u) continue; /* `highlights` is an array of the most relevant excerpts; the first * one is the closest thing to a snippet Exa offers. */ { yyjson_val *hl = jarr(el, "highlights"); if (hl && yyjson_arr_size(hl) > 0) { yyjson_val *h0 = yyjson_arr_get_first(hl); if (h0 && yyjson_is_str(h0)) first_highlight = yyjson_get_str(h0); } } it = ws_results_push(res); if (!it) { ws_copy(err, errsz, "out of memory"); yyjson_doc_free(doc); ws_resp_free(&r); return -1; } fill_result(it, title, u, first_highlight ? first_highlight : text, pub); n++; } } yyjson_doc_free(doc); ws_resp_free(&r); return 0; } /* ------------------------------------------------------------ Perplexity */ static int search_perplexity(const ws_config *cfg, const char *query, int count, ws_results *res, long *status_out, char *err, size_t errsz) { char base[WS_URL_MAX], url[1400], hdr[1200]; char *body; ws_resp r; yyjson_doc *doc = NULL; yyjson_val *root, *arr, *el; int n = 0; if (!cfg->pplx_key[0]) { ws_copy(err, errsz, "Perplexity needs an API key. Set PERPLEXITY_API_KEY, or save one " "on the plugin page."); return -1; } base_trim(base, sizeof base, cfg->pplx_base); if (strlen(base) >= 7 && ws_ieq(base + strlen(base) - 7, "/search")) snprintf(url, sizeof url, "%s", base); else snprintf(url, sizeof url, "%s/search", base); /* The Search API (not chat completions): it returns ranked sources rather * than prose, which is what a search tool is for. */ body = json_body(query, count, 0, 0); if (!body) { ws_copy(err, errsz, "out of memory"); return -1; } snprintf(hdr, sizeof hdr, "Content-Type: application/json\r\n" "Accept: application/json\r\n" "Authorization: Bearer %s\r\n", cfg->pplx_key); if (ws_http_do("POST", url, hdr, body, strlen(body), 30000, &r) != 0) { ws_copy(err, errsz, r.error); free(body); ws_resp_free(&r); return -1; } free(body); if (status_out) *status_out = r.status; if (!r.ok || r.status >= 400) { upstream_error(&r, "Perplexity", err, errsz); ws_resp_free(&r); return -1; } if (parse_json(&r, &doc, "Perplexity", err, errsz) != 0) { ws_resp_free(&r); return -1; } root = yyjson_doc_get_root(doc); arr = jarr(root, "results"); if (arr) { yyjson_arr_iter iter; yyjson_arr_iter_init(arr, &iter); while ((el = yyjson_arr_iter_next(&iter)) && n < count) { const char *title = jstr(el, "title"); const char *u = jstr(el, "url"); const char *snip = jstr(el, "snippet"); const char *date = jstr(el, "date"); ws_result *it; if (!u || !*u) continue; it = ws_results_push(res); if (!it) { ws_copy(err, errsz, "out of memory"); yyjson_doc_free(doc); ws_resp_free(&r); return -1; } fill_result(it, title, u, snip, date); n++; } } yyjson_doc_free(doc); ws_resp_free(&r); return 0; } /* --------------------------------------------------------------- dispatch */ int ws_search(const ws_config *cfg, const char *provider, const char *query, int count, const char *country, const char *language, const char *freshness, const char *safe_override, ws_results *r, long *status_out, char *err, size_t errsz) { const char *prov = (provider && *provider) ? provider : ws_provider_active(cfg); const char *safe = (safe_override && *safe_override) ? safe_override : cfg->safe; const char *lang = (language && *language) ? language : cfg->language; long long t0; int rc; if (status_out) *status_out = 0; err[0] = '\0'; if (!query || !*query) { ws_copy(err, errsz, "query is required"); return -2; } if (!ws_provider_known(prov)) { snprintf(err, errsz, "unknown provider \"%s\" (choose duckduckgo, searxng, brave, " "tavily, exa or perplexity)", prov); return -2; } if (count < 1) count = cfg->count > 0 ? cfg->count : WS_DEFAULT_COUNT; if (count > WS_MAX_COUNT) count = WS_MAX_COUNT; ws_copy(r->provider, sizeof r->provider, prov); ws_copy(r->query, sizeof r->query, query); r->count = count; r->n = 0; t0 = sx_now_ms(); if (ws_ieq(prov, "duckduckgo")) rc = search_duckduckgo(cfg, query, count, cfg->region, safe, r, status_out, err, errsz); else if (ws_ieq(prov, "searxng")) rc = search_searxng(cfg, query, count, lang, safe, r, status_out, err, errsz); else if (ws_ieq(prov, "brave")) rc = search_brave(cfg, query, count, country, lang, freshness, r, status_out, err, errsz); else if (ws_ieq(prov, "tavily")) rc = search_tavily(cfg, query, count, r, status_out, err, errsz); else if (ws_ieq(prov, "exa")) rc = search_exa(cfg, query, count, r, status_out, err, errsz); else rc = search_perplexity(cfg, query, count, r, status_out, err, errsz); r->took_ms = sx_now_ms() - t0; if (rc != 0) return rc; if (r->n > 0) r->truncated = 0; return 0; }